Convert strings of varying pattern to date

Question: In our date column, there are so many different types of string. I am having trouble to convert all those to date type since patterns are not worked on DD-MM-YYYY and MM-DD-YYYY.

12/14/2015  MM/DD/YYYY;
19/07/2016    DD/MM/YYYY;
23.04.2016    DD.MM.YYYY;
1-6-2016     M-D-YYYY;
5-15-2016 M-DD-YYYY;
30-10-2016  DD-MM-YYYY;
8-6-2016  M-D-YYYY;

Or is there a more convenient way to do this?
Comment: you shouldn't have stored DATE values in a varchar column to begin with - then you wouldn't have that problem now
Answer: There is no way at all to do this.
8-6-2016 et al are irretrievably ambiguous without meta information. There is nothing to tell us which is month and day. If you have additional meta information available (did you save the pattern?), there might be a way out of this. Else, your case is lost.
Like a_horse commented: should have been data type date all along.


Warning: imagejpeg() [function:imagejpeg]: gd-jpeg: JPEG library reports unrecoverable error

Question: I have wordpress installation on my root folder,
until yesterday it was working fine, but today it gives following error for i guess generating thumbnail images,
Warning: imagejpeg() [function:imagejpeg]: gd-jpeg: JPEG library reports unrecoverable error: in public_html/wp-includes/media.php on line 459

do anyone have any idea regarding this warning??
Please help me
following code is on line 459
if ( !imagejpeg( $newimage, $destfilename, apply_filters( 'jpeg_quality', $jpeg_quality, 'image_resize' ) ) )

Comment: How are we supported to know what's on line 459?
Comment: Is GD enabled on your site/host?, try adding the following to your .htaccess file:

AddType x-mapp-php5 .php
AddHandler x-mapp-php5 .php
Comment: till yesterday it was working fine, i do have cpanel access, how do i check that GD is enabled or not?
Comment: just run  file and chech if GD library is enabled or not, if not change settings in php.ini or use ini_set() method..check this link for further info regarding GD http://assets.webassist.com/how-tos/gd_library_ht.pdf
Comment: i have referred you pdf link, and GD is enabled in my server
Comment: No free disk space, or over quota (for WHM/etc) is where we were getting the error from.
Answer: You probably tried to create an image from jpeg that is not jpeg.
I got the same error when I was testing a thumbnail script in PHP.
Then I found that the header of my input file was png although its extension was .jpg.
So, I edited my script so that if there is an error in creating an image from jpeg, it tries to create it from png (or gif if another error occurs).
Comment: Better to use `exif_imagetype` function instead of brute forcing
Comment: This is the real answer
Answer: 1) Check the space in disk
Your system must have enough disk space
2) Check the memory limit
Set more memory in your php:
ini_set("memory_limit","256M");

3) Check the post_max_size and upload_max_filesize
Set more in your htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M

4) put @ in front of the function
@imagejpeg(..............);

Point 1) worked for me.
Comment: Don't suppress warnings. They are there for a reason. Handle them!
Comment: @YeppThat'sMe `@` is to avoid warning messages
Comment: What does the @ in front of mean?!
Comment: If its a unrecoverable error and you are in a loop, it will break the loop. You got to handle the error.
Answer: You have to use a function to correctly determine mime type of image. A png image that have jpg extension will lead to this error.
To avoid this error, you have to get correct mime type of image.
function getImage($path) {
switch(mime_content_type($path)) {
  case 'image/png':
    $img = imagecreatefrompng($path);
    break;
  case 'image/gif':
    $img = imagecreatefromgif($path);
    break;
  case 'image/jpeg':
    $img = imagecreatefromjpeg($path);
    break;
  case 'image/bmp':
    $img = imagecreatefrombmp($path);
    break;
  default:
    $img = null;
  }
  return $img;
}

Answer: On PHP7 imagecreatefromjpeg started throwing fatal errors when you try to open an invalid file, which even the @ sign cannot catch.
Use the following instead:
$im = imagecreatefromstring(file_get_contents($filename));
if ($im !== false) { ... }

Answer: I have a Same error .But now i am solved the same issue.
Answer is :We  are uploading png and it converts to  jpg .
    Please check with jpg it works.And we need to convert png to jpg so other functions are available please check on same.
Below code will be useful to convert images using GD Library.
//variable declare or parameter use
$originalImage ="1.jpg";
$quality=100; // for jpg good quality
$outputImage;   //for source file save.

// jpg, png, gif or bmp?
    $exploded = explode('.',$originalImage);
    $ext = $exploded[count($exploded) - 1];

    if (preg_match('/jpg|jpeg/i',$ext))
        $imageTmp=imagecreatefromjpeg($originalImage);
    else if (preg_match('/png/i',$ext))
        $imageTmp=imagecreatefrompng($originalImage);
    else if (preg_match('/gif/i',$ext))
        $imageTmp=imagecreatefromgif($originalImage);
    else if (preg_match('/bmp/i',$ext))
        $imageTmp=imagecreatefrombmp($originalImage);
    else
        return 0;

    // quality is a value from 0 (worst) to 100 (best)
    imagejpeg($imageTmp, $outputImage, $quality);
    imagedestroy($imageTmp);

Comment: Nice work @shashik493 ..It helps me great..thank you so much


Must interacting dichotomous categorical predictors be treated as factors?

Question: If examining the main effects of dichotomous categorical variables, the levels of which are binary and absolute (present/absent), must they be treated as factors rather than numerics?
Would the answer change if also including in one's regression model the interactions between those variables? Notably, when factorized the number of interaction predictors double (in light of additional contrasts, yes?). What gets lost when relying on the numeric * numeric interaction terms in such a model rather than various factor * factor versions of such terms?
I presume factorizing the variables is good form, regardless. However, I'm having difficult wrapping my head around what's differently captured in the interactions of dichotomous numerics vs. dichotomous factors.
I presume the response is a matter of the math, not the software, but if relevant, I am examining the above scenario in R.
Clarification: Note, I understand the mechanical process of factorizing a categorical variable and, in theory when to do it. My question relates more to the math involved when dealing with interactions between such dichotomous categorical variables. In a model containing both main effects and interactions, a model that treats the dichotomous predictors as factors includes additional predictor terms compared to a model in which the predictors are treated as numerics (as the interaction is then represented by multiple factor-level interaction terms and no longer simply a single numeric * numeric interaction term). When comparing these two models, why would the main effect values for these dichotomous predictors change?
Answer: If you are going to use a numerical representation using 0 or 1 you do not need to factor the categorical variable. When the value of the categorical variable is 0 then you have created your reference group (because 0 x beta = 0) so the beta of the categorical variable when x= 1 will be interpreted as the effect of having a condition present compared to the reference group (not present) on average holding all else constant.
If you do not want to use 0 or 1 then yes you need to have your categorical variable set as a factor, and it helps to specify which factor is your reference factor. You can use the following code to specify your reference group for your factor variable.
dat$x = as.factor(dat$x)
dat$x = relevel(dat$x, ref = "not present")
Then the coefficient of the present group will be evaluated as the effect of having a condition present compared to not having the condition present on average holding all other covariates constant. Sorry not sure how to include $, between dat and x without it formatting to an equation.
Both would give you the same answer in terms of your estimate.
Now for interactions of a numericnumeric interaction and factorfactor interactions. When using categorical variables it is important to note that the reference group is swallowed up in the intercept term. Meaning that when the covariates are equal to zero and the disease is not present the expected value of the response variable would be the intercept term on average. So if you have two categorical variables then both reference groups are included in the intercept term.
You are not losing any information using a numeric or factor. Since they are doing the same thing. So let's say your other dichotomous categorical variable is whether or not an individual smokes. We then have the categorical interaction model below;
$
\hat{y} = \hat\beta_0 + \hat\beta_1(x_{present}) + \hat\beta_2(x_{smokes}) + \hat\beta_3(x_{present})(x_{smokes})$
Now the reference groups are excluded from the model since they are taken up in the intercept term. This is understood more easily in numerical form. "not present" = 0 and "no smoking" = 0.
$
\hat{y} = \hat\beta_0 + \hat\beta_1(0_{not present}) + \hat\beta_2(0_{no smoke}) + \hat\beta_3(0_{not present})(0_{no smoke})$
Since all coefficients except for the intercept terms are multiplied by 0,  the resulting model gives, $\hat{y} = \hat\beta_0$. The factor*factor model gives the same resulting model for the reference group.
Comment: I updated my comment, sorry I skimmed over the interaction part!
Comment: Thanks for response. Note, I understand the mechanical process of factorizing a categorical variable and, in theory *when* to do it. I suppose my question relates more to the math involved when dealing with interactions between such dichotomous categorical variables. I've edited the original post to elaborate/clarify.
Comment: Very helpful, thanks. However, I realize now my confusion stemmed from me examining three-way interactions between three dichotomous predictors. In that case, shifting from numerics to factors *does* appear to make a difference, as each three-way interaction is represented through two separate model terms for factors (one for each level of the first variable, with reference levels identical for variables 2 and 3). For instance, something like $(0_{notpresent})(0_{nosmoke})(0_{nodiet})$ and $(x_{present})(0_{nosmoke})(0_{nodiet})$.
 Might you be able to lend insight into why this is the case?


Is Pink Panther Theme ALL in Em key?

Question: referring to this question, it was determined that Pink Panther theme is actually in Em, but I was wondering if the key could be considered Em even when the theme varies (Consider this video from minute 0:42 onwards), because I tried to improvise some pentatonic Em scales on and it seems there's just something wrong...
Could someone explain me why this is happening?
Comment: Suggest you use this as an example, but ask specifically about the modulation, otherwise 'vtc looms!
Answer: Not sure whether this question will stand, as it's asking specifics about one song. However, it appears it's modulated into Gm. The redeeming factor may be your last sentence. It sounds like a smooth transition as Em to G is the relative minor to major, then it's morphed into the parallel key, as in from G major to G minor.

Is Pink Panther Theme ALL in Em key?


how to edit a record in php using jQuery popup

Question: I have the list of record i want to edit the record in popup when I click on the button of the record it is showing the 1st record in the popup not all the record i want to edit every record but it is not working
this is my php code
<?php

    error_reporting(0);
        $conn = mysql_connect('localhost', 'root', '') or die("Can't Connect With Local");
        $db = mysql_select_db('school') or die("Local DB Not Found");

        $s = mysql_query("Select * from student");

        while($sql = mysql_fetch_array($s))
        {
        echo'
'. $sql["id"]."".$sql["Name"]."".$sql["Subject"].'
';
        echo '<input ammad="'.$sql["id"].'" type="submit" class="abc" id="abc"/>';

        }

?>

this is the popup html

    ×

and this is the script of my popup

Comment: var_dump $sql and see what is the output
Comment: it is append the ids but the popup is not openning it is only opening when i am edit the first record
Comment: popup is not opening on the 2nd 3rd and fourth record
Answer: You are using two scripts over same element

btn.onclick = function() {
$("#abc").click(function(){
 but both are same element and actions are same. Better use either one.   Do not mixup basic javascript and jquery for simple stuffs. Use either one you are comfortable with.


Arquivo Proguard.cfg Android

Question: Como eu faço para "ofuscar" as minhas classes, métodos, variáveis e etc no arquivo de configuração do Android proguard.cfg? Meu intuito é de dificultar a descompilação (engenharia reversa) do projeto.
Comment: Olha, por default o `ProGuard` já faz a obfuscação de tudo. Em geral num projeto você tem um arquivo chamado `proguard-rules.txt` no Android Studio mas pode ser `proguard.cfg`. É muito comum se configurar métodos/classes que não devem ser obfuscados porque atrapalha no uso de `Reflection`, e isso é/deveria ser divulgado pelo criador de bibliotecas de terceiros. Dependendo de qual sistema de Build esta usando, seja Ant ou Gradle, há formas diferentes de configurar a execução dependendo do tipo do build (release ou debug).
Comment: Ahh, legal. Vlw pela informação. Acredito que o default seja suficiente então...
Answer: A engenharia reversa do seu código, quando configurado pelo Proguard em default, pode ser obtida seguindo esse simples tutorial:
http://ebortolin.wordpress.com/2011/05/19/engenharia-reversa-de-aplicativos-android/
Gaste um pouco mais de tempo configurando o seu Proguard corretamente para ofuscar ainda mais seu código. Um bom link que demonstra como configurar o seu Proguard corretamente segue abaixo:https://github.com/exmo/equizmo-android/wiki/Ofuscando-aplicativos-Android
Comment: Muito bom!!!!!!

Arquivo Proguard.cfg Android


$X\sim U[0,1]$, given $X=x$, $Y\sim U[0,x],$ what is $\rho(X,Y)?$

Question: I want to compute $$\rho(X,Y)=\frac{\text{Cov}[X,Y]}{\sqrt{\text{Var}[X]\text{Var}[Y]}}=\frac{E[XY]-E[X]E[Y]}{\sqrt{\text{Var}[X]\text{Var}[Y]}}.$$
I know that $E[X]=1/2$, $\text{Var}[X]=1/12$. To complete this problem I need to find $E[Y]$ and $E[XY]$. For $E[Y]$ the mean should be is $(0+x)/2=x/2$ but the book says $1/4$, why?
For $E[XY]$ I have that
$$E[XY]=\int_0^1\int_0^xxy\cdot f(x,y) \ dydx,$$
but how do I find the joint distribution $f(x,y)?$ Sure if they stated that $X$ and $Y$ are independent then I could use that $f_X(x)f_Y(x)=1\cdot 1/x=1/x$ but I can't assume independence.
Comment: The joint distribution is not needed for finding $\rho(X,Y)$, as is shown in the answer below. Use the conditional distribution itself to find the answer. You would also need $V(Y)$ which can be found similarly.
Answer: What you found was: $$\mathbb E[Y\mid X=x]=\frac12 x$$
That means that: $$\mathbb E[Y|X]=\frac12 X$$ and applying the general rule: $$\mathbb EY=\mathbb E[\mathbb E[Y|X]]$$ we then find that: $$\mathbb EY=\mathbb E\frac12X=\frac12\mathbb EX=\frac12\frac12=\frac14$$
Applying that same rule in this form:$$\mathbb E[XY]=\mathbb E[\mathbb E[XY\mid X]]$$and exploiting that: $$\mathbb E[XY\mid X]=X\mathbb E[Y|X]$$
we find: $$\mathbb E[XY]=\mathbb E[\mathbb E[XY\mid X]]=\mathbb E[X\mathbb E[Y\mid X]]=\mathbb E\frac12X^2=\frac12\mathbb EX^2=\frac12\frac13=\frac16$$
Comment: Perfect! Thanks a lot!


CREATE_PROCESS_DEBUG_EVENT for child process

Question: I have a simple debugger which i wrote, and i'm running it on a process which creates a child process.
The CREATE_PROCESS_DEBUG_EVENT is called only for the main process and not the child process (i'm opening this process with CreateProcess and DEBUG_PROCESS flag).
how can it be that CREATE_PROCESS_DEBUG_EVENT isn't called when child process starts?
Comment: When you say "this process" do you mean the main process or the child process?
Comment: I'm opening with CreateProcess the main process, which it creates a child process on it's own. Since in debugging the main process, I should see the CREATE_PROCESS_DEBUG_EVENT twice (one for the main process, and one for the child process it creates). But I only see a single event
Comment: Do you know how the child process is being created?  Have you double-checked (using Process Explorer, for example) whether the process that you're debugging really is the child's parent?
Answer: This page indicates that a CREATE_PROCESS_DEBUG_EVENT generates a callback with "a handle to the image file of the process being debugged, a handle to the process being debugged, and a handle to the initial thread of the process being debugged". It doesn't say anything about the child process. Whereas the page on CREATE_PROCESS_DEBUG_EVENT does mention child processes. The reason I point this out is that there might be some undocumented stuff you have to do to get this to work.
One suggestion is to see if Windbg properly handles the case you're having trouble with. If it does, then debug Windbg and set a breakpoint on WaitForDebugEvent. See if there is anything different in how Windbg calls WaitForDebugEvent vs your debugger.
Another issue that occurs to me is that your debugger does not have rights to the child process. Running the above mentioned test with Windbg should tell you if that's the case.


How do actions work in Liferay?

Question: I've looked for this question, but couldn't find it.
I don't know for you, but I don't understand a single bit of the Liferay Tutorial. It's too big and non-explanatory. This led me into a big misunderstanding on how Actions work in Liferay and a pair of troublesome tests.

Given this introduction, let's be quick: how do Liferay actions work?

I know we have ActionRequests and ActionResponses at methods, but how do I trigger an ActionRequest on these? Do I need renderURL tags for it? Can you give an example?
Now that after the previous question I should be able to call a method in my Portlet class controller... how do I send the info to the client? I guess it's using the ActionResponse, but how do I handle this?

Thank you!
edit:
I gave a try to the first answer, yet I tried something very similar before. It's not working, but I'm getting this error on the console; I don't really know if this might be a problem:

Load denied by X-Frame-Options:
  https://www.google.es/?gfe_rd=ssl&ei=8Sc8V5OkBYGFaLiHksgO does not
  permit cross-origin framing.
Comment: Are you trying to use Liferay even though you don't understand the tutorial? Isn't that kind of a bad premise?
Comment: Just test purposes! Nothing that will go to production, clearly.
Answer: in your my_action.jsp
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

Hello :  <%=request.getAttribute("user-test") %>

<portlet:defineObjects />
//The name here is used to call the process action method you define for your action
<portlet:actionURL name="myAction" var="myActionUrl"></portlet:actionURL>

<aui:form action="${myActionUrl}">
    <aui:input name="inputField"></aui:input>
    <aui:button-row>
        <aui:button type="cancel" />
        <aui:button type="submit" value="save" />
    </aui:button-row>
</aui:form>

and than in the portlet class
public class CustomMVCPortlet extends MVCPortlet {

    public void myAction(ActionRequest actionRequest,
            ActionResponse actionResponse) throws IOException,     PortletException, PortalException, SystemException{
       //get value inserted in form
        String userName = ParamUtil.get(actionRequest, "inputField", StringPool.BLANK);
       //her you send back your data to use in the jsp
        actionRequest.setAttribute("user-test", userName);
    }

Mapping from action to method is done using the name in the actionRequest.setAttribute nd the name of the method in the class that extends MVCPortlet and is defined using the tags <portlet-class>fully.qulified.name</portlet-class> in WEB-INF/portlet.xml  if no method is found a PortletException is thrown
Comment: Thank you! But it's not working, I just see a green message saying "Your request has been succesful"; the "user" variable never gets shown.
Comment: Sorry..my bad.Form must be done using aui-tags, this way the variable gets readed in the portlet class. Also changed variable user in case you have used `` this may cause to read the liferay user you are using
Comment: It's still not working... check this screenshot: http://i.imgur.com/QONtIKH.png . I used exactly your code, just importing the aui tag:  <%@ taglib prefix="aui" uri="http://alloy.liferay.com/tld/aui" %>
Comment: Try adding this `false` in your `liferay-portlet.xml`
Comment: Finally found put whats wrong...the `${user-test}` of EL somehow doesn't read the requestAttribute set in portlet, replaced it with `<%=request.getAttribute("user-test") %>` and now it looks fine...
Comment: Now it works! It was definitely what you wrote in your last comment. Thank you :) ! edit: You should edit your main answer so other people can see the actual resolution.

How do actions work in Liferay?


about constructing a database for student multi-step form

Question: I need to construct a database for students. I am wondering how to implement the database. Do I add the students data into the users table? Do I create a student's table, and when a new student is added add part of the data of the student into the users table and the other part into the students table?
Answer: The "users" table is for containing information about what the Drupal site sees as authenticated users, which means the users with a login in a Drupal site.
If you are adding information about users that don't need to login on the site, e.g. people working for an organization for which you keep information, then you should not use the "users" table. You should create your own table that contains the necessary dat; possibly, you should create a custom module that creates that database table when installed.
If you are adding users as authenticated users, and you need to store extra information about those users you can:

In Drupal 7, you can add extra fields to the user's account.
In Drupal 6, you can enabled the Profile module, which allows you to add extra fields for the user profiles.
In Drupal 6, and Drupal 7, you can create a module that handles that information.

Of the two solutions, on Drupal 7 it is better to use the fields provided by the field API; if you need to handle the fields in a specific way, you can implement a new type of field in a module.
If you need something more customized, such as a multi-step form to fill the information, then you could write your own custom module that creates its own database table, and uses the user ID as primary key. In this case, you would need to write more code, such as the one that deletes rows from the database table when a user has been deleted from the "users" table. In Drupal 6, that could would be in a hook_user('delete') implementation, while in Drupal 7, it would be in a hook_user_delete() implementation.
Comment: What is the best way to build a multistep form in drupal 7. I have used six and tried using the multistep module but I didn't feel that it worked very well. Is there a better way to achieve this in drupal 7. Or should I go down my orignal root and build a database scheme for a table to store student data. I should mentioned that I need multiple multi-step forms during the registration phase and that was the main reason I went with the form api and building the form in code rather then using the content management system of drupal.


For time series AR model given by (...) Show that equivalent representations are :(...)

Question: I'm supposed to show that for an AR model given by y(t) = a0 + a1*y(t-1)+ Et
we have equivalent representation in (y(t)-average(y)) = a1(y(t-1)-average(y))
where average(y) is the unconditional mean of the y(t) series
I have no idea how to even start? Up until now I've just been solving some normal time series with homogenous and particular solution.
Comment: You need to add the self-study tag.
Answer: Hi: calculate the unconditional ,mean an then plug that into your
 $y_t - average(y) = a1 y_{t-1} - average(y)$ formula. Then show that the equation you have is algebraically equivalent to the original AR(1) with intercept.  For calculating the unconditional mean, take the expectation of both sides of the AR(1) with intercept and then solve for the expected value of $Y_t$. (Use the fact that the expectation of $Y_t$ is constant for all $t$.)  The expected value of $Y_{t}$ is what is meant by the unconditional mean. I would get also get my hands on a  good intro time series book. There's a green one by Chatfield that's fairly recent and not bad. An older one that is often recommended is the Box-Jenkins-Reinsel text.  There's also a  another green one by Ledolter. Personally, I don't recommend Box-Jenkins-Reinsel as a useful text when starting out. There are better intro books. I just can't think of any recent ones besides Chatfield.


NCSFDictionary, Mutating method sent to immutable object

Question: I have just started to jump into the realm of Objective-C and am slowly getting it all. I have been working on unarchiving a file that was a NSMutableArray and then initializing in my model with that array. The array is filled with various NSMutableDicationary's. From what I have seen it will add those dictionaries as non-mutable, so I went ahead and copied the regular and put them in a mutable and remove the old one. This solution seems to work for every instance except the very first.
I am at a loss as to why it would work for all but the first.
Here is how I am initializing it all
-(id) initWithList:(NSMutableArray *)savedList
{
    self = [super init];
    if (self)
    {
        int size=0;
        serverList=[[NSMutableArray alloc] initWithArray:savedList copyItems:YES];
        size=[serverList count];
        for(int i=0;i<size;i++)
        {
            loginList=[NSMutableDictionary dictionaryWithDictionary:[serverList objectAtIndex:i]];
            [serverList addObject:loginList];
            [serverList removeObjectAtIndex:i];
        }
    }
    return self;
}

Here is the code that is throwing the error, The value is being read off of a checkbox in a tableview and passed here to change the value.
-(void)setMount:(int)row value:(NSNumber*)boolAsNumber
{
    [[serverList objectAtIndex:row] setObject:boolAsNumber forKey:@"mountshare"];
}

Here is the error that it shows when I try and change the first element
2010-12-01 13:38:54.445 Network Share[35992:a0f] *** -[NSCFDictionary setObject:forKey:]: mutating method sent to immutable object

Thanks for your help. If there is a better way please let me know.
Answer: This loop code is wrong:
    size=[serverList count];
    for(int i=0;i<size;i++)
    {

        loginList=[NSMutableDictionary dictionaryWithDictionary:[serverList objectAtIndex:i]];
        [serverList addObject:loginList];
        [serverList removeObjectAtIndex:i];
    }

When you remove an object, the array is renumbered. After you've processed the 1st object at index 0, the original 2nd object is becoming the 1st object at index 0, but i is now set to index 1, which is where the original 3rd object is! This means you're only processing alternate items from the original array, and the 2nd, 4th, etc items never get swapped, and that's why you get the errors you're seeing.
One way to solve this would be to replace the "i" in the objectAtIndex: and removeObjectAtIndex: calls with "0", so you're always taking items off the front of the array.
The alternate solution would be to create a separate newServerList array and insert your new objects into that. At the end of the loop, release the old serverList and set the variable to point to newServerList.
Comment: and i answered too.. using your answer.. :) http://stackoverflow.com/questions/6100271/nsinternalinconsistencyexception-with-nsuserdefaults-when-using-method-setvalue/13952939#13952939
Answer: Your indexes are messed up. As soon as you remove the object at index 0, the next one will take it's place and you will never replace that, because you then carry on with index 1.
{immutable0, immutable1}

i = 0:

addObject:
{immutable0, immutable1, mutable0}

removeObjectAtIndex:
{immutable1, mutable0}

i = 1:

addObject:
{immutable0, mutable0, mutable02}

removeObjectAtIndex:
{immutable0, mutable02}

--> still got the immutable there. Remember to never remove objects from a mutable array you are looping through at the same time.
You could condense the code a bit:
NSMutableArray *serverList = [NSMutableArray arrayWithCapacity:[savedList count]];
for (NSDictionary *dictionary in savedList)
{
  mutable = [dictionary mutableCopy];
  [serverList addObject:mutable];
  [mutable release];
}

Unrelated to your problem: the argument is obviously wrong (NSMutableArray), if you expect an immutable array there; and if you create your serverList that way, there is no need for a deep copy (copyItems:YES).


import cannot be resolved(Spring with java classes)

Question: I am trying to use java classes in web application based on Spring MVC framework
i try to use <%@ page import="class_j" %>,i tried also accessing using the package name.ClasseName class_j.GetAllFonctionand i googled too but in vain

Thank you in advance
Comment: please put your code and not a picture
Comment: the principle is to understand the issue ,and if you tried to answer me instead of this comment may be better ,anyway thank you
Comment: mmmm, ok ......
Comment: thank you for your understanding
Answer: Add language of the page for example
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>


I see we're getting trolled about economists being "always wrong"

Question: Based on this answer I have the  impression this is the same "fascism" troll that occasionally posts antisemitic remarks as well.
I dubbed them the "fascism" troll because one of their recurring themes was to ask on politics SE if fascism will succeed "in the end"... and many variations on that.
Economists being "always wrong" seems to be a new theme of them...
On Politics SE a measure was taken to prohibit unregistered users from posting. This ups the bar somewhat, but not a whole lot.
Answer: the user's account has been destroyed as after reviewing the account i felt that most of the content contributed by the user was not positive or beneficial for the site. Additionally, though its not an explicit rule on the site (Though its probably a mandate by stackexchange in general) any sort of racial remarks or hate speech will not be tolerated.
I would like to have such a policy in place as i think it would improve the quality of content received on the site.
Comment: It's in the [Code of Conduct](https://economics.stackexchange.com/conduct) under Unacceptable Behaviour.


jQuery Search entire div block for string

Question: I have a block of code with various tags but all within a set of div tags.  I need to be able to search everything within the div block to replace a string with another.  Here is the block.

cmh0.
<input type="text" id="thoughts-cmh0-thought" class="form-control" name="Thoughts[cmh0][thought]">
<button type="button" class="entAdd"> Add Above </button>
<button type="button" class="entDelete"> Delete </button>

What I'm trying to do is replace all of the 'cmh0' instances with another string.  I know I can do this one by one, but there is a very good chance the above block is going to change and change multiple times as time goes on.  Consequently, I'd like an elegant way to select and replace all of the 'cmh0' instances within the main div block.
How would I do this?
Thanks in advance.
Comment: Why don't you use a [templating library](http://garann.github.io/template-chooser/)?
Comment: This is the first I've heard of a templating library and I'm not quite sure how I would use it for this purpose.
Answer: You can do this with a quick select and replace:
var container = $('div[class*="cmh0"]').parent();
container.html(container.html().replace(/cmh0/g, 'someotherclass'));

the class*= reads as, "select any element where the class contanis"`.
Then just replace the html and reapply it.
jsFiddle
Comment: Thanks!  This gave me exactly what I needed to solve the problem.  Really appreciate it!


override html inline background-color with css hover

Question: I have a problem, I need to change a table background-color, I can only change the css. I want a hover on a table tr but some of the table td have an inline bg-color and I can't get a hover over it. !important doesn't work. Here is my problem.
CSS

table{
border: 1px solid black;
}

table tr:hover{
background-color: pink !important;
}
HTML

        test1
        test2

        test3
        test4

Answer: Adding rules for td fixed your problem
table tr:hover td

table{
border: 1px solid black;
}

table tr:hover,
table tr:hover td {
background-color: pink !important;
}

        test1
        test2

        test3
        test4

Answer: Your style is Incorrect, In the CSS you try to change the tr background, not the td.
Replace the css by this and it works fine if you want change all the hover line in pink :
table tr:hover td{
    background-color: pink !important;
}

Replace the css by this and it works fine if you want change the hover td in pink :
table td:hover{
    background-color: pink !important;
}

Comment: I want the hole tr line change bg-color when you hover, not only the td


Erro ao instalar plugin OneSignal na plataforma iOS usando IONIC FRAMEWORK

Question: Estou desenvolvendo um app usando ionic framework, porém ao adicionar o plugin do OneSignal na plataforma iOS estou tendo alguns erros:

"Failed to install 'onesignal-cordova-plugin': undefined (node:3302)
  UnhandledPromiseRejectionWarning: Unhandled promise rejection
  (rejection id: 1): Version should contain only numbers and dots"

Já efetuei alguns comandos como:
sudo gem install cocoapods
prod repo update

Mas não obtive êxito.
Alguém teria alguma dica do que devo fazer para poder instalar o OneSignal?
Answer: Testa fazer esses procedimentos
cordova platform remove ios
cordova platform remove onesignal-cordova-plugin
sudo gem install cocoapods
pod repo update
pod setup (caso precise sincronizar o repositório CocoaPods)
cordova plugin add onesignal-cordova-plugin --save
cordova platform add ios


security updates reported but not actually available (recommended==installed)

Question: I installed Drupal 9.3.6.
At /admin/reports/status, I see the error:

There are security updates available for one or more of your modules or themes

and at /admin/modules/update, two modules are listed: PHP 8.x-1.1 and Remote Stream Wrapper 8.x-1.5.
However, for both these modules the recommended version is the already-installed version.

How do I see more details about the reason for the errors?
Alternatively, can I make Drupal ignore these two modules?
Answer: There are security updates available for one or more of your modules or themes isn't the more appropriate message that is correct in every case. It assumes that, once a release has been marked as insecure, a new release is created, but that doesn't always happen, for example because the project owner or one of the maintainers failed to fix the security issue.
In the specific case:

All the releases for the PHP module has been marked insecure; this means you cannot install a release that isn't marked insecure
The 8.x-1.5 release for the Remote Stream Wrapper module has been marked insecure; there aren't more recent releases and the project has been marked unsupported

Implementing hook_update_status_alter() in a module, you can set those modules as ignored.
use Drupal\update\UpdateFetcherInterface;

function mymodule_update_status_alter(&$projects) {
  if (isset($projects['php'])) {
    $projects['php']['status'] = UpdateFetcherInterface::UNKNOWN;
    $projects['php']['reason'] = t('MyModule prevents Drupal from receiving information about module updates .');
  }
  if (isset($projects['remote_stream_wrapper'])) {
    $projects['remote_stream_wrapper']['status'] = UpdateFetcherInterface::UNKNOWN;
    $projects['php']['reason'] = t('MyModule prevents Drupal from receiving information about module updates .');
  }
}

Comment: Thanks. This code seems to prevent the permanent error being shown while not hiding that the modules are problematic.
Answer: Sometimes Drupal messages regarding module updates can be outdated and can be fixed by manual check for updates from the /admin/reports/updates page:
Also, some error messages can be shown because of the "Remote Stream Wrapper" module's status:

To avoid receiving such messages you can:

Uninstall the Update MAnager module.
Try to use the hook_update_projects_alter


What is the difference between path and theme path in theme registry?

Question: I'm trying to alter the theme registry:
function comment_simplify_theme_registry_alter(&$theme_registry) {
  $module_path = drupal_get_path('module', 'comment_simplify') . '/tpl';
  $theme_registry['comment']['template'] = $module_path . '/comment';
  $theme_registry['comment']['theme path'] = $module_path;
  $theme_registry['comment_wrapper']['template'] = $module_path . '/comment-wrapper';
  $theme_registry['comment_wrapper']['theme path'] = $module_path;
}

Now this is what I have in theme registry:
comment_wrapper
  template: sites/all/modules/comment_simplify/tpl/comment-...
  path: themes/bartik/templates
  type: theme_engine
  theme path: sites/all/modules/comment_simplify/tpl
  render element: content

I want to know what the difference between path and theme path is.
Answer: From the hook_theme() docs:

path: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.
theme path: (automatically derived) The directory path of the theme or module, so that it doesn't need to be looked up.
Comment: So if I want to override default comment module's tpls its enough to define `template` and `path` instead `theme path`?
Comment: I think you'll need to set `theme path` as well if you're re-implementing a template file from another module (so the theme registry knows to look in your module path, not the comment module which originally implemented the hook).


Prove that $L^1$ is a Banach algebra with multiplication defined by convolution

Question: To be more specific, prove that $L^1(\mathbb{R}^n)$ with multiplication defined by convolution:
$$
(f\cdot g)(x)=\int_\mathbb{R^n}f(x-y)g(y)dy
$$
is a Banach algebra. All the properties of Banach algebra are easily proved except the last one:
$$
\|f\cdot g\|\le \|f\|\|g\|.
$$
Could anyone give me a hint?
Actually I found a proof on the web, but I don't see why the last equality holds.
$$\|f* g\|_1  = \int |f*g(x)|dx \le \iint |f(x-y) g(y)|dydx = \|f\|_1 \|g\|_1$$
Comment: What about Fubini?
Comment: I edited my question. Now I found a proof on the web, but I don't see why the last equality holds.
Comment: This is a special case of Young's inequality for convolutions by the way, with $p = q = r = 1$.
Answer: \begin{align}
\iint |f(x-y)g(y)|\;dx\;dy &=
\int\left[\int|f(x-y)|\;dx\right]|g(y)|\;dy \\
&= \int\left[\int|f(x)|\;dx\right]|g(y)|\;dy \\
&= \left[\int|f(x)|\;dx\right]\;\left[\int |g(y)| \;dy\right]\\
& = \|f\|_1\;\|g\|_1
\end{align}
Comment: I can see that by variable substitution $\int |f(x-y)|dx$ reduces to $\int |f(x)|dx$. But why isn't $\int |f(x-y)|dx$ a function of $y$? I am confused.
Comment: It is. But you can just shift it since you integrate over all of $\mathbb R$.
Comment: But I remember in the calculation of conditional density, by integrating over one variable $\int_{\mathbb{R}} f(x,y)dy=f_X(x)$ is a function of $x$. What is the difference here?
Comment: Yes, $\int |f(x-y)|dx$ is a function of $y$.  But a calculation shows it is a constant function.
Comment: I managed to get the conclusion that $\int |f(x-y)|dx$ is a constant by using the substitution $t=x-y$. Is there a more enlightening way of doing this? Moreover, I can also conclude that $\int |f(x-y)|dx=\int |f(x-y)|dy$, right?
Comment: "More enlightening" way: the Lebesgue integral is translation invariant.


R multiple regression output

Question: I realize that this may be answered somewhere but I cannot find it, either on Cross Validated or with Google.  I can find numerous examples of how to use multiple regression with R, and I have done that.  Then I used summary to view the output, like so:
fit <- lm(target_output ~ weekday + day + month + year + max_temp + min_temp + precip + tmax_trailing_7 + tmax_trailing_30 + factor(notes) + weekday:day + day:month + factor(notes):day + factor(notes):weekday, data=data)
summary(fit)

The "summary" works fine for a small model, but given the large number of factors I have, I am looking for an example on how to, well, summarize the summary.  In particular, I would like a list of all of the factors and interactions which are marked with "Signif codes" of 2 or 3 stars.
Ideally, I would also like the output to be something which I can then manipulate in the script.  For example, to dump the factors which are not significant at the "2 asterisk" level, and run the regression again.
If I am just missing the awesome R mulreg tutorial which shows how to do this, I apologize, but if you could point me at it that would be awesome, because I am having trouble finding it.  The tutorial examples I can find all have small numbers of input variables, and don't seem to cover pruning out the ones that are less significant.  Thanks for your time.
Comment: This is not multivariate regression (which, by definition, involves more than one response per observation): it is *multiple* regression.
Comment: @whuber Agreed, but I have seen multivariate syllabi that consider multiple regression to be multivariate
Comment: I will keep the distinction between multivariate and multiple regression in mind in the future.  I normally have just read/said "mulreg", and now I wonder if that was intentionally vague in order to avoid having to remember which is which. : )
Answer: I will show you how to do what you want to do but also give some reasons for why you may or may not want to do what you're interested in in the way that you describe.

I would like a list of all of the factors and interactions which are marked with "Signif codes" of 2 or 3 stars.

You can do this by turning your summary coefficients table into a matrix and then sorting out any rows where the p-values are less than some value, say .05. Here's an example. First, I'll generate data:
set.seed(1839)
# create four independent variables
x1 <- rnorm(100)
x2 <- rnorm(100)
x3 <- rnorm(100)
x4 <- rnorm(100)
# make y predicted by only two of them, plus some error
y <- x1 + x2 + rnorm(100)

Then you can extract the coefficients table as a matrix. Note that the fourth column are the p-values, so you can just ask for rows where p-values are less than .05:
model <- lm(y ~ x1 * x2 * x3 * x4)
coefficients <- round(summary(model)$coef, 4)
coefficients[coefficients[, 4] < .05, ]

Which returns:
   Estimate Std. Error t value Pr(>|t|)
x1   0.8575     0.1145  7.4900   0.0000
x2   0.9755     0.1162  8.3929   0.0000
x4   0.3679     0.1199  3.0671   0.0029

The three significant coefficients out of all the main effects, two-way, three-way, and four-way interactions I specified.
The resulting coefficients table brings out an issue with doing this: Type I error. Even though I coded it so that x4 was not related to y, the results still tell me that it does. When you are doing tons of tests, you're going to get some that are significant just by chance, so you might consider lowering your alpha level. But that type of indexing by row is how you could get that table.

For example, to dump the factors which are not significant at the "2 asterisk" level, and run the regression again.

One could code this by taking the rownames of the output above, then pasting all of them together using paste(rownames(output_above), "+"), then pasting that after "y ~ ", saving as.formula, then putting it back into an lm object...
HOWEVER, what you are doing is variable-selection, and this choosing based off of an arbitrary threshold is generally not suggested. Instead, you could look at the literature on variable selection or regularization. In particular, there is a thing called a LASSO, which adds a penalty term to your regression that will have the effect of eliminating variables that are not very informative. There are many good tutorials on this using R. A classic book you can use is Introduction to Statistical Learning with Applications in R, which can be accessed on the authors' website here. In particular, you should look at Section 6.2, especially 6.2.2, which will give you the effect that you are looking for. There are also exercises showing you how to implement the LASSO regression in R in Section 6.8.
Comment: Excellent, both the "here is how you could do that" part and the "here's where you read on what you should do instead" part.  I will read up on chapter 6 in the reference you cite.

R multiple regression output


problems with cross validation code - r -

Question: I'm writing a function to perform logistic regression on two columns of a dataframe. I can't get around the errors... I am trying to use 10-fold cross validation. Here's the code I'm using:
SAdata = read.table("http://statweb.stanford.edu/~tibs/ElemStatLearn/datasets/SAheart.data",
                     sep=",",head=T,row.names=1)

log.fun = function(x,y) {

    prediction = data.frame()
    tset = data.frame()
    dframe = cbind(x,y)
    dframe = as.data.frame(dframe)
    dframe$fold = sample(1:10, nrow(data), replace = TRUE)
    list = 1:10

    for (i in 1:10) {

        train = subset(dframe, fold %in% list[-i])
        test = subset(dframe, fold %in% c(i))
        model = glm(x~y, data=train, family=binomial)
        pred = as.data.frame(predict(model, test[,-1]))
        prediction <- rbind(prediction, pred)

    }
}

log.fun(SAdata$chd,SAdata$obesity)

The error I get is "Error in sample.int(length(x), size, replace, prob) :
  invalid 'size' argument"
Any ideas?
Comment: From the error, i'd guess the problem is in the `dframe$fold = sample(1:10, nrow(data), replace = TRUE)` line. You don't have `data` defined anywhere. What did you expect that to do?
Comment: Thank you. I fiddled with the code... that should be dframe instead of data.
Answer: This is kinda sub-optimal use of for loops and specially modelling... if you want to try some good models developing try the package 'caret'
If you still want to use that function here is a workaround
SAdata = read.table("http://statweb.stanford.edu/~tibs/ElemStatLearn/datasets/SAheart.data",sep=",",head=T,row.names=1)

log.fun=function(x,y){

  prediction = data.frame()
  tset=data.frame()
  dframe=cbind(x,y)
  dframe=as.data.frame(dframe)
  dframe$fold = sample(1:10, nrow(dframe), replace = TRUE)
  list = 1:10

  results <- list()
  for (i in 1:10) {

    results[[paste0('Fold',i)]]$train <- subset(dframe, fold %in% list[-i])
    results[[paste0('Fold',i)]]$test <- subset(dframe, fold %in% c(i))
    results[[paste0('Fold',i)]]$model <- glm(x~y, data=results[[i]]$train, family=binomial)
    results[[paste0('Fold',i)]]$pred <- as.data.frame(predict(results[[i]]$model, results[[i]]$test[,-1]))
    results[[paste0('Fold',i)]]$prediction <- rbind(prediction, results[[i]]$pred)

}
results}

your_results<-log.fun(SAdata$chd,SAdata$obesity)

head(your_results$Fold1$prediction)

In fact you had some problems in the function 'sample' since you were specifying 'data' and that object did not exist ... I replace it for dframe and added some names to each part of your results.
Hope it helps


Using video module with ffmpeg to convert; how do I display converted files?

Question: All uploaded videos on our Drupal 7 site need to be in a standard web format: MP4-H.264/AAC to assure play back by all user devices.
ffmpeg is working correctly. Video upload field stores all uploaded files into sites/default/files/videos/originals.
ffmpeg saves converted files into sites/default/files/videos/converted/nnnn which is a directory containing the converted file, and nnnn is a number unique for each file.
On the web page, the original uploaded file is displayed. How can I switch to the converted ("transcoded") file?
Video module supports Rules integration. Is that a good solution?
Production and QA sites are hosted on AWS.
Comment: Rules has 2 events for transcoding:  video_success, and video_failed.
Answer: Solved this by modifying the custom module. Test if file has been converted, by looking in sites/default/files/videos/converted/nnnn, where nnnn is the File ID of the original file. If not then display the original video file. If conversion completed successfully, then display the converted file from sites/default/files/videos/converted/nnnn. There is only one file in the nnnn directory.


Which hypothesis test should I use?

Question: I'm doing a personal project and would like to see if High Caloric Food has a statistical significance on Weight Level.
I've tried Chi Squared Contingency test as suggested by chatgpt but it gives a p-value of 1 which fails to reject null hypothesis that there is no association between High Caloric Food and Weight Level. Visually I can see that High Caloric Food does increase the Obesity Count.
What test should I use in this scenario?
Code:
weight_order = ['Normal_Weight', 'Overweight_Level_II', 'Insufficient_Weight', 'Overweight_Level_I', 'Obesity_Type_I', 'Obesity_Type_II', 'Obesity_Type_III']

df[['High Caloric Food Freq', 'Weight Level']].groupby('High Caloric Food Freq').value_counts(normalize=True).reindex(weight_order, level=1).unstack()

I've normalized the data since the 'yes' to High Caloric Food count is almost 3x greater than 'no'.
Here is what the table looks like:

Edit: sorry for the confusion. The numbers represent the proportion of each weight level that answered 'no' or 'yes' to frequent High Calorie food consumption. For example, 32.24% who have answered 'no' to frequent high calorie consumption have a normal weight.
Comment: Do you have actually weights and heights?  What order is obesity level in? (That is, is obesity level III the heaviest)?  It looks like the cells in your table are row proportions, but chi-square uses counts. What do you mean by "normalizing" the data?
Comment: How many observations do you have in your dataset?
Comment: Please explain what the numbers in your table mean and how they were measured.
Comment: sorry for the confusion. The numbers represent the proportion of each weight level that answered 'no' or 'yes' to frequent High Calorie food consumption. For example, 32.24% who have answered 'no' to frequent high calorie consumption have a normal weight
Answer: As Peter Flom points out in comments, a chi-square test requires to use counts, not proportions (that is, in your code, you should set the normalize parameter to False, not True). The fact that you have much larger counts of "yes" than "no" does not change that.
The sample size has a direct impact on the p-value. If you feed the chi-square test a table where you removed information about the sample size (like you did), you can't trust the results the test gives you. That's why you need to provide the actual counts, not the percentages.
On a side note, if you're in the specific case of some complex survey sampling design, you may want to use the survey weights associated to the observations along with the Rao-Scott chi-square test (instead of the "vanilla" chi-squared test). But even in this case you have to provide the counts as input, not proportions.
Note that if you have a very large number of observations, a test may be not necessary to judge if there is a difference between the two groups in the population, given the differences of percentages in your table.
Besides a chi-squared test, an interesting method when the outcome is ordinal, is ordinal regression. You can find several online resources about it, including questions and answers on this website; having a look at Frank Harrell's website should be informative too.
In any case, you should also focus your attention on a better visualization of your data if you intend to present the data to other people. You could for example consider using bar plots, instead of a table that uses an order that is quite confusing. For instance, why did you voluntarily put "Insufficient_Weight" between "Overweight_Level_II" and "Overweight_Level_I"? This is confusing, if one wants to see how the percentages change in the two groups, as we move from the weight level "Insufficient weight" to "Obesity type III".
Comment: How do you deduce the first row represents "at least 1 million" observations?  The top row can be expressed (to the precision given) as the vector $(79, 74, 51, 22, 11, 7, 1)/245,$ strongly suggesting the total number of observations in that row is either 245 or (possibly) 490, but no larger.
Comment: There's nothing the matter with your advice, though.  You might consider illustrating it using the inferred counts.  For the record, the second row equals $(208, 216, 221, 268, 340, 290, 323)/1866$ (to six decimal places).
Comment: @whuber Thanks. This is the occasion for me to dive into continued fractions. There's another information that OP gave, to probably take into account: the total counts in the second row are about 3 times the total counts in the first row. If I have some time one of these days, I think I'll probably ask a question on how to solve this problem :)
Comment: @whuber Indeed, my bad. I checked the irreducible fractions of the values in the table, but I was assuming that the given values were not rounded, which may be an incorrect assumption. I delete my answer, sorry for the inconvenience.
Comment: In case someone is interested, I asked a follow-up question relative to the discussion above: https://stats.stackexchange.com/questions/632731/finding-the-smallest-possible-sample-size-of-a-2x7-contingency-table-given-row

Which hypothesis test should I use?


Wording of a statistics question

Question: Apologies if this is not the correct area to post this but, I have a question about the specific wording of an assignment. We have been given this sentence, basically

The occurrence of false positives [in some experiment] is 40%

What does this mean? Does it mean that 40% of positives are false? Or 40% of all tested patients are specifically both false and positive? Or say 40% of those that are false are positive? I'm quite confused as to what this means, and none of the people I have asked understand either. Thanks
Answer: For binary classifiers (that output Negative or Positive), there are four types of outcomes:
True Positive -> The classifier reports positive and is correct.
False Positive -> The classifier reports positive but is wrong.
True Negative -> The classifier reports negative and is correct.
False Negative -> The classifier reports negative and is wrong.
40% false positives (fp) out of all responses does not tell you much about the other responses. But all together they sum up to 100%. Also: it does not automatically tell you how it will perform in the future. Also, the result is always relative to the true label distribution: If you tested it on 60 positive and 40 negative labels, 40% false positives means, that it misclassified 100% of the negatives, since there are only 100 instances and the positives cannot be classified as false positives, they need to come from the negatives. Since the percentage is always relative to the whole population, 40% of 100 are 40 which leaves no negatives that are classified as true negatives.
So you need all 4 types of outcomes and also the label ratios of the test set to judge your result.
TP + TN + FP + FN = 1.0
TP + TN = Rate of correctly classified over both outcomes, positive and negative classes.
FP / TP = Error rate for positives to be missclassified. Since you are missing the TP, you cannot say how many positives would be missclassified.
Maybe something that could also help to understand: Think about a classifier that always predicts positive, no matter what. What would be your TP, TN, FP, FN be for the two following cases:
a) You give it 60% positive and 40% negative instances.
b) You give it 99% positive and 1% negative instances.
Answer:

! a) TP = 60%, TN = 0%, FP = 40%, FN = 0%
! b) TP = 99%, TN = 0%, FP = 1%, FN = 0%
Comment: So you are saying given the wording of the question, FP / 100% = 40%? To give some context, this is a medical situation where the occurrence of false positives compared to all patients should be quite low.
Comment: Medical or not, FP is one of the four possible outcomes and the percentage value is always relative to the total number of instances in your test, not just the negatives. Therefore it is very important to know how many have been tested on and how the balance between positives and negatives in that set was. Also, to not confuse oneself, it is better to use absolute numbers for TP, TN, FP and FN. That would also convey some understanding about how reliable the numbers are. 40% if you only tested on 10 people is different from testing on 100.000.
Comment: One clarification though: There is a difference between False Positives(FP) and False Positive Rate (FPR)! False positive rate is usually FP / (TN+FP). But since the question explicitly says "False Positives" and not "False Positive Rate" I assume it means the first.
Comment: Thank you. This is exactly what I needed to hear. Some problems in the packet contained True Positive and some contained True Positive Rate. That makes a lot more sense then.
Answer: It means (mostly in medical testing) that the binary outcome of the model is falsely indicated as positive. Meaning that the test says that the condition is present, while in reality, it is not.
This is important in statistical hypothesis testing and especially in medical testing, because it can create some false interpretation of the accuracy of a test. Let me clarify with an example:
I recently read an article in a Belgian newspaper that said that a test was $99\%$ accuracy, but if you tested positive, you only had $1\%$ chance that you actually had the disease.
The ratio of people that had this disease was $$\frac{1}{10000}$$ and claimed to be $99\%$ accurate. So let's assume you have $1.000.000$ people, $100$ people should have the disease. But if you were out to test it, $99$ of these $100$ would get a true positive and $1$ of these $100$ people would get a false negative. On the other hand, of the $999.900$ people who don't have the disease, $989.901$ people would get a true negative and $9999$ people would get a false positive. This means that the probability you actually would have the disease if you were to test positive is only :
$$\frac{99}{10098} \approx 0.98 \%..%$$
Comment: In your explanation, the false positive rate would be 99.02% or 0.9999%? The first is FP / (FP + TP) and the second is FP / (FP+TP+FN+TN)
Comment: The false positive rate is FP/(FP+TN) so 0.01.
Answer: Let $D$ indicate the presence of a disease. Let $+$ indicate that the experiment shows a positive and a $-$ shows a negative. Thus,
($+ \mid D$) indicates that the person has the disease, and the experiment showed a positive result, i.e a true positive.
($- \mid D$) indicates that the person has the disease, and the experiment showed a negative result, i.e a false negative.
($+ \mid D^c$) indicates that the person does not have the disease, and the experiment showed a positive, i.e a false positive, which has the 40% chance.
($- \mid D^c$) indicates that the person does not have the disease, and the experiment showed a negative, i.e a true negative.
Thus, the statement "The occurrence of false positives [in some experiment] is 40%" indicates that a 40% of people that are not sick with the disease will show a positive in the test. In other words Pr($+ \mid D^c)=$0.4=40%$
Comment: Your explanation doesn't seem to gibe with your conclusion.  When you say $+\cap D^c$ has the $40\%$ rate, that seems to mean, at least to me, that $40\%$ of the people examined will test positive, although they don't have the disease: $\Pr(+\cap D^c)$, whereas your conclusion seems to talk about $\Pr(+|D^c)$.
Comment: I'm afraid I don't know which is correct, the explanation or the conclusion.  I would suggest that you couch the entire answer in terms of either joint or conditional probabilities, whichever is appropriate.
Comment: @saulspatz You are completely correct, any suggestions on how to correct it?
Comment: @saulspatz I agree.

Wording of a statistics question


How to concatenate strings from separate elements with jquery / javascript

Question: I am wanting to concatenate strings from 2 separate elements and have them stored in a variable.
Currently my code is setting the variable equal to:
"Daily: 1070300, Weekly: 1070300, Monthly: 1070300"
My goal is to make the variable in the console equal to:
"Daily: 10, Weekly: 70, Monthly: 300"

      $(document).ready(function() {
        var str = '';
        $('tbody > tr').each(function() {
          $(this).find('.key').each(function() {
            str += $(this).text() + ": " + $(this).parents().siblings('tr').find('.value').text() + ", ";
          })
        });
        console.log(str);
      });

      Daily
      Weekly
      Monthly

      10
      70
      300

Thank you for your help all!
Comment: because you are reading all of the tds text at once, not the one for the column you are after.
Comment: what do you want output if there is more than 1 row of values? Just the first row, or one console.log for each row of values?
Answer: Each time through the key loop, you're grabbing the content of all three value cells (since $(this).parents().siblings('tr').find('.value') matches all three). There are many ways to fix this but one easy one I see is to use the index argument on the inner loop to select the value cell corresponding to the current key (using jQuery's eq function):

  $(document).ready(function() {
    var str = '';
    $('tbody > tr').each(function() {
      $(this).find('.key').each(function(index) {
        str += $(this).text() + ": " + $(this).parents().siblings('tr').find('.value').eq(index).text() + ", ";
      })
    });
    console.log(str);
  });

      Daily
            Weekly
            Monthly

            10
            70
            300

Comment: The code works based on what OP did, but it is very inefficient.
Comment: What would make more sense @epascarello ?
Comment: Thank you for your answer @nvioli ! Is there a way to grab and combine the 2 values simultaneously so it is more efficient? Just wondering if my code is not optimal.
Answer: The code is very inefficient when you keep looking up stuff in the loop. So fixing it to read the index would work, it just causes the code to do more work than needed.
How can it be improved. Look up the two rows and one loop using the indexes.

var keys = $("table .key")  //select the keys
var values = $("table .value")  //select the values

var items = []  // place to store the pairs
keys.each(function(index, elem){ //loop over the keys
   items.push(elem.textContent + " : " +  values[index].textContent)  // read the text and use the index to get the value
})
console.log(items.join(", "))  // build your final string by joing the array together

            Daily
            Weekly
            Monthly

            10
            70
            300

Comment: Thank you for the answer @epascarello ! I learned a lot from it.
Answer: Collect the .key and .value classes into a NodeList convert the NodeList into arrays. Then merge the 2 arrays into key/value pairs stored in an Object Literal. Finally convert the object into a string so it can be displayed.
Demo
Details are commented in Demo

// Collect all th.key into a NodeList and turn it into an array
var keys = Array.from(document.querySelectorAll('.key'));
// As above with all td.value
var vals = Array.from(document.querySelectorAll('.value'));

function kvMerge(arr1, arr2) {
  // Declare empty arrays and an object literal
  var K = [];
  var V = [];
  var entries = {};

  /* map the first array...
  || Extract text out of the arrays
  || Push text into a new array
  || Then assign each of the key/value pairs to the object
  */
  arr1.map(function(n1, idx) {
    var txt1 = n1.textContent;
    var txt2 = arr2[idx].textContent;
    K.push(txt1);
    V.push(txt2);
    entries[K[idx]] = V[idx];
  });
  return entries;
}

var result = kvMerge(keys, vals);
console.log(result);

// Reference the display area
var view = document.querySelector('.display');
// Change entries object into a string
var text = JSON.stringify(result);
// Clean up the text
var final = text.replace(/[{"}]{1,}/g, ``);
// Display the text
view.textContent = final

      Daily
      Weekly
      Monthly

      10
      70
      300

Answer: You can also solve that using unique ids, like that:

$(document).ready(function() {
  var str = '';
  $('tbody > tr').each(function() {
    $(this).find('.key').each(function() {
      var index = $(this).attr('id').slice(3)
      str += $(this).text() + ": " + $('#value'+index).text() + ", ";
    })
  });
  console.log(str);
});

      Daily
      Weekly
      Monthly

      10
      70
      300


How to deploy Yii and Django together

Question: I have a yii site. But I want to have django to serve the pages that that have url path
www.mysite.com/django or in subdomain www.django.mysite.com  The sever has fastcgi installed and it is a shared server.
My .htaccess file for yii looks like this (it is in www folder) as I have removed index.php for clean url
<code>

    Options +FollowSymLinks
`   IndexIgnore */*
    RewriteEngine on

    # if a directory or a file exists, use it directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # otherwise forward it to index.php
    RewriteRule . index.php

</code>
Answer: By shared server do mean a paid host? The real question is do you have access to the apache conf, and if not can you ask the host politely to insert a VirtualHost for you for django.

How to deploy Yii and Django together


WFLYEJB0043: A previous execution of timer [timer] is still in progress, skipping this overlapping scheduled execution at [time]

Question: I have defined some persistent timers in a singleton EJB as follows (using WildFly 9.0.2 final).
@Startup
@Singleton
@Lock(LockType.READ)
public class BackgroundJobManager implements BackgroundJobService {

    @Schedule(dayOfMonth = "1", month = "Jan", year = "*", hour = "0", minute = "0", second = "0", persistent = true)
    private void doYearlyJob() {
        //...
    }

    @Schedule(hour = "*", minute = "*/5", second = "0", persistent = true)
    private void updateTopSellers() {
        //...
    }

    @Schedule(hour = "*", minute = "*/1", second = "0", persistent = true)
    private void updateFeedback() {
        //...
    }

    //...
}

Several warnings are issued on server startup and when the application is redeployed like the following (these are merely a few of them).
19:46:51,687 WARN  [org.jboss.as.ejb3] (EJB default - 3) WFLYEJB0043: A previous execution of timer [id=15baaed1-d804-48fc-acdb-80ea3e04735f timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 16:25:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:51 IST 2015.
19:46:51,796 WARN  [org.jboss.as.ejb3] (EJB default - 4) WFLYEJB0043: A previous execution of timer [id=fc285ef2-c7a1-4a2e-af57-d320c769b445 timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 22:50:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:51 IST 2015.
19:46:51,890 WARN  [org.jboss.as.ejb3] (EJB default - 5) WFLYEJB0043: A previous execution of timer [id=15baaed1-d804-48fc-acdb-80ea3e04735f timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 16:26:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:51 IST 2015.
19:46:51,953 WARN  [org.jboss.as.ejb3] (EJB default - 6) WFLYEJB0043: A previous execution of timer [id=fc285ef2-c7a1-4a2e-af57-d320c769b445 timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 22:55:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:51 IST 2015.
19:46:51,984 WARN  [org.jboss.as.ejb3] (EJB default - 7) WFLYEJB0043: A previous execution of timer [id=15baaed1-d804-48fc-acdb-80ea3e04735f timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 16:27:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:51 IST 2015.
19:46:52,062 WARN  [org.jboss.as.ejb3] (EJB default - 8) WFLYEJB0043: A previous execution of timer [id=fc285ef2-c7a1-4a2e-af57-d320c769b445 timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 23:00:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:52 IST 2015.
19:46:52,218 WARN  [org.jboss.as.ejb3] (EJB default - 9) WFLYEJB0043: A previous execution of timer [id=15baaed1-d804-48fc-acdb-80ea3e04735f timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 16:28:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:52 IST 2015.
19:46:52,328 WARN  [org.jboss.as.ejb3] (EJB default - 10) WFLYEJB0043: A previous execution of timer [id=fc285ef2-c7a1-4a2e-af57-d320c769b445 timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 23:05:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:52 IST 2015.
19:46:52,390 WARN  [org.jboss.as.ejb3] (EJB default - 3) WFLYEJB0043: A previous execution of timer [id=15baaed1-d804-48fc-acdb-80ea3e04735f timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 16:29:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:52 IST 2015.
19:46:52,453 WARN  [org.jboss.as.ejb3] (EJB default - 4) WFLYEJB0043: A previous execution of timer [id=fc285ef2-c7a1-4a2e-af57-d320c769b445 timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 23:10:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:52 IST 2015.
19:46:52,484 WARN  [org.jboss.as.ejb3] (EJB default - 5) WFLYEJB0043: A previous execution of timer [id=15baaed1-d804-48fc-acdb-80ea3e04735f timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 16:30:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:52 IST 2015.
19:46:52,531 WARN  [org.jboss.as.ejb3] (EJB default - 6) WFLYEJB0043: A previous execution of timer [id=fc285ef2-c7a1-4a2e-af57-d320c769b445 timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 23:15:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:52 IST 2015.
19:46:52,593 WARN  [org.jboss.as.ejb3] (EJB default - 7) WFLYEJB0043: A previous execution of timer [id=15baaed1-d804-48fc-acdb-80ea3e04735f timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 16:31:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:52 IST 2015.
19:46:52,687 WARN  [org.jboss.as.ejb3] (EJB default - 8) WFLYEJB0043: A previous execution of timer [id=fc285ef2-c7a1-4a2e-af57-d320c769b445 timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 23:20:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:52 IST 2015.
19:46:52,781 WARN  [org.jboss.as.ejb3] (EJB default - 9) WFLYEJB0043: A previous execution of timer [id=15baaed1-d804-48fc-acdb-80ea3e04735f timedObjectId=WildFly.WildFly-ejb.BackgroundJobManager auto-timer?:true persistent?:true timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@9e86f initialExpiration=null intervalDuration(in milli sec)=0 nextExpiration=Fri Dec 11 16:32:00 IST 2015 timerState=IN_TIMEOUT info=null] is still in progress, skipping this overlapping scheduled execution at: Sat Dec 12 19:46:52 IST 2015.

Timer service is defined in standalone-full-ha.xml as follows.
<timer-service thread-pool-name="default" default-data-store="clustered-store">
    <data-stores>
        <database-data-store name="clustered-store" datasource-jndi-name="java:jboss/datasources/projectXADatasource" database="mysql" partition="timer"/>
    </data-stores>
</timer-service>

These warnings also appear, when these timers are persisted to the file system in place of a database, no matter whether the application is deployed in a cluster (standalone-full-ha.xml) or non-cluster (standalone-full.xml) environment.
I regularly flush out all contents of standalone/data (except the deployed JDBC driver and custom contents), standalone/deployments and standalone/tmp whenever necessary. Symptoms of timers are no longer available in standalone/data as they were before, when timers were initially being persisted to the file system.
Is there a fix?

There is a question but I am not satisfied with the answer given (sorry). Besides, that question uses JBoss EAP 6.4 and why the tag spring presents there while using EJBs in an application server is a mystery to me.

Update :
The issue remains stationary in WildFly 10.0.0 final.
Comment: Persistent timers and development (hotdeploy/hotpublish) don't always go together very well. Theoretically, the IDE's server plugin is to blame.
Comment: NetBeans WildFly plugin indeed does not work as they claim. Turning to another IDE is a learning curve and is not possible immediately as I am completely accustomed to using NetBeans, since the beginning of time. I only wonder how other people afford to use WildFly with NetBeans in this way.
Comment: Eclipse is also far from Perfect ;)
Comment: If the plugin is not working as expected feel free to file a bug :) https://netbeans.org/bugzilla/enter_bug.cgi?product=serverplugins. As far as I know there's one guy working on the plugin in his spare time. He's usually quite responsive though.
Comment: @JamesR.Perkins : The path to Bugzilla initiates from [here](http://stackoverflow.com/q/33892879/1391249) and [here](http://stackoverflow.com/q/26447519/1391249) and finally reaches to the Bugzilla [tracker](https://netbeans.org/bugzilla/show_bug.cgi?id=248161). I reported about a year ago but its status was "RESOLVED INCOMPLETE". Not all bugs can be expressed linguistically without having a face to face conversation involving a practical approach.
Comment: Since you can 'talk' to me on wildfly hipchat channel or wildfly/netbeans irc channels this can be resolved this way.
Comment: @ehsavoie : I can easily sacrifice everything else except "Deploy on Save" for now which I can reproduce on a blank playground Java EE project having only a single Java source file or JSP / XHTML file avoiding all technical details in the project. I do not see the application being deployed when some changes to the application are saved. To be crystal clear, the "Deploy on Save" option on the IDE is turned on. The only thing which I do not use is Apache Maven to build and deploy Java EE applications. They are built and deployed using Apache Ant built in the IDE itself.
Comment: the "Deploy On Save" on Netbeans works this way : the IDE give me a list of files to update and I copy them in the exploded directory in the deployments folder. Then WildFly should redeploy it. Could you check that the files are updated ? I usually use wildfly examples to test but maybe they are a little too light. If you have some example application I would happily try it.
Comment: @ehsavoie : I never heard of copying some files somewhere for the deployment process to occur :) While using GlassFish or Apache Tomcat, the application automatically starts deploying, if one or more Java source files are modified and saved (Ctrl + Shift + S). This does not happen while using WildFly. Sample applications I use to test this contain nothing (plain empty) other than a single Java source file having no overhead of extra libraries. The application can only be deployed by "Right clicking on the application `->` Clean & Build and then Deploy" which is time consuming.
Comment: Hum which version ( WildFly, netbeans and plugin) do you use, this is a call from the IDE to the plugin giving it the changes. I've seen it work numerous times with JSP and Servlets
Comment: @ehsavoie : NetBeans 8.1 / WildFly 9.0.2 final. (I did not change the plugin shipped with the IDE).
Comment: Hi, is the bug fixed in WildFly 10?
Comment: @internet : I dunno.
Answer: This is an acknowledged bug.  See https://issues.jboss.org/browse/WFLY-6561.
The bug has also been applied to JBoss 7 as well:  https://issues.jboss.org/browse/JBEAP-4442
Comment: Thanks for the reference
Answer: We were getting this "warning" on startup which seems to execute the scheduledTimeout method successfully anyway.  There's not really an error here especially since the persistent attribute on the @Schedule annotation defaults to true.  This message appears for us (in development) during startup after the server has been down for a sustained period of time (therefore missing the timeout events that would have occurred had the server been online).  Other answers to this question are also probably valid, but noting this here if the proper function of this feature is being overlooked.
Basically, if you're thinking this is a problem, re-evaluate whether you want your @Schedule timed event to replay all events missed while the server was offline.  If not, then set the persistent attribute to false in the annotation.
Comment: i have the same problema and turning persistent to false does not solve the problem
Comment: @Ewerton, very interesting.  What would JBoss be in the middle of executing if it didn't persist your timer during the last shutdown?


Como implementar Actionbar e ViewPager como no Tinder

Question: Preciso implementar uma ActionBar e ViewPager como no Tinder.
Quando o Tinder abre, você pode deslizar por todas as abas.
A segunda aba é uma ListView ou uma ListFragment e quando você toca em um item, é levado para uma outra série de abas. Você pode deslizar de volta e estará na série de abas anterior.
Como posso fazer isso suave e elegantemente?
Comment: Que tal colocar umas fotos? Nem todos aqui tem ou podem ter o Tinder no celular. :)
Comment: Vou colocar fotos. Muito obrigado Pablo pela sugestao.
Comment: Como assim, abas do estilo whatsapp também?
Comment: Abas como no whatsapp. Diferente do whatsapp entretanto, na medida que #1- as abas no whatsapp formam uma tabbar abaixo da actionbar e no tinder as abas formam uma tabbar dentro da actionbar; #2- o whatspp tem somente 3 abas simplesmente e nao tem navigation drawer. O tinder tem um grupo (a) de 4 abas e se vc toca num item da segunda aba que e' uma listview ou listfragment vc e' levado para um grupo (b) de duas abas. A primeira aba e' um chat como whatsapp e a segunda aba e' uma horizontal scrollview das fotos que a pessoa disponibilizou. #3- quando vc desliza de volta do grupo 9
Comment: Abas como no whatsapp. Porem whatsapp:
#1- tem abas que formam uma tabbar abaixo da
actionbar;
tinder tem abas dentro da actionbar.
#2- whatspp tem 3 abas e nao tem navigation drawer.
Tinder tem 1 grupo (a) de 4 abas -
vc toca num item da 2a. aba que e' uma listview ou listfragment vc vai
para um grupo (b) de 2 abas.
no grupo (b) - 1a. aba e' um chat -
2a. aba e' 1 horizontal scrollview.
#3- qdo vc desliza de volta do grupo
(b) vc volta para a aba nro 2 do grupo (a) e para a aba nro 1 do grupo (a).
A transicao e' perfeita entre grupos (a) e (b).
#4- o tinder tem navigation drawer.
Answer: Selecionei esta Lib : CardStackView

Modo de usar

Declare o layout
<com.yuyakaido.android.cardstackview.CardStackView
    android:id="@+id/activity_main_card_stack"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="30dp"
    android:clipChildren="false"
    android:clipToPadding="false"/>

Agora implemente o Botão reverse.
final CardStackView cardStackView = (CardStackView) findViewById(R.id.activity_main_card_stack_view);
cardStackView.setAdapter(adapter);

View reverseButton = findViewById(R.id.activity_main_reverse_button);
reverseButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        cardStackView.reverse();
    }
});

Esta é a forma mais simples de implementar, porém no link acima tem explicações de implantações customizadas.
Comment: Muito obrigado Thiago. Vou checar. Mas nao pode ter botao. Tem que ser mesma coisa que o Tinder. Somente swiping.


Cutting out background from image/canvas using a predefined pattern

Question: I'm not requiring a full answer to this question, just an idea on how to approach it.
Let's say that a user on my site wants to cut out the background from this image:

Normally this would be a job for some magic outline tool, but this site already carries something that would provide a perfect cutout pattern, namely this:

As you can see this car will fit perfectly over the top one.
If the user could somehow fit the bottom picture over the top one and cut out everything outside that, it would be a perfect background removal.
How do I go about building something like this? Or are there already software out that does something similar?
The bottom picture could be anything, for examle a completely black model for easier recognition, but I'd think that it would be smarter if it used the outline of the transparent .png image and cut out everything outside it.
(The picture itself doesn't need to be used either if there is some way to extract the important bits of it needed for the cutout, of course).
Comment: SVG `` is the key https://sarasoueidan.com/blog/css-svg-clipping/
Answer: Here's how to do your knockout with html5 canvas
If you have an exact image that defines the desired cut and you also know the position where the cut is to be made, then you can use compositing to do you cut-out. With destination-in compositing, new drawings will keep existing pixels only where new & old pixels are non-transparent.
Here's a few notes, example code and a Demo:
Notes:

Your car on your car-only image is not exactly the size of the car on the car+background image -- the car-only is a bit wider. This causes the cut-out to have some extra pixels. But if you had exact sizing the cutout would be perfect.
Your car on your car-only image has semi-transparent shadowing. This causes the cutout to have some extra semi-transparent pixels where the shadow was on the car-only image.

Example & demo using a different exactly sized cutout with no shadow:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var bk=new Image();
bk.onload=start;
bk.src='https://dl.dropboxusercontent.com/u/139992952/multple/model-t-car.png';
var cut=new Image();
cut.crossOrigin='anonymous';
cut.onload=start;
cut.src="https://dl.dropboxusercontent.com/u/139992952/multple/model-t-cutout.png";
var imgcount=2;
function start(){
  if(--imgcount>0){return;}
  canvas.width=bk.width;
  canvas.height=bk.height;
  ctx.drawImage(bk,0,0);
  ctx.globalCompositeOperation='destination-in';
  ctx.drawImage(cut,125,40);
  // always clean up -- reset the default compositing mode
  ctx.globalCompositeOperation='source-over';
}
body{ background-color: ivory; }
canvas{border:1px solid red; margin:0 auto; }

Original with background

Exactly sized cutout

With background removed

<canvas id="canvas" width=300 height=300></canvas>
Answer: There's no easy plug-and-play way. I can think of 2 methods:
(1) SVGs. Plot the different points on the outline of the car yourself (very time-consuming), or import the car into Illustrator (or similar), export it as an SVG, and use the points it calculated for you with clip-path.
(2) PNG (or GIF).

Create a rectangle of solid color in Illustrator/Photoshop.
Paste the car image on top of it as a new layer.
Select the outline of the car.
Delete the selection from the rectangle of color. This will leave a rectangle with a transparent car-shaped hole in it.
Save the rectangle as a PNG or GIF or other format supporting transparent backgrounds.
Use CSS to overlay that PNG on various images of cars.

This is useful if, for instance, you have 5 photos of cars in different colors, all with the same dimensions and taken from the same angle, and want to display the 5 cars with the same background. No need to copy the same background 5 times in Photoshop; just re-use the PNG 5 times in CSS.
Now if you want to change the "background" (which is actually an overlay and not really a background) you need only change it in one place.
Keep in mind: The image you provided is not a perfect outline because it has a shadow.
Comment: Point 2 is clever but I *think* I need a transparent background. I somehow forgot about SVG. Does it rhyme well with canvas?
Comment: Truth be told, I'm not sure.
Comment: You could draw an svg on a canvas and do some composite operation from there, but it's way simpler to just do the composite opeartion from your raster images. svg won't do good here, anyhow you'll do the vectorization, it will be an approximation of the shape, better fit with what you have : pixels. Look at @markE's example, this is really easy + it will keep semi-transparent pixels.


Constrained nonlinear optimization

Question: I am wondering what is the easiest/best way to find the values of $x_i$ that maximize the expression  $\sum_{i=1}^N a_i \ln (x_i)$ under the constraints $\sum_{i=1}^Nx_i = 1$ and $ 0\leq x_i \leq 1$
Do I have to use Lagrange multipliers? Is there an easier way?
By using the Lagrange multiplier and setting the derivative of the Lagrangian $\sum_i a_i\ln x_i + \lambda(1-\sum_i x_i)$ to 0 I arrive at the following conclusion:
\begin{align}
x_i=\frac{a_i}{\lambda} \forall i \in \{1, \ldots, N \}
\end{align}
How would I proceed from that?
Update: solution
By enforcing $\sum_i x_i = 1$ it follows that $\sum_i \frac{a_i}{\lambda} = 1$ which leads to $\lambda = \sum_i a_i$ and $x_i = \frac{a_i}{\sum_j a_j}$
Comment: Lagrange multipliers is very easy for this question, so there probably isn't an easier way.
Comment: I am trying to solve it with the Lagrange multipliers but, being quite inexperienced, I am stuck.
Comment: Read your notes carefully, and try to apply them here.
Comment: I added my progress to the post. I will be very grateful if you respond with some contribution
Comment: Good.  You are nearly there.  You need to find $\lambda$, then you will know $x_i$.  Try $\sum_{i=1}^Nx_i=1$
Comment: done! :) I hope it's correct
Comment: Go ahead and post your results *as an answer*. You'll get much-deserved points for both.
Answer: Solution
By enforcing $\sum_i x_i = 1$ it follows that $\sum_i \frac{a_i}{\lambda} = 1$ which leads to $\lambda = \sum_i a_i$ and $x_i = \frac{a_i}{\sum_j a_j}$

Constrained nonlinear optimization


What top tips you have for designing drupal themes?

Question: I would like to use a 960 grid system master theme to create my own custom Drupal 7 subtheme for generic audience.
What should I consider when designing professionally looking Drupal themes ?
What is the most important when designing with end user experience in mind ?
Answer: All you need is a consistent architecture and good planning. I think getting started on a HTML5 foundation is a good beginning. I suggest you build your project on a subtheme based on Omega or Fusion Theme kits.
Omega has a based on 960 grid system (12,18,24 columns, 20px gutter). It uses the zone/region relationship for a better block handling. Of course is a responsive theme, it starts mobile to desktop (not viceversa) which is very good.
You can even copy Omega subtheme page layout settings, alter it and save it under a new template with Delta module (created by Jake Strawn). Your settings can be then used in various context using the Context Module.
This is a good architecture to start with.
As a UX designer keep in mind Drupal is jQuery and jQuery UI ready, so learn to manipulate widgets via a module or a js (added in your info file).
Keep a consistent architecture and never mess with modules that are not necessary and only bloats your site.
In additional a good knowledge of Views module, contextual filters and relationships is a must.
Comment: Thank you for your answer. I think yours is the most complete one.
Answer: I would highly recommend looking into using Responsive Web Design as suggested here for creating themes for mobile devices. That would be my top suggestion at least: A clean theme that would port easily from one system to the next, e.g. from desktop to phone, would probably be my most installed theme, especially since I am absolutely horrible at theme building.
Comment: ^_^ No problem, I realize that it probably wasn't as helpful as others, however I was trying to speak from the perspective of someone who doesn't design worth crap and what my needs typically wind up being.  It is difficult to find a theme that 1) works out of the box 2) is compliant to both desktop and mobile applications without installing a separate module, theme, or workaround.
Answer: I think Omega takes a good modern approach to a Drupal Theme, check it out for some inspiration. Omega mixed with Delta and Context is a very powerful combination.
I would also try and use HTML5 and maybe check out the HTML 5 boilerplate
If you are looking at designing polished and finished themes as opposed to a starter theme, some good examples can be found at at the rocket theme demos
Answer: +1 For your answer and +1 for the Accepted answer.
Here's some supplementary material to consider - these would help answer your question as well.

http://drupal.org/node/225125 (Official Guide 1, General)
http://drupal.org/node/1010576 (Official Guide 2, How to build your own sub-theme (7.x-3.x))
http://groups.drupal.org/node/155974 (Creating an Omega 3.x Subtheme)
http://opensourcecms.pro/drupal/howto-drupal-7-sub-theme-creation-step-by-step/
http://shutterfreak.net/blogs/olivier-biot/2010-01-03/drupal-theme-hacking-creating-sub-theme
http://www.youtube.com/watch?v=R0i5P3QGm5s (Drupal 7 sub themes a very simple how to guide.)

I've favourited your question as I may consider creating an Omega subtheme and I am including my own research here too.


dotnet error : Unable to obtain lock file access on '/tmp/NuGetScratch/lock/

Question: Passos para reproduzir
dotnet build or dotnet run
Comportamento esperado
Run or Build app
Comportamento atual
Getting ready...
The template "ASP.NET Core with Angular" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on /home/limup/Documents/Projetos/Limup/salao/salao.csproj...
/usr/share/dotnet/sdk/3.1.101/NuGet.targets(123,5): error : Unable to obtain lock file access on '/tmp/NuGetScratch/lock/b19d3901039706ea82571abad7c98ec690508d4b' for operations on '/home/limup/Documents/Projetos/Limup/salao/obj/salao.csproj.nuget.cache'. This may mean that a different user or administator is holding this lock and that this process does not have permission to access it. If no other process is currently performing an operation on this file it may mean that an earlier NuGet process crashed and left an inaccessible lock file, in this case removing the file '/tmp/NuGetScratch/lock/b19d3901039706ea82571abad7c98ec690508d4b' will allow NuGet to continue. [/home/limup/Documents/Projetos/Limup/salao/salao.csproj]

Restore failed.
Post action failed.
Description: Restore NuGet packages required by this project.
Manual instructions: Run 'dotnet restore'

Dados do ambiente
dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 3.1.101
Commit: b377529961

Runtime Environment:
OS Name: fedora
OS Version: 31
OS Platform: Linux
RID: fedora.31-x64
Base Path: /usr/share/dotnet/sdk/3.1.101/

Host (useful for support):
Version: 3.1.1
Commit: a1388f194c

.NET Core SDKs installed:
3.1.101 [/usr/share/dotnet/sdk]

.NET Core runtimes installed:
Microsoft.AspNetCore.App 3.1.1 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.1 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download

Obs
Tentei fazer correções no restore dotnet, mas recebi o mesmo erro.
Não tive esse problema com o dotnet sdk 2.0.
Comment: Bem-vindo ao StackOverflow em português. Tal como o nome sugere, o idioma oficial usado aqui é o português. Assim sendo, você poderia por favor traduzir sua pergunta? Caso prefira, você também pode fazer essa mesma pergunta no site em inglês do StackOverflow.
Comment: Claro! Feito a tradução.
Comment: Se você ler a mensagem de erro até o final, você vai encontrar: `This may mean that a different user or administator is holding this lock and that this process does not have permission to access it. If no other process is currently performing an operation on this file it may mean that an earlier NuGet process crashed and left an inaccessible lock file, in this case removing the file '/tmp/NuGetScratch/lock/b19d3901039706ea82571abad7c98ec690508d4b' will allow NuGet to continue.`
Comment: nesse caso só precisa remover o arquivo
Answer: Senhores, consegue resolver a situação com os seguintes comandos:
export TMPDIR=/tmp/NuGetScratch/

e
mkdir -p ${TMPDIR}

Obrigado a todos.