text:
Q: Android GPS service I have a working app that works in activity - it calls GPS data from the phone receiver and sends it to my php site filtering the last location in a thread from sqlite it looks like this
final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {
            public void run() {

                if(indikator != 0)
                {
                    Cursor c=db.rawQuery("select * from lokacije", null);
                c.moveToLast();

                try{
                    w.loadUrl(c.getString(c.getColumnIndex("lokacija")));
                    db.execSQL("delete from lokacije where id <"+c.getString(c.getColumnIndex("id")));
                    }
                    catch (Exception e) {
                        // TODO: handle exception
                    }

                }
                indikator=1;
                handler.postDelayed(this, 90000);

            }
        };

    //b.setBackgroundColor(Color.RED);

    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

             if(b.getText().equals("SLOBODAN"))
             {

                 b.setText("ZAUZET");
                 b.setTextColor(Color.GREEN);
             }
             else
             {

                 b.setText("SLOBODAN");
                 b.setTextColor(Color.RED);

             }
        }
    });
    //deo koji naknadno ubacujem za kriterijum
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);

    //kraj dela koji sam naknadno ubacio

final   LocationManager m=(LocationManager) MainActivity.this.getSystemService(Context.LOCATION_SERVICE);
    //deo koji sam takodje ubacio naknadno
String locationprovider =m.getBestProvider(criteria,true);
//deo koji sam takodje ubacio naknadno kraj

        LocationListener l=new LocationListener() {

                @Override
                public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProviderEnabled(String arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProviderDisabled(String arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onLocationChanged(Location arg0) {

                    String url=new String();
                    String zauzetost=new String();
                    zauzetost=b.getText().toString();

                    String format="MM/dd/yyyy";
                    SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.US);
                    String date= sdf.format(new Date());

                t.setToNow();

                ed1.setText("");
                ed2.setText("");
                String longitude=new String();
                String latitude=new String();
                String speed=new String();

                if((int)arg0.getSpeed()==0)
                {
                    speed="0";
                }
                else
                {
                speed=""+(((int)arg0.getSpeed()*3600)/1000);
                }
                longitude=""+  arg0.getLongitude();
                latitude=""+ arg0.getLatitude();
                ed1.setText(longitude);
                ed2.setText(latitude);
                ed3.setText(speed);
                Calendar cal=Calendar.getInstance();

                url="http://www.compensatemeonline.com/truckmeonline/TruckMeOnline/UnosLokacijaSaTelefona.php?id="+mojsadrzaj+"&longitude="+longitude+"&latitude="+latitude+"&brzina="+speed+"&vreme="+cal.getTime()+"&datum="+date+"&zauzetost="+zauzetost;

                db.execSQL("insert into lokacije (lokacija) values ('"+url+"');");

                    // TODO Auto-generated method stub

                }

            };

            // TODO Auto-generated method stub
            //pozivanje threada
             runnable.run();
            //pozivanje threada
            m.requestLocationUpdates(locationprovider, 60000, 0, l);

    //      zamenio sam m.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000, 0, l); sa m.requestLocationUpdates(locationprovider, 120000, 0, l);
        }

Now what I want to do is put it all in a service so that it works in the background .
Should I put my code in onCreate() or in onStart() method of Service since I also use a handler and an another thread . When I call a web site now with URL or HttpClient since i cannot use WebView as in Activity it gives my mistakes in my logcat like this:
  02-12 22:24:32.569: E/AndroidRuntime(1204): java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=2
02-12 22:24:32.569: E/AndroidRuntime(1204):     at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at com.example.serviceswithactivity.MyService$1.run(MyService.java:127)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at android.os.Handler.handleCallback(Handler.java:725)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at android.os.Looper.loop(Looper.java:137)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at android.app.ActivityThread.main(ActivityThread.java:5039)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at java.lang.reflect.Method.invokeNative(Native Method)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at java.lang.reflect.Method.invoke(Method.java:511)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at dalvik.system.NativeStart.main(Native Method)

How do I call a gps location from a service so that i do not get 10-15 points but only one? I did it in Activity by putting the data in a sqlite database and later on taking the last row in a thread and deleting the other rows and so on in a circle. Is there a better way to call a gps location and send it to web site in the background?
This is my entire Service:
public class MyService extends Service {

public int indikator=0;
public String mojsadrzaj=new String();
public String pib=new String();
public String username=new String();
public String password=new String();
public Cursor c;
public Cursor d;
 URL myURL;
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
super.onCreate();

Toast.makeText(this,"Service created ...",Toast.LENGTH_LONG).show();

final SQLiteDatabase db=openOrCreateDatabase("TruckMe", MODE_PRIVATE, null);
db.execSQL("create table if not exists lokacije (id INTEGER  PRIMARY KEY AUTOINCREMENT NOT NULL, lokacija VARCHAR(600));");

//regulisanje podataka za logovanje samo prvi put

String idvozaca=new String();
db.execSQL("create table if not exists vozac (id INTEGER  PRIMARY KEY AUTOINCREMENT NOT NULL, idvozaca VARCHAR(15));");
d=db.rawQuery("select idvozaca from vozac", null);

//db.execSQL("delete from vozac;");

if(d.getCount() > 0)
{
    d.moveToLast();
    idvozaca=d.getString(d.getColumnIndex("idvozaca"));
    mojsadrzaj=idvozaca;
    Toast t=Toast.makeText(this, "Id vozaca je : " + mojsadrzaj, Toast.LENGTH_LONG);
    t.setGravity(Gravity.CENTER, 0, 0);
    t.show();

}
else
{
    //ubacivanje forme za dijalog

            //unos vozacid u bazu
            db.execSQL("insert into vozac (idvozaca) values ('"+mojsadrzaj+"');");
            //unos vozacid u bazu

            //String resString = sb.toString(); // Result is here
            Toast t=Toast.makeText(this, "Aplikacija je aktivirana sa kodom : "+mojsadrzaj, Toast.LENGTH_LONG);
            t.setGravity(Gravity.CENTER, 0, 0);
            t.show();

        }

//regulisanje podataka za logovanje samo prvi put

final Time t=new Time();

 //deo za thread

 final Handler handler = new Handler();

    final Runnable runnable = new Runnable() {
        public void run() {

            if(indikator != 0)
            {

               //w.loadUrl(c.getString(c.getColumnIndex("lokacija")));

                    final SQLiteDatabase db=openOrCreateDatabase("TruckMe", MODE_PRIVATE, null);
                    c=db.rawQuery("select * from lokacije", null);
                    c.moveToLast();

                    try {
                        HttpClient client=new DefaultHttpClient();
                        URI website=new URI(c.getString(c.getColumnIndex("id")));
                        Log.e("Message", website.toString());
                        HttpGet request=new HttpGet();
                        request.setURI(website);
                        try {
                            client.execute(request);
                        } catch (ClientProtocolException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    } catch (URISyntaxException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    /*
                    URL url = null;
                    try {
                        url = new URL(c.getString(c.getColumnIndex("id")));
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    URLConnection urlConnection = null;
                    try {
                        urlConnection = url.openConnection();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        urlConnection.connect();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    */
                    /*
                    try {
                        myURL = new URL(c.getString(c.getColumnIndex("id")));
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    URLConnection myURLConnection = null;
                    try {
                        myURLConnection = myURL.openConnection();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        myURLConnection.connect();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                  */

                db.execSQL("delete from lokacije where id <"+c.getString(c.getColumnIndex("id")));

                    // TODO: handle exception
                  }
            indikator=1;

            handler.postDelayed(this, 15000);

        }
    };

//deo koji naknadno ubacujem za kriterijum
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);

//kraj dela koji sam naknadno ubacio

final   LocationManager m=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    //deo koji sam takodje ubacio naknadno
String locationprovider =m.getBestProvider(criteria,true);
//deo koji sam takodje ubacio naknadno kraj

    LocationListener l=new LocationListener() {

            @Override
            public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderEnabled(String arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderDisabled(String arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLocationChanged(Location arg0) {

                String url=new String();
                String zauzetost=new String();
                zauzetost="ZAUZET";

                String format="MM/dd/yyyy";
                SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.US);
                String date= sdf.format(new Date());

            t.setToNow();

            String longitude=new String();
            String latitude=new String();
            String speed=new String();

            if((int)arg0.getSpeed()==0)
            {
                speed="0";
            }
            else
            {
            speed=""+(((int)arg0.getSpeed()*3600)/1000);
            }
            longitude=""+  arg0.getLongitude();
            latitude=""+ arg0.getLatitude();

            Calendar cal=Calendar.getInstance();

            url="http://www.compensatemeonline.com/truckmeonline/TruckMeOnline/UnosLokacijaSaTelefona.php?id="+mojsadrzaj+"&longitude="+longitude+"&latitude="+latitude+"&brzina="+speed+"&vreme="+cal.getTime()+"&datum="+date+"&zauzetost="+zauzetost;
            Toast.makeText(MyService.this, url,Toast.LENGTH_LONG).show();
            db.execSQL("insert into lokacije (lokacija) values ('"+url+"');");

                // TODO Auto-generated method stub

            }

        };

        // TODO Auto-generated method stub
        //pozivanje threada
         runnable.run();
        //pozivanje threada
        m.requestLocationUpdates(locationprovider, 10000, 0, l);

//      zamenio sam m.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000, 0, l); sa m.requestLocationUpdates(locationprovider, 120000, 0, l);

}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Toast.makeText(this, "Service started onstartcommand ...",Toast.LENGTH_LONG).show();

   return START_STICKY;

}

@Override
public void onStart(Intent intent, int startId) {
    Toast.makeText(this, "Service started onstart...",Toast.LENGTH_LONG).show();

}

@Override
public void onDestroy() {
super.onDestroy();

Toast.makeText(this, "Service destroyed ...",Toast.LENGTH_LONG).show();

}

}

A: The problem is not with your GPS code, the problem is that the URL you're trying to load out of your cursor is incorrect.
I would recheck that the argument of w.loadUrl is correct.


text:
Q: Why are we getting cURL error 56, SSL errorno 104? I am working on an online store that uses a custom PHP script to interface with Orbital Chase Paymentech as a gateway.  Recently, the store's website has been failing to process orders because CURL is encountering an error.  In particular, curl_errno() returns 56 and curl_error() returns SSL read: error:00000000:lib(0):func(0):reason(0), errno 104.
The payment request to Paymentech, however, is going through just fine.  (Ie, our request is formatted correctly, and credit cards are being charged.)  The correct IPs are whitelisted at Paymentech's end.
Here is our CURL configuration:
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Chase Paymentech Gateway/1.0');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
// curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request);
// curl_setopt($ch, CURLOPT_SSLVERSION, 6);
// curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'TLSv1');
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

$result = curl_exec($ch);

I have tried just about every sensible permutation of CURL settings above to no avail.  We always get CURL error 56 with SSL read errno 104.  I've tried the suggestions from other stackoverflow questions, also to no avail.
I've pasted a sample log below from one payment request (with some sensitive info obscured).  As you can see, the request is running over TLSv1.2 / AES128-GCM-SHA256.  I have verified with Chase that this is an acceptable SSL version and cipher.
The certificate on the site is up to date, from Geotrust / RapidSSL, and a fresh one has been installed since I started working on this issue.
Does anyone have any idea what's going on here?  As best I can tell, there's something about our CURL / SSL Certificate setup that is causing the communication to fail, but I can't for the life of me figure out what the cause is or how to fix it.  Please help!
CURL Output:
* Hostname was NOT found in DNS cache, referer: https://www.==our-url===.org/index.php/payment
*   Trying 206.253.186.176..., referer: https://www.==our-url===.org/index.php/payment
* Connected to orbital1.chasepaymentech.com (206.253.186.176) port 443 (#0), referer: https://www.==our-url===.org/index.php/payment
* successfully set certificate verify locations:, referer: https://www.==our-url===.org/index.php/payment
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt, referer: https://www.==our-url===.org/index.php/payment
  CApath: none, referer: https://www.==our-url===.org/index.php/payment
* SSL connection using TLSv1.2 / AES128-GCM-SHA256, referer: https://www.==our-url===.org/index.php/payment
* Server certificate:, referer: https://www.==our-url===.org/index.php/payment
*      subject: C=US; ST=New York; L=New York; O=Chase Paymentech Solutions, LLC; OU=CPS ENA; CN=orbital1.chasepaymentech.com, referer: https://www.==our-url===.org/index.php/payment
*      start date: 2017-01-17 00:00:00 GMT, referer: https://www.==our-url===.org/index.php/payment
*      expire date: 2018-01-18 23:59:59 GMT, referer: https://www.==our-url===.org/index.php/payment
*      subjectAltName: orbital1.chasepaymentech.com matched, referer: https://www.==our-url===.org/index.php/payment
*      issuer: C=US; O=Symantec Corporation; OU=Symantec Trust Network; CN=Symantec Class 3 Secure Server CA - G4, referer: https://www.==our-url===.org/index.php/payment
*      SSL certificate verify ok., referer: https://www.==our-url===.org/index.php/payment
> POST /AUTHORIZE HTTP/1.0\r, referer: https://www.==our-url===.org/index.php/payment
MIME-Version: 1.0\r, referer: https://www.==our-url===.org/index.php/payment
Content-type: application/PTI41\r, referer: https://www.==our-url===.org/index.php/payment
Content-length: 1148\r, referer: https://www.==our-url===.org/index.php/payment
Content-transfer-encoding: text\r, referer: https://www.==our-url===.org/index.php/payment
Request-number: 1\r, referer: https://www.==our-url===.org/index.php/payment
Document-type: Request\r, referer: https://www.==our-url===.org/index.php/payment
Merchant-id: ############\r, referer: https://www.==our-url===.org/index.php/payment
Host: orbital1.chasepaymentech.com\r, referer: https://www.==our-url===.org/index.php/payment
\r, referer: https://www.==our-url===.org/index.php/payment
\r, referer: https://www.==our-url===.org/index.php/payment
            <?xml version="1.0" encoding="UTF-8"?>\r, referer: https://www.==our-url===.org/index.php/payment
            <Request>\r, referer: https://www.==our-url===.org/index.php/payment
                <NewOrder>\r, referer: https://www.==our-url===.org/index.php/payment
                    <IndustryType>EC</IndustryType>\r, referer: https://www.==our-url===.org/index.php/payment
                    <MessageType>AC</MessageType>\r, referer: https://www.==our-url===.org/index.php/payment
                    <BIN>000002</BIN>\r, referer: https://www.==our-url===.org/index.php/payment
                    <MerchantID>############</MerchantID>\r, referer: https://www.==our-url===.org/index.php/payment
                    <TerminalID>001</TerminalID>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AccountNum>################</AccountNum>\r, referer: https://www.==our-url===.org/index.php/payment
                    <Exp>0118</Exp>\r, referer: https://www.==our-url===.org/index.php/payment
                    <CurrencyCode123CurrencyCode>\r, referer: https://www.==our-url===.org/index.php/payment
                    <CurrencyExponent>2</CurrencyExponent>\r, referer: https://www.==our-url===.org/index.php/payment
                    <CardSecValInd>1</CardSecValInd>\r, referer: https://www.==our-url===.org/index.php/payment
                    <CardSecVal>###</CardSecVal>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSzip>A0B1C2</AVSzip>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSaddress1>123 Something St</AVSaddress1>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVScity>Somewhere</AVScity>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSstate>ON</AVSstate>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSphoneNum></AVSphoneNum>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSname>Testing</AVSname>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVScountryCode>CA</AVScountryCode>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSDestzip>A0B1C2</AVSDestzip>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSDestaddress1>123 Something St</AVSDestaddress1>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSDestcity>Somewhere</AVSDestcity>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSDeststate>ON</AVSDeststate>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSDestphoneNum></AVSDestphoneNum>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSDestname>Testing</AVSDestname>\r, referer: https://www.==our-url===.org/index.php/payment
                    <AVSDestcountryCode>CA</AVSDestcountryCode>\r, referer: https://www.==our-url===.org/index.php/payment
                    <OrderID>1343</OrderID>\r, referer: https://www.==our-url===.org/index.php/payment
                    <Amount>1450</Amount>\r, referer: https://www.==our-url===.org/index.php/payment
                </NewOrder>\r, referer: https://www.==our-url===.org/index.php/payment
            </Request>\r, referer: https://www.==our-url===.org/index.php/payment
         /authorize HTTP/1.1\r, referer: https://www.==our-url===.org/index.php/payment
Host: orbital1.chasepaymentech.com\r, referer: https://www.==our-url===.org/index.php/payment
Accept: */*\r, referer: https://www.==our-url===.org/index.php/payment
\r, referer: https://www.==our-url===.org/index.php/payment
* SSL read: error:00000000:lib(0):func(0):reason(0), errno 104, referer: https://www.==our-url===.org/index.php/payment
* Closing connection 0, referer: https://www.==our-url===.org/index.php/payment

A: Apparently restarting the firewall on our server fixed the issue.  We turned it off to do some testing with our certificate issuer, and we noticed that the website worked.  When we turned the firewall back on it was still working.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL query to retrieve row only if other rows have same column values I am trying to find a MySQL query that will retrieve a row only if it has the same value for 2 columns with other rows that share the same group. To be specific, the name of only one of the rows must be returned if multiple rows that have the same group all have status = 'S' and active = 1. Otherwise, the name should not be returned.
example db
id         name       status   active   group
-----      ------     ------   ------   -----
1          Alpha        S         1      A
2          Bravo        S         0      A
3          Charlie      S         1      B
4          Delta        F         1      B
5          Echo         S         1      C
6          Foxtrot      S         1      C
7          Golf         S         1      C

expected result
name
------
Echo/FoxTrot/Golf (Either one is fine)

A: The subquery will return all groups that have values other than 'S' for status OR 1 for active.
Then query only the groups that are not in this condition.
Since you don't mind which of the names will be returned you can use MIN function.
SELECT MIN(name)
FROM table
WHERE group NOT IN (SELECT DISTINCT group FROM table WHERE (status != 'S' OR active != 1))
GROUP BY group

Another solution using HAVING instead of a subquery:
SELECT MIN(name)
FROM table
GROUP BY group
HAVING SUM(CASE WHEN STATUS != 'S' OR ACTIVE != 1 THEN 1 ELSE 0 END) = 0

A: If you don't mind all the names put together, then it can be done with a simple query. You will see comma separated names.
SELECT GROUP_CONCAT(name)
FROM Table
WHERE active = 1
GROUP BY group
HAVING COUNT(name) > 1;


text:
Q: How to exit a for loop if the if loop inside condition is met I'm trying to create a method which allows you to choose which index in an array of test scores. It will check what the score is and return a grade for that score. In my getGrade method no matter what the score is it returns "NG".
private double[] scores = new double[3];
private static int[]boundaryVals={80,72,64,60,56,52,48,40,35,30,1,0};
    private static String[]grades={"A1","A2","B1","B2","B3","C1","C2","C3","D1","D2","F","NG"};

public String getGrade(int i) {
        String grade = "";
        for(int x=0;x<boundaryVals.length;x++) {
            if(boundaryVals[x] <= i) {
                grade = grades[x];

            }
        }
        return grade;
    }

A: Just change the loop exit condition to terminate when a grade has been assigned.
public String getGrade(int i) {
    String grade = "";
    for(int x=0; x<boundaryVals.length && !grade.equals(""); x++) {
        if (boundaryVals[x] <= i) {
            grade = grades[x];
        }
    }
    return grade;
}

This is better-structured since it has the loop termination condition in one place, rather than spreading it out by use of "break".
As usual, this is not a hard and fast rule.  For more complicated cases, "break" is clearer. It's a matter of taste.
The 'return' from mid-loop, as suggested in comments, is not a bad solution in this particular case either. But I think it's worth pointing out that loop conditions are not limited to simple counting from 0 to N.

A: Because in the end 0 always smaller/equals to i, so even if 80 is less than i, finally i will de "NG";
Try add the keywords break; after grade = grades[x]; to stop the loop when the condition is true.

A: break is the keyword you're looking for.
As soon as the break statement is encountered inside a loop, the loop is terminated and it resumes with the next statement.
In your code the loop is never terminated until it gets to the last item in your array, which is 0. And 0 is always smaller than or equal to i. ;)


text:
Q: Levi Civita identity We are given the following  following identity in levi civita notation without derivation and I wanted to try how far I can go by trying to derivate it myself. And I couldn't advance at all because I do not know the rules:
$\nabla\times(\nabla\times\vec A)$
I tried in the following way:
$\epsilon_{ijk}\partial_j(\epsilon_{lmn}\partial_mA_n)_k$
But I don't know the rules now. Can I remove the $\epsilon_{lmn}$ out without having an indecs "k" ?
Can I name the 2nd $\epsilon$ as $\epsilon_{klm}$ and not as I did? How can I know that I can do that? And is it ok if I don't and just write it as i initially wrote it, would I be able to reach the correct result even though my index notation is different then in my script ?
In the scrip when we consider the case of double cross product the two $\epsilon$'s have the same indexes like mine. While when we are given the above equation in the notation you can see that "k" is in both $\epsilon$'s
I should get the following : $\epsilon_{ijk}\epsilon_{klm}A{m,i,j}$


text:
Q: How to get the href value (which changes based on session) from the "Inspect Element" Requirement:
To get the data from a URL into S3 and build a data pipeline. I am trying to get the dataset using python requests.get().
However, the URL changes every few minutes, and it becomes difficult to fetch the data using requests.get() without manual changes to the python script.
My Approach:
I am able to get the data to S3 and build the data pipeline. However, the URL is dynamic I am kinda stuck there.
Code:
import json
import requests
import boto3
import csv
import re

def lambda_handler(event, context):
    response= requests.get("https://calcat.covid19.ca.gov/cacovidmodels/_w_d58f724d/session/d37479fcceb6b02080b6b7c23dd05046/download/dl.custom?w=d58f724d",verify=False)
    #print(response.content)
    s3_client = boto3.client('s3',region_name='us-west-2')
    with open('/tmp/data.csv', 'w') as datacsvfile:
        writer = csv.writer(datacsvfile, delimiter=",")
        for line in response.iter_lines():
                writer.writerows([line.strip().split(',')])

Query:
How can I get the href from the "Inspect element" section , store it in a variable and create a dynamic URL to make a REST call to. Below is the "Inspect element" code I am referring to :

This href only appears in the "inspect element" and not in the "View Source Code".


text:
Q: Pretty (maker-free) device names, where do I find those? I'm looking to do some things involving (removable) devices, so I was looking at WMI and other APIs, the 'Devices and Printers' screen and the Safely Remove Hardware popup as I want to have as seamless an experience as possible. Problem however.. is that I can't find any way to get the names as my user 'knows' them in his PC.
Example... I connect an iPod, this shows in both DaP and SRH as 'iPod', which is awesome. In WMI the closest I've been able to find are 'Apple Inc. iPod' and 'Apple iPod USB Device'. Similar stories apply for other hardware like a WD My Book and other such hardware. Where do I find the proper string?
Since I am beginning to doubt whether I'm approaching the bigger picture from the right direction with WMI, a bit more explanation... we do a fair bit with removable hardware around here, 99% disk drives. I thought over hard-coding a loop from A to Z and inspect each drive, but to my knowledge removable volumes do not NEED to be mounted on a letter, but can also be dumped in an empty folder on ntfs. That and my small doubt there might be other (non-drive) hardware that needs 'finalizing' before being unplugged is adding to a small nagging doubt that I might be asking the wrong question alltogether. (editors: if this is too much irrelevant information, feel free to edit this out of the question.)

A: You can get this with WMI. This Powershell script does just that, the interesting property being Label:
PS C:\>gwmi -Class Win32_Volume | select Name, Label

Name                                                        Label
----                                                        -----
C:\                                                         Windows 7
D:\                                                         Windows 2008
C:\TEST\                                                    MYUSBKEY
E:\                                                         RECOVERY

As you can see, it also works with devices not mounted with a letter.

A: As far as i can see, this does not work. The Powershell code (which is nothing else than another wmi wrapper) only retrieves the volume information for the mounted devices, such as usb keys. I have an iphone connected, and i see noting..


text:
Q: Login page on New window while using selenium webdriver I was facing an issue, while I was trying to click on a link it opens a new window.
If I try manually it opens the expected link but if my automation code runs it opens the login page, and after login it routes to home page, not the actual page.
If I try manually at the browser initiated by automation code it also opens the window with the login page.
I am using selenium with C# and IE for the automation.


text:
Q: Batch to exe Install adblock plus using batch file command
@echo off
start firefox.exe "file:///%tmp%/tmp-ho2.xpi"

suddenly the files wont install
cause the path is not correct because bath to exe program create a new random name folder in temporary folder once you execute it.I cant configure out what folder name should i add in "file:///%tmp%/?????/tmp-ho2.xpi"

A: start firefox.exe "%~p0\tmp-ho2.xpi"

%~p0 is expanded to the directory where the batch program was run from.


text:
Q: huxtable footnote: how to set bold, italic etc. - html coding does not work If you set a caption: set_caption("...") html codes like "b, i, font size"  and so on are working
But with add_footnote("...") this isn`t true anymore, it just prints the html code as text
Does someone know how to fix this. Or how to style the footnote?

A: Use escape_contents() on the footnote cell:

library(huxtable)
jams |>
   add_footnote("These jams are <i>tasty</i>") |>
   set_escape_contents(final(1), everywhere, FALSE) |>
   quick_html()

You might also think about using markdown:
jams |>
   add_footnote("These jams are *tasty*", markdown = TRUE) |>
   quick_html()

which produces the same output but will also work in TeX and other formats.


text:
Q: RabbitMQ in Docker Swarm: Discover task instances by hostname I have a RabbitMQ cluster running in Swarm, configured as a global service, which has the hostname set to the host's name:
services:
  rabbitmq:
    image: "rabbitmq:3-management"
    hostname: "rabbitmq-{{.Node.Hostname}}"
    networks:
      - rabbitmq
    configs:
      - source: rabbitmq_config
        target: /etc/rabbitmq/rabbitmq.conf
    secrets:
      - source: rabbitmq_erlang_cookie
        target: /var/lib/rabbitmq/.erlang.cookie
    environment:
      RABBITMQ_NODENAME: "rabbit@rabbitmq-{{.Node.Hostname}}"
    deploy:
      mode: global

The nodes all receive a dynamically generated configuration file with all the nodes in it, so they can form the cluster:
docker_hosts=$(docker node ls --format '{{.Hostname}}')
count=0
for host in ${docker_hosts}; do
  count=$((count+1))
  echo "cluster_formation.classic_config.nodes.${count} = rabbit@rabbitmq-${host}" >> rabbitmq.conf
done

I would like to replace this classic discovery configuration with the DNS peer discovery backend to discover the other tasks automatically, but hit some road blocks.
The built-in Docker DNS daemon allows to discover tasks by doing a query for tasks.<service name>. For RabbitMQ, this yields output like:
root@rabbitmq-foo-1:/# nslookup tasks.rabbitmq
Server:     127.0.0.11
Address:    127.0.0.11#53

Non-authoritative answer:
Name:   tasks.rabbitmq
Address: 10.100.8.158
Name:   tasks.rabbitmq
Address: 10.100.8.162
Name:   tasks.rabbitmq
Address: 10.100.8.163

This means we can pass the seed hostname tasks.rabbitmq to RabbitMQ, and it will perform an A lookup during startup. As per the documentation, the result to this query will "append [the] current node's prefix (e.g. rabbit in rabbit@hostname1.example.local) to each hostname and return the result."
Performing a manual reverse lookup, we get results like the following:
root@rabbitmq-foo-1:/# nslookup 10.100.8.158
158.8.100.10.in-addr.arpa   name = foo_rabbitmq.tjqxe6kpe5g4mnmgwoiuink16.xhosndlwm3eaoldu36udvjfi9.rabbitmq-net.

This means the Docker DNS service builds reverse records as:
<Project Name>_<Task Name>.<Task ID>.< Container ID>.<Network Name>.

Unfortunately, RabbitMQ doesn't work well with that name: Even if configured to use the FQDN for nodes, RabbitMQ will check the resolved RR record against the node's hostname and only join the cluster if they match.
So instead of foo_rabbitmq.tjqxe6kpe5g4mnmgwoiuink16.xhosndlwm3eaoldu36udvjfi9.rabbitmq-net., it needs rabbitmq-foo-1.whatever. (where the host is named foo-1.)
Is there a way to resolve the given hostname of the task instances instead? Or a DNS endpoint to get all Swarm nodes?


text:
Q: Do virtual particles contribute to mass of macroscopic objects, such as ice? In http://nautil.us/issue/54/the-unspoken/physics-has-demoted-mass it talks about how "classical" accounting of mass does not produce the right mass of ice, and it seems to suggest uncertainy principle and virtual particles "allow" for bigger mass of ice.
But from what I know, virtual particles are just artifacts of perturbative treatments, and uncertainty principle does not mean violation of special relativity.
Is the article somehow being misleading, or am I misunderstanding something?

A: Yes and no.
You are quite correct that virtual particles are a mathematical device used for doing perturbative calculations in QFT. So in that sense virtual particles don't contribute to the mass of the nucleons in ice. But although virtual particles are just a computational device they are describing something real i.e. the energy in the quantum field. And that energy does have a mass given by Einstein's famous equation $E = mc^2$.
The article is a little sensationalist, but what is says is basically correct. Even before QCD was understood we already knew that energy contributes to mass due to observations of things like the mass deficit in nuclei. Even leaving aside quantum mechanics, for example in special relativistic collisions we know that mass isn't conserved. See for example Is (rest) mass conserved in special relativity?
In quantum field theory the objects we call particles are the states of the quantum field in the free field limit i.e. when we consider a single completely isolated particle. When we have interactions between two of more particles the states of the field change, and in fact we have little understanding of what these states are. However we can approximate them as combinations of the free field states. So when we talk about there being three quarks in a proton this isn't really true because the field states in a strongly interacting system aren't the same as the quark states we would get in the free field limit$^1$. It is therefore little surprise that the mass of a proton is not simply the mass of the three quarks inside it.
I feel the article you cite gets a little hysterical about the idea that energy has mass. That has been known for a hundred years and won't be news to anyone who works in the area. However I can see that this seems bizarre to many, even given that much of quantum mechanics is already on the bizarre side.

$^1$ a hypothetical free field limit in the case of quarks


text:
Q: How to pass parameters to an ExecPackage in Bundle.wxs of WiX I am chaining a batch file in Bundle.wxs as an "ExecPackage". The batch file expects a parameter/commandline argument.
<ExePackage Id="Test" SourceFile="D:\TestBatch.bat" Vital="yes" InstallCondition="SelectedDBSize = 24" InstallCommand=""/>

How do I pass commandline arguments/parameters in the "ExecPackage". Can InstallCommand attribute be used for this? If so can somebody give me a small example to illustrate the same?

A: This is currently what I use to install SqlExpress 2008 R2 as part of my bundle:
<ExePackage Id="SqlExpress2008R2"
            Cache="no"
            Compressed="no"
            PerMachine="yes"
            Permanent="no"
            Vital="yes"
            InstallCommand="/QS /ACTION=Install /IACCEPTSQLSERVERLICENSETERMS /BROWSERSVCSTARTUPTYPE=Automatic /SQLSVCSTARTUPTYPE=Automatic /FEATURES=SQL /INSTANCENAME=[SqlInstance] /SQLSVCACCOUNT="NT AUTHORITY\Network Service" /SQLSYSADMINACCOUNTS="BUILTIN\ADMINISTRATORS" /AGTSVCACCOUNT="NT AUTHORITY\Network Service" /SECURITYMODE=SQL /SAPWD="[SqlAdminUserPassword]""
            Name="redist\SQLEXPR_x86_ENU.exe"
            DownloadUrl="http://download.microsoft.com/download/D/1/8/D1869DEC-2638-4854-81B7-0F37455F35EA/SQLEXPR_x86_ENU.exe"
            InstallCondition="NOT SQLServer2008R2Installed AND NOT SQLServerInstalled">
    <RemotePayload ProductName="SQL Server 2008 R2 Express SP1"
                   Description="SQL Server 2008 R2 Express SP1"
                   CertificatePublicKey="5C499B10F7EF186DC729991A262AB52066423909"
                   CertificateThumbprint="93859EBF98AFDEB488CCFA263899640E81BC49F1"
                   Hash="6F399D641F322A3E47E3DD605F2A2EDF21074375"
                   Size="111274848"
                   Version="10.50.2500.0" />
  </ExePackage>

The parts in the InstallCommand attribute surrounded with square-brackets (e.g. [SqlInstance]) are supplied by the bundle variables that can be supplied to the bundle exe on the command-line:
<Variable Name="SqlInstance"
          Value="SQLEXPRESS"
          bal:Overridable="yes" />

Note the important attribute bal:Overridable="yes" this means that it can be set via the bundles command-line, without it it will just be an internal variable (set by registry search for example).


text:
Q: How to pass params in url to another resource in rails? I am developing a kind of job board, where I have a "page" called 'jobdetails' with job details ('jobdetails' displays openings resources) job with apply button that should redirect to 'jobapplications' "page" where the jobseeker can upload his cv (not yet implemented) and save opening_id.
I tried many ways but still not working.
I said I want to pass params with url but i'am open with other ways, model or controller.
thanks.
Edit: I Am able to save a record but opening_id remains blank...

Rails.application.routes.draw do
  resources :posts
    devise_for :jobseekers, controllers: { registrations: "jobseekers/registrations", sessions: "jobseekers/sessions" }
  resources :companypics
  devise_for :users, controllers: { registrations: "registrations" }
  resources :openings
  resources :jobapplications
  resources :companies
  resources :locations
  resources :timesheets
  resources :expenses
  resources :jobdescriptions
  resources :jobdetails
  root :to => 'dashbords#index'
  end

class JobapplicationsController < ApplicationController
  before_filter :authenticate_jobseeker!

  layout 'apply'
def applyparam
  @opening = Opening.find(params[:opening])

end

  def index
    @jobapplications = Jobapplication.all
  end

  def show
  end

  def new
    @jobapplication = Jobapplication.new
  end

  def edit
  end

  def create
    @jobapplication = current_jobseeker.jobapplications.create(jobapplication_params)
    @jobapplication.save
    redirect_to new_jobapplication_path
  end

  def update
    @jobapplication.update(jobapplication_params)
  end

  def destroy
    @jobapplication.destroy
  end

  private

    def jobapplication_params
      params.require(:jobapplication).permit(:opening_id, :jobseeker_id, )
    end
end

class JobdetailsController < ApplicationController
  layout 'apply'

  def show
    @jobdetail = Opening.find_by_applyjobid(params[:applyjobid])
    @logo = current_user.company.logo.url

  end
  end

Jobdetails Show

              <%= @jobdetail.jobdescription.job_title %>

            Company:

            <%= @jobdetail.company.company_name %>

            <%= image_tag @logo  %>

            Job Location:

            <%= @jobdetail.location.name %> <%= @jobdetail.location.postalcode %>

            Job salary:

            <%= @jobdetail.jobdescription.rate_pay %>

Job Summary:

                <%= @jobdetail.jobdescription.job_summary %>

            <% if !@jobdetail.jobdescription.shift.blank? -%>
          Job shift:

            <%= @jobdetail.jobdescription.shift %>

            <% end %>

            Job requirements:

            <% if !@jobdetail.jobdescription.job_duties.blank? -%>
               <%= @jobdetail.jobdescription.job_duties %>

            <% end %>

            <% if !@jobdetail.jobdescription.tasks.blank? -%>
            <%= @jobdetail.jobdescription.tasks %>

            <% end %>
            <% if !@jobdetail.jobdescription.job_duties.blank? -%>
                <%= @jobdetail.jobdescription.job_duties %>

            <% end %>
            <% if !@jobdetail.jobdescription.responsibilities.blank? -%>
                <%= @jobdetail.jobdescription.responsibilities %>

            <% end %>
            <% if !@jobdetail.jobdescription.results.blank? -%>

            <%= @jobdetail.jobdescription.results %>

            <% end %>
            <% if !@jobdetail.jobdescription.skills.blank? -%>

          <%= @jobdetail.jobdescription.skills %>

            <% end %>

            <% if !@jobdetail.jobdescription.knowledge.blank? -%>

          <%= @jobdetail.jobdescription.knowledge %>

            <% end %>

            <% if !@jobdetail.jobdescription.abilities.blank? -%>
          <%= @jobdetail.jobdescription.abilities %>

            <% end %>

            Education:

            <% if !@jobdetail.jobdescription.education_and_training.blank? -%>
                <%= @jobdetail.jobdescription.education_and_training %>

            <% end %>
            <% if !@jobdetail.jobdescription.qualifications.blank? -%>
                <%= @jobdetail.jobdescription.qualifications %>

            <% end %>
            <% if !@jobdetail.jobdescription.license_certification.blank? -%>
                <%= @jobdetail.jobdescription.license_certification %>

            <% end %>

            Job environment:

            <% if !@jobdetail.jobdescription.physical_requirement.blank? -%>
                <%= @jobdetail.jobdescription.physical_requirement %>

            <% end %>
            <% if !@jobdetail.jobdescription.work_envir_condition.blank? -%>
                <%= @jobdetail.jobdescription.work_envir_condition %>

            <% end %>
            <% if !@jobdetail.jobdescription.protective_clothing_and_devices_required.blank? -%>
                <%= @jobdetail.jobdescription.protective_clothing_and_devices_required %>

            <% end %>
            <% if !@jobdetail.jobdescription.tools_or_equipment_required.blank? -%>
                <%= @jobdetail.jobdescription.tools_or_equipment_required %>

            <% end %>

            Benefits:

            <% if !@jobdetail.jobdescription.benefits.blank? -%>
                <%= @jobdetail.jobdescription.benefits %>

            <% end %>
            <% if !@jobdetail.jobdescription.other_benefits.blank? -%>
                <%= @jobdetail.jobdescription.other_benefits %>

            <% end %>

            <%= link_to "Apply now", new_jobapplication_path(:opening => @jobdetail.id) %>

<%= form_for (@jobapplication) do |f| %>

Apply

        <%= render 'layouts/messages' %>

<%= f.hidden_field :opening %>
        <%= f.submit "Submit", class: "btn btn-large btn-success" %>
        <% end %>
        </form>

class Jobapplication < ActiveRecord::Base
  belongs_to :opening

end

create_table "jobapplications", force: true do |t|
    t.integer  "opening_id"
    t.integer  "jobseeker_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

Started POST "/jobapplications" for 127.0.0.1 at 2015-05-25 10:49:38 +0100
Processing by JobapplicationsController#create as HTML
  Parameters: {"utf8"=>"V", "authenticity_token"=>"+0z1IIG0COeYZUQavPUZXu/5m316t9VrUs9eiOFrMjA=", "jobapplication"=>{"opening"=>"#<Opening:0x85cc
f80>"}, "commit"=>"Submit your timesheet"}
  Jobseeker Load (1.0ms)  SELECT  "jobseekers".* FROM "jobseekers"  WHERE "jobseekers"."id" = 1  ORDER BY "jobseekers"."id" ASC LIMIT 1
Unpermitted parameters: opening
   (0.0ms)  begin transaction
  SQL (2.0ms)  INSERT INTO "jobapplications" ("created_at", "jobseeker_id", "updated_at") VALUES (?, ?, ?)  [["created_at", "2015-05-25 09:49:39.
818752"], ["jobseeker_id", 1], ["updated_at", "2015-05-25 09:49:39.818752"]]
   (131.0ms)  commit transaction
   (0.0ms)  begin transaction
   (0.0ms)  commit transaction
Redirected to http://localhost:3000/jobapplications/new
Completed 302 Found in 591ms (ActiveRecord: 134.0ms)

A: In your view change opening to opening_id :
<%= link_to "Apply now", new_jobapplication_path(opening_id: @jobdetail.id) %>

In you new action instantiate with the opening_id :
def new
  @jobapplication = Jobapplication.new(opening_id: params[:opening_id])
end


text:
Q: Do I need a VAO for each different object rendered? I believe I misunderstood the limits of VAO's.
I have 3 VAO's, one for each vertex spec. format.
Focusing on the VAO intended for menus/quads rendering in homogeneous screen coordinates, how many buffers can I have connected to the same array index of a single VAO ?
Due to results in my program I am inclined to believe every separate instance rendered should have it's own VAO.  However, I am still able to draw two instances using one VAO, although with incorrect results.  (Cursor takes up fullscreen and position doesn't change, rendered overtop fullscreen TitleMenu).
I'm fairly certain I already know the answer is have a VAO for each instance with differing array buffer data, would just like confirmation I have rationalized this correctly.
Also, are the buffers bound to the VAO copied to the VAO and can be deleted?
Does a glVertexAttribPointer() need to be called again to update the information in a VAO ?  Or is buffering data to the original buffer sufficient ?


text:
Q: How can I test functions that are provided by context using jest and react-testing-library? I have a <UserProvider /> component that provides context which has a login method in its value. In my test I want to check if that method has been called. How can I check to make sure this method is being called in my test if it comes from context? I've tried using the spyOn and mock methods but I can't get them to work.
Here's my UserProvider component which provides the context.
import React, { useState, useContext, createContext } from 'react'

const UserContext = createContext()

function UserProvider({ children }) {
  const [user, setUser] = useState(null)
  const login = user => setUser(user)

  return <UserContext.Provider value={{ user, login }}>{children}</UserContext.Provider>
}

const useUser = () => useContext(UserContext)

export { UserProvider, useUser }

Here's my Login component using the context from UserProvider (via useUser)
import React from 'react'
import { useUser } from './UserProvider'

function Login() {
  const { login } = useUser()

  const handleSubmit = async e => {
    e.preventDefault()

    // I need to make sure this method is being called in my test.
    login({ name: 'John Doe' })
  }

  return (
    <form onSubmit={handleSubmit}>
      <button>Login</button>
    </form>
  )
}

export default Login

Here's my Login test
import React from 'react'
import { render, fireEvent } from '@testing-library/react'
import Login from './Login'
import { UserProvider, useUser } from './UserProvider'

// Is this correct?
jest.mock('./UserProvider', () => ({
  useUser: jest.fn(() => ({
    login: jest.fn()
  }))
}))

it('should log a user in', () => {
  const { getByText } = render(
    <UserProvider>
      <Login />
    </UserProvider>
  )

  const submitButton = getByText(/login/i)
  fireEvent.click(submitButton)

  // How can I make this work?
  const { login } = useUser()
  expect(login).toHaveBeenCalledTimes(1)
})

I have a codesandbox but it's erroring out about jest.mock not being a function so I don't know if it's very useful.

A: I see 2 more approaches here:

*

*Inject Context.Consumer alongside your component under test. Then so you would be able to verify against it

  const contextCallback = jest.fn();
  const { getByText } = render(
    <UserProvider>
      <Login />
      <UserContext.Consumer>{contextCallback}</UserContext.Consumer>
    </UserProvider>
  );

  const submitButton = getByText('Login');
  fireEvent.click(submitButton);

  expect(contextCallback.mock.calls[0][0]).toEqual({
    user: "John Doe"
  });

*Mock calls behind UserContext.Consumer(let it be speculative LoginAPI call in UserContext)

jest.mock("../LoginAPI.js");
...
  const { getByText } = render(
    <UserProvider>
      <Login />
    </UserProvider>
  );

  const submitButton = getByText('Login');
  fireEvent.click(submitButton);

  expect(LoginAPI.login).toHaveBeenCalledTimes(1);

To me 2nd one is better while 1st rely on implementation details(context data's structure).
PS to 1st approach you may declare consumer component right in the test to avoid exporting UserContext:
function ContextHelper({ spy }) {
  const contextData = useUser();
  spy(contextData);
  return null;
}

...
  const contextCallback = jest.fn();
  const { getByText } = render(
    <UserProvider>
      <Login />
      <ContextHelper spy={contextCallback} />
    </UserProvider>
  );

But keep in mind that spy may be called more times that you'd expect.

A: I can't get it to work without slightly change the source code a little bit.
First, I have to export the actual context
export { UserProvider, useUser, UserContext }

We can re create provider with a mocked login function and the following test will serve you purpose.
import React from 'react'
import { render, fireEvent } from '@testing-library/react'
import Login from './Login'
import { UserProvider, useUser, UserContext } from './UserProvider'

it('should log a user in', () => {
  const login = jest.fn();
  const { getByText } = render(
    <UserContext.Provider value={{ login }}>
      <Login />
    </UserContext.Provider>
  );

  const submitButton = getByText('Login');
  fireEvent.click(submitButton);

  expect(login).toHaveBeenCalledTimes(1)
});

It is entirely possible that this is not the best approach. I hope it helps.


text:
Q: Decorate a subset of a generic registration I'm using SimpleInjector for my DI container. I have an open generic interface with 2 type arguments
public interface IAdapter<TRepository, TEntity>
    where TRepository : AbstractRepository
    where TEntity : AbstractModel, new()
{
}

which I register with the container as:
container.RegisterOpenGeneric(typeof(IAdapter<,>),
    typeof(Adapter<,>));

I would like to decorate IAdapter dependent on the types provided. e.g. (I know this code is not valid but it demonstrates what I'm trying to do)
class RepositoryX : AbstractRepository { }
class RepositoryY : AbstractRepository { }
class RepositoryZ : AbstractRepository { }

container.RegisterDecorator(typeof(IAdapter<RepositoryY,>),
    typeof(SpecificAdapterDecorator<,>));

container.RegisterDecorator(typeof(IAdapter<[RepositoryX|RepositoryZ],>),
    typeof(GeneralAdapterDecorator<,>));

Is there a way to do this?

A: From the generic decorator documentation:

There's an overload of the RegisterDecorator available that allows you
  to supply a predicate to determine whether that decorator should be
  applied to a specific service type. Using a given context you can
  determine whether the decorator should be applied.

So you will need something like this:
container.RegisterDecorator(
    typeof(IAdapter<,>),
    typeof(SpecificAdapterDecorator<,>),
    c => c.ServiceType.GetGenericArguments()[0] == typeof(RepositoryY));

container.RegisterDecorator(
    typeof(IAdapter<,>),
    typeof(GeneralAdapterDecorator<,>),
    c => c.ServiceType.GetGenericArguments()[0] != typeof(RepositoryY));


text:
Q: Changing a PHP value dynamically with Javascript I'm making a blog type webpage, with a div that has a 'like' and 'dislike' button, and a rating above which is a mysql query of likes/(likes+dislikes).  When a user clicks like or dislike, I want to add their vote to the db, and dynamically change the rating value without reloading the page.  Here's a little snippet of the html, I have barely worked with javascript, so any help would be great.

   <?php
    $popularity = get_popularity($row);
   ?>

Rating:  <?php echo $popularity . "%"; ?>

       Dislike

       Like

A: You will have to use ajax to accomplish this. Its not possible to alter PHP variables VIA javascript.
You will have to call an Ajax function that will handel the database work and after its done that, you will have to update the count using javascript. This will give the allusion that the count was updated while the count will also be updated in the database (from the Ajax)
Here is a great example of how you could accomplish this:

Example Code
Live Demo

A: You would not actually be changing a PHP value--once the page is output to the browser, consider PHP gone--you can't interact with it because it's on the server. Instead, think of interacting with the document that's in the browser.
The best way to do this is to make an ajax call to a server-side script. That server-side script can commit the like or dislike to the database, and then return the new rating, which you can insert in place of the old one using javascript.
You'll probably want to check out some tutorials on javascript and ajax, as it seems you have a more general need for a tutorial than for a specific problem. In other words, if you fill in your knowledge gaps on the general subject, you'll be able to solve your specific problem quite easily.

A: You will want to create some PHP code for handling the saving to the database on the Server side. You will POST the like / dislike value information to this server side script. If possible, I would use jQuery's AJAX helper to post data to the PHP page you just created.
Something like this:
$.ajax({
  url: "whatever.php",
  type: "POST",
  data: {Like: true},
  success: function(data){ /* update view */}
});

A: $('.like').click(function(){
   rate(1);
})
$('.dislike').click(function(){
   rate(-1);
})

function rate(_val){
$.ajax({
  url: 'ajax/rate.php?val='+_val,
  success: function(data) {
    alert('Rate was performed.');
    $(".narrow_right_container").find(".yellow_bg").append("Rating: "+data+"%");
  }
});
}

in rate.php:
if(isset($_GET['val'])){
  $sql = "UPDATE.........."; //do an update to your rate table
  echo get_popularity($row); //return rating to ajax
}


text:
Q: expected value of a $e^{-2|x|}$ Let $f(x)=e^{-2|x|}$
Find:

*

*$E(X)$

*$E(|X|)$

*$E(x')$ where $x'$ denotes the largest integer not greater than $x$.
I'm stuck on this question and am confused about how to use the modulus sign. I feel I need to show it separately for cases when $x\ge0$ and $x\le0$ but I'm not sure.
Any help is appreciated

A: By definition,
$$E(X)=\int_{-\infty}^\infty xe^{-2|x|}\,dx.\tag{1}$$
To evaluate this integral is easy. First, a technical thin, the integral does converge. The function $xe^{-2|x|}$ is an odd function, so the integral is $0$.
We have
$$E(|X|)=\int_{-\infty}^\infty |x|e^{-2|x|}\,dx.\tag{2}$$
Now the integrand is symmetric about the $y$-axis, so we find the integral from $0$ to $\infty$, and double.
To find the integral from $0$ to $\infty$, we need
$$\int_{-\infty}^\infty xe^{-2x}\,dx.$$
We can use integration by parts, or recall that the exponential with parameter $2$ has mean $\frac{1}{2}$. That tells us that $\int_0^\infty (x)2e^{-2x}=\frac{1}{2}$.
The greatest integer one takes a bit more woek to analyze. The integral breaks up into parts. From $0$ to $1$ we are integrating $0\cdot e^{-2x}$. From $1$ to $2$ we are integrating $1\cdot e^{-2x}$, and so on.
So we get
$$(1)\frac{1}{2}(e^{-2}-e^{-4})+(2)\frac{1}{2}(e^{-4}-e^{-6})+(3)\frac{1}{2}(e^{-6}-e^{-8})+\cdots.$$
This is a geometric series, not hard to evaluate.
However, we can be tricky, and do the negative part, hoping for cancellation. We get
$$(-1)\frac{1}{2}(e^{0}-e^{2})+(-2)\frac{1}{2}(e^{-2}-e^{-4})+(-3)\frac{1}{2}(e^{-4}-e^{-6})+\cdots.$$
Add the two, simplify.

A: *

*$f(x)=f(-x)$, so if $E[X]$ exists then $E[X]=0$ as a symmetric random variable.  It does exist, because $E[|X|]$ exists.

*If $Y=|X|$ then the density of $Y$ is $g(y)=2e^{-2y}$ for positive $y$ and $E[|X|]=E[Y]=\frac12$ as an exponential random variable

*If $Z=\lfloor X \rfloor $ then $\Pr(Z=n) = \Pr(Z=-(n+1)) = e^{-2n}(1-e^{-2})$ for non-negative integer $n$, so is should be easy to see $E[\lfloor X \rfloor]=E[Z]=-\frac12$.

A: Hint:

$$\operatorname{E}[X] = \int_{-\infty}^\infty x f(x)\, \mathrm{d}x,  $$

and more generally

$$\operatorname{E}[g(X)] = \int_{-\infty}^\infty g(x) f(x)\, \mathrm{d}x. $$

To deal with integrals contain the floor function $\lfloor x\rfloor$ see here.


text:
Q: Facebook native ios login error with test user I'm getting the following error when attempting to use the ios6 native facebook login
The Facebook server could not fulfill this access request: Temporarily unable to make API calls on behalf of XYZ

The login works fine if I remove the ios facebook user from settings and use the webview style of login rather than the built in ios way.  It also works if I don't use the fb test user.  I've checked the test user's permissions and it has all the read and write permissions.  Are test users not allowed to use the native ios login?
Is this an error on Facebook's servers?  How can I further diagnose this?
here's the full error output
2013-03-24 10:45:57.701 HelloFacebookSample[39800:19a03] FBLoginView encountered an error=Error Domain=com.facebook.sdk Code=2 "The operation couldn't be completed. (com.facebook.sdk error 2.)" UserInfo=0xa288a00 {com.facebook.sdk:ErrorLoginFailedReason=com.facebook.sdk:SystemLoginCancelled, com.facebook.sdk:ErrorInnerErrorKey=Error Domain=com.apple.accounts Code=7 "The Facebook server could not fulfill this access request: Temporarily unable to make API calls on behalf of 10000000" UserInfo=0xa157760 {NSLocalizedDescription=The Facebook server could not fulfill this access request: Temporarily unable to make API calls on behalf of 10000000}, com.facebook.sdk:ErrorSessionKey=<FBSession: 0xa27e530, state: FBSessionStateClosedLoginFailed, loginHandler: 0x0, appID: 20000000, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0xa2742c0>, expirationDate: (null), refreshDate: (null), attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(null)>}

I am using a test facebook user that has been added to the testers group of the app

A: I don't have yet enough reputation to vote, but MonkeyBonkey is right. I was having the same issue, change the Facebook's test user to other "real" Facebook user and it worked!!

A: You can login to an app using a test user as long as the app is set to 'live'.  To do that, go here https://developers.facebook.com/apps and click on 'Status & Review' then make sure the switch is set to 'On'.  If it's grayed out, just hover over it with your mouse and it will tell you want you need to do to make it live, I was missing a contact email.
If you want to create test users, go to 'Roles' then the 'Test Users' tab.
Hope that helps someone.


text:
Q: Dependency injection issue with services and filter I am new to angularjs and have created three apps based on the angularjs tutorial.
https://docs.angularjs.org/tutorial
The apps are documentprofileApp, machineorderApp and regionresourceApp.  I've setup services for each that reside in the core folder.  Also in the core folder is a filter named checkmark.
To use checkmark you enter 'core' as a dependency in the app.module.  If I want to use the checkmark in the documentprofileApp I have to add script references to the machineorder and regionresource services files or I get an injection error.

Error: [$injector:modulerr] http://errors.angularjs.org/1.7.7/$injector/modulerr?p0=documentprofileApp&p1=%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.7.7%2F%24injector%2Fmodulerr%3Fp0%3Dcore%26p1%3D%255B%2524injector%253Amodulerr%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.7.7%252F%2524injector%252Fmodulerr%253Fp0%253Dcore.machineorder...

documentprofileApp doesn't use those services so I would prefer not to have to have references to them.
My question is, should I create the services outside of the core folder or have I set something up incorrectly in how the dependencies are referenced in the various modules.
Instead of referencing 'core' as a dependency I tried referencing 'core.checkmark' similar to how the services are referenced (core.document, core.machineorder, etc).  This doesn't work.
I went back to the tutorial and made sure I understood and followed how they had set it up there.  Since this is an introductory tutorial it might just be that it is simplified for its purpose and I need to seek other sources to learn how to setup my project for multiple applications.
Folder structure:
FolderStructure

core.module:
 angular.module('core', [
 'core.document',
 'core.organization',
 'core.department',
 'core.machineorder',
 'core.regionresource',
 'core.region']);

app.module:
 angular.module('documentprofileApp', [
     'ngAnimate',
     'ngRoute',
     'core',
     'documentDetail',
     'documentList'
 ]);

 angular.module('machineorderApp', [
     'ngAnimate',
     'ngRoute',
     'ngCookies',
     'thatisuday.dropzone',
     'machineorderDetail',
     'machineorderList'
 ]);

angular.module('regionresourceApp', [
     'ngAnimate',
     'ngRoute',
     'regionresourceDetail',
     'regionresourceList'
 ]);

document-list.module:
 angular.module('documentList', ['core.document']);

layout template:

     <title>Document Profiles</title>
     @Styles.Render("~/bundle/machineOrderFileCommonCss")
     @Scripts.Render("~/bundle/machineOrderFileCommonJs")
     @Scripts.Render("~/bundle/documentProfileJs")

Bundles:
        bundles.Add(new ScriptBundle("~/bundle/machineOrderFileCommonJs").Include(
            "~/Scripts/common.js",
            "~/Scripts/angular.min.js",
            "~/Scripts/angular-animate.min.js",
            "~/Scripts/angular-resource.min.js",
            "~/Scripts/angular-route.js",
            "~/Scripts/angular-ui/ui-bootstrap-tpls.min.js",
            "~/Scripts/angular-messages.min.js",
            "~/app/app.module.js",
            "~/app/app.config.js",
            "~/app/core/core.module.js"
            ));

        bundles.Add(new ScriptBundle("~/bundle/machineOrderFileJs").Include(
            "~/Scripts/angular-cookies.min.js",
            "~/Code/FileManagement/dropzone.js",
            "~/Scripts/ng-dropzone.js",
            "~/app/core/machineorder/machineorder.module.js",
            "~/app/core/machineorder/machineorder.service.js",
            "~/app/machineorder-list/machineorder-list.module.js",
            "~/app/machineorder-list/machineorder-list.component.js",
            "~/app/machineorder-detail/machineorder-detail.module.js",
            "~/app/machineorder-detail/machineorder-detail.component.js"
            ));

        bundles.Add(new ScriptBundle("~/bundle/documentProfileJs").Include(
            "~/app/core/checkmark/checkmark.filter.js",
            "~/app/core/document/document.module.js",
            "~/app/core/document/document.service.js",
            "~/app/core/organization/organization.module.js",
            "~/app/core/organization/organization.service.js",
            "~/app/core/department/department.module.js",
            "~/app/core/department/department.service.js",
            "~/app/document-list/document-list.module.js",
            "~/app/document-list/document-list.component.js",
            "~/app/document-detail/document-detail.module.js",
            "~/app/document-detail/document-detail.component.js"
            ));

Thank you in advance to anyone who can offer any insight as to why the service files must be linked.

A: Your error message decodes as follows:

Failed to instantiate module documentprofileApp due to:
  [$injector:modulerr] http://errors.angularjs.org/1.7.7/$injector/modulerr?p0=c....
Failed to instantiate module core due to:
  [$injector:modulerr] http://errors.angularjs.org/1.7.7/$injector/modulerr?p0=c...
Failed to instantiate module core.machineorder due to:
  {1}

A common reason why the module fails to load is that you've forgotten to include the file with the defined module or that the file couldn't be loaded.
Either you did not include those files, or the module is not named "core.machineorder".


text:
Q: How to access stageDependencies variables in multiple stages in Azure Release pipeline using bash In Azure, I have a release pipeline with two stages. The first stage stores a value to a pipeline variable. I need to access that variables value in the 2nd stage's tasks. Currently the value retrieved in the second stage is empty. Is it however not empty when accessed within the same stage (multiple tasks in the same stage).
I have checked out Microsoft's documentation and it seems to only show YAML.

A:
How to access stageDependencies variables in multiple stages in Azure Release pipeline using bash

Yes, the Stage to stage dependencies only used for the YAML pipeline.
For the Classic pipeline, we need to pass them manually so that we can use them in the next stage.
We could use the REST API to update the variable in the Variables tab.
Steps:

*

*Define a variable in the release definition Variable.

*Use REST API (Definitions - Update) to update the value of the release
definition variable in the stage 1.

*Use the updated value of the release definition variable in the second stage.

The details info about using REST API to update the value of the release definition variable, you can follow the below ticket:
How to modify Azure DevOps release definition variable from a release task?
or you could use the Azure CLI to update the variable:
az pipelines variable update --name
                             [--allow-override {false, true}]
                             [--detect {false, true}]
                             [--new-name]
                             [--org]
                             [--pipeline-id]
                             [--pipeline-name]
                             [--project]
                             [--prompt-value {false, true}]
                             [--secret {false, true}]
                             [--subscription]
                             [--value]


text:
Q: Is it possible to create full screen color overlay effects in windows? I remember my old Radeon graphics drivers which had a number of overlay effects or color filters (whatever they are called) that would render the screen in e.g. sepia tones or negative colors. My current NVIDIA card does not seem to have such a function so I wondered if it is possible to make my own for Vista.
I don't know if there is some way to hook into window's rendering engine or, alternatively, into NVIDIA's drivers to achieve this effect. While it would be cool to just be able to modify the color, it would be even better to modify the color based on its screen coordinates or perform other more varied functions. An example would be colors which are more desaturated the longer they are from the center of the screen.
I don't have a specific use scenario so I cannot provide much more information. Basically, I'm just curious if there is anything to work with in this area.

A: You could have a full-screen layered window on top of everything and passing through click events.. However that's hacky and slow compared to what could be done by getting a hook in the WDM renderer's DirectX context. However, so far it's not possible, as Microsoft does not provide any public interface into this.
The Flip 3D utility does this, though, but even there that functionality is not in the program, it's in the WDM DLL, called by ordinal (hidden/undocumented function, obviously, since it doesn't serve any other purpose). So pretty much another dead end, from where I haven't bothered to dig deeper.
On that front, the best we can do is wait for some kind of official API.


text:
Q: How does C++ Opengl circle function work I am reading a book of opengl and there is a function to draw a circle but I don't know how to put this function in my code and run it and also I don't know what parameter I put in this.
I am new to opengl and I am trying to figure it out.
Code
#include <stdlib.h>
#include <GL/glut.h>
#include <cmath>

void keyboard(unsigned char key, int x, int y);
void display(void);
void drawCircle(float cx, float cy, float r, int num_segments);

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutKeyboardFunc(&keyboard);
    glutDisplayFunc(&display);
    glutMainLoop();

    return EXIT_SUCCESS;
}

void keyboard(unsigned char key, int x, int y)
{
    switch (key)
    {
    case '\x1B':
        exit(EXIT_SUCCESS);
        break;
    }
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    //drawCircle(, , , );
    glFlush();
}

void drawCircle(float cx, float cy, float r, int num_segments)
{
    glBegin(GL_LINE_LOOP);
    for (int i = 0; i < num_segments; i++)
    {
        float theta = i * (2.0f * PI / num_segments); // get the current angle
        float x = r * cos(theta); // calculate the x component
        float y = r * sin(theta); // calculate the y component
        glVertex2f(x + cx, y + cy); // output vertex
    }
    glEnd();
}

A: You're missing window creation and a setting the color of the circle you are
drawing:
#include <stdlib.h>
#include <gl/glut.h>
#include <math.h>
#define M_PI 3.14159265359

void keyboard(unsigned char key, int x, int y);
void display(void);
void drawCircle(float cx, float cy, float r, int num_segments);

int main(int argc, char** argv)
{
  int width = 1280;
  int height = 720;
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
  glutInitWindowSize(width, height);
  glutCreateWindow("circle");
  glutKeyboardFunc(&keyboard);
  glutDisplayFunc(&display);
  glutMainLoop();
  return EXIT_SUCCESS;
}

void keyboard(unsigned char key, int x, int y)
{
  switch (key)
  {
  case '\x1B':
    exit(EXIT_SUCCESS);
    break;
  }
}

void display()
{
  glColor3f(1.0, 0, 0);
  glClear(GL_COLOR_BUFFER_BIT);
  gluOrtho2D(0.0, 1280, 0.0, 720);
  glColor3f(1.0, 1.0, 1.0);
  drawCircle(640, 360, 100, 200);
  glFlush();
}

void drawCircle(float cx, float cy, float r, int num_segments)
{
  glBegin(GL_LINE_LOOP);
  for (int i = 0; i < num_segments; i++)
  {
    float theta = i * (2.0f * M_PI / num_segments); // get the current angle
    float x = r * cos(theta); // calculate the x component
    float y = r * sin(theta); // calculate the y component
    glVertex2f(x + cx, y + cy); // output vertex
  }
  glEnd();
}


text:
Q: Is there a difference between \textit and \itshape? I have only ever used \textit (and \emph for emphasized text), but have noticed that in some TeX examples, \itshape is used instead of \textit. Is there a difference between \textit and \itshape? If so, what is that difference?

A: \itshape is a switch:
Not italic {\itshape Italic} Not italic

\textit takes an argument:
Not italic \textit{Italic} Not italic

Many people seem to like \itshape{...}, which is wrong (but doesn't give an error since the braces are interpreted as grouping delimiters here).
\itshape doesn't automatically insert italic correction, whereas \textit does, so inside a paragraph, \textit is usually better. On the other hand, sometimes the switch commands are more handy if you already have grouping (e.g., with braces or environments):
\begin{table}
  \itshape
  Everything inside this table is italic
\end{table}

A: *

*\itshape is a declaration. It affects the following text. That's why it's often used for larger amounts of text or within a group. In contrast, \textit affects only its argument.

*\textit provides italic correction, \itshape does not. This means, that immediately after an italic text made by \textit there's a little more space before the following text, compared with \itshape. A reason for the correction is, that because of the slanting the spacing could be too narrow, visually. It depends on the font.

*\textit works in math mode, \itshape doesn't work in math mode.
Here's code for \textit, from latex.ltx:
\DeclareTextFontCommand{\textit}{\itshape}

\def \DeclareTextFontCommand #1#2{%
  \DeclareRobustCommand#1[1]{%
    \ifmmode
      \nfss@text{#2##1}%
    \else
      \hmode@bgroup
       \text@command{##1}%
       #2\check@icl ##1\check@icr
       \expandafter
      \egroup
    \fi
                       }%
}

As you can see, \textit uses \itshape but does more regarding math mode and italic correction.

A: \itshape and others like it (bfseries) are modal commands which don't take arguments.  They change all succeeding text to that font shape/weight etc.  \textit (and textbf) is a macro that takes an argument.


text:
Q: Two array series with different time stamps and a different number of data points I have 2-time series data with different time stamps and a different number of data points.
First one:
[
 { time: "2020-03-10T06:48:08.884220928Z", value: 99.05870056152344 }

 { time: "2020-03-10T06:48:10.888220928Z", value: 99.09293365478516 }

 { time: "2020-03-10T06:48:14.890221056Z", value: 99.17850494384766 }

 { time: "2020-03-10T06:49:18.894221056Z", value: 99.12715911865234 }

 { time: "2020-03-10T06:49:20.895220992Z", value: 99.16139221191406 }

 { time: "2020-03-10T06:49:24.900220928Z", value: 99.14427185058594 }

 { time: "2020-03-10T06:49:26.901220864Z", value: 99.21273040771484 }

 { time: "2020-03-10T06:50:30.904220928Z", value: 99.24696350097656 }

 { time: "2020-03-10T06:50:32.904220928Z", value: 99.22985076904297 }

 { time: "2020-03-10T06:50:36.910221056Z", value: 99.22985076904297 }
]

and the second one:

[
{ time: "2020-03-10T06:48:59.000Z", value: 0 }

{ time: "2020-03-10T06:49:01", value: 61.7744735137 }

{ time: "2020-03-10T06:49:05", value: 27.1289544868 }

{ time: "2020-03-10T06:49:09", value: 100 }
]

As I have seen in the stacked line chart https://www.echartsjs.com/examples/en/editor.html?c=line-stack one has to add additional data points to the second array in order to plot it correctly. Otherwise only 4 first points on xAxis (positions 0,1,2,3) are shown on the chart for the second distribution.
Which is not what I want. I need to place the location according to the data stamp.
Is there a way to just plot this points in the chart without altering the second array which will be feeding the second series object with nulls?

A: I have figured out my solution but it is a strange one
so, basically, one needs to feed the data with each point of second.
In order to do so for different arrays of timestamps, one gets the start and end times, runs a loop with each second added and populates the the first series (0) data with this array. Only afterwards will the points from subsequent data series (1 and 2) start to adjust correctly to the timestamp points from series 0.
This is totally unclear from the documentation on the official example page.


text:
Q: tty всегда в RAM В случае зависания системы (например при активном использовании swap раздела) приходится подолгу ждать переключения в tty (ctrl+alt+fN). Как можно запретить перемещать процесс tty в swap? Или каким образом можно быстро починить зависшую систему?

A: Быстро починить - это убить процесс жрущий ресурсы. Например через SysRq -
прописываем в /etc/sysctl.conf
kernel.sysrq = 1

или без перезагрузки sysctl -w kernel.sysrq=1
Теперь убить 1 самое активное приложение по мнению OOM достаточно один раз нажать
Alt+PrntSrc+F

Есть опасность, не известно, какое приложение  ООМ решит убить, это может быть и вкладка в браузере - где обновилась вкладка с множеством медиа банеров, плеером или музыкой, а может и графический интерфейс. Ещё одно нажатие , запустит ООМ ещё раз, и так далее пока не прибьётся всё )
По поводу запрета свопирования для конкретного процесса, думаю тут только играться с приоритетами, например как советуют тут: https://superuser.com/questions/243357/how-to-prevent-a-specific-program-from-swapping


text:
Q: Huge data in C++ program during compile time I have around 30 XML files, which my C++ process (at run time) should parse and make some installation.
I felt, instead of using XML at runtime, why can't I write a script which will encode the XML files into my own structure and generate a C++ program which should be compiled and built?
What I mean is, my script should populate the encoded structure as a variable assignment in C++ program.
Something like
class generatedCode
{
private:
   unsigned char = ox11, ox22....
};

Then my C++ process will decode this and do installation instead of XML parsing.
My whole intention is the bring all the XML info by some means into C++ process memory.
Can someone please suggest, is this a good way? Do suggest any other ways of doing it?

A: You could indeed "compile" (i.e. transform) these XML files into a more compact representation, and you might even generate a huge array to represent it in C++ code.
Perhaps a simpler solution could be to transform these XML files into your internal representation, and to use some fast memory projection mechanism (like mmap on Linux) to access it.
But you did not explain what these XML files represent and how do you want to use them later inside your application.

A: Maybe I'm not interpreting your proposal correctly, but it sounds like you are starting with XML files, which describe how some installation process needs to be done.  And you want to avoid parsing the xml by translating it into C++ code which can be compiled to do the installation.
If this "installation" is to be executed repeatedly, then this optimization you suggest might be worthwhile.  But you aren't avoiding parsing the XML -- you need to parse it in order to translate them into your C++ program(s)!  So your savings are in avoiding re-parsing the XML for each run, at the cost of having extra files (the executables) as well as having to re-build them whenever the XML changes.
Of course. if I'm misunderstanding the situation, as Roseanne Roseannadanna would say, "never mind" :)


text:
Q: Gnuplot_Set line style_frequency of the points Hello I have plotted data from three different files against time series. I have used different line colours and line points. I have two questions regarding the line points.

*

*In the plot below the frequency of the line points differ in one of the output. I could not figure out the reason for it as I used the same code for all the three outputs.
set style line1 lc rgb 83b300 lw 4 pt 4 pi500 ps2

The input files for the dark green and light green colour outputs contains the data in time steps of 0.01 seconds whereas the input file for the orange colour output contain the data in time steps of 0.02. Could it be the reason for different frequency of the line points?

*Is it possible to get the line points wiht a phase shift? I mean all the line points should not be alligned in the same vertical line and there should be some phase shift. so that it will be easy to distinguish if all the three outputs fall on the same line

A: I think you answered your first question already, since you have a different sampling in one of the three files.
For the second part, you could sample the three files with different time steps that are not divisible by one another, then the point would not align.  You could also introduce a shift doing
plot "file" using ($1+0.005):2 ...

but then the plot would not ultimately reflect the underlying data.
As a final comment, why is your y-range so large?


text:
Q: running a web project outside eclipse using tomcat I am midway developing my first dynamic web project in eclipse. I am using tomcat v7. I have developed a login.jsp page. On success, it redirects to another home.jsp.
It worked well in eclipse. I edited the web.xml file by changing index.jsp to login.jsp. Both the jsp files are in WebContent folder. Also, i have included a servlet.java file in the jsp file. the servlet file resides in projectName/resources/src/pkg folder.
But when I pasted the project folder as a whole into the Apache/webapps folder, and tried to run the project from browser (after starting tomcat) using localhost:8080/ProjectName/ it returned error 404.
When i tried using localhost:8080/ProjectName/WebContent/login.jsp , then the jsp file was loaded. But on entering the correct username and password, it didnt redirect to home.jsp.
Can anyone please help me.. Thanks in advance.

A: Don't paste the whole project, you must export it as a WAR file and then copy it to the Tomcat 's webapp folder.

A: Package the application as a WAR file and put it in Tomcat's webapps directory.
Tomcat will automatically deploy the application on startup.
You cannot simply drop an Eclipse project directory in to Tomcat since Eclipse projects won't generally follow the Java EE webapp directory structure. Eclipse creates/moves the artifacts to appropriate locations during the development process "behind the scenes" so everything works.

A: It is most important question in interview for experienced candidates.
We can auto deploy the java source code in tomcat by using the following file example.
Location:
E:\Tomcat6.0\conf\Catalina\localhost\DMS.xml.
From this file we need to do our configurations in DMS.xml file.
Here DMS is my project name.
Example
Context antiJARLocking="true" docBase="E:\DMS\build\web" path="/DMS"


text:
Q: A ring without zero divisors that can't be extended to a ring with division In the book that I read it says that A. Malcev gave such an example in 1936.
But I can't find it...
any help will be appriciated.

A: Searching for "cannot be embedded in a division ring" with Malcev's name yielded this article, which cites the example on the final page.

Malcev, A. L. "On the immersion of an algebraic ring into a field." Mathematische Annalen 113.1 (1937): 686-691.


text:
Q: General term of a series I am trying to find the general term of the series:
$$( 1 + x + ... + x^{m-1} )^k$$
I am trying to implement the KZ filter and it requires the coefficients of the above series. Here, k and m are dependent on the specific case so they will vary and hence, we need to find the general term for the coefficients.
We tried using the binomial expansions and moving ahead from there, but that did not take us anywhere. So, how do I find the general term of this series in terms of k and m?

A: If we write $$(1+x+...+x^{m-1})^k=\sum_{n=0}^{(m-1)k}a_nx^n=\sum_{n=0}^{\infty}a_nx^n$$
need to find $a_n$ where $a_n=0$ for $n>(m-1)k$
$$(1+x+...+x^{m-1})^k=\left(\frac{1-x^m}{1-x}\right)^k=(1-x^m)^k(1-x)^{-k}=$$
$$=\sum_{i=0}^{k}\binom{k}{i}(-x^m)^i\sum_{j=0}^{\infty}\binom{k+j-1}{j}x^j=$$
$$=\sum_{i=0}^{k}\sum_{j=0}^{\infty}(-1)^i\binom{k}{i}\binom{k+j-1}{j}x^{j-mi}=$$
$j-mi=n\Rightarrow j=n+mi$
$$=\sum_{n=0}^{\infty}\sum_{i=0}^{k}(-1)^i\binom{k}{i}\binom{k+n+mi-1}{n+mi}x^{n}$$
finally we have
$$a_n=\sum_{i=0}^{k}(-1)^i\binom{k}{i}\binom{k+n+mi-1}{k-i}$$


text:
Q: How to convert Google Charts Data Table into python dictionary? I'm using the Google Visualization Library for python (gviz) to generate chart objects. This works great for generating JSON that can be read by the Google Charts using the DataTable.ToJSon method. What I'm trying to do now, however, is add multiple Google Chart data tables to one JSON dictionary. In other words, what I'm making now is this:
Chart_Data = JSON_Chart_Data_1

and what I want to make is this:
Chart_Data = {'Chart_1' : JSON_Chart_Data_1,
              'Chart_2' : JSON_Chart_Data_2,}

Where Chart_Data is converted into a JSON string in both cases.
I'm pretty sure I can do this by converting the JSON string from gviz back into a python dictionary, compile the strings in a container dictionary as necessary, and then convert that container dictionary back into JSON, but that doesn't seem like a very elegant way to do it. Is there a better way? What I'm picturing is a .ToPythonObject method equivalent to .ToJSon, but there doesn't appear to be one in the library.
Thanks a lot,
Alex

A: I ended up doing my original, inelegant, solution to the problem with this function:
def CombineJson(JSON_List):
      #Jsonlist should be a list of tuples, with the dictionary key and the json file to go with that.
      #eg: [('json1', 'some json string'), ('json2', 'some other json string')]
      Python_Dict = {}
      for tup in JSON_List:
            parsed_json = json.loads(tup[1])
            Python_Dict[tup[0]] = parsed_json
      BigJson = json.dumps(Python_Dict)
      return BigJson

Thanks guys,
Alex


text:
Q: Comparing strings and extracting differences at the phrase-level in R I'm trying to compare two columns containing strings in a data frame and extract the differences. However all solutions I've seen extract differences at the character level, and I'm looking to extract entire words/phrases.  I have a dataframe set up like this:
TECH_ID YRTR    pre_drop_courses                post_drop_courses               unchanged
71795   20213   BUSN 2100,BUSN 2400,ACCT 2254   BUSN 1102,BUSN 1102,BUSN 1102   FALSE
71795   20183   BUSN 1102,BUSN 1102,BUSN 1102   BUSN 2100,BUSN 2400,ACCT 2254   FALSE
73677   20183   BIOL 2041,BIOL 2041,BIOL 2041   BIOL 2042,BIOL 2042,BIOL 2042   FALSE
73677   20193   BIOL 2042,BIOL 2042,BIOL 2042   BIOL 2041,BIOL 2041,BIOL 2041   FALSE

For rows that have differences between the pre_drop and post_drop columns I want to extract the entire course code that is different. Ideally I would have a column for what courses were dropped and what were added. For example in the first row BUSN 2100, BUSN 2400, and ACCT 2254 would all appear in the 'dropped' column, and BUSN 1102 would appear in the 'added' column. Likewise in the third row we would see that BIOL 2041 was dropped and BIOL 2042 was added.
Edited to show results of dput(head(mydata, 3))
structure(list(TECH_ID = c("00000108", "00000108", "00000270"
), YRTR = c("20173", "20173", "20183"), pre_drop_courses = c("MUSC 2231,MUSC 2281,MUSC 2231,MUSC 2281,MUSC 2231,MUSC 2281",
"MUSC 2231,MUSC 2281,MUSC 2231,MUSC 2281,MUSC 2231,MUSC 2281",
"ACCT 1853,ACCT 1853,ACCT 1853"), post_drop_courses = c("MUSC 2231,MUSC 2281,MUSC 2231,MUSC 2281,MUSC 2231,MUSC 2281",
"MUSC 1116,MUSC 1116,MUSC 1116", "ACCT 1853,ACCT 1853,ACCT 1853"
), unchanged = c(TRUE, FALSE, TRUE)), row.names = c(NA, 3L), class = "data.frame")

A: Allow me to handle the process of making the course list unique while I'm at it, since it makes the solution cleaner.
Load stringr to take out any unnecessary whitespace, and then split the string of courses into a vector of courses...
library(stringr)
df$pre <- stringr::str_split(stringr::str_squish(df$pre_drop_courses), ",")
df$post <- stringr::str_split(stringr::str_squish(df$post_drop_courses), ",")

Use Map to get the unique values of courses for pre and post
df$pre <- Map(unique, df$pre)
df$post <- Map(unique, df$post)

Use Map to find the set differences.  One direction is adds the other is drops
df$dropped <- Map(setdiff, df$pre, df$post)
df$added <- Map(setdiff, df$post, df$pre)

df
#>    TECH_ID  YRTR               pre_drop_courses             post_drop_courses
#> 1 00000108 20173  BUSN 2100,BUSN 2400,ACCT 2254 BUSN 1102,BUSN 1102,BUSN 1102
#> 2 00000108 20173 BUSN 1102,BUSN 1102,BUSN 1102  BUSN 2100,BUSN 2400,ACCT 2254
#> 3 00000270 20183  BIOL 2041,BIOL 2041,BIOL 2041 BIOL 2042,BIOL 2042,BIOL 2042
#>   unchanged                             pre                            post
#> 1      TRUE BUSN 2100, BUSN 2400, ACCT 2254                       BUSN 1102
#> 2     FALSE                       BUSN 1102 BUSN 2100, BUSN 2400, ACCT 2254
#> 3      TRUE                       BIOL 2041                       BIOL 2042
#>                           dropped                           added
#> 1 BUSN 2100, BUSN 2400, ACCT 2254                       BUSN 1102
#> 2                       BUSN 1102 BUSN 2100, BUSN 2400, ACCT 2254
#> 3                       BIOL 2041                       BIOL 2042

Your original sample data
df <-
   structure(list(TECH_ID = c("00000108", "00000108", "00000270"),
   YRTR = c("20173", "20173", "20183"),
   pre_drop_courses = c("BUSN 2100,BUSN 2400,ACCT 2254",
                        "BUSN 1102,BUSN 1102,BUSN 1102 ",
                        "BIOL 2041,BIOL 2041,BIOL 2041"),
   post_drop_courses = c("BUSN 1102,BUSN 1102,BUSN 1102",
                         "BUSN 2100,BUSN 2400,ACCT 2254",
                         "BIOL 2042,BIOL 2042,BIOL 2042"
                                                             ),
   unchanged = c(TRUE, FALSE, TRUE)), row.names = c(NA, 3L), class = "data.frame")


text:
Q: How do I add a extra row on top and assign category in R? The original dataframe I have doesn't specify what those values are. Now I want to add a extra on top and add category to each column like below:
Original has only two row and no category names:

blank
blank

1
34

2
22

I want to transform it like this:

Habitat
Count of birds

1
34

2
22

How do I do this?
I found several functions on Google, but the don't really match with my needs.


text:
Q: Passing multiple dataframes from a list into a new dataframe I have a problem facing with lists, list where each value has two columns like a whole data frame. how do I pass each value into a new data frame?
For suppose, I have three dataframes which are loaded into list name A as shown below
df10 = pd.DataFrame({'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]})
df20 = pd.DataFrame({'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]})
df30 = pd.DataFrame({'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]})
A = [df10,df20,df30]

the output for this will be:
[ one two 0 1.0 4.0 1 2.0 3.0 2 3.0 2.0 3 4.0 1.0, one two 0 1.0 4.0 1 2.0 3.0 2 3.0 2.0 3 4.0 1.0, one two 0 1.0 4.0 1 2.0 3.0 2 3.0 2.0 3 4.0 1.0]

Now I want to get back those data frames out of the list, how do I do that?

A: As stated by @Lambda in the comments, access individual item of the list by using index. See python tutorial for more.
import pandas as pd

# define 3 different dataframes
df10 = pd.DataFrame({'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]})
df20 = pd.DataFrame({'one' : [3., 4., 5., 6.], 'two' : [6., 5., 4., 3.]})
df30 = pd.DataFrame({'one' : [7., 8., 9., 0.], 'two' : [0., 9., 8., 7.]})

# combine them in the list
A = [df10,df20,df30]

# access each item of the list (dataframe) directly by using index (A[i])
print(A[0],"\n")
print(A[1],"\n")
print(A[2],"\n")

# access all items (dataframes) in the loop
for x in A:
    print(x,"\n")


text:
Q: Using an old graphics card on a new mother board I will be getting my ASUS P8Z77-V Z77 MB ATX 2400 (O.C) SLI Crossfire motherboard today that will be running the Intel Core i7-2600K. I have an old EVGA GeForce 8800GT and was curious if I could use it on this board. I've been out of this for quite a while and don't really know how old components work with new ones. What are the considerations when placing older components into newer boards? Will the on-board Intel® HD Graphics (CPU embedded) display surpass the capabilities of said card?

A: As long as the graphic card uses a PCI-E Slot, which I assume it does, you will have no problem using it on that board. Unless it is a monster card with extraordinarily great length or cooler.
The embedded GPUs in the Intel chips are not that bad, they can play HD movies without a problem, but for gaming I would not reccommend using them. If you do not play with your computer you should take into account that a GFX-card like the 8800GT will use up a lot of additional energy, so it might be relevant on your electric bill at the end of the month.

A: There might be some issues with getting the drivers for the old card if it is really 'that' old.  But as Walter suggested, so long as the motherboard has a slot that has the same form factor as the graphic card you should be good to go.


text:
Q: MongoDB Aggregate by subgroup already group by Date I have a mongo collection which contains Projects and represented like this (small sample):
{
    {
        "_id" : ObjectId("5c615f9141d6ec562be9fd4d"),
        "title" : "Project1",
        "_created" : ISODate("2019-02-11T11:42:09Z"),
        "org" : [
            "ORG1"
        ]
    }
    {
        "_id" : ObjectId("5cf4ec11362a5f02b74effd3"),
        "title" : "Project2",
        "org" : [
            "ORG2"
        ],
        "_created" : ISODate("2018-06-03T09:44:49Z")
    }
    {
        "_id" : ObjectId("5d0362eb362a5f488a315508"),
        "title" : "Another Project",
        "org" : [
            "ORG3"
        ],
        "_created" : ISODate("2019-06-14T09:03:39Z")
    }
    {
        "_id" : ObjectId("5d0362eb362a5f488a315508"),
        "title" : "Multi Org Project",
        "org" : [
            "ORG1",
            "ORG3"
        ],
        "_created" : ISODate("2018-06-14T09:03:39Z")
    }
}

What I would like to do is to known by a time interval (e.g $day/$month/$year) the number of project created in each organisation (org).
I am struggling at doing that in a mongo aggregation.
I succeed to do this :

*

*Counting the number of projects created by year

db.projects.aggregate({$group:{_id:{$year: "$_created"}, project:{$sum:1}}})

*

*Counting the projects created by Org

db.projects.aggregate([{$unwind:"$org"}, {$group:{_id: "$org", project: {$sum:1}}}])

But how combinate both ? I don't want to force any results format but he would be something like :
{
    2017: {
        "ORG1": 12,
        "ORG2": 3,
    },
    2018...
}

I found lot of question about MongoDB Aggragation Framework but I still don't get it.
Thanks for your help!

A: unwind your org array, then group twice to achieve this :
db.collection.aggregate([
  {
    $unwind: "$org"
  },
  {
    $group: {
      _id: {
        year: {
          $year: "$_created"
        },
        org: "$org"
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $group: {
      _id: "$_id.year",
      res: {
        $addToSet: {
          org: "$_id.org",
          count: "$count"
        }
      }
    }
  },
])

WIll output
[
  {
    "_id": 2018,
    "res": [
      {
        "count": 1,
        "org": "ORG1"
      },
      {
        "count": 1,
        "org": "ORG3"
      },
      {
        "count": 2,
        "org": "ORG2"
      }
    ]
  },
  {
    "_id": 2019,
    "res": [
      {
        "count": 1,
        "org": "ORG2"
      },
      {
        "count": 1,
        "org": "ORG1"
      },
      {
        "count": 1,
        "org": "ORG3"
      }
    ]
  }
]

You can add further stages to reshape your documents if needed.
Mongo playground