text:
Q: How do you set an on click function for a dynamically created textview? Okay so I want to dynamically create a text view, then upon clicking that textview I went it to run a function. Here is my code
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = data.getExtras();
        contacts.add(bundle);
        String fname = bundle.getString("fname");
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout layout = (LinearLayout) findViewById(R.id.contactList);

        TextView textView = new TextView(this);
        textView.setLayoutParams(params);
        textView.setText(fname);
        textView.setId(idCounter);
        textView.setOnClickListener(showDetails());
        layout.addView(textView);

    }

And here is the function that I wish to call
public void showDetails(View view){
        //create intent
        //get id of textview
        //get bundle object for that textview
        //send bundle object to new activity
        //start new activity

    }

How would I get the text view to call showDetails on clicking the textview?

A: You have to pass a View.OnClickListener instance to setOnClickListener:
View.OnClickListener listener = view -> {
    showDetails();
};
textView.setOnClickListener(listener);


text:
Q: Joke "Hipster burns his mouth" - why is it funny? The joke is: why did the hipster burn his mouth? Because he drank his coffee / ate his pizza / etc. before it was cool.
Why is it funny? Does the hipster have special meaning or background?

A: Hip and hep are adjectives from American slang of the early 20th century, meaning in the know. According to the Historical Dictionary of American Slang, hip become the common form by the 1960s. The suffix -ster nominalizes an adjective, so a hipster is someone in the know, that is, someone familiar with and sophisticated about societal trends. The HDAS can find an attribution from 1940.
The HDAS traces the slang cool meaning fashionable back to 1946. Putting the words together, we can say that hipsters appreciate trends that are cool. In fact, the most avant-garde, the hippest of hipsters pride themselves on appreciating trends before other people catch on that those trends are cool.
So the joke, such as it is, is word play on the two meanings of cool -- the one meaning not elevated in temperature and the slang one meaning trendy. So in the slang meaning, a hipster tries things before those things are commonly judged to be cool. But extending that to the ordinary meaning in eating or drinking means ingesting things that are hot and liable to burn.

redpajama_set_name: RedPajamaStackExchange


text:
Q: my login page is going to next page but shows warning sign first that  <?php

     session_start();

            $c=mysqli_connect('mysql.hostinger.in','u808297599_eval','nandini123');
      if(!$c)
      exit("ERROR");
   $db=mysqli_select_db($c,'u808297599_eval');
   if(!$db)
    exit("ERROR");
       $e=$_POST['username'];
       $p=$_POST['password'];
        $_SESSION['username']=$e;
        $query="SELECT * FROM tecaherlogin WHERE username='$username' AND     password='$password' ";
            $result=mysqli_query($c,$query);
       $exists=mysql_num_rows($result);

       if ($exists!=0)
       {
                     //while loop
              while ($row = mysqli_fetch_assoc($query))
              {
               $dbusername = $row['username'];
               $dbpassword = $row['password'];
                  }
              if($dbpassword==$p)
                        {
                Print '<script>alert("Correct Password!");</script>';
                 Print '<script>window.location.assign("evaluate.html");     </script>';}

                else
             {
                Print '<script>alert("Incorrect Password!");</script>';
                 Print       '<script>window.location.assign("teacherloginnew.html");</script>';
    }
   }
  else
  echo "user does not exist!";
  ?>

I get this error:

warning:mysqli-fetch-assoc expects parameter 1 to be mysqli_result, string given

This shows up before loading the page, the warning sign should not be there as this is for my project. Please help.

A: You're trying to fetch_assoc of a string $query.
Your mysqli_result is the variable $result, which is the one you should be passing here:
while ($row = mysqli_fetch_assoc($query))

Do this:
while ($row = mysqli_fetch_assoc($result))

This query below will already verify if the password is correct. So you don't need to fetch assoc again below.
$query="SELECT * FROM tecaherlogin WHERE username='$username' AND     password='$password' ";

You just need this:
$exists=mysql_num_rows($result);

    if ($exists!=0)
    {
        Print '<script>alert("Correct Password!");</script>';
        Print '<script>window.location.assign("evaluate.html");     </script>';
    }
    else
    {
        Print '<script>alert("Incorrect User or Password!");</script>';
        Print '<script>window.location.assign("teacherloginnew.html");</script>';
    }


text:
Q: QGIS GDAL selects XYZ driver rather than GTIFF etc I think this is an issue to do with running QGIS on a mac but I might be wrong.
When I run a GDAL tool like clipper or translate GDAL seems to select the -XYZ driver regardless of what the input files are so the tool fails to run properly. If I manually edit the GDAL script to change the -XYZ to GTIFF the tool runs fine.
I have been living with this for a while but it would be nice to fix it.
QGIS 2.18 kyngKhaos MAC OSX 1405.7461 El Capitan i7 32GB ram


text:
Q: How to make sure the ordering of sending message to channel are right I know this is wrong
func e6() {
    c1 := make(chan struct{}, 1)
    <-c1
    go func() {
        c1 <- struct{}{}
    }()
}

and this is right
func e6() {
    c1 := make(chan struct{}, 1)
    go func() {           //statement1
        c1 <- struct{}{}
    }()
    <-c1        //statement2
}

Since we cannot assume the order of the statement1 and statement2 in the right example, what if the statement2 executes ahead of statement1, and in this case, the right example just looks like the wrong example, but why is that right? Thanks for helping me.

A: Actually, here is what happens after you spawned the goroutine: Either the goroutine is executed first and the channel is populated so you can read from it (<-c1) right away. Or the read statement is executed first, but since there is nothing to read from that channel, it waits until something can be read ("It blocks"). Now the goroutine scheduler kicks in, notices that one of two goroutine blocks and it "finally" executes the other goroutine, which populates the channel and exits, making the blocking goroutine the only remaining so it gets execution time again. But now the channel is populated, it can be read from, the value from the channel is read into nothing and the original goroutine continues, ending the function.
Please noted that this is a bit simplified, and you should definitely read up on goroutines.

A: This is wrong:
func e6() {
    c1 := make(chan struct{}, 1)
    <-c1
    go func() {
        c1 <- struct{}{}
    }()
}

because the execution goes into a deadlock. By calling <-c1 in the main function thread, you are blocking on a receive from an open channel. Receive will block until it receives some data from c1 but no process is sending any data on it. The goroutine that is suppose to send on c1 hasn't started yet since code execution got blocked before reaching the go statement.
In the correct implementation:
func e6() {
    c1 := make(chan struct{}, 1)
    go func() {           //statement1
        c1 <- struct{}{}
    }()
    <-c1        //statement2
}

it doesn't matter which statement runs first. If statement1 runs first, the goroutine (running in a different thread) blocks at send on c1 (c1 <- struct{}{}) since statement2 hasn't executed yet and no other process is receiving data from c1. This results in the entire goroutine blocking and yielding execution to the main function thread where statement2 will execute (remember that go statement generally does not block). This time statement2 will not block because some other process (statement1) is already ready with the data to send over c1. Thus both the threads continue to completion.
Similar reasoning can be made for the case in which statement2 executes first.


text:
Q: Prevent div from new line in table th
As you can see the progressbar is not in line with the text.
The bar is an seperate div:

    Atv opgenomen / totaal: 22:48 h / 62.0 h

<?php
                echo '

                    '.round($perc_bar_atv).'%

';
            ?>

Any suggestions how to get this inline? I have tried style="display: inline" That works but removes some the markup

style="display: inline-block; vertical-align:center"gives

A: It seems to set proper margin for .progress is enough, like this:
.progress {
    margin: 10px 0 !important;
}

or this
.progress {
    margin: auto 0 !important;
}

.progress {
    margin: 10px 0 !important;
}
 th {
     border: 1px solid green;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    Atv opgenomen / totaal: 22:48 h / 62.0 h

50%


text:
Q: The R package XLSX is converting entire column to string or boolean when one cell is not numeric I am using a shiney interface under R to read in a CSV file and load it into one sheet of an excel xlsm file. The file then allows user input and preforms calculations based on VBA macros.
The R xlsx package is working well for preserving the VBA and formatting in the original excel sheet. However some of the data is being converted to a different data type than intended. For example a cell containing the string "F" is causing the column containing it to be converted to type boolean, or a miss-entered number in one cell is causing the entire column to be converted to string.
Can this behavior be controlled so that, for example, cells with valid numbers are not converted to string type? Is there a work-around? Or can someone just help me to understand what is happening in the guts of the package to cause this effect so I can try to find a way around it?
Here are the calls in question:
#excelType() points to an excel xlsm template

data = read.csv("results.csv")
excelForm = loadWorkbook(excelType())
sheets = getSheets(excelForm)
addDataFrame(data, sheets[[1]], col.names = FALSE, row.names = FALSE, startRow=2, colStyle = NULL)
saveWorkbook(excelForm, "results.xlsm")

Thanks!

A: I hope this is the correct protocol for explaining the outcome which worked for me. I hope it will be of help to others if they end up doing something similar, though the solution is not very elegant!
I tried r2evans's suggestion of forcing column types I could not get that to work in this case. Using readxls gave the same problem, and also broke my VBA. Given lebelionz's comment suggesting that this is an R thing and not a package thing I followed his advice to deal with it after the fact. (I do not see how to credit a comment rather than an answer, but for the record this was very helpful, as were the others).
I therefore altered the program producing the CSV that was being loaded through R. I appended "::" to each cell produced, so that R saw all cells as strings, regardless of the original content. Thus "F" was stored as "::F", and therefore was not altered by R.
I added an autorun macro to the excel sheet thus created, so that when opened it automatically performed a global search and replace to remove the prefix "::" from the whole of the data. This forces Excel to choose a data type for each cell after it was restored, resulting in the types being detected cell by cell and in the correct format for my purposes.
It feels kludgy, but it works and is relatively transparent to the user. One hazard is that if the user data intentionally contained the string "::" it would be lost (I am confident this cannot arise in my particular application, but if someone would like to suggest a better prefix I would be interested). I still hope for an eventual solution rather than a work-around.
And here I thought it was only the movie industry that had to "fix it in post"!


text:
Q: Ordering of format strings in Python's struct There seems to be some ordering issues when using format strings in Python.
For example, I am trying to unpack, in order: 3 doubles, 1 float, 2 doubles.
This should be 5*8+4 == 44 bytes in size.
Consider the following code:
import struct

A = struct.calcsize("dddfdd")
B = struct.calcsize("dddf")+struct.calcsize("dd")
C = struct.calcsize("dddddf")

For me, in Python 3.6.9 on Linux, I get that A == 48, meanwhile B == C == 44 (as I would expect).
This means that something like the following would fail, when packed_data is 44 bytes.
unpacked_data = struct.unpack('dddfdd',packed_data)

I can, instead, resort to:
unpacked_data1 = struct.unpack('dddf',packed_data1)
unpacked_data2 = struct.unpack('dd',packed_data2)

What gives? Is there a better way to do the unpacking?

A: Try to specify a byte order with your format string:
# assumes a native byte order, size and alignment.
# This means for alignment purposes, that it will align bytes to multiples of 8 bytes
A = struct.calcsize("dddfdd")

# if you prepend '=' infront of the format string, the order assumes system byte order and no alignment
A = struct.calcsize("=dddfdd")
# A == 44

To check your system byteorder you can also use:
import sys
print(sys.byteorder)

As reference look here


text:
Q: NVIDIA 520 Open, unable to set the dual monitor I created a backup of my system first using Timeshift, then I installed NVIDIA 520 Open. After I rebooted my system, the external monitor is not working (HDMI cable is securely plugged in on both ends)
I then restore my system backup and was able to see my external monitor.
How can I install NVIDIA 520 Open and make my external monitor work simultaneously?
System Info


text:
Q: Ranking text to see if they got a better health plan I need to write code that will evaluate whether their plan change from the previous year and put "Moved Up" in a column to the right if the plan changed. First the code needs to make sure that they have the same member ID and that it is a new year. Here is what it looks like in excel:
 000880093121    2015     Bronze 60 HMO
 000880093121    2016     Silver HMO

My first thought was to use nested IF statements but I do not know how to tell excel that the Silver plan is a better plan than Bronze. There is a total of five different plans that members can have.
=IF(A3=A2,IF(B3>B2,"Moved Up"))

This will successfully compare the member ids and make sure that it is a new year. I just do not understand how to give text values a numeric value so that it can be compared. Also there is over 30k rows that I will be applying it to.
The output that I am looking for should be this:
 000880093121    2015     Bronze 60 HMO     -
 000880093121    2016     Silver HMO        Moved Up

Thanks for the help, much appreciated.

A: Put the different plans in a table sorted from "least-good" (top) to "best" (bottom), and name that range (e.g.) "planTable".
Then you can do this:
=IF(AND(A3=A2,B3>B2),
    IF(MATCH(C3,plantable,0)>MATCH(C2,plantable,0),"Moved Up",""),
    "")


text:
Q: How to use Hyperopt or perform hyperparamter tuning on a GAN? I am creating a Generative Adversarial Network, and I want to run Hyperopt on the GAN. However, I am confused about how to do this in Python in Keras because the GAN is essentially 2 models, with the output of one model, going into the next model. Any other method to run Bayesian Optimization or performing HP tuning on a GAN would be helpful.

A: Unfortunately I don't think there is an easy way of doing this. It all comes down to this: you need some way to evaluate how good your GAN is, which isn't an easy task.
Why not use the discriminator?
The way evaluation is done during training is through the discriminator. So, one first thought would be to hold out one part of the training samples, generate the same amount of fake samples and check how many of those the discriminator predicts correctly. Generally speaking the goal is to achieve close to $50\%$ accuracy, i.e. the discriminator is cannot distinguish between real or fake.
This, however cannot work for evaluation. What you are evaluating is how confused the discriminator is. However, discriminator being bad doesn't imply that the generator is good (which is what you want).
Any viable solutions?
There are actually some theoretically-viable, but impractical solutions:

*

*Have a pretrained discriminator to evaluate all generators. To be able to compare generators, you need the same discriminator to evaluate all of them.

*Evaluate them through a secondary task. E.g. if you are generating cat and dog images, see how well an image classifier can classify cats as cats and dogs as dogs.

*Have some other domain-specific way of evaluating how realistic the fake samples are.

Unfortunately, none of these are straightforward to use in an automatic hyperparameter optimization scheme.


text:
Q: Trying to make a photo filter's effects cumulative on the photo-java swing Basically I have made an interface that displays a picture and it has multiple JSliders.  Each one has a different function such as blur, brighten, and saturate.   I have implemented the sliders in such a way that I override the stateChanged method when adding a new slider.  This works fine when I do the sliders individually, however it changes back to the original picture once I use a different slider.  I want to make it so that it the picture accumulates the filters on the photo.  Any suggestions?  Here is an example of one of my sliders.
brightSlider.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {

            JSlider source = (JSlider) e.getSource();
            double scaleValue = source.getValue() / 100.0;
            Picture newPic = new PictureImpl(picture.getWidth(), picture.getHeight());
            //Picture newPic = picture;
            Pixel zeroPixel = new ColorPixel(0, 0, 0);
            Pixel p;
            for (int i = 0; i < picture.getWidth(); i++) {
                for (int j = 0; j < picture.getHeight(); j++) {
                    newPic.setPixel(i, j, zeroPixel);
                }
            }
            for (int i = 0; i < picture.getWidth(); i++) {
                for (int j = 0; j < picture.getHeight(); j++) {
                    if (scaleValue > 0) {
                        p = picture.getPixel(i, j).lighten(scaleValue);
                        newPic.setPixel(i, j, p);
                    } else if (scaleValue < 0) {
                        p = picture.getPixel(i, j).darken(scaleValue);
                        newPic.setPixel(i, j, p);
                    }
                }
            }
            setPic(newPic);
            picture_view.setPicture(newPic.createObservable());
        }
    });

A: As shown in Image processing with Java 2D, you can create a Map<String, BufferedImageOp> that holds concrete instances of the BufferedImageOp interface.
Map<String, BufferedImageOp> ops = new TreeMap<String, BufferedImageOp>();
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ops.put("Gray", new ColorConvertOp(cs, null));
…

Add the Map key set to a JComboBox.
final JComboBox opBox = new JComboBox();
for (String key : ops.keySet()) {
    opBox.addItem(key);
}

In the combo's handler, invoke the image operation's filter() method on your target BufferedImage.
String key = (String) opBox.getSelectedItem();
BufferedImageOp op = ops.get(key);
bufferedImage = op.filter(bufferedImage, null);

The image below illustrates "Threshold 64" followed by "Invert". ImageDicer is a complete example.


text:
Q: Find Index of array I have an JSON object that looks like this . I need to find the index based on ID so that I can retrieve the value. indexOf function seem to work for array of single values. This is almost find index of an array within an array.
I have an for loop that gets me the ID from a different object, my goal is to pull the associated value from the below object without iterating through each element. (Below is a sample actual object has about 50 Id and Value's)
"Field": [
    {
      "id": 360000165507,
      "value": 123
    },
    {
      "id": 360000128528,
      "value": null
    },
    {
      "id": 360000122207,
      "value": xyz
    },
    {
      "id": 360000091348,
      "value": abc
    },
 ]

Thanks
Ashish

A: Use filter() to get the object, then return the indexOf() the object in the obj.Field array:

let obj={Field:[{id:360000165507,value:123},{id:360000128528,value:null},{id:360000122207,value:"xyz"},{id:360000091348,value:"abc"}]};

function getIndexById(id){
    let resObj = obj.Field.filter((el) => el.id == id)[0]
    return obj.Field.indexOf(resObj)
}

console.log(getIndexById(360000122207))


text:
Q: Yang pattern not accepting regex containing ^ and $ Yang pattern does not accept valid Regex when it contains caret ^ or dollar $.
The bellow pattern is valid on Regex validators, but when run inside a Yang pattern template in an is-types.yang file my application errors.
However when i take off the ^ and $ from each part of the expression it works fine. However this now allows the regex to accept unwanted values.
I am trying to match either 1, 11, 1/1/1, 1/1/1/1.
Trying the pattern:
^([0-9]{1,3}/[0-9]{1,3}/[0-9]{1,3})$|^([0-9]{1,3}/[0-9]{1,3}/[0-9]{1,3}/[0-9]{1,3})$|^([0-9]{1,2})$

Yang typedef:
typedef interface_number_value {
    type string {
        pattern "([0-9]{1,3}/[0-9]{1,3}/[0-9]{1,3})|([0-9]{1,3}/[0-9]{1,3}/[0-9]{1,3}/[0-9]{1,3})|([0-9]{1,2})" {
            error-message "error";
        }
    }
    description
        "description";
}

Also I am not sure where to raise issues/bugs with Yang.

A: This is what RFC7950 says about the "pattern" statement:

The "pattern" statement, which is an optional substatement to the
"type" statement, takes as an argument a regular expression string,
as defined in [XSD-TYPES].  It is used to restrict the built-in type
"string", or types derived from "string", to values that match the
pattern.

If you follow the normative reference XSD-TYPES, you eventually get to:

[XSD-TYPES]
Biron, P. and A. Malhotra, "XML Schema Part 2: Datatypes
Second Edition", World Wide Web Consortium Recommendation
REC-xmlschema-2-20041028, October 2004,
http://www.w3.org/TR/2004/REC-xmlschema-2-20041028.

Therefore the regular expressions in YANG "pattern" statements are defined by XML Schema (XSD) type specs (and that specific revision of them for YANG 1.0 and 1.1).
Unlike some other regex flavors, a ^ character at the beginning of a YANG "pattern" or a $ at the end of a YANG "pattern" are not interpreted as anchors. Instead they are interpreted literally as characters that must match. All "pattern" expressions are implicitly anchored and therefore match the entire value.
You can find out more about the specifics of XML Schema Regular Expressions here.


text:
Q: How to .Net Unit Tests with SQLite with Multiple Databases My work has various .Net C# classes to perform discrete actions (i.e. get items in user's shopping cart, get list of products available, etc). I am looking to added unit tests to these classes/methods using Visual Studio unit test projects. My goal is to have the unit tests self contained where they do not depend on an external database. So I started investigating SQLite. I'm thinking each unit test will create it's own "mock" database to be used by the corresponding classes/methods that the unit test is executing.
Here is the problem I am running into. The real classes/methods execute SQL with fully qualified (guess that is the right term) database names and schemas as part of the query. Example:
SELECT * FROM Database01.Schema01.Table01

In SQLite is there a way to make it work with these type of table references? I see there is an ATTACH command where you can attach multiple databases to one connection. Then you reference a table with database-name.table-name. That is still missing the middle schema part though. Any thoughts?

A: If that code does not take care to quote database/schema names correctly, you could name the database [Database01.Schema01] and then tell that code that the database is called [Database01, and the schema, Schema01].
If your code is too smart for that, or if the database/schema names are fixed, then there is nothing you can do with SQLite.


text:
Q: Extracting coefficients with CIs from stan_glm model: Error with fixef-command: Error: Can't combine `..1$fixef`  and `..3$fixef`  Goal: the estimation of coefficients with a confidence interval in one command for stan_glm models.
When trying to extract coefficients CIs of my stan_glm model with fixef(), I get the error below. I try to use the fixef() from bayr instead of rstanarm, because it conveniently provides confidence intervals.
Error: Can't combine `..1$fixef` <character> and `..3$fixef` <logical>.

Here is the simplest model that I tried:
M1 <-  stan_glm(variable ~ 1, data = data)
fixef(M1)

I first thought it might be a conflict in libraries, so I tried activating libraries who use fixef (rstanarm, bayr) in a different order, but that didn't help. At the moment I use the following libraries (in that order):

janitor, haven, data.table, modeest, dplyr, tidyverse, readxl, gridExtra, rstanarm, devtools, mascutils, bayr

Any suggestions on what could be the source of that error?
edit:
rstanarm::fixef(M1) works, but gives the coefficient without confidence intervals. the bayr::fixef() would give them automatically.
I tried also tried the following:
coef(M1)
"Error: Can't combine `..1$fixef` <character> and `..3$fixef` <logical>."

posterior_interval(M01) #gives only confidence interval without the coefficient estimate


text:
Q: starting Android app on multiple emulators simultaneously As we all know, Android resolution is rather fragmented.
I (like many others) don't have all the screen resolution, or OS versions to test my app on.
Emulators give a solution to the resolution and OS problem, but it is getting rather tedious and annoying to run my app on each emulator (even if they are already running) just to see one layout.
So, my question is; is there any way to run my app on EACH emulator I have selected, not doing them individually?
For now, I am using a solution called Manymo, which allows me to launch emulators faster, but my ideal solution would be to start 1 app, and have a setting to be able to launch it simultaneously on several emulators.
I am surprised to see after many searches, that although people ask about running multiple, I can't seem to find anyone who would like to launch an app in multiple instances simultaneously.
Thanks!

A: Once you've got your emulators running, I believe in the Run Configurations control, you can select Launch on all compatible devices/AVD's and then select Active AVD's from the dropdown. I believe this should launch your app on all emulators you have running. Could be quite taxing on your system, though, unless you're swimming in RAM.

A: Im not sure if this is exactly, what you want but you dont even need to start an emulator to check how a layout will look like.
the ADT plugin in Eclipse allows you to check how a layout will look on different versions and devices without having to start each emulator every time.
Graphical Layout , allows you to select a device, the orientation and android OS version.


text:
Q: I do not receive FCM Push Notifications with the application closed. Ionic 3 and Angular Good day folks, it is my first publication on the site, I apologize if I do not comply with all the publication rules because I do not know them in detail.
Step to comment my problem .. I have an app made with ionic 3 and angular, which works with notifications between users to emerge an action, investigate the firebase forums and several other places and tried several codes but I could not fix it. The application sends data and notification to a specific token, the device registered by the token receives the data but not the notification. Not when it is with the application open, or when it is in the background or closed. This is the code you use:
1) To receive the token
 this.fcm.getToken (). then (token => {

         alert ('token' + JSON.stringify (token))

         // Here I save the token I receive from the device
      })

This works .. I can get the device token.
2) To receive the notification:
this.fcm.onNotification (). subscribe (data => {
        if (data.wasTapped) {
          alert ("Received in background")
        } else {
          alert ("Received in foreground")
        };
      })

This also works, when I sent a notification from the firebase console I get it perfectly .. the problem is when I sent it from the server
3) Code for notification:
SendNotific ()
{
let keytoken = 'fqN5yelN7gk: APA91bGT0 ......'
let keyserver = 'AAAA4oCrTNk: APA91bHLBWcyQimF ....'
let headers = {'Authorization': 'key =' + keyserver,
'Content-Type': 'application / json'};
let url = 'https://fcm.googleapis.com/fcm/send';
let body = {
"notification":{
"title": "notification title",
"body": "notification body"
},
"data":{
"key1": "value1",
"key2": "value2"
},
"to": keytoken,
"priority": "high",
"content_available": true
}

this.http.post (url, body, headers) .then (data =>
{
alert (JSON.stringify (data))

}). then (error => {
alert ('error' + JSON.stringify (error))
})
}

If the application is in the foreground of the device, the alert becomes visible, that is, I receive the data that I sent in "Data". (For this case it would be "key1" and "key2") but I do not receive any notification. If the application is in the background or closed, no notification is shown, and when I open the app again the alert messages are shown with the "Data" that arrived.
As I said before, if you sent a notification from the Firebase console it works perfectly ..
Clearly I'm missing some data that I can not find .. I saw several publications that talk about the same thing but I can not give the solution ..
Will I be missing specific data within the notification so it can be visible?
Does the user need to accept any permission to receive the notification?
Thank you very much and sorry if I could not explain clearly
regards,
Julian.

A: So, the first thing I note in your code is that Sender is missing from headers.
headers should be something like:
let headers = {
               'Authorization': 'key=' + keyserver,
               'Content-Type': 'application / json',
               'Sender': 'id=' + senderId
              };

The body will have a to or token for the device token i.e., the recipient. So, the body will be something like:
let body = {
  "token": keytoken,
  "notification":{
    "title": "notification title",
    "body": "notification body"
  },
  "data":{
    "key1": "value1",
    "key2": "value2"
  },
  "priority": "high",
  "content_available": true
}

And, I think you wanted to promisify http and catch the error in http.post. In that case, the code should look something like:
this.http.post(url, body, headers).toPromise().then(data =>
{
  alert (JSON.stringify(data));
}).catch( error => {
  alert ('error' + JSON.stringify (error));
})


text:
Q: Mostrar Count de un Query en un Label Que tal, estoy tratando de mostrar el resultado de un query en el que cuento los resultados dependiendo del where
mi query esta en una carpeta llamada conexiones y dentro tiene una clase llamada conexion-general en esa clase realizo el query de esta manera:
public class conteo_maint
    {
        public DataTable countconnect()
        {
            string myConnectionString = @"C:\\Users\\gutiece\\Desktop\\database\\" + "Database1.accdb";

            DataTable CouMaiTable = new DataTable();

            OleDbConnection connection = new OleDbConnection();
            OleDbCommand command = new OleDbCommand();
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            DataSet dataset = new DataSet();

            try
            {
                connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data source= " + myConnectionString;
                bool ok = System.IO.File.Exists(myConnectionString);
                String qry = "SELECT COUNT(*) FROM status_change WHERE area = maintenance";
                String allqry = "SELECT * FROM status_change WHERE area = maintenance";
                command.Connection = connection;
                command.CommandText = qry;
                command.CommandText = allqry;

                adapter.SelectCommand = command;

                command.Connection.Open();
                OleDbDataReader reader = command.ExecuteReader(); // close conn after
                CouMaiTable.Load(reader);
                if (!reader.IsClosed)
                {
                    reader.Close();
                }

                return CouMaiTable;
            }
            catch (Exception)
            {
            }
            return CouMaiTable;
        }
    }

tengo los dos querys con la finalidad de que uno solo muestre el total y el otro poder llenar un GridView.
despues tengo dashboard.aspx en la cual es donde quiero mostrar el resultado de count. en el Backend mando a llamar a la case de conteo_maint de esta manera:
conexiones.conteo_maint countconnect = new conexiones.conteo_maint();
conexiones.conteo_maint CouMaiTable = new conexiones.conteo_maint();

y quiero que el resultado del conteo se muestre en este label:
<button class="btn btn-primary" type="button">
                  Messages
                      <asp:Label Text="text" runat="server"  id="Lbl_notu"/>
                </button>&nbsp

A: No te hace falta hacer dos queries. Simplemente con la de allqry tendrías bastante.
Devolviendo esto, luego en tu code-behind de dashboard.aspx, simplemente haz un
Lbl_notu.Text = CouMaiTable.Rows.Count y te dirá cuantas filas tiene.


text:
Q: How to separate php mvc controller directories for backend directory and frontend directory? I am struggling to separate controller directories that are responsible for backend controller and frontend controller so it can be easy for working with two parties of the application.
I use this directory structure.
    |APP( DIRECTORY )
    |---CONTROLLERS
            |-Home.php
            |-Error.php
    |---CORE
          |-Application.php
          |-Controller.php
    |---MODEL
          |-User.php
    |---PUBLIC
          |-index.php
          |.htaccess

I want to be able to create backend and frontend contollers directories like this.
    |---CONTROLLERS
        |---FRONTEND
                |-Somecontoller.php
        |---BACKEND
                |-Somecontoller.php|APP( DIRECTORY )

Thanks in advance.
// Application
   <?php

    class Application
    {
        public $url = null;
        public $controller = null;
        public $controllerPath = '../CONTROLLERS/';
        public $modelPath = '../MODELS/';
        public $errorFile = 'Err.php';
        public $defaultFile = 'Home.php';

        public function BootApp()
        {
            $this->parseUrl();

            if (empty($this->url[0]))
            {
              $this->loadDefaultController();
              return false;
            }

            $this->loadExistingController();
            $this->callControllerMethod();
        }

        public function setController($path)
        {
            $this->controllerPath = trim($path, '/') . '/';
        }

        public function setModel($path)
        {
            $this->modelPath = trim($path, '/') . '/';
        }

        public function parseUrl()
        {
            $this->url = isset($_GET['url']) ? $_GET['url'] : null;
            $this->url = str_replace('-', '', $this->url);
            $this->url = filter_var($this->url, FILTER_SANITIZE_URL);
            $this->url = rtrim($this->url, '/');
            $this->url = explode('/', $this->url);
        }

        public function loadDefaultController()
        {
            require $this->controllerPath . $this->defaultFile;
            $this->controller = new Home();
            $this->controller->index();
        }

        public function loadExistingController()
        {
            $file = $this->controllerPath . $this->url[0] . '.php';
            if (file_exists($file)){
                  require $file;
                  $this->controller = new $this->url[0];
            }
            else{
                  $this->error();
            }
        }

        public function callControllerMethod()
        {
            $this->controller->index();
        }

        private function error()
        {
            require realpath($this->controllerPath . $this->errorFile);
            $this->controller = new Err();
            $this->controller->index();
            exit;
        }
    }
}

// PUBLIC / .htaccess
   <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-l
      RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
   </IfModule>

// PUBLIC / index.php
<?php
    // SPL AUTOLOAD CORE, CONTROLLERS, MODELS
    $app = new Application();
    $app->BootApp();
    $app->setController('../CONTROLLERS/');


text:
Q: Spawn multiple telnet with tcl and log the output separately I'm trying to telnet to multiple servers with spawn & i want to log the output of each in a separate files.
If i use the spawn with 'logfile' then, it is logging into a same file. But i want to have it in different files. How to do this?

A: Expect's logging support (i.e., what the log_file command controls) doesn't let you set different logging destinations for different spawn IDs. This means that the simplest mechanism for doing what you want is to run each of the expect sessions in a separate process, which shouldn't be too hard provided you don't use the interact command. (The idea of needing to interact with multiple remote sessions at once is a bit strange! By the time you've made it sensible by grafting in something like the screen program, you might as well be using separate expect scripts anyway.)
In the simplest case, your outer script can be just:
foreach host {foo.example.com bar.example.com grill.example.com} {
    exec expect myExpectScript.tcl $host >@stdout 2>@stderr &
}

(The >@stdout 2>@stderr & does "run in the background with stdout and stderr connected to the usual overall destinations.)
Things get quite a bit more complicated if you want to automatically hand information about between the expect sessions. I hope that simple is good enough…

A: I have found something from the link
http://www.highwind.se/?p=116
LogScript.tcl
#!/usr/bin/tclsh8.5

package require Expect
proc log_by_trace {array element op} {
    uplevel {
        global logfile
        set file $logfile($expect_out(spawn_id))
        puts -nonewline $file $expect_out(buffer)
    }
}

array set spawns {}
array set logfile {}

# Spawn 1
spawn ./p1.sh
set spawns(one) $spawn_id
set logfile($spawn_id)  [open "./log1" w]

# Spawn 2
spawn ./p2.sh
set spawns(two) $spawn_id

set logfile($spawn_id)  [open "./log2" w]
trace add variable expect_out(buffer) write log_by_trace

proc flush_logs {} {
    global expect_out
    global spawns
    set timeout 1
    foreach {alias spawn_id} [array get spawns] {
        expect {
        -re ".+" {exp_continue -continue_timer}
        default {  }
        }
    }
}
exit -onexit flush_logs
set timeout 5
expect {
    -i $spawns(one) "P1:2" {puts "Spawn1 got 2"; exp_continue}
    -i $spawns(two) "P2:2" {puts "spawn2 got 2"; exp_continue}
}

p1.sh
#!/bin/bash
i=0

while sleep 1; do
    echo P1:$i
    let i++
done

p2.sh
#!/bin/bash
i=0

while sleep 1; do
    echo P2:$i
    let i++
done

It is working perfectly :)


text:
Q: Instance variable of interface type does not have access to implementation class methods where as instance variable of type implementation class do I have an interface called Functions without any method defined in it. Then I have an implementation class that implements that interface and has also a method defined in the implementation class. If I create a variable of the interface type and assign it with a new instance of the implementation type (which has a method defined in it). Why can't I access that method from the variable? I think I'm missing something here. I was under the impression that if the variable of the interface type has been assigned an instance of the implementation type which has a method defined in it, than that variable can be used to run the method.
Please advise. Thank you in advance.

A: Conceptually, you are doing the wrong thing here.
If you want to call "that method" then you should use a variable of the implementation type, not the interface type.
Alternatively, if "that method" really does belong in the intended functionality the interface, then you should move it "up" to the interface.

A: As far as I can understand, your problem is the following:
// Interface with no methods
public interface Functions {
}

// Implementation class with a method defined in it
public class Implementation implements Functions {
    public void foo() {
        System.out.println("Foo");
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a variable from the interface type and
        // assign a new instance of the implementation type
        Functions f = new Implementation();
        // You try to call the function
        f.foo();     // This is a compilation error
    }
}

That's the correct behavior, this is not possible. Because the compiler sees that variable f has the (static) type of Functions, it only sees the functions defined in that interface. The compiler is not aware of whether the variable actually contains a reference to an instance of the Implementation class.
To solve the issue you either should declare the method in the interface
public interface Functions {
    public void foo();
}

or make your variable have the type of your implementation class
Implementation f = new Implementation();

A: You are restricted to the methods defined by the Reference type, not the Instance type, for example:
AutoClosable a = new PrintWriter(...);
a.println( "something" );

Here, AutoClosable is the reference type and PrintWriter is the instance type.
This code will give a compiler error because the only method defined in AutoClosable is close().

A: You cannot do that, consider this example:
interface Foo {

}

And class:
class FooBar implements Foo {
   public void testMethod() { }
}

class FooBarMain {
    public static void main(String[] args) {
       Foo foo = new FooBar();
       //foo.testMethod(); this won't compile.
    }
}

Because at the compile time, compiler will not know that you are creating a new FooBar();and it has a method called testMethod() which will be determined dynamically. So it expects whatever you are accessing via interface variable should be available in your interface.
What you can do is if you want to access that method via interface variable, it's better to move that method to interface and let clients implement it.
Let me know if you have doubts on this.


text:
Q: Prevent caching for certain API route - ETag? I am confused why I am getting this:
GET /api/v1/changelog/json 304 50.967 ms - -

It looks like the browser is caching the result...but this a JSON request, that should never be cached.
I guess I need to change a header so it uses the 'application/json' header?
That will prevent caching?
But the thing is, I already have that header:
     getGitLog: function () {
        return $http({
          method: 'GET',
          url: `/api/v1/changelog/json`,
          data: {},
          headers: {
            'Content-Type': 'application/json'
          },
        })
     },

A: You can use cache: false option like this:
getGitLog: function () {
    return $http({
      method: 'GET',
      url: `/api/v1/changelog/json`,
      cache: false,
      data: {},
      headers: {
        'Content-Type': 'application/json'
      },
    })
 },

A: It appears that disabling Etag's was the solution. With Node.js Express, that would be:
app.disable('etag');


text:
Q: Flutter: How to use SharedPreferences synchronously? I am using Shared Preferences in my Flutter app and what I would like to do is store SharedPreferences as a field on startup and then use it synchronously in the app. However I'm not sure if I'm not missing anything.
What I want to achieve is instead of:
method1() async {
  SharedPreferences sp = await SharedPreferences.getInstance();
  return sp.getString('someKey');
}

to
SharedPreferences sp;
//I would probably pass SharedPreferences in constructor, but the idea is the same
someInitMethod() async {
  sp = await SharedPreferences.getInstance();
}
method1() {
  return sp.getString('someKey');
}
method2() {
  return sp.getString('someKey2');
}
method3() {
  return sp.getString('someKey3');
}

In that way I would achieve synchronous access to sharedPrefs. Is it bad solution?
EDIT:
What is worth mentioning is that getInstance method will only check for instance and if there is any than it returns it, so as I see it, is that async is only needed to initialize instance. And both set and get methods are sync anyway.
static Future<SharedPreferences> getInstance() async {
  if (_instance == null) {
    final Map<String, Object> fromSystem =
        await _kChannel.invokeMethod('getAll');
    assert(fromSystem != null);
    // Strip the flutter. prefix from the returned preferences.
    final Map<String, Object> preferencesMap = <String, Object>{};
    for (String key in fromSystem.keys) {
      assert(key.startsWith(_prefix));
      preferencesMap[key.substring(_prefix.length)] = fromSystem[key];
    }
    _instance = new SharedPreferences._(preferencesMap);
  }
  return _instance;
}

A: @iBob101 's answer is good, but still, you have to wait before you use the SharedPreferences for the first time.
The whole point is NOT to await for your SharedPreferences and be sure that it will always be NOT NULL.
Since you'll have to wait anyway let's do it in the main() method:
class App {
  static SharedPreferences localStorage;
  static Future init() async {
    localStorage = await SharedPreferences.getInstance();
  }
}

And the main method:
void main() async{
  await SharedPref.initSharedPref();
  runApp(MyApp());
}

the line await SharedPref.initSharedPref(); takes ~100ms to execute. This is the only drawback as far as I can see.
But you definitely know that in every place in the app your sharedPreferenes instance in NOT NULL and ready for accessing it:
String s = App.localStorage.getString(PREF_MY_STRING_VALUE);

I think it's worthwhile

A: The cleanest way is to retrieve SharedPreferences in main method and pass it to MyApp as a dependency:
void main() async {
  // Takes ~50ms to get in iOS Simulator.
  final SharedPreferences sharedPreferences =
      await SharedPreferences.getInstance();

  runApp(MyApp(sharedPreferences: sharedPreferences));
}

class MyApp extends StatefulWidget {
  final SharedPreferences sharedPreferences;

  const MyApp({Key key, this.sharedPreferences})
      : assert(sharedPreferences != null),
        super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    // You can access shared preferences via widget.sharedPreferences
    return ...
  }

A: I made a simple way to using this PrefUtil class:
import 'package:shared_preferences/shared_preferences.dart';

class PrefUtil {
  static late final SharedPreferences preferences;
  static bool _init = false;
  static Future init() async {
    if (_init) return;
    preferences = await SharedPreferences.getInstance();
    _init = true;
    return preferences;
  }

  static setValue(String key, Object value) {
    switch (value.runtimeType) {
      case String:
        preferences.setString(key, value as String);
        break;
      case bool:
        preferences.setBool(key, value as bool);
        break;
      case int:
        preferences.setInt(key, value as int);
        break;
      default:
    }
  }

static Object getValue(String key, Object defaultValue) {
    switch (defaultValue.runtimeType) {
      case String:
        return preferences.getString(key) ?? "";
      case bool:
        return preferences.getBool(key) ?? false;
      case int:
        return preferences.getInt(key) ?? 0;
      default:
        return defaultValue;
    }
  }
}

In main.dart:
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  PrefUtil.init();
  .....

Save it like:
PrefUtil.setValue("isLogin", true);

Get the value like:
PrefUtil.getValue("isLogin", false) as bool

By this, it will initialize only once and get it where ever you need.

A: You can use FutureBuilder to render the loading screen while waiting for SharedPreferences to be intialized for the first time in a singleton-like class. After that, you can access it synchronously inside the children.
local_storage.dart
class LocalStorage {
  static late final SharedPreferences instance;

  static bool _init = false;
  static Future init() async {
    if (_init) return;
    instance = await SharedPreferences.getInstance();
    _init = true;
    return instance;
  }
}

app_page.dart
final Future _storageFuture = LocalStorage.init();

@override
Widget build(BuildContext context) {
  return FutureBuilder(
    future: _storageFuture,
    builder: (context, snapshot) {
      Widget child;
      if (snapshot.connectionState == ConnectionState.done) {
        child = MyPage();
      } else if (snapshot.hasError) {
        child = Text('Error: ${snapshot.error}');
      } else {
        child = Text('Loading...');
      }
      return Scaffold(
        body: Center(child: child),
      );
    },
  );
}

my_page.dart
return Text(LocalStorage.instance.getString(kUserToken) ?? 'Empty');

A: I use the same approach as the original poster suggests i.e. I have a global variable (actually a static field in a class that I use for all such variables) which I initialise to the shared preferences something like this:
in globals.dart:
class App {
  static SharedPreferences localStorage;
  static Future init() async {
    localStorage = await SharedPreferences.getInstance();
  }
}

in main.dart:
void main() {
  start();
}

Async.Future start() async {
  await App.init();
  localStorage.set('userName','Bob');
  print('User name is: ${localStorage.get('userName)'}');  //prints 'Bob'
}

The above worked fine but I found that if I tried to use App.localStorage from another dart file e.g. settings.dart it would not work because App.localStorage was null but I could not understand how it had become null.
Turns out the problem was that the import statement in settings.dart was import 'package:<packagename>/src/globals.dart'; when it should have been import 'globals.dart;.

A: *

*call shared prefs on startup of a stateful main app (we call ours a initState() override of a StatefulWidget after super.initState())

*after shared prefs inits, set the value to a field on main (ex: String _someKey)

*inject this field into any child component

*You can the call setState() on _someKey at you leisure and it will persist to children injected with your field


text:
Q: Cut-off frequency for RC-filter with two resistors and two capacitors I'm sort of hard stuck on this question regarding RC-filters. I've tried calculating the total resistance of the circuit but I felt that it was the wrong way. Than I tried calculating Vout in terms of Vin so that I could use the formula in the picture below to calculate the cut-off frequency, but I don't know how to get the right expression for Vout. I've tried using voltage division but I keep getting the wrong answer. The correct answer according to my book is around:
W = 0,64/(R*C)
 = 1/sqrt(2)

A: Getting the transfer function
You could just view it this way:

simulate this circuit – Schematic created using CircuitLab
Above, you can see that \$R\$ and \$Z_{_\text{C}}\$ form a voltage divider that divides \$V_{_\text{X}}\$ into \$V_{_\text{OUT}}\$. Also, \$R\$ and \$Z_{_\text{X}}\$ form a voltage divider that divides \$V_{_\text{IN}}\$ into \$V_{_\text{X}}\$.
So:
$$\begin{align*}
V_{_\text{X}} &= V_{_\text{IN}}\left[\frac{1}{1+\frac{R}{Z_{_\text{X}}}}\right]\\\\
V_{_\text{OUT}} &= V_{_\text{X}}\left[\frac{1}{1+\frac{R}{Z_{_\text{C}}}}\right]\\\\
&\therefore\quad \frac{V_{_\text{OUT}}}{V_{_\text{IN}}}=\left[\frac{1}{1+\frac{R}{Z_{_\text{X}}}}\right]\cdot \left[\frac{1}{1+\frac{R}{Z_{_\text{C}}}}\right]
\end{align*}$$
Finding then that \$Z_{_\text{C}}=\frac1{s\,C}\$ and \$Z_{_\text{X}}=\frac{Z_{_\text{C}}}{1+\frac1{1+\frac{R}{Z_{_\text{C}}}}}\$, and setting \$\omega_{_0}=\frac1{R\,C}\$, then the Laplace transfer function is:
$$\begin{align*}
H\left(s\right)&=\frac{\omega_{_0}^2}{s^2+3 \omega_{_0}\, s+\omega_{_0}^2}\\\\\text{or,}\\\\
H\left(s=j\omega\right)&=\frac1{\left(1-\left[\frac{\omega}{\omega_{_0}}\right]^2\right)+j\,3\left[\frac{\omega}{\omega_{_0}}\right]}
\end{align*}$$
SymPy confirmation
Just to confirm, let's use SymPy:
zc = 1/s/c
zx = zc/(1+(1/(1+r/zc)))
tf2( 1 / (1+r/zx) / (1+r/zc) )
{omega: 1/(c*r), zeta: 3/2, P: [{A: 1, N: 0}]}

(The tf2 function is one I wrote. It's documented elsewhere in other answers I've provided here.)
This confirms \$\omega_{_0}=\frac1{R\,C}\$ and since I should see a term in the denominator of \$2\zeta\,\omega_{_0}\,s\$ and I know that \$2\zeta=3\$ in this case, then it all appears in order to me. I didn't make an error in the algebra process I followed.
Addressing the problem question
Your problem sets the magnitude to \$\lvert H\left(j\omega\right) \rvert=\frac1{\sqrt{2}}\$. But that's \$\left(1-\left[\frac{\omega}{\omega_{_0}}\right]^2\right)^2+\left(3\left[\frac{\omega}{\omega_{_0}}\right]\right)^2 =\sqrt{2}^2=2\$.
So set a new parameter, \$x=\frac{\omega}{\omega_{_0}}\$ and solve for \$x\$:
$$\begin{align*}
\left(1-x^2\right)^2+\left(3x\right)^2 =2
\end{align*}$$
Note that you can now set \$y=x^2\$ and just solve for \$\left(1-y\right)^2+9 y =2\$ or \$y^2+7y-1=0\$, which easily works out to \$y=\frac{-7\pm\sqrt{49-4\cdot -1}}{2}=\frac{-7\pm\sqrt{53}}{2}\$. And since \$x=\sqrt{y}\$ you can select the real-valued version, which is \$x=\frac{\sqrt{\sqrt{53}-7}}{\sqrt{2}}\$. That's then the ratio of the two.
So \$\omega=\frac{\sqrt{\sqrt{53}-7}}{\sqrt{2}}\cdot\omega_{_0}\approx \frac{0.37423}{R\,C}\$. And it disagrees, I think, with the answer you suggested you are supposed to get.
LTspice confirmation
Let's target \$\omega_{_0}=1\:\text{kHz}\$. I'll use \$R=15.915\:\text{k}\Omega\$ and \$C=10\:\text{nF}\$. We would predict that the \$-3.01\:\text{dB}\$ frequency will then be \$374.23\:\text{Hz}\$.
Running LTspice, I get:

Which does meet with prediction.

A: Well, it is not hard to show that:
$$\left|\underline{\mathscr{H}}\left(\text{j}\omega\right)\right|=\frac{1}{\sqrt{\left(1-\left(\omega\text{CR}\right)^2\right)^2+\left(3\omega\text{CR}\right)^2}}\tag1$$
So, solving for:
$$\left|\underline{\mathscr{H}}\left(\text{j}\omega\right)\right|=\frac{1}{\sqrt{2}}\tag2$$
Gives:
$$\omega=\frac{1}{\text{CR}}\cdot\sqrt{\frac{\sqrt{53}-7}{2}}\tag3$$


text:
Q: Android Custom Adapter Hangs Until I Scroll Down I'm trying to populate a List View with Android, and I'm very new at this... Haven't seen an exact solution to the issue on here yet.  The problem appears to be in my getView(...) method in my custom adapter.  When I run the app, it instantly crashes.  When I debug, the list get populated just fine, until it reaches the bottom of the view - then it hangs until I physically scroll down, and populates again until it reaches the bottom... the process is repeated until fully populated.  Even though this issue seems to have been resolved here, none of the solutions work in this case.  Any Android guru's out there have any advice?
Here's the for the ListView xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.heytow.challenge.heycontacts.ContactsActivity">

<ListView
    android:layout_width="368dp"
    android:layout_height="495dp"
    android:id="@+id/customListView"
    tools:layout_editor_absoluteY="8dp"
    tools:layout_editor_absoluteX="8dp">
</ListView>

and the item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:paddingTop="10dp"
                android:paddingBottom="10dp">

    <ImageView
        android:id="@+id/contact_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginRight="10dp"
        android:contentDescription="Property Image" />

    <LinearLayout
        android:id="@+id/contact_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/image"
        android:orientation="vertical">

        <TextView
            android:id="@+id/contact_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:text="Street Address"
            android:textSize="18sp"/>

        <TextView
            android:id="@+id/contact_company"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:text="Description"
            android:textSize="15sp"/>
    </LinearLayout>

</RelativeLayout>

My Custom Adapter:
public class ContactAdapter extends ArrayAdapter<Contact> {
    private final String TAG = ContactAdapter.class.getSimpleName();

    private Context mContext;
    private List<Contact> mContactList;

    //constructor, call on creation
    public ContactAdapter(Context context, int resource, ArrayList<Contact> objects) {
        super(context, resource, objects);

        this.mContext = context;
        this.mContactList = objects;
    }

    @Override
    public int getCount() {
        return mContactList.size();
    }

    //called when rendering the list
    public View getView(int position, View convertView, ViewGroup parent) {

        //get the property we are displaying
        Contact contact = mContactList.get(position);

        //get the inflater and inflate the XML layout for each item
        LayoutInflater inflater;
         View view = convertView;
        if(view == null) {
            ViewHolder holder = new ViewHolder();
            if (contact.isFavorite() == true) {
                inflater = ((Activity)mContext).getLayoutInflater();
                view = inflater.inflate(R.layout.favorite_contact_layout, null);
            } else {
                inflater = ((Activity)mContext).getLayoutInflater();
                view = inflater.inflate(R.layout.contact_layout, null);
            }
        }
        TextView name = (TextView) view.findViewById(R.id.contact_name);
        TextView company = (TextView) view.findViewById(R.id.contact_company);
        ImageView image = (ImageView) view.findViewById(R.id.contact_image);

        //set address and description
        if(contact.getName() != null) {
            name.setText(contact.getName());
        }

        if(contact.getCompanyName() != null) {
            company.setText(contact.getCompanyName());
        }

        //get the image associated with this contact
        ImageParser parser = new ImageParser();
        AsyncTask<String, Void, Bitmap> urlImage = parser.execute(contact.getSmallImageURL());
        try {
            image.setImageBitmap(urlImage.get());
        } catch (InterruptedException e) {
            Log.e(TAG, "Error accessing image URL: " + e.getMessage());
        } catch (ExecutionException e) {
            Log.e(TAG, "Error accessing image URL: " + e.getMessage());
        }
        return view;

    }
}

And the call in my MainActivity class, onCreate.
ArrayAdapter<Contact> adapter = new ContactAdapter(ContactsActivity.this, 0, mContacts);
ListView listView = (ListView) findViewById(R.id.customListView);
listView.setAdapter(adapter);

I'm simply trying to populate the ListView from an arrayList. Any help would be appreciated.  Thanks!
* EDIT *
Here's the new getView - same effect - it hangs... when the data is not in view, it says "application is running" and getView does not continue until I scroll:
public View getView(int position, View convertView, ViewGroup parent) {
    //get the property we are displaying
    Contact contact = mContactList.get(position);
    ViewHolder viewHolder;
    //get the inflater and inflate the XML layout for each item
    LayoutInflater inflater;
    if(convertView == null) {
        viewHolder = new ViewHolder();
        if (contact.isFavorite() == true) {
            inflater = ((Activity)mContext).getLayoutInflater();
            convertView = inflater.inflate(R.layout.favorite_contact_layout, parent, false);
        } else {
            inflater = ((Activity)mContext).getLayoutInflater();
            convertView = inflater.inflate(R.layout.contact_layout, parent, false);
        }
        viewHolder.contactName = (TextView) convertView.findViewById(R.id.contact_name);
        viewHolder.contactCompany = (TextView) convertView.findViewById(R.id.contact_company);
        viewHolder.contactImage = (ImageView) convertView.findViewById(R.id.contact_image);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    //set address and description
    if(contact.getName() != null) {
        viewHolder.contactName.setText(contact.getName());
    }

    if(contact.getCompanyName() != null) {
        viewHolder.contactCompany.setText(contact.getCompanyName());
    }

    //get the image associated with this contact
    ImageParser parser = new ImageParser();
    AsyncTask<String, Void, Bitmap> urlImage = parser.execute(contact.getSmallImageURL());
    try {
        viewHolder.contactImage.setImageBitmap(urlImage.get());
    } catch (InterruptedException e) {
        Log.e(TAG, "Error accessing image URL: " + e.getMessage());
    } catch (ExecutionException e) {
        Log.e(TAG, "Error accessing image URL: " + e.getMessage());
    }
    return convertView;
}

A: ListView reuses the views. It appears you are inflating two different layouts for the views. Try using the same layout by merging both and set visibility for only necessary parts.

A:
I suggest you to following: a) Move all these view declaration within
  a static class(your viewholder):

static class ViewHolder{
        public TextView name;
        public TextView company;
        public ImageView image;
}

b) Assign your ViewHolder's views within below block:(For
  reusability)

  View view= convertView;
  if(view == null) {

        if (contact.isFavorite() == true) {
            inflater = ((Activity)mContext).getLayoutInflater();
            view = inflater.inflate(R.layout.favorite_contact_layout, null);
        } else {
            inflater = ((Activity)mContext).getLayoutInflater();
            view = inflater.inflate(R.layout.contact_layout, null);
        }

        ViewHolder holder= new ViewHolder();

        holder.name = (TextView) view.findViewById(R.id.contact_name);
        holder.company = (TextView) view.findViewById(R.id.contact_company);
        holder.image = (ImageView) view.findViewById(R.id.contact_image);

        view.setTag(viewHolder);
    }

    ViewHolder holder = (ViewHolder) view.getTag();
    //below do the proper assignments:

    //set address and description
    if(contact.getName() != null) {
        holder.name.setText(contact.getName());
    }

    if(contact.getCompanyName() != null) {
        holder.company.setText(contact.getCompanyName());
    }

//Set imageview with picasso:

1)First add dependency on your gradle file:

compile 'com.squareup.picasso:picasso:2.5.2'

2)Set imageviews with picasso:

Picasso.with(context).load(contact.getSmallImageURL()).into(holder.image);


text:
Q: Database INSERT not saving I have created a function called addPeople() with the parameters of firstname and lastname.
When the user inputs the first and last name and clicks the add button, the new entry is added to the database. However, once the program is restarted, the newly added entry is gone and wasn't saved. Why is this? How can I actually save the new data?
Sub addPeople(ByVal fname As String, ByVal lname As String)
        Dim conn As SqlConnection
        conn = New SqlConnection(getConnectionString)

        Dim cmd As New SqlCommand
        cmd.CommandType = CommandType.Text

        cmd.Connection = conn

        ' Open the connection '
        conn.Open()
        ' Start the "transaction" so the insert saves to the database '
        cmd.CommandText = "BEGIN TRANSACTION"
        cmd.ExecuteNonQuery()
        ' Insert the new data into the database '
        cmd.CommandText = "INSERT people (firstname, lastname) VALUES ('" + fname + "', '" + lname + "')"
        cmd.ExecuteNonQuery()
        ' Save the changes to the database '
        cmd.CommandText = "COMMIT"
        cmd.ExecuteNonQuery()
        ' Close the connection '
        conn.Close()
    End Sub

I've tried starting the transaction and then using COMMIT to make sure the changes are saved, but that still doesn't work.
Edit:
After some further testing, I've also noticed my deletePeople() function also doesn't fully save the changes to the database.
Sub deletePeople(ByVal id As String)
        Dim conn As SqlConnection
        conn = New SqlConnection(getConnectionString)

        Dim cmd As New SqlCommand
        cmd.CommandType = CommandType.Text

        cmd.Connection = conn

        ' Open the connection '
        conn.Open()
        ' Start the "transaction" so the insert saves to the database '
        cmd.CommandText = "BEGIN TRANSACTION"
        cmd.ExecuteNonQuery()
        ' Insert the new data into the database '
        cmd.CommandText = "DELETE FROM people WHERE people_id='" + id + "'"
        cmd.ExecuteNonQuery()
        ' Save the changes to the database '
        cmd.CommandText = "COMMIT"
        cmd.ExecuteNonQuery()
        ' Close the connection '
        conn.Close()
    End Sub

ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"

A: Instead of this:
cmd.CommandText = "BEGIN TRANSACTION"
cmd.ExecuteNonQuery()

You want to Begin the Transaction on the Connection:
var transaction = connection.BeginTransaction()

All up:
using (var transaction = connection.BeginTransaction())
{
    cmd.CommandText = "INSERT people (firstname, lastname) VALUES ('" + fname + "', '" + lname + "')";
    cmd.Transaction = transaction;
    cmd.ExecuteNonQuery();
    transaction.Commit();
    //transaction.Rollback();
}


text:
Q: Can the probability vary in dependence of other players action? Let's consider a classic hold'em poker game.
We want to calculate the odds of hitting a straight (5 cards in sequence) when we have 4 sequential cards on the flop.
For those who don't know poker, everyone is dealt 2 cards,(followed by the 1st betting round), then 3 common cards are discovered (this is called the "flop", and second betting round), then another card (the "turn", and another betting round), and the last common card (the "river", and the last betting round).
A classical poker table is composed by 9 players, they decide to get involved in the hand by looking at their starting hand. They are more willing to play if their hand has an higher expected value.
The highest 5 cards combination (you can combine yours with the 5 common cards) wins the pot.
So we have 4 sequential cards on the flop and if the turn will complete the sequence of 5 cards we'll have a straight.
What's the probability?
The deck is composed by 52 cards.
Let's consider we have 54, and the flop is 36A. So if a 2 or a 7 comes out we'll have a straight. (8 outs out of 47 undiscovered cards)
$P$ = 8/47 = 0.1702
The odds are 1:4.875.
My question is, do you think this probability vary in dependence of how many players are currently involved in the hand? How to quantify it?
What I mean is, since players get involved in a hand when they have good cards, in an hand where there are fewer players we can suppose the other players were dealt bad (low) cards, so there are more high cards still in the deck.
So it seems reasonable to me that we are more likely to hit a low cards straight in a hand with more players (they probably have high cards) then in a game where there are fewer players (they probably have high cards, but many low cards have been discarded pre-flop by the others).
What do you think? How can I quantify this in terms of probability and odds?
Best regards.
Giorgio

A: I've seen detailed analyses on this (sadly no longer online) all of which came to the conclusion that card removal is negligible in Hold'em specifically.  This is because too many "bad" hands can contain "good" cards (A3o, K6o, etc), and if pots are expected to be multiway, "good" hands can also contain "bad" cards (33, 78s, etc).  I hear it matters a lot more in 5-card draw variants.


text:
Q: How to search all tables in a database? EDIT:  Updated to include some current code for context, and added questions in bold
Newbie here:
I will have 20 or so tables of manufacturers filled with 15,000-100,000 rows of parts in each table. Information such as PartNumber, Superceding Part Number, List Price, MFG Price, Sale Price, etc will be stored as columns.  I would like to be able to start typing a part number in a search box and have it display all the parts that match the numbers so far, and then update as I enter more of the number.
I currently have a version working with 1 table of 40,000 parts where as I type a few numbers such as '0000', it will return the top 5 parts beginning with 0000, such as: 000011, 000013,00015,000023, and 000025 and some corresponding info on them. If I type one more number '00002' it will only display 000023 and 000025.  However I would like this search to run over all tables in the database in case I do not know which manufacturer made the part.
Currently I have a database named taft_test1, with two tables named ariens_prices and briggs_prices.  Each table will contain the same columns, but possibly not have  them filled with data on every entry.
Any ideas on the best way to go about this?
Some have mentioned UNION which is ok but should I do 20+ unions or might there be a better way to layout the database?
Appreciate the help.
Sample Code I have working:
partslookup.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <title>Taft Power Equipment</title>

    <link rel="stylesheet" type="text/css" href="style.css" />

Home

Work

Blog

About

Contact

Parts Look Up

                <input id="test" class="auto" type="text" size="25" placeholder="Enter Part Here" onkeyup="showUser(this.value)"

Part info will display here.

&copy Copy Right Taft Power Equipment Corp

livesearch.php
<?php

$q = $_GET['q'];

echo "Part Entered:       $q

";

$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = "SELECT * FROM `briggs_prices` WHERE briggs_prices.Description LIKE '$q%'
        UNION
        SELECT * FROM `ariens_prices` WHERE ariens_prices.Description LIKE '$q%'
        LIMIT 0, 50 ";

mysql_select_db('taft_test1');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}

echo "

Part#
Description
Price

";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
  echo "
";
  echo "
";
  echo "" . $row['Description'] . "	";
  echo "" . $row['SuperNum'] . "	";
  echo "" . $row['LIST1'] . "	";
  echo "
";
}
echo "
";

while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
    echo "Part# :{$row['Description']}   ".
         "Desc : {$row['SuperNum']}  ".
         "Cost : {$row['LIST1']}  ".
         "--------------------------------
";
}
//echo "Fetched data successfully\n";
mysql_close($conn);
?>

A: You need a better database layout.  Something like:
(P) means Primary Key
(F) means Foreign Key
(I) means Indexed

manufacturers
    id                  unsigned int(P)
    name                varchar(50)
    ...

+----+--------+-----+
| id | name   | ... |
+----+--------+-----+
|  1 | Ariens | ... |
|  2 | Briggs | ... |
| .. | ...... | ... |
+----+--------+-----+

parts
    id                      unsigned int(P)
    number                  char(50)(I)
    manufacturer_id         unsigned int(F manufacturers.id)
    name                    varchar(75)
    superceding_part_id     unsigned int(F parts.id) // Allow NULL
    list_price              double
    manufacturer_price      double
    sale_price              double
    ...

+----+--------+-----------------+----------+---------------------+------------+--------------------+------------+-----+
| id | number | manufacturer_id | name     | superceding_part_id | list_price | manufacturer_price | sale_price | ... |
+----+--------+-----------------+----------+---------------------+------------+--------------------+------------+-----+
|  1 | 000011 |               1 | Widget A | NULL                |       1.00 |                .50 |        .90 | ... |
|  2 | 000012 |               1 | Widget B |                   1 |       2.00 |                .75 |       1.75 | ... |
|  3 | 000013 |               2 | Widget A | NULL                |       1.15 |                .70 |       1.00 | ... |
| .. | ...... | ............... | ........ | ................... | .......... | .................. | .......... | ... |
+----+--------+-----------------+----------+---------------------+------------+--------------------+------------+-----+

A: examples $part is the variable you're typing. Here is the query
$query = 'SELECT TOP 5 PartNumber FROM yourTable WHERE PartNumber LIKE "'.$part.'%"'

A: Hey if you have same column in all the tables, better try UNION to get rows from single query. Have a Try
WHERE `PartNumber` LIKE "0001%"


text:
Q: My code works, but is there a command to really send a whatsapp message without user confirmation? I'm developing a phone application and have this function to send an automatic wink (;)) to a specific phone number/contact:
public void onClickWhatsApp(View view) {
    PackageManager pm=getPackageManager();
    String mensajillo =  ";)";
    String toNumber = "xxxxxxxxxxx"; //The xs are replaced with the number which I obtain from other function, but that doesn't matter here
    Intent sendIntent = new Intent(Intent.ACTION_SENDTO,Uri.parse("smsto:" + "" + toNumber + "?body=" + ""));
    sendIntent.setPackage("com.whatsapp");
    startActivity(sendIntent);
    Intent texintent = new Intent(Intent.ACTION_VIEW);
    texintent.setData(Uri.parse("http://api.whatsapp.com/send?phone="+toNumber +"&text="+mensajillo));
    startActivity(texintent);
}

The thing is that it's just opening the chat and writing the ";)", but not actually sending it. I've been reading for hours and I'm if there's even a way to automatize that.
If you know some code that could do what I'm talking about, it would be very welcome ;)

A: Well, at the moment it is impossible. Some people say it would be a pretty big security flaw, so it seems justified
(In any case, sending automatic SMS is pretty easy :P)


text:
Q: Nest.js/mongoose and TypeScript - error in Prop decorator I'm implementing connection to Mongo database in my Nest.js application (with usage of mongoose and @nestjs/mongoose modules. I'm following instructions from Nest.js docs:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class User {
  @Prop({ required: true })
  userName: string;

  @Prop()
  password: string;
}

export const UserSchema = SchemaFactory.createForClass(User);

export type UserDocument = User & Document;

However above code results in TypeScript error:
TS2345: Argument of type '{ required: true; }' is not assignable to parameter of type 'PropOptions'.
  Type '{ required: true; }' is not assignable to type '"number"'.

How do I pass options to Prop decorator properly?

A: as stated here you should use @nestjs/mongoose v7.2.3 (or later) :)


text:
Q: How to print variables in pdf document? dompdf I'm showing the result of a search in a PHP file. However when trying to display the data when generating the pdf document, this does not, does not recognize the variables, how could I do it? I am using the structure of an HTML. Currently generating some errors when trying to pass the file to PDF, the errors shown are syntax errors
    <?php

require_once APPPATH. '/third_party/dompdf/autoload.inc.php';

use Dompdf\Dompdf;

$html ='

     <title>Porcentaje de Cias</title>

Porcentaje de Citas

    Fecha de Inicio:<?php echo $_GET['fecha_ini']; ?>

    Fecha de termino: <?php echo $_GET['fecha_ter']; ?>

    Jefe de Carrera: <?php echo $_GET['jc']; ?>

        Motivo
        Cantidad
        Porcentaje

               <?php

                foreach($consulta as $row)

                {?>

                  <?php echo $row->descripcion_mot ;?>
                  <?php echo $row->cantidad_motivos ;?>
                  <?php echo $row->porcentaje ; echo '%'?>

           <?php }?>

                  Totales
                  <?php foreach($total as $row){ echo $row->total; }  ?>
                  100 %

';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("Porcentaje de Citas.pdf", array("Attachment" => false));

exit(0);
?>


text:
Q: Double *ngFor in a table - Angular 2 I need to create a table based in two loops. I have tried the following:

    {{car?.id}}
     {{bike?.id}}

I know the I get the data because I have tried it in typescript with console.log but when I display it in HTML I print null for bike

A: If both have same no of records , you can do it like

    {{cars[i]?.id}}	 // or {{car?.id}}
    {{bikes[i]?.id}}

A: You can use <ng-container>. It is a helper element that allows to use *ngFor, *ngIf, or other structural directives but doesn't actually create HTML content.
<ng-container *ngFor="let car of cars">

    {{car.id}} {{bike.id}}

</ng-container>

A: In your typescript code you can do this:
vehicles = (<any[]>cars).concat(<any>[bikes]);

And then in your view you can bind it easily like:

  {{vehicle.id}} is car
  {{vehicle.id}} is bike

A: You cannot use on the same line, try it as separate rows

    {{car?.id}}

    {{bike?.id}}

EDIT
if you want on the same row use index which will hold the array value

    {{cars[x]?.id}}
    {{bikes[x]?.id}}


text:
Q: Migrate / index / reindex mongodb into elasticsearch using express JS Trying to migrate the mongodb into elasticsearch using following mongo-elasticsearch module.
var mongo-elasticsearch = require('mongo-elasticsearch');
var t = new mongo-elasticsearch.Transfer({
  esOpts: {
    host: 'localhost:9200',
    log: 'trace'
  },
  esTargetType: 'tweet',
  esTargetIndex: 'twitter',
  mongoUri: 'mongodb://abc123:def456@myhost.com:27747/dbname',
  mongoSourceCollection: 'tweets'
});

t.start().then(function(results) {
  process.exit();
});

I have used reboundodm module to index the document. Suggest me, how to re-index the document.


text:
Q: Deep Linkng: Open Multiple Apps with same host but different pathPrefix I am using Deep Linking in my application. But, now I have a requirement of opening two seperate apps on two seperate url's but same host like
http:www.google.com/Nexus5 - This should open App1

http:www.google.com/Nexus6 - This should open App2

The above url opens both the apps, but my requirement is that If I provide complete url like http:www.google.com/Nexus5 then it should only show option to of App1.
So, its like if I pass on url

*

*http:www.google.com/Nexus5 then only Nexus5 app should open and show option to browse the app. There should be no option to open Nexus6 app.

*Same way for http:www.google.com/Nexus6 if I open Nexus6 url the it should not show option of Nexus5 App.

Below is my AndroidManifest file for that Activity,
<activity
            android:name=".DeepLinkDemo"
            android:label="@string/app_name">
            <intent-filter android:label="@string/app_name">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data
                    android:host="www.google.com"
                    android:pathPrefix="/Nexus5"
                    android:scheme="http" />
            </intent-filter>
        </activity>

Now, this will run fine but if there is any other app with same host that means www.google.com I want to restrict that app from showing in the Browsable list(that other app will also be controlled by me)
So, is there anyway for achieving my above requirement?
Let, me know if anyone has any query!

A: You can use android:pathPattern to uniquely identify different application


text:
Q: PHP - Slashes are coming after using the stripshales for String i am using mysqli connection.
 $conn = new mysqli($host, $user, $password, $database);

Storing the Data in DB with below syntax
$site_description = $conn->real_escape_string($_POST['site_description']);
$conn->query("UPDATE `r_site_details` SET  `site_description` = '".$site_description."' WHERE `id` = ".$id);
input : Telangana's

it adding slashes.
But when i output the value with stripslashes its still showing the slashes in the string
$query = $conn->query("select * from r_site_details where id=$id")or die(mysqli_error());
$result = $query->fetch_assoc();
    echo stripslashes($result["site_description"]) // output : Telangana\'s

A: Dont Find a Optimize Solution, Just Tried to Replace the Slashes it works fine,
echo str_replace('\"', '"',str_replace("\'", "'", $result["site_description"]));
Can anyone suggest me an alternative Solution.

A: Hope Disabling Magic Quote could help you.


text:
Q: Dimension of intersections of affine algebraic sets I was wondering if I could verify this with someone. I could only find it for when everything is projective but I am guessing it is true for affine as well. Let $X,Y\subset \mathbb A^n_k$ be algebraic sets.  Does it then follows that
$$ \operatorname {codim}  (X\cap Y) \leq \operatorname {codim} X+\operatorname {codim}Y.$$


text:
Q: Limit of a product of two continuous functions I have two functions, $f(x)$ and $g(x)$ that are continuous on the real number line.  I'm taking the limit of their product:
$$\lim_{x\rightarrow\infty}f(x)g(x)$$
Suppose that the limit $\lim_{x\rightarrow\infty}g(x)=c$.
Is there a continuous function $f(x)$ such that:
$$\lim_{x\rightarrow\infty}f(x)g(x)\neq\lim_{x\rightarrow\infty}cf(x)$$

A: Same goes for the following:
If $$g=\begin{cases}1/x&\text{ if }x>1\\1&\text{ otherwise}\end{cases}\text{ and  }f(x)=x$$
Then both functions are continuous on the real line, $\lim_{x\to\infty}g(x)=0$, and $f(x)g(x)$ is the constant one function on the ray $[1,\infty)$, suggesting that $$\lim_{x\to\infty}f(x)g(x)=1\neq 0\cdot\lim_{x\to\infty}f(x)$$

A: If $f(x)=x$ and $\lim\limits_{x\to\infty}g(x)=c$, and $c$ is a real number (thus not $\infty$ or $-\infty$), then $f$ is continuous and $\lim\limits_{x\to\infty}\Big(f(x)g(x)\Big)$ does not exist.


text:
Q: How to manipulate view inside ListView items? I have a ListView in which there several rows containing two buttons and a ProgressBar (Visibility:GONE) each.
My purpose is to display the ProgressBar upon click on the buttons and after completing a certain set of background operations remove that row entirely.
The problem here is that after removing the item from the ArrayList which the ListView is created upon and calling notifyDataSetChanged the row is removed successfully but the ProgressBar remains visible.
Shouldn't it be removed along with it's parent view?
Checkout the following record to see the problem in action.

Here is the source of my entire fragment:
public class FriendRequestFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = "FriendRequestFragment";
    ArrayList<FriendRequest> friendRequests;

    @InjectView(R.id.friendRequestList)
    ListView mListView;
    @InjectView(R.id.noRequestsText)
    TextView noRequestsText;
    @InjectView(R.id.swipe)
    SwipeRefreshLayout swipeRefreshLayout;

//    NotificationHandler nh;
    /**
     * The Adapter which will be used to populate the ListView/GridView with
     * Views.
     */
    private FriendRequestAdapter mAdapter;
    private Context c;
    private boolean isProcessing = false;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public FriendRequestFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Util.trackFragment(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_friendrequest_list, container, false);
        ButterKnife.inject(this, view);
        c = getActivity();
        friendRequests = new ArrayList<>();
        swipeRefreshLayout.setOnRefreshListener(this);
        mAdapter = new FriendRequestAdapter(getActivity(), friendRequests);

        mListView.setAdapter(mAdapter);

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int topRowVerticalPosition =
                        (view == null || view.getChildCount() == 0) ?
                        0 : view.getChildAt(0).getTop();
                swipeRefreshLayout.setEnabled(firstVisibleItem == 0 && topRowVerticalPosition >= 0);
                Log.d(TAG, "SwipeRefresh: " + String.valueOf(firstVisibleItem == 0 && topRowVerticalPosition >= 0));
            }
        });

        loadRequests();
        return view;
    }

    private void loadRequests() {
//        nh = new NotificationHandler(getActivity());
        swipeRefreshLayout.setRefreshing(true);
        Log.d(TAG, "loading requests init");
        HashMap<String, Integer> params = new HashMap<>();
        params.put("profile_id", Util.getCurrentProfileID(c));
        final String uniqueID = Util.getCurrentProfileID(c) + String.valueOf(System.currentTimeMillis() / 1000 / 1200);
        new ApiRequest(Util.URL_GET_FRIEND_REQUESTS, params, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String result, AjaxStatus status) {
                super.callback(url, result, status);
                ApiResponse apiResponse = new ApiResponse(url, result, uniqueID);
                Log.d(TAG, "Friend Requests Response: " + result);
                if (apiResponse.isSuccessful()) {
                    JSONArray jsonArray = apiResponse.getDataJSONArray();
                    try {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            friendRequests.add(new FriendRequest(jsonArray.getJSONObject(i)));
                        }
                        mAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mListView.setVisibility(View.VISIBLE);
                } else if (apiResponse.getErrorMessage().equals("request_not_found")) {
                    noRequestsText.setVisibility(View.VISIBLE);
                }
                swipeRefreshLayout.setRefreshing(true);
            }

        }).setUniqueID(uniqueID).execute();
    }

    @Override
    public void onRefresh() {
        loadRequests();
    }

    private void acceptRequest(final int position, final View rootView) {
        if (isProcessing) {
            CustomToast.makeToast(getActivity(), CustomToast.TYPE_ALERT, getString(R.string.please_wait), CustomToast.LENGTH_SHORT);
            return;
        }
        rootView.findViewById(R.id.loading).setVisibility(View.VISIBLE);
        rootView.findViewById(R.id.acceptBtn).setVisibility(View.GONE);
        rootView.findViewById(R.id.denyBtn).setVisibility(View.GONE);
        isProcessing = true;
        Log.d("FriendRequest", "accepting:" + position);
        FriendRequest request = friendRequests.get(position);
        HashMap<String, Integer> params = new HashMap<>();
        params.put("request_id", request.getRequestID());
        params.put("profile_id", ProfilesSingleton.getInstance().getCurrentProfile().getProfileID());
        new ApiRequest(Util.URL_ACCEPT_REQUEST, params, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String object, AjaxStatus status) {
                super.callback(url, object, status);
                ApiResponse apiResponse = new ApiResponse(object);
                if (apiResponse.isSuccessful()) {
                    friendRequests.remove(position);
                    CustomToast.makeToast(getActivity(), CustomToast.TYPE_DEFAULT,
                            getString(R.string.you_are_now_friends_with) + " " + friendRequests.get(position).getFullName(),
                            CustomToast.LENGTH_SHORT);
                    mAdapter.notifyDataSetChanged();
                }else {
                    rootView.findViewById(R.id.loading).setVisibility(View.GONE);
                    rootView.findViewById(R.id.acceptBtn).setVisibility(View.VISIBLE);
                    rootView.findViewById(R.id.denyBtn).setVisibility(View.VISIBLE);
                }
                isProcessing = false;
            }
        }).execute();
    }

    private void denyRequest(final int position, final View rootView) {
        if (isProcessing) {
            CustomToast.makeToast(getActivity(), CustomToast.TYPE_ALERT, getString(R.string.please_wait), CustomToast.LENGTH_SHORT);
            return;
        }
        rootView.findViewById(R.id.loading).setVisibility(View.VISIBLE);
        rootView.findViewById(R.id.acceptBtn).setVisibility(View.GONE);
        rootView.findViewById(R.id.denyBtn).setVisibility(View.GONE);
        Log.d("FriendRequest", "denying:" + position);
        FriendRequest request = friendRequests.get(position);
        HashMap<String, Integer> params = new HashMap<>();
        params.put("request_id", request.getRequestID());
        params.put("profile_id", ProfilesSingleton.getInstance().getCurrentProfile().getProfileID());
        new ApiRequest(Util.URL_DENY_REQUEST, params, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String object, AjaxStatus status) {
                super.callback(url, object, status);
                ApiResponse apiResponse = new ApiResponse(object);
                if (apiResponse.isSuccessful()) {
                    friendRequests.remove(position);
                    mAdapter.notifyDataSetChanged();
                }else {
                    rootView.findViewById(R.id.loading).setVisibility(View.GONE);
                    rootView.findViewById(R.id.acceptBtn).setVisibility(View.VISIBLE);
                    rootView.findViewById(R.id.denyBtn).setVisibility(View.VISIBLE);
                }
            }
        }).execute();
    }

    public class FriendRequestAdapter extends ArrayAdapter<FriendRequest> {

        public FriendRequestAdapter(Context context, ArrayList<FriendRequest> objects) {
            super(context, 0, objects);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View rootView = convertView;
            final ViewHolder holder;
            final FriendRequest friendRequest = getItem(position);
            if (rootView == null) {
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                rootView = inflater.inflate(R.layout.friend_request_item, parent, false);
                holder = new ViewHolder();
                holder.profilePhoto = (RoundedImageView) rootView.findViewById(R.id.profilePhoto);
                holder.fullName = (TextView) rootView.findViewById(R.id.fullName);
                holder.acceptBtn = (ImageView) rootView.findViewById(R.id.acceptBtn);
                holder.denyBtn = (ImageView) rootView.findViewById(R.id.denyBtn);
                holder.loading = (ProgressBar) rootView.findViewById(R.id.loading);
                rootView.setTag(holder);
            } else {
                holder = (ViewHolder) rootView.getTag();
            }

            holder.fullName.setText(friendRequest.getFullName());
            if (friendRequest.getFullPhotoPath().equals("")) {
                ImageUtil.replaceWithInitialsView(getContext(), holder.profilePhoto, friendRequest.getInitials());
            } else {
                Util.aQuery.id(holder.profilePhoto).image(friendRequest.getFullPhotoPath(), false, true, 50, R.drawable.avatar_profile, null, AQuery.FADE_IN);
            }

            final View finalRootView = rootView;
            holder.acceptBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    acceptRequest(position, finalRootView);
                }
            });
            holder.denyBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    denyRequest(position, finalRootView);
                }
            });
            return rootView;
        }

        public class ViewHolder {
            RoundedImageView profilePhoto;
            TextView fullName;
            ImageView acceptBtn, denyBtn;
            ProgressBar loading;
        }
    }
}

A: Add a field in your FriendRequest class that saves the current state of the progress bar. based on it set the visibility of the progress bar.
The same view row has been sent to another row. in your getView method you must always set the progress bar visibility based on its status.
Code Sample:
        final View finalRootView = rootView;

        if (friendRequest.acceptingRequestInProgress())
             holder.loading.setVisibility(View.Visibile);
        else
             holder.loading.setVisibility(View.Gone);

        holder.acceptBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                friendRequest.setAcceptingInProgress(true);
                acceptRequest(position, finalRootView);
            }
        });
        holder.denyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                denyRequest(position, finalRootView);
            }
        });

Another place to modify:
if (apiResponse.isSuccessful()) {
    friendRequest.setAcceptingInProgress(false);
    friendRequests.remove(position);
    mAdapter.notifyDataSetChanged();
}

Note: this is also handles the case when the user scrolls the list
  view and the row view in progress is no longer visible. this will
  hands the view to another row. But since we check the row state the
  progress bar will be stopped. and when user scrolls back to the row
  view in progress and hands it a reusable view the progress bar will be
  visible again if accepting is still in progress.

A: Views are getting reused by the ListView and in the getView() method you are not cleaning up the reused view, that's why the progress bar will become visible for an item that shouldn't display it.
Similarly if an item would be removed some items with progress bars visible would loose their progress bar, handing them over to an item that didn't need it.
In getView(), after initializing the holder, you should check if progress bar is necessary.
Start with storing progress bar values at the beginning:
private ArrayList<Integer> progresses = new ArrayList<Integer>();

Update these values every time the list changes (when list changes in loadRequests and when value changes not sure where).
And in getView()
if (progresses.get(position) == 100) {
  holder.loading.setVisibility(View.GONE);
} else {
  holder.loading.setVisibility(View.VISIBLE);
  holder.loading.setProgress(progresses.get(position));
}

A: The problem is due to visibility of progressbar is VISIBLE default so in getView() after you call notifyDataSetChanged(), the progressbar becomes visible to row position (i - 1).
holder.loading = (ProgressBar) rootView.findViewById(R.id.loading);
holder.loading.setVisibility(View.GONE);

Set progressbar visibility to GONE in getView() and this problem will not come