text:
Q: Having trouble downloading pictures from a RSS feed? I'm having trouble coming up with the correct code to download pictures from a RSS feed and then handing that download off to RadControls slide View or Pagination.
The only thing I can get with the code I'm using is either the text for the pictures or just thumbnails of the pictures, not the full image. I must be missing something or leaving something out.
This is for Windows Phone C#
The web links for the RSS feeds are generic for testing purposes.
//Constructor
public MainPage()
{
    InitializeComponent();
}

private void FlickrSearch_Click(object sender, RoutedEventArgs e)
{
    WebClient webclient = new WebClient();
    webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler

    (webclient_DownloadStringCompleted);
}

void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show("error");
    }
    // parsing Flickr

    XElement XmlTweet = XElement.Parse(e.Result);
    XNamespace ns = "http://api.flickr.com/services/feeds/photos_public.gne?tag="; // flilckr
    listBox1.ItemsSource =
        from tweet in XmlTweet.Descendants("item")
        select new FlickrData
        {
            ImageSource = tweet.Element(ns + "thumbnail").Attribute("url").Value,
            Message = tweet.Element("description").Value,
            UserName = tweet.Element("title").Value,
            PubDate = DateTime.Parse(tweet.Element("pubDate").Value)
        };
}

A: I have found the way you are parsing & fetching the inner data is erroneous. I have closely verified the XML data from Flickr and modified the logic accordingly.
Here goes the complete code:
void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show("error");
    }
    // parsing Flickr

    XElement XmlTweet = XElement.Parse(e.Result);
    string ns = "http://www.w3.org/2005/Atom";

    XName entry = XName.Get("entry", ns);
    XName loc = XName.Get("loc", ns);
    XName title = XName.Get("title", ns);
    XName published = XName.Get("published", ns);
    XName link = XName.Get("link", ns);
    XName content = XName.Get("content", ns);
    XName url = XName.Get("url", ns);

    listBox1.ItemsSource =
        from tweet in XmlTweet.Elements(entry)
        select new FlickrData
        {
            ImageSource = tweet.Element(link).Attribute("href").Value,
            Message = tweet.Element(content).Value,
            UserName = tweet.Element(title).Value,
            PubDate = DateTime.Parse(tweet.Element(published).Value)
        };
}


text:
Q: Controlling a KVM guest Linux OS using Java without network access I know there is
kvm -stdio

to access a kvm guest without having to set up networking. But it is slow and probably cumbersome. Are there better solutions? I want to run commands and transfer data.
Main problem is that I don't want to run anything with root privileges and I don't want a local bridge network requirement for ssh access because that requires a specific host configuration that cannot be done by the user ad-hoc. Maybe there are alternatives? User-networking etc.?

A: From http://www.linux-kvm.org/page/Networking:
kvm -hda img -device e1000,netdev=user.0 \
    -netdev user,id=user.0,hostfwd=tcp::5555-:22 -nographic

User networking with port forward. User can listen on ports > 1024, and kvm redirects it to port 22. Should work with everything tcp (ssh, scp, rsync, telnet etc.).

redpajama_set_name: RedPajamaStackExchange


text:
Q: For a given $u(z)$ are there any $v(z)$ which make $f(z) = u(z)+iv(z)$ differentiable? I got the answer "no such $v$ exists" for both exercises. However, I am very surprised, since the $u's$ I have been given seem very nice and arbitrary. I would like to know if I solved them correctly, and if so, what underlying reason makes these seemingly nice functions so hostile?

$1) u(z) = x^3$

Using the Cauchy Riemann equations, we need $3x^2 = v_y$ and $0 = v_x$. The first equation gives us $v(z) = 3x^2y + g_1 (y)$, and the second gives us $v(z) = g_2(y)$. There is no $v(z)$ which satisfies these requirements.

$2) u(z) = x^2+y$

Using the Cauchy Riemann equations, we need $2x = v_y$ and $-1 = v_x$. The first equation gives us $v(z) = 2xy + g_1 (y)$, and the second gives us $v(z) = -x + g_2(y)$. There is no $v(z)$ which satisfies these requirements.

A: For such a function to exist on an open set, $u$ must be harmonic: that is,
$$
u_{xx}+u_{yy}=0
$$
To see that this is necessary, suppose $u$ and $v$ satisfy the Cauchy-Riemann equations:
$$
u_x=v_y\\
u_y=-v_x
$$
Differentiating the first equation by $x$ gives $u_{xx}=v_{yx}$; differentiating the second by $y$ gives $u_{yy}=-v_{xy}$. By the symmetry of partial derivatives, it follows that $u_{xx}=-u_{yy}$.
(Such a function $v$ is called a harmonic conjugate of $u$.)


text:
Q: Abstract Class of Interface in PHP? Respecting SRP I have a need to design what, in my head, seems to be a simple system that performs some calculations on data passed from a webform where data is entered by a user. The webform itself is throwaway but the back end code should go on to be used in a new project I will start soon that handles these calculations on data that it goes out and finds by itself.
I originally thought that the Strategy pattern was a good fit for these back-end classes but as I started writing them Friday it really hit me that I have probably 95% duplication in my code between my 4 classes. While I feel like my current solution would work well if it was ever decided that the formulas or how the data interacts were to change, right now that code duplication makes me uneasy.
The basics are like this:
We have 4 sales programs and each of these programs has 5 properties that vary between each program but the formula to calculate what I need to know is all the same.
Currently I have an interface with a single function calculate and 4 classes (one for each program) that implement this function. That was all well and good until I quickly realized that calculate and the other functions I implemented in my classes are all 100% to the letter the same. The only thing that is different in my 4 files are the 5 values.
My original design plan was to build so that I could key from a dropdown on the webform and to pass in a class that had my values in it and perform the calculation. Since I've stepped back from that I see that I've missed that mark and need to re-evaluate my structure.
I've done some research on Abstract classes and even the Decorator pattern but nothing really seems to be clicking right away. I like the idea of building it so that in the future other sales programs could be easily brought into it but I don't like requiring someone to basically go into my files and copy the file and adjust the variables at the top, that seems very sloppy.
The easy solution seems to be just to write a single Calculator class and pass in an array of these variables based on what the user selected. I may be trying to over-engineer this but going with the easy solution doesn't feel right either.

A: Seems like you might be looking for the Strategy pattern ;)


text:
Q: Tile layers content is repeating on each tile I am new to leaflet and mapbox. I built a map with with mapbox with my own tiled layers that I made with tilemill exported as mbtiles and extracted with mb-util. Tested from my localhost everything is fine, but when I built the map from my webserver, the layer contents are repeating on each tile when zooming the map. Below is my code. I don't understand this different behaviour and how to avoid this. Can anybody help me, please??
<!DOCTYPE html>

<meta charset=utf-8 />
<title>Layers Control</title>

<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />

<link href='https://api.tiles.mapbox.com/mapbox.js/v1.6.2/mapbox.css' rel='stylesheet' />


text:
Q: Laravel Artisan command is not working I Have installed PHP7.1 earlier. Then I downgraded to 5.6.
Now Laravel Artisan command is not working.The error is
command not found...

and also php -vis not working either. instead of php -v  , php56 -v is working.
I'm using Fedora 26 , Laravel version is v5.0

A: You can configure your default php version on terminal : update-alternatives --config php
This will provide you php options available to select the preferred one.

A: Switch PHP version:
From php5.6 to php7.0:
Apache:
sudo a2dismod php5.6 ; sudo a2enmod php7.0 ; sudo service apache2 restart

CLI:
sudo update-alternatives --set php /usr/bin/php7.0

From php7.0 to php5.6:
Apache:
sudo a2dismod php7.0 ; sudo a2enmod php5.6 ; sudo service apache2 restart

CLI:
sudo update-alternatives --set php /usr/bin/php5.6


text:
Q: $21$ people in classroom, split into $4$ groups of $4$ and $1$ group of $5,$ probability specified two people together
Alice and Bob are two students among a class of $21$. Their teacher will randomly divide the class into $4$ groups of $4$ and one group of $5.$ Find the probability that Alice and Bob are put in the same group?

A possible way of solving this problem outlined is to do $(4)(4)(3)$ and $(5)(4),$ add them and divide by $420.$ However, I'm not really sure how this works. If we split the problem into cases of when they are together in a group of $4$ and when they are together in a group of $4,$ for the first case there are $4$ possible groups, but from there why do we have to do $4 \cdot 3?$ If we want the two to be in the same group, then there will be $19$ undetermined spots, and of those we can choose $2$ people to  be in that group of $4,$ to obtain $\tbinom{19}{2} \cdot 4=15504,$ but this is clearly wrong. What am I doing wrong?
Also, I was wondering if there is a easier way of doing this problem instead of computing number of desired possibilities over total possibilities, and instead considering the problem as, since there are $4$ groups of $4,$ then there is a $\tfrac{16}{21}$ possibility of groups of $4,$ and a $\tfrac{5}{21}$ possibility of groups of $5.$ In other words, I am curious if there are any other approaches to the aforementioned one, which I am confused on why it works. Thanks in advance!

A: Rare problem that is best attacked as probability of events problem rather than enumeration of Combinatorics.

Probablity that Alice is at a table of $(4)$ is $\dfrac{16}{21}.$
When that happens, probability that Bob is at the same table is $\dfrac{3}{20}.$

Probablity that Alice is at a table of $(5)$ is $\dfrac{5}{21}.$
When that happens, probability that Bob is at the same table is $\dfrac{4}{20}.$

Putting this all together, the desired computation is
$$\left[\frac{16}{21} \times \frac{3}{20}\right] + \left[\frac{5}{21} \times \frac{4}{20}\right].$$

A: The first approach that you mention considers there to be different "orderings" of the students. This means that for each assignment of students into groups, they can still have a different "ordering" within each group, which would result in more than $1$ possibility. Whereas if order didn't matter, it would only be $1$ possibility for each assignment.
As such, the $420$ comes from the fact that there are $21$ spots for the first person (let's say it's Alice; it doesn't really matter), and after Alice chooses her spot, Bob has $20$ spots remaining.
The $4\cdot4\cdot3$ for the $4$ groups of $4$ case comes from the fact that there are $4$ groups of $4$ to choose from, then within that group, there are $4$ "spots" that Alice can choose (this is where the ordering part comes into play; if order didn't matter we won't have to do this). After Alice chooses her spot, there are $3$ spots left that Bob can choose.
A similar reasoning applies for the $1$ group of $5$: There is $1$ group of $5$ to choose from, and within that group, Alice has $5$ spots to choose from. After Alice chooses her spot, Bob has $4$ spots remaining to choose from, resulting in $1\cdot5\cdot4$.
Because the two cases are independent, we can then add them up to get the number of possibilities such that Alice and Bob are in the same group. Dividing that by the total number of possibilities, which is $420$, gives the final probability.

A: Doing it with probabilities (as done in the answer of @user2661923) is beyond doubt the most efficient and elegant route.
Doing it with combinations you could go for:
$$\frac{\frac{19!}{2!4!4!4!5!}+\frac{19!}{4!2!4!4!5!}+\frac{19!}{4!4!2!4!5!}+\frac{19!}{4!4!4!2!5!}+\frac{19!}{4!4!4!4!3!}}{\frac{21!}{4!4!4!4!5!}}=\frac{4\times3\times4+4\times5}{20\times21}=\frac{68}{420}=\frac{17}{105}$$


text:
Q: What is an eloquent word for a disrespectful, impertinent child? I'm looking for a word that denotes a child (either a young one or a fully grown one) who acts disrespectfully and spitefully toward their parents.
For instance, if you see your friend being disrespectful toward his or her parent, you might ask your friend,

Why are you acting like a ________ ?

An adverbial form would be sufficient too, like

"Why are you acting [adverbial form of word]?"

I do not want any words that have connotations of annoying, whiny, irritating, etc. This includes "brat," "rascal," etc.
The word can be archaic (that is, old-fashioned) but preferably not obsolete (i.e. no longer used at all).

A: Few of the eloquent as well as euphemistic words use to present disrespectful and impertinent kid(s) or person are:
impudently (adverb) ODO

Meaning: rude and not showing respect, especially towards someone who is older or in a more important position

Usage: an impudent child

malapert (noun) ODO
[archaic]

:(of person)
Meaning: An impudent person.

Usage: "A child's outcry, more malapert than the priest, called the attention of the lingerers, and before any one knew, the passion of destruction had seized like a frenzy upon the people."

Above is an excerpt from the book: Royal Edinburgh: Her Saints, Kings, Prophets and Poets by Mrs. Oliphant
Collins dictionary also suggest malapertly (adverb)

A: Brat and punk come to mind, followed by a long list of apt, witty, precise, but, alas, mostly outdated, words.
UPD:
Since the OP does not mind (he just said so), here are some words that may strike some people as way out of date:
imp: little devil (applied to children)
urchin: a mischievous boy
rascal: dishonest or unscrupulous person; and mischief maker when applied to kids
scamp: very naughty young person


text:
Q: UnderscoreJS -- _.some() vs _.find() From what I've read in the documentation, _.find() functions very similarly to _.some()
Does anyone know whether there are (performance) advantages between the two?

A: If you look into it's source, you will find that those two are identical, _.find actually calls _.some.
_.find = _.detect = function(obj, iterator, context) {
  var result;
  any(obj, function(value, index, list) {
    if (iterator.call(context, value, index, list)) {
      result = value;
      return true;
    }
  });
  return result;
};

var any = _.some = _.any = function(obj, iterator, context) {
  iterator || (iterator = _.identity);
  var result = false;
  if (obj == null) return result;
  if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  each(obj, function(value, index, list) {
    if (result || (result = iterator.call(context, value, index, list))) return breaker;
  });
  return !!result;
};

A: Their performance characteristics are probably the same, assuming you want to know wether to use find or some in a specific case. They are both lazy in the same way.
The difference is in the output. find will return the value, some will return a boolean.

I checked the source (1.4.4). some and find both use some (=== any) internally. So even if a native implementation of some is used it benefits both find and some.


text:
Q: Delphi Rio after patching not starting I just did a complete system rebuild (format C drive and go from there)... Win 10 Pro 64 bit.  I reinstalled Delphi Rio, the INITIAL release (6.7GB).... Delphi started up fine.  I had previously downloaded Delphi Rio Patch 2, (7.3GB), so I unzipped it, and ran setup.  It automatically chose the middle option (Modify), so I left it at that... and installed.  It appeared to run fine.  After completion, I noticed that it had removed the Delphi icon I created on my desktop, and that the links in my start menu for Delphi no longer work...  I did not investigate a whole lot, as I had a patch 3 (7.9GB) to install as well.  I unzipped, ran setup, and again Modify was the default option, so I ran with that... no errors.  When completed, I tried to run Delphi.  I have what I think is the appropriate directory structure (C:\Program Files (x86)\Embarcadero\Studio\20.0\bin) with 298 files in the bin directory, however bds.exe is NOT one of the files.  Any idea what is going on?
The only possibility I can think of is that I have let my subscription expire....  and I am not entitled to the patches, yet the Embarcadero support system let me download them.  Could this be the explanation?

A: Updating a certain Delphi version is usually done like this:

*

*Download new ISO file or web installer

*Uninstall the Delphi version you want to update and keep the registry settings (you are asked about this during the process)

*Run setup from downloaded ISO or web installer

Your approach of installing the newer version on top of the older one is clearly the wrong way.
This is also explained in the install instructions (readme file) that comes with every ISO or web installer.


text:
Q: Nonstandard spellings for dialects Are there standard ways of indicating dialect, as "I 'aven't," I asked 'is name," and especially "It couldn't 'a' 'appened."  Can "have" be indicated with just "a"?

A: It will depend on dialect, and probably even more so on its written history.
If it's a book oriented towards the majority of the English-speaking world (or expecting many non-native speakers to read it), the apostrophes become more important.
If the book is oriented towards people already familiar with the dialect in question, you are less likely to need an apostrophe every half word.
Basically, consider the audience, and what they'll be familiar with.  Any standard will be decided through tyranny of the masses and what other authors have done in the past that people consider to be of good form.
And don't forget another option: write with MSE spelling but dialectal syntax, and then add in the intended dialect, such as: "'What are you saying?' he asked, his voice thick with a central Alabamian accent"1 to be read mentally by the reader as What are ya sayin'?.  That will let you effectively represent things (like the wh-w distinction in my example) that are difficult to otherwise show otherwise.
1. There are certainly more elegant ways to integrate this, but an elegant writer I'm not.


text:
Q: How to receive array within Vardictonary in Native Client send from javascript I am sending dictionary with string and array from javascript to native client like
   var paramdata=[]  //with values

   common.naclModule.postMessage({'message' : 'Configuration',
                                 'param_array' : paramdata});

and trying to receive from native client like
    if (var_message.is_dictionary()) {
     pp::VarArray param_array;
       pp::VarDictionary dictionary_js(var_message);
       std::string js_message = dictionary_js.Get("message").AsString();
       if(js_message == "Configuration")
       {
                pp::Var var(dictionary_js.Get("param_array"));

but it gives error like error: no match for call to `(pp::VarArray) (pp::Var&)'...what is the proper way to get array from dictionary.
Thanks in advance.

A: I got an answer.. I have to use
pp::VarArray array = dictionary_js.Get("param_array");

instead of
pp::Var var(dictionary_js.Get("param_array"));


text:
Q: User Authentication - Play Framework, Java I am new to Play Framework. I am doing practicing (Play+Java) by creating various types of scenario e.g. link with the DB, retrieve data from Database using JPA, Master Detail forms, saving data into database etc.
I want to implement user authentication. User login to application. To access application user must have authorization.
For example : Employee - Add/Edit/View/Delete. Some users may have all the authorization and some users have View only or Add/Edit/Delete or only Edit. Even in Employee Edit option user can only edit certain field e.g. Emplyee name is not allowed but employee's address can edit. i.e. field level authorization.
Thanks

A: *

*use an Authentication Controller to check user login id/password

class AuthController @Inject()(cache: CacheApi, cached: Cached, actorSystem: ActorSystem) extends Controller {

*if id/password is correct, generate an UUID key, and stored user object (uservo) in memory cache with UUID key. The key can be stored in browser cookie.

    val cacheTimeout = 10.minutes
    val key = UUID.randomUUID.toString
    cache.set(key, uservo, cacheTimeout)
    Ok().withSession( request.session + ("key" -> key) )

*We can get cookie with "key" value in the following html requests. If the key can be retrieved from memory cache, the user is valid to do the action.
Remember to set the cookie value again, or else the cached uservo in memory cache will timeout after 10 minutes

    (request.session.get("key").flatMap { key =>
       cache.get[Uservo](key)
      } map { uservo =>
         // need to set cache with "key" again, or else the memory will timeout in 10 minutes
         cache.set(request.session.get("key").get, uservo, cacheTimeout)
         // do the action..
      }).orElse {
         // failed and return to login home page
         Some(Future(Redirect("/").withNewSession))
      }


text:
Q: string and subscript in label
s = Import[
"Desktop/crack.xlsx", {"Data", 2, Range[1, 546], {1, 2, 4}}];
ListContourPlot[s, AspectRatio -> Automatic,
ColorFunction -> "Pastel",
Contours -> Range[0.054, 0.27, (0.27 - 0.054)/10],
FrameLabel -> {Subscript[X, 1], Subscript[X, 2]},
PlotLegends -> Placed[Automatic, Right], ColorFunction -> "Pastel",
PlotLabel -> Style["MLS" Subscript[u, 2]
OverTilde[\[Eta]] "=0.048%", FontSize -> 18]]

The label of this ouput has subscript and string. But I want the label show like the below. How to modify the Plotlabel command??

A: You can try using Row to layout the text, and use Spacer command to adjust the spacing as needed

Plot[Sin[x], {x, -Pi, Pi},
 PlotLabel ->
  Text@Style[
    TraditionalForm[
     Row[{"MLS", Spacer[5], Subscript[u, 2], Spacer[20],
       OverTilde[\[Eta]] , Spacer[5], "= 0.048%"}]], FontSize -> 18],
 ImagePadding -> 20]

Or, the way I would actually do it, is use Szhorvat nice MaTex package, like this
<< MaTeX`
label = MaTeX["\\text{MLS}\\, u_2 \\qquad \\tilde\\eta = 0.048\%",
   Magnification -> 2];
Plot[Sin[x], {x, -Pi, Pi}, PlotLabel -> label, ImagePadding -> 20]

A: Your output is formatted wrongly, because what you gave to Style is not a series of things to style, but a multiplication of its elements. Just evaluate the arguments on their own in your notebook to see the effect:
"MLS" Subscript[u, 2] OverTilde[\[Eta]] "=0.048%"
(* "=0.048%" "MLS" \!\(\*OverscriptBox[\(\[Eta]\), \(~\)]\) Subscript[u, 2] *)

To get what you wanted, you could modify PlotLabel to
PlotLabel->TraditionalForm@
 Style[Row[{"MLS ", Subscript[u, 2], "\t", OverTilde[\[Eta]],
  "=0.048%"}], FontSize -> 18]


text:
Q: Trying to use Java file.getAbsolutePath() to get the absolute path of a file I'm working on a simple project, and i'm trying to get the absolute path of a file. This is what i'm trying:
String s = "file.txt";
System.out.println(new File(s).getAbsoluteFile().getAbsolutePath());

The output is:
C:\Users\Marcello\Desktop\Java Workspace\Simple Project\file.txt

Where "Simple Project" is the name of the project where the code is.
But the output should be:
C:\Users\Marcello\Desktop\file.txt

That is where i created the .txt file.
I also tryed with file.getCanonicalFile() and "file.getCanonicalPath()". And i've had the same issue.
In this project i'm using a text file, but i want it to work with folders too. So if someone knows a solution also for folder, i'd like to see it.
Sorry for my english but it's not my mother-tongue, thanks in advance.

EDITED:
I think the absolute path should be:
C:\Users\Marcello\Desktop\file.txt

Because i created the .txt file by right-clicking on the desktop....
Here is a screenshot of my desktop:

A: File is not an actual file, it is just a reference to a file path which may or may not exist. The file you created on your desktop has nothing to do with the File object you created in Java. The output is telling you, not where your expected file is, but where the File object's reference is going to go looking for it if you try to open the file.
To find an actual path to a file in an unknown location, you'll have search for it, as in "Recursively list files in Java".

A: Since you say that the file is in your current location, File just adds that in front of it. If you execute your program in another directory, the path would be something else. Java does not check if the file exists and java can't know where you created a file named that - and there might be multiple files named so.
If you want to access a file that is not in your current work directory (you can see that using System.getProperty("user.dir)), you need to give it a path in front of it - no matter if relative or absolute, but java can't guess where your file is.

A: The easiest way to do this for any file whether it be on the desktop or wherever would be to first browse for the file.
Second, select the file.
Third, use code to get the absolute file path of the file you selected.
To do that, you can use something like this:
JFileChooser choose = new JFileChooser();
choose.showOpenDialog(null);
File f = choose.getSelectedFile();
String filePath = f.getAbsolutePath();

Otherwise, IF AND ONLY IF your file is located on the desktop or if the desktop is somewhere in the file path, then you can use this:
File f = new File(System.getProperty("user.home") + "/Desktop" + "\\file.txt");
if(f.exists())
   String filePath = f.getAbsolutePath();

Hope this helps!!
This code goes directly to the desktop and then gets the file you hardcoded in.


text:
Q: Can`t understand how to create a Fragment, my App is crashing I started studying fragments of android studio and find some tutorials "how to create a fragment". But when I am run my app, it is crushes in emulator without errors. I think some error in MainActivity, but I am not sure
This is my MainActiviti.java:
public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragment_container);

        if(fragment == null){
            fragment = new CrimeFragment();
            fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
        }

    }
}

And it`s a code for fragment(CrimeFragment):
public class CrimeFragment extends Fragment {

    private Crime mCrime;
    private EditText mTittleField;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCrime = new Crime();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_crime, container, false);
        mTittleField = v.findViewById(R.id.crime_tittle);
        mTittleField.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mCrime.setmTittle(s.toString());

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        return v;
    }
}

I think problem in MainActivity.java maybe...
This is 2 xml files:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"

    android:id="@+id/fragment_container">

</FrameLayout>

fragment_crime.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fr">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/crime_tittle"
        android:hint="@string/crime_tittle_hint"/>

</LinearLayout>

Hope someone can help me.
THIS IS LOG ERROR
Process: com.hocage.tutorial_2, PID: 10713
    java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
        at com.hocage.tutorial_2.CrimeFragment.onCreateView(CrimeFragment.java:33)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
        at android.app.Activity.performStart(Activity.java:8024)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)


text:
Q: Change Redirect URI of Identity Provider in Keycloak Whenever we configure Identity Provider in KeyCloak, it automatically sets Redirect URI like
http://keyclaok:8080/auth/realms/{MY_REALM}/broker/google/endpoint
I am implementing multi-tenancy in the project. For every tenant, I will have a separate realm and in turn, have a separate Redirect URI.
For this to work, I need to configure the same URL in "Authorized Redirect URLs" in Google Cloud Platform Console.
To ensure KeyCloak's IDP Redirect URI and Google console's configured Authorized URL match, there are 2 possible options

*

*Dynamically(programmatically) configure Authorized Redirect URL in Google console when new tenant/realm is created. As far as I know, there is no way to dynamically set this authorized redirect URL. So this doesn't look like a viable option.

*Configure custom redirect URI in KeyCloak. However, Keycloak doesn't seem to allow changing Redirect URI for Identity Provider.

Any solution, workaround or hints would be appreciated. I feel this is not a unique problem that I am solving. It must be already done and solved by many.


text:
Q: Redirect when page isn't exactly found Okay, so I posted here the other day and it was a ton of help so I decided to come back. I have another problem with the same code. I wanted to add another source to it which I used = "$location_url2" I then added a second "$content" to match the code up. the difference between the two sources is "$location_url" returns a blank page if nothing is found, but "$lcation_url2" redirects to index.php if nothing is found, but keeps the extension on the url... The code I'm using:
<?php
    if(isset($_POST['search'])) {
        $search_text = $_POST['search'];
        $location_url = "http://cydia.saurik.com/package/{$search_text}/";
        $location_url2 = "http://rpetri.ch/cydia/{$search_text}/";
        $content = @file_get_contents($location_url);
        $content2 = @file_get_contents($location_url2);

        if($content) {
            header("Location: {$location_url}");
        } else if($content2) {
            header("Location: {$location_url2}");
        } else {
            header("Location: suggest.php");
        }
    }
?>

HTML code:

    <form method="POST" name="search" action="search.php">
      <input type="text" name="search" name="placeholder" placeholder="Search Tweaks..."/>
      <input type="submit" name="submit" value="Search"/>
    </form>

A: this might be hard to do, unless you're absolutely sure the two links return nothing when nothing's found. If either of the two locations return something like a 404 your script will interpret the 404 as actual content and redirect there... You might need to look for an alternative way of determining if a site "has content or not"
You could check the header for a 200 like this:
$header=get_headers($url,true);

and then test $header[0] to have "200" in it... it makes it dodgy code though. If at any time one of the URL's returns any unexpected output with HTTP/1.1 200 OK in the header your script will think it's all ok
There's also a lot of redundancy in your code. Right now $location_url2 is downloaded even if there's content in $location_url, which is only burning resources and makes your scripting slower than needed...
I would go somewhere alongs the lines of this: (keep in mind, you're highly depending on what the url's return):
<?

$search_text=filter_input(INPUT_POST,"search",FILTER_SANITIZE_ENCODED);

if($search_text!=""){
    $location_url = "http://cydia.saurik.com/package/{$search_text}/";
    $location_url2 = "http://rpetri.ch/cydia/{$search_text}/";

    $content=@file_header($location_url,true);
    if(strpos($content,"200 OK")!==false)
        header("Location: {$location_url}");
    else{
        $content=@file_header($location_url2,true);
        if(strpos($content,"200 OK")!==false)
            header("Location: {$location_url2}");
        else
            header("Location: http://www.amazingjokes.com");
    }
}


text:
Q: Код словаря, который будет одинаково хорошо работать на Python 2.x и 3.x В Python 3.x с PEP 3106: Dictionary Views поменялось поведение словарей.
У меня есть свой класс, производный от dict, похожий по поведению на collections.OrderedDict, но отличающийся от него. В любом случае, у класса «под капотом» есть список self._ordering. Вот фрагмент, отражающий основную суть:
class TimestampingDict(dict):
    """
    An ordered dictionary, tracking item update times.
    Least recently updated items are returned first.
    """
    def __init__(self, *args, **kwargs):
        self._ordering = []
        super(TimestampingDict, self).__init__(*args, **kwargs)

    def __getitem__(self, key):
        _timestamp, value = super(TimestampingDict, self).__getitem__(key)
        return value

    def __setitem__(self, key, value):
        if key in self:
            # TODO: Speed this up with key->order_idx mapping?
            self._ordering.remove(key)
        super(TimestampingDict, self).__setitem__(key, (datetime.now(), value))
        self._ordering.append(key)

    def __delitem__(self):
        self._ordering.remove(key)
        super(TimestampingDict, self).__delitem__(key)

    def __iter__(self):
        for key in self._ordering:
            yield key

Хочется написать такой код, который будет одновременно одинаково хорошо работать и для 2.6+ и 3.x, ведя для каждой версии максимально «нативно.»
Посоветуйте, пожалуйста, как бы это сделать покрасивее, максимально DRY?
Идея запихать этот класс в отдельное яйцо-пакет и использовать setup.py с вызовом 2to3 мне откровенно не нравится.
A: А почему просто не унаследоваться от OrderDict? Тогда уж это точно будет масимально DRY.
from datetime import datetime
from collections import OrderedDict

class TimestampingDict(OrderedDict):
    """
    An ordered dictionary, tracking item update times.
    Least recently updated items are returned first.

    >>> d = TimestampingDict()
    >>> d['c'] = 1
    >>> d['a'] = 2
    >>> d['z'] = 3
    >>> d['g'] = 4
    >>> d['a'] = 5

    >>> for i in d.items(): print('%s = %s' % i)
    a = 5
    g = 4
    z = 3
    c = 1

    >>> d.timestamp('z').__class__
    <class 'datetime.datetime'>
    """

    def __getitem__(self, key):
        return super(TimestampingDict, self).__getitem__(key)[1]

    def timestamp(self, key):
        return super(TimestampingDict, self).__getitem__(key)[0]

    def __setitem__(self, key, value):
        if key in self: del self[key]
        super(TimestampingDict, self).__setitem__(key, (datetime.now(), value))

    # для использования принципа LIFO, согласно документации класса
    def __iter__(self):
        it = super(TimestampingDict, self).__iter__()
        return reversed(list(it))


text:
Q: How do I remove a character from a string in c++? I need help debugging my code. I've tried many things, but I can't seem to be able to delete a character from a string.
I also don't understand completely how std::erase works, I'm not sure if you can erase characters with it.
#include <iostream>
#include <string>

using namespace std;
int main(){

    string s;
    char n;
    cin >> s;
    cin >> n;

    for (int i = 0;i < s.length(); i++) {
        s.erase (n[i]);
    }

    cout << s;

    return 0;

}

EDIT: Sorry for being so vague. I recognized my issue of attempting to delete something from an array rather than the intended string. With the help of the answers posted; the updated code is attached below that works the way I want it to. Thank you for your responses!
#include <iostream>
#include <string>

using namespace std;
int main(){

string s;
char n;
cin >> s;
cin >> n;

for (int i = 0; i < s.length(); i++) {
    while (s[i] == n) {
      s.erase(i, i);
    }
}

cout << s;

return 0;

}

A: Use the erase-remove idiom:
#include <iostream>
#include <string>
#include <algorithm>

int main() {

    std::string s = "Hello World!";
    s.erase(std::remove(s.begin(), s.end(), 'l', s.end());
    std::cout << s << std::endl;
    return 0;
}

Broken down into two statements it would be:
#include <iostream>
#include <string>
#include <algorithm>

int main() {

    std::string s = "Hello World!";
    auto it = std::remove(s.begin(), s.end(), 'l');
    s.erase(it, s.end());
    std::cout << s << std::endl;
    return 0;
}

A: If you want just to remove one character from the string you can use its method find to find the character in the string. For example
auto pos = s.find( n );
if ( pos != std::string::npos ) s.erase( pos, 1 );

Or you can use a loop the following way
std::string::size_type pos = 0;

while ( pos < s.size() && s[pos] != n ) ++pos;

if ( pos != s.size() ) s.erase( pos, 1 );

If you want to erase all occurrences of the character in the string using a loop you can write
for ( std::string::size_type pos = 0; pos < s.size(); )
{
    if ( s[pos] == n ) s.erase( pos, 1 );
    else ++pos;
}

A: It will be helpful if you included a proper description of what you are trying to do. The question is a little vague but I presume you are trying to remove a given char from a string, if that's what you are trying to do, here is a working example that builds on what you already provided.
#include <iostream>
#include <string>

using namespace std;
int main(){

    string s;
    char n ;

    cin >> s;
    cin >> n;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == n) {

          s.erase(i, 1);

        }
    }

    cout << s;

    return 0;

}


text:
Q: Reading words from file and storing them in a vector c++ void print(vector<const char*> v) {
    for (vector<const char*>::const_iterator i = v.begin(); i != v.end(); ++i)
        cout << *i << ' ';
    cout << endl;
}
int main()
{
    vector<const char*> v;
    FILE *infile;
    infile = fopen("Text.txt", "r");
    char buffer[100];
    while ((fgets(buffer, 100, infile) != NULL)) {
        if (buffer[strlen(buffer) - 1] == '\n')
            buffer[strlen(buffer) - 1] = '\0';
        v.push_back((const char*)buffer);
        printf("%s\n", buffer);
    }
    fclose(infile);
    print(v);
return 0;

}
So this is what I have so far. At the printf (in the while loop), the words from the file are printed correctly. But the function print (which prints the elements of the vector) shows me only the last word repeated by the number of words from the file. For example, let's say I have this in my file:
apple
banana
orange

The print function will print:
orange
orange
orange

Edit: So I managed to get this to work. I made a list of "buffers" and it's working fine now. Thanks everyone for your help!

A: The problem is that you are calling push_back on the same array buffer, each time storing the same pointer to its initial element in the vector.
This means, among other things, that no matter what you put into buffer, before or after calling push_back, the vector elements are going to point to it. In your case the result is that you see the last element that you have read, but if you wrote to buffer after reading the file, the vector would show that new value.
In order to solve this problem you need to push back copies of the buffer, instead of pushing the buffer itself. The preferred approach in C++ would be switching away from vector<const char*> to vector<string>, because strings make the copying and resource management much easier for you.
If you must use pointers, make vector store non-const pointers; otherwise you wouldn't be able to call delete on them. Instead of pushing back buffer allocate strlen(buffer)+1 chars with new[], and strcpy the buffer into it before calling push_back.

A: Since an actual answer has already posted, your print() function could use some improvements:
void print(vector<const char*> const & v) {
    for (auto const chp : v) {
        cout << chp << ' ';
    }
    cout << '\n';
}

This version takes a reference instead of copying the whole vector. And because the vector isn't changed by print() it's const.
Also if you want to iterate over all elements of a container you don't have to manage the iterators manually.


text:
Q: MySQL can't connect using private IP address I have a fresh install of MySQL 5.7 on my Windows machine. When I make a connection using root@localhost, I am able to connect, but when i try to make a connection root@192.168.1.10 (the private IP address of my server) I  get the following error:
mysql 5.7 access denied for user 'root'@'192.168.1.10'.
I opened my my.ini file and added the line bind-address=0.0.0.0. I saved the file and restart my MySQL instance, but still not luck the same error appears.
I then tried:
**GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;**

This did not work either. I then tried to change the password for root to make sure I was using the correct password:
UPDATE mysql.user SET authentication_string=PASSWORD('password')  WHERE  User='root';

But no luck.

A: I have reinstalled MySQL and now everything works.


text:
Q: How add box shadow to a div inside a container ? (Image included) the image says what I want to do

A: Either:

*

*Put some margin on the top one's left side

*Remove overflow-hidden from the grey div

*Postion the top box with position:relative, and increase the z-index

A: this might help:
{
-moz-border-radius: 5px;
border-radius:5px;

-moz-box-shadow: 3px black;
-webkit-box-shadow:3px black;
box-shadow:3px black;
}


text:
Q: How to launch an external Process? I am reading through the docs of swift and came across Type Methods. For example here: https://developer.apple.com/documentation/foundation/process
The offered Type Method is:
class func run(URL, arguments: [String], terminationHandler: ((Process) -> Void)? = nil)
How can I use this in my code? For example when I press a button? How can I add a clean-up function to the terminationHandler?

A: In a macos app, you may use run for launching external processes, an example might be:
1) one-shot execution:
let url = URL(fileURLWithPath:"/bin/ls")
do {
   try Process.run(url, arguments: []) { (process) in
      print("\ndidFinish: \(!process.isRunning)")
   }
} catch {}

2)  you may want to use a Process instance to be able to setup more comfortably its behaviour, doing so:
let process = Process()
process.executableURL = URL(fileURLWithPath:"/bin/ls")
process.arguments = ["-la"]
process.terminationHandler = { (process) in
   print("\ndidFinish: \(!process.isRunning)")
}
do {
  try process.run()
} catch {}

So I did launch the ls command (you may check your console for the result), then in the closure terminationHandler I'm getting back such process.


text:
Q: House numbers as multiple stops route with pgRouting How do I create a routing with multiple stops?
Currently I have uploaded on PostGIS the nodes and edges of the road graph but I want the stops to match the housenumbers. The ideal work would be to considerate the time windows of each stop and the capacity of the vehicle (once reached the max capacity, the vehicle must return to a point 0, resume the route and then complete it).
Which is the best algorithm to solve this problem?
Here is a small area of housenumbers and nodes (orange points) on QGIS

A: The problem is called VRPTW: Vehicle Routing Problem with Time Windows. Google that. The best algorithms are most likely far from free.

A: You could have a look at the set of functions offered by pgRouting in the field of VRP http://docs.pgrouting.org/latest/en/VRP-category.html?highlight=vrp. Some additional information can be found here http://osgeo-org.1560.x6.nabble.com/pgrouting-users-Introduction-to-VRP-with-time-windows-Work-done-in-Gsoc-2014-td5197304.html and here https://github.com/pgRouting/pgrouting/wiki/VRP-Algorithms.


text:
Q: How can I change the color of icons? How can I change the color of icons for moreNavigationController screenshot
For tabBar i use the code:
self.tabBarController.tabBar.tintColor = [UIColor colorWithHexString:@"30cbff"];
self.tabBarController.tabBar.barTintColor = [UIColor whiteColor];

Played here with this function;
- (void)tabBarController:(UITabBarController *)tabBarController willBeginCustomizingViewControllers:(NSArray *)viewControllers;

like this:
for (UINavigationController *controller in viewControllers) {
    controller.tabBarController.tabBar.tintColor = [UIColor colorWithHexString:@"30cbff"];
}

But without results;

A: In IOS7 you can use tintColor to change Icon color.

A: Make the image as a transparent area in a white image. Put this over a view and change the background color of the underlying view. That color will show through the transparent image and provide the colored image. Change the background image color for a different color image.
This is essentially the way the color iOS created for UITabBar images.
Get something like Spark Inspector (free demo), create a Tabbed Application and inspect to see how Apple changes the color.


text:
Q: Bootstrap 3 collapse can have multiple panels open after programmatically opening a panel I have a problem with bootstrap 3 collapse, after opening a panel programmatically it is possible to keep another panel open while reopening the first panel.
My HTML:
<button type="button" class="btn showpanel">Show panel 3</button>
<button type="button" class="btn hidepanel">Hide panel 3</button>
<button type="button" class="btn openpanel">Open panel 3</button>
<button type="button" class="btn closepanel">Close panel 3</button>

                Panel 1

                Contents panel 1

                Panel 2

                Contents panel 2

                Panel 3

                Contents panel 3

And some JavaScript:
$(".hidepanel").on("click", function() {
    $("#panel3").parent().hide();
});
$(".showpanel").on("click", function() {
    $("#panel3").parent().show();
});
$(".openpanel").on("click", function() {
    $("#panel3").collapse('show');
});
$(".closepanel").on("click", function() {
    $("#panel3").collapse('hide');
});

My jsfiddle that demonstrates this issue
To reproduce:

*

*Click the button 'Open panel 3'.

*Click 'Panel 2' to open it. So far no problems.

*Click 'Panel 3' to open it again. Panel 2 remains open!

So opening a panel programmatically seems to mess up bootstraps internal registration about panel states? I don't see anything visibly wrong with the 'state change' of the third panel (it's class changes from 'collapse' to 'in' and back as you would expect).

A: You can create a handler for the collapse show event which occurs just before any panels are displayed.
Add this to ensure any other open panels are closed before the selected one is shown:
$('#accordion').on('show.bs.collapse', function () {
    $('#accordion .in').collapse('hide');
});

Bootply demo
You can read more about the collapse events here: http://getbootstrap.com/javascript/#collapse

A: I think the problem is due to the way you are changing the open panel.  Rather than using the 'show' feature you need to fire the click event on the appropriate panel link.  For example with an accordion with an id "accordion", with three panels, if you want to show the 2 panel then use:
$("a[href=#accordion-2]").click()

Or whatever ID you have given your second panel (I use twitterboostrapmvc so the panel ids are auto-generated from the accordion ID).

A: For anyone using data-target attributes to control the accordion (rather than the href attribute), this is an adaptation of ProfNimrod's answer which will click the relevant element if the target is currently hidden. (Note that the if check relies on setting up the accordion with the collapsed class applied by default, which I find useful anyway to take advantage of using css to put a chevron icon on the accordions).
var expandAccordion = function() {
    var header = $('[data-target="#accordion-0"]');
    if (header.hasClass('collapsed')) {
        header.click();
    }
}


text:
Q: Play Framework: How to log in using POST? I'm developing a web service using Play Framework. My next step is to log in using module secure. However, Im getting a nullpointer exception as the following:
play.exceptions.JavaExecutionException
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:227)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.NullPointerException
at play.utils.Java.invokeStaticOrParent(Java.java:146)
at controllers.Secure$Security.invoke(Secure.java:193)
at controllers.Secure$Security.access$0(Secure.java:184)
at controllers.Secure.authenticate(Secure.java:61)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:540)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:498)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:474)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:469)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:157)
... 1 more

According to Playframework Secure module: how do you "log in" to test a secured controller in a FunctionalTest? it's possible to do a post to /login, which I also have tested and it works perfectly in a test-case.
To recreate nullpointer exception do the following:

*

*List item

*Create a new project

*Add the module secure as a dependency

*install the dependencies 'play dependencies'

*Restart web app.

*Send a post to /login. I have added two request headers (username and password), but the exception occurs both with and without any headers. The post is (in my case) sent using REST Client for Firefox.

Thankful for any help!

A: It looks like either your username or password is null. Since you're POSTing to the login action, you should be sending the username and password as part of the encoded request body, but it sounds like you may be doing something different (or I misunderstood what you meant by adding the request headers).
This is might be a bit of a bug in the Secure module too, as I imagine this case should be handled a bit more gracefully. The reason you get the NullPointerException is because invokeStaticOrParent needs to determine the types of the arguments to figure out which method to invoke, and in the case of a null argument an exception is thrown when trying to call getClass().
The authenticate action in the Secure module should probably mark the password parameter as @Required, and perform a check against validation.hasErrors() before trying to invoke the underlying authentify/authenticate method, instead of after like it does now.
There's actually even an existing ticket related to this, but I don't know what progress has been made. I'll check sometime later to see if there's a pending commit to address this, and if not I'll see what I can do about submitting a patch.


text:
Q: How to parse login response in android? I am confused about parsing so I want to know about how to parse. Whenever I login with valid login id and password give response
{
  "data": {
    "status": "1",
    "Full Name": [
      {
        "user_id": 1,
        "user_name": "deepika@soms.in",
        "full_name": "",
        "display_name": "",
        "token": "",
        "photo_url": "http://clients.vfactor.in/putt2gether/images/profile/default.jpg"
      }
    ],
    "Event": [
      {
        "latest_event_id": "",
        "format_id": ""
      }
    ],
    "msg": "Success Login"
  }
}

and if invalid login id then give response
{
  "Error": {
    "msg": "Please Enter valid Email Address"
  }

A: You need to parse the json answer.
There are many sources to learn how to do that:

*

*Oracle documentation

*Jackson documentation - Jackson is a library to parse json

*GSon documentation - Another json parser

A: try {
     JSONObject obj = new JSONObject(response);
            if (obj.has("Error")) {
                JSONObject objError = obj.getJSONObject("Error");
            } else if (obj.has("data")) {
                JSONObject objData = obj.getJSONObject("data");
            }
    } catch (Exception e) {
            e.printStackTrace();
    }

A: Let's assume response be,
String response;
try
  {
   JSONObject jsonObject = new JSONObject(response);

   if (jsonObject.has("data"))
     {
            JSONObject jsonObjData = jsonObject.getJSONObject("data");

            String status = jsonObject.getString("status");

            JSONArray jsonArrayName = jsonObjData.getJSONArray("Full Name");

            for (int i = 0; i < jsonArrayName.length(); i++) {
                JSONObject jsonObj = jsonArrayName.getJSONObject(i);

                Integer user_id = jsonObj.getInt("user_id");
                String user_name = jsonObj.getString("user_name");
                String full_name = jsonObj.getString("full_name");
                String display_name = jsonObj.getString("display_name");
                String photo_url = jsonObj.getString("photo_url");
            }

            JSONArray jsonArrayEvent = jsonObjData.getJSONArray("Event");

            for (int i = 0; i < jsonArrayEvent.length(); i++) {
                JSONObject jsonObj = jsonArrayEvent.getJSONObject(i);

                String latest_event_id = jsonObj.getString("latest_event_id");
                String format_id = jsonObj.getString("format_id");
            }

            String msg = jsonObject.getString("msg");
        } else if (jsonObject.has("Error")) {
            JSONObject jsonObjError = jsonObject.getJSONObject("Error");

            String msg = jsonObjError.getString("msg");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }


text:
Q: Different result posting sql query through php than through phpmyadmin Sorry if it's been asked before but I think this might be very specific to the query..I'm very new to both PHP and SQL but got a high scores system working and now stuck on one last thing...I have a query that if I paste into phpmyadmin it works fine, but when included between $sql ="" (in PHP) it doesn't.
In a vain attempt to debug it calling via a browser I can see the offending item just can't see why, in PHP:
$sql = "SET @rownum := 0; SELECT * FROM (SELECT @rownum := @rownum+1 AS rank, ID, Username, Score, UDID FROM users ORDER BY Score DESC)
AS derived_table WHERE Username = 'Dave';";

This returns nothing...but paste it into phpmyadmin and it works fine, returns two entries sorted by score and displaying their rank.
If I remove SET @rownum := 0; then it works but returns null for rank...so I guess the ; is causing it to terminate?
Any ideas would be a big help before I pull the last piece of hair out.

A: In a regular mysql API in PHP, this is not possible.
Try executing your queries separately (SET & SELECT) and use mysqli_multi_query.
http://se2.php.net/manual/en/mysqli.multi-query.php


text:
Q: Determining a distribution
For part (i), I have:
1) $X$ is binomial with parameters $n$ and $p = \frac{1}{2} + \frac{1}{3} = \frac{5}{6}$ i.e. $X$ is $\operatorname{Bin}(n,\frac{5}{6})$?
2) $Y$ is geometric with parameter $\frac{1}{3}$?
I think I can use the $P(Y \geq 3) = 1 - P(Y = 2) - P(Y=1) - P(Y=0)$ for the final part in that case?
Any help please

A: Yes that is so, except that $Y$ has the support of $\{1,2,\ldots\}$. It is the count of trials until the first strictly positive result, so the count begins at $1$.   Make sure you are using the correct Geometric Distribution (there are two).   But the success rate is $1/3$.
You can also use that for such a Geometric random variable, $\Bbb P(Y\geq k)$ is the probability of $k-1$ consecutive 'failures' (ie: that the first 'success' occurs later than this).

A: Your thinking is correct, but you need to specify the distribution for $Y$ explicitly.  In particular, $\Pr[Y = 0] = 0$, because $Y$ counts the number of entries up to and including the first strictly positive entry, thus it is not possible for $Y = 0$.  The smallest value is $Y = 1$, attained with probability $\Pr[Y = 1] = 1/3$, occurring when the first draw from $\Omega$ is $1$.  With this in mind, what is $\Pr[Y = 2]$?

A: The event $Y\ge3$ is the same as failure to get a positive number on the first two trials. On each trial the probability of such failure is $2/3$, so the probability you seek is $(2/3)^2.$


text:
Q: How to get FxCop for WinXP? I have Windows XP and Visual Studio 2010 installed.
Intended to use FxCop to check if the solution corresponds to the Microsoft Code Guides.
Now found out that FxCop is part of "Microsoft Windows SDK for Windows 7 and .NET Framework 4"
Should I install this thing, even if I have Windows XP?

A: FxCop 10 can be run on WindowsXP (I have installed it on my XP box at work.) Having said that, I agree with Anuraj's comment - if you are using a version of VisualStudio 2010 that includes code analysis, using that is an easy place to start.  With a few exceptions, both VS and FxCop use the same rule set, so knowing one will help with the other.

A: I think you can use Static code analysis enabled instead of FxCop. It include FxCop and more. More information can be get from this SO link
Visual Studio Code Analysis vs StyleCop + FxCop

A: FxCop 1.36 is the last version that officially supports Windows XP. Essentially, it is part of the SDK.  The SDK in question ( WinSDK 7.0 (Windows SDK for Windows 7 and .Net Framework 3.5 SP1)) can be downloaded here.


text:
Q: How to make Eclipse support JQuery
Possible Duplicate:
Is it possible to integrate Jquery with Eclipse?

Found WTP does not support jQuery by default. Any other plugin exists supporting jQuery?

A: You can add jquery to any html project you open in eclipse by adding this line to your html
<script src="http://code.jquery.com/jquery-latest.js"></script>

You can also integrate jquery with autocompletion to your Eclipse installation with jQueryWTP.
http://www.langtags.com/jquerywtp/
http://javascriptly.com/2008/10/jquery-eclipse-wtp/

A: This plugin has just been released a few days ago :
http://www.langtags.com/jquerywtp/

A: You can use Aptana, it can be installed as a plugin in Eclipse. Take a look here for jquery support


text:
Q: How to avoid having to reference an external XML file? I am writing an app in C and using Glade3 to make the GUI (and GTK builder).
Glade 3 doesn't allow C code generation anymore (which I understand the reasons for), but now all applications need to have the XML file hanging around the compiled app like an annoying .dll file. Does anyone have any knowledge of project to create C code for it, or how to embed the XML file in the code itself? I imagine this could be done, but it would be a pain I bet.

A: What you probably want is:
gtk_builder_new_from_string(const gchar *string, gssize length);
https://developer.gnome.org/gtk3/3.10/GtkBuilder.html#gtk-builder-new-from-string
Just stringify the glade3 xml file (in GtkBuilder format) and include it as a string.
It is still possible to use glade-2.12 to generate gtk2 code and then port it to gtk3; however if you are going to do that it may be worth it to simply modify that version of glade to output the gtk3 syntax directly.


text:
Q: NavigationItem leftNavigationItem is not clickable I am having MasterViewController and it has childView as UITabBarController. UITabBarController has navigationcontroller as tab bar item. Both MasterViewController and TabBarItem ViewController extends from BaseViewController. I have written code to add leftNavigationItem(UIBarButtonItem) on BaseViewController viewDidLoad method. But leftNavigationItem(UIBarButtonItem) is not clickable. I have added selector to the leftnavigationItem(UIBarButtonItem) as well.
MasterViewController
class MasterViewController: BaseViewController {
    // MARK: Outlets
    var masterTabBarController: UITabBarController!

    // MARK: View Methods
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeView()
    }

    // MARK: Overridden Methods
    override func initializeView() {
        super.initializeView()
        addTabBar()
    }

    // MARK: Private Methods
    private func addTabBar() {
        guard let appTabBarController = AppRouter.appTabBarController
            else {
                return
        }
        masterTabBarController = appTabBarController
        addChild(appTabBarController)
        appTabBarController.delegate = self
        view.addSubview(appTabBarController.view)
    }
}

TransactionsViewController
class TransactionsViewController: BaseViewController {
    // MARK: Outlets

    // MARK: View Methods
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeView()
    }

    // MARK: Overridden Methods
    override func initializeView() {
        super.initializeView()
    }
}

BaseViewController
// MARK: -
enum LeftButtonType: Int {
    case site
    case back
}

// MARK: -
class BaseViewController: UIViewController {
    private var leftButtonType: LeftButtonType = .site

    // MARK: View Methods
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.barTintColor = ColorConstants.white
        addLeftNavigationItem()
    }

    // MARK: Action Methods
    @objc func leftNavigationButtonClicked() {
        print("leftNavigationButtonClicked")
        switch leftButtonType {
        case .site:
            AppRouter.presentSiteSelectionViewController(fromViewController: self)
        case .back:
            navigationController?.popViewController(animated: true)
        }
    }

    // MARK: Private Methods
    private func addLeftNavigationItem() {
        if navigationController?.viewControllers.count != 1 {
            leftButtonType = .back
        }
        switch leftButtonType {
        case .site:
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(leftNavigationButtonClicked))
        case .back: break
        }
    }
}

This is Storyboard


text:
Q: Pre installed Qt designer 4.6.2 no option for c++ creation At my work we have a pre installed version of qt designer 4.6.2,
The problem is that pre installed version
Seems to only create the ui file,
I dont have an option to create new c++ file or  class
How can i add this option to the qt desginer ???
Thanks dart

A: The old Qt Designer is just for editing .ui files. It is not related to creating Qt code (C++, QML, Python...). The Qt Creator, a completely separate application, is a full-fledged IDE, which includes the old Qt Designer as a (small) part of it, and these parts are fully compatible AFAIK (the .ui file format has not changed).
So you need to install Qt Creator to have something which helps you create Qt C++ classes etc. I'm not sure, but I don't think they've explicitly dropped support for old Qt, so you can just try by installing the latest Qt Creator, then adding your Qt version to it manually. If you have trouble with this, you may want to ask a new question, but the gist of it is, add the Qt version by pointing Qt Creator to qmake binary of the Qt version you want to use, and then create a kit which uses that Qt version.


text:
Q: Composition on sets [(1,2,3,4) ○ (1,2)(3,5)]^-1
The solution has the following steps:
f=(1,2,3,4) g=(1,2)(3,5)
Compute f○g:

Where can I find information regarding what the steps are doing in this problem? I understand how to compute the composition of two functions but I can't follow what's done for sets.

A: Except for the odd style of writing things backward, this is the same as usual composition. $f \circ g$ means as usual first do $g$ then do $f$. For example $g=(12)(35)$ takes $1$ into $2$, then one sees what $f=(1234)$ takes that intermediate result $2$ into, and sees it is $3$. This shows $f \circ g$ carries $1$ to $3.$ If the cycle decomposition is desired the next one to do would be to see what $f \circ g$ takes $3$ into, in the above way, and so on to get the cycles for $f \circ g.$ After that is all done, the usual trick of reversing all the cycles in $f\circ g$ will give the cycle decomposition for $(f \circ g)^{-1},$ and if one likes one can shuffle the representations of the cycles now to place least elements first, etc.


text:
Q: Перевод из Unicode в Char #pragma _UNICODE
#pragma UNlCODE
#include <TChar.h>

char * c_f,*c_d;
wchar_t * h,*k;
...

WideCharToMultiByte(CP_ACP, 0, h, -1, c_d,0, NULL, NULL));

*

*При компиляции ругается на функцию. (Е2379 Statement missing ). Подскажите в чем проблема?

*При открытии файла *.txt кодировки Unicode в Memo он отображает только английские символы. Подскажите что не так?

*Способны циклы работать с символами wchar_t?

A: В строке #pragma UNlCODE ошибка, надо - #pragma UNICODE.
В строке WideCharToMultiByte(...)) ошибка, надо WideCharToMultiByte(...)
Попробуйте так
wchar_t* s = L"Здравствуй!";
char to[32] = { 0 };

::WideCharToMultiByte(1251, 0, s, -1, to, sizeof(to)/sizeof(to[0]), NULL, NULL);

e->Text = buf;

Да, итерация по w_char возможна, например
for (wchar_t c = 0x4ff0;  c < 0x5ff0;  c++) {
    std::wstring s(1, c);
}


text:
Q: Bash script ffmpeg pic to video not working but does in command line This works in command line for a sequence of jpg to convert to a video.
cat *.jpg  | ffmpeg -f image2pipe -framerate 5 -i - -s 1280x720  ./HD720_out.mp4

but doesn't work (except for first jpg) in a executable script temp.sh  containing:
eval  cat "$1"  | ffmpeg -f image2pipe -framerate 5 -i - -s 1280x720  "./HD720_out.mp4"

e.g. ./temp.sh *.jpg   gives only the first file to video, not the sequence.  What am I doing wrong?  The command line works perfectly.

A: Simplified: $1 gets expanded to the first commandline argument of a script.
But before your script interprets the shell running temp.sh will first expand the asterisk * in ./temp.sh *.jpg, effectively resulting a in a commandline:
./temp.sh first.jpg second.jpg third.jpg
            \
             \_  $1

You have two options to get around this. The first (and preferred):
cat "$@" | ...

will just use all command line paramters, not  only the first one. You don't need eval for this one and shouldn't use it.
The second (where eval comes into play):
eval cat "$1"  |

while calling the script with quoted parameters to avoid expansion:
 ./temp.sh '*.jpg'


text:
Q: Information will not save when I switch Content Views I am new to android dev and am trying to make a simple app that keeps the score of a basketball game and the team lineups. The problem is that whenever I switch back and forth between views, the score (or lineup) shows up as the default setup of zero (or no players). I added the code (I formatted it as nicely as I could) but I believe, since it is likely a logical error, the only important piece would be the MainActivity class at the top. Thank you for your help!
package com.example.ryan.basketballscorekeeper;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    homeScore=0;
    awayScore=0;
}

int homeScore;
int awayScore;

public void lineupsView(View view){
    TextView textView = (TextView) findViewById(R.id.homeTeamScore);
    textView.setText(homeScore+"");
    TextView textView2 = (TextView) findViewById(R.id.awayTeamScore);
    textView.setText(awayScore+"");
    setContentView(R.layout.lineups);
}
public void mainView(View view){

    EditText editText1 = (EditText) findViewById(R.id.one);
    editText1.setText(editText1.getText());
    EditText editText2 = (EditText) findViewById(R.id.two);
    editText2.setText(editText2.getText());
    EditText editText3 = (EditText) findViewById(R.id.three);
    editText3.setText(editText3.getText());
    EditText editText4 = (EditText) findViewById(R.id.four);
    editText4.setText(editText4.getText());
    EditText editText5 = (EditText) findViewById(R.id.five);
    editText5.setText(editText5.getText());
    setContentView(R.layout.activity_main);
}

public void threePointerAway(View view){
    TextView textView = (TextView) findViewById(R.id.awayTeamScore);
    awayScore+=3;
    textView.setText(awayScore+"");
}
public void threePointerHome(View view){
    TextView textView = (TextView) findViewById(R.id.homeTeamScore);
    homeScore+=3;
    textView.setText(homeScore+"");
}
public void twoPointerHome(View view){
    TextView textView = (TextView) findViewById(R.id.homeTeamScore);
    homeScore+=2;
    textView.setText(homeScore+"");
}
public void twoPointerAway(View view){
    TextView textView = (TextView) findViewById(R.id.awayTeamScore);
    awayScore+=2;
    textView.setText(awayScore+"");
}
public void freeThrowHome(View view){
    TextView textView = (TextView) findViewById(R.id.homeTeamScore);
    homeScore+=1;
    textView.setText(homeScore+"");
}
public void freeThrowAway(View view){
    TextView textView = (TextView) findViewById(R.id.awayTeamScore);
    awayScore+=1;
    textView.setText(awayScore+"");
}

public void reset(View view){
    TextView awayView = (TextView) findViewById(R.id.awayTeamScore);
    TextView homeView = (TextView) findViewById(R.id.homeTeamScore);
    homeScore=0;
    awayScore=0;
    awayView.setText(awayScore + "");
    homeView.setText(homeScore + "");
}

}

//////////////End Of .java file/////////////////////////
//////////////Beginning of Score Keeping View//////////////////////////

<ImageView
    android:layout_width="match_parent"
   android:layout_height="match_parent"
    android:src="@drawable/bballcourt"
    android:scaleType="centerCrop"
    />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_gravity="center"
        android:orientation="vertical"
        >

        <TextView
            android:textColor="#ffffff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Home Team"
            android:layout_margin="10dp"
            android:layout_gravity="center"
            android:textSize="15dp"
            />
        <TextView
            android:textColor="#ffffff"
            android:id="@+id/homeTeamScore"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0"
            android:textSize="50dp"
            android:layout_gravity="center"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+3 Points"
            android:background="#ffbf80"
            android:layout_gravity="center"
            android:onClick="threePointerHome"
            android:layout_marginTop="20dp"
            android:textSize="20dp"
            android:padding="10dp"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+2 Points"
            android:background="#ffbf80"
            android:layout_gravity="center"
            android:onClick="twoPointerHome"
            android:layout_marginTop="20dp"
            android:textSize="20dp"
            android:padding="10dp"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Free Throw"
            android:background="#ffbf80"
            android:layout_gravity="center"
            android:onClick="freeThrowHome"
            android:layout_marginTop="20dp"
            android:textSize="17dp"
            android:padding="10dp"
            />
    </LinearLayout>

    <View
        android:layout_width="5dp"
        android:layout_height="340dp"
        android:background="#d9d9d9"
        android:layout_marginTop="40dp"

        />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_gravity="center"
        android:orientation="vertical"
        >

        <TextView
            android:textColor="#ffffff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Away Team"
            android:layout_margin="10dp"
            android:layout_gravity="center"
            android:textSize="15dp"
            />
        <TextView
            android:textColor="#ffffff"
            android:id="@+id/awayTeamScore"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0"
            android:textSize="50dp"
            android:layout_gravity="center"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+3 Points"
            android:background="#ffbf80"
            android:layout_gravity="center"
            android:onClick="threePointerAway"
            android:layout_marginTop="20dp"
            android:textSize="20dp"
            android:padding="10dp"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+2 Points"
            android:background="#ffbf80"
            android:layout_gravity="center"
            android:onClick="twoPointerAway"
            android:layout_marginTop="20dp"
            android:textSize="20dp"
            android:padding="10dp"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Free Throw"
            android:background="#ffbf80"
            android:layout_gravity="center"
            android:onClick="freeThrowAway"
            android:layout_marginTop="20dp"
            android:textSize="17dp"
            android:padding="10dp"
            />
    </LinearLayout>

</LinearLayout>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="reset"
    android:textAllCaps="true"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    android:padding="15dp"
    android:layout_marginBottom="40dp"
    android:textSize="20dp"
    android:background="#ffbf80"
    android:onClick="reset"

    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Lineups"
    android:textAllCaps="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:padding="15dp"
    android:layout_margin="10dp"
    android:textSize="20dp"
    android:background="#ff8000"
    android:onClick="lineupsView" />

</RelativeLayout>
//////////End Of Scorekeeping View/////////////////////////////////

//////////Beginning of Lineups view/////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/bballcourt"
    android:scaleType="centerCrop"
    />

 <TextView
    android:id="@+id/lineups"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#ffffff"
    android:text="Lineups"
    android:textSize="30dp"
    android:padding="30dp"
    />

 <EditText
    android:textColor="#ffffff"
    android:id="@+id/one"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textNoSuggestions"
    android:maxLines="1"
    android:layout_below="@id/lineups"
    />
 <EditText
    android:textColor="#ffffff"
    android:id="@+id/two"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textNoSuggestions"
    android:maxLines="1"
    android:layout_below="@id/one"
    />
 <EditText
    android:textColor="#ffffff"
    android:id="@+id/three"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textNoSuggestions"
    android:maxLines="1"
    android:layout_below="@id/two"
    />
 <EditText
    android:textColor="#ffffff"
    android:id="@+id/four"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textNoSuggestions"
    android:maxLines="1"
    android:layout_below="@id/three"
    />
 <EditText
    android:textColor="#ffffff"
    android:id="@+id/five"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textNoSuggestions"
    android:maxLines="1"
    android:layout_below="@id/four"
    />
 <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Score"
    android:textAllCaps="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentBottom="true"
    android:padding="15dp"
    android:layout_margin="10dp"
    android:textSize="20dp"
    android:background="#ff8000"
    android:onClick="mainView"
    />
</RelativeLayout>

</LinearLayout

A: Try to save the state of the instance and then restoring when the activity is shown again overriding this two methods:
public void onSaveInstanceState(Bundle savedInstanceState) {}
public void onRestoreInstanceState(Bundle savedInstanceState) {}

So when activity is resumed, you can restore all data kept in the corresponding bundle.
For instance:
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

Then, you can override OnCreate or onRestoreInstanceState to get the old state:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);

    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}


text:
Q: Reducing shapefile size from PostgreSQL using ogr2ogr I have a PostGIS database created from an old AutoCAD system. Because of this, every column is type varchar(254), even though actual data lengths are small. I need to export tables as shapefiles, and would like to minimize the extra space created in the shapefile due to the large column fields, in order to reduce the overall size of the .dbf file. Is there any way to reduce the size of fields when utilizing ogr2ogr to convert PostgreSQL data to Esri shapefiles?

A: You can shrink the shapefile that ogr2ogr has created. Read https://gdal.org/drivers/vector/shapefile.html#field-sizes

It is also possible to force a resize of the fields to the optimal
width by issuing a SQL 'RESIZE ' via the datasource
ExecuteSQL() method. This is convenient in situations where the
default column width (80 characters for a string field) is bigger than
necessary.

Usage example with ogrinfo
ogrinfo -sql "RESIZE test" test.shp


text:
Q: Download the files that are bigger than a certain size I have Files.txt, which consists of a list of URLs of Excel files:
http://www.bcheadset.ca/applicant.xlsx
http://www.bcheadset.ca/fte.xlsx
http://www.iutox.org/TRTF_Matrix2012_Oct.xlsx
http://www.journalprices.com/2013_FinalSummaryForWeb.xlsx
http://www.camts.org/7__2013_Aircraft_Checklist.xlsx
http://www.nanotr11.org/poster_program.xlsx
http://www.vliruos.be/media/6352100/nss2015_annex_3_budget.xlsx
...

What I want to do is to download (by wget) the files that are bigger than 10Mo.
To verify if a file is bigger than 10Mo before dowloading it, we could use curl --head. For instance, curl --head http://www.bcheadset.ca/fte.xlsx returns
HTTP/1.1 200 OK
Content-Length: 3158847
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Last-Modified: Mon, 27 Jul 2015 22:16:45 GMT
Accept-Ranges: bytes
ETag: "ffb49fecb9c8d01:c05"
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Date: Tue, 06 Oct 2015 15:14:27 GMT

And from Content-Length, we can verify that it is bigger than 10Mo.
My question is how to automate this by a piece of Bash or Perl. Especially I don't know how to extract the Content-Length and does a comparison...
Could anyone help?

A: You can use LWP and perl and send a HEAD request, fetching response headers. Something like this:
#!/usr/bin/env perl
use strict;
use warnings;

use LWP;
use Data::Dumper;

my $request = HTTP::Request -> new ( HEAD => 'http://www.google.com' );
my $agent = LWP::UserAgent -> new;
my $response = $agent -> request ( $request );
print $response -> header ( 'Content-Length');

And then use LWP to do a GET instead of a HEAD you want that file.

A: In order to adapt to various HTTP forms and their content some type of pattern matching may be prudent. Here is a rough example of how to use glob matching in shell to accomplish this:
#!/bin/sh

BUFFER=$(curl --head http://www.bcheadset.ca/fte.xlsx )

HOLD=""

TAKENEXT=0

for i in $BUFFER
do case "$i" in
       Content-Length:)
       TAKENEXT=1
       ;;
    *) if [ "$TAKENEXT" -eq 1 ]
       then HOLD="$i"
            break
       fi
       ;;
    esac
done

printf "SIZE was:  %s\n" "$HOLD"

Here is a simpler method using grep:
SIZE=$(curl --head http://www.bcheadset.ca/fte.xlsx | grep 'Content-Length:' | awk '{print $2}')

printf "%s\n" "$SIZE"

.


text:
Q: OpenSSL installation and "openssl.so loading failed ... execution halted" I'm trying to install OpenSSL in R via
install.packages("openssl")

It's a clean install of R via brew so not sure what's wrong. Here are the last ~20 logs
> o compatibility.o diffie.o envelope.o error.o hash.o info.o keygen.o
> keys.o onload.o openssh.o password.o pem.o pkcs12.o pkcs7.o rand.o
> rsa.o signing.o ssl.o stream.o write.o
> -L/usr/local/opt/openssl@1.1/lib -L/usr/local/opt/openssl/lib -lssl -lcrypto -F/usr/local/Cellar/r/3.3.2/R.framework/.. -framework R -lintl -Wl,-framework -Wl,CoreFoundation installing to /usr/local/lib/R/3.3/site-library/openssl/libs
> ** R
> ** inst
> ** preparing package for lazy loading
> ** help
> *** installing help indices
> ** building package indices
> ** installing vignettes
> ** testing if installed package can be loaded Error in dyn.load(file, DLLpath = DLLpath, ...) :   unable to load shared object
> '/usr/local/lib/R/3.3/site-library/openssl/libs/openssl.so':
> dlopen(/usr/local/lib/R/3.3/site-library/openssl/libs/openssl.so, 6):
> Symbol not found: _DSA_get0_key   Referenced from:
> /usr/local/lib/R/3.3/site-library/openssl/libs/openssl.so   Expected
> in: flat namespace  in
> /usr/local/lib/R/3.3/site-library/openssl/libs/openssl.so Error:
> loading failed Execution halted ERROR: loading failed
> * removing '/usr/local/lib/R/3.3/site-library/openssl'
>
> The downloaded source packages are in
>   '/private/var/folders/8n/47bzk9810mq31790qbb38zg80000gn/T/Rtmpe7etrQ/downloaded_packages'
> Warning message: In install.packages("openssl") :   installation of
> package 'openssl' had non-zero exit status

A: Just lucky I guess but randomly solved it. I uninstalled openssl from brew, which may require you to do this:
brew uninstall --ignore-dependencies openssl

If you run it without the --ignore-dependencies, then it will list the packages that depend on it, if any. Then go back to R and install openssl and it works (at least for me). You can then install openssl from brew for brew packages if they stop working. I had no trouble using R with it (so far)
brew install openssl

A: I got the same error to you and after trying to uninstall and reinstall, etc. without error, I finally succeeded with changing the lib to my local lib install of using default:
/Users/username/Library/R/3.6/library

By default, R install packages into /usr/local/lib/R/3.6/site-library. Let's try with
install.packages("openssl", lib = "/Users/username/Library/R/3.6/library")

You can run .libPaths() for checking your library paths


text:
Q: Is it possible to share a custom data type between a go plugin and an application? I know that it is possible to look up for go-plugin symbols that were exported and type assert them into an interface. However, I wonder if is there a way to type assert them into a struct, for example. Is there a way to do it?
For example:
plugin.go
package main

type Person struct {
    Name string
}

var (
    P = Person{
        Name: "Emma",
    }
)

app.go
package main

import (
    "fmt"
    "plugin"
    "os"
)

func main() {
    plug, err := plugin.Open("./plugin.so")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    sym, err := plug.Lookup("P")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    var p Person
    p, ok := sym.(Person)
    if !ok {
        fmt.Println("Wrong symbol type")
        os.Exit(1)
    }

    fmt.Println(p.Name)
}

The symbol P, which is a Person, is found when plug.Lookup is called. However, I can't type-assert P into Person, I get an execution time error. In this example, "Wrong symbol type".
Is there a way to achieve this or the only way to share data between the plugin and the application is using interfaces?
Thanks.

A: Identifiers defined in the main package cannot be referred to from other packages, so an exported identifier from a plugin cannot be the same type what you have in your main app. Even if you would duplicate the Person type both in the plugin's file and in your main app, type assertion would fail because they are not the same type!
But it is possible to define the type in a separate package, and use this same package in the plugin and in the main app. And then you can type assert this type from a symbol you lookup from the plugin.
See this example:
The separate type defined in its own package:
package filter

type Filter struct {
    Name string
    Age  int
}

Plugin code:
package main

import (
    "play/filter"
)

var MyFilter = filter.Filter{
    Name: "Bob",
    Age:  21,
}

func CreateFilter() filter.Filter {
    return filter.Filter{
        Name: "Bob",
        Age:  21,
    }
}

The main app:
package main

import (
    "fmt"
    "log"
    "os"
    "play/filter"
    "plugin"
)

func main() {
    p, err := plugin.Open("plugin.so")
    if err != nil {
        log.Fatal(err)
    }
    mf, err := p.Lookup("MyFilter")
    if err != nil {
        log.Fatal(err)
    }
    f, ok := mf.(*filter.Filter)
    if !ok {
        log.Fatal("Wrong symbol type")
    }

    fmt.Printf("%+v\n", f)
}

Running the main app, the output is:
&{Name:Bob Age:21}

What you may notice is that the exported identifier in the plugin MyFilter is a variable of non-pointer type, yet we type-asserted a pointer type from the exported symbol. This is because if you lookup a variable, you will get a pointer to it, else you could not modify the value of the variable, you could only modify the copy. This is detailed in this answer: Plugin symbol as function return
This is not the case if we lookup the other symbol our plugin exports: the CreateFilter() function which returns a value of non-pointer type filter.Filter:
cf, err := p.Lookup("CreateFilter")
if err != nil {
    log.Fatal(err)
}

createFilter, ok := cf.(func() filter.Filter)
if !ok {
    log.Fatal("Wrong function type")
}
f2 := createFilter()
fmt.Printf("%+v\n", f2)

Running this code, the output will be:
{Name:Bob Age:21}

See related question: go 1.8 plugin use custom interface
Also note that if you change the filter package used commonly by the plugin and the main app, you also have to rebuild the plugin. Attempting to run the app without rebuilding the plugin will result in an error during the plugin.Open() call. For details, see How do Go plugin dependencies work?


text:
Q: How to detect inactive tables? I started working on a project whose former developer ragequited, and it left a complete mess both in the code and database. The server is using MySQL 5.5
There are a lot of tables created for backup or test purposes. For example, from all this tables, only two are really being used.

Is there any way to check which tables weren't used in the last XX hours, to be able to safely delete them? Can I set a log for that, besides from the general log, which is really big and fills the available space too quickly?
I cant trust names as in some cases, the table being used is the one that ends with _test or _bk.

A: Unfortunately, using the update_time column from INFORMATION_SCHEMA.TABLES only works for MyISAM tables. It does not work for InnoDB.
The most effective way to get the last time a table was written is to rely on the OS. You must check the timestamp of the .ibd or .MYD files within a database folder.
I wrote earlier posts about how to do this:

*

*Dec 21, 2011 : Fastest way to check if InnoDB table has changed

*Apr 04, 2013 : How to check which tables in DB (MYSQL) updated in last 1 hour / last 1 minute?

*Jun 03, 2013 : Is there a way to find the least recently used tables in a schema?

*Sep 25, 2014 : want to find out which databases are used in last 30 days or not

*Jan 16, 2015 : How can I determine which Innodb table is being written?

A: I would ensure that MySQL query logging is enabled and then duplicate the query log. In the duplicated log I would find and replace FROM [table_name] one-by-one in order to determine which tables aren't being actively used.
Good luck! Those table names do not reflect a positive path for that developer. :-( Let me know if you need to figure out how to enable query logging in MySQL and I'll find the answer for you on that as well.

A: You can use the OS level stat command.
Locate the ibd file for that particular table and run the below command
stat file_location
If the Table is being queried by SELECT, You can find the timestamp of when it was accessed with under the Access field.

A: SELECT update_time FROM information_schema.tables WHERE table_name='yourtablename'

Or if you want a list of all tables, with last accessed time in order
SELECT table_schema ,
  table_name,
  update_time as LastAccessed
FROM information_schema.tables
GROUP BY table_schema
ORDER BY update_time ASC

For tables weren't used in the last XX hours add WHERE clause
WHERE update_time < 'yyyy-mm-dd'