text:
Q: How to count no of days id is having positive balance and negative balance in SAS My data is as following:
id   balance  date
1     10      02Mar2018
1     12      05Mar2018
1    -15      07Mar2018
1     14      14Mar2018
1    -25      25Mar2018

Now i want the number of days id 1 was in positive bal and number of days the id was in negative bal in a march month.
For example no of days in positive will be calculated as following 01mar to 06 mar as first negative entry came on 07Mar so that 6 days.
Then again it went on positive bal on 14 to ,24 that 11 days
so in total it was 6+11=17 days in positive.
And similarly for negative bal.
I tried using following code:
DATA B;
SET A ;
BY ID;
IF FIRST.ID THEN Y=DATE;
RETAIN Y;
ELSE Y=INTCK('day',DATE,Y);
RUN;

But couldn't get the exact results.
Any help will be appriciated.

A: Assuming your data is sorted by id and date.
First do a 'look-ahead' merge (to get the next date) :

data lookahead ;
  merge have
        have (firstobs=2 rename=(date=nextdate id=nextid)) ;

  if id ^= nextid then call missing(nextdate) ;
  drop nextid ;
run ;

/* data now looks like this */
id   balance  date      nextdate
1     10      02Mar2018 05Mar2018
1     12      05Mar2018 07Mar2018
1    -15      07Mar2018 14Mar2018
1     14      14Mar2018 25Mar2018
1    -25      25Mar2018

Then, expand out the missing dates, dealing with instances where the first date per id isn't the 1st of a month, and the last record per id isn't the last day of the month :

data expand ;
  set lookahead (rename=(date=thisdate)) ;
  by id ;

  if first.id and day(thisdate) ^= 1 then do ;
    /* loop from 1st of month to day before date, output new record for each date */
    do date = intnx('month',thisdate,0,'b') to thisdate - 1 ;
      output ;
    end ;
  end ;

  /* output the input record */
  date = thisdate ; output ;

  /* output dates up to the next date */
  if nextdate > thisdate + 1 then do ;
    do date = thisdate + 1 to nextdate - 1 ;
      output ;
    end ;
  end ;
  else
  /* last record for id, loop to end of month */
  if missing(nextdate) and thisdate ^= intnx('month',thisdate,0,'end') then do ;
    do date = thisdate + 1 to intnx('month',thisdate,0,'end') ;
      output ;
    end ;
  end ;

  drop thisdate nextdate ;
  format date date9. ;
run ;

/* data now looks like this */
id   balance  date
1     10      01Mar2018
1     10      02Mar2018
1     10      03Mar2018
1     10      04Mar2018
1     12      05Mar2018
1     12      06Mar2018
1    -15      07Mar2018
1    -15      08Mar2018
... etc ...
1    -15      13Mar2018
1     14      14Mar2018
1     14      15Mar2018
... etc ...
1     14      24Mar2018
1    -25      25Mar2018
... etc ...
1    -25      31Mar2018

It should now be relatively easily to flag the values accordingly, and count them up per id/month.


text:
Q: Create a dictionary whose keys are month names and values are no. of days in the corresponding month. #program stack please correct the code.
Create a dictionary whose keys are month names and values are no. of days in the corresponding month. WAP with separate user defined functions to implement the following operations.
(i)push only those names on the stack whose no. of days are 31.
(ii) pop and display the content of the stack.
plzz correct the code
code: https://docs.google.com/document/d/1fj3eaa2zXIkwhE6W4apLjmva44hxi51C/edit

A: This is probably what you wanted
Edit: Edited the code to meet the new requirements.
(I don't understand what do you mean by 'stack' but you can continue from here)
def create_month_day_dict(year, long_only=False):
    months_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
                    'November', 'December']
    days_in_month = [31, 28 + (year % 4 == 0), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    return dict((k, v) for k, v in zip(months_names, days_in_month) if not long_only or v == 31)

print(create_month_day_dict(2022, long_only=True))
print(create_month_day_dict(2024))

output:
{'January': 31, 'March': 31, 'May': 31, 'July': 31, 'August': 31, 'October': 31, 'December': 31}

{'January': 31, 'February': 29, 'March': 31, 'April': 30, 'May': 31, 'June': 30, 'July': 31, 'August': 31, 'September': 30, 'October': 31, 'November': 30, 'December': 31}

Note: also considered the relevant year

A: You need to consider the year when building a dictionary to help with this problem. The calendar module is ideal for this:
from calendar import monthrange, month_abbr

def make_dictionary(year):
    d = {'year': year}
    for i in range(1, 13):
        d[month_abbr[i]] = monthrange(year, i)[1]
    return d

print(make_dictionary(2024))

Output:
{'year': 2024, 'Jan': 31, 'Feb': 29, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sep': 30, 'Oct': 31, 'Nov': 30, 'Dec': 31}

If you want the full (rather than abbreviated) month name then import month_name and use that

redpajama_set_name: RedPajamaStackExchange


text:
Q: calling method Versus class.method I have a class with two methods defined in it.
public class Routines {

     public static method1() {
      /* set of statements */
     }

     public static method2() {
      /* another set of statements.*/
     }
}

Now I need to call method1() from method2()
Which one the following approaches is better? Or is this qualify as a question?
public static method2() {

        method1();

}

OR
public static method2() {

        Routines.method1();

}

A: I'd go with the first method. In my eyes, it's the equivalent of:
public void method2()
{
    method1();
}

and:
public void method2()
{
    this.method1();
}

I don't know many people who explicitly call this when calling another method in a class. So personally my taste is option 1 - no need to call ClassName explicitly.

A: While I agree with the existing answers that this is primarily a style issue, it is enough of a style issue that both Eclipse and IntelliJ's code critics will flag "non-static references to static methods" in code that does not use the Classname.method() style.
I made it a habit to emphasize intent by using the classname to qualify references to static targets, this to qualify references to instance targets, and bare names for local  references.   A modern IDE will use different highlighting for these constructs, so I suppose it is less important these days.  I like for the maintainer (often myself) to know what was intended, that yes, I knew that was a static reference.
Yeah, it does make for slightly more verbose code, but I think it is worth the extra characters.

A: Well, it qualifies as a question, but obviously the results are going to be the same either way so it's just a matter of style. (There are probably weird overload situations where it could make a difference, but you should avoid those to start with. I can come up with examples if you want, but it's probably not worth it.)
If you feel a particular need to emphasize that it's a static method, feel free to make it Routines.method1() - but normally I'd just leave it as method1().
EDIT: I've tried to come up with an example where it makes a difference using overloading with params:
void CallMethod()
{
    Console.WriteLine("Calling Method()");
    Method();
    Console.WriteLine("Calling Test.Method()");
    Test.Method();
}

void Method(params string[] ignored)
{
    Console.WriteLine ("  Instance method called");
}

static void Method()
{
    Console.WriteLine ("  Static method called");
}

This calls the static method in both cases though. (Interestingly, putting the params on the static method gives a slightly confusing error message using the MS C# compiler, and blows up the Mono compiler completely - at least the version I'm using.)
With a parameter, you could get into odd situations with generic type parameters and type inference, but not without any parameters. Even so, the non-generic form would take precedence.
In short, I don't think I can do it after all :(

A: This is purely a style question, so it depends on your taste.
I prefer the first version. As the 2 methods are in the same class I dont find useful to repeat the class name.

A: I do
public static method2() {
        Routines.method1();
}

No guessing.
It is very clear if I call static method from parent class.
I don't like static import for same reason.

A: It's only an issue of personal favour and code readability, but calling just "method1()" is not an equivalent to "this.method", because both methods in the example are static and you cannot call an object, which has not been instantiated. With static methods you cannot foresee, if there is an instantiated object the moment you call the method, so you cannot use "this". "this" is only a pointer to the executed object, if instantiated.
To answer the question:
It's complete syntactic sugar to just write "method1()" instead of "Routines.method1()". The result on what the computer is executing/calling, which is what the compiler made out of the code, is completely the same.


text:
Q: finding DateOFBirth From Age Is there any formula to direct finding D.O.B from put Year,month and day's in TextField ??
InShort put 21 year 6 month 16 day in text filed that return the calculating D.O.B ?

A: In iphone you do not have direct method how ever you can write on your own.
step 1: Make a NSDate object from year,month,day.
NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setYear:year];
[comp setMonth:month];
[comp setDay:day];
 NSDate *birthdate = [[NSCalendar currentCalendar] dateFromComponents:comp];
[comp release];

step 2: Find the interval from from today.
NSTimeInterval dateDiff = [birthDate timeIntervalSinceNow];
int age=trunc(dateDiff/(60*60*24))/365;

EDIT ...
    NSDateComponents *comp = [[NSDateComponents alloc] init];
    [comp setYear:-year];
    [comp setMonth:-month];
    [comp setDay:-day];
     NSDate *birthdate = [[NSCalendar currentCalendar]dateByAddingComponents:comp toDate:[NSDate date] options:0];;
    [comp release];

A: ...In Java...
I like to use Calendar for this operations. In your case I recommend you to use the add method
So you should create a new instance of Calendar with current date, set the day and the month, and then substract the age.

A: Try this.
Calendar c = Calendar.getInstance();
    System.out.println();
    c.add(Calendar.YEAR, -21);
    c.add(Calendar.MONTH, -6);
    c.add(Calendar.DAY_OF_MONTH, -16);
    System.out.println((c.get(Calendar.MONTH)+1)+"-"+ c.get(Calendar.DAY_OF_MONTH)+"-"+c.get(Calendar.YEAR));

A: Try this it is more useful
Just enter the two dates it gives the difference.
 NSDateComponents *comp=[[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date] toDate:self.objDate options:0] ;

 NSLog(@"%@",[NSString stringWithFormat:@"%d : %d : %d : %d : %d : %d",comp.year,comp.month,comp.day,comp.hour,comp.minute,comp.second]);

Following code may helping to you.
Happy coding


text:
Q: How is $example different from example(%rip)? I've spent 2 hours googling, but to no avail --- there are not many beginner-level guides for assembly, and the course I am taking right now dos not do a very good job at explaining some stuff.
Anyway; I've been trying to work with SSE and tried comparing two doubles using comisd instruction. I've spent a lot of time to understand how to hard-code a non-integer constant (let's call it example, it is declared as
example:
    .long   3794832442
    .long   1044740494

); but after I've done that, I couldn't get it to work --- "operand type mismatch". I've turned to C-to-assembly translator and found out that instead of my comisd  $example, %xmm0 it used comisd example(%rip), %xmm0, and it turned out to work. Now I don't understand, how does it work and how are these different?

A: $example is simply the absolute address of that variable - it doesn't mean a memory access.
You get the "operand type mismatch" because comisd does not support an immediate operand. comisd example, %xmm0 (without the $) would have worked, as that is a memory reference.
example(%rip) is using the PC-relative addressing mode introduced in x86-64, which makes the code position-independent because instead of using an absolute address, it uses an offset from the current instruction pointer.

Based on an answer of Jonathon Reinhart.


text:
Q: Tag de bloco inválido Sou novo em Django e estou com um problema com as tags de Template
Meu código:
{% load static %}
{% block content %}

    {{ questao.afirmativa }}

    {% alternativas = questao.get_alternativas %}

        {% for alternativa in alternativas %}
          {{alternativa}}
        {% end for %}

{% endblock content %}

O objeto questao já vem no context da view. O método get_alternativas gera uma lista de alternativas que quero percorrer com o for e mostrar na página.
O que estou fazendo de errado?
Está dando erro nessa linha:
{% alternativas = questao.get_alternativas %}

Mensagem de erro:

"- Tag de bloco inválido na linha 7: 'alternativas', esperado 'endblock'. Você esqueceu de registrar ou carregar esta tag?"

A: As tags {% ... %} são exclusivas para os comandos do sistema de templates do Django (seja o que vem embutido nele, seja usando o Jinja2).
Para criar uma nova variável dentro do modelo, use a tag {% with ... %}:
{% with alternativas as questao.get_alternativas %}

    {% for alternativa in alternativas %}
      {{alternativa}}
    {% endfor %}

{% endwith %}

Aliás o {% endfor %} está grafado errado no teu código.


text:
Q: Java StringBuilder remove XML Tags I'm trying to pass a XML object through a StringBuilder to compare to Objects, fitting to my needs.
I was wondering if there is a nice way to remove specific tags from the whole String. Underneath I prepared an example:
Original:
<ApprovalSet>
   <ApprovalItem application="Annotext" id="a089989361v451cag47e9f5e9a35716" name="ApprovalItemName" nativeIdentity="xxx12345" operation="Add" state="Finished" value="G1">
       <ApprovalItemComments>
          <Comment author="Random Guy" comment="THE NAME" date="1657122647591"/>
      </ApprovalItemComments>
   </ApprovalItem>
</ApprovalSet>

Desired Outcome:
<ApprovalSet>
   <ApprovalItem application="Annotext" name="ApprovalItemName" nativeIdentity="xxx12345" operation="Add" value="G1"/>
</ApprovalSet>

So basically, I want to remove the id, state and the whole comment and close the ApprovalItem Tag (or just remove all slashes).
Any ideas? Thank you in advance :)
Jonas

A: Instead of string manipulation or regex, I would recomend to use a XML-parser. If all you need is to remove some elemnts and some attributes, you might want to look into Jsoup, which is actually a HTML-parser but can also handel XML and is very intuitive to work with. Using Jsoup your code could look like:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;

public class Example {
    public static void main (String[] args) {
        String originalXml =
                  "<ApprovalSet>\n"
                + "   <ApprovalItem application=\"Annotext\" id=\"a089989361v451cag47e9f5e9a35716\" name=\"ApprovalItemName\" nativeIdentity=\"xxx12345\" operation=\"Add\" state=\"Finished\" value=\"G1\">\n"
                + "       <ApprovalItemComments>\n"
                + "          <Comment author=\"Random Guy\" comment=\"THE NAME\" date=\"1657122647591\"/>\n"
                + "      </ApprovalItemComments>\n"
                + "   </ApprovalItem>\n"
                + "</ApprovalSet>";

        Document doc = Jsoup.parse(originalXml, "", Parser.xmlParser());

        Element approvalSet  = doc.selectFirst("ApprovalSet");
        Element approvalItem = doc.selectFirst("ApprovalItem");
        Elements comments    = approvalItem.select("ApprovalItemComments");

        approvalItem.removeAttr("id").removeAttr("state");
        comments.remove();

        String result = approvalSet.toString();

        System.out.println(result);
    }
}

output
<ApprovalSet>
 <ApprovalItem application="Annotext" name="ApprovalItemName" nativeIdentity="xxx12345" operation="Add" value="G1">
 </ApprovalItem>
</ApprovalSet>

mvn dependency
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.13.1</version>
</dependency>


text:
Q: UWP: Registering an in-process background task fails with "Value does not fall within the expected range" I want to run an in-process background task and so use the following code to try and register it. As per the documentation from Microsoft, for an in-process background task you do not provide a TaskEntryPoint, as it will call the application method App.OnBackgroundActivated instead when it needs to run.
await BackgroundExecutionManager.RequestAccessAsync();

BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.Name = "Background Ping";
builder.SetTrigger(new TimeTrigger(15, false));
builder.Register();

It fails on the Register call with "Value does not fall within the expected range". I cannot see anything that is wrong. Any ideas?

A: Turns out the error is caused by trying to allow multiple instances of the application. I had added the following attribute to the Application tag in the .appxmanifest
desktop4:SupportsMultipleInstances="true"

This is a relatively new attribute used to indicate your UWP application can have multiple instances. So starting the UWP app causes new instances instead of simply moving focus to the existing running instance. As an Enterprise application I need to support multiple instances. Seems you cannot have in-proc background tasks. Guess I am stuck with using an out-of-process task and handle the pain that is communicating with it.


text:
Q: php recursion error factoring so I am new at the idea of recursion and i wrote this simple code to factor a number ($n) this is the code:
$n = 120;
$y = 1;

function factor($n, $y) {
    if($y > $n) {
        return 1;
    } else {
        $x = $n / $y;
        list($whole, $dec) = array_pad(explode('.', $x), 2, Null);
        if($dec == '') {
            echo 'x:' . $x . ' y:' . $y . '
';
            return factor($n, ($y + 1));
        }
    }
}

this is what the code outputs:
x:120 y:1
x:60 y:2
x:40 y:3
x:30 y:4
x:24 y:5
x:20 y:6

so my question is why does this stop before it completes?

A: Your next step would be 120 / 7 which equals 17.142857....
So this check fails and as such the recursion does not happen:
if($dec=='') // $dec would equal to 142857.....
{
    echo'x:'.$x.' y:'.$y.'
';
    return factor($n,($y+1));
}

A: else
{
    $x=$n/$y;
    list($whole,$dec)=array_pad(explode('.', number_format($x)), 2, Null);
    if($dec=='')
    {
        echo'x:'.$x.' y:'.$y.'
';
        return factor($n,($y+1));
    }
}

PART OF DECIMAL LIMITATION

A: There are two things I see wrong with your example:

*

*Your recursion stops the first time it encounters a fractional value. The tail recursion (return factor($n, $y + 1);) only occurs when $dec == ''. Otherwise, the function simply exits. That's why it stops when $y is 7.

*Your condition for ending recursion ($y > $n) is incorrect. You want to break the recursion when the divisor is greater than the quotient — i.e., when $y > $x — because that means you've found all the integer factors.

I think this is what you want:
$n = 120;
$y = 1;

function factor($n, $y) {
    $x = $n / $y;

    if($y > $x) {
        return 1;
    } else {
        list($whole, $dec) = array_pad(explode('.', $x), 2, Null);

        if($dec == '') {
            echo 'x:' . $x . ' y:' . $y . "
\n";
        }

        return factor($n, ($y + 1));
    }
}

echo factor($n, $y);


text:
Q: Android: Firebase authentication with Facebook failing I'm trying to use Firebase to handle authentication with Facebook logins. I've created the activity by following the documentation on both Firebase's and Facebook's sites and making sure the settings on both sites are filled as needed.
I'm able to log in to Facebook from my app, but when it comes to Firebase saving the user, I get an error:

signInWithCredential com.google.firebase.FirebaseException: An
  internal error has occurred. [ Access Not Configured. Google Identity
  Toolkit API has not been used in project 27973105972 before or it is
  disabled. Enable it by visiting https ]

On Firebase I have for Sign-in providers: Facebook enabled with correct App ID and App secret.
On Facebook I have added the Firebase's redirect URI to the Valid OAuth redirect URIs list.
As a note, searching for Google Identity Toolkit API, leads me to https://developers.google.com/identity/toolkit/ where it says to use Firebase Authentication. So not a very helpful error message.
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private CallbackManager mCallbackManager;

    private FirebaseAuth mAuth;

    private FirebaseAuth.AuthStateListener mAuthListener;

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

        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();

        // [START auth_state_listener]
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    Toast.makeText(MainActivity.this, "Authentication successful 2.",
                            Toast.LENGTH_SHORT).show();
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                    Toast.makeText(MainActivity.this, "Authentication signed out.",
                            Toast.LENGTH_SHORT).show();
                }
                // ...
            }
        };
        // [END auth_state_listener]

        // Initialize Facebook Login button
        mCallbackManager = CallbackManager.Factory.create();
        LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setReadPermissions("email", "public_profile");
        loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.d(TAG, "facebook:onSuccess:" + loginResult);
                handleFacebookAccessToken(loginResult.getAccessToken());
            }

            @Override
            public void onCancel() {
                Log.d(TAG, "facebook:onCancel");
                Toast.makeText(MainActivity.this, "facebook onCancel",
                        Toast.LENGTH_SHORT).show();
                // ...
            }

            @Override
            public void onError(FacebookException error) {
                Log.d(TAG, "facebook:onError", error);
                Toast.makeText(MainActivity.this, "facebook onError",
                        Toast.LENGTH_SHORT).show();
                // ...
            }
        });
        // [END initialize_fblogin]
    }

    @Override
    public void onStart() {
        super.onStart();
        // [START on_start_add_listener]
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        // [START on_stop_remove_listener]
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Pass the activity result back to the Facebook SDK
        mCallbackManager.onActivityResult(requestCode, resultCode, data);
    }

    // [START auth_with_facebook]
    private void handleFacebookAccessToken(AccessToken token) {
        Log.d(TAG, "handleFacebookAccessToken:" + token);

        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());

        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInWithCredential", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Authentication successful.",
                                    Toast.LENGTH_SHORT).show();
                        }

                        // ...
                    }
                });
    }
}

A: I hope your query has been resolved by now.
In my case following question did the trick. All you have to do is make sure that you have enabled the appropriate sign-in method.

*

*Go to your Firebase console

*Select the chosen app

*(As of this date)

*Click on Authentication (on the left side)

*Select sign-in method

*Enable desired method

*Check this tutorial for complete details for Java code

Your code seems sound to me.


text:
Q: firefox js getSVGDocument().getElementsByClassName('myClass') broken? i have an embedded SVG, using js to change 20 path fill colors, all having the same class.
<script>
function svgMod(){
    //var links = document.getElementById("tornado5").getSVGDocument().
    //    getElementsByClassName('SVGlogo');
    var links = document.getElementById("tornado5").contentDocument.
        getElementsByClassName('SVGlogo');

    for (var i=0;i<links.length;i++) { links[i].style.fill="00ff00"; }
}
</script>
<object type="image/svg+xml" id="tornado5" data="bitmaps/frames/tornado2.svg">
</object>        <!-- cant use img -->
<button onclick="svgMod();" >Click to change</button>

It works in Chrome, but not firefox.
ive tried both contentDocument and getSVGDocument(), but no help.  links.length is 20, even in firefox, so the problem seems to be in links[i].style.fill
any ideas?

A: Can you try changing this line:
for (var i=0;i<links.length;i++) { links[i].style.fill="00ff00"; }

to this:
for (var i=0; i < links.length; i++) {
    links[i].setAttribute("fill", "#00ff00");
}

OR
for (var i=0; i < links.length; i++) {
    links[i].style.fill = "#00ff00";
}

Hope this helps.


text:
Q: WCF Soap Service call without waiting to finish I have a webservice which I want to call from a client tool (C#).
The challange is to call the webservice, without waiting for it to end.
An asnyc call will result in killing the webservice instance / resulting the call not to end.
I can not use Threads or Task to call the webservice in the client on an async process.
Is there some other way to not wait for a webservice to end?
If needed, I don't need a callback from the webservice.


text:
Q: modifying every other element's class inside while loop <?php
    $homePosts = new WP_Query(array(
        'posts_per_page' => 5
    ));

    while ($homePosts->have_posts()) {
      $homePosts->the_post(); ?>

            <?php the_title(); ?>
            <?php the_content(); ?>

<?php } wp_reset_postdata(); ?>

The above code is part of my front-page.php. I am trying to modify the class that is in
, so that the 1st, 3rd, and 5th sections have class='align-left' and the 2nd, and 4th sections have class='align-right'.
What would be the best approach to modify the class values within a WordPress loop? Would I need to write my own function in functions.php? Use jQuery? Is there a WP function that can help with this?

A: <?php
$homePosts = new WP_Query(array(
    'posts_per_page' => 5
));

$count = 1;

while ($homePosts->have_posts()) {
  $homePosts->the_post();

    if ( $count % 2 == 0 ) {
        $class = 'right';
    } else {
        $class = 'left';
    }

?>

<section class="align-<?php echo $class; ?>" >

        <?php the_title(); ?>
        <?php the_content(); ?>

<?php
$count++;

} wp_reset_postdata();

?>

You can try this code


text:
Q: What are the ranges to recognize different colors in RGB space? How do I programmatically determine whether or not a given pixel is yellow? Or red? Or another color?
Red is usually (255,0,0) in the RGB space, but we also know that (230,0,0) will also appear red.
Is there any standard which splits the RGB space into, say, the eight major colors - red, green, blue, yellow, magenta, cyan, black, and white?

A: Determining that in RGB can be complicated, but you can convert a RGB value into HSV, a format that represents colors by Hue, Saturation and Value. This is the system used to pick specific colors in software like Photoshop.
In this system all colors of the spectrum are represented in a single floating pointer number (Hue) that ranges from 0 to 360 degrees, the other 2 numbers only modify this color (tell if it's grayer or brighter).

This makes it easy to compare colors, as you can see on this image every primary color in both the RGB and CMYK systems are exactly 60 degrees apart.
Here you can easily tell that anything between 30 and 90 is a tone of yellow, anything between 330 (or -30) and 30 is a tone of red and so on.
You can even be more specific and determine ranges for tones of orange, purple, and other colors that are not primary.
About black and white, you can determine if a color appears black by checking if it's Value is low, say less than 0.1 for instance (it ranges from 0 to 1), and if it's white if you find the combination of high Value (bigger than 0.9 for instance) and low Saturation (lower than 0.1 for instance). There are no exact numbers of course, so you will have to decide for yourself when a very dark or very bright color becomes black or white.

A: In the RGB color model you have three channels reg, green and blue with values ranging from 0 - 255 (you knew that!).
To cover the whole spectrum you combine the three channels with a certain amount of value options.
So if you have x amount value options for each channel, you'll get x * x * x = x^3 color values.
For two options e.g. 0 and 255 you get 2^3 = 8 colors.
For six options, which constitute five (= 6 - 1) segments, you have the values
0 * (255 / 5), 1 * (255 / 5), 2 * (255 / 5), 3 * (255 / 5), 4 * (255 / 5), 5 * (255 / 5)
which makes 6^3 = 216 colors, which you can see as an example here.
The range above showed you how to build your one dimensional array for one channel. Since the three channels are the same, you can use it for all three channels.
With this you build your two-dimensional array:
0, 0, 0
51, 0, 0
102, 0, 0


text:
Q: How can I get the graphical output from another program? I'm trying to build my own remote desktop which can be accessed by the browser. My first idea was building a server (with python I would use flask) and including the graphical output of the OS into my html page. Because I thought that that would be difficult/not possible my next plan is to get just the graphical output of one program which I started from the server.
Please tell me how I could do this or how I could start with this project.

A: This is a daunting task, but I guess this procedure would be a good start for a prototype.

*

*Capture the display using ffmpeg:
Capturing and streaming with ffmpeg while displaying locally

*Create a route to view this stream: Streaming MOVIE Python flask

*Listen to click/keyboard events on the page and relay them back to source, apply these interactions using a input driver


text:
Q: How to cleanly remove MacPorts I'd like to cleanly remove all changes made by MacPorts as well as MacPorts itself, to try my luck with homebrew. How can I do that?

A: The MacPort documentation advises to use your Terminal and type:
sudo port -fp uninstall installed
and with this command, all remaining items will be deleted:
sudo rm -rf /opt/local
sudo rm -rf /Applications/DarwinPorts
sudo rm -rf /Applications/MacPorts
sudo rm -rf /Library/LaunchDaemons/org.macports.*
sudo rm -rf /Library/Receipts/DarwinPorts*.pkg
sudo rm -rf /Library/Receipts/MacPorts*.pkg
sudo rm -rf /Library/StartupItems/DarwinPortsStartup
sudo rm -rf /Library/Tcl/darwinports1.0
sudo rm -rf /Library/Tcl/macports1.0
sudo rm -rf ~/.macports

Warning: Don't run a sudo command, especially a rm -rf one, unless you know what it's doing.


text:
Q: Let $E$ be a Banach space, prove that the sum of two closed subspaces is closed if one is finite dimensional Let $E$ be a Banach space and let $S$ and $T$ be closed subspaces, with dim$\space T<\infty$. Prove that $S+T$ is closed.
To prove that $S+T$ is closed I have to show that for any limit point $x$ of $S+T$, $x \in S+T$. So let $x$ be a limit point that subspace. Then, there is a sequence $\{x_n\}_{n \in \mathbb N} \subset S+T$ : $x_n \rightarrow x$. $x_n \in S+T \space \forall \space n \in \mathbb N$. This means that $x_n=s_n+t_n$ with $s_n \in S$ and $t_n \in T$ $\forall \space n \in \mathbb N$. Well, I couldn't go further than this. $\{s_n\}_{n \in \mathbb N}$ and $\{t_n\}_{n \in \mathbb N}$ are sequences in $S$ and $T$ respectively. I would like to prove that both of them converge to some points $s$ and $t$, for if this is the case, the hypothesis would assure $s \in S$ and $t \in T$. Then, I would have to prove that $x=lim x_n=lim s_n+t_n=lim s_n+limt_n=s+t$ and from all the previous steps I would conclude $x \in S+T$. $$$$Maybe I could start by proving that $\{t_n\}_{n \in \mathbb N}$ is convergent. But I don't see why this is true, I've tried to prove that $\{t_n\}_{n \in \mathbb N}$ is a Cauchy sequence (in a Banach space this would imply that the sequence converges) but I couldn't.

A: One way to do this is as follows : $E/S$ is a Banach space, and the image of $T$, $\pi(T)$, in the quotient is a finite dimensional subspace of $E/S$. Hence, $\pi(T)$ is closed, and so
$$
S+T = \pi^{-1}(\pi(T))
$$
is closed in $E$
Added : Here is another approach - by induction on $dim(T)$, we can assume without loss of generality that $dim(T) = 1$. So let $z \in T$ be non-zero, so we are now looking at
$$
S+T = \{s + \alpha z : s \in S, \alpha \in \mathbb{K}\}
$$
By the Hahn-Banach theorem, there is a continuous linear functional on $E$ such that
$$
f(s) = 0 \quad\forall s\in S, \text{ and } f(z) =1
$$
So if $x_n = s_n + \alpha_nz \to x$, then
$$
\alpha_n = f(x_n) \to f(x)
$$
Hence,
$$
s_n = x_n - \alpha_nz\to x-f(x)z
$$
Since $S$ is closed, $s:= x-f(x)z\in S$, and hence
$$
x = s+f(x)z \in S+T
$$

A: if Y1 and Y2 are closed subspaces of X(Banach space , Y2 is finite dimensional the Y1+Y2 is closed  )
Note: if X is not Banach then also its TRUE as we can get X'(Banach) such that X is contained in X'


text:
Q: Match all string followed by asterisk Basically I'm creating a simple Interpreter for our compiler course. Of course this is not a homework-type question.
Anything that is followed by an asterisks is considered a comment provided that it is not part of the string. I have an escape character in my Interpreter which are brackets.
These are sample syntax for my interpreter
* hello world
OUTPUT: "This is asterisk [*]" * outputs string
OUTPUT: "This is asterisk *"  * outputs string produces syntax error
x = "[*]" & "hello" & "[*]*]" this is already comment which produces syntax error

when I try to run this Regex
[^\[]\*.*

It matches with the following:
* hello world
 * outputs string
 *"  * outputs string produces syntax error
]*]" this is already comment which produces syntax error

My question is, why did the regex "eats" one character before? Wherein I already need
* hello world
* outputs string
*"  * outputs string produces syntax error
*]" this is already comment which produces syntax error

A: You need to use zero width assertions to stop capturing the condition you just want to match, and
not "eat" :
(?<=[^\[])\*.*
(?<=REGEX_CONDITION) ensures that matching is done, but the matched part ( NOT A "[" in your case) is not included in the matched result.
Demo : http://regexr.com?32b99
Edit: to make it fully working, I just added or condition on it
(?<=[^\[])\*.*|^\*.*

A: Try using groups and use the group value as in [^\[](\*.*)


text:
Q: Wrong value while doing Binary Search using Recursion in java I am trying to implement binary search using recursion but i am not getting the correct results as expected. Here's the code:
import java.util.*;
class BinarySearchRecursion{

    static private int searchNum(int[] array, int item){
        if(array.length >=2){
            int remainder = array.length%2;
            int splitSize = array.length/2;
            if(remainder==0){
                if(item> array[splitSize-1]){
                    int num = searchNum(Arrays.copyOfRange(array,splitSize,array.length), item);
                    return num;
                }else{
                    int num = searchNum(Arrays.copyOfRange(array,0,splitSize), item);
                    return num;
                }
            }else{
                if(array[splitSize]== item)
                    return splitSize;

                if(item> array[splitSize-1]){
                    int num = searchNum(Arrays.copyOfRange(array,splitSize,array.length), item);
                    return num;
                }else{
                    int num = searchNum(Arrays.copyOfRange(array,0,splitSize), item);
                    return num;
                }
            }
            //System.out.println(splitSize);
        }else{
            if(array[0] == item){
                System.out.println("Item exist");
                return item;
            }
            else
                return -1;
        }
        //return -1;
    }

    public static void main(String... args){
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        int index = searchNum(arr, 89);
        if(index != -1){
            System.out.println("Number exist: "+ Integer.valueOf(index));
        }
        else
            System.out.println("Number does not exist in the given list.");
    }
}

I am not getting the correct items, like if i search for 8 it give me value 2,etc. What i am doing wrong here?

A: You are trying to search for the index of a given number in the array, but since your recursive method keeps passing sub-arrays to the recursive calls, the indices keep changing.
For example, when you call
searchNum(Arrays.copyOfRange(array,splitSize,array.length), item)

Index splitSize of the current array will become index 0 of the new array passed to searchNum().
You should always pass the original (full) array to the recursive calls, and in addition you should pass the first and last indices of the relevant range.
Another error in your code is in the if(array[0] == item) condition, where you return the item value instead of the index of that item.
Other than that, you probably don't have to write separate logic for the case of odd vs. even range of the array.


text:
Q: What official connection is there, if any, between "Sabrina the Teen-Age Witch", and "Wendy the Good Little Witch"? What official connection is there, if any, between "Sabrina the Teen-Age Witch" and "Wendy the Good Little Witch"?
Why do I think there's some connection?

*

*They're both originally comic characters.

*They arrive within a decade of each other: Wendy in May 1954, Sabrina in Oct. 1962.

*They're both blonde witch girls.

*They live with their aunts who are more hag-like witches, and the aunts' names all end in "l_a", are two syllables long, and mostly 5 letters long.

*

*Sabrina: Zelda, Hilda

*Wendy: Thelma, Velma and Zelma.

A: There is no official connection
Given that the connections you establish are original traits of both characters, we can assume that Wendy was not given any of these traits, in connection with Sabrina; Sabrina was not created for almost a decade.
I can not find any reference to a connection, in the creation of Sabrina Spellman; yes, they do have similarities, but there does not appear to be any official recognition of any form, connecting Sabrina to Wendy.
One may speculate that Wendy was the influence for Sabrina
I would speculate that if Sabrina was created with influence from Wendy, admitting so would be a very unwise move by the creators. The respective characters are creations of two companies that are very much in competition with each other. When you consider that the character "Sabrina Spellman" has been one of the most (if not, the most) popular characters to come out of the Archie series; she has already had her own live action TV series, and with the actual Archie live action taking off, is slated to get another one.
Even if the creators came out and admitted influence, today, they could be opening themselves up to a very expensive lawsuit; so I do not think we will ever know, for sure. They do not appear to be related, but there is good reason for a lack of evidence to say that they are.
Bonus fact: Wendy is a creation of Harvey comics. Harvey is the name of Sabrina's on-again-off-again love interest, and ultimately, her true love (at least, as far as the TV show went. I only really watched the TV show. Sorry, not sorry.)


text:
Q: Need help correcting a Regex pattern I did I wanted to extract specific data from a data string.
This is the data string
** Case Description:
- Xyz Xyz

This is the regex pattern I used
Case Description:\n(.+)

This is the output I am getting
- help with the paperwork

How can I cancel out the "-"

A: You can use
Case Description:\n\s*-\s*(.+)

See the regex demo.
I'd recommend to use a more regex-friendly terminology since regex does not "cancel out" anything, regex either matches or does not match a piece of or the whole text.
In your case, you are matching Case description:, then a newline (line feed) char, and capture into Group 1 any one or more chars other than line break chars as many as possible. That means, you captured the hyphen and spaces that the line starts with.
Thus, what you need is match (consume) the hyphen and spaces without capturing them, that is what the suggested pattern does.


text:
Q: How to get the crossvalidated prediction for each observation in Random Forest classification problem in python? I would like to understand, how I can get the predicted value for each observation in a dataset through cross validation in python RandomForestClassifier.
I'm using code as below.
I wanted to understand if there was any more efficient way of  doing this? Including tuning the parameters for the trees. Please let me know.
X=data.predictors[:150]
y=data.target[:150]
rfc = RandomForestClassifier()
y_pred = cross_val_predict(rfc, X, Y, cv=10)

A: I think you need to do it in 2 steps, first use gridsearchcv to tune your hyper parameters, for example:
import seaborn as sns
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_predict, StratifiedKFold, GridSearchCV

iris = sns.load_dataset('iris')
X=iris.iloc[:,:4]
y=(iris['species'] == "versicolor").astype('int')

rfc = RandomForestClassifier(random_state=77)
skf = StratifiedKFold(n_splits=10,random_state=88,shuffle=True)

model_params = {
    'max_features': [1,2,3],
    'min_samples_split': [2, 4, 6]
}

clf = GridSearchCV(rfc, model_params,cv=skf)
clf.fit(X,y)

We find the parameter with the best result:
best_p = np.argmin(clf.cv_results_['rank_test_score'])
param = clf.cv_results_['params'][best_p]
param

{'max_features': 2, 'min_samples_split': 6}

Redefine the classifier and use cross_val_predict:
rfc = RandomForestClassifier(random_state=77,max_features=param['max_features'],
                             min_samples_split=param['min_samples_split'])
cross_val_predict(rfc, X, y, cv=skf)


text:
Q: Scrollview not working in fragment I have a sign up fragment whose root layout is ScrollView and the child is LinearLayout. I have edit texts inside that LinearLayout. But when I click on an EditText and try to scroll the view, it doesn't work.
To open this fragment I have to click on signup view at login fragment.
Here is my SignUpFragment.java
public class SignUpFragment extends Fragment {

    private EditText etFirstName, etLastName, etEmail, etPassword, etcity, etMobile;
    private String firstName, lastName, email, password, city, mobile;

    private Button proceed;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_sign_up, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        findViews(view);

        proceed.setOnClickListener(v -> {
            getStrings();
            if (checkFields()) {
                Bundle bundle = new Bundle();
                bundle.putString("firstName", firstName);
                bundle.putString("lastName", lastName);
                bundle.putString("email", email);
                bundle.putString("password", password);
                bundle.putString("mobile", mobile);
                bundle.putString("city", city);

                jumpToDeliverAddress(bundle);
            }
        });
    }

    private void jumpToDeliverAddress(Bundle bundle) {
        Fragment fragment = new DeliveryAddressFragment();
        FragmentManager fragmentManager = getFragmentManager();
        fragment.setArguments(bundle);
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    private boolean checkFields() {
        if (firstName.trim().isEmpty()) {
            etFirstName.setError("Please enter a valid first name");
            return false;
        }
        if (lastName.trim().isEmpty()) {
            etLastName.setError("Please enter a valid last name");
            return false;
        }
        if (email.trim().isEmpty() || (!isEmailValid())) {
            etEmail.setError("Please enter a valid email");
            return false;
        }
        if (password.trim().length() < 6) {
            etPassword.setError("Password must contain 6 digits");
            return false;
        }
        if (mobile.trim().length() != 10) {
            etMobile.setError("Please enter a valid mobile number");
            return false;
        }
        if (city.trim().isEmpty()) {
            etcity.setError("Please enter a valid city");
            return false;
        }

        return true;
    }

    private boolean isEmailValid() {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void getStrings() {
        firstName = Constants.getString(etFirstName);
        lastName = Constants.getString(etLastName);
        email = Constants.getString(etEmail);
        password = Constants.getString(etPassword);
        city = Constants.getString(etcity);
        mobile = Constants.getString(etMobile);
    }

    private void findViews(View view) {
        etFirstName = view.findViewById(R.id.firstName);
        etLastName = view.findViewById(R.id.lastName);
        etEmail = view.findViewById(R.id.email);
        etPassword = view.findViewById(R.id.password_edittext);
        etcity = view.findViewById(R.id.city);
        etMobile = view.findViewById(R.id.mobile_number_edittext);
        proceed = view.findViewById(R.id.proceed);
    }
}

And the fragment_sign_up.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".fragments.SignUpFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/firstName"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="First name"
                android:inputType="textPersonName" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/lastName"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Last name"
                android:inputType="textPersonName" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Email"
                android:inputType="textEmailAddress" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/password_edittext"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Password"
                android:inputType="textPassword"
                android:maxLength="10" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/mobile_number_edittext"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Mobile number"
                android:inputType="number"
                android:maxLength="10" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/city"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="@string/city" />

        </android.support.design.widget.TextInputLayout>

        <Button
            android:id="@+id/proceed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="Proceed to add delivery address" />
    </LinearLayout>
</ScrollView>

Please note that, currently, my flow is this:-
Mainactivity loads LoginFragment -> click on signup -> signUpfragment opens.
If I directly open signup fragment from MainActivity, scroll works fine.
MainActivity.java
public class MainActivity extends AppCompatActivity implements
        NavigationView.OnNavigationItemSelectedListener, DrawerLocker {
public static SharedPreferences sharedPreferences;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle toggle;
private Toolbar toolbar;
private VolleyCallback volleyCallback;

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

    drawerLayout = findViewById(R.id.drawer_layout);
    navigationView = findViewById(R.id.nav_view);
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    initDrawer();

    if (checkToken())
        jumpToHome();
    else
        jumpToLogin();

}

private void jumpToLogin() {
    Fragment loginFragment = new LoginFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container_body, loginFragment);
    fragmentTransaction.commit();

}

private void jumpToHome() {
    Fragment homeFragment = new HomeFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container_body, homeFragment);
    fragmentTransaction.commit();

}

private boolean checkToken() {
    APICall apiCall = new APICall(volleyCallback, this);
    String token = apiCall.getTokenFromLocal(this);
    return !token.isEmpty();

}

private void initDrawer() {

    toggle = new ActionBarDrawerToggle(this,
            drawerLayout,
            toolbar,
            R.string.drawer_open,
            R.string.drawer_close);

    toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            drawerLayout.openDrawer(GravityCompat.START);
        }
    });

    drawerLayout.addDrawerListener(toggle);
    toggle.syncState();

    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    drawerLayout = findViewById(R.id.drawer_layout);
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    int id = item.getItemId();
    if (id == R.id.nav_manage_address)
        jumpToManageAddress();
    else if (id == R.id.nav_book_order)
        jumpToBookOrder();

    drawerLayout.closeDrawer(GravityCompat.START);
    return true;
}

private void jumpToBookOrder() {
    Fragment bookOrderFragment = new BookOrderFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container_body, bookOrderFragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

private void jumpToManageAddress() {
    Fragment manageAddressFragment = new NewAddressFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container_body, manageAddressFragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

@Override
public void setDrawerLocked(boolean enabled) {
//        if (enabled) {
//            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
////            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
////                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
//            toggle.setDrawerIndicatorEnabled(false);
//        } else {
//            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
////            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//            toggle.setDrawerIndicatorEnabled(true);
//        }
    }
}

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

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff">
<LinearLayout
    android:id="@+id/container_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:elevation="5dp"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:theme="@style/MyToolbarStyle"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/container_body"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

    </FrameLayout>

</LinearLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/nav_items">

    <RelativeLayout
        android:id="@+id/expandable_Frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </RelativeLayout>

</android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

LoginFragment.java
public class LoginFragment extends Fragment {

private Button loginButton;
private VolleyCallback volleyCallback;
private EditText mobileNumber, password;
private TextView signup;

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // Inflate the layout for this fragment
//        ((MainActivity) getActivity()).setDrawerLocked(true);

    return inflater.inflate(R.layout.fragment_login, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mobileNumber = view.findViewById(R.id.mobile_number_edittext);
    loginButton = view.findViewById(R.id.login);
    password = view.findViewById(R.id.password_edittext);
    signup = view.findViewById(R.id.signup);

//        ((MainActivity) getActivity()).getSupportActionBar().setTitle("Login");

    signup.setOnClickListener(v -> jumpToSignup());

    loginButton.setOnClickListener(v -> {
        if (checkLength(mobileNumber, 10) && checkLength(password, 6)) {

            apiCallForLogin(Constants.getString(mobileNumber), Constants.getString(password));
        } else {
            if (!checkLength(mobileNumber, 10))
                mobileNumber.setError("Enter a valid mobile number");
            else
                password.setError("Password should contain atleast 6 digits");
        }
    });
}

private void jumpToSignup() {
    Fragment fragment = new SignUpFragment();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container_body, fragment);
//        fragmentTransaction.addToBackStack(null);

    fragmentTransaction.commit();
}

private void apiCallForLogin(String mobileNumber, String password) {
    APICall apiCall = new APICall(volleyCallback, getContext());
    apiCall.addParams("mobile", mobileNumber);
    apiCall.addParams("password", password);

}
}

fragment_login.xml
   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.LoginFragment">

<android.support.design.widget.TextInputLayout
    android:id="@+id/mobile_number_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@id/password_layout"
    android:layout_centerHorizontal="true">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/mobile_number_edittext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/enter_your_mobile_number"
        android:inputType="number"
        android:maxLength="10"
        android:minEms="10" />
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:id="@+id/password_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/password_edittext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Enter Password"
        android:inputType="textPassword"
        android:maxLength="10"
        android:minEms="10" />
</android.support.design.widget.TextInputLayout>

<Button
    android:id="@+id/login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/password_layout"
    android:layout_centerHorizontal="true"
    android:text="Login" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="52dp"
    android:text="@string/new_user_signup_here"
    android:textColor="@color/black"
    android:textSize="15sp"
    android:id="@+id/signup"
    />

</RelativeLayout>

A: Its hard to understand the exact problem that you are having without seeing your MainActivity code. However, based on some common problems, I would suggest to use a NestedScrollView here in this case.
However, you might consider wrapping the ScrollView with an extra LinearLayout. So the final layout will be looking something like the following.
<LinearLayout>
    <ScrollView>
        <LinearLayout>
            <!-- Other views -->
        <LinearLayout/>
    <ScrollView/>
<LinearLayout/>


text:
Q: Entity Framework and deep sync I need to get update local DB to have actual data from external resource.
Model has the following structure:
public class Invoice
{
    public string Id { get; set; }
    public string InvoiceNumber { get; set; }
    public DateTime InvoiceDate { get; set; }
    public DateTime DueDate { get; set; }
    public decimal Amount { get; set; }
    public DateTime CreatedTime { get; set; }
    public DateTime UpdatedTime { get; set; }

    public string CustomerId { get; set; }
    public virtual Customer Customer { get; set; }

    private ICollection<InvoiceLineItem> _invoiceLineItems;
    public virtual ICollection<InvoiceLineItem> InvoiceLineItems { get => _invoiceLineItems ??= new List<InvoiceLineItem>(); protected set => _invoiceLineItems = value; }

}

and related entity:
public class InvoiceLineItem
{
    public int Quantity { get; set; }
    public decimal? Amount { get; set; }
    public decimal? Price { get; set; }
    public string TaxCode { get; set; }

    public string InvoiceId { get; set; }
    public virtual Invoice Invoice { get; set; }
}

so, as we can see, one invoice can have zero, one or many items inside
First time I get from external resource invoice with its items. It's easy:
var newRecurringInvoice = _mapper.Map<Invoice>(recurringInvoiceRemote);
_dataContext.RecurringInvoices.Add(newRecurringInvoice);

But when record with such Id already exists, it's a little complex.
Possible situations:

*

*new item is added to remote source and we need to add its locally

*item is deleted from remote source and we need to remove its locally

*item without changes (identically on both resources)

*item with the same Id is changed (one or several fields) and we need to update locally

How to do it? Is it enough for do it only
localRecurringInvoice = _mapper.Map<InvoiceDto, Invoice>(recurringInvoiceRemote, localRecurringInvoice);
_dataContext.RecurringInvoices.Update(localRecurringInvoice);

or need to do carefully for every case? How to do it better? As I understand, it's standard common situation
ADDED #1
full code is in loop, looks like:
        foreach (var recurringInvoiceRemote in remoteRecurringInvoices)
        {
            var localRecurringInvoice = localExistingRecurringInvoices.Where(a => a.Id == recurringInvoiceRemote.Id).FirstOrDefault();
            if (localRecurringInvoice != null)
            {
                // update existing
                localRecurringInvoice = _mapper.Map<RecurringInvoiceDto, RecurringInvoice>(recurringInvoiceRemote, localRecurringInvoice);
                _dataContext.RecurringInvoices.Update(localRecurringInvoice);
            }
            else
            {
                // add new
                var newRecurringInvoice = _mapper.Map<RecurringInvoice>(recurringInvoiceRemote);
                _dataContext.RecurringInvoices.Add(newRecurringInvoice);
            }
        }


text:
Q: Как добавить числа с++ Нужно сгенерировать числа, и вывести те, которые больше 0 и меньше 1, с этим проблем нет, но их ещё нужно добавить (т.е допустим вывело 0.5 и 0.9, нужно найти их суму), а это я не понимаю как реализовать, вот сам код (И ещё нужно как-то сделать, чтобы пользователь сам вводил кол-во генерируемых чисел, пока это 50, но я тоже не понимаю как это реализовать)
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main() {

    srand(time(0));

    const int size = 50;
    double array[size];

    for (int i = 0; i < size; ++i)
        array[i] = (rand() % 380 - 190) / 10.0;

    for (int i = 0; i < size; ++i)
        cout << array[i] << " ";
    cout << endl;

    for (int i = 0; i < size; i++) {
        if (array[i] >= 0 && array[i] < 1) {
            cout << endl;
            cout << "Numbers between 0 and 1 --> " << array[i];
            cout << endl;
            //cout << "Sum --> " << array[i] + array[i];
            //cout << endl;
        }
    }

    cin.get();
    return 0;
}

A:
И ещё нужно как-то сделать, чтобы пользователь сам вводил кол-во
генерируемых чисел, пока это 50, но я тоже не понимаю как это
реализовать

выводите текст через std::cout <<
получаете от пользователя ввод через std::cin >>
вам разве этого не давали на занятиях?
массив в этом случае придётся делать динамическим - выделять под него память
вместо:
double array[size];

надо будет сделать:
double *array = new double[size];

но их ещё нужно добавить (т.е допустим вывело 0.5 и 0.9, нужно найти
их суму),

если я правильно понял русский, то требуется сделать
double sum = 0;

for (int i = 0; i < size; i++) {
    if (array[i] >= 0.5 && array[i] < 0.9) {
        sum += array[i];
    }
}

P.S.
почему такие вопросы чаще всего в воскресенье возникают?

A: Массив тут вообще не нужен. А когда пишете код, сначала напишите саму логику, а потом добавьте все выводы, которые захотите (эти сообщения на консоль далеко не самая важная часть кода). Код без сообщений может выглядеть:
int size;
double sum = 0, el;
cin >> size;

for (int i = 0; i < size; ++i) {
    cin >> el;
    if (el > 0 && el < 1)
        sum += el;
}
cout << el;


text:
Q: How do I run individual testcases in a cppunit runner? The following piece of code gets all my tests and their testcases and runs them. I am trying to get a few individual testcases and get them alone to run. How do I achieve that?
CPPUNIT_NS::TestFactoryRegistry &reg = CPPUNIT_NS::TestFactoryRegistry::getRegistry("");
CPPUNIT_NS::TextUi::TestRunner runner;   //the runner
runner.addTest(reg.makeTest());
bool wasSucessful = runner.run();

I read that you can iterater through the testcases by getting the list using getTests(), but I was not sure how to do that.
Can someone please help me?
EDIT1:
I would like to run individual testcases from a test(which has multiple testcases). I would like to run run just one testcase.
For example,
We could have a Test, named "Mathematical Operations" and that has multiple test cases like, "Mathematical Operations.TestAdd" and "Mathematical Operations.TestSubtract". I want to be able to run just "TestAdd" and not run the whole Test  of "Mathematical Operations".
Thanks!

A: The ask mentioned in this question is a duplicate of How to run subset of unit tests in CPPUnit by selecting them at run-time?
This answer on the question does provide a solution.


text:
Q: JSoup - Number of Table Rows per Table Body I have the following html table which i am trying to parse using JSoup.
I am parsing it as follows;
Elements table = document.select("table[class=MsoNormalTable]");
Elements tbody = table.select("tbody");
Elements tr = tbody.select("tr");
Elements td = tr.select("td");
Elements tableHeaders = td.select("p[class=MsoNormal]");

How am I able to find out, per table body how many table rows there are?

€ SUPR:

Available on TW

Ticker

Coupon

Maturity Date

ISIN

ISIN Location

06/05/2014

OSEOFI

1%

25/10/2019

FR0011898196

FR

07/05/2014

ESM

0.875%

15/10/2019

EU000A1U9829

DE

£ SUPR:

Available on TW

Ticker

Coupon

Maturity Date

ISIN

XS ISIN Location

06/05/2014

FMSWER

FRN

09/05/2016

 DE000A11QBT6

DE

$ SUPR:

Available on TW

Ticker

Coupon

Maturity Date

ISIN

ISIN Location

Benchmark

07/05/2014

MP

3.050

14/05/2024

US563469UD51

CA

US912828WJ58

08/05/2014

IBRD

0.976

09/05/2019

XS1055866559

XS

3M LIBOR

09/05/2014

AUST

0.000

07/05/2015

XS1066373421

AT

US912828C814

09/05/2014

BNG

FRN

15/05/2014

XS1068089025

NL

3M LIBOR

A: Just use size method. The document.select("table[class=MsoNormalTable] tbody") statment gives all the tbody and and form that if you select tr and check size you'll get the number.
Iterate over each tbody and get tr size like
Elements tables = document.select("table[class=MsoNormalTable] tbody");

int index = 0;
for(Element table : tables){
    System.out.println("Table : " + (++index) + " has " + table.select("tr").size() + " rows.");
}

A: According to the JavaDoc, the select() "Find[s] matching elements within this element list", which indicates the return is limited to the DOM elements under the element(s) you are searching in (like a limit), and the size() returns the "size in interface Collection".  This seems to indicate that using select() on a given DOM element followed by the size() on the returns Elements would give you the size/count of all the Elements returned by the select.  You are doing a select of all tables that have the class of 'MsoNormal', which from what I can see in your example are 3 tables.  You then get the tbodys, followed by the trs, followed by tds.  You are essentially getting all tables (at least the ones you are showing), followed by all tbodys, followed by all trs, etc, etc.  If you want to limit the count to ONLY the trs in a single table, then you will need to limit the things are are searching in (i.e. the tables) to the single table you want to count.
If that is not possible, then get the List<Element>s from the table select, loop through each one, then use the Elements select to limit the search to only that one Element.  It's really just a matter of reading the API and figuring out what you need to do.  Do you want to search on the Elements you returned or the Elements individually?


text:
Q: captivate 7 does not run the exe on windows xp We are using adobe captivate 7 installed (trail version ) in a windows 7 with SP1 computer . when we publish it and run exe in the windows XP (home ) under administrator we get  following error even if the flash player is updated.
The installed version of Flash Player is not the latest.  The latest Flash Player version has been installed successfully without affecting your existing Flash Player installation.  Double-click the EXE again to run it.

when we click OK it disappears and when we run the exe for the next time it runs . whereas if we run the same exe in the other user (not having admin permission ) also gets the same error and after clicking OK if we run exe again it shows the same error message again and again .
we have tested in win 7, win 8 , win server 2012 it works fine.
Please suggest me how to prevent it .


text:
Q: How to calculate signifiance on an A/B test on revenue I am having trouble calculating the statistical significance of a split test based on revenue. Most online calculators only look at the number of visitors and the number of conversions, outputting a p-value (and thus measuring the significance). I want to take this to the next level and measure if a test is significant based on revenue, not just the number of purchases.
Here is an example calculator using the "traditional" method: http://visualwebsiteoptimizer.com/ab-split-significance-calculator/
Here' an example to try to illustrate this a bit better:
Pretend you have baseball card store, and you are testing a new version of your website. Version A is the control, Version B is the variation.
With normal split testing, you would measure the number of people who visit both websites, and the number of purchases.
But what if you had more data? Instead of just tracking wether or not a purchase was made, what if you knew how much each customer spent, and what version of the website they saw? Over the course of a month you track purchases from customers depending on the variation they saw. At the end of the month, you want to know - with 95%+ confidence - if the new version of the website resulted in more revenue, not just the number of sales.
Is this possible to calculate in excel? Here's some sample data to use:
Version A
2000 visitors, 500 sales: $
123
115
103
177
188
120
114
189
134
80
126
142
144
108
141
139
114
119
181
82
154
114
128
166
163
116
112
180
122
159
109
185
126
178
40
161
101
175
184
150
180
174
159
132
166
154
125
151
126
157
111
210
152
151
130
107
118
105
113
162
118
163
142
124
132
157
128
101
106
167
147
148
158
160
156
168
177
149
155
830
113
100
136
152
176
171
129
158
189
188
156
187
178
78
130
130
171
163
120
164
128
168
145
110
186
189
149
140
142
134
145
189
187
161
164
129
104
167
166
186
142
169
137
60
126
157
174
183
176
166
136
190
170
109
141
125
187
105
178
147
113
137
141
106
60
167
153
155
174
141
117
154
140
118
118
177
187
149
159
151
109
111
115
149
182
138
168
115
171
167
123
178
104
120
121
126
176
154
182
164
139
106
162
139
138
138
166
137
152
182
172
106
120
162
107
117
103
114
162
168
160
122
161
160
138
159
124
179
124
112
138
170
146
137
153
122
163
167
156
150
186
127
153
187
141
187
143
172
184
104
121
104
176
145
102
156
143
167
139
137
125
101
109
183
100
110
127
106
119
179
131
116
166
169
108
141
189
143
109
107
124
108
146
147
158
155
183
140
101
100
111
107
151
177
130
147
186
156
117
162
187
139
131
177
147
146
111
112
142
107
141
164
157
159
169
148
190
165
172
181
190
111
175
190
103
127
132
173
101
178
101
161
160
144
123
189
121
182
147
141
166
144
180
126
161
141
116
152
130
164
147
163
177
126
163
167
135
164
116
104
169
126
175
179
185
137
130
139
131
139
147
123
124
172
130
100
189
111
186
105
106
147
136
122
171
165
151
123
126
132
169
106
158
120
165
144
120
182
131
174
107
127
165
105
139
127
161
103
114
143
184
101
105
185
153
148
142
162
187
167
154
149
158
135
180
179
182
139
104
159
164
149
168
187
131
107
175
111
189
162
133
131
180
101
141
153
139
171
175
124
119
102
130
152
121
159
122
124
123
188
104
130
184
109
126
114
188
100
139
179
187
104
165
169
152
169
127
152
165
177
103
187
167
157
141
150
120
180
101
129
104
157
104
161
120
162
139
110
182
150
105
170
121
160
133
151
116
190
153
189
101
171
184
179
153
188
173
141
164
100
Version B
2,200 visitors, 510 sales: $
144
143
159
194
90
158
149
145
197
192
139
132
467
185
164
159
166
190
159
170
168
132
157
134
151
183
183
180
135
320
128
185
141
184
181
126
126
167
134
120
163
138
345
150
199
156
173
194
183
186
360
165
183
149
143
156
167
174
177
430
258
175
143
183
122
145
184
1029
170
183
126
146
165
193
157
154
199
192
145
199
129
156
157
173
125
127
182
164
159
182
147
126
160
184
193
133
154
127
183
125
189
151
192
182
178
169
189
132
157
142
310
147
158
164
196
155
135
167
146
167
123
172
198
129
135
176
131
120
124
166
157
280
149
165
146
158
128
199
147
198
149
153
157
154
133
195
198
385
192
195
123
158
199
146
163
183
164
173
130
187
168
123
196
120
176
179
197
150
173
161
150
187
193
195
192
164
130
194
180
124
142
180
152
125
186
181
166
181
187
159
127
125
130
179
134
143
148
154
139
161
162
161
147
133
160
143
126
127
130
160
133
156
168
194
164
120
130
168
188
127
141
127
171
150
162
189
163
177
160
145
197
176
134
142
124
137
166
197
188
191
193
178
121
162
134
175
199
146
157
147
127
151
159
140
125
163
197
187
165
155
137
163
139
136
181
151
148
176
178
153
162
151
164
199
147
161
148
185
132
141
157
134
158
145
150
127
140
165
138
163
182
176
173
173
184
196
174
121
137
121
159
145
139
145
191
152
178
163
171
198
175
145
192
126
159
165
128
161
129
134
192
136
175
132
176
144
159
147
131
138
188
134
132
193
183
166
176
170
136
146
139
151
197
173
161
121
194
150
179
120
174
196
139
137
140
148
161
195
157
174
197
193
156
156
183
168
192
146
170
120
145
151
134
173
182
172
167
134
145
132
182
178
158
156
168
170
167
195
159
181
177
126
152
142
134
131
176
139
190
162
195
139
193
172
169
153
184
172
167
154
147
124
141
156
169
146
142
168
147
163
143
154
175
179
175
127
157
129
190
189
175
159
146
183
183
164
154
167
162
156
145
151
181
121
140
145
158
183
185
166
122
136
189
121
191
136
166
192
134
195
153
168
146
133
144
123
162
181
125
181
196
182
165
196
146
168
138
146
144
179
152
149
134
195
158
135
129
189
177
142
137
199
144
193
170
122
184
194
130
146
213
394
128
394
231
495
201
120
90
50

A: For revenue it is a bit difficult. There is a similar question to yours here
https://stats.stackexchange.com/questions/72242/bootstrapping-do-i-need-to-remove-outliers-first
If you have large enough samples the CLT lets you just use the mean, $\mu$ and the standard error on the mean, $\sigma_\mu = \sigma / \sqrt{N}$. You can then calculate your 95% CL through the comparison of the two Gaussians formed by $\mu$ and $\sigma_\mu$ for each scenario in your split test.
This is a very stripped down answer and there are a lot of special cases to be considered. However, this is a fast way to get your answer in excel.


text:
Q: Python operator != isn't working as expected Does anyone know why this sample is not working? I have not used Python in years and wanted to test NOT operators. As far as I can remember this should work, I have checked online and it appears to be the correct format. Am I missing something?
Essentially it is just asking for an input of 1, 2 or 3. If the user enters those it will break out the loop. If they do not enter either 1, 2 or 3 it will print to screen and loop again. Currently it is only printing "Invalid input!" then looping not breaking.
while True:
    x = input("1, 2, or 3?\n")
    if x != 1 or x != 2 or x != 3:
        print("Invalid input!")
    else:
        break

I am using Python 3.6.4.

A: Well, this will be always true. if I type 1, it'll fail the first condition, but it'll pass the other two: x != 2 or x != 3. Any other number different than 1, 2 or 3 will also be true for all the conditions. There's no problem with the comparison operator.
I think you want to do something like:
x = int(input("1, 2, or 3?\n"))
if x not in [1, 2, 3]:
    print("Invalid input!")

The conversion of x to int is also important. Otherwise, the comparison of x with the numbers will be always false.


text:
Q: java main function public static void main() & public void main() What is the difference between these two?

A: The former is (potentially) an entry point method (if it has a String[] argument).  The latter is not.
The rule is that an entrypoint method must have the signature:
public static void main(String[])

If we ignore the question of "entrypointness", then the difference between a "static" method and a normal method is as follows:

*

*A normal method can only be invoked on a target object, but it can access the instance variables of the target object via explicit or implicit use of this.

*A static method is not invoked on a target object, and cannot access instance variables via this.

A: Static functions belong to the class (that is, they use no instance variables (object variables)).

A: public static void main(String[] args)

Because it uses the special 'main' name and is also static with string arguments, it is the entry point into your program.  It can be called like this
YourClass.main(new String[] {"hello"})

However, when you compile you program into a runnable .jar file java will automatically know to run this method.  It is the starting point of your program.
In the terminal you will run it like this

java -jar YourClass.jar hello

Other methods can also be made static
public static void myOtherFunction()

The difference here is that myOtherFunction() is NOT the starting point of the application but can be used anywhere in your application that you main need it, you also don't need an instance of a class to use it.
public void main()

Is a normal methods of a class It needs an instance to be able to use it.
YouClass me = new YouClass();
me.main();

Don't ever call any method main() without it being of the signature
public static void main(String[] args)

ie. the entry point of the application.  This could potentially be confusing for people reading your code.

A: Static means that the function does not need a class instance in order to be called.

A: It's simple: the former main is static (and p in lowercase ;-P)
And the meaning is obvious: ensuring the entrypoint exists before the rest, and tell the framework where the entrypoint is.

A: Actually static allows only one instance of he main function to be initialized. All static methods can be called without creating an instance of that class. Its global. Main is always delcared static.

A: varargs version:
public static void main(String... args) {

    for (String arg : args) {
        System.out.println("Argument: " + arg);
    }
}

Available since Java 5.


text:
Q: How do I add a local script file to the HTML of a WebBrowser control? This seems really dumb. I've tried a bunch of different ways and it's just not working. I have a WinForms app with a WebBrowser control. If I try with a raw html file on my desktop using the same src string, the src I put together works fine. But plugging the same stuff into the WebBrowser control won't work.
Here's my code:
HtmlElementCollection head = this.wbPreview.Document.GetElementsByTagName( "head" );
if (head != null)
{
    HtmlElement elm = this.webBrowserControl.Document.CreateElement("script");
    string mySource = Environment.CurrentDirectory + @"\MyScriptFile.js";
    elm.SetAttribute("src", mySource);
    elm.SetAttribute("type", "text/javascript");
    ((HtmlElement)head[0]).AppendChild(elm);
}

The WebBrowser doesn't get the script. However, if I change "mySource" to an external resource (via http://), it works fine!
Help!

A: Try adding file:// to the URL.

A: i came up on your post, while playing around with things following worked for me:
HtmlElementCollection head = webBrowser1.Document.GetElementsByTagName("head");
if (head != null)
{
    HtmlElement elm = webBrowser1.Document.CreateElement("script");
    elm.SetAttribute("type", "text/javascript");
    elm.InnerText = System.IO.File.ReadAllText(Environment.CurrentDirectory + @"\helperscripts.js");
    ((HtmlElement)head[0]).AppendChild(elm);
}

, so all methods of helperscript.js can be invoked using
webBrowser1.Document.InvokeScript("methodname");

, here as a reference for the script invoke: How to inject Javascript in WebBrowser control?
greetings

A: There is a long story about workarounds of that "security fix" from MS. New behavior was implemented starting from IE7. Take a look into "base" tag and IE Feature controls.
I did the following:
                    //TODO: if not mono
                var executableFilename = Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location);
                var keys = new[] { executableFilename, [vsname]+".vshost.exe" }; //check!

                Action<string, object, string> SetRegistryKeyOrFail =
                    (key, val, regStr) =>
                        {
                            var reg =
                                Registry.CurrentUser.CreateSubKey(regStr);
                            if (reg == null) throw new Exception("Failed registry: " + regStr);
                            reg.SetValue(key, val);
                        };

                foreach (var key in keys)
                {
                    SetRegistryKeyOrFail(key, 1, @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BLOCK_LMZ_IMG");
                    SetRegistryKeyOrFail(key, 0, @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BLOCK_LMZ_SCRIPT");
                }

A: This is because of security reasons. You need a webserver to do that, else you can access any file on a system which would be a big security hole.
In developement mode, you can set e.g on chrome:
chrome.exe --allow-file-access-from-files

And you will be able to run your code.


text:
Q: Security best pratices, how to deny rest api connections that don't belong to dedicated client Is there a way to handshake server/client?
Im aware of security tokens, but how often they should updated, and what should trigger that? Isn't calling DB to update tokens often a expensive operation? (i dont know how they work at all)
Can someone give me a hand on how should an implementation of that should work?
If not possible in react-native, nodejs and mysql, an explanation in in meta-code would be already helpfull.
Thanks!


text:
Q: undo ax.set_yticks([]) I use an existing script to plot a very specific data type. The script returns an ax object.
These ax objects are used to populate subplots in an new bigger main plot.
In the main script somewhere,
ax.set_yticks([])

is called. Usually this is wanted. For one of the individual plotting scripts I would like to simply undo this and have matplotlib set my y ticks automatically depending on the data just as if ax.set_yticks([]) had never been called.

A: you can store the tick locator before you call set_yticks([]) and restore it later
import matplotlib.pyplot as plt

ax = plt.gca()
ax.plot(range(10), range(10), 'ko')

#store the yticks locator
l = ax.yaxis.get_major_locator()

#hide ticks and display the figure
ax.set_yticks([])
plt.gcf().show()
raw_input('pause') # => no more yticks

#restore the tick locator to its originale state
ax.yaxis.set_major_locator(l)
plt.gcf().canvas.draw()  #refresh the plot to sow the yticks again

plt.show()


text:
Q: Jacobi-Trudi Identity - Enumerative Combinatorics The Jacobi-Trudi Identity states that:
Let $\lambda=(\lambda_1, \ldots ,\lambda_n)$ and $\mu=(\mu_1, \ldots ,\mu_n)\subseteq \lambda$.
Then, $s_{\lambda/\mu} = \det(h_{\lambda_i -\mu_j -i+j})^n_{i,j=1}$
where $h_0=1$ and $h_k=0$ for all $k<0$.
Is this theorem necessarily true? Can someone prove that the identity is indeed equal?

A: Hint:  It's simply just a pure application of theorem 2.7.1 stated in Enumerative Combinatorics Vol. 1. (Link here)

 Take $\alpha_j=\lambda_j+n-j$, $\beta_i=\mu_i+n-i$, $\gamma\to\infty$.


text:
Q: (True of False) $X,Y$ are discrete random variables
With $P(x=1)>0$ and $P(x=2)>0$. Suppose $P(y=1\mid x=1)=3/4$ and $P(y=2\mid x=2)=3/4$. Then $X$ and $Y$ cannot be independent.

My idea is to suppose it's independent, then $P(Y\cap X)=P(X)P(Y)$ and thus cancel with the denominator, then $P(Y_1)=P(Y_2)=3/4$, which is impossible.

A: If $\mathbb P(Y = 1 | X=1)$ does not depend on the condition $X=1$, then we should have $\mathbb P(Y=1 | X=1) = \mathbb P(Y=1) = 3/4$ and similarly $\mathbb P(Y=2 | X=2) = \mathbb P(Y=2) = 3/4$. But then $\mathbb P(Y \in \{ 1,2 \}) = \mathbb P(Y=1) + \mathbb P(Y=2) = 3/4 + 3/4 = 3/2$, contradicting the fact that $\mathbb P$ is a probability because probabilities are in the interval $[0,1]$.
You were on the right track with your $\mathbb P(Y \cap X) = \mathbb P(Y) \mathbb P(X)$ thing but watch out; you must compute probability of events (such as $\{ Y=1 \}$ or $\{Y \le 0 \}$) and not of variables (such as $\mathbb P(Y)$, which doesn't make sense). That is probably where you got stuck, I assume. It doesn't make sense to "intersect variables", but intersecting events (which are sets) makes sense. Note that $\mathbb P(A \cap B) = \mathbb P(A) \mathbb P(B)$ is equivalent to
$$
\mathbb P( A | B) = \frac{\mathbb P( A \cap B ) }{\mathbb P(B)} = \mathbb P(A).
$$
Hope that helps,


text:
Q: How do I kill the boss of Grape Garden? This boss completely confounds me. The only enemies I have seen give me the High Jump ability, which seems rather useless, and the boss keeps removing the clouds I am standing on, so I usually fall to my death if he doesn't kill me by running into me repeatedly.
I haven't really figured out what to do here, other than to keep floating upward, which doesn't really gain me much, because I am not actually hurting the boss.
What do I need to do to kill him?

A: In the first stage of this fight, Kracko is actually invincible. The Star Men are actually meant as a hint for what you need to do - keep climbing up! Kracko will be persistently attacking you and removing platforms, so High Jump is the safest way to make the climb, by continually jumping sky high. Don't wait for Kracko, just keep climbing. Eventually, you'll come across a more decorated platform with clouds, at which point Kracko will get his life bar and the real battle begins.
The climb is possible to accomplish with other skills, but not recommended. Your standard flight is not very fast and Kracko can easily knock you into a pit, or simply make you lose your ability into a pit. If you are insistent, though, Tornado, Hammer, and Throw all make good choices. You'll have to keep an eye on Kracko's movements, and generally do your best to stay on the opposite side of the screen as him.

In the real fight, Kracko isn't too hard, especially with High Jump. The ammo for shooting at him comes from the occasional Star Man that he'll produce (which, of course, you'll probably just use to regain High Jump if you lose it). His other means of attack are mostly to move across the screen with a wave of lightning, or to just charge around the screen directly.
The invincibility of High Jump renders pretty much all of his attack patterns harmless, though. For a non-aggressive fight, stay at the opposite half of the screen (you don't need to hug the corner), and simply jump through him each time he starts an attack or moves across the screen. He'll go down pretty swiftly even without being aggressive.


text:
Q: ASP.NET: How to process postback events for my own control? I have my own Control1 which is dynamically added as child control to Control2 which implements INamingContainer in CreateChildControls() of control2.
Control1 itself implements IPostBackEventHandler. But RaisePostBackEvent() method is never called on Control1, despite I do call postback method from JavaScript.
And yes, there are other controls which implement IPostBackEventHandler interface on the page.
What did I miss?
What could cause the issue?
UPDATE: Control1 is always created exactly the same way and assigned exactly the same ID in Control2
it looks like this in Control2:
protected override void CreateChildControls()
{
  if(!this.DesignMode)
  {
    Control1 c = new Control1();
    c.ID = "FIXED_ID";
  }
  base.CreateChildControls();
}

UPDATE2:
Control1:
public class Control1: Control, IPostBackEventHandler
{
...
    protected virtual void RaisePostBackEvent(string eventArgument)
    {
              if(!String.IsNullOrEmpty(eventArgument))
              {
                  // Some other code
              }
    }
}

if I add line
Page.RegisterRequiresRaiseEvent(c);

In CreateChildControls() in Control2 then this method is being called but always with null eventArgument.
UPDATE3:
In JavaScript on some onClick event I do the following:
__doPostBack(Control1.UniqueID,'commandId=MyCommand');

where Control1.UniqueID is of course substituted with real uniqueID during rendering. I checked, this script is being called.

A: Can you show us the source code of first control? Anyway there is a simple example.
public class TestControl2 : CompositeControl
{

    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        if (!DesignMode)
            this.Controls.Add(new TestControl());
    }

}

public class TestControl : WebControl, IPostBackEventHandler
{

    public TestControl() : base(HtmlTextWriterTag.Input) { }

    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
        base.AddAttributesToRender(writer);

        writer.AddAttribute(HtmlTextWriterAttribute.Type, "button");
        writer.AddAttribute(HtmlTextWriterAttribute.Name, base.UniqueID);
        writer.AddAttribute(HtmlTextWriterAttribute.Onclick, Page.ClientScript.GetPostBackEventReference(this, null));
        writer.AddAttribute(HtmlTextWriterAttribute.Value, "Submit Query");
    }

    void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
    {
        // Raise post back event
    }

}

Edit

*

*Why you are generating the post back script out of the control and manually? You have to use Page.ClientScript.GetPostBackEventReference method. It generates and includes some necessary inline and embedded scripts to the page.

*Why you are deriving your class from Control? It's good for those controls which don't have any user interface.
From MSDN

This is the primary class that you
  derive from when you develop custom
  ASP.NET server controls. Control does
  not have any user interface (UI)
  specific features. If you are
  authoring a control that does not have
  a UI, or combines other controls that
  render their own UI, derive from
  Control. If you are authoring a
  control that does have a UI, derive
  from WebControl or any control in the
  System.Web.UI.WebControls namespace
  that provides an appropriate starting
  point for your custom control.

You have to derive your control from WebControl class as follows.
public class TestCtl : WebControl, IPostBackEventHandler
{

    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
        base.AddAttributesToRender(writer);
        // Add onclick event.
        writer.AddAttribute(HtmlTextWriterAttribute.Onclick, Page.ClientScript.GetPostBackEventReference(this, "Arguments"));
    }

    void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
    {
        throw new NotImplementedException();
    }

}

A: I'm going to guess that it's the "dynamically added as child control to Control2" that is the issue, but without any code it's pretty hard to diagnose.
When during the page lifecycle are you dynamically adding it?  Are you recreating the dynamic control in the exact same way, with the same ID, after the postback?


text:
Q: Service Worker: pitfalls of self.skipWaiting() and self.clients.claim() To immediately activate a service worker after it's installed, I use self.skipWaiting() in the install listener. To immediately take control of a page (without the need for a page navigation, e.g. page load), I use self.clients.claim(). I understand that doing such things means:

*

*Page could first load without it being under the control of a Service Worker, but then be taken over by a Service Worker during its lifespan.

*A page could start under the control of version 1 of Service Worker but then be taken over by version 2 during its lifespan.

There are all kinds of warnings online about doing such things, but I don't see the pitfalls. Perhaps one potential problem is if the controlled page does some initial handshake or setup with a Service Worker when it first loads. That obviously will be missed when the new Service Worker activates in the background, but even then, the Service Worker could message its controlling pages to notify them of the change.
It seems to me that for most applications under most scenarios would benefit significantly by using both self.skipWaiting() and self.clients.claim() without any downside. Did I miss something?

A: The pitfalls of self.skipWaiting() is described really well here (thanks @RobertRowntree for the link):
https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68
As for self.clients.claim(), I still haven't seen a compelling argument against it, but when I do, I'll update my answer.


text:
Q: code for showing weekdays and nonweekdays in VBA Sub wd()
Dim Isweekday As Boolean
Select Case Weekday(A3, vbSaturday)
Case 1 To 2
Isweekday = False
Case Else
Isweekday = True
End Select
Range("A4").Value = Isweekday
End Sub

whats wrong in this code?...I want to show true for weekdays and false for  non weekdays

A: Your code treats A3 as an undeclared variable.
Select Case Weekday(Range("A3").Value, vbSaturday)

Shorter:
Sub wd()
    Range("A4").Value = (Weekday(Range("A3").Value, vbSaturday) > 2)
End Sub