Sending message on IBM MQ: Hangs on AccessQueue

Question: We're trying to send a message on an IBM MQ Message Queue.
We can contact the Queue Manager, but as soon as we call the MQMessage constructor, the process hangs. We suspect that this is actually because whatever AccessQueue is doing is failing.
        using (MQQueueManager qMgr = new MQQueueManager(queueManagerName, connectionProperties))
        {
            // Set up the options on the queue we want to open
            int openOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;

            // Now specify the queue that we want to open,and the open options
            MQQueue system_default_local_queue =
                qMgr.AccessQueue(sendQueueName, openOptions); // we suspect this is actually where things are wrong

            // Define a WebSphere MQ message, writing some text in UTF format
            MQMessage mqMessage = new MQMessage(); // ** THIS HANGS
            mqMessage.WriteUTF(text);

            // Specify the message options
            MQPutMessageOptions pmo = new MQPutMessageOptions(); // accept the defaults,
            // same as MQPMO_DEFAULT

            // Put the message on the queue
            system_default_local_queue.Put(mqMessage, pmo);

            system_default_local_queue.Close();

            // Disconnect from the queue manager
            qMgr.Disconnect();
        }

Is there an option we're not including or something we're missing?
We're using the the NuGet package WebSphereMqClient v184.108.40.206.

Update:
I'll include our connection properties for completeness based on feedback.
        Hashtable connectionProperties = new Hashtable();
        connectionProperties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
        connectionProperties.Add(MQC.USE_MQCSP_AUTHENTICATION_PROPERTY, true);
        // Set up the rest of the connection properties, based on the
        // connection type requested
        // this is all for MQC.TRANSPORT_MQSERIES_MANAGED
        connectionProperties.Add(MQC.HOST_NAME_PROPERTY, "myserver.com");
        connectionProperties.Add(MQC.CHANNEL_PROPERTY, "MY.CHANNEL");
        connectionProperties.Add(MQC.PORT_PROPERTY, 3223);
        connectionProperties.Add(MQC.CONNECT_OPTIONS_PROPERTY, MQC.MQCNO_RECONNECT_Q_MGR);

In answer to a question from Roger, this is a Managed Queue.
Answer: You don't show us your connection properties, so I don't know if you set everything correctly.  Did you make sure you set 'managed mode'?  Also, why aren't you doing any print-outs of what the code has completed?
Here is a complete and working C# .NET/MQ program that uses 'managed mode' connection.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using IBM.WMQ;

///  Program Name
/// MQTest51
///
/// Description
/// This C# class will connect to a remote queue manager
/// and put a message to a queue under a managed .NET environment.
///
/// Sample Command Line Parameters
/// -h 127.0.0.1 -p 1414 -c TEST.CHL -m MQWT1 -q TEST.Q1
///
///
namespace MQTest51
{
   class MQTest51
   {
      private Hashtable inParms = null;
      private Hashtable qMgrProp = null;
      private System.String qManager;
      private System.String outputQName;

      /*
      * The constructor
      */
      public MQTest51()
         : base()
      {
      }

      ///  Make sure the required parameters are present.
      /// <returns> true/false
      /// </returns>
      private bool allParamsPresent()
      {
         bool b = inParms.ContainsKey("-h") && inParms.ContainsKey("-p") &&
                  inParms.ContainsKey("-c") && inParms.ContainsKey("-m") &&
                  inParms.ContainsKey("-q");
         if (b)
         {
            try
            {
               System.Int32.Parse((System.String)inParms["-p"]);
            }
            catch (System.FormatException e)
            {
               b = false;
            }
         }

         return b;
      }

      ///  Extract the command-line parameters and initialize the MQ variables.
      /// <param name="args">
      /// </param>
      /// <throws>  IllegalArgumentException </throws>
      private void init(System.String[] args)
      {
         inParms = Hashtable.Synchronized(new Hashtable());
         if (args.Length > 0 && (args.Length % 2) == 0)
         {
            for (int i = 0; i < args.Length; i += 2)
            {
               inParms[args[i]] = args[i + 1];
            }
         }
         else
         {
            throw new System.ArgumentException();
         }

         if (allParamsPresent())
         {
            qManager = ((System.String)inParms["-m"]);
            outputQName = ((System.String)inParms["-q"]);

            qMgrProp = new Hashtable();

            qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);

            qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ((System.String)inParms["-h"]));
            qMgrProp.Add(MQC.CHANNEL_PROPERTY, ((System.String)inParms["-c"]));

            try
            {
               qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse((System.String)inParms["-p"]));
            }
            catch (System.FormatException e)
            {
               qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
            }

            if (inParms.ContainsKey("-u"))
               qMgrProp.Add(MQC.USER_ID_PROPERTY, ((System.String)inParms["-u"]));

            if (inParms.ContainsKey("-x"))
               qMgrProp.Add(MQC.PASSWORD_PROPERTY, ((System.String)inParms["-x"]));

            if ( (inParms.ContainsKey("-u")) && (inParms.ContainsKey("-x")) )
               qMgrProp.Add(MQC.USE_MQCSP_AUTHENTICATION_PROPERTY, true);
         }
         else
         {
            throw new System.ArgumentException();
         }
      }

      ///  Connect, open queue, write a message, close queue and disconnect.
      ///
      ///
      /// <throws>  MQException </throws>
      private void testSend()
      {
         MQQueueManager qMgr = null;
         MQQueue outQ = null;
         System.String line = "This is a test message embedded in the MQTest51 program.";
         int openOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;
         MQPutMessageOptions pmo = new MQPutMessageOptions();

         try
         {
            qMgr = new MQQueueManager(qManager, qMgrProp);
            System.Console.Out.WriteLine("MQTest51 successfully connected to " + qManager);

            outQ = qMgr.AccessQueue(outputQName, openOptions);
            System.Console.Out.WriteLine("MQTest51 successfully opened " + outputQName);

            // Define a simple MQ message, and write some text in UTF format..
            MQMessage sendmsg = new MQMessage();
            sendmsg.Format = MQC.MQFMT_STRING;
            sendmsg.MessageType = MQC.MQMT_DATAGRAM;
            sendmsg.MessageId = MQC.MQMI_NONE;
            sendmsg.CorrelationId = MQC.MQCI_NONE;
            sendmsg.WriteString(line);

            // put the message on the outQ
            outQ.Put(sendmsg, pmo);
            System.Console.Out.WriteLine("Message Data>>>" + line);
         }
         catch (MQException mqex)
         {
            System.Console.Out.WriteLine("MQTest51 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
         }
         catch (System.IO.IOException ioex)
         {
            System.Console.Out.WriteLine("MQTest51 ioex=" + ioex);
         }
         finally
         {
            try
            {
                if (outQ != null)
                {
                    outQ.Close();
                    System.Console.Out.WriteLine("MQTest51 closed: " + outputQName);
                }
            }
            catch (MQException mqex)
            {
                System.Console.Out.WriteLine("MQTest51 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
            }

            try
            {
                if (qMgr != null)
                {
                    qMgr.Disconnect();
                    System.Console.Out.WriteLine("MQTest51 disconnected from " + qManager);
                }
            }
            catch (MQException mqex)
            {
                System.Console.Out.WriteLine("MQTest51 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
            }
         }
      }

      ///  main line
      /// <param name="args">
      /// </param>
      //        [STAThread]
      public static void Main(System.String[] args)
      {
         MQTest51 write = new MQTest51();

         try
         {
            write.init(args);
            write.testSend();
         }
         catch (System.ArgumentException e)
         {
            System.Console.Out.WriteLine("Usage: MQTest51 -h host -p port -c channel -m QueueManagerName -q QueueName [-u userID] [-x passwd]");
            System.Environment.Exit(1);
         }
         catch (MQException e)
         {
            System.Console.Out.WriteLine(e);
            System.Environment.Exit(1);
         }

         System.Environment.Exit(0);
      }
   }
}

Comment: Great sample Roger!
Comment: Wow, thanks for that. I didn't include the connection properties because they are server, port, etc. I'll include them in my question for completeness. This example is brilliant and will definitely help fill in blanks that we may be missing. With regards my issue, I have been testing this a lot with breakpoints. It seems if I remove breakpoints and let it "run through", it always works. So might need to chalk it up to that.
Comment: Well yeah, if you sit on a breakpoint in your application then the MQ's MCA (linked into your code) cannot send a heartbeat message back to the queue manager, so the queue manager will close the channel because it thinks you have gone away.


WDS Auto Logging in after Install

Question: I have setup WDS to push out images to our machines completely hands of. It all works fine, accept at the end of the process, when the machine is sat at the crl+alt+del login prompt. If you hit crl_alt+del instead of asking for a username/pass, is is automaticly logging on as the local admin account.
Anyone any ideas how to stop it auto logging on, we are going to be deploying to remote unmanned sites, and dont really want a user to be able to use the machine logged in as the local admin
Cheers
Luke
Answer: WDS doesn't really have anything to do with the resulting OS that ends up on your machines.  It is just the delivery mechanism.  You have to look at the customizations you've made to the OS deployment you're pushing out.  What tool(s) did you use to create your deployment?
Comment: we just syspreped the image, then created a wim file via the vista boot capture image from the dvd. Could it be something left in the sysprep.ini on the image?
Answer: I would suggest that you look at your sysprep inf file.  There may be a setting in there that will allow for autologging in the first time.

WDS Auto Logging in after Install


Angular 12 - When I click an already selected tab from mat-tab-link it doesn't reload the page

Question: I have an application that has a navbar, in that navbar there are several mat-tab-link .
Clicking on one of the links loads a certain page.
When I click a link that is currently focused, it doesn't perform any load/reload of current page/tab.
Currently I have to click on another tab and then click the previous tab in order to "reload" the tab.

      {{routeLink.label}}

  <router-outlet></router-outlet>

import { ChangeDetectionStrategy, Component, ViewChild } from "@angular/core";
import { Router } from "@angular/router";
import { Observable } from "rxjs-compat";

@Component({
    //changeDetection: ChangeDetectionStrategy.OnPush,
    selector: 'app-app-control',
    templateUrl: './app-control.component.html',
    styleUrls: ['./app-control.component.scss']
  })
  export class AppControlComponent {
    routeLinks:any[];
    asyncTabs: Observable<any>;
    activeLinkIndex = 0;

    @ViewChild('tabs', {static: false}) tabs;
  realignInkBar() {
    // this.tabs.realignInkBar();
    this.tabs._alignInkBarToSelectedTab();
  }

    constructor(private router: Router) {
      this.routeLinks = [
      {label: 'Page1', link: 'page1'},
      {label: 'Page2', link: 'page2'},
      {label: 'Page3', link: 'page3'}]

      this.asyncTabs = new Observable((observer: any) => {
        setTimeout(() => {
          observer.next(this.routeLinks);
        }, 1000);

    })
    this.activeLinkIndex =
          this.routeLinks.indexOf(this.routeLinks.find(tab => router.url.indexOf(tab.link) != -1));
    }

    tabClick(){

      console.log("clicked")
    }
  }

I don't know what to even try here.
Comment: why would you want to do that? is there a some kind of `:id` parameter in the url of that route?
Comment: In the selected page, there is a table with filters.
so when a user is selecting several filters and wants to clear everything, refreshing the page clears it in a fast matter
Comment: you can do ```(click)``` on the tab to run a function which goes to the certain link probably.
Answer: there is a way to make the page reload on the same url navigation. but it is only possible to configure this for the whole app, when registering RouterModule.forRoot(...)
RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})

Comment: That doesn't work unfortunately
Comment: You'r answer was half of the answer.
I had to add the following:
  ngOnInit(): void {
    //  ...
    // With the below line you can now reload the same component from the same route
    this.router.routeReuseStrategy.shouldReuseRoute = () => { return false; };
  }


How to compare text values of two lists of elements in cypress?

Question: I have code like this:
let firstUserPrices

cy.get('.fw-price').each($value => {
    firstUserPrices = $value.text()
})

let secondUserPrices
cy.get('.fw-price').each($value => {
    secondUserPrices = $value.text()
    expect(firstUserPrices, 'PRICES').to.equal(secondUserPrices)
})

cy.get('.fw-price') has 10 elements and I want to compare all of it one by one. But what i get is 10 times same value with firstUserPrices(it's last value form list) what am I doing wrong here?
Answer: You can try this , assuming the length of both lists are equal -
cy.get('list1').then((list1) => {
   cy.get('list2').then((list2) => {
      for (var i = 0, i < list1.length, i++) {
         expect(list1.eq(i).text()).to.equal(list2.eq(i).text())
      }
   })
})

Comment: When I do this it compare first value of firstUserPrices with all values of secondUserPrices. I want to compare first value of firstUserPrices with first value of secondUserPrices, second value of firstUserPrices with second value of secondUserPrices and so on...
Comment: I added this into variables becouse after firstUserPrices I'm doing some stuff and didn't want to put everything inside that scope
Answer: I figured it out, had to put firstUserPrices into an array and push elements to that array
let firstUserPrices = []

cy.get('[data-t="my-price"] span span').each($value => {
    firstUserPrices.push($value.text())
})

//do some stuff here

cy.get('[data-t="my-price"] span span').each(($value,index) => {
    const secondUserPrices = $value.text()
    expect(firstUserPrices[index], 'PRICES').to.not.equal(secondUserPrices)
})

Answer: from https://glebbahmutov.com/cypress-examples/6.5.0/commands/assertions.html#comparing-arrays
const arr = ['Apples', 'Bananas', 'Grapes']
// assert that cy.wrap yields the same array reference
// as we passed into it
cy.wrap(arr).should('equal', arr)
// assert the yielded array has the expected items inside
cy.wrap(arr)
  .invoke('reverse')
  .should('deep.equal', ['Grapes', 'Bananas', 'Apples'])


What is a league duck?

Question: http://www.theguardian.com/football/2015/feb/10/liverpool-tottenham-hotspur-premier-league-match-report

Liverpool's Mario Balotelli breaks league duck to sink Tottenham
Liverpool's Mario Balotelli broke his league duck within nine minutes of coming on as a substitute against Tottenham.

What is a league duck? Does each player have one?
Comment: That poor, poor duck.
Answer: It means his first goal in the [Premier] league (for Liverpool). I guess every player "has one" but with some Players it is more important.
The importance here being it took him quite a while as a striker.
Comment: I've also seen headlines where they say a *team* has broken a duck... is that their first goal in a league? first win in a league? first win in a season?
Comment: I would guess their first win in a season, but if it's a team that's got promoted their first win in a league is also possible. Please note that I'm not a native English speaking person, so I'm not really certain about the team one.
Answer: "Duck" means 0 in cricket, as noted in this question. Presumably, breaking one's "league duck" means getting one's first goal in the league, though I have not heard this usage.
See also Wikipedia on ducks.
Answer: 'Breaking one's duck' is when someone makes their first score or achieve a particular feat for the first time.
It's actually answered really well in the Stack Exchange English Language & Usage Q&A https://english.stackexchange.com/questions/26809/broken-my-duck-is-this-a-common-idiom-phrase
Comment: Thanks! So in baseball, you'd break ducks when you get your first at-bat, first hit, first stolen base, first home run, first grand slam etc?
Comment: It is usually used as a reference to scoring but technically could be applicable to these, yes.

What is a league duck?


cache images that has been resized with php

Question: URL of the image is like this

resize.php?image=imagename.jpg&w=100&h=100

and I want to cache the result in RAM. Can APC of php do it? how? Or I must install something else?
Answer: Yes, you can use APC to store the result in RAM. You just need to install APC module, and then add code to store /fetch resized versions inside APC using apc_store() and apc_fetch() functions.


Is there a Google plus API to check if a person has added me into to his circle

Question: Is there a Google API to check if a person has added me into his circle? I checked the google plus api list and couldn't find one.
Answer: No but you can star this feature request.


Compare distributions with uneven and small sample sizes

Question: I will be performing my analysis in R but any general mathematical-based answers will be appreciated.
I realize similar questions have been asked before but I am new to statistics so please excuse my ignorance. I do not know enough to be sure that approaches used in other threads I viewed are valid for my case so I would like to be sure.
Here is the context, simplified for those unfamiliar with this kind of data: I am looking at gene expression data. Essentially, I have a number of categories that each have a set of genes in them. Each gene has an associated expression value (amount present in my sample, log2 transformed). I also have three different test conditions (these conditions are completely independent of one another!). What this amounts to is a distribution. As an example:
Biological Process A:

Contains X genes and their expression levels for Condition 1
Contains Y genes and their expression levels for Condition 2
Contains Z genes and their expression levels for Condition 3

I would like to compare these three distributions. By compare I mean that I want to see if there are any large shifts in either the shape or spread of the distribution. EDIT: as Peter has pointed out, what I am really interested in is 1. Location, 2) Spread and 3) Shape with regards to the three distributions under comparison. For example, if Condition 1 moved such that it was almost entirely below the x-axis and Condition 2 was entirely above it, that would be a very interesting shift. Additionally, if two Conditions went above the axis and one went down, this would also be an interesting shift. Essentially, I need a way to compare the distributions for the biggest changes in mean density above or below the x-axis.
I have about 400+ "Biological Processes". The problem is that for some of them, the sample sizes may vary considerably (genes (n) = 3, 25, 10 for the three conditions respectively would be an extreme example in my case) so I do not think simply comparing the means is a fair approach. Visual comparison will take a very long time with 400 beanplots to look at and I would also like some statistics to back up the conclusions I may be making. I want to essentially say something like "Treating tissue with Condition 1 had the effect of increasing expression for most genes known to be involved in Biological Process A".
Additionally, if this approach is invalid or there is a better way to look at this data I would be open to suggestions. Thank you.
Comment: Something like a k-sample Kolmogorov-Smirnov? Or are you interested in allocating any rejection to the three causes?
Answer: You ask

I would like to compare these three distributions. By compare I mean
  that I want to see if there are any large shifts in either the shape
  or spread of the distribution

and your question implies you are also interested in shift of location.
Then there are really three things you want to compare: 1. Location, 2) Spread and 3) Shape.
For 1., you can compare means, medians or other quantiles. There are statistical tests of these, or you could bootstrap. One problem, though, is your sample sizes: They are small and varying. So, as often, you have to look at effect size, not just p value. For comparing 3 means, you  can use a linear model (ANOVA/regression) provided the assumptions are met. For comparing quantiles (including the median) you could use quantile regression (fewer assumptions than linear model). Or you could just list them and say "Look!"
For 2, again, there are different measures of spread: Most common are probably standard deviation and inter quartile range. Do either of these appeal?
For 3, things are trickier. You could look at measures of skewness and kurtosis across the three groups, but 1) These don't fully capture "shape" and 2) They are less intuitive than measures of location or spread (in particular, kurtosis doesn't really match intuition for any particular aspect of shape). So, you'd have to say what about the shape you are interested in.
Visual inspection gives you more information; looking at 400 beanplots is a lot; but so is looking at 400 quantile regressions or ANOVAs.
Comment: Thank you for your concise answer! You are correct that what I am really trying to compare is location, spread, shape. I will update my question to reflect this. Regarding these comparisons - how do I know if a standard deviation, IQR, etc. between three sets is really a meaningful change? I suspect this is going to be based on a threshold I set myself given my data and what I am looking for but it seems I should be able to get a sense of how different any two distributions are given the difference in their particular statistic. Does this make sense?
Comment: "Meaningful" differences are, as you suspected, context dependent. A t-test can examine the difference in means and whether it is significant. Only a subject matter expert can tell if it is meaningful.


how to fix wierd intellisense coloring ( VS 2019 )

Question: I just upgraded to visual studio 2019 from 2017 and a lot of colors changed in the formatting.
I have been changing it back to the old colors but there's something wierd that I don't know how to fix.
calling methods show the method with a diffrent color depending on the parameters, and I want them both to show the same color.
Example:
<code>
    public void method( int  t){

    }

    public int a;
    public vector3Int v;

    ///////

    method( a); /// method shows as teal color
    method(v.z); /// method shows as black color

</code>
so the fact that I have a parameter that is an int is showing one color and when the parameter is a vector.z it shows another color, even though both are ints, obviously this is discriminating between a direct int and a int inside a struct, the question is, how do I fix this so they are both the same color?
Comment: Intellisense does not color text based on subtypes, but based on types. For it "main" type is `vector3Int` in this case, so then all parameters which variable of this type holds will be displayed with the same color. Your a and v variables are types of `int` and `struct`, they are not the same. But if you will define something like `public int vInt = v.z` - they I believe it will be displayed with the teal color.
Comment: thanks, but how can I change it to the same color on both?( i dont want to change code but the options on visual studio)
Comment: You could change color using Tools -> Fonts and Colors -> User Types; but it will not help you - because you could set color for struct, but then this color will be applied to all struct variables which you have.
Answer: I fixed it by changing color on Tools -> Fonts and Colors -> User Types : Methods
Answer: user members locals worked for me in 2022 VS
Comment: Under tools- fonts colors---
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


12 independent samples are "enough" in MCMC sampling for what?

Question: I'm reading Learning in Graphical Models (Jordan 1998) and in the chapter Introduction to MCMC method by D. J. C. Mackay (page 201) it says this:

It's not clear to me to what this is referring to. "We really only need about twelve independent samples" for what precisely?
Add: I've found this particular chapter online here.
Comment: This sounds meaningless from looking at the quoted passage only.
Comment: I tried to paste a significant portion, sorry. Not sure if I could paste more without infringing copyright .
Comment: I've found and added the chapter online @Xi'an, please see the updated question.
Answer: It looks like this applies to a situation where you want to predict a future data point.
Let $X$ be a random variable, $\Phi=E[X]$ and $\sigma^2=Var(X)$ (in the notation of your screenshot, this corresponds to $\phi(x)=x$).
You get an estimator $\hat\Phi$ from $R$ independent samples, with $E[\hat\Phi]=\Phi$ and $Var(\hat\Phi)=\frac{\sigma^2}{R}$. You use $\hat\Phi$ as your prediction for the value of a future observation $\tilde X$. Your error can be measured by
$$
\begin{eqnarray}
E[(\tilde X-\hat\Phi)^2]&=&E[\tilde X^2]-2E[\tilde X]E[\hat\Phi]+E[\hat\Phi^2]\\
&=&E[\tilde X^2]-2\Phi^2+E[\hat\Phi^2]\\
&=&Var(\tilde X)+Var(\hat\Phi)\\
&=&\sigma^2\left(1+\frac{1}{R}\right)
\end{eqnarray}
$$
In this situation, there is not much point in spending time and energy on getting $R$ large, since $Var(\tilde X)$ will dominate. The exact value of 12 is rather arbitrary.
This point does not hold if what you want to learn is $\Phi$ itself, in which case a larger sample would be needed (typically 100 or 1000).


Display taxonomy term description within the content page

Question: I've a content type with some fields, one of the field is associated with a taxonomy and it has some terms (each term has its own description). Here, when I input the field with the terms and submit the content. The content page appears as:
<code>[title] : title of the content.

[field1] :

[field2] :

[taxonomy] : [term1]

             [term2]

             [term3]
</code>
The content page is viewed with all the fields and taxonomy terms with an anchor/link. I would also like to include the description in its display as
<code>[term1] : [description]

[term2] : [description]

[term3] : [description]
</code>
Any Ideas on how to get this done.
Answer: You can do this with the display suite module. Install and enable the ds module. Then you will have a new 'Rendered taxonomy term' formatter. Go to the 'manage display' option for the content type you created. Just select the 'Rendered Taxonomy Term' for the format for your taxonomy field and you will get the description displayed.
Comment: There is no 'Rendered Taxonomy term' option in the format. There are only 4 options 1. link, 2. Plain Text, 3. RSS Category, 4. hidden.
Comment: Sorry didn't realise that 'Rendered Taxonomy Term' came from the display suite module. Have updated the answer to include that information.


Remove separator from breadcrumb

Question: How can I remove the < from the breadcrumb I tried implode('<', $value['data']) but no luck
   function bootstrap_fit_breadcrumb($variables) {
            $breadcrumb = $variables['breadcrumb'];

            if (!empty($breadcrumb)) {
              //$breadcrumb[] = drupal_get_title();
              $breadcrumbs = '
';

              $count = count($breadcrumb) - 1;

              foreach ($breadcrumb as $key => $value) {
                  if ($key==0) {
                    $breadcrumbs .= '
' . $value . '
';
                  } else {
                   $breadcrumbs .= '
' . $value['data'] . '
';

                  }
              }
              $breadcrumbs .= '
';
              return $breadcrumbs;
      }
   }

displaying
Home < Financial Services

Answer: Have you reviewed this page?
https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_breadcrumb/7
Also, what theme are you using? I would check the base theme to make sure that it isn't preprocessing the breadcrumbs itself. If so, you'll need to make sure you are calling the appropriate function in order to override the breadcrumb settings.
Comment: yes that's where I got the `implode()` method from... but no luck
Answer: Super simple solution: use str_replace. In page.tpl.php replace
print $breadcrumb;

with
print str_replace(" < ", "  ", $breadcrumb);

or
print str_replace(" < ", " > ", $breadcrumb);

NOTE: I assume that '<' is surrounded by specific pattern otherwise str_replace will remove all opening parenthesis of html tags in $breadcrumb variable.
Answer: Drupal 8: I found a breadcrumb.html.twig file in my theme. The separator was coded into the theme (Businessgroup Zymphonies Theme). After removing it from the template, you can add a custom separator using CSS. Something like this:
.breadcrumb li:not(:last-child):after {
   content: ">"
}

Remove separator from breadcrumb


.Net c# libraries / assemblies - Crystal Reports

Question: i've developed a .Net C# (Crystal Reports) application in computer 1
dependencies link : https://i.stack.imgur.com/nEsb8.png
while running this application in computer 2 , it doesn't work because of the missing dependencies
how can i import all these dependencies with the application to make it running everywhere ?
not by copy & paste all the Needed DLLs in the same path with the executable ?
or how ?
thanx a lot
Answer: You will need to install the Crystal reports on the target machine. By this you will have all dlls on the same path and application will find them automatically.
Comment: i thought that importing some DLLs will be sufficient ... it was not, because the applications needs other assemblies ..

Precisely, CRRedist2005_x86.msi to install the needed Assemblies , that works well for me , thanx


Pip compiled as part of dockerfile - fastest way to add a new entry to requirements.txt?

Question: I'm using this Dockerfile as part of this docker compose file.
Right now, every time I want to add a new pip requirement, I stop my containers, add the new pip requirement, run docker-compose -f local.yml build, and then restart the containers with docker-compose -f local.yml up. This takes a long time, and it even looks like it's recompiling the container for Postgres if I just add a pip dependency.
What's the fastest way to add a single pip dependency to a container?
Answer: This is related to fact that the Docker build cache is being invalidated. When you edit the requirements.txt the step RUN pip install --no-cache-dir -r /requirements/production.txt and all subsequent instructions in the Dockerfile get invalidated. Thus they get re-executed.
As a best practice, you should avoid invalidaing the build cache as much as possible. This is achieved by moving the steps that change often to the bottom of the Dockerfile. You can edit the Dockerfile and while developing add separate pip installation steps to the end.
...

USER django

WORKDIR /app

pip install --no-cache-dir <new package>
pip install --no-cache-dir <new package2>

...

And once you are sure of all the dependencies needed, add them to the requirements file. That way you avoid invalidating the build cache early on and only build the steps starting from the installation of the new packages on ward.
Comment: One question - am I wrong in thinking that given the docker compose file it recompiles the unrelated containers as well upon docker-compose build?
Comment: That shouldn't be the case, unless other images are being invalidate due to changes in files being copied to them.


Understanding $F\phi \to FF\phi$ as density of time

Question: I'm talking about the basic temporal language in modal logic.
Suppose we insist that the following is always true:
$$F\phi \to FF\phi$$
It is supposed to be interpreted as between any 2 time instants, there is always a third, i.e. density of time. I'm not able to understand how.
$F\phi$ means $\phi$ will be the case in the future, and $FF\phi$ means $F\phi$ will be the case in the future. How do I understand this as density?
Answer: See Temporal Logic for the basic definition and the condition expressing "dense" in term of the precedence operator: $<$.
Suppose that the temporal model $\mathcal M$ is dense.
Consider a valuation $v$ such that   $\mathcal M, t \vDash \text F p[v]$. By the clause for $\text F$ operator we have that $\mathcal M, t' \vDash p[v]$ for some $t' > t$ [a valuation is a function assigning to each atomic proposition $p$ the set of time instants $v(p)$ at which $p$ is true.]
By density, there is some $t''$ such that: $t < t'' < t'$ and the fact above implies that $\mathcal M, t'' \vDash \text F p[v]$.
But this in turn implies: $\mathcal M, t \vDash \text F \text F p[v]$.
Thus, if the temporal model is dense, we have that: $\mathcal M, t \vDash \text F p \to \text F \text F p$.
Conversely, we show that the formula $\text F \text F p$ is not valid on a discrete ordering of time.
Consider two successive points $t_0$ and $t_1$ and consider the valuation $v^*$ that makes $p$ true only at $t_1$ [i.e. $v^*(p) = \{ t_1 \}$].
Obviously, $\text F p$ holds at $t_0$; but since there is no point in time between $t_0$ and $t_1$, the formula $\text F \text F p$ cannot be true at $t_0$.
Thus, in a discrete model of time, the formula $\text F p \to \text F \text F p$ is not satisfied by valuation $v^*$.
Comment: Thank you, that helps!


I want to feed the results of a clustering into a logistic regression

Question: Basically, my problem is, I have a dataset where I know about 12% of the rows should be classified as something, and I have some reasonable predictors. The problem is, my predictors aren't too good, because when I run a K-means with two clusters, they classify 85% of the rows as target instead of 12%. But otherwise the centroids elaborated seem to have face validity.
My idea is that I could feed the cluster assignments and the predictors into a logistic regression, and then I could fine tune the acceptance threshold to 12% instead of 50%. Mathematically, it seems like it should work but it reeks of inelegance.
Answer: Clustering is determined by the "geometry" of your data, i.e. by the "distances" between your data points, where "distance" is meant to be understood very broadly here. Classification, in your case I guess binary classification, is determined by the labels $\{0, 1\}$ of your data points.
There doesn't have to be any relation between the labels and the clustering of your data. E.g., you could have something like this:

Here, the blue points are labeled with $0$ and the red ones with $1$. This shows a situation where you have two clusters above each other, but this has nothing to do with the labels.
Thus, I would not get distracted by the clustering via k-means and would concentrate on classification alone. If your labels cannot be separated linearly, think about other classification methods, e.g. kernel logistic regression or SVM.
Having said that, the geometry can sometimes contain some indication about the labeling. And, if one knows about that, one can use this, via semi-supervised learning, to improve the classification. But one needs some evidence, e.g. via domain knowledge, that this connection between geometry and labeling is indeed the case.
Comment: So you don't have labels and clustering isn't aligned with what you want, either. But you do have some "approximate domain knowledge" (adk) of what would be an ideal candidate for label "one" in binary classification. Since this adk is the only thing you have, try to assign an "adk score" to as many data points as possible, then choose a threshold for that score to assign the labels zero and one to this subset of scored points and use this to train some binary classifier.
Comment: Thank you. The problem is I have no labels, just approximate domain knowledge of what an ideal example is, with a bunch of data that is actually linear in nature and inultiole dimensions spans the gamut. I was hoping clustering would see what I couldn't but it wasn't helpful. It maybe because I need better predictors, or maybe because my ideal example is not very common. But I think at 12% of the idealest examples I would get close to the truth, given the limitations of my data.


Is backlinking possible in drupal 7?

Question: Is there a way to tell what pages within the site link back to a particular page within the site?
Answer: Create a view of the pages with, for example, a list of tiles linked to the content. Then create a contextual filter using the entity reference field. In the Contextual Filter configuration for the entity reference, select 'Provide default value > Content ID from URL' under 'When the filter value is NOT available'.
Set the view to display as a block on the page, and it will display a list of the titles referencing that page.

Is backlinking possible in drupal 7?


ArrayIndexOutOfBoundException at VideoListFragment

Question: I am getting a runtime exception:

java.lang.ArrayIndexOutOfBoundsException: length=1; index=4   at
  com.sit.loco.frgment.VideoListFragment.onCreateView(VideoListFragment.java:110)

I mentioned that line no.110 in below coding.
StackTrace:
08-25 04:55:10.808: E/AndroidRuntime(2402): FATAL EXCEPTION: main
08-25 04:55:10.808: E/AndroidRuntime(2402): Process: com.loco.android, PID: 2402
08-25 04:55:10.808: E/AndroidRuntime(2402): java.lang.ArrayIndexOutOfBoundsException: length=1; index=4
08-25 04:55:10.808: E/AndroidRuntime(2402):     at com.sit.loco.frgment.VideoListFragment.onCreateView(VideoListFragment.java:110)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:478)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.View.measure(View.java:16497)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.View.measure(View.java:16497)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.View.measure(View.java:16497)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.View.measure(View.java:16497)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.View.measure(View.java:16497)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.Choreographer.doFrame(Choreographer.java:544)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.os.Handler.handleCallback(Handler.java:733)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.os.Handler.dispatchMessage(Handler.java:95)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.os.Looper.loop(Looper.java:136)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at java.lang.reflect.Method.invokeNative(Native Method)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at java.lang.reflect.Method.invoke(Method.java:515)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at dalvik.system.NativeStart.main(Native Method)

VideoListFragment.java:
package com.sit.loco.frgment;

import android.support.v4.app.Fragment;

public class VideoListFragment extends Fragment {

    OnVideoSelectedListener mCallback;
    boolean loadingMore = false;

    // create string variables
    String YOUTUBE_USERNAME = "";

    private String YOUTUBE_API = "http://gdata.youtube.com/feeds/api/users/"+YOUTUBE_USERNAME+"/uploads?alt=jsonc" +
            "&v=2"+
            "&start-index=1"+
            "&max-results=10";

    // create object of views
    ListView list;
    ProgressBar prgLoading;
    Button btnRefresh;
    Button btnLoadMore;

    // create variable to get position, connection status, resources, and channel username
    int position;
    boolean isConnect = true;
    Resources res;
    String[] ChannelUsername;

    // create object of custom adapter
    VideoListAdapter vla;

    // create arraylist variables
    ArrayList<HashMap<String, String>> menuItems;
    ProgressDialog pDialog;

    // flag for current page
    int current_page = 1;
    int previous_page;

    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_THUMBNAIL = "thumbnail";
    static final String KEY_DURATION = "duration";

    // create interface listener
    public interface OnVideoSelectedListener{
        public void onVideoSelected(String ID);
    }

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            View view = inflater.inflate(R.layout.fragment_list, container, false);

            list = (ListView)view .findViewById(R.id.list);
            btnRefresh = (Button)view .findViewById(R.id.btnRefresh);

        menuItems = new ArrayList<HashMap<String, String>>();

        // get value that passed from previous page
        Bundle bundle = getArguments();
        position = bundle.getInt("position", 0);

        // get channel username and put selected channel to youtube api
        res = getActivity().getResources();
        ChannelUsername = res.getStringArray(R.array.channel_username);
        YOUTUBE_USERNAME = ChannelUsername[position];---->Error at Line 110

        YOUTUBE_API = "http://gdata.youtube.com/feeds/api/users/"+YOUTUBE_USERNAME+"/uploads?alt=jsonc" +
                "&v=2"+
                "&start-index=1"+
                "&max-results=10";

        // create LoadMore button
        btnLoadMore = new Button(getActivity());
        btnLoadMore.setBackgroundResource(R.drawable.btn_default_holo_light);
        btnLoadMore.setText(getString(R.string.load_more));

        // adding load more button to lisview at bottom
        list.addFooterView(btnLoadMore);

        new loadFirstListView().execute();

        // listener to handle load more buttton when clicked
        btnLoadMore.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Starting a new async task
                isConnect = true;
                new loadMoreListView().execute();
            }
        });

        // listener to handle list when clicked
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
                // TODO Auto-generated method stub
                HashMap<String, String> item = new HashMap<String, String>();
                item = menuItems.get(position);

                mCallback.onVideoSelected(item.get("id"));

                list.setItemChecked(position, true);
            }
        });

        // listener to handle refresh button when clicked
        btnRefresh.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                isConnect = true;
                new loadFirstListView().execute();
            }
        });
        return view;
    }

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnVideoSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    // load first 10 videos
    private class loadFirstListView extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // Showing progress dialog before sending http request
            pDialog = new ProgressDialog(
                    getActivity());
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected Void doInBackground(Void... unused) {
            try {

                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
                HttpConnectionParams.setSoTimeout(client.getParams(), 15000);

                // Perform a GET request to YouTube for a JSON list of all the videos by a specific user
                HttpUriRequest request = new HttpGet(YOUTUBE_API);
                // Get the response that YouTube sends back
                HttpResponse response = client.execute(request);
                // Convert this response into an inputstream for the parser to use
                InputStream atomInputStream = response.getEntity().getContent();

                 BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

                //BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
                String line;
                String str = "";
                while ((line = in.readLine()) != null){
                    str += line;
                }

                    JSONObject json = new JSONObject(str);
                    JSONObject dataObject = json.getJSONObject("data"); // this is the "data": { } part
                    JSONArray items = dataObject.getJSONArray("items"); // this is the "items: [ ] part

                    for (int i = 0; i < items.length(); i++) {

                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject youtubeObject = items.getJSONObject(i);

                        map.put(KEY_ID, youtubeObject.getString("id")); // id not using any where
                        map.put(KEY_TITLE, youtubeObject.getString("title"));
                        map.put(KEY_THUMBNAIL, youtubeObject.getJSONObject("thumbnail").getString("hqDefault"));

                        String duration = secondToTime(youtubeObject.getInt("duration"));
                        map.put(KEY_DURATION, duration);

                        // adding HashList to ArrayList
                        menuItems.add(map);
                    }

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                isConnect = false;
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
            }

            return (null);
        }

        protected void onPostExecute(Void unused) {
            // closing progress dialog
            pDialog.dismiss();

            if(isAdded()){
                if(isConnect){
                    btnRefresh.setVisibility(View.GONE);
                    // Getting adapter
                    vla = new VideoListAdapter(getActivity(), menuItems);
                    list.setAdapter(vla);

                }else{
                    btnRefresh.setVisibility(View.VISIBLE);
                    Toast.makeText(getActivity(), getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // load more videos
    private class loadMoreListView extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // Showing progress dialog before sending http request
            pDialog = new ProgressDialog(
                    getActivity());
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected Void doInBackground(Void... unused) {

            // store previous value of current page
            previous_page = current_page;
            // increment current page
                    current_page += 10;

                    YOUTUBE_API = "http://gdata.youtube.com/feeds/api/users/"+YOUTUBE_USERNAME+"/uploads?alt=jsonc" +
                    "&v=2"+
                    "&start-index="+current_page+
                    "&max-results=10";

            try {

                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
                HttpConnectionParams.setSoTimeout(client.getParams(), 15000);

                // Perform a GET request to YouTube for a JSON list of all the videos by a specific user
                HttpUriRequest request = new HttpGet(YOUTUBE_API);
                // Get the response that YouTube sends back
                HttpResponse response = client.execute(request);
                // Convert this response into an inputstream for the parser to use
                InputStream atomInputStream = response.getEntity().getContent();

                 BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

                //BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
                String line;
                String str = "";
                while ((line = in.readLine()) != null){
                    str += line;
                }

                    JSONObject json = new JSONObject(str);
                    JSONObject dataObject = json.getJSONObject("data"); // this is the "data": { } part
                    JSONArray items = dataObject.getJSONArray("items"); // this is the "items: [ ] part

                    for (int i = 0; i < items.length(); i++) {

                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject youtubeObject = items.getJSONObject(i);

                        map.put(KEY_ID, youtubeObject.getString("id")); // id not using any where
                        map.put(KEY_TITLE, youtubeObject.getString("title"));
                        map.put(KEY_THUMBNAIL, youtubeObject.getJSONObject("thumbnail").getString("hqDefault"));

                        String duration = secondToTime(youtubeObject.getInt("duration"));
                        map.put(KEY_DURATION, duration);

                        // adding HashList to ArrayList
                        menuItems.add(map);
                    }

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                isConnect = false;
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return (null);
        }

        protected void onPostExecute(Void unused) {
            // closing progress dialog
            pDialog.dismiss();

            if(isConnect){
                // get listview current position - used to maintain scroll position
                int currentPosition = list.getFirstVisiblePosition();

                btnRefresh.setVisibility(View.GONE);
                // Appending new data to menuItems ArrayList
                vla = new VideoListAdapter(
                        getActivity(),
                        menuItems);
                list.setAdapter(vla);
                // Setting new scroll position
                list.setSelectionFromTop(currentPosition + 1, 0);

            }else{
                if(menuItems != null){
                    current_page = previous_page;
                    btnRefresh.setVisibility(View.GONE);
                }else{
                    btnRefresh.setVisibility(View.VISIBLE);
                }
                Toast.makeText(getActivity(), getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
            }
        }
    }

    // method to convert second to hours, minutes, and seconds
    String secondToTime(int duration){

        String time = "";

        String Hours = "";
        String Minutes = "";
        String Seconds = "";

        double hours = 0.0;
        double minutes = 0.0;
        double seconds = 0.0;

        DecimalFormat df = new DecimalFormat("#.####");

        hours = duration / 3600;
        minutes = (duration % 3600) /60;
        seconds = duration % 60;

        if((hours < 10) && (hours > 0)){
            Hours = "0" + df.format(hours);
        }else if(hours == 0){
            Hours = "00";
        }else{
            Hours = df.format(hours);
        }

        if((minutes < 10) && (minutes > 0)){
            Minutes = "0" + df.format(minutes);
        }else if(minutes == 0){
            Minutes = "00";
        }else{
            Minutes = df.format(minutes);
        }

        if((seconds < 10) && (seconds > 0)){
            Seconds = "0" + df.format(seconds);
        }else if(seconds == 0){
            Seconds = "00";
        }else{
            Seconds = df.format(seconds);
        }

        time = Hours +":"+Minutes+":"+Seconds;
        return time;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        vla.imageLoader.clearCache();
        Log.d("clear cache", "clear cache");

    }
}

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Loco</string>

    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string-array name="channel_name">
        <item >The Loco</item>

    </string-array>
    <string-array name="channel_username">
        <item >LOCOMEDIATVM</item>

    </string-array>
</resources>

EDITED:
HomeActivity.java:
package com.sit.loco.activity;

import com.loco.android.R;
import com.sit.loco.frgment.VideoListFragment;

public class HomeActivity extends FragmentActivity
implements ActionBar.OnNavigationListener, VideoListFragment.OnVideoSelectedListener{

// create object of ActionBar and VideoListFragment
ActionBar actionbar;
VideoListFragment videoListFrag;
int selectedItem;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    // add channel list array to actionbar spinner
    Context context = getSupportActionBar().getThemedContext();
    ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.channel_name, R.layout.sherlock_spinner_item);
    list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);

    // remove actionbar title and add spinner to actionbar
    getActionBar().setDisplayShowTitleEnabled(false);
    getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    getActionBar().setListNavigationCallbacks(list, this);
}

@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    // TODO Auto-generated method stub

    selectedItem = itemPosition;

    // create object of VideoListFragment and send data position to that fragment
    videoListFrag = new VideoListFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("position", itemPosition);
    videoListFrag.setArguments(bundle);

    // call video list fragment with new data
    getSupportFragmentManager()
    .beginTransaction()
    .replace(R.id.content_frame, videoListFrag, "VIDEO_LIST_FRAGMENT")
    .commit();
    return true;
}

@Override
public void onVideoSelected(String ID) {

    // call player page to play selected video
    Intent i = new Intent(this, PlayerActivity.class);
    i.putExtra("id", ID);
    startActivity(i);

}
}

I didn't know how to solve this.Anybody can help me with this.Thank you.
Comment: why are you passing 4 as position if your array contains just 1 item?
Comment: Most of the time we faces the indexout of bound exception because of the loop when we executes the loop more the the size of our datastructure for example if we have 6 element in our arraylist or string array or any structure and we are trying to access the 8 element of that so it will return this exception that is well known as Array Index Out of bound exception
Comment: @blackbelt I didn't know why I got this error.Can you tell me exactly where the error would be occurred
Comment: I don't know exactly where, but probably, before you replace/add your fragment you are settings a bundle as argument for the instance that contains 4 as value for position
Comment: can you please shown setArguments() code ?
Comment: I am edited the post @blackbelt
Comment: how many item in navigation ?
Comment: it looks good. Can you try to clean and rebuild the project
Comment: @Haresh I just need to show the list of videos related to a url with the help channel user name.I need to show only one channel user name.
Comment: @blackbelt yes clean and rebuild but it shows the similar error again
Comment: is onNavigationItemSelected called with the correct position? (`0` I would expect)
Comment: if you have only one channel user name then how you get 4 index ?
Comment: yes I know about it.I run the you tube demo seperately it works fine.But I am trying to adapt in main project that time I got an error. @Hasnain
Answer: Your previous page passes a wrong position:
Bundle bundle = getArguments();
position = bundle.getInt("position", 0);

Although you could just add a check
ChannelUsername = res.getStringArray(R.array.channel_username);
if (position > ChannelUsername.length()-1) {
    YOUTUBE_USERNAME = ChannelUsername[position];
}

You'd better figure out why you are sending a wrong position in the first place.
Comment: `08-25 05:24:17.328: V/position(2514): 4
08-25 05:24:18.148: V/test page(2514): here` I got it like that in logcat.
Comment: @Naruto It's obvious that the argument you get is wrong. The problem is not in the code you've shown, rather the activity that sends you this information.
Comment: @Naruto [this answer](http://stackoverflow.com/a/9696739/3249477) suggests that you need to intercept first navigation menu item selection as it's done by the system. Perhaps that's your problem as the code seems to be fine.
Answer: In VideoListFragment.java:
I changed this

YOUTUBE_USERNAME = ChannelUsername[position];---->Error at Line 110

to

YOUTUBE_USERNAME = ChannelUsername[0];

Why I set this position to 0 means I had a only one channel user_name.


Why is the width and height changed after clicking tabs?

Question: I have index.html, main.js, main.css, ajax.php files on my site: http://goo.gl/HpLQc
I have #home-copy set to height:auto !important. When user clicks above link, the main page is displayed. However, if user clicks the logo (foxcode), the width and length changes.
Why does it happen? How do I fix it?
Comment: Is it because the page width changes due to it adding a scrollbar?
Comment: yap , i think so,  do you know how to solve it? thank you
Answer: You should try to add to the body
overflow: hidden;

This will hide the content that stand out of the box. But adding this to the body is not the 'cleanest' method.
Comment: or keep the scroll bar always visible in case it is usefull : overflow;scroll
Comment: hi Benjamin,  it does not solve my problem. It cause other issue.


Major chords on bass guitar

Question: So I've been playing the bass for about a year and a half, I play most nights and play with friends as often as I can. Until now I have only played songs I can get tab for, and spend time learning it before playing with friends.
I have an understanding of the major scale, but I don't know how to apply it? Does that make sense?  As in, I know what notes would make up a D major scale, but when would I play them? If the guitar plays a D chord can I use any note on the D major scale?
Please answer this question like I have little to no theory knowledge!  In all honesty I wouldn't even know how to find the root chord of a song (yes I am that basic).
I'm asking as I am trying to come up with a bassline for 'Boomerang' by the Plain White T's as I can only find guitar chords for this and not bass tab.
Is there an easier way to do this?
Comment: https://www.musictheory.net/lessons/40 might help
Answer: TL;DR: there is a huge amount of bass playing to do before you need to look at scales at all. Learning a scale pattern isn't going to hurt, but hearing and knowing chord tones is more important.

Asin i know what notes would make up a D major scale, but when would i
play them?

Scales are best used as reference grids for reasoning about notes, and having a means to know where the sounding notes are relative to each other and to the harmonic centerpoint. The most important reference grid is the basic scale of the key the song is in. (The key may sometimes change during the song, and such a key-change, or shift-of-centerpoint is called a "modulation".).
The key i.e. harmonic centerpoint is decided by the tonic chord i.e. home chord. If the home chord is E minor, the song is "in E minor". And there may be a D major chord somewhere in that song. But an E minor scale may not fit every situation in the whole song, because there can be chromatic alterations. You can have an A major chord in the key of E minor, but in the next bar there can be an A minor chord. Or B minor or B major chord. These are chromatic alterations. The scale degrees are changed - the set of notes that seems to fit the harmony changes.

if the guitar plays a D chord can i use any note on the D
major scale?

You might, depending on the situation and if you know what you're doing. But if you don't have any idea what's happening and what the context is, then no, playing randomly from a scale will create chaos, regardless of what the scale is. The D major scale is probably not even the right scale to think about, even if the guitar is playing a D major chord. If the song's home chord is A major, you should think of the A major scale as a basic reference grid to which you compare what's happening.
Having a sense for a harmonic centerpoint i.e. key is essential, and I strongly recommend trying to develop that sense. If you can't tell where home is, if you have to resort to calculation formulas and rules without being able to hear what your notes are doing, then it's better to stick to playing chord root notes.
I've been telling bass players to proceed along the following levels of complexity, when learning to construct bass lines:

(1) written chord root note only. If you strictly play the chord root note only, you don't need to care about scales.
(2) written chord root note only, and an octave above it, which is the same note. For example A on the fifth fret of the E string, and A on the seventh fret of the D string. If you strictly play the chord root note only, you don't need to care about scales. Try an octave down-up jumping disco bass line, or just throw the octave-higher note in for variation here and there.
(3) written chord root note and a fifth above (or fourth below which is the same note-name), for example if the written chord is D major, you alternate between D and A notes. Depending on the genre, this might sound dumb, silly and completely out of place, but it's a necessary skill for a bass player. If you strictly play the chord root note and the chord's fifth only, you don't need to care about scales.
(4) written chord root and other chord tones of the written chord, most importantly the third of the chord. For example if the written chord is D major, you alternate between the notes D, F# and A. D is the chord's "root", F# is the "third", and A is the "fifth". If it was a D minor chord, the notes would be D, F and A. Again, playing this kind of a bass line will usually sound dumb and get you kicked out of the band, but you just have to be able to do it and know what is what in the chord and on the bass fretboard. If you strictly play the written chord's tones only, you don't need to care about scales. But you have to know what notes a minor chord has, what notes a major chord has, what notes a diminished chord has etc.
(5) written chord root and a scale-step below it, along the scale of the key or whatever the prevailing harmony is. If the chord is a seventh chord, you can tell from the seventh what the note below the root is. If the chord is not a seventh, you'll have to know the key. For example if the song is in A major, and there's D major chord, you alternate between D and C# notes.
(5 B) written chord root, an octave above it, and a seventh, which is right below the octave-higher note. This is a variation of the previous bass line. For a written D major chord in key of A major, you'll play e.g. D - D' - C#' - D', where D' and C#' are in the next higher octave.
(6) boogie woogie bass below the written chord note. If there is a D major or D minor chord, play D - B - C - C# - D - B - C - C# - ... it may or may not fit any given instance. But you have to learn to play it anyway, and doing it will help you do the next variation. This is a chromatic line, and with chromatic lines you don't need to care about scales. "Chromatically" means, with one-semitone steps. The distance between adjacent frets on a bass (and guitar) is one semitone. If you go like fret 1, fret 2, fret 3, fret 4... on the same string, it's going chromatically upwards.
(7) chromatically stepping to the next chord root from below. Whatever chord there is, you look at the next chord - that's your target note, and exactly three beats or pulses before it you start stepping towards your target, so you land on the target note exactly on beat ONE, or whenever the target chord is supposed to start. For example if the current chord is D major, you play D, D, D, D, .... then you see a G major chord. Exactly three pulses before the G, you start stepping: (3:) E, (2:) F, (1:) F#, (ZERO:) G. Instead of three steps, you could do two, or just one. With chromatic lines you don't need to care about scales. You just go semitone by semitone.
(8) chromatically stepping to a target chord root from above. Kind of the same as trick 7, but from above instead of from below. Two added steps may work better than three. When you go from D major chord to G major chord, you go like D, D, D, D, A, G#, G, ... A is two semitones above the target note G, and G# is one semitone above it. This could also be called "chromatic approach from above". Again, this is a chromatic line, and with chromatic lines you don't need to care about scales. A single-step chromatic approach on the bass can be analyzed as a "tritone substitution". Theory geeks will get excited when they notice you did a tritone substitution!
(9) stepping to the next chord along the scale (which may be chromatically altered). For this you'll really need to know a suitable scale, so you don't mix major and minor chords, for example.
(X) walking bass. This is maybe the most difficult phase. It means all sorts of walking and jumping to target notes. But even with just the tricks 7 and 8 i.e. chromatic approaches from above and below, you may be able to fake a walking bass, if you do that constantly. If you throw in a few chord tones from tricks 4 (or 3), maybe nobody even notices that you don't know about scales at all! Only chord tones and chromatic approaches, no scales...

If we sum all of the above, and if those 10 tricks are representative of all commonly done basslines, we can say - and I claim - that for MOST pop/rock/blues bass playing, you don't play from any scale at all. You know your chord tones and add some chromatic stuff, and that gets you something like 80% of everything. I'm sure there are lots of bass players out there who play nice and varied bass lines, but they have never memorized a scale pattern in their lives.
But. Outside of ALL THAT chord+scale+chromatic, in its own separate category is: learning basslines and riffs from existing songs. You learn to play a bass pattern, and know what style and chord it's in. Then you move the same pattern to other chords. Memorized movable riffs and patterns over chords is yet another way of playing bass lines which doesn't require caring about scales.
Here's a really nice bassline from Johnnie Taylor's "Still Called The Blues". It's in Bb minor, so it fits the video below. It would fit pretty much any blues in Bb, although that's a rare key for blues tunes.

You basically play minor blues with that pattern. It's a blues and the same bass line works equally well over minor and major chords. First you play it in Bb like in the tab, then in in Eb, then in F, etc.

If a song is in A or A minor, the first chord's pattern would be one fret i.e. one semitone lower like this:

Someone might comment something about the particularities of that bass pattern, and the fact that it has a "minor seventh" or "dominant seventh", but... As the most important thing there could be in music, I say that you have to learn to listen. Learn a pattern and try playing it over different things. Do you notice anything different? Try to apply a pattern from some other song - what does it sound like? You cannot infinitely rely on any teacher or tab or internet forum to tell you what to play and when some note fits or doesn't fit. At some point you have to be able to hear yourself.
Answer:
I'm asking as I am trying to come up with a bassline for 'Boomerang' by the Plain White T's as I can only find guitar chords for this and not bass tab.

One important point: "guitar chords" are bass chords too, if we mean letter names. (Guitar tab is another matter.) But if you see "C ... F ... G," then it's as simple as playing the note C, the note F, and the note G.
That's the most basic starting point in bass playing, and you can go far with it. If you want to liven things up, you can start adding extra notes; e.g. during the time that the chord is C, you can play notes that do or don't belong to a C chord. (The actual bass line in "Boomerang" does a lot of quick arpeggiating of the notes in the chord.) But start by just playing these "root" notes and wait until you get bored to try anything fancier!
Answer: Diego,
You can never go wrong by studying and plucking/fingering the notes of the D Maj scale, (D, E, F#, G, A, B, C#, next octave higher D), and then experimenting with repeating whichever notes form a pleasing riff or run that pleases your ear.
Evaluate the songs you have learned to play before this date.
Were any of them rooting in D Major?
Study what that bass player did, and isolate his or her parts.
Practice those.
Improvise on your own.
Bounce any fresh ideas you come up with off of your musical friends.
Once they begin to add guitar and percussion, you may find that you have written a new song!
Answer: Firstly, learning from tab isn't the best. You only learn each individual song, rather than learn what a bassist might play in a specific key - as you're finding.
Using your key D example, get your guitarist to play a load of D chords, and play each note in your already known D scale.
You'll find that some fit perfectly. Those will be ^1, ^3 and ^5, Matching exactly the notes the guitar plays at that time. The other notes in that scale are what I call 'stepping stone ' notes. They can be used to bridge the gaps, as bass players will most often play ^1, ^3 or ^5 on the main beats in a bar - beats 1 and 3. I'll stop there, as this could develop into a very long answer, but try that first. Good luck!

Major chords on bass guitar


Invariant measure of a reflected random walk

Question: Let $(X_n), n \geq 0$ be a Reflected Random Walk defined by:
$X_0 = 0$ and:
$ X_{n+1}=\max( 0 , X_n + \xi )$
$\xi $ is a random variable such that $P(\xi=a)=\theta$ and $P(\xi=-b)=1-\theta$ for a given of strictly positive integers $a$, $b$.
I think that this RRW is positively recurrent iif $\theta \leq \frac{b}{a+b}$. (i computed the drift as if the RW was not reflected).
So if i understood the theory, i know that there exists a stationary distribution in this case.
But when i try to compute it just using the definition $(\pi P = \pi)$ i have a linear equation which links $\pi_n, \pi_{n-a}$ and $\pi_{n+b}$ for large enough $n$. I don't know what i can do to get an explicit expression for $\pi$ from that?
Please let me know if i made a mistake, or if you have any idea for this computation.
Thank you in advance!
Answer: Actually if $\theta=b/(a+b)$ the drift is zero on $[b,+\infty)$ hence the chain is null recurrent. Positive recurrence holds for every $\theta\lt b/(a+b)$, which we assume from now on.
As you explain, the stationary distribution solves $\pi=\pi P$. For every $n\geqslant a$, this reads $$\pi(n)=\theta\pi(n-a)+(1-\theta)\pi(n+b).$$ Such linear systems are solved through their characteristic equation $$r^a=\theta+(1-\theta)r^{a+b}.$$ In general, this has $a+b$ solutions $(r_k)$, one of them being $1$, hence $$\pi(n)=\sum_{k=1}^{a+b}c_kr_k^n,$$ for some constants $(c_k)$ determined by the "limit" conditions, that is, by $(\pi(n))_{0\leqslant n\lt a}$, and by  the normalizing condition $$\sum\limits_{n=0}^\infty\pi(n)=1.$$ The normalizing condition imposes that $c_k=0$ for every $|r_k|\geqslant1$ hence the sum over $k$ giving $\pi(n)$ can be restricted to those $k$ such that $|r_k|\lt1$.

Example: Consider the case $(a,b)=(1,2)$ with $\theta=\frac12$, then the chain is indeed positively recurrent and its characteristic equation is $\frac12r^3-r+\frac12=0$, with roots $1$, $p=\frac12(\sqrt5-1)$, and $-\frac1p$, hence $p$ is in $(0,1)$ and $-\frac1p\lt-1$.
The only root such that $|r|\lt1$ is $p$ hence $\pi(n)=cp^n$ for some constant $c$. The "limit" condition reads $\pi(0)=\frac12\pi(0)+\frac12\pi(1)+\frac12\pi(2)$, which is satisfied by every sequence  $\pi(n)=cp^n$. Finally, the normalizing condition $\sum\limits_{n=0}^\infty\pi(n)=1$ yields $$\pi(n)=(1-p)p^n.$$


Change a Node Reference field value with VBO

Question: I'm having trouble setting a Node Reference field using VBO. If I select Integer as the parameter type it doesn't change the field value, and if I set it to Node Reference it has a "Data selector *" field for the input and no value seems to satisfy it.
Any suggestions?
Comment: Maybe you should select full node as a parameter. If you have only nid, you can load node just in rule.
Answer: Ok what worked out was having 2 parameters. One the node I'm altering, the other an integer field to input the node ID. Then I set up a "Fetch entity by id" action using the integer parameter. I use the entity variable provided by the fetch action to set the node reference field.


Can this clinical data be modeled with survival analysis or recurrent neural network

Question: I am not from statistics background but I am faced with data that seems to be survival data.
First of all, I read about survival analysis and I know about recurrent survival data and different models (AG, PWP, Frailty, WLW) for it.
Data description
The data that I have is from clinical trials:
Each patient was supposed to have a specific test (T) each year and from this test we can "guess" the percentage of infection (POI). The data also has more covariates about patients; Age, Sex, DOB, Race, and more. All in all, some patients did all T tests in 10 years (Folow-up time) while the others did some of these tests.
The goal
To predict the POI for next visit from previous or current test. I already restructured the data such that I can use it with one of previous recurrent models.
Suggestion
I read about Recurrent Neural Network and I am thinking to use it as a predicting mechanism, is this possible?
Answer:
I read about Recurrent Neural Network and I am thinking to use it as a predicting mechanism, is this possible?

I am less familiar with survival analysis, but this seems to be a fine fit for an RNN.  You define $T$ as the test but also as the number of tests, but let's go with the second one and say that for each patient you have $T$ tests.  The RNN would take as input the lengh-$T$ sequence of $K$-dimensional vectors (assuming you have $K$ features, which include the covariates and the test) and output the POI.  So you would be mapping from a sequence to a scalar.
Survival analysis generally seems to be concerned with 'time-to-event' estimation (eg, time to death), so might not be as applicable here, where you're not concerned with time, although you might run into issues like censoring (eg, missing data because the patient didn't follow up) associated with survival analysis.
Depending on the amount of data, an RNN might have too much capacity for this task, but it wouldn't hurt to try.  You could also try simply using fixed-length representations for the sequences and using a non-temporal model.  For example, transforming each patient's sequence by taking their mean previous POI and seeing if it predicts the next POI as features in a regression.

My point of interest is to predict the POI for next visit from previous or current test.

The benefit of the RNN would be that you could predict POI of the next visit taking into account all previous tests, covariates from a patient---ie, the RNN will remember not just the most recent but all tests.
How do you deal with misaligned, irregularly sampled, missing clinical data?

See:
Lipton, Zachary C., David C. Kale, and Randall Wetzel. "Modeling
missing data in clinical time series with rnns." Machine Learning for
Healthcare (2016).
Futoma, Joseph, et al. "An Improved Multi-Output Gaussian Process RNN
with Real-Time Validation for Early Sepsis Detection." arXiv preprint
arXiv:1708.05894 (2017).
Comment: I really appreciate your FAST respond to my question and the valuable info. that you mention. I will go with your suggestions and let you know what is the results. Thanks user99889
Comment: So I read about RNN and to fit this to data I am confused if what I am thinking is right. Let say I have five patients A,B,C,D,E with 10,3,7,1,2 T test respectively. What about the missing data, i.e patient A has a length 10 vector of let say 7 features while the B patient will be with 3 length and so on? what about the value of each test?  Please more clarification and details.
Comment: Missing data in clinical time series is a huge issue that would have to be dealt with using any time series model, although it's much better to deal with it as you describe than to use a time window approach and deal with it implicitly, sometimes unconsciously.  A naive approach: carry the most recent value over (forward fill).  A better approach: use a statistical model to interpolate. Also see my edits.


Is Component inside render function called child component

Question: I have a little confused about children component. As I know children component is the component nested inside other component, for example
<Parent>
   <Child />
</Parent>

But what is the component inside the render function of Parent component. What is it called? For example of Parent component
class Parent extends React.Component {
  render() {
    return (
      <ComponentX>
        {this.props.children}
      </ComponentX>
    )
  }
}

Is ComponentX called a children of Parent Component?
I appreciate any explanation. Thanks in advance
Answer:
Is ComponentX called a children of Parent Component?

NO.
ComponentX is called an Enclosing component of Parent's children.
Similar to how React.Fragments are used, without an enclosing element, there will be a warning:

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag
Comment: If `Parent` component is an enhancement of `ComponentX`, then yes.
Comment: Thanks for reply, so what happen if Parent component render function only return ComponentX (return ). Is it still called enclosing component of parent?
Comment: That's a bit unusual since React is based on [Composition](https://reactjs.org/docs/composition-vs-inheritance.html) pattern. Typically this is an ideal case for [Higher Order Components](https://reactjs.org/docs/higher-order-components.html).
Comment: So Parent component is like a HOC of componentX right
Answer: class Parent extends React.Component {
  render() {
    return (
      <ComponentX>
        {this.props.children}
      </ComponentX>
    )
  }
}

this.props.children here is of Parent, and when you pass them into children of ComponentX. In ComponentX you will got this children.
Example:
class Parent extends React.Component {
  render() {
    return (
      <ComponentX>
        {this.props.children} // Here is children of Parent
      </ComponentX>
    )
  }
}

In ComponentX:
class ComponentX extends React.Component {
  render() {
    return (

        {this.props.children} // Here is children of ComponentX that you passed
        // in above

    )
  }
}

In this case, you get children of Parent to use for childrent of
  ComponentX
Comment: Thanks for replies. But I wonder is that what is the relationship between ComponentX and Parent?


Using finite difference in python

Question: I am trying to use Python with Numpy to solve a basic equation using the finite difference method. The code gives me the correct first value for a i.e it gives me a[1]; however, every other value after that is just zero?
I don't know what I'm doing wrong because it obviously works for the first value so how do I fix this?
Any ideas would be very helpful.
from numpy import *
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
from scipy.integrate import odeint

def solver(omega_m, dt):
    #t_0, H_0, a_0, dt, n, T; always the same; omega's change
    t_0 = 0.0004
    a_0 = 0.001
    H_0 = 1./13.7

    T = 13.7
    dt = float(dt)
    n = int(round((T - t_0)/dt))
    x = zeros(n+1)
    t = linspace(t_0, T, n+1)

    x[0] = a_0

    for i in range (0, n):
        x[i+1] = x[i] + (H_0 * ((omega_m)**(1./2.)) * ((x[i])**(-1./2.)) * dt)
        return x, t

a, t = solver(omega_m =1, dt=0.001)
print a, t

Answer: Your function returns after the first iteration because your return statement is inside the for loop. You should dedent the return statement so your loop does not terminate prematurely:
for i in range (0, n):
    x[i+1] = x[i] + (H_0 * ((omega_m)**(1./2.)) * ((x[i])**(-1./2.)) * dt)
return x, t

Comment: Thank you very much, really should have noticed that myself! But thats a big help, working as it should now.
Comment: Done now. Sorry didn't know how to do that.

Using finite difference in python


Left inverse matrix for two different matrices?

Question: Consider two matrices $\mathbf{D}_1$ and $\mathbf{D}_2$ in $\mathbb{R}^{m\times n}$ $(m>n)$ of full column rank, is there a matrix $\mathbf{D}^{-}$ in $\mathbb{R}^{n\times m}$ satisfying $\mathbf{D}^{-}\mathbf{D}_1=\mathbf{I}_n$ and $\mathbf{D}^{-}(\mathbf{D}_1+\mathbf{D}_2)=\mathbf{I}_n$?  Note that $(\mathbf{D}_1+\mathbf{D}_2)$ is a matrix of full column rank. Many thanks! and if so, any way to prove it?
Answer: Note that if $\mathbf{D}^-$ were to exist, we should have
$$
\mathbf I_n = \mathbf{D}^-(\mathbf{D}_1+\mathbf{D}_2) = \mathbf{D}^-\mathbf{D}_1+\mathbf{D}^-\mathbf{D}_2 = \mathbf I_n + \mathbf{D}^-\mathbf{D}_2,
$$
hence
$$
\mathbf{D}^-\mathbf{D}_2 = 0.
$$
But since $\mathbf{D}_2$ has full rank, this implies $\mathbf{D}^- = 0$, a contradiction.


Join Azure VM to Azure AD

Question: Using Microsoft Azure I have a default Active Directory domain (apparently) and I can create VMs.  To my surprise, such VMs are not joined to the AD domain automatically and domain users can't log into it.
Is it possible to join these Azure VMs to the Azure Default AD?  How or why not?
Thanks!
Answer: Azure AD isn't your "regular" AD. You're not able to join computers to it. What you CAN do, is the following:
Set up your own domain controllers (these can also run on Azure), and use Azure Dirsync (which is a service you install on a VM) to sync user objects between your "regular" AD and Azure AD. That way, you have a normal AD forest you can use for computer joins and such, but also enjoy the benefits of being able to do single-sign on to Azure websites, Office365 etc using the replicated accounts in Azure AD. There is a very good document describing this sort of architecture (although it's made for Office365 it goes for Azure as well, since the Azure AD instance is the same), which can be found here. Well worth the read:
Deploying Office 365 Single Sign-On using Windows Azure
Comment: This may have changed a bit with Azure AD Domain Services (currently in preview) https://azure.microsoft.com/en-us/documentation/services/active-directory-ds/
Comment: Correct. Think of Azure AD as a membership db and authentication system, not a full-blown AD. And the sync stuff makes it pretty cool, actually.
Comment: Thanks.  So in order to have a real Active Directory I need a VM that I dedicate to be domain controller and have it running all the time.  That's lame!
Comment: @MrHinsh Windows 10 Pro or Enterprise
Comment: This answer is out of date - the solution is to use Azure AD DS
Comment: You can join computers to Azure AD as long as the client is Windows 10.
Comment: Who on server fault has Home? ;)
Comment: If you're joining Azure VMs to the Azure AD DS domain, you can do it with Windows 2012 R2.
Answer: Check out the (Still in preview) Azure Active Directory Domain Services. with this feature you will be able to join an Azure VM to your Azure AD Domain. you will also be able to use GPOs for computer and users.
Comment: In 2020 this should be the accepted answer.
Answer: Only Windows 10 OS/VM can be now join directly to Azure AD.
2 usefull links on this subject
http://blogs.technet.com/b/ad/archive/2015/05/28/azure-ad-join-on-windows-10-devices.aspx
http://blogs.technet.com/b/ad/archive/2015/05/13/azure-active-directory-and-windows-10-making-the-enterprise-cloud-a-reality.aspx
Regards
Stanislas
Comment: links are broken :(
Answer: I was able to do this with Azure VMs (Windows Server 2012 R2).
It requires Azure AD Domain Services. If you're setting group-based permissions (e.g. for folder or RDP access) you need to use a security group (distribution lists and O365 groups, including built-in groups, will not work).
You may need to configure the DNS servers if they're not set up correctly.
You need to have a local VM admin-level account and an Azure AD admin-level account.
You just change the domain under my computer as you would when joining it to a regular domain (you will need to enter the Azure AD admin credentials).
Note: Don't forget that you also need to add RDP access for the users/groups before they will be able to RDP into the VM with their Azure Accounts.
You don't need a separate domain controller or DirSync.
Answer: Keep in mind that by promoting one of the servers to a domain controller, you can then have it sync with Azure AD for the users and groups.  When we talk about Windows 10 joining the Azure AD you are only joining to see the list of applications available and authentication for the user.  This is not the same as joining a typical on-premises active directory domain.  Suggestion is to build two AD controllers in Azure VMs and then have them sync with Azure AD.  Have any servers or computers created join the same virtual network that the domain controllers are a part of.  Here is a step by step guide for setting up a lab environment around the same idea:
http://www.virtuallycloud9.com/index.php/2015/02/it-camp-azure-labs-lab-1-building-the-foundation-step-by-step/
Comment: Unfortunately, sync is only one way when you have both AD servers and O365. It will only sync from the AD server to O365, so if someone wants to, say, add new accounts from O365 then these won't actually be added to the AD server. For this ticket, they wanted the O365 accounts to be the "source of truth".

Join Azure VM to Azure AD


Role of regression model fit in causal analysis

Question: When analysing causal questions, we use DAGs that give us covariates needed for modelling. But another time we assess model fit to get the best prediction. These two approaches have different purposes and are mostly used separately (?). But is there also a place for their simultaneous use?
For instance, we have a nested data, and we would like to analyse temporal trends on an outcome.

Minimal sufficient adjustment sets for estimating the direct effect of year on outcome:
covariate, state

Though the DAG gives us model structure, we still have multiple options for specifying our model. For example, we can use hierarchical modelling if we know that there were regionally different baselines and/or varying temporal trends.
outcome ~ covariate + state
outcome ~ covariate + (1 | state)
outcome ~ covariate + (covariate | state)

Thus, would it be a case in causal analysis where we should also assess the model fit? Meaning that the published model was chosen according to the DAG and model fit comparison?
And is there also another dimension - interpretation. When reporting predicted country-wide trends (not regional trends), isn't it so that the first additive model only gives us the temporal trend for one state (state and covariate variables needs to be fixed on one value)? In contrast, hierarchical models' temporal trends predictions are somewhat done for all states at once? If my understanding is true, the first additive model is poor for reporting country-wide trends?
Answer: A DAG is a non-parametric model of the causal relations among a set a variables. The DAG tells you that covariate and state should be adjusted for, but it tells you nothing about how to adjust. Covariate adjustment is one approach, and stratification is another. Here you are proposing three covariate adjustment models:

outcome ~ covariate + state
outcome ~ covariate + (1 | state)
outcome ~ covariate + (covariate | state)

The DAG does not help you choose which one to use. Each model represents different parametric assumptions, none of which the DAG can inform us about. There are many considerations for choosing among these models. A few are:

how mahy state's are there ? If too few then the first model is the only option.

Does covarate vary within levels of state ? If not then the third model is not appropriate. If it does, then the 3rd model may be appropriate provided that the model is supported by the data (and random slopes often are not - despite being clinically/theoretically appropriate)

Also note that, for the exact same reasons, the DAG can't tell you whether you should include nonlinear terms such as quadratic, cubic, or splines; nor can it help determine any transformations that might be needed