If $A\subset B$ then $\bar{A}\subset \bar{B}$

Question: Please let me know if you find my proof satisfactory.
Let $A\subset B\subset \mathbb{R}^n$, where $\bar{A}$ is the closure of $A$.
If $\vec{x}\in \bar{A}$ then $\vec{x}\in A^\circ$ or $\vec{x}\in ∂A$ (in the boundary of $A$). If $\vec{x}\in A^\circ$ then $\vec{x}\in A \implies \vec{x}\in B\subset \bar{B}$.
If $\vec{x} \in ∂A$ then $B_\varepsilon(\vec{x})\cap A\ne \emptyset \ne B_\varepsilon(\vec{x})\cap B$ (for any $\varepsilon > 0$). Thus, since $A\subset B$, $\vec{x}\in B \implies \bar{A}\subset \bar{B}$.
Comment: $A \subset B$ doesn't preclude $A = B$, does it?
Answer: $A\subset B\implies A\subset\bar B\implies\bar A\subset\bar B $.
Comment: While that is true, I'm not sure the second step is less trivial than the actual claim.
Comment: $\bar A$ is the smallest closed set containing $A$ (that's how it was defined for me anyway...) from which it is a pretty trivial step.
Comment: In that case I agree, I was given the definition $A \cup \partial A$ though.
Answer: For $x\in \partial A$ you cannot proof in general that $x \in B$. Also $B_\varepsilon(x)\cap A\neq\emptyset\neq B_\varepsilon(x) \cap B$ is not realy an argumentation. The logic should be $B_\varepsilon(x)\cap A\neq\emptyset \Rightarrow B_\varepsilon(x)\cap B\neq\emptyset$ since  $B_\varepsilon(x)\cap A\subseteq  B_\varepsilon(x)\cap B$ for all $\varepsilon>0$. As I said, this cannot imply that $x \in B$, but it does imply that either $x \in \partial B$ or $x \in \mathring{B}$ which is sufficient for you.
That comment was right of course, I fixed the answer.
Answer: Almost.
If $x\in∂A$ then, for any $\epsilon>0$ we have $$B_{\epsilon}(x)\cap A\neq\emptyset\Rightarrow B_{\epsilon}(x)\cap B\neq\emptyset$$ and $$B_{e}\cap A^{c}\neq\emptyset$$ where $A^{c}$ is the complement of $A$. If $B_{\epsilon}(x)\cap B^{c}\neq\emptyset$ we have $x\in ∂B$. If $B_{\epsilon}(x)\cap B^{c}=\emptyset$ we have $x\in B^\circ$. Therefore $x\in\overline{B}$.


Keras ModelCheckpoint overwrites previous best checkpoint when training resumed

Question: I am using ModelCheckpoint callback from Keras:
    checkpointer = ModelCheckpoint(filepath= model_filepath,
                                   verbose=1,
                                   save_best_only=True)

I cannot train my model in one step, so I have to save/load my model several times and resume the training to improve my model. However, when I load my model and resume the training, when the first epoch ends, since the val_loss changes from inf to some value (let's say 0.23) the previous model will be always overwritten. But my previous best val_loss in the previous time that I was training my model was 0.19 (0.19 < 0.23 => the previous model is still the best => previous model should not be overwritten).
How can I tell Keras: Please consider the previous best val_loss in the previous time that I trained my model and stop this wrong behavior.
Answer: Since it is not programmed for this purpose I would not consider it wrong.
I would suggest that you change the filepath parameter for of the callback whenever you resume your training, this way at least you do not lose the previous best.
Answer: from tensorflow.keras.callbacks import ModelCheckpoint, LambdaCallback

work_dir = "drive/My Drive/Training Records/"
NUM_EPOCHS = 300
checkpointer_name  = "model_checkpoint.hdf5"
log_name = "log_"+checkpointer_name[:-5]+".log"

Step 1:
checkpointer = ModelCheckpoint(filepath = work_dir+checkpointer_name,
                           monitor='val_loss',
                           mode='auto',
                           verbose = 0,
                           save_best_only =False
                           )
checkpointer_best = ModelCheckpoint(filepath = work_dir+"best_"+checkpointer_name,
                                monitor='val_loss',
                                mode='auto',
                                verbose = 1,
                                save_best_only = True
                                )

Step 2:
def checkBestPerformance(epoch, logs):
    log_data = pd.read_csv(work_dir+log_name, sep=',', usecols=['val_loss', 'val_accuracy'], engine='python')
    min_val_loss = min(log_data.val_loss.values)
    max_val_acc = max(log_data.val_accuracy.values)

    current_val_acc = logs['val_accuracy']
    current_val_loss = logs['val_loss']

    save_filepath = work_dir+"best_"+checkpointer_name
    if current_val_loss < min_val_loss:
        model.save(filepath = save_filepath)
        print("\nval_loss decreased from", min_val_loss, "to", current_val_loss, ".")

    elif (current_val_loss==min_val_loss) and (current_val_acc>max_val_acc):
        model.save(filepath = save_filepath)
        print("\nval_accuracy increased from", max_val_acc, "to", current_val_acc, ".")

    else:
        print("\nPerformance did not improve from existing min_val_loss =", min_val_loss, ", max_val_acc =", max_val_acc, ".")

Step 3:
epochs_completed = 0
csv_logger = CSVLogger(work_dir+log_name, separator=',', append=True)

try:
    log_data = pd.read_csv(work_dir+log_name, sep=',', usecols=['epoch'], engine='python')
    epochs_completed = log_data.shape[0]

    if epochs_completed > 0:
        model = load_model(work_dir+checkpointer_name)
        list_callbacks = [checkpointer, LambdaCallback(on_epoch_end=checkBestPerformance), csv_logger]
        print("epochs_completed =", epochs_completed)
except:
    list_callbacks = [checkpointer, checkpointer_best, csv_logger]

Step 4:
print("Previously completed epochs =", epochs_completed, "\n")

history = model.fit(final_train_imageset, final_train_label,
                shuffle=True,
                batch_size = BATCH_SIZE,
                epochs = NUM_EPOCHS - epochs_completed,
                validation_split = 0.1,
                callbacks=list_callbacks
                )


Is it possible to include extra arguments when migrating via command line?

Question: Is it possible to include extra arguments when migrating via command line?
I have a custom migration which migrates XML content into Drupal as entities. However, each XML document of migrated entities need to be associated with a different node.
I'm successfully doing this entities to node association via the following code:
function complete($entity, stdClass $row) {
    $node = node_load(1);
    $node->field_questions[$node->language][ sizeof($node->field_questions[$node->language]) ]['target_id'] = $entity->id;
    node_save($node);
}

As you can see from the code, the NID is hardcoded. Of course, the NID could be extracted from the XML input but it is unknown in advance of the migration.
So, I just wonder if running drush migrate Questions could be run with custom arguments where I could specify the target NID to associate my migrations with?
Something like, drush migrate Questions --nid=10
Answer: In the URL below you can find Dush arguments for migrations. Following the documentation you need --idlist argument.

See here https://www.drupal.org/node/1561820
Hope that helps.


SQL Server Reporting Services: Limit Legend to One Series for Chart that has Multiple Series

Question: I have a chart with these characteristics:

chart type is XY (scatter )
all XY data have x-values that are integers; they are called "Update Cycle" numbers. This represents "score" data from a given program.
in addition to the values that produce the XY data, I've added two other elements to the "Values:" list: one that is the average of the XY data for any Update Cycle (x-axis) value, and another that is the average of "similar programs" for any Update Cycle. These elements are plotted as lines ("trend lines") on the chart.
Category Group is Update Cycle number
Series Group are (1) PersonID and (2) ProgramID

It all plots fine, but here's my problem:
If I add a Legend, it wants to add Legend entries for each and every point for each and every person (because of SeriesGroup1)  - I imagine it's also showing legend entries for the second series, but there are so many for the first series, I can't read anything.
Question: How do I supress legend entries for the first series and only display the two legend entries for the 2nd series?
Answer: I have the same problem, Is any solutions for the series text overlaping?, I found a solutions, but I cann't use, because divided the chart in various charts, by the way, heres is the link of the article:
http://social.msdn.microsoft.com/Forums/en-US/sqlreportingservices/thread/841e1515-3519-4c4f-a76f-f6fcebd25dfd/
If somebody have another solutions, pleace post it.
Thanks and sorry, my English is a little poor.


Creating a transition plot with three columns

Question: I have data consisting of multiple classes (in this example three classes) of test subjects but the classes vary based on three time points: genotype, early phenotype and late phenotype stages.
Here is the sample data:
genotype<-cbind(c(rep("A",100),rep("B",100),rep("C",100)))
early_phenotype<-cbind(c(rep("A",75),rep("B",75),rep("C",75),rep("A",75)))
late_phenotype<-cbind(c(rep("A",50),rep("B",100),rep("C",100),rep("A",50)))
df<-cbind(genotype,early_phenotype,late_phenotype)
df<-as.data.frame(df)
colnames(df)<-c("genotype","early_phenotype","late_phenotype")

I would like to produce what is commonly referred a "transition plot". The closest I have gotten is this:
library(Gmisc)
transitionPlot(table(df[,1:2]), txt_start_clr = "black", txt_end_clr = "black", fill_start_box = "white", fill_end_box = "white")

... which producing this plot:

But I am trying to achieve two things that this plot does not have:

I want more than two columns, in this example three columns: genotype, early phenotype, and late phenotype. In this example, it would look like this (I achieved this in Photoshop, not in R)

Instead of single arrows with different weights that connects two boxes, I would much rather have multiple arrows with jitter / transparency where each arrow would represent an individual observation, and would appear something like this:

Any suggestions?
P.S. I don't really care about the curved edges of the boxes, or the fancy shadows.
Comment: More than 2 columns is possible using the [Gmisc::Transition-class](https://cran.r-project.org/web/packages/Gmisc/vignettes/Transition-class.html)
Answer:

I want more than two columns, in this example three columns
Instead of single arrows with different weights that connects two
  boxes, I would much rather have multiple arrows

Maybe try something using igraph:
m <- sapply(1:3, function(x) paste0(df[, x], x))
el <- rbind(m[, 1:2], m[, 2:3])
library(igraph)
g <- graph_from_edgelist(el)
coords <- layout.norm(t(sapply(strsplit(V(g)$name, ""), function(x) as.numeric(c(-match(x[1], LETTERS), x[2])))))
plot(g, layout=coords[, 2:1])

Comment: looks promising, never heard of `igraph` before. Is there a way to change the spindle-shaped arrows to be less overwhelming? The real data has 1000+ observations so I'd rather employ alpha / transparency (I added sample picture in my above post)
Comment: Have a look at `?igraph.plotting` - you can for instance add `edge.arrow.size=0.5` to decrease the arrow size. It seems as if an `edge.color` with alpha (e.g. "#99999966`) does not work.
Comment: I see, without alpha though it would look like a solid spindle


Can I use z-scores with an exponential distribution? Or is there another test statistic for these types of distributions?

Question: I have an exponential distribution for a population. $\theta = \mu = \sigma$ is known. Sample size $n$ is known. I need to find $"(<¯<)"$ for a random sample with size $n$.
I think I am supposed to use the z-score (or at least that's what I would do if it was normally distributed), but I'm not sure what to do for an exponential distribution.
If you need to know numbers to help me:
$\theta = \mu = \sigma = 50$
$a = 45$
$b = 60$
$n = 60$
If I use the z-score this is how I would do it:
P(x>45): z = (45-50)/(50/sqrt(60)) = -.77 -> 0.2794 (from table) -> .5-.2794 = .2206
P(x<60): z = (60-50)/(50/sqrt(60)) = 1.55 -> 0.4394 (from table)
.4394 + .2206 = .66
this seems a lot better intuitively
Comment: 1. Your body text says "$P(a45 and x<60, get the values from the table in my book and subtract to find the inbetween
Comment: I meant to do that calculation in an edit to your original post. Write it out with the numbers and a final answer.
Comment: I did it and got 0.16. This intuitively does not seem correct, I would expect it to be higher
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/106444/discussion-between-ethan-hennessey-and-dave).
Answer: From your work with z-scores, it seems clear than you want
to find $P(45 < \bar X < 60),$ where $\bar X$ is the mean of
a sample of size $n = 60$ from an exponential distribution
with mean $\mu = 50,$ rate $\lambda = 1/50 = 0.02.$
Normal approximation. You can get a useful rough approximation by assuming that
$\bar X$ is approximately normally distributed.
It is true that $E(\bar X) = 50,\,$ $Var(\bar X) = \sigma^2/n
= 50^2/60 = 41.67,\,$ and $SD(\bar X) =6.455.$
If it were exactly true that $\bar X \sim
\mathsf{Norm}(\mu=50, \sigma =6.455),$ then $P(45 < \bar X < 60) =0.720,$ according to the following computation in R. (Your method of standardizing and using printed tables of the standard normal CDF will get very nearly the same answer, if you use the results of the table properly.)
diff(pnorm(c(45,60), 50, 6.455))
[1] 0.7200416

The Central Limit Theorem provides accurate results for
sufficiently large $n.$ However, the mean of $n=60$ exponential observations is still noticeably skewed to the right. A normal approximation would work better for the
mean of a sample twice as large.
Exact computation using a gamma distribution. An exact solution is available, as follows. One can
show that $\bar X/\mu \sim \mathsf{Gamma}(n, n),$ so
$P(0.9 = 45/50 < \bar X/\mu < 60/50 = 1.2) = 0.709,$ according
to the following computation in R.
diff(pgamma(c(.9, 1.2), 60, 60)
[1] 0.7090068

Simulating the sum of exponential observations. Also, the following simulation of a million averages of 60 such
exponential random variables gives the same answer, within the margin of simulation error. (The simulation should be accurate
to two or three decimal places.)
set.seed(2020)    # for reproducibility
a = replicate(10^6, mean(rexp(60,1/50)))
mean(45 < a & a < 60)
[1] 0.708975      # aprx 0.709
2^sd(45 < a & a < 60)/1000
[1] 0.001370056   # aprx 95% margin of sim error

Below is a histogram of simulated values of $\bar X/50$ along
with the density function (black) of its exact gamma distribution
and the density function (broken red) of its approximate normal distribution $\mathsf{Norm}(50/50, 6.455/50).$
(The gamma distribution is slightly right-skewed and the normal distribution is symmetrical.)


Has anyone obtained an invitation to SUN Cloud?

Question: Does anyone here know how to get an early invitation to the Sun Cloud?
Comment: As ever in life, I'm sure it's not what you know, but who you know.
Answer: From Sun's Cloud website:
Four Ways To Touch the Sun Cloud
Subscribe: Get on the list for the Early Access programs.
Share: Review and comment on developing cloud APIs.
Learn More: Get Sun's free guide to cloud computing architecture and infrastructure.
Join Us: Sun's partner initiative helps qualified companies with co-marketing and technology assistance.
Comment: Yes. Before I tried this forum I did all those steps.  I think Farseeker is right, you probably need to know someone ;).

Thanks


UIImagePickerController returns different image sizes for iPhone 3Gs and 4s

Question: I'm picking an image using UIImagePickerController . In iPhone 4s, the image looks like

And when I use an iPhone 3GS the image looks like this

3gs images look blurred.
I don't know why this is so. Here's how I'm fetching the images.
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"])
    {
        [picker dismissModalViewControllerAnimated:YES];
        imgPicker = nil;
        UIImage * userOriginal = [info valueForKey:UIImagePickerControllerEditedImage];
        NSLog(@"orinal image Image size: (%f, %f)",
              userOriginal.size.width, userOriginal.size.height);
     }
}

Comment: Well, you should expect that, the cameras are quite different.
Comment: so we do any thing for this issue
Comment: I have no idea of what your app does, it's up to you to choose how you want to handle different resolutions.
Answer: UIImagePickerController returns images at the highest quality and resolution that the camera can capture - and this is different for all iOS devices.
If you want a standardized output, you will have to manually resize the image returned.


How to change taxonomy term ID to term name?

Question: I'm trying to change path of my site which is based on taxonomy tags. Default path of my site in this context is /taxonomy/term/120 (or other number - TID).
In Drupal 7 option to change TID to term:name was easy using Contextual filter and Filter value type set to Term name coverted to Term ID (shown eg here: Views contextual filters taxonomy name).
The big problem I'm struggling with is that there is no Filter value type field (dropdown menu) in Drupal 8. This is picture of my screen:

So I cannot change TID to term name.
Have anyone idea how I can exchange them. Is there another way to change them in Drupal 8?
Comment: Cant you use the term name itself as the filter? Without converting it to a term id first?
Comment: You are right, but if you have space in your taxonomy and you want convert this space into dash look this patch (#14). https://www.drupal.org/project/drupal/issues/2710407
Answer: You first have to create a relation with the taxonomy terms by adding the relationship with the taxonomy list or Taxonomy terms on node. Once you have added the relation, you can now add a contextual filter called name with the category Taxonomy term. This way you can pass the taxonomy term by name to the filter.
Answer: I have found that a relationship to taxonomy term: field will do just about the same thing as taxonomy term: on node


All MP3 media from an array is not playing properly: Android Studio

Question: I have created an activity, in which different mp3 sounds have to be played onFling a TextView. I created an array with all media required. Sometimes this plays all the media properly but most of the time it stop playing in between.
private int[] voice ={R.raw.media1,R.raw.media2,R.raw.media3,R.raw.media4,R.raw.media5,R.raw.media6,R.raw.media7,R.raw.media8};

media = MediaPlayer.create(BaseActivity.this, voice[num]);
media.start();

Answer: Updating here as I have got the solution. I was facing such issues as I was not releasing the recourses. After using below code, issue resolved:
private int[] voice ={R.raw.media1,R.raw.media2,R.raw.media3,R.raw.media4,R.raw.media5,R.raw.media6,R.raw.media7,R.raw.media8};

if(media!=null){
    media.stop();
    media.release();
    media=null;
}
media = MediaPlayer.create(BaseActivity.this, voice[num]);
media.start();


ListFragment RuntimeException 'android.R.id.list' missing

Question: Edit 1/16/2013: Problem Resolved!  Two days ago, I released an updated version of the app and correctly identified the ListViews as I had originally done, by using android:id="@android:id/list.  Really though, the exception being thrown was misleading and that had nothing to do with the actual problem...
The real fix came when I implemented the suggestions by Sean on inflating the ListFragment views by passing null to the ViewGroup.  I have not received the same Exception from the new version, and the new version has been downloaded by enough devices to safely say this issue is resolved.  However I really appreciate the comments and answer made by Lawrence, and will continue to read about how he is instantiating the Fragments.  While he provided the suggestion of passing null to the View inflater, Sean was actually the first to do so, and since his solution seems to have resolved the issue, the bounty will be awarded accordingly.  I will update this thread in the future if I learn/read more about the different ways of instantiating the Fragments as suggested by Lawrence's excellent answer.  Too bad I can't split the bounty!
Edit 1/14/2013: ListView related XML files are located at http://pastebin.com/2xnG1VfF per @LawrenceChoy's request
Edit 1/13/2013:  I released an updated version of my app and used android:id="@+id/android:list instead of android:id="@android:id/list" per Bishan's suggestion, however I am still receiving random exceptions that my Fragment Actvity does not have a ListView whose id attribute is 'android.R.id.list', even though that activity does not have any ListViews.  Added another exception from LGE phone.
Edit 1/9/2013: Although Bishan provided an answer, I was hoping for a little more explanation as to why his solution might prevent this exception.  After reading further I believe it is because when using a custom ListView, one should use a + symbol.  However would like to get confirmation I am correct or to get clarification, especially considering both seem to work on many different devices and emulators.  Raising a bounty in about 20 minutes to seek a reputable source/answer on the matter.  Thanks.

I'm getting some very odd behavior from a few devices out in the wild after a recent updated release to the play store.
In my new release I have a FragmentActivity (called TabsStyled) that uses a FragmentStatePagerAdapter to manage several fragments.  I have a total of 4 fragments, and 2 of those fragments extend ListFragment and have listviews populated by LoaderManager and CursorLoader, all from support.v4 libraries.  The other two fragments do not have ListViews and do not extend ListFragment.
I did extensive testing on multiple devices as well as AVDs and never encountered any RuntimeExceptions for missing android.R.id.list.
However, upon release, a few ACRA crashes showed up for the FragmentAcitivty "Your content must have a ListView whose id attribute is 'android.R.id.list'".  TabsStyled.class is the FragmentActivity that manages the ListFragments and itself does not have any `ListViews'.   This seems very strange to me, since I would think that if this exception were to be thrown, it should be for one of the ListFragments, and not the "parent" FragmentActivity.
Here's the top of the stack trace, and I'm happy to provide any additional code or info as requested rather than paste everything here.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.hiddenforsecurity/com.myapp.hiddenforsecurity.TabsStyled}:
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

A full stack trace available on pastebin here: http://pastebin.com/aiV7pwXP.
The XML for each of the ListFragments which contain the ListViews (a separate ListView in a separate XML for each ListFragment):
<ListView android:id="@android:id/list"

    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="45" />

One of the ListFragments (slightly simplified to make this easier to diagnose) uploaded to pastebin (the other ListFragment is very similar): http://pastebin.com/Nts3nVx1
And a slightly simplified full version of TabsStyled (FragmentActivity): http://pastebin.com/ZS4Xg8kP
The devices that created the exceptions thus far (and as of 1/14 they continue to post crashes):
MODEL       BRAND    ANDROID API
GT-I9305    Samsung  4.1.1 (using @android:id/list)
GT-S7562    Samsung  4.0.4 (using @android:id/list)
GalaxyNexus Samsung  4.2.1 (same exception seen with @+id/android:list)
L-01E       LGE      4.0.4 (same exception seen with @+id/android:list)

Comment: You can see from logcat that the activity is trying to create a `ListFragment` when the error happens. Can you post all layout files for those `ListFragment`? Also, the correct form of id should be `android:id="@android:id/list", Bishan's answer, as stated below, is incorrect.
Comment: Thanks @LawrenceChoy for your comment, I uploaded the layout files here: http://pastebin.com/2xnG1VfF.  Both ListFragments are almost identical.
Comment: Please see my answer below.
Comment: I always set View IDs to `@+id/id_name`. I think the [View page](http://developer.android.com/reference/android/view/View.html#attr_android:id) on Android developers site has a good explanation. Also, as the [**First app** tutorial](http://developer.android.com/training/basics/firstapp/building-ui.html) states _The plus sign (+) before the resource type is needed only when you're defining a resource ID for the first time._ I'm guessing that you are defining it for the first time?
Comment: @NiklasEkman, thanks for your comment.  For a ListView in a ListFragment, this is a very special case, and one must not use @+id when defining the ListView.  According to the documentation you are ONLY to use android:id="@android:id/list".  Anyhow, that really was/is not the source of the problem I'm having (the missing 'android.R.id.list' Exception being thrown is misleading), as the core problem looks to be related to references to the ViewGroup within each ListFragment and/or the way the Fragments are being instantiated.
Answer: Just a hunch, but try inflating your custom View for your ListFragment without using the ViewGroup. So in your ListFragment change
View logv = inflater.inflate(R.layout.listroot, container, false);

to
View logv = inflater.inflate(R.layout.listroot, null);

Comment: and change the android:id back to "@android:id/list". Bishan's answer is incorrect.
Comment: I fast tracked this into release and should know by tomorrow or the next day, since I'm seeing several of these exceptions each day.  Thanks again, hope this works.
Comment: This seems to have resolved the problem, I'm not seeing this crash anymore with the updated release and your suggestion implemented.  Now to award the bounty to you and try to learn about why this fixed the problem.
Answer: I have been unable to reproduce your problem with the code you provided, as I do not have any devices that you listed above. My first thought is that it may have something to do with the way you initialize the fragments. Please see my modified nFragmentAdapter class below. I have changed getItem() to initialize fragments in a different way:
nFragmentAdapter:
class nFragmentAdapter extends FragmentStatePagerAdapter {

        public nFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public Fragment getItem(int position) {

            Fragment f = null;
            Bundle args = new Bundle();
            args.putString("content", TabsStyled.CONTENT[position
                    % TabsStyled.CONTENT.length]);
            switch (position) {
            case 0:
                f = Fragment.instantiate(TabsStyled.this,
                        ReviewFragment.class.getName(), args);
                break;
            case 1:
                f = Fragment.instantiate(TabsStyled.this,
                        MyListFragment.class.getName(), args);
                break;
            case 2:
                f = Fragment.instantiate(TabsStyled.this,
                        SmartFragment.class.getName(), args);
                break;
            case 3:
                f = Fragment.instantiate(TabsStyled.this,
                        MyListFragment.class.getName(), args);
                break;
            case 4:
                f = Fragment.instantiate(TabsStyled.this,
                        f.getClass.getName(), args);
                break;
            case 5:
                f = Fragment.instantiate(TabsStyled.this,
                        f.getClass.getName(), args);
                break;
            case 6:
                f = Fragment.instantiate(TabsStyled.this,
                        f.getClass.getName(), args);
                break;
            }
            return f;
        }

        @Override
        public int getCount() {
            return TabsStyled.CONTENT.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TabsStyled.CONTENT[position % TabsStyled.CONTENT.length].toUpperCase();
        }
    }

And corressponding MyListFragment:
public class MyListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {

        myCursorAdapter mAdapter;
        String orderBy = DBAdapter.activityDateTime + " DESC";

        static final String[] activityQuery = new String[] { DBAdapter.activityRowID, DBAdapter.activityReason, DBAdapter.activityDateTime };

        String content;

    public void refreshView() {
        getLoaderManager().restartLoader(0, null, this);
    }

    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                Bundle args = getArguments();
                if(args != null)
                    content = args.getString("content");
                View logv = inflater.inflate(R.layout.listroot, null);
                return logv;
        }

        @Override
    public void onActivityCreated(Bundle savedInstanceState) {
                  super.onActivityCreated(savedInstanceState);
                mAdapter = new myCursorAdapter(getActivity(), null);
                setListAdapter(mAdapter);
                getLoaderManager().initLoader(0, null, this);
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
        }

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
                return new CursorLoader(getActivity().getApplicationContext(), myListProvider.activity_URI, activityQuery, null, null, orderBy);
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
                mAdapter.swapCursor(data);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
                mAdapter.swapCursor(null);
        }

    public class myCursorAdapter extends CursorAdapter {

        private final LayoutInflater mInflater;

        public myCursorAdapter(Context context, Cursor c) {
                super(context, c, 0);
                mInflater = LayoutInflater.from(context);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {

            TextView logleft = (TextView) view.findViewById(R.id.logleft);
                        logleft.setText(cursor.getString(cursor.getColumnIndex(DBAdapter.activityDateTime)));

            TextView logcenter = (TextView) view.findViewById(R.id.logcenter);
            logcenter.setText(cursor.getString(cursor.getColumnIndex(DBAdapter.activityReason)));

        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
                View view = null;
                view = mInflater.inflate(R.layout.vlist, parent, false);
            return view;
        }
    }

}

Please update on me if this changes anything.
Comment: Thank you, I do appreciate your answer and time.  I see the way you've changed from using the static constructor newInstance and moved to using instantiate (which I'm still reading about the differences).  Also I see how you've moved the bundle code around.  I also see you suggested the same thing as SeanPONeil on inflating the view, to use null for the container.  I currently have his suggestion in production and have not seen the exception thrown, but still need to give it a day or so.  Oh also, yes I also could not reproduce this issue on 4 different devices or emulators.
Answer: try this.
<ListView android:id="@+id/android:list"
    android:choiceMode="singleChoice"
    android:paddingTop="4dp"
    android:paddingBottom="4dp"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="45" />

i have replaced android:id="@android:id/list"  with android:id="@+id/android:list"
Comment: Well, it's not crashing on my test devices or emulators when I use your code.  However it wasn't crashing before when I was using id/list without the +.  Is there an explanation why + will not produce a crash but not using the + does?  I've read too many conflicting posts about this same issue, and I'm not sure which to use.  Thanks
Comment: read answer on this [quetion](http://stackoverflow.com/questions/5025910/difference-between-id-and-id-in-android)
Comment: Thanks, I did read through that one before and I suppose I'm just as confused as I was before.  Everything I've read says use @android:id/list, and considering both work on my test devices I'm not convinced this is the right answer.  Thanks again.
Comment: This was the comment that confused me the most!  "The '+' means to create the symbol if it doesn't already exist. You don't need it (and shouldn't use it) when referencing android: symbols, because those are already defined for you by the platform and you can't make your own in that namespace anyway."
Comment: Sorry, your answer did not resolve the problem.  I get the same exception even with android:id="@+id/android:list".
Comment: This is incorrect. See the developer docs for [ListFragment](http://developer.android.com/reference/android/app/ListFragment.html)
Answer: Don't use android:id="@+id/list" inside ListView  . Either You can create id by using one more option  i.e android:id="@id/android:list" or you can use android:id="@+id/list1".
Comment: Thanks for the answer, but this is basically just duplicating what has already been said and is also incorrect according to two others.  Also I never used "@+id/list".  I believe you are incorrect on the second part, "@+id/list1" nor @id/android:list should be used in my case.  Check out the docs here http://developer.android.com/reference/android/app/ListFragment.html posted as a comment by SeanPONeil on Bishan's answer.
Comment: i have mentioned above lines of code to create id in ListView . I haven't compared it with your lines of code. If you implemented according to my lines of code you will get the desired result..
Comment: Well thanks again for your answer and comment, but it doesn't make any sense related to the content of my question.
Answer: thanks for your posts. I was struggling a bit with this as I have just started with Android programming. Changing it to android:id="@android:id/list" did the trick for me.
Though I have just written a sample program which has only one ListView that I displayed inside the ListFramgment, but finally after reading this post I could make it work. Now I am gonna try & see if instead of displaying array of Strings, can I show some custom object (say comprising of a text & icon in one row) in a list.
Thanks much!


Please help me finding my voice type

Question: I understand you're probably bored with questions like this, but it's really important for me and I can't get a definite answer for years now.
I'm 26 years old.
The lowest note I can sing is E2, the highest I can hit (not sing, it's very thin) without the falsetto is C5-C#5. The falsetto ends at G5-A5
My voice gets strained (but doesn't slide into falsetto) around E4-F4.
My previous vocal teacher (whom I don't trust) defined me as a lyrical baritone.
My current vocal teacher says I'm a dramatic tenor and she thinks my (working) range is about 2 octaves, up to G#4, though recently during the warm-up we got to A#4.
What I just recorded to show you the range
Some additional songs to show you my timbre.
Thank you!
Comment: This may sound strange, but why is it so important? It sounds like it's early days yet, so things will change anyway, and even if there was an exact label, what difference would it make? I'm curious, as when I sing with others, if I can't reach one harmony, I'll find another. Alone, I'll find a key that fits.
Comment: Thank you for your reply! I didn't include that information because I didn't want to include too many details. It is important for me because I always tend to sing higher stuff, I find that those high notes (not extremely high, but up to around A4) express my feelings in the best way possible. It's harder for me to feel that I'm singing or performing when I do it in the lower register. But I don't want to waste my time at trying if that's not possible. I also don't want to harm my voice because I don't really imagine my life without singing.
Answer: There would be no way to answer this here.  For one thing, the two fachs are very similar.  My first thought is almost that the answer doesn't matter that much when you are in your early studies.  As you gain command of your voice, improve your vocal technique, and work with various repertoire, you will find that certain spots speak better, come out easier, etc.  There will come a time when your natural vocal strengths will be much more obvious, and you will know if you need to switch.
Also, the fachs are discreet in ways that real voices are not.  You could be naturally between the two, and may find that you develop into one role or the other through your training.
A word of warning: I am not, myself, a deep expert on the voice.  I work with vocalists professionally, however, and this answer reflects my experiences.  If an experienced operatic vocal teacher chimes in with different information, I would defer to their experience.
Comment: Thank you for sharing your thoughts. Didn't know it's possible to develop in one way or another, that one can do that with training. Many sources state that you only have what you were born with. If I only knew that I can become a low tenor in 5 years of hard training I would go for it.
Comment: I'm not suggesting that you can necessarily go in whatever direction you choose -- your voice should have some natural tendencies -- but there is a simple truth: there is an infinite continuum of the male voice, but only 19 male fachs.  This means that for most males, there must be at least *some* range of choice available.  Only time, effort, and learning will tell you whether what you're doing is really within that range.  But if, say, several years into your studies, you are still straining at the top, that's a big clue about whether you are headed in a reasonable direction.
Comment: One more thought to add: the stakes aren't as high as you might fear. If it turns out you are training in a slightly wrong fach, it's not as if the vocal instruction you got until that point is totally useless. Good breath support is good breath support, good posture is good posture, etc.  There may be a few habits to re-learn, but that time, effort and learning won't be lost just because everything isn't perfect at the very beginning of your studies.
Comment: Thanks a lot for your words of inspiration/

I don't even think that having a great range is very important or that having high notes is that important. It's just that if I sing in baritone range it's most of the not so convincing, perhaps because I don't have exactly right timbre for singing in baritone range. But when I try singing in more tenor range I face "range" problems. So you can see it's not your average insecure Joe. I just really want to find my way (no Frank Sinatra pun intended!)
Comment: Seems like with your help I'm finally becoming calm about this whole thing. I can't stop singing anyway.

Please help me finding my voice type


CDF from a probability function

Question: Hi I have this exercise where I must calculate the CDF and I wanted to see if what I have done is correct:
The exercise goes as follows:
Determine the distribution function F of the probability measure $P$ on $(\mathbb{R}, B(\mathbb{R}))$ with the
following density:
$f(x)=\left\{\begin{matrix}
&0 & x<m-5\\
&\frac{1}{25}(x-m+5) &  m-5 \leq x \leq m\\
&-\frac{1}{25}(x-m-5) & m\leq x \leq m+5\\
& 0 & m + 5 < x
\end{matrix}\right.$
Then, to calculate the CDF I simply calculated the respective integrals:
$F(x)=\left\{\begin{matrix}
& F_1(t) & x<m-5\\
& F_2(t) &  m-5 \leq x \leq m\\
&F_3(t) & m\leq x \leq m+5\\
& F_4(t) & m + 5 < x
\end{matrix}\right.$
I know that $F_1(x)=0$ and $F_4(x)=1$
$F_2(t)=\int_{m-5}^{t}\frac{1}{25}(x-m+5)dx=\dfrac{x\cdot\left(x-2m+10\right)}{50}$
$F_3(t)=\int_{m}^{t}\frac{-1}{25}(x-m-5)dx=\dfrac{x-m-5}{25}$
So at the end we have:
$F(x) =
\left\{\begin{matrix}
 &0  &   x<m-5\\
 & \dfrac{x\cdot\left(x-2m+10\right)}{50} &  m-5 \leq x \leq m \\
 &\dfrac{x-m-5}{25} & m\leq x \leq m+5\\
 & 1 & m + 5 < x
\end{matrix}\right.
$
Have I done any errors or is everything allright?
Comment: I haven't checked the calculus, but there is a conceptual mistake. By definition $F(x) = \int_{-\infty}^x f(t) dt$. Therefore, if a pdf is presented to you in different parts, it is not sufficient to only integrate each part separately. The new part should be added on top of what you had before. In this case, if $m \leq x \leq m+5$ you get $F(x) = F(m) + \int_m^x f(t) dt$.
Comment: Yes, indeed, because $t$ is your variable. Also, in the expression for $F_3(t)$, it should be $F_2(m)$ instead of $F_2(t)$.
Comment: Okay so the right answer is $F(x)=\left\{\begin{matrix}
& F_1(t)=0 & x<m-5\\
& F_2(t)=F_1(t)+\int_{m-5}^{t}\frac{1}{25}(x-m+5)dx=\dfrac{x\cdot\left(x-2m+10\right)}{50} &  m-5 m\leq x \leq m\\
&F_3(t)=F_2(t)+ \int_{m}^{t}\frac{1}{25}(x-m-5)dx& m\leq x \leq m+5\\
& F_4(t)=1 & m + 5 < x
\end{matrix}\right.$

Right?
Comment: $F(x)$ or $F(t)$ ? The condition $m-5\color{red}{m}\le x\le m$ looks wrong. $x(x-2m+10)/50$ is wrong as it is not zero for $x=m-5$.
Comment: Sorry I made a big mess with calculations. So:
$F(x) =
\left\{\begin{matrix}
 &0  &   x<m-5\\
 &F_2(t)=F_1(t)+\int_{m-5}^t\frac{1}{25}(x-m+5)dx=\dfrac{t^2+\left(10-2m\right)t+m^2-10m+25}{50} &  m-5 \leq x \leq m \\
 &F_3(t)=F_2(t)+\int_{m}^t\frac{1}{25}(x-m-5)dx & m\leq x \leq m+5\\
 & 1 & m + 5 < x
\end{matrix}\right.
$
Comment: and in the conditions I must write a t instead of x
Answer: Just extending a little bit the suggestion from @Rik93, using your notation and indicator functions:
$$F(x)=\mathbf{1}_{(m-5\le x \le m)}(x)F_2(x)+\mathbf{1}_{(m< x \le m+5)}(x)[F_2(m)+F_3(x)]+\mathbf{1}_{(m+5<x)}(x)$$

CDF from a probability function


Join two mysql queries

Question: I have 3 tables:
Table1
RouteID             int
departure_stop      int
destination_stop    int
Price               decimal(6,2)

Table2
StopID          int
Stop            varchar(50)
Cities_CityID   int

Table3
CityID      int
City        varchar(50)

I want to get all Routes which are cheaper than 50.
I want get departure city and destination city like this
City    City
Paris   London
Madrid  Zagred

So far I have dove two queries I am getting departure city and then second query for destination city, but don't know how join them side by side. Here are my queries:
SELECT
    Cities.City
FROM Routes, Stops, Cities
WHERE (Stops.StopID = Routes.departure_stop AND Stops.Cities_CityID = Cities.CityID AND Routes.price < '50')

And
SELECT
    Cities.City
FROM Routes, Stops, Cities
WHERE (Stops.StopID = Routes.destination_stop AND Stops.Cities_CityID = Cities.CityID AND Routes.price < '50')

So the question is how to join them together side by side so I could see departure and destination?
Answer: Select
    DepartureCity.City AS 'Departure City',
    DestinationCity.City AS 'Destination City'
FROM Routes
INNER JOIN Stops DepartureStop    ON DepartureStop.StopID   = Routes.departure_stop
INNER JOIN Stops DestinationStop  ON DestinationStop.StopID = Routes.destination_stop
INNER JOIN Cities DepartureCity   ON DepartureCity.CityID   = DepartureStop.Cities_CityID
INNER JOIN Cities DestinationCity ON DepartureCity.CityID   = DestinationStop.Cities_CityID

WHERE Routes.price < 50

Comment: Thank you it works! Looks complicated but I'll try to figure it out
Comment: It's not that complicated. Just start from the route, then join the end tables for the departure and destination and then join the cities to these two stops each. If you're happy, please accept the answer that suits you. Cheers

Join two mysql queries


integrate the following equation (what am I doing wrong here 2)

Question: Here is the equation:
$$\int 3x \sqrt{1-2x^2}dt$$
Here is my answer:
$$  \dfrac14 \int (1-2x^2)^{1/2} . 3x = -\dfrac14 \dfrac{(1-2x^2)^{3/2}}{3/2} = -\dfrac14 \cdot \dfrac23 (1-2x^2)^{3/2} + c$$
correct answer:
it should be -1/2 instead of -1/4 . 2/3 at the end. what am I doing wrong?
Comment: It should be $dx$, not $dt$.
Comment: You missed a factor of 3. Try to derivative your result and see where's missing.
Comment: It is not an equation.
Answer: let $$\sqrt{1-2x^2}=t$$ then $$-4xdx=dt$$ the integral becomes $$\int \frac{-3}{4}\sqrt{t}dt$$
$$= \frac{-3}{4}.\frac{2}{3}t^\frac{3}{2}$$
Answer: let us denote $s=1-2*x^2$,then $ds=-4*xdx$ ,because  you have $3$ in your equation,outside of integrat  will come  $-3/4$,so it would be
$$\int (-3/4)*\sqrt{s}ds$$
can you continue from this?
Comment: so it would be 12x....
Comment: no look please  ,i have updated
Comment: you are welcome, good lucks
Comment: @CashVai any question ?if yes you are welcome
Comment: thank you very much! I will, stay tuned :DD
Comment: i am happy that my reputation is increasing :D
Answer: Another way:
Denote $t^2 = 1-(\sqrt{2}x)^2$. Then you get $dx=-\frac{tdt}{\sqrt{2}x}$. So you get cancellations and the integral becomes
$$
-\frac{3}{\sqrt{2}} \int |t|tdt= -\frac{t^3 \ sign (t)}{\sqrt{2}}+C
$$
or just $-\frac{t^3}{\sqrt{2}}+C$ assuming $t>0$.


Transposing on a Yamaha PSR-180

Question: I'm new to the keyboard and music. Is it possible to transpose on the Yamaha PSR-180 so I can play Moonlight?
If it is, how do I do it?
Comment: Similar question: [Yamaha YPG: 235 : shifting octaves](https://music.stackexchange.com/questions/12507/yamaha-ypg-235-shifting-octaves)
Answer: Unfortunately it seems that no, this instrument won't allow you to do this. I checked the manual on the Yamaha site, but there's no mention of any transposition facility.
Of course there's nothing to stop you transposing it yourself as you play - in fact transposing 'in your head' is a very useful skill and this may be a good opportunity to learn how to do it!

Transposing on a Yamaha PSR-180


403 Forbidden when loading images from public/image folder laravel vuejs xampp

Question: In my profile the image is displayed perfectly  but I am getting the below error in the console. if i try to access the image from public folder it dose not show me the error but if I try to access it form image folder which is sub folder it shows me the error.anyone can help me with this problem since 4 days I am searching the solution but I did not find any solution yet it will be so kind of him.

Access forbidden! You don't have permission to access the requested
  directory. There is either no index document or the directory is
  read-protected.
If you think this is a server error, please contact the webmaster.
Error 403 admin-cms.me Apache/2.4.39 (Win64) OpenSSL/1.0.2s PHP/7.1.31

My API Code is :
Route::get('profile','API\UserController@profile');

My Controller Code is:
 public function profile()
    {
        //
        return auth('api')->user();
    }

My  Data and Methods  Code is:
  data() {
    return {
      users: {},
      form: new Form({
        id: "",
        name: "",
        email: "",
        password: "",
        type: "",
        bio: "",
        photo: ""
      })
    };
  },

methods: {
    getProfilePhoto() {
      return "image/" + this.form.photo;
    }

My HTML Code in profile.vue is:

Answer: Are you sure this.form.photo has a value at the time of getProfilePhoto() being called?
The error message:

There is either no index document or the directory is read-protected

Makes me think getProfilePhoto() is returning 'image/' + '' which results in the image directory attempting to be indexed.
One option would be to only show the profile photo if this.form.photo has a value, using v-if:

Comment: yes because on page load I am filling the form and as it is loading the picture is displayed but still getting the error
Comment: Mr.Brice can you tell me what should I do or how should I do it
Comment: I have edited my answer to show a possible way forward: hiding the profile photo until `this.form.photo` has a value.
Answer: Might be some issue with permissions, do you have access to your public directory, if you do can you check your permissions? ie:
ls -li public

now check if www-data or nginx have allow-read access permission to your image folder.
Comment: Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        11/6/2019  12:31 AM                css
d-----        11/6/2019  12:31 AM                fonts
d-----        11/6/2019   1:19 AM                images
d-r---        11/6/2019  10:16 AM                img
Comment: the main problem is when the image is in public/img it gives me the error if I take it out of the sub folder it wont give me the error
Comment: then the `img` folder isn't accessible, to make sure it can also be publicly accessed you can try and change it's permission:

`sudo chmod ugo+w public/img`
Comment: sudo : The term 'sudo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name,


How to calculate $max_{\alpha}Q(S',a')$ in q learning?

Question: This is the pseudo code I am using for my reinforcement learning programme.

and consider this is my reward  and action-value matrix (these are sample matrices)
<code>R= Reward matrix with row (1:4) as state and column as action(1:4)

[0,0,0,0]
[0,0,0,1]
[0,1,0,0]
[0,1,0,0]

Q= action-value matrix with row (1:4) as state and column as action(1:4)

[2,0,3,0]
[3,4,0,1]
[7,6,8,0]
[0,1,3,0]
</code>
where first row(1) is the starting state and last row(4) is the terminal state
if I take gamma as 0.9 and alpha as 0.1 then I can find action-value for Q(3,2) as
$Q(3,2) \leftarrow Q(3,2)+0.1 \times [R(3,2)+0.9\times \max_{0.1}Q(s',a')-Q(3,2)] \\ \\ \hspace{1.8cm} \leftarrow 6 + 0.1 \times [1+0.9\times \max_{0.1}Q(s',a')-6]$
How should I find $max_{0.1}Q(s',a')$?
Answer: There should be an "a", not an "alpha" in the subscript, like $max_{a'}{Q(s',a')}$, meaning that you are choosing the maximum value over all the actions for state $s'$. It's just the maximum entry from the corresponding row of $Q$.
Comment: That's right. The optimum strategy for this state was to pick the third action, so you adjust the expected value upwards. Note that $s'$ can be different from $s$, depending on which state your action leads you to.
Comment: @Eka NB what Don said about $s'$ being different from $s$: You take the max over the row corresponding to the state you wind up in, not the state you start in.
Comment: If I  understand you correct for Q(3,2) its the maximum value of  3th row, that is $max(7,6,8,0)=8$. then equation becomes $6+0.1*[1+0.9*8-6]=6,22$Am i right?


Trying to avoid a Force close after a bullet goes off screen

Question: So I'm just messing around learning to create a Space invaders type game. I can get the bad guys to move, Great!!. Hero moves, Great!! Bullets move, Great!! However I try to remove my bullets once they leave the screen as to not eat up all resources and it force closes on me once it gets rid of the bullet. It goes off the screen. Hits the int of -2 and then we use the remove() and boom. Force Close.
Here is my code. I'm wondering if they access the size() at the same time and just cause a force close because of it.
//I removed everything that doesn't pertane to the bullets.
public class GameScreen{
    Bullet bullet = world.bullet;

    public GameScreen(Game game) {
        super(game);
        world = new World();
    }

    //Draws our bullets.
    int bulletLength = bullet.bullets.size();
    for(int i = 0; i < bulletLength; i++) {
        Placement part = bullet.bullets.get(i);
        x = part.x * 32 + 11;
        y = part.y * 32;
        g.drawPixmap(Assets.bullet, x, y);
    }

Class that holds my bullets.
public class Bullet {
    public List<Placement> bullets = new ArrayList<Placement>();

    public Bullet() {

    }

    public void shoot(int x, int y){
        bullets.add(new Placement(x,y));
    }

    public void advance(){
    int len = bullets.size(); // gets all bullets.
    for(int i = 0; i < len; i++) {
        bullets.get(i).y --;

        if (bullets.get(i).y <= -2){//removes them once they are off the screen.
            bullets.remove(i);
        }
    }
}

This is what I use to keep track of placement.
package com.learning.planecomander;

public class Placement {
public int x, y;

public Placement(int x, int y) {
    this.x = x;
    this.y = y;
}
}

Comment: The question title is confusing. I'm assuming you don't want to close your application when a bullet goes off the screen.
Comment: 1) *"However I try to remove my bullets once they leave the screen as to not eat up all resources. Here is my code."*  Huh?  So ..what is the problem?  What did you expect to happen?  What **did** happen?  2) For better help sooner, post an [SSCCE](http://sscce.org/).
Answer: When going through your list to remove bullets, you can remove bullets from a list but that affects the list immediately instead of after your loop is done. Since you are traversing to the length of the list at the start, you are going off the end of the list since you've removed elements. An example is probably more helpful than that description.
Let's say you have a list with three bullets (which I'll call a, b, c to make the example easier). On a pass through the list, a and c are fine but b needs to be removed.
i = 0;
bullets[0] = a;
bullets[1] = b;
bullets[2] = c;
First loop goes fine, second loop starts like this
i = 1;
bullets[0] = a;
bullets[1] = b;
bullets[2] = c;
We remove b, but the loop keeps going
i = 2;
bullets[0] = a;
bullets[1] = c;
OH CRAP ARRAYINDEXOUTOFBOUNDS! PROGRAM CRASHES!
The way to solve this is to use a temp list to store the bullets that need to be removed, and then once your update loop is finished, make a call to bullets.removeAll(temp)
Comment: How would I go about making a temp list? Wouldn't moving the bullet to another list cause the same problem?
Comment: For your first question

`List temp = new ArrayList();
    for(int i = 0; i < len; i++) {
        bullets.get(i).y --;

        if (bullets.get(i).y <= -2){//removes them once they are off the screen.
            temp.add(bullets.get(i));
        }
    }
    bullets.removeAll(temp);
Comment: Wow, that's hard to read. basically, you don't have the same problem, because you are just adding the bullets to the second list, not moving them. So the bullets to be removed will be in two lists after the loop. Then the call to `removeAll` takes all the bullets out of the main list.
Answer: Doing two passes is a good answer. It makes the loops simpler and easy to understand. If you'd like to do it in one pass though, iterate through the list in reverse order, and when you remove a bullet you can go to the next one and not worry about blasting past the end of the ArrayList.
Alternatively, you can keep your bullets in a linked list, and run through the list with an Iterator, which you can also use to remove items from the list with. Removing from the beginning middle or end of an linked list is always a constant time operation. Whereas removing from the beginning of an ArrayList can be more expensive. If you need random access to the elements in the list, then they can be inefficient. Keep in mind though, if you're only dealing with a handful of objects, then it doesn't really matter.
For bonus points, you might want to put all of your objects in a list, and then have your central loop process them all and have your game objects respond polymorphically to calls like dead?, think, move, draw or whatever you think is appropriate.
Comment: Wow that went way over my head. I'm still pretty new to this so I'll have to look into putting all elements into one list and pushing that thought. Although collision detection sounds like it would be easier to push through.


xgb.importance in R some reference or articles?

Question: I would like to understand how the "Gain" column is calculated with xgb.importance function in R and if there exist some scientific articles about that with convergence results for example (working well with correlated features, non linear link, ...).
My objective is to compare this approach to the SHAP one or other estimation methods to interpreate features impact on output with xgboost models. In my context the output is a count poisson.
Answer: Not at all a complete answer, just a starter:
It calculates

the number of splits on feature j or
the gain in total loss from splits on feature j.  (You choose).

As such, the inverse link is simply part of the predict function used to find the total loss gain. Regarding correlated features: you will see their importance as used by the model (the model is never refitted without feature j). This can or cannot be what users are interested in.


Converting $\tanh^{-1}{x}$ to an expression involving the natural logarithm

Question: I know how to convert $\sinh^{-1}{x}$ and $\cosh^{-1}{x}$ to $\ln{|x+\sqrt{x^2 \pm 1}|}$, but for some reason I am struggling to do the same for the following statement:
$$\tanh^{-1}{\frac{x}{2}}$$
Can someone please show me how to convert it to a $\ln$ form? thanks!
Answer: Set $ y = \tanh^{-1} t $ and take $\tanh$ to take both sides so we have $$ \tanh y = t .$$
Now convert the $\tanh$ term into it's definition in terms of exponentials: $$ t = \frac{ e^{y} - e^{-y} }{e^y + e^{-y} } = \frac{ e^{2y} -1 }{e^{2y} +1 }.$$
Remember we want to solve for $y.$ Firstly solve for $u= e^{2y} $ first. Rearranging $ t= \frac{u-1}{u+1} $ is simple, and hopefully you can do the rest.
Answer: Why is people not answering?
Look, it's quite intuitive so I'll just show you the step by step:
$y=\tanh^{-1}x$
$\tanh y=x$
$\frac{e^{y}-e^{-y}}{e^{y}+e^{-y}}=x$
$e^{y}-e^{-y}=xe^{y}+xe^{-y}$
$e^{2y}-1=xe^{2y}+x$
$e^{2y}(1-x)=1+x$
$e^{2y}=\frac{1+x}{1-x}$
$y=\frac{1}{2}\ln(\frac{1+x}{1-x})$
Answer: $$\tanh x=\frac{e^{2x}-1}{e^{2x}+1} \Rightarrow \tanh \frac{x}{2}=\frac{e^{x}-1}{e^{x}+1} $$  In order to find $artanh\frac{x}{2}$ we have to solve following equation :
$$\frac{x}{2}= \frac {e^{2artanh \frac{x}{2}}-1}{e^{2artanh \frac{x}{2}}+1} \Rightarrow x \cdot e^{2artanh \frac{x}{2}}+x=2e^{2artanh \frac{x}{2}}-2 \Rightarrow$$
$$x+2=(2-x) \cdot e^{2artanh \frac{x}{2}} \Rightarrow e^{2artanh \frac{x}{2}}=\frac{2+x}{2-x} \Rightarrow artanh \frac{x}{2} =\frac{1}{2} \ln \left(\frac{2+x}{2-x}\right) ; |x| < 2$$


How to show output of xcopy in powershell script while it's running

Question: I have this powershell scrip where I want to copy files from our production server to our test server, and only have it copy files which are newer or changed.
The script itself has many more functions but this copying is one of those.
I'm using the following XCopy command for that:
  ... some other scriptingcode
  try {
      xCopy $source $destination /f /e /r /k /y /d
  }
  catch {
      Write-Host "issue: $PSItem" -ForegroundColor Yellow -BackgroundColor Red
  }
  ... some more other scriptingcode

When I run the XCopy command directly from the powershell prompt it shows it's progress, the files being copied, while it's running, but when I run it from the script itself, it doesn't output anything. And just adding -Verbose at the end just gives me a script error.
I've tried the following:
  $output = $(xCopy $source $destination /f /e /r /k /y /d) -join "`r\`n"
  Write-Host $output

But that only gives me the output after it's already been copied, and isn't a problem when no, 1 or 2 files are copied, but not really helpfull when you have a 100 or 1.000 files to copy. FYI, the -join "'r'n" is because the output is an array when more than one line is output, so I had to join the lines into one string which could be shown by Write-Host.
I have tried to google for a solution, but I guess my google skills aren't good enough to get me any results to this problem.
So, is there a way to have XCopy output while it's doing it, just like directly from the powershell commandline?
Comment: Normally `xcopy` shouldn't behave differently when called from the console or from a script. Do you redirect/pipe output of your script? In this case output might be delayed as many native executables buffer output when redirected.
Comment: As an aside: `try` / `catch` has no effect on calls to external programs such as `xcopy.exe`. Check `$LASTEXITCODE` for containing a nonzero value to infer failure.
Answer: You shouldn't see a problem with your script, because by default PowerShell passes stdout and stderr output from external programs such as xcopy.exe directly through to the host (console), without interfering with the output or its timing - irrespective of whether you execute the program interactively or from a script.
Similarly, if you send stdout (success) output through the pipeline , PowerShell streams it, i.e. sends each output line as it is being received (conceivably, a given program may itself buffer lines before emitting them when not printing to the console, but that doesn't seem to be the case for xcopy.exe).
The simplest way to print an external program's output to the console in streaming fashion while also capturing its output is to use the Tee-Object cmdlet:
# Prints the output to the console as it is being received
# while also capturing it in variable $output
xcopy $source $destination /f /e /r /k /y /d | Tee-Object -Variable output

Afterwards, $output contains the stdout output as an array of lines (or a single string, if there happened to be just one output line).
To also capture stderr output, append redirection 2>&1 to the external-program call; stderr lines are captured as System.Management.Automation.ErrorRecord instances, as if they were PowerShell errors; to convert all array elements to strings afterwards, use $output = [string[]] $output.
Character-encoding note: When PowerShell is involved in handling external program output (in the pipeline, capturing in a variable, saving to a file), the output is invariably decoded into  .NET strings first, based on the encoding stored in [Console]::OutputEncoding, which may situationally have to be modified to match the specific encoding used by a given external program - see this answer for more information.
If you want to perform transformations or apply additional formatting to the lines being received from the external program, consider Cpt.Whale's helpful solution based on  ForEach-Object.
Comment: I did not know `Tee-Object` lets you specify a variable, I thought it only split to files. TIL!
Comment: As an aside: The PowerShell ISE is [no longer actively developed](https://docs.microsoft.com/en-us/powershell/scripting/components/ise/introducing-the-windows-powershell-ise#support) and [there are reasons not to use it](https://stackoverflow.com/a/57134096/45375) (bottom section), notably not being able to run PowerShell (Core) 6+. The actively developed, cross-platform editor that offers the best PowerShell development experience is [Visual Studio Code](https://code.visualstudio.com/) with its [PowerShell extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell).
Comment: I tried the `Tee-Object` as provided, but it didn't show anything directly to the screen, only when I had a breakpoint right after it and I stopped the script when it hit the breakpoint. But if I remove the breakpoint, nothing is shown.
I do run the scripts directly from Windows PowerShell ISE (x86), so maybe there lies some problem with the not showing of the output directly.
Comment: Glad to hear it, @BendertheGreatest. Another option would be (though it doesn't offer much of an advantage, except in PS Core if you want to capture _stderr_ lines merged with `2>&1` directly as _strings_): `xcopy $source $destination /f /e /r /k /y /d | Out-String -Stream -OutVariable output`
Comment: @SuperDre, there must be something unusual about your setup - I don't see the issue, neither in the 32-bit nor in the 64-bit version of the ISE. As an aside: The ISE is obsolescent, and I suggest migrating to Visual Studio Code (see next comment). You can try to append `| Out-Host` to see if it helps in your situation, but I have no explanation for your symptom:  `xcopy $source $destination /f /e /r /k /y /d | Tee-Object -Variable output | Out-Host`
Comment: @mklement0 thanx for suggesting VSC, never occured to me to use it for this as I normally don't use VSC, still mostly use VS2019 or even VS6 (because if VB6).
Answer: For xcopy, you can both output to the host and capture the output with a foreach:
try {
  $output = xcopy $src $dst /f /e /r /k /y /d |
    Foreach {
      # write line to console
      $_ | Write-Host -ForegroundColor Yellow -BackgroundColor Red

      # add line to $output
      $_
    }
}

Note that xcopy is not a powershell command, so it's not able to do some things like use the default -verbose or -ErrorAction flags. It also does not throw terminating errors, so Try/Catch will not work unless you set your $ErrorActionPreference correctly.
Comment: Damn you this is a really clever use of ForEach-Object :D
Comment: One thing to watch out for is if this approach is used with PowerShell objects instead of strings/output from external commands; `Write-Host` will `ToString()` proper objects first whereas `Out-Host` does not. `Out-Host` may be desired if colored output isn't necessary, or else additional processing will need to be done to get a suitable output when non-string objects are in play.
Comment: Also, `ErrorAction` AFAIK *never* triggers on non-zero exit codes. You would have to check that yourself and either `throw`/`Write-Error` accordingly (in this case the try is meaningless as OP can just handle the failure case in the current scope).
Comment: As Bender says, that's really a cleaver way of fixing my problem. This is exactly what I needed, although at the moment Bender the Greatest is also an excellent solution as I don't need the output for further analysis. For now I'll use Bender's solution, but I'll keep your solution commented out at the same spot. The `Try/Catch` was something that was left over from my try with `Copy-Item`.
Comment: @BendertheGreatest :P - I only did a quick test with `xcopy`, but setting the error preference does let you run the catch block on an error. Or did you mean just the `-ErrorAction` flag? I think I could have picked a less confusing example, but it was only meant to help show `xcopy` isn't going to behave like a posh cmdlet.
Comment: I... have to raise an eyebrow on that one. At least with Windows PowerShell I've never had a script inherently throw an error when `$ErrorActionPreference = 'Stop'` is set and something exits with a non-zero exit code. In fact I had to address an issue with one of my setup scripts a few weeks ago surrounding this, where a command was not completing and its success was not checked. Unless this is something new in PS Core I haven't tried yet, and there is a mechanism for setting what the appropriate exit codes are I don't see this being a particularly useful feature if it does work this way now.
Comment: I just tried this in PS Core: `try{ ping w -n 1 } catch { 'i failed' }` the catch block did not run. I set `$ErrorActionPreference = 'Stop'` before running this. Note that the exit code of ping here is `-1`.
Answer: This is a side-effect of using the sub-expression operator $() here (note you would get the same effect using the group-expression operator () as well). The reason this happens is because $() and () function like parentheses in mathematics, and order of operations (technically order of precedence in computing) dictates that inner expressions be worked out before outer expressions. So anything inside the parentheses must complete first before it can be processed by the outer code.
In your case here, the "outer code" is what displays information to the console, hence, why the inner command has to complete before it gets displayed.

If you don't need to evaluate $output later on, the simplest and most performant approach is to pipe your command output directly to Out-Host instead (you probably also want to redirect error output as well):
# 2>&1 will redirect the error stream (external command STDERR gets written here)
# to the success stream (external command STDOUT gets written here)
# The success stream is what gets passed down the pipeline
xCopy $source $destination /f /e /r /k /y /d 2>&1 | Out-Host

However, if you need to assign $output to a variable at the same time for further processing, see @Cpt.Whale's solution involving the clever use of ForEach-Object. There are some edge caveats to their approach but does allow you to display the output and either stage the output in another variable for later processing or process the lines of output as they are read in. @mklement0's answer also shows how to use Tee-Object to simultaneously output to a variable and the success stream.
Comment: Most of the time you *don't* want to use `Out-Host` as there are certain implications of using it also. For starters, unlike `Write-Host` which writes to the *information stream*, `Out-Host` outputs directly to the console making any redirection impossible short of using `Start-Transcript` for logging. But in this case you should be fine.
Comment: thanx, the Out-Host is also an excellent solution as at the moment I don't need the output for later use. Both your and @Cpt.Whale's solution  would not have been something I would have thought about, and the `Out-Host` also never showed up in my google results, haha..


How to determine number of week of the month

Question: On the Linux CLI, is there a way to get the number of the week of the month? Maybe there is another way to get this with one simple (like date) command? Let's say that day 1 to 7 is the first week, day 8 to 14 is the second week, and so on.
Comment: For nothing I was reading man for date and that came to my mind (Sometimes I have so silly thoughts). So what will be a better definition ?
Comment: How do you define the week of the month? The day number divided by 7 and rounded down? Number of Sundays/Mondays/whatever which have passed?
Comment: lets say  from one to 7 day its 1rst week, from 7 to 14 second week, from 14 to 21 third and from 21 to end of the month its fourth week. I know that simple bash script with date nad if  is nice solution for this but im wondering if i can di that with one command without doing a script.
Comment: @B14D3 your "week of month" definition is pretty coarse -- what specifically are you using this for?
Answer: The date command can't do this internally, so you need some external arithmetic.
echo $((($(date +%-d)-1)/7+1))

Edit: Added a minus sign between the % and the d
Comment: Sorry I dont know how to format the comment to look nicer. Anyway, great idea to implement, however if the date is 08 or 09, it will
cause error: -bash: (09: value too great for base (error token is
"09").

Thats is because if numerical value starts with 0, it will be
intepreted as octal number by C language, so 08 09 are invalid.

For me, the workaround is to change from %d to %e, %e omits the
leading 0:

echo $((($(date +%e)-1)/7+1))
Comment: That's correct -- days 29+ are in the 5th week of the month.
Comment: Bash only does integer arithmetic.
Comment: That work fine, but I dont understand why this arithmetic returns integer ?
Comment: Wow didn't know that. Thx :D
Comment: I've checked your solution and it gives 5 for days >= 29 ... So it's not working the way  it supposed to.
Comment: If instead of **+%d** you use **+%-d** it will strip leading zero, making code work
Answer: You can use this:
Monday First week day
WEEKNUMBER=$(( 1 + $(date +%V) - $(date -d "$(date -d "-$(($(date +%d)-1)) days")" +%V) ))

Sunday Firs week daty
WEEKNUMBER=$(( 1 + $(date +%U) - $(date -d "$(date -d "-$(($(date +%d)-1)) days")" +%U) ))

Answer: Try this:
d=`date +%d` ; m=`date +%m` ; y=`date +%Y` ; cal $m $y | sed -n "3,$ p" | sed -n "/$d/{=;q;}"

Comment: doesn't look simple for me :D and for today it gives me 5
Answer: simplifying Victor Sanchez's solution:
expr 1 + $(date +%V) - $(date +%V -d $(date +%Y-%m-01))

replace %V with %U if you want weeks starting on Sunday.
btw: had to use expr instead of $((...)) because the later doesn't seem to like numbers with leading zeroes.
Answer: If you accept external tools in your quest, try dateutils.  It's got the notion of occurrence-within-month dates, i.e. 27 Apr 2012 is the 4th Fri in Apr 2012, which just coincides with your week definition.  To get that number use:
dconv 2012-04-27 -f %c
=>
  04

%c (count) is the format specifier for the occurrence-within the month.  Or to be even cooler try
dconv today -f '%cth %a in %b %Y'
=>
  1st Wed in Sep 2012


Convergence of a Complex Power Series at the radius of convergence

Question: I am currently reviewing some complex analysis, and have come across this question which I absolutely have no idea on how to attempt:
Suppose the radius of convergence of the power series $f(z) = \sum_{n = 0}^{\infty}a_nz^n$ is $1$, and $f$ has only finitely many singularities $z_1,\ldots,z_m$ on the unit circle $|z| = 1$ which are all simple poles. Show $\{a_n\}$ is bounded.
Obviously it suffices to show $\sum_{n = 0}^{\infty}a_n < \infty$. Since there are only finitely many singularities, we can find a $w_1$ with $|w_1| = 1$ such that $\sum_{n = 0}^{\infty}a_nw_1^n < \infty$...? But I have no intuition on how to proceed, since most of the theory I've read is for points interior to the circle of convergence.
Any suggestions appreciated!
Comment: "It suffices to show..." but you can't show that, it's too strong a statement. Consider $\sum z^n = 1/(1-z)$.
Answer: The thought process should probably begin with: let's look at some function with a simple pole on the unit circle, and with a  power series that I can find. This should remind of the example
$$\frac{1}{1-z} = \sum_{n=0}^\infty z^n$$
Here the coefficients are all equal to $1$, so they are bounded. More generally, we can place a simple pole at any point $a$ on the unit circle, and give it the residue of $b$, like this:
$$\frac{b}{z-a}=\frac{-\bar a b}{1-\bar az}  = -\bar a b \sum_{n=0}^\infty \bar a^n z^n$$
Again, the coefficients are bounded. And if we form a finite sum of such functions, the coefficients will be bounded still...
This sparks an idea (spoilered):

 Subtract such a sum from given $f$ to cancel out the poles. The resulting function will have a radius of convergence greater than $1$, hence its coefficients will tend to $0$.
Comment: Really nice solution, I was way off with my thoughts on this question!
Answer: Since $f$ has only finitely many singularities $z_1,……,z_m$ which are simple poles, then $f$ can be extended to some $B(0,R)(R>1)$ to become a meromorphic functions.
Without lost of generality we set the non-zero residue $Res(f,z_j)=c_j$, then $$g(z):=f(z)-\sum_{j=1}^m \frac{c_j}{z-z_j} \in H(B(0,R))$$
and set $$f(z)=\sum_{n=0}^{\infty}a_n z^n,z \in B(0,1)$$
$$g(z)=\sum_{n=0}^{\infty}b_n z^n, z\in B(0,R)$$
Notice that
$$
\frac{c_j}{z-z_j}=-\frac{c_j}{z_j} \frac{1}{1-\frac{z}{z_j}}
=-\frac{c_j}{z_j} \sum_{n=0}^{\infty}(\frac{z}{z_j})^n
$$
Hence
$$
\sum_{n=0}^{\infty}a_n z^n = \sum_{n=0}^{\infty}(b_n-\sum_{j=1}^m \frac{c_j}{z_j^{n+1}})z^n
$$
and $$a_n=b_n-\sum_{j=1}^m \frac{c_j}{z_j^{n+1}}=\sum_{j=1}^m \frac{b_nz_j ^{n+1}-mc_j}{mz_j^{n+1}}$$
Consequently $$|a_n| \le \sum_{j=1}^m \frac{|b_nz_j^{n+1}|+m|c_j|}{m} \to \sum_{j=1}^m |c_j|, n \to \infty$$.
Here $b_n z_j^{n+1} \to 0, n \to \infty$ because of the convergency of $$\sum_{n=0}^{\infty} b_n z_j^n$$
obviously ${a_n}$ is bounded.


How to validate .NET Framework 4.8 is installed on Windows Server 2016

Question: I installed .NET Framework 4.8 on a Windows Server 2016 using this link .NET 4.8 offline installer]1. And although everything seems to be going well, when I check the windows features it does not appear installed and 4.6 is displayed. Please, could you tell me what I do wrong?
<code>[X] Application Development                     Web-App-Dev                    Installed
        [X] .NET Extensibility 3.5                  Web-Net-Ext                    Installed
        [X] .NET Extensibility 4.6                  Web-Net-Ext45                  Installed
        [X] Application Initialization              Web-AppInit                    Installed
        [X] ASP                                     Web-ASP                        Installed
        [X] ASP.NET 3.5                             Web-Asp-Net                    Installed
        [X] ASP.NET 4.6
</code>
My guessing is that I should look for something like this:
Comment: Windows Features lists some versions of .net; but this is confusing; it's not showing all possible/all installed versions; only those versions which it can install (I believe those specific versions get bundled as Windows Features as they're required by many other Windows components).  To see what versions of .Net you have installed, you can use this handy program: http://www.asoft.be/prod_netver.html
Answer: Under what logic would you expect installing what is IIRC an in place upgrade (4.8) to change the name of a windows feature THAT INSTALLERS MAY RELY UPON?
It makes sense to not change that unless you introduce breaking changes - which 4.8 is designed not to do.
Comment: I have an application that we have migrated to 4.8. So, shouldn't I install 4.8 and has this appear in Windows Features? Currently is not working.
Comment: YOu should intall it - but you should not expect the windows feature to change the name. Use the registry to find out what versions of he. NET runtime are installed.
Comment: I added a picture for the thing I suppose I should looking for. What is your opinion about that?
Answer: If there is something not working, you should provide that instead of assuming that the Windows Feature dialog would change.
You may query the registry to determine the version of .NET Framework installed:
<code>reg query "HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" /v Release
</code>
If the value is 528040 (decimal) (0x80EA8 hex) or higher, .NET 4.8 is installed.
https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed


LocationManager not working on actuall device

Question: i have this problem. i am getting the location Updates. it is working fine on my emulator. but when i test it on my device it shows the current location fine. but when i change my position it do not show me updates in my location. but it is working fine on emulator.
here is my code
Main.java
<code>import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {

    TextView tvStatus;
    LocationManager lm;
    boolean gpsEnabled;
    LocationListener ls = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {}

        @Override
        public void onProviderEnabled(String provider) {}

        @Override
        public void onProviderDisabled(String provider) {}

        @Override
        public void onLocationChanged(Location location) {
            tvStatus.setText("Latitude: "
                    + location.getLatitude() + "\nLongitude: "
                    + location.getLongitude());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(this, "on create", 300).show();
        tvStatus = (TextView) findViewById(R.id.textView1);
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    }
    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this, "on resume", 200).show();
        if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            tvStatus.setText(l.getLatitude()+" "+ l.getLongitude());
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ls);
        }else{
            //use network provider
            Toast.makeText(this, "dsfdsfdsfdsf", 300).show();
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(this,"on pause" ,300).show();
        lm.removeUpdates(ls);
    }

}
</code>
i have added all the permisions in my manifest.xml
Comment: perhaps some logging is in order?...
Answer: first, make sure your gps is enabled and signal is locked/fixed on actual device. if the issue still persist then initial your locationlistener in OnCreate() rather than in class.
Comment: gps is enabled. because when my app starts it shows the current location which i got by `locationManager.getLastKnownLocation()` . when i change it do not show changes. And It Works Fine on Emulator
Answer: If you are inside a building my suggestion is not to use GPS_PROVIDER as gps doesn't work much  inside the building or takes large amount of time while taking the location fixes.


CentOS 8 server: /bin/ld: cannot find -lstdc++

Question: I get an error running make. I have never seen this error. There are no other errors except this one. I am seriously baffled.
Help is appreciated.
Comment: Please show full `ld` command line and error message.
Comment: The error message is in the title. What do you mean with ld command line? I am new to linux.
Comment: Then you need to involve a more experienced colleague.
Answer: So, I have been able to fix this. It was a missing line of code in CMakeLists.txt in the failing program. Had to put in "link_libraries_(stdc++fs)".


Fourier transform of two distinct signals

Question: I would like to generate some figures to show the disadvantages of using Fourier transforms for time series analysis. I aim to show that 2 apparently very distinct signals have a spectra with very similar shape. To begin I create my series:
t =  0:.01:2;
y = sin(2.*pi.*5.*t)+sin(2.*pi.*10.*t);
r1 = find(t <= 1);
r2 = find(t > 1);
y2a =  sin(2.*pi.*5.*t(r1));
y2b = sin(2.*pi.*10.*t(r2));
y2 = [y2a,y2b];

figure(1);
subplot(211);
plot(t,y,'k');
subplot(212);
plot(t,y2,'k');

Producing:

Now, I would like to show that their spectra have very similar shapes:

These are examples taken from some class notes that I would like to reproduce in matlab. However, I am having difficulties in reproducing the second plot. Could anyone suggest how the second plot can be produced in matlab with the information provided?
Comment: have you tried `doc fft` ? this will also give you more than a hint: http://stackoverflow.com/questions/10758315/understanding-matlab-fft-example
Comment: @Kate this is not the issue, but `t` should be from 0 to 4, according to your class notes, but you have defined it from 0 to 2.
Comment: Ok, so saying that I change it from 0 to 4, how would I reproduce the second plot?
Answer: Reproducing those plots is fairly easy. However, note several things:

In your class notes, the time domain plots are from t = 0 to t = 4 (not t = 2 like you did).
The frequency domain plots show only the positive frequencies, i.e. half the frequency spectrum. The frequency range is from 0 to 20Hz, meaning that the sampling frequency is 40Hz.
The amount of energy must remain the same, so if only half the spectrum is displayed, the plotted frequency components should be multiplied by a factor of 2.

That said, here's the complete code (including fixes to your time domain plots):
% # Time domain plots
fs = 40;
t = 0:(1 / fs):4;
y1 = sin(2 * pi * 5 * t)+ sin(2 * pi * 10 * t);
y2 = [sin(2 * pi * 5 * t(t <= 2)), sin(2 * pi * 10 * t(t > 2))];

figure
subplot(2, 1, 1), plot(t, y1)
subplot(2, 1, 2), plot(t, y2)

% # Frequency domain plots
Fy1 = abs(ifft(y1));
Fy2 = abs(ifft(y2));
N = numel(t);
idx = 1:numel(Fy1) / 2;    % # Indices of half the spectrum
f = fs * (0:(N - 1)) / N;  % # Actual frequencies

figure
subplot(2, 1, 1), plot(f(idx), 2 * Fy1(idx))
subplot(2, 1, 2), plot(f(idx), 2 * Fy2(idx))

The time domain plots are:

and the corresponding frequency domain plots are:
Comment: Great, thank you very much. I used the periodogram function to compute the power spectra but like you said the plots only show the positive frequencies, this caused some confusion.
Comment: @Kate Ah, I have found a mistake in my frequency plot: the plot shows only half the spectrum, hence everything (including the peaks) must be twice as high, in order to maintain the same amount of energy. Therefore, I've amended my answer by multiplying the plotted `Fy1` and `Fy2`.


Prove that $f_1, \ldots, f_n$ are vector Linearly Independent.

Question: Given $f_1, f_2,  \ldots, f_n \in C^{n-1}(\mathbb{R})$. Prove that if there is $v$ such that the matrix
$$
\left( \begin{array}{ccc}{f_{1}(v)} & {\ldots} & {f_{n}(v)} \\ {f_{1}^{\prime}(v)} & {\cdots} & {f_{n}^{\prime}(v)} \\ {\vdots} & {\ddots} & {\vdots} \\ {f_{1}^{(n-1)}(v)} & {\dots} & {f_{n}^{(n-1)}(v)}\end{array}\right)
$$
is invertible, then, $f_1, f_2, \ldots, f_n$ are linearly independent.
I can't do it.
Comment: Assume that $\sum_{k=1}^na_kf_k(x)$ is the zero function. Then rake derivatives of this equation, one, twice, ..., $n-1$ times to get $n$ equations. Plug in $x=v$. Solve for the coefficients $a_k$. Since that is the matrix of the system that you got, that means that the system has only the solution $a_1=...=a_n=0$.
Comment: Show the contrapositive. Suppose that $f_1, f_2,\dots,f_n$ are linearly dependent. Keep differentiating the equation expressing the linear dependence to find a linear dependence between columns of the above matrix. Since the columns are linearly dependent, the matrix can't be invertible. This matrix is called the Wronskian.
Comment: @JaneDoé thanks for the comments. I didn´t know about the name of matrix "the Wronskian". I will search about now.
Comment: @logarithm thanks too much
Answer: If $ \sum\limits_{k=1}^{n} c_kf_k=0$ then $ \sum\limits_{k=1}^{n} c_kf_k^{(j)}=0$ for $0 \leq j \leq n-1$. In particular $ \sum\limits_{k=1}^{n} c_kf_k^{(j)}(v)=0$ for $0 \leq j \leq n-1$. Since the matrix of this linear system is invertible we get $c_i=0$ for all $i$.


Check if Cantor's Theorem is applicable in the following examples. Also, find $\bigcap_{n\in\Bbb{N}} F_n$ in each case

Question: So we have to find whether Cantor's Theorem is applicable to the following
(i) $F_n = [n, \infty)$ (ii) $F_n = (0, \frac{1}{n})$ (iii) $F_n = [1 − \frac{1}{n} , 2 + \frac{1}{n}]$
Now I've tried doing these as

$F_n$ is non-empty and closed and $[n+1,\infty)\subset[n,\infty)$. But since $n\to\infty$, the length of $F_n$ does not tend to $0$. So not applicable
$F_n$ is an open interval so not applicable
$F_n$ is non-empty and closed. But as $n\to\infty$, $F_n\to [1,2]$ and length $[1,2]$ is not equal to $0$. So not applicable.

Is my method correct or am I doing something wrong??
Comment: Your answers are correct .
Comment: what do you mean by "applicable"?
Comment: @Lorenzo Do the conditions apply: i.e. are the $F_n$ closed non-empty and nested and do their diameters tend to $0$? We're working in $\Bbb R$ so that condition is OK.
Answer: Note that the exact statement of Cantor's Intersection Theorem is the following:

The intersection of any decreasing sequence of non-empty nested compact sets is non-empty.

Thus, as you correctly stated, it is not applicable in cases a) and b). However, it is clearly applicable in case c), since that sequence satisfies all of the assumptions of Cantor's Theorem.
Comment: No, Cantor's theorem states that if $(X,d)$ is complete and $(F_n)$ is a decreasing sequence of closed non-empty sets such that $\textrm{diam}(F_n) \to 0$ then $\bigcap_n F_n$ is a singleton.
Comment: @HennoBrandsma that is indeed a form of the Theorem in the case of complete metric spaces. However, you should be aware that what i wrote in my answer is the topological version of Cantor's Intersection Theorem. If you are not, I recommend you do some research first. Also OP did not mention in his statement which version of the Theorem he is interested in, so my answer is rather valid.
Comment: No, he checks diameters in his answer so he definitely means the above version in a metric space. Of course much more general versions of this exist. But the above is the "Urversion" by Cantor himself (which he used to show that $\Bbb R$ is uncountable (original proof)).
Comment: Cantor did not know the concept of compactness yet. He comes before that.
Comment: That does not mean that my answer is wrong or not valid. Anyhow, you do you, boo.
Comment: It doesn't apply as this is not the version the OP uses. He does not mention compactness either. It's also not a critique of his attempt.
Answer: The reason that a condition in i. fails, is to note that for all $n$, $\operatorname{diam}(F_n)=+\infty$ and it follows from that that $\lim_{n \to \infty} \operatorname{diam}(F_n) =+\infty$ in particular, so the diameters do not tend to $0$ as they should.
Another condition in ii. fails because $F_n$ is not closed (that it's an open interval is not relevant, as open does not always imply it's not closed). In both i. and ii. we have $\bigcap_n F_n = \emptyset$, so the conclusion fails too, showing the necessity of the diamater resp. closedness conditions.
For iii. again $\operatorname{diam}(F_n) = 1+\frac{2}{n} \to 1$, so it does not apply (limit not $0$). But indeed $\bigcap_n F_n = [1,2]$, as you claimed. So the conclusion fails too: the intersection is not a singleton.
You should be more precise in checking the conditions. That the conclusion of the theorem fails indicates that not all conditions of the theorem are fulfilled, but you're asked to say which condition exactly fails how...

Check if Cantor’s Theorem is applicable in the following examples. Also, find $\bigcap_{n\in\Bbb{N}} F_n$ in each case


Interaction in Hierarchical Regression

Question: I need some helps to interpret results of a hierarchical regression that included an interaction in the last stage.

Dependent Variable is Well-being.
Predictors are A-H, as well as the interaction of G and H.

Question

Is stage 3 only for the interaction analysis purpose? Which stage should be used to report significant predictor G and H, stage 2 (without interaction) or stage 3 (with interaction)?

2.The variable G changed negative (stage 2) to positive (stage 3), while the interaction effect is negative. Still, relation between G and DV. is positive over all?
Thank you.

Answer: Welcome to the site, StudentY. The key thing to remember with interactions is that in a model with two interacting variables, the "main effects" coefficients for those variables are their coefficient at the 0 value of the other variable.
So, in your stage 3 model, the coefficient of G is the change in the outcome for a 1 unit change in G at H==0. Likewise the coefficient of H is the change in the outcome for a 1 unit change in H at G==0.
The interaction is the degree to which the slope of G is altered for every unit increase in H. Or equivalently, the degree to which the slope of H is altered for every unit increase in G.
It is easiest to understand these by graphing them. If you are using R, this can be done with the ggeffects package:
library(ggeffects)
ggpredict(stage3, c("G", "H")) %>% plot()

In terms of your questions:

Is stage 3 only for the interaction analysis purpose? Which stage should be used to report significant predictor G and H, stage 2
  (without interaction) or stage 3 (with interaction)?

Yes, stage 3 is the model you want to use to understand your interaction and stage 2 is the model to understand the unique effects of predictors G and H.

The variable G changed negative (stage 2) to positive (stage 3), while the interaction effect is negative. Still, relation between G
  and DV. is positive over all?

The reason that variable G changed is because, as said above, in this model the coefficient on G is telling you about the association between G and the outcome at H==0. At H==0, the association is positive. But when you adjust for all levels of H in stage 2, the overall association between G and the outcome is negative.
By the way, when you report results from mixed models, you should report the variance estimates in addition to the coefficients.
Comment: Thank you so much for your detailed explanation. It is really helpful.After a slope test, only high in H can predict DV(well-being) while low and average H were not significant.
Comment: Thank you so much for your detailed explanation. It is really helpful. After a slope test, only "high in H" can predict DV(well-being) while low and average H were not significant. I can make an explicit statement only from one direction?
Comment: Thank you again, Erik Ruzek!I appreciate it so much!!
Comment: Yes, I'll do it definitely when I become eligible to vote after earning 15 reputation points!
Comment: I am not familiar with the slope test you mention, @StudentY, and cannot speak to that. From the stage 2 model, H has a significant association with the outcome, adjusting for all the other covariates. That's what I would feel comfortable reporting.
Comment: @StudentY, my pleasure! If you feel that my post answered your question satisfactorily, it would be great if you accepted it by clicking on the check mark next to my answer.

Interaction in Hierarchical Regression


This simple algebra question

Question: \begin{cases}
3x + y = \frac{12}{y^2}\\
3y + x = \frac{15}{x^2}
\end{cases}
$x+y = ?$
I tried adding side by side but I found only $4x+4y = \dfrac{15}{x^2} + \dfrac{12}{y^2}$ so I couldn't find anything. Can someone solve it?
Comment: If one edits a question, he should at least fix the tags and give a decent formatting: it does not take much effort. I can't edit it myself, but this should be tagged algebra-precalculus.
Comment: @bharb I'm sorry for missing the tag.  I've [suggested that](http://math.stackexchange.com/review/suggested-edits/567937).
Answer:
Multiply the first equation by $y^2$: $3xy^2+y^3 = 12$
Multiply the second equation by $x^2$: $3x^2y+x^3=15$
Add them up to get $3xy^2+y^3+3x^2y+x^3=(x+y)^3=27.$

Hence, $x+y=3$.
Comment: Nice and clean and you'll deserve an upvote for it but why do you ignore the two complex solutions $\frac{3^{\frac{3}{2}}i-3}{2}$ and $-\frac{3^{\frac{3}{2}}i+3}{2}$? Not in the syllabus at the time they teach pre-calculus?
Comment: @deamentiaemundi Most likely not.
Comment: @deamentiaemundi I'm sorry that I missed the complex roots.  When teachers teach quadratic equations (in one variable), they usually reject non-real roots.  Even in math competitions in high schools, from my experience, usually the variables are assumed to be real unless otherwise specified.  Therefore, I overlooked them carelessly.  IMHO, I think (correct me if I'm wrong) finding complex roots is within the scope of the (algebra-precalculus) tag.  By the way, it's me who changed the tag of this question to (algebra-precalculus).
Comment: @GNUSupporter I asked without any ulterior motive, I just wanted to know the reason behind your decision because I don't have much knowledge about the specific syllabi of the different jurisdictions (assuming USA in this specific case but the individual states differ, too, as far as I know), so: no reason for you to apologize.
Comment: @deamentiaemundi It's simple : I want to answer it as quick as possible, and I had never thought of complex roots.

This simple algebra question


When to convert an ordinal variable to a binary variable?

Question: I have seen some people convert their ordinal variable to a binary one, especially in the public opinion literature. For instance, when there is a four-scale question with responses including "Strongy agree," "Agree," "Disagree," and "Strongly disagree," some authors simply code "strongly agree" and "agree" as 1, the two other responses 0. Then they use a logistic regression model to analyze their data. I am not sure why they simply don't use their ordinal data with an ordered logistic model.
When do we need to convert our ordinal data to binary one?
Comment: There is a wide diversity of opinion about the real meaning of a Likert-5 scale from 1=Strongly opposed to 5=Strongly agree. // Once an exec from a car mfg told me that it was only the 5's that count as + because people who hate the car/ad/design often mark 3 or 4 for fear of giving offense. Don't know whether that says more about the exec or the customers. (Few really believe responses are never linked to respondents--unfortunately with good reason. Often used to help craft follow-up contacts.)
Answer: While I am not sure there is ever a time that one needs to convert ordinal data to binary, there are times when it may be more appropriate.
First, the authors may simply choose to opt for a simpler model.  That is to say, a logistic model is easier to run and analyze than is an ordinal model.  Also, fewer assumptions to be tested.  Following from this, it is also easier to explain the results of the logistic model compared to the trying to explain the results for an ordinal model.  Of course, one can argue that the better model to fit the data should be run...but I have had editors and reviewers ask me to scale back to an easier model to accommodate the general audience of the journal.  So, it is always good to keep the audience in mind.
Second, it may be a matter of cell sizes.  For example, if you have very few responses in one or more categories, it may make the model estimation difficult or unstable.  One work around is to collapse neighboring categories into a single category.  For example, if there are too few strongly-disagree responses, then combining the D + SD categories into one group may be beneficial for computational purposes.  Note, this is a strategy that is often employed in item response theory (IRT) for ordinal data.
Third, there may be a theoretical/conceptual motivation for collapsing the data.  For example, if you are working under the assumption that there are response styles present in the data (people responding to the response scale provided in different fashions), then you may argue that the only "true" distinction is between whether someone agrees (to any degree) or disagrees (to any degree).  Thus, the research question most likely focusses only on that comparison, and not degrees of difference in the comparison.
I hope this is helpful.
Comment: Discretizing data reduces power, and adds aggregation bias.
Comment: To clarify, my response indicates that we probably never need to do this, but I provide reasons why researchers may do this.  The OP did not ask questions about what happens when this is done.