Codename One - Start editing in the search bar programmatically

Question: I need to start editing in the search bar programmatically when the Form is shown. Because I didn't find any API for that, I wrote this code inside the Form:
 addShowListener(l -> {
        for (int i = 0; i <= getToolbar().getComponentCount(); i++) {
            if (getToolbar().getComponentAt(i) instanceof Button) {
                Button btn = (Button) getToolbar().getComponentAt(i);
                if (btn.getUIID().equals("TitleCommand")) {
                    btn.pressed();
                    btn.released();
                }
                if (btn.getUIID().equals("BackCommand")) {

                    btn.addActionListener(ev -> {
                        backForm.showBack();
                    });
                }
            }
        }

    });

The problems of this code:

it relies on the current implementation of the method Form.getToolbar().addSearchCommand, that created in the toolbar a button with UIID TitleCommand (the search icon on the right) and another button with UIID BackButton (the arrow on the left).
my listener added to the back button doesn't work: instead of show the backForm, it shows the toolbar without the search bar.

So... my question is how to implement what I need with a better coding. Is it necessary to do an RFE to expose an API like Toolbar.startSearchEditingAsync()? And how can I change the default actionListener of backButton?
Answer: If you need to initiate it before it's shown you might need something more elaborate similar to Form.setEditOnShow().
This seemed a bit simpler in my head when I started it but once I started I had to finish so I implemented this here: https://github.com/codenameone/CodenameOne/commit/86fea99196dd5a453988ede8217e0809e529469a
It should work, let me know if it has issues.
Comment: Great work, thank you! I'm going to comment your commit to report a (small) issue about the back button.


Maximum number of simultaneous threads in a Winforms application

Question: I am working on a Winforms application (.NET 4.0), and I need to show 16 charts simultaneously, in 16 different threads to have a responsive UI. I am planning to use the System.Threading.Thread class directly.
Each chart requires at least 5 data-intensive SQL queries (that will be optimized in the future, but not now).
Considering all this -should I be concerned about the number of simultaneous threads? Should I implement a limit? Many thanks.
Comment: @JonB It is not the exact duplicate: the OP want the UI more reactive. Maybe changing the title would help
Comment: The UI is mono-threaded.
Comment: If you're talking numbers like 16, then you don't need to worry about this. However, you might look at Tasks and Timers before working with threads directly.
Answer: The UI has it's own thread. This mean you can't have different thread updating the UI ( and note the same apply even to a WPF gui). You can better use BackgroundWorker to call the DB in a background thread, and update the UI when finished. This is the preferred architecture.
Your application will behave as a browser which load the page then gracefully load asynchronously all the images, and you will see your chart appear dinamically, this usually make the user feel the application faster.
Having 16 Background worker just hanging from a response from a DB, even if not the best, is perfectly acceptable. using the background worker has the benefit  the thread marshalling is done automatically, just put the chart binding logic in the RunWorkerCompleted event handler, and the data retrieving logic in the DoWork event handler.
Here below a snippet:
<code>BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += (sender, e) => { //data retrieving logic here }
bgw.RunWorkerCompleted+= (sender, e) => { //bind results to chart here if no canceled nor errors }
bgw.RunWorkerAsync();//starts async execution
</code>
By doing this way, you'll implement an asynchronous UI pattern, that is really a must for any reactive application.
Addition
Just for the sake of completeness, since the "hanging agent" is the database, you can even consider Asynchronous ADO.NET calls. This is perhaps the best you can do in term of resource usage, since this will use under the hood the  I/O Completion Port mechanism to minimize the number of thread and context switches, but maybe it is a little overdesigned in your scenario. You can read further information here about ado.net and I/O completion port, look at the paragraph "True Asynchronous I/O".


A product of curves is a minimal surface

Question: Let $E$ and $B$ be smooth projective curves of genus 1 and $g$, respectively. Set $X=E \times B$. Then, the second projection $f: X \rightarrow B$ is a genus 1 fibration and $\omega_X \cong f^* \omega_B$.
How does one see that $X$ is a minimal surface and that $X$ is of type (A), (B), or (C), if $g(B)=0$, $1$ , or $\geq 2$, respectively.
Where the following are the types:
(A) $K_X$ is not nef.
(B) $K_X \equiv 0$.
(C) $K_X$ is nef, $K_X \not \equiv 0$ and $K_X^2=0$.
Comment: First step is to find the canonical sheaf of the product. Also, what definition of minimal surface are you working with e.g. it is minimal if there exists no $(-1)$-curves?
Comment: Yes, this is my definition. I also know that the canonical sheaf of the product is the tensor product of the pull back of the canonical sheaf on each factor, but I am unsure as to how to use this, especially to see minimality
Answer: Here's an answer. Hopefully there are no silly mistakes as written. Note that $K_X\cong \pi_1^*O_E\otimes \pi_2^*K_B\cong \pi_2^*K_B$ where $\pi_i$ are the two projections from $E\times B$.
(A) In this case, $K_B\cong \pi_2^* O_{\mathbb{P}^1}(-2)$. Take the canonical divisor $K_X$, observe it has negative degree along any fibre of the map $\pi_1:X\to E$, and so cannot be nef.
(B) Since $K_B\cong O_B$ due to $B$ being an elliptic curve, the canonical divisor $K_X$ is trivial so it is certainly nef. Alternatively, $X$ is an abelian surface and canonical bundles on abelian varieties are always trivial.
(C) This is trickier $K_X\cong \pi_2^*K_B$ requires we use the higher genus assumption in a particular way: $\pi_2^*K_B$ is an effective divisor. The reason is that $K_B$ itself is an effective divisor: by Riemann-Roch $H^0(B,K_B)-1=2g(B)-2+1-g(B)=g(B)-1$ so that $H^0(B,K_B)\neq 0$. Then, the pullback of an effective divisor under $E\times B\to B$ is effective. Furthermore, it cannot be numerically trivial. By effectiveness of $K_X$, if $K_X^2\geq 0$, then $K_X$ is nef.
So we show $K_X^2\geq 0$ and $K_X\not\equiv 0$. The first fact follows from a standard result: Hartshorne Exercise V.1.5. $K_X^2= 8(g(E)-1)(g(B)-1)=0$. So $K_X\not\equiv 0$ is all that is left.
Probably the easiest way to show that $K_X\not\equiv 0$ is to show that it intersects some curve nontrivially. Consider $\{O\}\times B\subseteq X$ and then $K_X.(\{O\}\times B)$ intersects at some point in $\{O\}\times B$.
Now to prove minimality, we need to show there are no $(-1)$-curves.
(A) is the case of $E\times \mathbb{P}^1$ which is a ruled surface over $E$. These are always minimal e.g. Hartshorne V.2 computes $\operatorname{Num}(X)=\mathbb{Z}C_0\oplus\mathbb{Z}f$ where $C_0$ is a section $\mathbb{P}^1\to X$ and $f$ is the numerical class of the fibre and $C_0.f=1$, $f^2=0$, and $C_0^2=0$. The fact that $C_0^2=0$ comes from the fact that $E\times \mathbb{P}^1$ is the $\mathbb{P}^1$-bundle associated to the rank $2$-vector bundle $O_E\oplus O_E$.
(B) and (C) here I will cheat a little and use the following fact: if the canonical bundle is nef, then there are no $(-1)$-curves.  One way to see this is that if $C$ is a $(-1)$-curve, then applying the adjunction formula to $C$ implies $2g(C)-2=C.(C+K)$ and since $g(C)=0$ we get $-2=C.(C+K)$ and so $C.K=-1$. Since $K_X$ is nef due to $K_X$ being trivial, this cannot be and there are no $(-1)$-curves. This also proves (c) is minimal.
Comment: in case (C), wouldn't the fact $K_X$ is effective and contained in fibers be enough to show that it is nef and that $K_X^2 = 0$
Comment: Isn't (A) the case of $\mathbb{P}^1 \times E^1$? where $E^1$ is an elliptic curve... so i'm not quite sure how to show that this is a minimal surface.
Comment: @PaulImmanuel Oops, I had the typo in case $A$. Let me fix this. Also for (c), I think the self-intersection of the fibre being $0$ is enough too. Didn't think to write it that way.


Introduction to the study of logics

Question: Rather than study FOL and it's properties, I'm looking for some references to study the relationships between logics, the associated ideas with these relationships, and properties of categories of logics. For example, the idea of modality is a property of some logics, or the idea of certain logics being extensions of other logics.
Essentially, rather than study a logic and the structures associated with it, I'm looking for a reference where the structures being studied are different logics. Is there any such reference?
Comment: [This old answer of mine](https://math.stackexchange.com/a/2525310/28111) may be of interest.
Answer: Great question!
For good or ill (I'd argue for good) there is no single formal definition of "logic" which is universally accepted, and as such there isn't really a unified "study of logics." However, there are various areas where one particular notion shines. Below I'll describe a few of these.
Before I do that, though, here's my concrete reading advice. I tend to think of three "strands" here - pure semantics-first, pure syntax-first, and applied (especially to theoretical computer science) - which while not unrelated do have fundamentally different aesthetics. I think the first step you should do is read a bit about each, to get a sense of what you're interested in:

For a taste of the semantics-first approach, look at the end of Ebbinghaus-Flum-Thomas where they treat Lindstrom's theorem, or at the first two chapters of Model-theoretic logics which outline the nature of the subject and treat Lindstrom's theorem more seriously.
For a taste of the syntax-first approach, look at Blok/Pigozzi's book or the introduction to Czelakowski's subsequent book.
For a taste of how the idea of "general logics" can be applied in CS, I think this paper of Halpern et al is a quite good introduction, but I'm not nearly competent enough in this area to be confident that it's the right choice - hopefully someone will mention a better one.

If you have a decent background in classical first-order logic and in abstract algebra, this should give you a good sense of where your own aesthetics lie at the moment.

Now in a bit more detail:

Abstract model theory. Largely holding the semantics unchanged (we're still looking at the same structures as first-order logic), abstract model theory focuses mostly on strengthenings of first-order logic. In the AMT context a logic $\mathcal{L}$ is thought of purely semantically: ignoring set/class issues for the moment, $\mathcal{L}$ consists of a map $Sent$ sending each language $\Sigma$ to the collection of $\Sigma$-sentences in the sense of $\mathcal{L}$ and a relation $\models$ between $\Sigma$-structures and $\Sigma$-sentences. The pairs we're interested in - called regular logics - are those satisfying some nice properties. Most of these are extremely basic, like "Every $\Sigma$-sentence should be a $\Sigma'$-sentence when $\Sigma\subseteq\Sigma'$" and "For every $\Sigma$-sentence $\varphi$ there should be a $\Sigma$-sentence $\psi$ which is true in exactly those structures not satisfying $\varphi$;" there is one more subtle requirement (relativization) which is less obvious at first, but playing around with the notion will quickly convince you of its importance. The end of Ebbinghaus/Flum/Thomas discusses regular logics, and in particular Lindstrom's theorem (= there is no strengthening of first-order logic which retains the Lowenheim-Skolem and compactness properties). After reading that, the collection Model-theoretic logics is all about abstract model theory and covers a gigantic range of material.

A confession is due here. Abstract model theory largely lost steam a couple decades ago; I'm not a historian, but I'll tentatively claim that a big part of this was an initial over-selling of the promise of the subject coupled with just how hard it turned out to be. This isn't totally negative, though: the reason for that optimism was the profound success of one particular extension of first-order logic, namely the simplest infinitary logic $\mathcal{L}_{\omega_1,\omega}$, in many different areas. So while you've stated an interest in the general side, it's also worth mentioning that the particular case of infinitary logic is well worth your time; see the discussion here for some sources.

Algebraic logic. Here, as the name suggests a logic is thought of primarily as an algebraic entity. Specifically, in contrast to abstract model theory, in algebraic logic any semantics is secondary and the main object of study is the internal deductive structure of logics. As such, logics are initially thought of as simply deduction relations on sets of sentences. There is a gigantic amount of material here. Both seriously and for funsies I'll recommend Humberstone's book The Connectives, which is $\sim$$1500$ pages long and doubles as submarine ballast; more feasibly, Halmos' expository article is quite good despite being old.

Going more specific: one major question which emerges at this point (maybe the first?) is "When does a logic admit an algebraic semantics?" with the motivating examples being Boolean algebras for classical propositional logic, Heyting algebras for intuitionistic propositional logic, and cylindrical algebras for classical first-order logic; this question leads to a number of dividing lines amongst logics. I strongly recommend Blok/Pigozzi's monograph, and the introduction to the subsequent book by Czelakowski is also a great read.

Fragments of first-order logic. More generality isn't always a good thing. Focusing specifically on fragments of first-order logic, or logics equivalent to such in some sense, yields a rich and valuable theory as well. For example, there is a tight connection between modal logic and intuitionistic logic, which is explored in great detail in Chagrov/Zakharyaschev. Even weaker fragments are treated throughout computer science, where I'm even less qualified to recommend texts; however, this article of van Bentham/ten Cate/Vaanaanen is a good read if you already know about Lindstrom's theorem.

And for that matter, there's also a spiritual connection between CS and abstract model theory, as logics stronger than first-order logic restricted to finite structures play a significant role in complexity theory via descriptive complexity theory. In some sense that's far from the study of fragments, but they have interestingly overlapping areas of application; I'm not remotely competent to speak on their relationship but I suspect they have nontrivial overlap.

Introduction to the study of logics


Make cluster ignore CPU requests?

Question: I have a single-node cluster where I would like to ignore any requests for CPU. I am aware that it's usually not the way to go about handling resources but it's necessary in this case. An alternative would be to override any CPU request to a specific value.
How can be this accomplished?
Answer: Use a mutating webhook admission controller. Here is configuration for Gatekeeper that rewrites the resource requests on pods to a small amount of CPU and memory. This works even for pods created by deployments, or by OpenShift operators.
apiVersion: operator.gatekeeper.sh/v1alpha1
kind: Gatekeeper
metadata:
  name: gatekeeper
spec:
  mutatingWebhook: Enabled
  validatingWebhook: Disabled

apiVersion: mutations.gatekeeper.sh/v1
kind: Assign
metadata:
  name: relieve-resource-pressure
spec:
  applyTo:
  - groups: [""]
    kinds: ["Pod"]
    versions: ["v1"]
  match:
    scope: Namespaced
    kinds:
      - apiGroups: [ "*" ]
        kinds: [ "Pod" ]
  location: "spec.containers[name:*].resources.requests"
  parameters:
    assign:
      value:
        cpu: "1m"
        memory: "1Mi"

See Gatekeeper docs at https://open-policy-agent.github.io/gatekeeper/website/docs/mutation/

Make cluster ignore CPU requests?


Dominated convergence theorem and fundamental lemma

Question: this is a proof of the fundamental lemma of calculus of variation.
Some preparations:
Let $g(x):=e^{\frac{-1}{1-||x||}} \chi_{||x||<1},$ with characteristic function $\chi,$ then $$c:= \int_{\mathbb{R}^n}g(||x||^2)dx$$ and $\delta_k(x):=\frac{k^n}{c} g(||kx||^2)$ with $||\delta_k||_{L^1} = 1$ and $supp(\delta_k) = B_{[0,\frac{1}{k}]}(0).$
So we have that $f \in L^1$ has the property that $\delta_k * f \rightarrow f$ in $L^1$. This is basically how you show that $C^{\infty}$ is dense in $L^1.$
The fundamental lemma of the calculus of variation says now that if for $f \in L^1_{loc}(\Omega)$ we have $\int_{\Omega} f\phi dx = 0$ for all testfunctions $\phi$, then we already get $f=0.$
First I assume that $\Omega$ is bounded, because the general case is an easy consequence of this. Now define $\Omega_{\delta}:=\{x \in \Omega: d(x,\partial \Omega) \ge \delta\}$ and $f_m:= f|_{\Omega_m}.$
Now, $f_m * \delta_k \in C_c^{\infty}(\Omega)$ for $k$ large enough and $f_m * \delta_k \rightarrow f_m$ in the $L^1$ sense.
At this point, I know that $0 = \int_{\Omega} f(\delta_k * f_m)$ by the assumption of the fundamental lemma.
I definitely get a subsequence $(\delta_{k_j} * f_m)$ that converges pointwise a.e. to $f_m$ and I want to apply Lebesgue's theorem to conclude
$0 = \int_{\Omega} f(\delta_{k_j} * f_m) \rightarrow \int_{\Omega_m} |f_m|^2$ which shows that $f_m = 0$ a.e. for all m , so $f=0$ a.e., but I don't see why the condition of the dominated convergence theorem is fulfilled here.
Please do not post different proofs to this Lemma, I want to understand this last piece of this one.
Comment: This isn't a homework problem, is it?
Comment: no, in a homework problem I would ask: Hey, I am too lazy to do it, please give me a proof of theorem XYZ. No honestly, I am actually interested how the dominated convergence theorem could be applied here or if there is no way out?
Comment: But the fix is easy: instead of using $\delta_{k_j} * f_m$, use $\delta_{k_j} * \operatorname{sgn}(f_m)$.  Then we get $|\delta_{k_j} * \operatorname{sgn}(f_m)| \le 1$ so the integrand is dominated by $|f|$ which is integrable over $\Omega$.  And the limit is $\int |f_m|$.
Comment: @NateEldredge thank you. well, I basically have the proof from here and they also give a reason why you can apply Lebesgue's theorem, but I don't see what they are doing there and I assume it to be wrong (see page 38 on this pdf file https://www.math.tu-berlin.de/fileadmin/i26_fg-kutyniok/Fritz/FA2_WS1415/FAII.pdf)
Comment: Yes, I believe their proof is incorrect.
Comment: this looks like a meaningful question...
Comment: The problem is with the statement $\delta_k\ast f\to f$ in $L^1$. Why does this happen?  It is not clear that you can invoke dominated convergence here.   For example, in Brezis' *Functional analysis* book he uses the fundamental lemma of variational calculus to prove this. Other proofs I know use the fact that $C_{cpt}(\mathbb{R}^n)$ is dense  in $L^1(\mathbb{R}^n)$.  Like Nate Eldredge, I believe that the proof of the fundamental lemma  you outlined is incorrect.
Answer: (I write this as an answer because it is a bit longer than a comment.)
The problem is with the statement $\delta_k\ast f\to f$ in $L^1$. Why does this happen?  You cannot invoke the dominated convergence theorem here.
For example, in Brezis' Functional analysis book this fact is proved  using fundamental lemma of variational calculus. Other proofs use the fact that $C_{cpt}(\mathbb{R}^n)$ is dense  in $L^1(\mathbb{R}^n)$. This follows from Urysohn's  theorem on the abundance of continuous function. This density factn cannot be proved using convolutions, and it is also responsible for the fundamental lemma. Like Nate Eldredge, I believe that the proof of the fundamental lemma  you outlined is incorrect.


Python regex matching multiple lines

Question: I'm trying to get the contents of a
 tag from a webpage in python. I used the following code:
matchResult = re.search(r'
(.*)
', queryResult, re.MULTILINE)
This does not work.
However if I remove the line breaks by using
queryResult = queryResult.replace('\r','').replace('\n','')
It works.
This regular expression in PHP works fine without removing line breaks:
preg_match('@
(.*)
@msU', $queryResult, $matches);
How can I match over multiple lines using Python?
Answer: Include the re.DOTALL option as well, that will allow the . character to match newlines.

Python regex matching multiple lines


Show data in listview with Asynctask

Question: I success show my data from web service JSON in listview, but I want to add Asyntask.
Where I can put code Asyntask in my code.
This my code to show data in list view
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.main);

    String status ="";
    String date = "";
    String result = "";
    String url = "http://10.0.2.2/remix/view_list.php";
    JSONParser jParser = new JSONParser();
    JSONObject json = jParser.AmbilJson(url);
    try
    {
        r_js = json.getJSONArray("view_list");

        for (int i =0; i < r_js.length(); i++)
        {
            String my_array = "";
            JSONObject ar = r_js.getJSONObject(i);
            status = ar.getString("st");
            date = ar.getString("date");
            result = ar.getString("result");

            if (status.trim().equals("er"))
            {
                my_array += "Sorry "+result;
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("result", my_array);
                myArray.add(map);
            }
            else
            {
                my_array += "Date : "+date+" "+"Result : "+result;
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("result", my_array);
                myArray.add(map);
            }

        }
    }
    catch (JSONException e)
    {
         e.printStackTrace();
    }
    adapter_listview();

}

public void adapter_listview() {

    ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
    setListAdapter(adapter);
}
}

And this JSONParser
public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject AmbilJson(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
 }

Where can I put code for Asyntask?
Ok, I get sample code, and my code now like this
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.main);

private class myProses extends AsyncTask<Void, Void, Void> {
    ProgressDialog dialog;

    protected void onPreExecute() {
        dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);

    }
protected Void doInBackground(Void... params) {

    String status ="";
    String date = "";
    String result = "";
    String url = "http://10.0.2.2/remix/view_list.php";
    JSONParser jParser = new JSONParser();
    JSONObject json = jParser.AmbilJson(url);
    try
    {
        r_js = json.getJSONArray("view_list");

        for (int i =0; i < r_js.length(); i++)
        {
            String my_array = "";
            JSONObject ar = r_js.getJSONObject(i);
            status = ar.getString("st");
            date = ar.getString("date");
            result = ar.getString("result");

            if (status.trim().equals("er"))
            {
                my_array += "Sorry "+result;
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("result", my_array);
                myArray.add(map);
            }
            else
            {
                my_array += "Date : "+date+" "+"Result : "+result;
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("result", my_array);
                myArray.add(map);
            }

        }
    }
    catch (JSONException e)
    {
         e.printStackTrace();
    }
    return null;
protected void onPostExecute(Void unused) {
        adapter_listview();
        dialog.dismiss();
    }

}

public void adapter_listview() {

    ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
    setListAdapter(adapter);
}
}

I'm get problem when server is die, it still loading.
How I can show message ex: can't connect to server?
Comment: Please do some searching first, try some concepts, and then if you hit a wall, ask for help.
Answer: Working ASyncTask tutorial,
Full ASyncTask Eclipse Project,
and here's some code that I think, when mixed with the above sample, will get you the result with the list that you desire (you'll have to adapt it to your needs a bit, though (pay attention to the list stuff, even though this is from a custom Dialog:
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Kies Facebook-account");
        builder.setNegativeButton("Cancel", this);
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View dialogLayout = inflater.inflate(R.layout.dialog, null);
        builder.setView(dialogLayout);

        final String[] items = {"Red", "Green", "Blue" };

        builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
                new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                Log.v("touched: ", items[which].toString());

            }}
            );

        return builder.create();

    }

Answer: This is my code please try this one,
MAinActivity.java
public class MyActivity extends Activity {

private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_listview);

    contests_listView = (ListView) findViewById(R.id.activity_listView);
    pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
    listActivities = new ArrayList<Object>();

    new FetchActivitesTask().execute();

}

public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {

    int i =0;
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
         pgb.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        String url = "Your URL Here";
        String strResponse = util.makeWebCall(url);

        try {
            JSONObject objResponse = new JSONObject(strResponse);

            JSONArray jsonnodes = objResponse.getJSONArray(nodes);

            for (i = 0; i < jsonnodes.length(); i++)
            {
                String str = Integer.toString(i);
                Log.i("Value of i",str);

                JSONObject jsonnode = jsonnodes.getJSONObject(i);

                JSONObject jsonnodevalue = jsonnode.getJSONObject(node);

                bean = new ActivitiesBean();

                bean.title = jsonnodevalue.getString(title);
                bean.image = jsonnodevalue.getString(field_activity_image_fid);

                listActivities.add(bean);

            }
        }
        catch (JSONException e) {

            e.printStackTrace();
      }

        return null;
    }

    @Override
    public void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        pgb.setVisibility(View.GONE);
        displayAdapter();
    }
}

public void displayAdapter()
{
    adapter = new ActivityAdapter(this, listActivities);
    contests_listView.setAdapter(adapter);
    contests_listView.setOnItemClickListener(new OnItemClickListener() {

        //@Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long id) {
            // your onclick Activity
        }

    });

}
}

util.class
public static String makeWebCall(String url) {

    DefaultHttpClient client = new DefaultHttpClient();

    HttpGet httpRequest = new HttpGet(url);
  //  HttpPost post = new HttpPost(url);

    try {

        HttpResponse httpResponse = client.execute(httpRequest);

         final int statusCode = httpResponse.getStatusLine().getStatusCode();

         if (statusCode != HttpStatus.SC_OK) {

            return null;
         }

         HttpEntity entity = httpResponse.getEntity();

         InputStream instream = null;

         if (entity != null) {
              instream = entity.getContent();
         }

            return iStream_to_String(instream);
    }
    catch (IOException e) {
        httpRequest.abort();
      // Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
    }

    return null;

 }

public static String iStream_to_String(InputStream is1) {
    BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
    String line;
    StringBuilder sb = new StringBuilder();
    try {
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String contentOfMyInputStream = sb.toString();
    return contentOfMyInputStream;
}

}

ActivityBean.java
public class ActivitiesBean implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 1L;

public String title;
public String image;

public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getImage() {
    return image;
}
public void setImage(String image) {
    this.image = image;
}

Comment: Don't provide full working code. Try to stick to segments that convey the entire idea.

Show data in listview with Asynctask


group policy in Windows Server 2008

Question: One of the employee in the Enterprise changed the users setting in group policy which effects the login permissions for Administrators users.
Each time I tried to log in locally this message shown:

You cannot log on because the logon method you are using is not allowed on this computer

All the solutions on the Internet worked inside Windows but I have only access to Command Prompt (by using repair wizard).
What should I do?
Answer: I think you're saying that someone has modified a Group Policy object deny members of the "Administrators" group the right to logon locally on some subset of the computers in the  domain. If that's not correct please clarify in your question.
If I were in this situation I'd logon to a computer with a local user account (or use a non-domain member computer) and use an LDAP browser (like ldp.exe from the Windows Support Tools) to access the Active Directory to locate the GUID for the offending Group Policy Object. If you're not familiar with querying an LDAP directory then, admittedly, it's going to be fairly difficult to guide you step-by-step. Basically, you'd be looking under the "CN=System,CN=Policies" container of the domain to find the GPO with the messed-up setting (probably by examining the "displayName" attribute of the GPOs). That will give you the GUID of the GPO.
Once you've got the GUID I'd "map" a "drive" to the SYSVOL share on a Domain Controller (DC) (using NET USE x: \\domain\sysvol /user:domain\domain-admin-username). Then, I'd browse into that "drive", the "domain.com" subfolder, the "Policies" subfolder, the folder corresponding to the GUID of the messed-up GPO, the "Machine" subfolder, the "Windows NT" subfolder, and the "SecEdit" subfolder.
In that folder you'll find a GptTmpl.inf file. Open that file in "Notepad" and locate the line starting with SeDenyInteractiveLogonRight. Delete that line and save the file.
In 5 minutes (odds are within 2.5 minutes) the DC you modified the SYSVOL on will refresh Group Policy and allow you to logon. As the change replicates to the SYSVOL of other DCs and member computers that are refreshing their Group Policy will pick up the change, too.
You could forego the search on the LDAP directory by just searching the domain SYSVOL share for GptTmpl.inf files containing the string SeDenyInteractiveLogonRight but if you have GPOs that legitimately contain that string you risk "breaking" them.
Whatever you do, be sure you take notes as to what you're changing as you do this so that you can back-off any incorrect changes you make.
Comment: thanks Evan for the fast reply

yes, its correct someone has modified a Group Policy

soory I could not apply your solution because even normal users can not login ,,, there isnot any user could login :(
Comment: You can always use a non-domain member computer to do what I describe.

group policy in Windows Server 2008


help with newbie c++ code

Question: I am learning C++ and need help with my code. I don't understand how I get compiler errors in my second function. It's almost a mirror of the first, but I don't get any errors from the first.
#include <iostream>
using namespace std;

// Function prototypes
int getLargest(int[], int);
int getSmallest(int[],int);

int main()
{
    const int ARRAY_SIZE = 10;
    int array[ARRAY_SIZE];
    int count = 0;

    cout << "Please enter 10 numbers into the array.\n\n";
    for (count; count < ARRAY_SIZE; count++)
    {
        cout << "Number " << (count +1) << ": " ;
        cin     >> array[count];
    }

    // Call function to calculate largest number.
    int largest = getLargest(array, ARRAY_SIZE);

    // Display the largest number
    cout << "The largest number is " << largest << endl;

    // Call function to calculate smallest number.
    int smallest = getSmallest(array, ARRAY_SIZE);

    // Display the smallest number.
    cout << "The smallest number is " << smallest << endl;

    return 0;
}

//**********************************************************************
// Function definition getLargest.
// This function accepts an array argument and returns the largest element.
//**********************************************************************
int getLargest(int arrays[], int size1)
{
    // Find the largest  number in the array.
    int large = arrays[0];
    for (int count = 1; count < size1; count++)
    {
        if(arrays[count] > large)
            large= arrays[count];
    }
    return large;
}

//**********************************************************************
// Function getSmallest definition.
//  This function accepts an array argument and returns the smallest element.
//**********************************************************************
int getSmallest(int arrays[], int size2)
{
    // Find the smallest number in the array.
    int small = arrays[0];
    for (count = 1; count < size2; count++)
    {
        if (arrays[count] < small)
            small = arrays[count];
    }
    return small;
}

Here are my errors:
777.cpp: In function 'int getSmallest(int*, int)':
777.cpp:62: error: overloaded function with no contextual type information
777.cpp:62: error: 'size2' cannot appear in a constant-expression
777.cpp:62: error: parse error in template argument list
777.cpp:62: error: could not convert 'count<<expression error> >' to 'bool'
777.cpp:62: error: no post-increment operator for type
777.cpp:64: error: invalid types 'int*[<unresolved overloaded function type>]' for array subscript
777.cpp:65: error: invalid types 'int*[<unresolved overloaded function type>]' for array subscript

Answer: In getSmallest()
for (count = 1; count < size2; count++)

You forgot to declare count
for (int count = 1; count < size2; count++)

Answer: Here's your problem:
for (count = 1; count < size2; count++)

in your second method. You have forgotten the int:
for (int count = 1; count < size2; count++)

Answer: I get error on count in second function and it's because you didn't define it. Use this:
for (int count = 1; count < size2; count++) // int count; instead of count
    {
        if (arrays[count] < small)
            small = arrays[count];
    }

help with newbie c++ code


Cálculo do volume de um terreno irregular

Question: O código consiste em calcular o volume de uma superfície irregular onde estou usando uma matriz 2 x 2 de tamanho máximo 1000 x 1000, que representa um retângulo, portanto a área máxima do terreno é 1.000.000 m², e devo usar uma variável y livre, que representa a altura do terreno, como o terreno é irregular o y varia, em regiões de declives e aclives do terreno.
Quero calcular o volume total do terreno, onde devo utilizar um delta incremental aplicado às coordenadas X, Y e Z. A cada passo da aplicação do delta às coordenadas, deverá ser feito um cálculo/adição do volume de um pequeno cubo de volume delta³ ao volume total do terreno, não ultrapassando as dimensões do terreno ou o cálculo ficará errado, onde aqui também para a coordenada Y, devo  calcular uma reta de interpolação entre duas alturas Y de modo a determinar o limite de cubos adicionados para o cálculo do volume, ou seja, um limite para a progressão do loop que fará a varredura sistemática da altura do terreno.
Quando um cubo transpor o limite da coordenada Y interpolada será a hora de terminar o loop que incrementa a coordenada Y.
Eu estou com dúvida em como fazer isso eu escrevi um código, abaixo segue a parte do loop, entretanto ocorre um erro e estou com dúvida de como consertar:
for(i=0; i<x; i++){ // x representa a largura do terreno
    for(j=0; j<z; j++){ // z representa a profundidade do terreno
        fscanf(y, "%.2f\t", altitude[i][j]); // Armazena os valores das coordenadas x e z na altura y ( DÚVIDA NESSA LINHA, SEMPRE QUE TENTO ARMAZENAR NA VARIÁVEL Y, OCORRE ERRO )
    }
}

for(i=0; i<x; i++){
    for(j=0; j<z; j++){
        delta = aux - altitude[i][j];
        volume = volume +(altitude[i][j]*delta);
        aux=altitude[i][j];
    }
}

printf("\n O volume do terreno é: %f\n", volume);

Comment: Qual o erro que a aparece quando você compila?
Comment: Basicamente ocorre o erro  nessa linha fscanf(y, "%.2f\t", altitude[ i ] [ j ]);  o programa não compila, e também tenho dúvida se apenas esse loop que eu escrevi já é o bastante para resolver meu problema.
Comment: É, realmente a sua pergunta não tá muito clara. Primeiramente, tá ok, o programa não compila... mas qual é a mensagem de erro do compilador? Em segundo lugar, o que vc quer fazer nessa linha do `fscanf`? Se vc só quer armazenar o valor do array na variável `y`, por que não fez simplesmente `y = altitude[i][j]`?. Sobre a questão do cálculo, você está considerando o terreno como sendo dividido em porções (as células do array) discretas, certo? Talvez se vc preparar um desenho ilustrativo de como a sua matriz representa o seu terreno isso ajude (até vc mesmo) no entendimento do problema.
Comment: `fscanf(f, "%f" ,  &( altitude[i][j] ))` ?
Answer: Não entendi bem o que você deseja fazer na linha com a instrução fscanf, mas caso esteja tentando gravar o resultado em um arquivo, o melhor seria usar a instrução fputs. Dá uma olhadinha aqui.
Mas se você apenas quer calcular o volume total do terreno, basta você somar todas as alturas que você armazenou no array. Algo assim:
// inicializa volume com 0 para acumular no loop
int volume = 0;
for(i=0; i<x; i++){
    for(j=0; j<z; j++){
      // adiciona o volume de cada área
      volume += altitude[i][j];
    }
}

No final deste loop, a variável volume terá o volume total do terreno.
Comment: Nessa linha eu quero armazenar o valor do array na variável y, que é a altura, pois a altura está variando e preciso levar em consideração ela para o cálculo do volume posteriormente.
Comment: E também preciso levar em conta o delta incremental para o cálculo do volume, esse delta incremental é análogo a uma soma de Riemann onde para calcular o valor de uma integral você divide a curva em vários retângulos.
Comment: Pelo que entendi, cada elemento do array terá a altura no ponto x,z. Se for isso, não existe a necessidade do delta, pois a soma das alturas de todos os pontos te dará o volume total. No cálculo, a divisão ao infinito é feito para calcular a área da curva (ou neste caso, o volume de uma superfície), mas a interpolação é limitada pela dimensão do array, onde cada elemento do array é uma área mínima a ser adicionada no somatório. Neste caso, como falei antes, basta somar todos os elementos do array para chegar ao volume total.
Comment: Por exemplo, se o seu terreno tiver uma dimensão de 10x10, e cada ponto tiver uma altura de 10 (estou simplificando), somando cada valor do array você chegaria a 1000, que é o volume do cubo de 10x10x10 de comprimento.


PDFBox: Remove a single field from PDF

Question: The simplest way I can describe the problem is that we to use PDFbox to remove only one field from a PDF that is sent to us from HelloSign.  (e.g. Credit Card Number)

The data in question will always be on the last page, and it will always be at the same coordinates in the page.
The data needs to be completely removed from the PDF.  We can't simply change the font to white or draw a box on top as it will still be selectable, and thus, can be copied.
Only that one field can be removed.  We still need the other fields and the signatures.
I've created a sample document and uploaded it to Dropbox. input.pdf
For the sake of this question, let's assume the field to be removed is the Street Address from the file I uploaded.  Not the City, State, Zip, Signatures, or Dates.  (In real life it will be a sensitive data field like a Credit Card Number or SSN.)

I'm putting a loooong-winded explanation of the problem and what I've tried so far in the first comment below.
Comment: "I'm putting a loooong-winded explanation of the problem and what I've tried so far in the first comment below." Please don't. All relevant information should be in your question (note the "relevant", which is kind of the opposite of the proposed "long-winded").
Comment: We have PDFs that we generate and send to customers via HelloSign for signatures and filling in data (addresses, phone, etc.).  After it is signed by everyone, we store a local copy on our servers.

We would like to start attaching a Credit Card Authorization form to the end to speed up payments.  However, for compliance reasons, we don't want the credit card number to be stored in plain text on our servers so we want to remove the 3 fields from the PDF using PDFBox.

The data/fields will always be on the last page, and will always be at the same coordinates in that page.
Comment: First, I tried to draw an image or a box over that location.  That only kind of works.  It's okay in that you can't see it on the screen or when printed, but you can still select it and copy it.

Next, I tried to search and replace the text, which I know is not trivial, but I couldn't find it anywhere.  Then I tried [RemoveAllText.java](https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/RemoveAllText.java?view=markup) from the examples directory in svn, which made me realize that that data is not stored as text.
Comment: I moved on to modifying RemoveAllText.java a bit to display all the tokens in the file and started to remove them one by one until I found a token that would remove it.  It is a "Do" token, but removing it removes ALL of the data as well as ALL of the signatures.  No bueno.

A little more investigation tells me that the object I'm working with is a org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject.  However, I can't seem to find a way to only remove the 3 fields in this object without removing all of them.
Comment: After I figured out it was a PDFormXObject, I thought I would try the [PrintFields.java](https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/PrintFields.java?view=markup) example, but the document doesn't appear to have an AcroForm.
Comment: Your PDF doesn't have any "fields", so the customer can't "fill" any data.
Comment: This is a PDF after they have filled in the fields.  In this case, the address and signatures are what was filled in.
Comment: The fields, if there were any to start with, have not merely being filled but also flattened, i.e. the field content has become regular page content and the fields as form elements have been removed. Thus, there are no PDF fields anymore, so there is no field to remove.
Comment: Concerning your attempts to remove the text: [RemoveAllText.java](https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/RemoveAllText.java?view=markup) is severely incomplete: It only looks for two of four possible text drawing instructions, and it only looks for them in the immediate page content, not in the content of used form xobjects or patterns. But text may be stored anywhere, in the page content, in form xobjects or patterns drawn on the page, in form xobjects or patterns used in form xobjects or patterns drawn on the page, ...
Comment: But editing generic such content streams is not as easy as one might imagine. And in particular, you asked us to assume *"the field to be removed is the Street Address from the file I uploaded. Not the City, State, Zip, Signatures, or Dates. (In real life it will be a sensitive data field like a Credit Card Number or SSN.)"* It is fairly easy to show how to remove the street address from your sample file. But that probably won't help you for differently added content.
Comment: (And if your sample document indeed is some representative result of that signing service, it looks very easy to repudiate.)
Comment: @mkl "It is fairly easy to show how to remove the street address from your sample file. But that probably won't help you for differently added content."

How can it easily be removed?  I can probably adjust it to what I need for CC numbers.

And why do you think it wouldn't work for other content?
Answer: The code in this answer probably appears to be somewhat generic as it first determines a map of fields in the document and then allows to delete any combination of the text fields. Please be aware, though, that it has been developed with only the single example PDF from this question. Thus, I cannot be sure if I correctly understood the way fields are marked for/by HelloSign and in particular the way HelloSign fills these fields.
This answer presents two classes, one which analyzes a HelloSign form and one which manipulates it by clearing selected fields; the latter one relies on the information gathered by the former. Both classes are built upon the PDFBox PDFTextStripper utility class.
The code has been developed for the current PDFBox development version 2.1.0-SNAPSHOT. Most likely it works with all 2.0.x versions, too.
HelloSignAnalyzer
This class analyzes the given PDDocument looking for the sequences

[$varname    ] which appear to define placeholders for placing form field contents, and
[def:$varname|type|req|signer|display|label] which appear to define properties of the placeholders.

It creates a collection of HelloSignField instances each of which describes such a placeholder. They also contain the value of the respective field if text could be found located over the placeholder.
Furthermore it stores the name of the last xobject drawn on the page which in case of the sample document is the place where HelloSign draws its field contents.
public class HelloSignAnalyzer extends PDFTextStripper
{
    public class HelloSignField
    {
        public String getName()
        { return name; }
        public String getValue()
        { return value; }
        public float getX()
        { return x; }
        public float getY()
        { return y; }
        public float getWidth()
        { return width; }
        public String getType()
        { return type; }
        public boolean isOptional()
        { return optional; }
        public String getSigner()
        { return signer; }
        public String getDisplay()
        { return display; }
        public String getLabel()
        { return label; }
        public float getLastX()
        { return lastX; }

        String name = null;
        String value = "";
        float x = 0, y = 0, width = 0;
        String type = null;
        boolean optional = false;
        String signer = null;
        String display = null;
        String label = null;

        float lastX = 0;

        @Override
        public String toString()
        {
            return String.format("[Name: '%s'; Value: `%s` Position: %s, %s; Width: %s; Type: '%s'; Optional: %s; Signer: '%s'; Display: '%s', Label: '%s']",
                    name, value, x, y, width, type, optional, signer, display, label);
        }

        void checkForValue(List<TextPosition> textPositions)
        {
            for (TextPosition textPosition : textPositions)
            {
                if (inField(textPosition))
                {
                    float textX = textPosition.getTextMatrix().getTranslateX();
                    if (textX > lastX + textPosition.getWidthOfSpace() / 2 && value.length() > 0)
                        value += " ";
                    value += textPosition.getUnicode();
                    lastX = textX + textPosition.getWidth();
                }
            }
        }

        boolean inField(TextPosition textPosition)
        {
            float yPos = textPosition.getTextMatrix().getTranslateY();
            float xPos = textPosition.getTextMatrix().getTranslateX();

            return inField(xPos, yPos);
        }

        boolean inField(float xPos, float yPos)
        {
            if (yPos < y - 3 || yPos > y + 3)
                return false;

            if (xPos < x - 1 || xPos > x + width + 1)
                return false;

            return true;
        }
    }

    public HelloSignAnalyzer(PDDocument pdDocument) throws IOException
    {
        super();
        this.pdDocument = pdDocument;
    }

    public Map<String, HelloSignField> analyze() throws IOException
    {
        if (!analyzed)
        {
            fields = new HashMap<>();

            setStartPage(pdDocument.getNumberOfPages());
            getText(pdDocument);

            analyzed = true;
        }
        return Collections.unmodifiableMap(fields);
    }

    public String getLastFormName()
    {
        return lastFormName;
    }

    //
    // PDFTextStripper overrides
    //
    @Override
    protected void writeString(String text, List<TextPosition> textPositions) throws IOException
    {
        {
            for (HelloSignField field : fields.values())
            {
                field.checkForValue(textPositions);
            }
        }

        int position = -1;
        while ((position = text.indexOf('[', position + 1)) >= 0)
        {
            int endPosition = text.indexOf(']', position);
            if (endPosition < 0)
                continue;
            if (endPosition > position + 1 && text.charAt(position + 1) == '$')
            {
                String fieldName = text.substring(position + 2, endPosition);
                int spacePosition = fieldName.indexOf(' ');
                if (spacePosition >= 0)
                    fieldName = fieldName.substring(0, spacePosition);
                HelloSignField field = getOrCreateField(fieldName);

                TextPosition start = textPositions.get(position);
                field.x = start.getTextMatrix().getTranslateX();
                field.y = start.getTextMatrix().getTranslateY();
                TextPosition end = textPositions.get(endPosition);
                field.width = end.getTextMatrix().getTranslateX() + end.getWidth() - field.x;
            }
            else if (endPosition > position + 5 && "def:$".equals(text.substring(position + 1, position + 6)))
            {
                String definition = text.substring(position + 6, endPosition);
                String[] pieces = definition.split("\\|");
                if (pieces.length == 0)
                    continue;
                HelloSignField field = getOrCreateField(pieces[0]);

                if (pieces.length > 1)
                    field.type = pieces[1];
                if (pieces.length > 2)
                    field.optional = !"req".equals(pieces[2]);
                if (pieces.length > 3)
                    field.signer = pieces[3];
                if (pieces.length > 4)
                    field.display = pieces[4];
                if (pieces.length > 5)
                    field.label = pieces[5];
            }
        }

        super.writeString(text, textPositions);
    }

    @Override
    protected void processOperator(Operator operator, List<COSBase> operands) throws IOException
    {
        String currentFormName = formName;
        if (operator != null && "Do".equals(operator.getName()) && operands != null && operands.size() > 0)
        {
            COSBase base0 = operands.get(0);
            if (base0 instanceof COSName)
            {
                formName = ((COSName)base0).getName();
                if (currentFormName == null)
                    lastFormName = formName;
            }
        }
        try
        {
            super.processOperator(operator, operands);
        }
        finally
        {
            formName = currentFormName;
        }
    }

    //
    // helper methods
    //
    HelloSignField getOrCreateField(String name)
    {
        HelloSignField field = fields.get(name);
        if (field == null)
        {
            field = new HelloSignField();
            field.name = name;
            fields.put(name, field);
        }
        return field;
    }

    //
    // inner member variables
    //
    final PDDocument pdDocument;
    boolean analyzed = false;
    Map<String, HelloSignField> fields = null;
    String formName = null;
    String lastFormName = null;
}

(HelloSignAnalyzer.java)
Usage
One can apply the HelloSignAnalyzer to a document as follows:
PDDocument pdDocument = PDDocument.load(...);

HelloSignAnalyzer helloSignAnalyzer = new HelloSignAnalyzer(pdDocument);

Map<String, HelloSignField> fields = helloSignAnalyzer.analyze();

System.out.printf("Found %s fields:\n\n", fields.size());

for (Map.Entry<String, HelloSignField> entry : fields.entrySet())
{
    System.out.printf("%s -> %s\n", entry.getKey(), entry.getValue());
}

System.out.printf("\nLast form name: %s\n", helloSignAnalyzer.getLastFormName());

(PlayWithHelloSign.java test method testAnalyzeInput)
In case of the OP's sample document the output is

Found 8 fields:

var1001 -> [Name: 'var1001'; Value: `123 Main St.` Position: 90.0, 580.0; Width: 165.53601; Type: 'text'; Optional: false; Signer: 'signer1'; Display: 'Address', Label: 'address1']
var1004 -> [Name: 'var1004'; Value: `12345` Position: 210.0, 564.0; Width: 45.53601; Type: 'text'; Optional: false; Signer: 'signer1'; Display: 'Postal Code', Label: 'zip']
var1002 -> [Name: 'var1002'; Value: `TestCity` Position: 90.0, 564.0; Width: 65.53601; Type: 'text'; Optional: false; Signer: 'signer1'; Display: 'City', Label: 'city']
var1003 -> [Name: 'var1003'; Value: `AA` Position: 161.0, 564.0; Width: 45.53601; Type: 'text'; Optional: false; Signer: 'signer1'; Display: 'State', Label: 'state']
date2 -> [Name: 'date2'; Value: `2016/12/09` Position: 397.0, 407.0; Width: 124.63202; Type: 'date'; Optional: false; Signer: 'signer2'; Display: 'null', Label: 'null']
signature1 -> [Name: 'signature1'; Value: `` Position: 88.0, 489.0; Width: 236.624; Type: 'sig'; Optional: false; Signer: 'signer1'; Display: 'null', Label: 'null']
date1 -> [Name: 'date1'; Value: `2016/12/09` Position: 397.0, 489.0; Width: 124.63202; Type: 'date'; Optional: false; Signer: 'signer1'; Display: 'null', Label: 'null']
signature2 -> [Name: 'signature2'; Value: `` Position: 88.0, 407.0; Width: 236.624; Type: 'sig'; Optional: false; Signer: 'signer2'; Display: 'null', Label: 'null']

Last form name: Xi0

HelloSignManipulator
This class makes use of the information a HelloSignAnalyzer has gathered to clear the contents of text fields given by their name.
public class HelloSignManipulator extends PDFTextStripper
{
    public HelloSignManipulator(HelloSignAnalyzer helloSignAnalyzer) throws IOException
    {
        super();
        this.helloSignAnalyzer = helloSignAnalyzer;
        addOperator(new SelectiveDrawObject());
    }

    public void clearFields(Iterable<String> fieldNames) throws IOException
    {
        try
        {
            Map<String, HelloSignField> fieldMap = helloSignAnalyzer.analyze();
            List<HelloSignField> selectedFields = new ArrayList<>();
            for (String fieldName : fieldNames)
            {
                selectedFields.add(fieldMap.get(fieldName));
            }
            fields = selectedFields;

            PDDocument pdDocument = helloSignAnalyzer.pdDocument;
            setStartPage(pdDocument.getNumberOfPages());
            getText(pdDocument);
        }
        finally
        {
            fields = null;
        }
    }

    class SelectiveDrawObject extends OperatorProcessor
    {
        @Override
        public void process(Operator operator, List<COSBase> arguments) throws IOException
        {
            if (arguments.size() < 1)
            {
                throw new MissingOperandException(operator, arguments);
            }
            COSBase base0 = arguments.get(0);
            if (!(base0 instanceof COSName))
            {
                return;
            }
            COSName name = (COSName) base0;

            if (replacement != null || !helloSignAnalyzer.getLastFormName().equals(name.getName()))
            {
                return;
            }

            if (context.getResources().isImageXObject(name))
            {
                throw new IllegalArgumentException("The form xobject to edit turned out to be an image.");
            }

            PDXObject xobject = context.getResources().getXObject(name);

            if (xobject instanceof PDTransparencyGroup)
            {
                throw new IllegalArgumentException("The form xobject to edit turned out to be a transparency group.");
            }
            else if (xobject instanceof PDFormXObject)
            {
                PDFormXObject form = (PDFormXObject) xobject;
                PDFormXObject formReplacement = new PDFormXObject(helloSignAnalyzer.pdDocument);
                formReplacement.setBBox(form.getBBox());
                formReplacement.setFormType(form.getFormType());
                formReplacement.setMatrix(form.getMatrix().createAffineTransform());
                formReplacement.setResources(form.getResources());
                OutputStream outputStream = formReplacement.getContentStream().createOutputStream(COSName.FLATE_DECODE);
                replacement = new ContentStreamWriter(outputStream);

                context.showForm(form);

                outputStream.close();
                getResources().put(name, formReplacement);
                replacement = null;
            }
        }

        @Override
        public String getName()
        {
            return "Do";
        }
    }

    //
    // PDFTextStripper overrides
    //
    @Override
    protected void processOperator(Operator operator, List<COSBase> operands) throws IOException
    {
        if (replacement != null)
        {
            boolean copy = true;
            if (TjTJ.contains(operator.getName()))
            {
                Matrix transformation = getTextMatrix().multiply(getGraphicsState().getCurrentTransformationMatrix());
                float xPos = transformation.getTranslateX();
                float yPos = transformation.getTranslateY();
                for (HelloSignField field : fields)
                {
                    if (field.inField(xPos, yPos))
                    {
                        copy = false;
                    }
                }
            }

            if (copy)
            {
                replacement.writeTokens(operands);
                replacement.writeToken(operator);
            }
        }
        super.processOperator(operator, operands);
    }

    //
    // helper methods
    //
    final HelloSignAnalyzer helloSignAnalyzer;
    final Collection<String> TjTJ = Arrays.asList("Tj", "TJ");
    Iterable<HelloSignField> fields;
    ContentStreamWriter replacement = null;
}

(HelloSignManipulator.java)
Usage: Clear single field
One can apply the HelloSignManipulator to a document as follows to clear a single field:
PDDocument pdDocument = PDDocument.load(...);

HelloSignAnalyzer helloSignAnalyzer = new HelloSignAnalyzer(pdDocument);

HelloSignManipulator helloSignManipulator = new HelloSignManipulator(helloSignAnalyzer);

helloSignManipulator.clearFields(Collections.singleton("var1001"));

pdDocument.save(...);

(PlayWithHelloSign.java test method testClearAddress1Input)
Usage: Clear multiple fields at once
One can apply the HelloSignManipulator to a document as follows to clear multiple fields at once:
PDDocument pdDocument = PDDocument.load(...);

HelloSignAnalyzer helloSignAnalyzer = new HelloSignAnalyzer(pdDocument);

HelloSignManipulator helloSignManipulator = new HelloSignManipulator(helloSignAnalyzer);

helloSignManipulator.clearFields(Arrays.asList("var1004", "var1003", "date2"));

pdDocument.save(...);

(PlayWithHelloSign.java test method testClearZipStateDate2Input)
Usage: Clear multiple fields successively
One can apply the HelloSignManipulator to a document as follows to clear multiple fields successively:
PDDocument pdDocument = PDDocument.load(...);

HelloSignAnalyzer helloSignAnalyzer = new HelloSignAnalyzer(pdDocument);

HelloSignManipulator helloSignManipulator = new HelloSignManipulator(helloSignAnalyzer);

helloSignManipulator.clearFields(Collections.singleton("var1004"));
helloSignManipulator.clearFields(Collections.singleton("var1003"));
helloSignManipulator.clearFields(Collections.singleton("date2"));

pdDocument.save(...);

(PlayWithHelloSign.java test method testClearZipStateDate2SuccessivelyInput)
Caveat
These classes are mere proofs-of-concept. On one hand they are built based on a single example HelloSign file, so there is a huge chance of having missed important details. On the other hand there are some built-in assumptions, e.g. in the HelloSignField method inField.
Furthermore, manipulating signed HelloSign files in general might be a bad idea. If I understood their concept correctly, they store a hash of each signed document to allow verification of the content, and if the document is manipulated as shown above, the hash value won't match anymore.

PDFBox: Remove a single field from PDF


How do I get the relevant string match that is associated for a given string?

Question: For the output below from Data1, I want to create a regular expression that can help me identify that POOLNAME2 is associated to KNOWNSERVER2. POOLNAME1 is not associated to KNOWNSERVER2. POOLNAME1 is associated to KNOWNSERVER1.
ltm pool POOLNAME1 {
    load-balancing-mode least-connections-member
    members {
        KNOWNSERVER1
ltm pool POOLNAME2 {
    load-balancing-mode least-connections-member
    members {
        KNOWNSERVER2

This regex works:
match = re.findall( r'ltm pool POOLNAME2.*KNOWNSERVER', data1, re.DOTALL )

But this regex doesn't work the way I want it to (which is that it should provide me the same result as the previous one):
match = re.findall( r'ltm pool .*KNOWNSERVER', data1, re.DOTALL )

Instead, it would give me the entire string below...

ltm pool POOLNAME1 {
      load-balancing-mode least-connections-member
      members {
          KNOWNSERVER1 ltm pool POOLNAME2 {
      load-balancing-mode least-connections-member
      members {
          KNOWNSERVER2

The match that is relevant is POOLNAME2 and not POOLNAME1.
Comment: Don't fix in comments - fix in question body. And, please, format you code/data properly - it hurts my eyes just to look at your post.
Comment: Correction: match = re.findall( r'ltm pool POOLNAME2.*KNOWNSERVER2', data1, re.DOTALL )
Comment: Correction: match = re.findall( r'ltm pool .*KNOWNSERVER2', data1, re.DOTALL )
Answer: I am not sure I understand the question ? what I understand your question to be is, you have a defined virtual IP address,
and two pools with names POOLNAME1 and POOLNAME2, with the least load balancing algorithm used.
I am predicting that, you have multiple servers that are grouped into servicing different requests. What I recommend is
you put the first group of servers in a pool and give them a name eg: POOLNAME1, and the second group of servers will be put
in a second pool with POOLNAME2.
=== > To answer what I think is the main core of this question, I suggest you use an i-Rule and associate the i-Rule with the
 virtual server associated With the use of these two pools, the i-Rule will provide the logic required to select the appropriate pool
and the flexibility to incorporate much more. I gave you two sample examples of i-Rules. Below is an
explanation of what the i-Rules do.
i-Rule-1:
when HTTP_REQUEST {
   set URI [string tolower [HTTP::uri]]
   if { $URI starts_with "/<uri-name"}{
      pool <POOL_NAME>
   } else {reject}
}

This i-Rule satifies an http request and will send the request to a particular poolname if the URI which is part of the request string consists of
the defined name. In this case the name in the script is generic (uri-name).
So let say you access the url   http://pptesting.kno.agc.com/chico
in the request above  (uri-name) will replace "chico", so the i-Rule will send the request to the servers in the pool with pool
name POOLNAME1 (POOL_NAME in the script) and reject any more request after that. I am assuming this is the logic in your question.
The second i-Rule below adds a bit more to the logic flow.
i-Rule-2:
when HTTP_REQUEST {
  if {([ string tolower [HTTP::uri]] starts_with "/<uri>" ) } { pool POOLNAME1 }
     else { pool POOLNAME2 }

This i-Rule satifies an http request and will send the request to a primary pool with name POOLNAME1 and if this pool is not available it will send the request to
POOLNAME2. The pools are only reference only if the "uri" starts with a defined string. In this case the "uri" will be similar to "chico" in the example above
I hope I was able to answer your questions, let me know if you intended to relay an different reasoning.


Which of the following is sufficient for $\lim_{n\to\infty} \frac{a_n}{b_n} = 1$

Question:
Assume both $a_n$ and $b_n$ are convergent. Which of the following is sufficient for $\lim_{n\to\infty} \frac{a_n}{b_n} = 1$
I. $\lim a_n = \lim b_n$
II. $\lim \frac{a_n ^2}{b_n^2} = 1$
III. $\lim \frac{b_n}{a_n} = 1$
IV. $\lim |\frac{a_n}{b_n}| = 1$
V. $|a_n - \frac{a_n}{n}| \le |b_n| \le |a_n|$

I know that I and IV are wrong since I have found counterexamples. V is wrong as well.
I am not sure about $II$ and $III$. I am tempted to say that $III$ is true because we can do something like $\frac{a_n}{b_n} = \frac{1}{\frac{b_n}{a_n}}$. But I couldn't come up with a counterexample for $II$.
Comment: What's your counterexample for IV?
Comment: @paf $a_n = -n$ and $b_n = \frac{1}{n+1}$.
Comment: @paf For example if $b_n=1$ and $a_n=-1$
Comment: @ZacharySelk Oh...snap, alternating one. Forgot that.
Comment: Yes, I didn't see that we wanted to know if IV is sufficient for having $a_n/b_n\to 1$ (I thought about the converse).
Answer: For II: $a_n=-1$, $b_n=1$ gives a counterexample.
Answer: If $a_n=-1$ and $b_n=1$ for all $n$ then both sequences are convergent and
$$\lim\frac{a_n^2}{b_n^2}=1$$
but
$$\lim\frac{a_n}{b_n}=-1$$
The condition III is good, for the reason you said.


Is there a significant difference between a 16x18 and a 16x19 tennis racket string pattern on performance?

Question: A difference of one string, yet the 16x19 seems significantly more popular than the 16x18. Is there a significant difference between these rackets performance-wise?
Comment: how do you implied 16x19 is more popular than 16x18, since most of the article talks about open string pattern (16×18) and a closed string pattern (18×20) not 16x19.
Answer: Rackets with more vertical and horizontal strings – e.g. 18 x 20 – are described as having a "dense or closed" pattern, while rackets with less vertical and horizontal strings – e.g. 16 x 18, 16 x 19 – are considered to have an "open" pattern. All these string patterns are most common. As per your question, 16 x 18 and 16 x 19 can be considered as open pattern one and has a difference of one string only.
How open pattern affect on-court performance:Source

Power: Fewer strings result in more power
Spin: Fewer strings create larger "squares," grip the ball more, and result in more spin
Feel and Comfort: Open patterns absorb shock better and are more comfortable
String Tension: Lower string tension will result in more power for all string patterns

An article from Tennis Warehouse University has done a research on Spin and String Pattern few important parts summary related with this question are:
Even if the two rackets are of same pattern in our case open pattern, tension also plays part in producing spin. Following two figures obtained from the website shows the spin ratio for open pattern with high and low string tension.(For pattern 16 x 18)

The pictures are obtained from the web and copyright belong to the author of the content and posted here for educational purpose only.

Summarizing, open pattern generates more spin than the closed pattern but even for the same pattern spin produce will differ because of tension of strings. Considering both 16 x 18 and 16 x 19 have same tension there will be little variation on produce spin.
At last there will not be significant difference between these two rackets performance wise considering both have same tension. It will ultimately depend on choice of a player, which one he feels comfortable with. But I couldn't find something suggesting 16 x 19 being popular than 16 x 18 pattern racket.


Laravel upon selecting from dropdown run ajax to scrape and display results?

Question: I have a dropdown with values such as:
<select style="padding-top:300px;">
            <form id="tram_stops">
                            <option onchange="tram_stops(this.value);" value="abraham-moss-tram">Abraham Moss tram stop</option>
                            <option onchange="tram_stops(this.value);" value="altrincham-tram">Altrincham tram stop</option>
                            <option onchange="tram_stops(this.value);" value="anchorage-tram">Anchorage tram stop</option>

and on change call ajax:
function tram_stops(tram_value) {
    $.ajax({
        url: '/tramsearch' + tram_value,
        type: 'post',
        dataType: 'html',
        success: function(data) {

        },
        error: function(data) {

        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}

And controller:
public function tram_search($tram_value) {
        $tram_text = $tram_value;
            if ($tram_text) {
                $client = new Client();
                $crawler = $client->request('GET', 'https://beta.tfgm.com/public-transport/tram/stops/'.$tram_text);
        echo "

";
        $tfgm = $crawler->filter('table[id="departures-data"]')->each(function ($node) {
            echo $node->html()."\n";
        });
        }
    }

So what I want to achieve:
allow user to choose a tram stop. Value is a slug which is used in request('GET') in Controller. I then want to display data from that request and output it on the page.
As of this moment, when I choose an option from a dropdown, nothing happens.
Comment: You've got your select and form tags mixed up... I wouldn't suggest opening a form inside a select element :)
Comment: doesn't change the fact that the function doesn't run
Comment: Oh well, good luck
Answer: Try doing like this :
<form id="tram_stops">
    <select style="padding-top:300px;" onchange="tram_stops(this.value);" >
        <option value="abraham-moss-tram">Abraham Moss tram stop</option>
        <option value="altrincham-tram">Altrincham tram stop</option>
        <option value="anchorage-tram">Anchorage tram stop</option>
    </select>
</form>

Comment: so I do get a html response, how do I tell it to display on page?
Comment: `success: function(data) {`
`$("#displayHTML").html(data);`
`},`
success callback function of ajax. `#displayHTML` id where you want to place html.
Comment: sorry just 1 more quick question, is there anyway to repeat (refresh) results even when onchange is not ran? so let's say someone choose Anchorage tram stop and leave it on the page, is there a way to call ajax anyway? let's say after 30 sec
Comment: using `setTimeout()` you can send request periodically
Comment: where should it go? never used it before
Comment: Refer this link https://stackoverflow.com/questions/33982057/refresh-div-to-retrieve-information-from-database-without-refreshing-wholepage
Comment: it calls it every 30 seconds now, but the value is 'undefined' and not the value that I have choosen the first time?


How do I get a strict/sharp cut from Frequency A to Frequency B of a WAV audio using NWaves (or any other library)?

Question: I need to get a sharp "cut" of a WAV audio file from frequency A (500 Hz) to Frequency B (800 Hz) and put it into a new file.
This is how it is done in Adobe Audition
I tried using NWaves.Filters.Butterworth.BandPassFilter but it does not do the trick the way I want it:
BandPassFilter. Not sharp enough
        DiscreteSignal signal = waveContainer[Channels.Average];

        int samplingRate = signal.SamplingRate;

        int lowerFrequencyHz = 500;
        int upperFrequencyHz = 800;
        double lowerFrequency = (double)lowerFrequencyHz / samplingRate;
        double upperFrequency = (double)upperFrequencyHz / samplingRate;

        var tf = new NWaves.Filters.Butterworth.BandPassFilter(lowerFrequency, upperFrequency, 3).Tf;
        var filter = new NWaves.Filters.Base64.IirFilter64(tf);
        var filtered = signal.Samples.Select(s => (float)filter.Process(s));
        DiscreteSignal outSignal = new DiscreteSignal(signal.SamplingRate, filtered);

How do I achieve it using C# and possibly NWaves library making it as sharp as Adobe does it with exact selection, copy and paste?
Answer: I found out how to do it:
        DiscreteSignal signal = waveContainer[Channels.Average];

        int samplingRate = signal.SamplingRate;

        int lowerFrequencyHz = 500;
        int upperFrequencyHz = 800;
        double lowerFrequency = (double)lowerFrequencyHz / samplingRate;
        double upperFrequency = (double)upperFrequencyHz / samplingRate;

        var tf = new NWaves.Filters.Butterworth.BandPassFilter(lowerFrequency, upperFrequency, 5).Tf;
        var filter = new NWaves.Filters.Base64.IirFilter64(tf);
        var filtered = signal.Samples.Select(s => (float)filter.Process(s));
        DiscreteSignal outSignal = new DiscreteSignal(signal.SamplingRate, filtered);

        for (int i = 0; i < 5; i++) // 1 + 5 iterations makes it very clear and sharp
        {
            filtered = outSignal.Samples.Select(s => (float)filter.Process(s));
            outSignal = new DiscreteSignal(outSignal.SamplingRate, filtered);
        }

The main things are:

BANDPASS FILTER order of 5
6 iterations of filtering makes it clear and sharp


How do you find the radius with only the slant height? Please show work.

Question: The radius of the circle is 12cm, it is then made into a cone
Question:
A cone is made by joining the straight edges and securing them with tape.  Calculate the angle of inclination, to the nearest tenth of a degree, for the sides of the cone.
Answer:
Angle of inclination is 41.4 degree.
Comment: Do you know formula for area of a circle, area of a sector, circumference of a circle, lateral surface area of a cone, Pythagoras theorem and $\cos \theta$
Comment: I think you need to remove a sector from the circle before you can make a cone out of it.
Answer: We need to find the perimeter of the circle sector first:
Answer: Let $l$ denote the slant height of the cone.  Let $r$ denote the radius of the cone.  Let $\varphi$ denote the angle of the sector of the circle.  Let $\theta$ denote the angle of inclination.
Strategy:

The lateral surface area of the cone is equal to the area of the sector.  The lateral surface area of the cone is
$$L = \pi rl$$
Since the sector has radius $l$, its area is
$$A = \frac{\varphi}{360^\circ} \pi l^2$$
where $\varphi$ is measured in degrees.  Since $l$ is given, you can set $L = A$ to solve for $r$.
To determine the angle of inclination, solve the equation $$\cos\theta = \frac{r}{l}$$ for $\theta$.


Installing VisualRuby on a MAC

Question: I'm trying to understand how to install visualruby on a MAC.  I work in ubuntu, and I've developed install instructions for Ubuntu and Windows, but I don't know the corresponding instructions for the MAC:
http://visualruby.net/Download
I know that you need to install the Glade Interface Designer.  This should install the graphics toolkit, gtk2 as well.  Visualruby needs gtk2.  After that you can install visualruby:
gem install visualruby
My friend told me that it needs to be run in the X11 terminal.  I don't understand any of this.  I'd like to develop step-by-step instructions for installing it on the MAC that includes the correct version of Glade/Gtk2.  I know that visualruby requires Glade version 2.6 thru 2.8.  The latest version of Glade uses Gtk3 which isn't good.
EDIT:  Visualruby will also require "gtksourceview2" installed (perhaps via homebrew?)
Step-by-step instructions would be greatly appreciated.
Answer: I'm the friend referred to above.
I had the best success with QuartzX11.
I installed glade, gtk+ and gtksourceview via homebrew but perhaps that's not the best way.

Installing VisualRuby on a MAC


EF Core ocorre num erro ao aplicar update-database

Question: Estou a criar a tabela AspNetUSers sendo que ao aplicar update-database
Ocorre o seguinte erro

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) NULL,
      LockoutEnabled bit NOT NULL,
      AccessFailedCount int NOT N' at line 14

Estou a utilizar uma base de dados mysql
E pelo que percebi o problema ocorre nesta linha LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "AspNetUSers",
            columns: table => new
            {
                Id = table.Column<string>(nullable: false),
                UserName = table.Column<string>(nullable: true),
                NormalizedUserName = table.Column<string>(nullable: true),
                Email = table.Column<string>(nullable: true),
                NormalizedEmail = table.Column<string>(nullable: true),
                EmailConfirmed = table.Column<bool>(nullable: false),
                PasswordHash = table.Column<string>(nullable: true),
                SecurityStamp = table.Column<string>(nullable: true),
                ConcurrencyStamp = table.Column<string>(nullable: true),
                PhoneNumber = table.Column<string>(nullable: true),
                PhoneNumberConfirmed = table.Column<bool>(nullable: false),
                TwoFactorEnabled = table.Column<bool>(nullable: false),
                LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
                LockoutEnabled = table.Column<bool>(nullable: false),
                AccessFailedCount = table.Column<int>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_AspNetUSers", x => x.Id);
            });
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "AspNetUSers");
    }

Retirei o campo //LockoutEnd = table.Column<DateTimeOffset>(nullable: true), e acaba por criar as tabelas.
Mas como faço este campo ser compativer com o mysql
Answer: Ao criar a entidade, o Provider do MySQL olha para a propriedade que você passa no Type Constraints do mapeamento, como DateTimeOffSet não é um tipo Nullable<T> então o mapeamento quebra, tente trocar a linha citada para:
LockoutEnd = table.Column<DateTimeOffset?>(nullable: true)

UPDATE
Após os comentários abaixo, foi visto que o problema é do provider do MYSQL que não interpreta corretamente o tipo de dados DateTimeOffSet por ser um tipo de dados exclusivo do SQL Server, vide pergunta do SOEn. Na documentação do provider Pomelo.MySQL existe um Workarround para trabalhar com DateTimeOffset.
Basicamente existem duas alternativas para corrigir o problema:
Converter o DateTimeOffSet para DateTime UTC e armazenar os dados.

Prós:

Comparação e ordenação serão trabalhadas pelo próprio banco de dados;
Você irá armazenar apenas 8 bytes de espaço para cada informação no banco.

Contras:

O contexto do TimeOffset (SQL) poderá ser quebrado;
O contexto do Timezone (SQL) poderá ser quebrado.

Armazenar no banco uma representação em String da data e utilizar uma propriedade não mapeada com a conversão para o tipo de dados desejado.

Prós:

O contexto do TimeOffset (SQL) será preservado;
O contexto do Timezone (SQL) será preservado.

Contras:

A ordenação e comparação não será a ordenação do mecanismo do banco de dados;
O tamanho de da informação no banco de dados pode ser de até 33 bytes ("* 2016-10-10T13:49:58.2065722+00:00").

A documentação (neste link) esta mais clara e oferece material de referencia:
DateTime vs DateTimeOffSet
Armazenando DateTime e DateTimeOffset
Comment: Não corrige essa solução
Comment: https://stackoverflow.com/questions/32103607/will-does-mysql-support-datetimeoffset
Comment: Então é uma questão específica do Provider do MySQL, vou editar a resposta com um conteúdo da documentação do provider Pomelo.MySQL
Comment: criei no banco de dados directamente no mysql desta forma LockoutEnd datetime e funcionou apesar de nao saber se depois não dará problemas futuros em alguma coisa
Comment: Você seguiu a orientação que eu estava colocando na resposta, mais complementei a mesma para ficar mais clara e ajudar quem mais tiver a mesma dúvida.


Can't update the symfony CLI through scoop

Question: When I try to update symfony through this command:
scoop update symfony-cli

It says:

Scoop was updated successfully!
symfony-cli: 5.4.12 (latest version)
Latest versions for all apps are installed! For more information try 'scoop status'
Scoop is up to date.
Everything is ok!

However, when I then do symfony new, I get:

A new Symfony CLI version is available (5.4.12, currently running 5.4.2).

UPDATE: I think it's because I first installed symfony-cli with binaries. How do i uninstall binaries to use symfony through scoop OR update the binaries?
(Also, I have PHP 8.1.6.)
Answer: You can try to remove update protection and run update again.
scoop unhold symfony-cli
scoop update symfony-cli

If this doesn't work, you can reinstall it.
scoop uninstall symfony-cli
scoop install symfony-cli

Comment: After uninstalling, symfony is still installed. I think it's because I first installed symfony with binaries. (So I will update the question)


Expressão regular

Question: Tenho uma dúvida de como posso fazer uma expressão regular para remover mascaras de telefone, cpf, cnpj.
Consegui fazer para tirar ("-") do CEP
String[] cepText = edtCep.getText().toString().split("-");

ai no caso de telefone tem ()#####-#### como posso fazer para remover?
Comment: Em resumo, você quer que fique somente os números?
Comment: Sim somente os números, @Randrade
Answer: Você pode utilizar a expressão [^0-9] para obter somente os números.
Um exemplo seria esse:
    String tel = "(99) 9 9999-9999";
    String cpf = "111.111.111-11";
    String cnpj = "11.111.111/0001-11";

    System.out.println("Tel: " + tel.replaceAll("[^0-9]", ""));
    System.out.println("CPF: " + cpf.replaceAll("[^0-9]", ""));
    System.out.println("CNPJ: " + cnpj.replaceAll("[^0-9]", ""));

Veja funcionando no Ideone.
Answer: Se sua intenção é deixar a string somente com os número utilize:
    String fone = "(51)9994-5845";
    String cpf = "025.454.644-55";
    String cnpj = "02.321.351/0001-35";

    System.out.println(fone.replaceAll("[^\\d ]", ""));
    System.out.println(cpf.replaceAll("[^\\d ]", ""));
    System.out.println(cnpj.replaceAll("[^\\d ]", ""));

Com a utilização da negação e valores diferentes de dígitos numéricos (^\d), serão removidos da string todos os caracteres diferentes de números. Isso evita a necessidade de ficar adicionando restrições a hífen, parenteses, pontos, etc...

Expressão regular


Having a background color set up on a button using linear gradient

Question: I have a requirement to have  a button which on hover should display two colors on it. I was able to achieve mix up the colors  to a certain level but not able to produce the exact one.Below is my code,

.triangle:hover{
background: -webkit-linear-gradient(-45deg, red 50%,yellow 20%);
}
<button class='triangle'>
  Linear Check
</button>

Using the above I was able to produce a image like this one on below

Please let me know if this is possible and  can be achieved using linear gradient .
Thanks in advance
Comment: What's the question here? cuz I feel you already answered it?
Answer: You can do it with 2 conic gradients.

.triangle{
  padding:20px;
  border:none;
  --g:red 135deg,yellow 0; /* the coloration */
  --p:30%;/* the position */
  background:
    conic-gradient(from -180deg at 50% var(--p)             ,var(--g)) top,
    conic-gradient(from -135deg at 50% calc(100% - var(--p)),var(--g)) bottom;
  background-size:100% 51%;
  background-repeat:no-repeat;
}
<button class='triangle'>
 some content
</button>

<button class='triangle' style="--p:60%">
 some content
</button>

<button class='triangle' style="--p:20%;--g:blue 135deg,pink 0">
 some content
</button>
Comment: Is it possible to have the edges curved (red color gradient) rather than have sharp edges?
Comment: @Developer like this: https://jsfiddle.net/sh0x5zvL/ ?
Comment: "https://i.stack.imgur.com/LvAw7.jpg".This is the gradient shape I am trying to achieve.Thanks
Comment: if you could pls help me with this. Been stuck with this for a while .Also can this be achieved using the gradients.
Answer: it's better to use rgba() or hsl or HEX:
background: linear-gradient(deg or (from to),rgba(),rgba());

Comment: I tried actually using linear gradient initially but was not able to change the border of the gradient color.In my case the red color  gradient needs to have a curved edge similar to the image but need curved edges rather than sharped one
Comment: @developer if this is a new question, ask a new question ;)
Comment: just set the border property to unset;
.triangle:hover{
background: -webkit-linear-gradient(-45deg, red 50%,yellow 20%);
  border:unset;
}


python executa mas não envia nada na saída

Question: por algum motivo, esse código está rodando, aparece que executou mas não tem resultado nenhum, alguém pode me ajudar?
def tempo(horaEntrada, minutoEntrada, horaSaida, minutoSaida):

  horaEntrada = int(input("digite a hora de entrada "))
  minutoEntrada = int(input("digite o minuto da entrada "))
  horaSaida = int(input("digite a hora de saida "))
  minutoSaida = int(input("digite o minuto de saida "))

  horaTotal = (horaSaida - horaEntrada)
  minutoTotal = (minutoSaida + minutoEntrada)

  return horaTotal, minutoTotal

  if minutoTotal >= 60:
    minutoTotal = minutoTotal - 60

  print(f"o horario de permanencia foi de {horaTotal}:{minutoTotal}")

  if horaEntrada >= 24:
    print("erro, a hora digitada é inválida")

  elif minutoEntrada >= 60:
    print("erro, os minutos são inválidos")

  elif horaSaida >= 24:
    print("erro, a hora digitada é inválida")

  elif minutoSaida >= 60:
    print("erro, os minutos são inválidos")

  valorT = horaTotal * 7
  print(f"o valor total é R${valorT}")

Answer: Código Python é interpretado pela indentação. Tudo que está abaixo de return horaTotal, minutoTotal está sendo considerado como dentro da função, porém não é executado porque ao chegar no comando return, a função acaba.
Comment: agora deu certo, obrigado!
Comment: -De nada amigo!
Answer: Quando a função foi determinada fez alguns parametros como obrigatorios a serem passados, e logo quando entra na função solicita novamente isso pode acarretar a erros aleatórios também


Como retornar erros de validação de subobjetos, atributos(objetos), listas, para o spring?

Question: Hoje eu consigo validar erros de atributos da minha classe que não sejam objetos complexos (outros objetos do meu model que estão relacionados a ele), mas o que ocorre é que o "bean validation" valida os atributos desses objetos, mas, só retorna para o BindingResult os erros de validação dos atributos simples da minha classe (int, Integer, String...), os atributos complexos da minha classe (Endereco, Contato, Documentos...) que possuem outros atributos a serem validados, não estão sendo retornados pelo BindingResult no meu controller, eu sei que eles estão sendo validados corretamente, por que o Hibernate tenta persistir e gera uma exception por não atender aos requisitos da validação.

Minha classe Modelo Locador:

package model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import annotations.JSONComponent;

@Entity
public class Locador implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Digits(integer=9, message="O campo código deve ter pelo menos 3 números até 9 números !", fraction = 0)
    @Min(value=1, message="O campo código não pode ter um número menor que 1.")
    @Max(value=999999, message="O campo código pode ser um número entre 1 e 999999.")
    @NotNull(message="O campo código não pode estar vazio !")
    private Long codigo;
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Documentos documentos;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Endereco> enderecos;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Contato> contatos;
// outros atributos e omitidos...

Minha classe Modelo Endereco:

package model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;

@Entity
public class Endereco implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;

        private String logradouro;

        @NotNull(message="O campo número não pode estar vazio !")
        private Integer numero;

//Outros atributos omitidos...

Fiz um teste no meu controlador e percorri todos os erros de
  validação, mas só aparece os erros de validação dos atributos
  "simples" da minha classe :

   @PostMapping
        public ModelAndView cadastrarLocador(@Valid Locador locador, BindingResult errors, RedirectAttributes redirectAtriAttributes)
                throws Exception {
//aqui varro os erros de validação mas só aparece para mim os referentes ao "código" da minha classe principal....
            if (errors.hasErrors()) {
                errors.getGlobalErrors().forEach(System.out::println);
                errors.getAllErrors().forEach(System.out::println);
                return form();
            }
    //      locadorService.salvar(locador);
            redirectAtriAttributes.addFlashAttribute("locadorCadastrado", locador.getNome());
            return new ModelAndView("redirect:/carregar/carregarLocador");
        }

        private ModelAndView form() {
            return new ModelAndView("forward:/carregar/carregarLocador");
        }

Comment: Eu consegui um comportamento parecido do que eu queria criando a minha própria validação, mas infelizmente dessa forma eu não consigo mudar a mensagem dependendo do erro de validação.
Answer: Opa, tenho uma solução simples para isso. Anote seu atributo como valid. Espero que funcione!
@Valid
private Endereco endereco


Is there a regulation grass height for football?

Question: The grass or turf of a playing field can greatly affect gameplay, as grass affects the spin of the ball, traction / drag, among other things.
In FIFA's Laws of the Game booklet, there is little specified about natural playing surfaces. The blurb only applies to artificial turf:

The colour of artificial surfaces must be green.
... the [artificial] surface must meet the requirements of the FIFA Quality Concept for Football Turf or the International Artificial Turf Standard, unless special dispensation is given by FIFA.

Are there any regulations on grass height, density etc?
Answer: Found in 2015/16 UEFA Regulations
IV - Stadium Infrastructure 29.02

For natural pitches, the height of the grass may not, in principle, exceed 30mm
  and the entire playing surface must be cut to the same height. The height of the
  cut should be the same for both the training sessions and the match. If deemed
  necessary by the referee or a UEFA match officer, the home club may be
  requested to reduce the height of the grass for the match and training sessions
Comment: Seems specific to the UEFA Champions League. Are there other regulations for FA / English leagues?
Comment: http://www.premierleague.com/content/dam/premierleague/site-content/News/publications/handbooks/premier-league-handbook-2015-16.pdf Just ctrl+f "grass" Just pick a competitionname and add rules and enter it in google


Probability involving dependent normal variables

Question: I have two independent, identically distributed normal random variables $X \sim N(0,\sigma^2)$, $Y \sim N(0,\sigma^2)$.  I want to know
$$Pr[X-Y>4\sigma \text{ and } X<3\sigma \text { and } Y<3\sigma]$$
Of course, the condition $Y<3\sigma$ seems to be redundant, since we must have $Y<-\sigma$ in order to have $3\sigma>X>4\sigma+Y$.  I also know the fact that $X-Y$ is itself a normal random variable with $X-Y \sim N(0,2\sigma^2)$.  However, $X-Y$ and $X$ are not independent, so I don't know how to separate out the "and"s in the probability condition...
Comment: The last condition seems indeed redundant. Are you sure you didn't forget some absolute values?
Answer: Let $g(x)=\frac1{\sqrt{2\pi}}\mathrm e^{-x^2/2}$, then the probability $p$ you are interested in is
$$
p=\int_{-\infty}^3g(x)\int_{-\infty}^{x-4}g(y)\mathrm dy\,\mathrm dx=\frac1{2\pi}\int_{-\infty}^3\int_{-\infty}^{x-4}\mathrm e^{-(x^2+y^2)/2}\mathrm dy\,\mathrm dx.
$$
Obviously, $\Phi(1)\Phi(3)\leqslant p\leqslant\Phi(3)$ but I see no reason why $p$ should have an analytic expression.
Comment: Thanks! Did you assume $\sigma=1$?  Also, where can I read about the function $\Phi$ (which I assume bounds the probability $p$)?
Comment: The result does not depend on the value of  sigma. // About Phi: try WP.
Comment: [Yes](http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution), as already mentioned.