VBA code not running after this one line of code (Excel)

Question: This has had me stumped for over a week now and I have spent hours of time trying to get it working. Even ChatGPT is stumped.
I have a function which basically inserts a new line at a specific point in a table based on a searched value. It is supposed to insert a blank row to move everything else down, then copy the row above and paste it into the new blank row. Essentially making a duplicate row. I will then have other code to remove certain values from some of the newly pasted in data in the new row.
However, nothing ever runs after this line:
tbl.ListRows.Add(lastRowNumber - 2).Range.Offset(1).Insert Shift:=xlShiftDown

It doesn't matter what comes after this line of code, nothing runs, msgboxes, nothing. The row inserts exactly at the correct point, the rest of the code previous to this line works as it should up to this point. The row is inserted and code stops.
Here is the functions full code:
Sub InsertNewRowAfterSearchPO()
Dim ws As Worksheet
Dim tbl As ListObject
Dim rng As Range
Dim searchValue As String
Dim lastRowNumber As Long

' Set the worksheet and table variables
Set ws = ThisWorkbook.Worksheets("POData")
Set tbl = ws.ListObjects("POTable")

' Get the search value from the user
searchValue = InputBox("Enter the value to search for:")

' Find the last matching row based on the search value
Set rng = tbl.DataBodyRange.Columns(2) ' PO Number column
Dim cell As Range
For Each cell In rng.Cells
    If cell.value = searchValue Then
        lastRowNumber = cell.Row
    End If
Next cell

If lastRowNumber = 0 Then
    MsgBox "No matching value found."
Else
    ' Display the identified row number
    MsgBox "The last row number for PO Number '" & searchValue & "' is " & lastRowNumber & "."

    ' Insert a new row after the identified row number
    tbl.ListRows.Add(lastRowNumber - 2).Range.Offset(1).Insert Shift:=xlShiftDown

    'Run extra code here after insert, yet nothing runs, event this below message box.
    MsgBox "New row inserted beneath the last row with PO Number '" & searchValue & "'."

End If
End Sub

Appreciate any ideas as to why the Insert line of code is stopping anything else running even though it inserts successfully.
By the way, if I run the macro manually and it inserts the new line I can then run a second macro to do what I need. But it has to be run one after the other. If I try to call that second function to do the extra business in the above function, it does nothing. For some reason the insert function has to run to completion and fully end, before I can do anything else. But it never ends as the message box is not even displayed.
Comment: Cannot reproduce the issue, the code continues when I test it. Do you have any event routine that are triggered (Worksheet_Change or Selection_Change) and could cause that? However, the statement is strange, it will create 2 new rows: One with the `Add`-command and one with the `Insert`-command: Is that what you want?
Comment: That is really odd. Mine creates only the one row. And I don't have any Worksheet_Change functions. Crazy, this one has me completely stumped. I do have a mountain of other code, but nothing that is triggered from any events related to this or onchange.
Comment: It *should* create two, as @FunThomas stated.
Comment: The fact mine is only create one row I guess is a clue as to something else going wrong. Like the msgbox not being displayed I suspect after the row is added the code is stopping which is why I am not seeing the second row or the msgbox. I tried @FaneDuru's suggestion below and the new row is being inserted, but again no additional code will run afterwards. If I call other functions manually afterwards, they work fine, but trying to call a function after the insert automatically does not work either. Still lost on this one.
Answer: In order to insert a row (in a table, specific position) and then copy the value above it, please, use the next way:
   'your code/declarations...
   Dim insRng As Range
   Set insRng = tbl.ListRows.Add(lastRowNumber - 2, True).Range 'second parameter is AlwaysInsert
   insRng.Value = tbl.ListRows(lastRowNumber - 3).Range.Value
   'your existing code...

Without using a declared range, in some circumstances you need to previously select the inserted row and only after that using to copy the above row content on it. Don't ask me why, because I do not know the answer. It happened to me some times and found this way, not involving the table row selection and clipboard neither...
Comment: Thanks for the helpful explanation. I have tried your suggestion and the code works for inserting the row, but it does not copy the values from above and I am still left with a blank row only. Also, it still appears the msgbox after the insert is still not being displayed. I suspect something else is glitching after the row insert, but for the life of me I cannot figure out what could cause this. I get no errors and everything else seems to run as it should.  Is there a way for force code to run or at least present an error if it is not working?
Comment: FYI: I have tried on Error resume next, on Error Goto xxx etc
I have even enabled in VBA settings, break on all errors to at least try to see what is faulting. But no errors are reported. The function just stops dead after the insert and nothing else runs in that function.
Comment: @MrK Try inserting a code line to select the newly inserted row (`insRng.Select`). Followed by `Selection.Value = tbl.ListRows(lastRowNumber - 3).Range.Value`. This behavior happened to me **only in huge workbooks keeping a lot of code**. Why is that happening? The onest answer is "I don't know"... It looks to be a bug in Excel Application. Selecting it, you 'remember' somehow to Excel about its existence, I think. :) It it still does not solve the problem, please try running the code on a new workbook having in the first sheet only such a tab. I like to believe that you will not have problems
Answer: I appreciate all the helpful comments. But I have solved the issue and gutted I didn't try this earlier. Not sure why this fixes the problem, but now the code at least runs. I suspect a bug in Excel that after the insert and with screen updating on code stops. All I did was add...
Application.ScreenUpdating = False
    'All code here for the insert
    ' Additional code for after the insert
Application.ScreenUpdating = True

That was it. This solved the issue. ♂


Are dual spaces with unconditional bases weakly sequentially complete?

Question: It is well known that a weakly sequentially complete Banach space with an unconditional basis is isomorphic to a conjugate space.
Is the converse to this statement true?

If a Banach space is a conjugate space and has an unconditional basis, must it be weakly sequentially complete?
Answer: Yes. More generally this holds for separable Banach lattices that are dual spaces (spaces with unconditional bases are Banach lattices with the positive cone consisting of vectors having non-negative coefficients with respect to a given unconditional basis).
Indeed, we have the following generalisation of a theorem of James (This is Theorem 1.4.c in the second volume of Lindenstrauss and Tzafriri):

Let $X$ be a Banach lattice. Then $X$ is weakly sequentially complete if and only if it does not contain subspaces isomorphic to $c_0$.

Now, a separable dual cannot contain subspaces isomorphic to $c_0$ as every such subspace would be complemented (Sobczyk's theorem) and this would contradict the Phillips-Sobczyk theorem. (You will find more details here.)


On average, how many times must a circular pizza be randomly cut, to get a piece with no curved edge?

Question: On a circular pizza, we make a random straight cut by choosing two uniformly random points on the perimeter and cutting through them.

On average, how many times must the pizza be randomly cut, to get a piece with no curved edge?

(In other words, on average, how many random chords must be drawn on a circle, to get a polygon, if each random chord is drawn by connecting two uniformly random points on the perimeter of the circle?)
In the following example, a piece with no curved edge is obtained by the fifth random cut.

My attempt
I made a pizza cutting simulator on desmos. It seems that the average should be around $7$ or so.
I tried to find the probability that a piece with no curved edge is obtained by the $n$th random cut. But I only worked out that the probability for $n=3$, is $\frac{1}{15}$. (Consider the six points that define three cuts. Start with one point: it must be paired with its opposite point, which has probability $\frac15$. Then one of the remaining points must be paired with its opposite point, which has probability $\frac13$. The remaining two points must be paired together. So the probability is $\frac15\times\frac13=\frac{1}{15}$.)
Comment: Is it possible to infer whether a piece without a curved edge exists based on the number of vertices, edges and faces in your pizza? (Asking because there are lots of results about e.g. number of intersections of random chord diagrams.)
Comment: Another possibility: could the existence of a center piece depend only on the combinatorial property of which of the $2n$ vertices (ordered clockwise) are paired with each other, independent of the exact locations of those vertices?
Comment: @EricSnyder, for $n=4$, it's $23/105$, if I count correctly.
Comment: @JeroenvanderMeer Likely no. The way the edges lie matter. EG With 6 vertices, if we connect 3 pairs of neighbors, there is no "center" piece. However, if we connect opposite points, then we can get a "center" piece.
Comment: @CalvinLin Yes, but those two situations do have different numbers of faces/edges/vertices though right?
Comment: @Milten Not completely. Each has $6$ vertices and $3$ edges. From those you can create five isoforms with $4, 4, 5, 6, 7$ faces each. Only in the last case do we get a center piece. So I suppose if we know the number of faces we can *possibly* infer the existence of a "center" piece, but beyond $6$ vertices it becomes much harder I suspect. However, I think OP's probabilities are on the right track; we just need to generalize to $n>3$.
Comment: @GregMartin I think that is definitely possible. I think that if any three chords all cross each other, you get a non-edge piece. And that tracks with OP's $1/15$ probability. But the question is, how to do it for $n>3$ ?
Comment: FWIW, running some sims suggests the probability of a center piece existing after $4$ (or fewer) cuts is almost certainly $\frac15$; for $n=5,6,7,8,9$ I get $37\%, 55\%, 69\%, 81\%, 89\%$ respectively. Not sure what fractions those correspond to, however.
Comment: @zhoraster You may well be correct; I realized after posting that I missed a configuration type: four chords that each cross two of the others in a cycle produces a center piece that isn't a triangle, and doesn't require three chords to all cross each other. Having that be $2/105$ chance seems completely reasonable. (Oh, it's two possibilities due to chirality. So that makes sense.)
Answer: Write the expectation as
$$
\mathbb{E}[X] = \sum_{n=0}^{\infty} \mathrm{P}(X> n).
$$
The latter probability is that for $n$ cuts, there is no "central" piece. Note that, thanks to symmetry, all possible $(2n-1)!!$ pairings of the $2n$ endpoints are equally likely. So we need to count the number of pairings such that there is no central piece. In other words, we need to count the number of chord diagrams of size $n$ such that their intersection graph has no cycles, i.e. is a forest. The latter number, according to Hüseyin Acan Forests of chord diagrams with a given number of trees, is equal to$^*$
$$
\sum_{m=1}^n \frac{1}{3n-2m}{2n \choose m-1}{3n-2m \choose n-m}.
$$
Therefore, the expectation in question is
$$
1+ \sum_{n=1}^\infty \frac{1}{(2n-1)!!}\sum_{m=1}^n \frac{1}{3n-2m}{2n \choose m-1}{3n-2m \choose n-m};
$$
I haven't found a way to simplify it even to a single series.

$^*$ Quite surprisingly, the sequence is not in the OEIS. I'm not registered there, so I would be grateful if someone submits it.
Comment: Can you edit your answer to include some numerical probabilities for individual $n$, of which $\frac1{15}$ is the first nontrivial one?
Comment: @zhoraster If I understand correctly, you are saying that if $X$ is the number of cuts made to obtain a piece with no curved edge, then $P(X>n)=\frac{1}{(2n-1)!!}\sum_{m=1}^n \frac{1}{3n-m}{2n \choose m-1}{3n-m \choose n-m}$. But this formula gives $P(X>1)=\frac12, P(X>2)=\frac23, P(X>3)=\frac45$, but I believe the correct values should be $P(X>1)=1, P(X>2)=1, P(X>3)=\frac{14}{15}$.
Comment: I agree with what @Dan commented just above; the transformation doesn't seem to have worked. Running the formula from the paper's Thm $1$ gives $14$ for $n=3$, where yours gives $12$. Similarly, I get the $23$ you noted above from the paper's formula, but $19$ from yours.
Comment: Sorry, $2$ was missing before $m$ in $3n-2m$. It's ok now.
Comment: So the expectation is approximately $6.11446944632...$. Seems reasonable.
Comment: Are you sure you've quoted the formula correctly? What you've written doesn't match Theorem 1 in the linked paper. I found this while trying to compute the probabilities of a central piece with a fixed number $n$ of cuts (which would be helpful information to add to this answer).
Comment: @GregMartin, to make the formula work both for $mn)$, we should still start with $P(X>0)$ [as shown here](https://math.stackexchange.com/q/843845/398708). I'm still getting $6.1144694...$.
Comment: @Dan Oops, you're right. I have my output misaligned. Apologies!
Comment: I wonder if the expectation has a closed form.
Comment: @Dan, not likely. Even writing it as a single sum (or integral) is quite challenging...
Comment: This sum looks like a hypergeometric series and should be able to be analyzed with some of those common techniques, like Zeilberger's Algorithm.  I am not expert but I added the tag so maybe someone else will be able to do this?


Expected LdrDoDebuggerBreak(), got NtWaitForWorkViaWorkerFactory()

Question: During a debugging workshop, one of the participants could not follow an example.
When running an executable under WinDbg 10.0.15603.137 on his Windows 10 machine, the debugger was breaking the first time at NtWaitForWorkViaWorkerFactory() instead of the initial breakpoint in LdrDoDebuggerBreak().
When trying to run the executable with g, it says that there's no debugee to run. What could the problem have been?
Here's what it looked like:

The source code of the application is trivial:
#include "stdafx.h"
#include <exception>

int _tmain(int /*argc*/, _TCHAR* /*argv*/[])
{
    throw std::exception();
}

Note: I'll hardly be able to provide additional information, since I have no more access to the customer's PC and it doesn't happen on mine.
Comment: Well, it didn't really break. It's a lie about an already exited process. I don't know what happened, but I can tell you what you should have done. Break at process creation instead of at the initial breakpoint and step/trace/go/whatever from there. I described how to do this in this answer: https://stackoverflow.com/a/42046071/306930
Comment: @conio: usually, the initial breakpoint is enough for the analysis I want to do. Interesting approach. If I have the chance to analyze the issue with your approach, I'll probably find out why it terminated before the initial breakpoint.
Comment: Well, sure. I don't suggest have it the default behavior. You're right that usually you don't need it. Process termination before the ibp is pretty much the textbook example of why you would need it. :)
Answer: It's not possible to say for sure what the problem was, but we can say what the problem could have been. Luckily that's what you asked.
I can't assign exact probabilities to this, but it's quite likely that an implicitly linked DLL failed loading. That's the major thing that happens before the initial breakpoint1.
Why did a DLL failed to load? Maybe some kind of resource problem, but - especially assuming you tried running a "fresh" machine after a restart - somewhat more likely is an extra DLL being loaded on the problematic machine. Maybe an AVRF DLL, maybe an AppInit DLL, maybe one of a hundred other ways to inject DLLs into unknowing and unwilling processes2.
As I said in my comment, the way to find out for sure would have been having WinDBG break on process creation rather than on the initial breakpoint, and start debugging from there.
The way to do this is to start NTSD/CDB with -xe cpr, setting this in WinDBG's Event Filters window (accessible through the Debug menu), or using sxe cpr and .restart in WinDBG, assuming you started the process in WinDBG (rather than attached to it), which is the best easiets and best in my opinion, but that's a matter of taste.

1 I think TLS callbacks for the main modules are also executed before the initial breakpoint, but what are the chances someone messes with the project configuration or the CRT LIBs to add a problematic TLS callback? (TLS callbacks of the implicitly linked DLLs are included in "DLL loading".)
2 But again, the more nefarious and clever tricks are less common and thus less likely.
Comment: Thanks. With this information, I compared the ModLoad events to a "typical" run that "works" and stops at the initial breakpoint. In addition to my screenshot, I see `C:\Windows\SysWOW64\MSVCR110.dll` in the list of modules. So to me, it sounds like that participant has not compiled the sources by himself and ran an executable for which he did not have the C runtime installed. Does that sound plausible?
Comment: @ThomasWeller: It's possible, though in that case I think I would expect the [MessageBox about a missing import](https://i.stack.imgur.com/85ZJM.png). I also assumed that the participant used the same machine to build and run, but maybe I shouldn't have had. :)


Orthogonal projection of a conic onto a plane

Question: It is well known that conic sections are the intersections of a plane with a cone.  Let the cone be $z^2 = x^2 + y^2$ and the plane be $z = ex + b$.  Project orthogonaly the resultant conic onto the $xy$ plane (projecting both up and down).
I conjecture that the projection of a non-degenerate conic (even a parabola or hyperbola) is an ellipse, but cannot prove this, or find a way to have Wolfram Alpha or similar display this visually.

Is my conjecture correct?
Is there a way to visualize this?
What about degenerate conics? Clearly the point obtained for $b = 0$ projects to a point.  What about other degenerate conics?
Comment: The projection onto a plane not parallel to the plane of the conic gives you a linear transformation. Whatever shape you project is compressed along one axis while its size along a perpendicular axis remains unchanged. What do you think happens to each type of conic?
Answer: All you need to do is eliminate $z$ from the system cone-plane. Specifically, you get
$$
(ex+b)^2=x^2+y^2
$$
or
$$
(e^2-1)x^2+2bex-y^2+b^2=0
$$
Therefore, the type of the resulting conic-projection depends on $e$. If $|e|>1$ you get a hyperbola, if $|e|=1$, a parabola and, if $|e|<1$, an ellipse.
This is geometrically obvious. Just observe that when $|e|=1$, your plane is parallel to one of the generators of the cone.


Do I need to put _gaq.push(['_trackEvent' ..... inside

Question: I want to push some event tracking to my google analytics account from my PHP scripts. I include an external PHP file which has the google analytics code in my header script which is included in all my site PHP files -
header.php :
<?php
include_once("analytics_script.php");
...
?>

index.php :
<?php
include("header.php");
//When i want to track an event from this script -
_gaq.push(['_trackEvent', 'Category', 'Action', 'Label']);
?>

analytics_script.php :

So in index.php will just using _gaq.push track events ok or do I need to wrap the line in javascript tags like -

thanks
Answer: Unless the included header.php files ends while there's still an open script tag (which I'd seriously recommend against) then yes you'll need to wrap that in


Using a switch with an array?

Question: So I think a switch might not be the most appropriate method of doing this, how else could I do it?
Basically I want to break the string into single letters, then pass values for each letter to a new variable. What I have so far (with most letters taken out, so you can get the gist but I don't fill the screen):
$word = $_POST["word"];
$word_value = 0;
$word_array = str_split($word);

switch ($word_array){
    case "a":
    case "t":
        $word_value++;
        break;
    case "g":
    case "d":
        $word_value +2;
        break;
 }

Thanks in advance!
Comment: Use a letter value lookup table instead.
Answer: You insert the switch inside a foreach loop where you analyze every element of the array.
$word_array is your array and $word is an element of the array.
$word = $_POST["word"];
$word_value = 0;
$word_array = str_split($word);

foreach($word_array as $letter){
    switch ($letter){
        case "a":
        case "t":
            $word_value++;
            break;
        case "g":
        case "d":
            $word_value+=2;
            break;
    }
}

Comment: Shouldn't the $word in the switch case be $word_value? Right now, you'd just be increment, or adding to the letter itself.
Answer: Try something like:
class Word{
  private $pn = 'word'; private $wv = 0;
  public function __construct($postName){
    $this->pn = $postName;
  }
  public function change_postName($postName){
    $this->pn = $postName;
  }
  public function value(){
    $wA = str_split($_POST[$this->pn]);
    foreach($wA as $w){
      switch($w){
        case 'a':
        case 't':
          $this->wv++;
          return $this->wv;
        case 'g':
        case 'd':
        $this->wv+=2;
          return $this->wv;
      }
    }
  }
}
$wrd = new Word('word'); $word_value1 = $wrd->value();

Now you can change where you get your information like:
$wrd->change_postName('other'); $word_value2 = $wrd->value();

and reset your word value to zero, like:
$nwrd = new Word('word');

Answer: Assuming that the values are constant, create a second array. This array holds the amount to increment for each letter. Now you don't need a switch statement, you simply index into the second array.
For example:
$letter_value["a"] = $letter_value["t"] = 1;
$letter_value["g"] = $letter_value["d"] = 2;

foreach ($word_array as $letter){
   $word_value += $letter_value[$letter];
}

Using a switch with an array?


How to develop a soft keyboard for Android?

Question: I would like to play around with some ideas and develop a soft keyboard for Android to replace the default one.

Is there any general information about soft keyboard development for Android out there? Any best practices or guidelines?
Can I do with my keyboard application pretty much anything I could do with a normal Android application?
Can I do HTTP connections to synchronize keyboard data with a cloud DB and other phones I have?
Can I open other windows/screens from a key press, e.g. to display a custom input interface different to a normal QWERTY one. If that doesn't work, can I use a pop-up dialog instead?
Answer: Some tips:

Read this tutorial: Creating an Input Method
clone this repo: LatinIME

About your questions:
An inputMethod is basically an Android Service, so yes, you can do HTTP and all the stuff you can do in a Service.
You can open Activities and dialogs from the InputMethod. Once again, it's just a Service.
I've been developing an IME, so ask again if you run into an issue.
Comment: the link to LatinIME repo seems to be down
Comment: Hey, I just came across this post. I was wondering how to build the LatinIME keyboard. I cloned the repo but when I try to build the java part it seems to complain about the native part, and I can't figure out how to get the ndk to build the right part. Any tips?
Comment: I have one problem regarding keyboard.I have added input method as per the steps given above, though my custom keyboard option is showing in setting option with built in keyboard, but in actual when i select my custom keyboard to replace inbuilt keyboard my app in crashing. Do you have any idea where i am going wrong?
Comment: the link to LatinIME repo seems to be down @Bruce
Comment: @Macarse I have followed up with the mentioned tutorial and I am stuck at resizing the heighnt of the keyboard . Any directions ?
Answer: Create Custom Key Board for Own EditText
Download Entire Code
In this post i Created Simple Keyboard which contains Some special keys like
( France keys ) and it's supported Capital letters and small letters and Number keys
 and some Symbols .
package sra.keyboard;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

public class Main extends Activity implements OnTouchListener, OnClickListener,
  OnFocusChangeListener {
 private EditText mEt, mEt1; // Edit Text boxes
 private Button mBSpace, mBdone, mBack, mBChange, mNum;
 private RelativeLayout mLayout, mKLayout;
 private boolean isEdit = false, isEdit1 = false;
 private String mUpper = "upper", mLower = "lower";
 private int w, mWindowWidth;
 private String sL[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
   "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
   "x", "y", "z", "ç", "à", "é", "è", "û", "î" };
 private String cL[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
   "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
   "X", "Y", "Z", "ç", "à", "é", "è", "û", "î" };
 private String nS[] = { "!", ")", "'", "#", "3", "$", "%", "&", "8", "*",
   "?", "/", "+", "-", "9", "0", "1", "4", "@", "5", "7", "(", "2",
   "\"", "6", "_", "=", "]", "[", "<", ">", "|" };
 private Button mB[] = new Button[32];

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  try {
   setContentView(R.layout.main);
   // adjusting key regarding window sizes
   setKeys();
   setFrow();
   setSrow();
   setTrow();
   setForow();
   mEt = (EditText) findViewById(R.id.xEt);
   mEt.setOnTouchListener(this);
   mEt.setOnFocusChangeListener(this);
   mEt1 = (EditText) findViewById(R.id.et1);

   mEt1.setOnTouchListener(this);
   mEt1.setOnFocusChangeListener(this);
   mEt.setOnClickListener(this);
   mEt1.setOnClickListener(this);
   mLayout = (RelativeLayout) findViewById(R.id.xK1);
   mKLayout = (RelativeLayout) findViewById(R.id.xKeyBoard);

  } catch (Exception e) {
   Log.w(getClass().getName(), e.toString());
  }

 }

 @Override
 public boolean onTouch(View v, MotionEvent event) {
  if (v == mEt) {
   hideDefaultKeyboard();
   enableKeyboard();

  }
  if (v == mEt1) {
   hideDefaultKeyboard();
   enableKeyboard();

  }
  return true;
 }

 @Override
 public void onClick(View v) {

  if (v == mBChange) {

   if (mBChange.getTag().equals(mUpper)) {
    changeSmallLetters();
    changeSmallTags();
   } else if (mBChange.getTag().equals(mLower)) {
    changeCapitalLetters();
    changeCapitalTags();
   }

  } else if (v != mBdone && v != mBack && v != mBChange && v != mNum) {
   addText(v);

  } else if (v == mBdone) {

   disableKeyboard();

  } else if (v == mBack) {
   isBack(v);
  } else if (v == mNum) {
   String nTag = (String) mNum.getTag();
   if (nTag.equals("num")) {
    changeSyNuLetters();
    changeSyNuTags();
    mBChange.setVisibility(Button.INVISIBLE);

   }
   if (nTag.equals("ABC")) {
    changeCapitalLetters();
    changeCapitalTags();
   }

  }

 }

 @Override
 public void onFocusChange(View v, boolean hasFocus) {
  if (v == mEt && hasFocus == true) {
   isEdit = true;
   isEdit1 = false;

  } else if (v == mEt1 && hasFocus == true) {
   isEdit = false;
   isEdit1 = true;

  }

 }

 private void addText(View v) {
  if (isEdit == true) {
   String b = "";
   b = (String) v.getTag();
   if (b != null) {
    // adding text in Edittext
    mEt.append(b);

   }
  }

  if (isEdit1 == true) {
   String b = "";
   b = (String) v.getTag();
   if (b != null) {
    // adding text in Edittext
    mEt1.append(b);

   }

  }

 }

 private void isBack(View v) {
  if (isEdit == true) {
   CharSequence cc = mEt.getText();
   if (cc != null && cc.length() > 0) {
    {
     mEt.setText("");
     mEt.append(cc.subSequence(0, cc.length() - 1));
    }

   }
  }

  if (isEdit1 == true) {
   CharSequence cc = mEt1.getText();
   if (cc != null && cc.length() > 0) {
    {
     mEt1.setText("");
     mEt1.append(cc.subSequence(0, cc.length() - 1));
    }
   }
  }
 }
 private void changeSmallLetters() {
  mBChange.setVisibility(Button.VISIBLE);
  for (int i = 0; i < sL.length; i++)
   mB[i].setText(sL[i]);
  mNum.setTag("12#");
 }
 private void changeSmallTags() {
  for (int i = 0; i < sL.length; i++)
   mB[i].setTag(sL[i]);
  mBChange.setTag("lower");
  mNum.setTag("num");
 }
 private void changeCapitalLetters() {
  mBChange.setVisibility(Button.VISIBLE);
  for (int i = 0; i < cL.length; i++)
   mB[i].setText(cL[i]);
  mBChange.setTag("upper");
  mNum.setText("12#");

 }

 private void changeCapitalTags() {
  for (int i = 0; i < cL.length; i++)
   mB[i].setTag(cL[i]);
  mNum.setTag("num");

 }

 private void changeSyNuLetters() {

  for (int i = 0; i < nS.length; i++)
   mB[i].setText(nS[i]);
  mNum.setText("ABC");
 }

 private void changeSyNuTags() {
  for (int i = 0; i < nS.length; i++)
   mB[i].setTag(nS[i]);
  mNum.setTag("ABC");
 }

 // enabling customized keyboard
 private void enableKeyboard() {

  mLayout.setVisibility(RelativeLayout.VISIBLE);
  mKLayout.setVisibility(RelativeLayout.VISIBLE);

 }

 // Disable customized keyboard
 private void disableKeyboard() {
  mLayout.setVisibility(RelativeLayout.INVISIBLE);
  mKLayout.setVisibility(RelativeLayout.INVISIBLE);

 }

 private void hideDefaultKeyboard() {
  getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

 }

 private void setFrow() {
  w = (mWindowWidth / 13);
  w = w - 15;
  mB[16].setWidth(w);
  mB[22].setWidth(w + 3);
  mB[4].setWidth(w);
  mB[17].setWidth(w);
  mB[19].setWidth(w);
  mB[24].setWidth(w);
  mB[20].setWidth(w);
  mB[8].setWidth(w);
  mB[14].setWidth(w);
  mB[15].setWidth(w);
  mB[16].setHeight(50);
  mB[22].setHeight(50);
  mB[4].setHeight(50);
  mB[17].setHeight(50);
  mB[19].setHeight(50);
  mB[24].setHeight(50);
  mB[20].setHeight(50);
  mB[8].setHeight(50);
  mB[14].setHeight(50);
  mB[15].setHeight(50);

 }

 private void setSrow() {
  w = (mWindowWidth / 10);
  mB[0].setWidth(w);
  mB[18].setWidth(w);
  mB[3].setWidth(w);
  mB[5].setWidth(w);
  mB[6].setWidth(w);
  mB[7].setWidth(w);
  mB[26].setWidth(w);
  mB[9].setWidth(w);
  mB[10].setWidth(w);
  mB[11].setWidth(w);
  mB[26].setWidth(w);

  mB[0].setHeight(50);
  mB[18].setHeight(50);
  mB[3].setHeight(50);
  mB[5].setHeight(50);
  mB[6].setHeight(50);
  mB[7].setHeight(50);
  mB[9].setHeight(50);
  mB[10].setHeight(50);
  mB[11].setHeight(50);
  mB[26].setHeight(50);
 }

 private void setTrow() {
  w = (mWindowWidth / 12);
  mB[25].setWidth(w);
  mB[23].setWidth(w);
  mB[2].setWidth(w);
  mB[21].setWidth(w);
  mB[1].setWidth(w);
  mB[13].setWidth(w);
  mB[12].setWidth(w);
  mB[27].setWidth(w);
  mB[28].setWidth(w);
  mBack.setWidth(w);

  mB[25].setHeight(50);
  mB[23].setHeight(50);
  mB[2].setHeight(50);
  mB[21].setHeight(50);
  mB[1].setHeight(50);
  mB[13].setHeight(50);
  mB[12].setHeight(50);
  mB[27].setHeight(50);
  mB[28].setHeight(50);
  mBack.setHeight(50);

 }

 private void setForow() {
  w = (mWindowWidth / 10);
  mBSpace.setWidth(w * 4);
  mBSpace.setHeight(50);
  mB[29].setWidth(w);
  mB[29].setHeight(50);

  mB[30].setWidth(w);
  mB[30].setHeight(50);

  mB[31].setHeight(50);
  mB[31].setWidth(w);
  mBdone.setWidth(w + (w / 1));
  mBdone.setHeight(50);

 }

 private void setKeys() {
  mWindowWidth = getWindowManager().getDefaultDisplay().getWidth(); // getting
  // window
  // height
  // getting ids from xml files
  mB[0] = (Button) findViewById(R.id.xA);
  mB[1] = (Button) findViewById(R.id.xB);
  mB[2] = (Button) findViewById(R.id.xC);
  mB[3] = (Button) findViewById(R.id.xD);
  mB[4] = (Button) findViewById(R.id.xE);
  mB[5] = (Button) findViewById(R.id.xF);
  mB[6] = (Button) findViewById(R.id.xG);
  mB[7] = (Button) findViewById(R.id.xH);
  mB[8] = (Button) findViewById(R.id.xI);
  mB[9] = (Button) findViewById(R.id.xJ);
  mB[10] = (Button) findViewById(R.id.xK);
  mB[11] = (Button) findViewById(R.id.xL);
  mB[12] = (Button) findViewById(R.id.xM);
  mB[13] = (Button) findViewById(R.id.xN);
  mB[14] = (Button) findViewById(R.id.xO);
  mB[15] = (Button) findViewById(R.id.xP);
  mB[16] = (Button) findViewById(R.id.xQ);
  mB[17] = (Button) findViewById(R.id.xR);
  mB[18] = (Button) findViewById(R.id.xS);
  mB[19] = (Button) findViewById(R.id.xT);
  mB[20] = (Button) findViewById(R.id.xU);
  mB[21] = (Button) findViewById(R.id.xV);
  mB[22] = (Button) findViewById(R.id.xW);
  mB[23] = (Button) findViewById(R.id.xX);
  mB[24] = (Button) findViewById(R.id.xY);
  mB[25] = (Button) findViewById(R.id.xZ);
  mB[26] = (Button) findViewById(R.id.xS1);
  mB[27] = (Button) findViewById(R.id.xS2);
  mB[28] = (Button) findViewById(R.id.xS3);
  mB[29] = (Button) findViewById(R.id.xS4);
  mB[30] = (Button) findViewById(R.id.xS5);
  mB[31] = (Button) findViewById(R.id.xS6);
  mBSpace = (Button) findViewById(R.id.xSpace);
  mBdone = (Button) findViewById(R.id.xDone);
  mBChange = (Button) findViewById(R.id.xChange);
  mBack = (Button) findViewById(R.id.xBack);
  mNum = (Button) findViewById(R.id.xNum);
  for (int i = 0; i < mB.length; i++)
   mB[i].setOnClickListener(this);
  mBSpace.setOnClickListener(this);
  mBdone.setOnClickListener(this);
  mBack.setOnClickListener(this);
  mBChange.setOnClickListener(this);
  mNum.setOnClickListener(this);

 }

}

Comment: i have developed custom keyboard and my code is some what same as  posted above, when i create apk it is running successfully on any android device(as it is working as user app). But problem comes when i need to add my app as system app (for that i used input method) in any device by replacing currently exist keyboard, it is showing the my keyboard name in settings, but when i select my keyboard it gives me error like "Unfortunalety, MyKey board has stopped". Anybody have any idea about this???.....
Answer: A good place to start is the sample application provided on the developer docs.

Guidelines would be to just make it as usable as possible. Take a look at the others available on the market to see what you should be aiming for
Yes, services can do most things, including internet; provided you have asked for those permissions
You can open activities and do anything you like n those if you run into a problem with doing some things in the keyboard. For example HTC's keyboard has a button to open the settings activity, and another to open a dialog to change languages.

Take a look at other IME's to see what you should be aiming for. Some (like the official one) are open source.
Answer: first of all you should define an .xml file and make keyboard UI in it:
<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="12.50%p"
android:keyHeight="7%p">

<Row>
    <Key android:codes="-5" android:keyLabel="remove"  android:keyEdgeFlags="left" />
    <Key android:codes="48"    android:keyLabel="0" />
    <Key android:codes="55006" android:keyLabel="clear" />
</Row>
<Row>
    <Key android:codes="49"    android:keyLabel="1"  android:keyEdgeFlags="left" />
    <Key android:codes="50"    android:keyLabel="2" />
    <Key android:codes="51"    android:keyLabel="3" />
</Row>
<Row>
    <Key android:codes="52"    android:keyLabel="4"  android:keyEdgeFlags="left" />
    <Key android:codes="53"    android:keyLabel="5" />
    <Key android:codes="54"    android:keyLabel="6" />
</Row>

<Row>
    <Key android:codes="55"    android:keyLabel="7"  android:keyEdgeFlags="left" />
    <Key android:codes="56"    android:keyLabel="8" />
    <Key android:codes="57"    android:keyLabel="9" />
</Row>

In this example you have 4 rows and in each row you have 3 keys.
also you can put an icon in each key you want.
Then you should add xml tag in your activity UI like this:
<android.inputmethodservice.KeyboardView
        android:id="@+id/keyboardview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:visibility="visible" />

Also in your .java activity file you should define the keyboard and assign it to a EditText:
CustomKeyboard mCustomKeyboard1 = new CustomKeyboard(this,
            R.id.keyboardview1, R.xml.horizontal_keyboard);
    mCustomKeyboard1.registerEditText(R.id.inputSearch);

This code asign inputSearch (which is a EditText) to your keyboard.
import android.app.Activity;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.text.Editable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class CustomKeyboard {

/** A link to the KeyboardView that is used to render this CustomKeyboard. */
private KeyboardView mKeyboardView;
/** A link to the activity that hosts the {@link #mKeyboardView}. */
private Activity mHostActivity;

/** The key (code) handler. */
private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {

    public final static int CodeDelete = -5; // Keyboard.KEYCODE_DELETE
    public final static int CodeCancel = -3; // Keyboard.KEYCODE_CANCEL
    public final static int CodePrev = 55000;
    public final static int CodeAllLeft = 55001;
    public final static int CodeLeft = 55002;
    public final static int CodeRight = 55003;
    public final static int CodeAllRight = 55004;
    public final static int CodeNext = 55005;
    public final static int CodeClear = 55006;

    @Override
    public void onKey(int primaryCode, int[] keyCodes) {
        // NOTE We can say '<Key android:codes="49,50" ... >' in the xml
        // file; all codes come in keyCodes, the first in this list in
        // primaryCode
        // Get the EditText and its Editable
        View focusCurrent = mHostActivity.getWindow().getCurrentFocus();
        if (focusCurrent == null
                || focusCurrent.getClass() != EditText.class)
            return;
        EditText edittext = (EditText) focusCurrent;
        Editable editable = edittext.getText();
        int start = edittext.getSelectionStart();
        // Apply the key to the edittext
        if (primaryCode == CodeCancel) {
            hideCustomKeyboard();
        } else if (primaryCode == CodeDelete) {
            if (editable != null && start > 0)
                editable.delete(start - 1, start);
        } else if (primaryCode == CodeClear) {
            if (editable != null)
                editable.clear();
        } else if (primaryCode == CodeLeft) {
            if (start > 0)
                edittext.setSelection(start - 1);
        } else if (primaryCode == CodeRight) {
            if (start < edittext.length())
                edittext.setSelection(start + 1);
        } else if (primaryCode == CodeAllLeft) {
            edittext.setSelection(0);
        } else if (primaryCode == CodeAllRight) {
            edittext.setSelection(edittext.length());
        } else if (primaryCode == CodePrev) {
            View focusNew = edittext.focusSearch(View.FOCUS_BACKWARD);
            if (focusNew != null)
                focusNew.requestFocus();
        } else if (primaryCode == CodeNext) {
            View focusNew = edittext.focusSearch(View.FOCUS_FORWARD);
            if (focusNew != null)
                focusNew.requestFocus();
        } else { // insert character
            editable.insert(start, Character.toString((char) primaryCode));
        }
    }

    @Override
    public void onPress(int arg0) {
    }

    @Override
    public void onRelease(int primaryCode) {
    }

    @Override
    public void onText(CharSequence text) {
    }

    @Override
    public void swipeDown() {
    }

    @Override
    public void swipeLeft() {
    }

    @Override
    public void swipeRight() {
    }

    @Override
    public void swipeUp() {
    }
};

/**
 * Create a custom keyboard, that uses the KeyboardView (with resource id
 * <var>viewid</var>) of the <var>host</var> activity, and load the keyboard
 * layout from xml file <var>layoutid</var> (see {@link Keyboard} for
 * description). Note that the <var>host</var> activity must have a
 * <var>KeyboardView</var> in its layout (typically aligned with the bottom
 * of the activity). Note that the keyboard layout xml file may include key
 * codes for navigation; see the constants in this class for their values.
 * Note that to enable EditText's to use this custom keyboard, call the
 * {@link #registerEditText(int)}.
 *
 * @param host
 *            The hosting activity.
 * @param viewid
 *            The id of the KeyboardView.
 * @param layoutid
 *            The id of the xml file containing the keyboard layout.
 */
public CustomKeyboard(Activity host, int viewid, int layoutid) {
    mHostActivity = host;
    mKeyboardView = (KeyboardView) mHostActivity.findViewById(viewid);
    mKeyboardView.setKeyboard(new Keyboard(mHostActivity, layoutid));
    mKeyboardView.setPreviewEnabled(false); // NOTE Do not show the preview
                                            // balloons
    mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);
    // Hide the standard keyboard initially
    mHostActivity.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

/** Returns whether the CustomKeyboard is visible. */
public boolean isCustomKeyboardVisible() {
    return mKeyboardView.getVisibility() == View.VISIBLE;
}

/**
 * Make the CustomKeyboard visible, and hide the system keyboard for view v.
 */
public void showCustomKeyboard(View v) {
    mKeyboardView.setVisibility(View.VISIBLE);
    mKeyboardView.setEnabled(true);
    if (v != null)
        ((InputMethodManager) mHostActivity
                .getSystemService(Activity.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(v.getWindowToken(), 0);
}

/** Make the CustomKeyboard invisible. */
public void hideCustomKeyboard() {
    mKeyboardView.setVisibility(View.GONE);
    mKeyboardView.setEnabled(false);
}

/**
 * Register <var>EditText<var> with resource id <var>resid</var> (on the
 * hosting activity) for using this custom keyboard.
 *
 * @param resid
 *            The resource id of the EditText that registers to the custom
 *            keyboard.
 */
public void registerEditText(int resid) {
    // Find the EditText 'resid'
    EditText edittext = (EditText) mHostActivity.findViewById(resid);
    // Make the custom keyboard appear
    edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
        // NOTE By setting the on focus listener, we can show the custom
        // keyboard when the edit box gets focus, but also hide it when the
        // edit box loses focus
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus)
                showCustomKeyboard(v);
            else
                hideCustomKeyboard();
        }
    });
    edittext.setOnClickListener(new OnClickListener() {
        // NOTE By setting the on click listener, we can show the custom
        // keyboard again, by tapping on an edit box that already had focus
        // (but that had the keyboard hidden).
        @Override
        public void onClick(View v) {
            showCustomKeyboard(v);
        }
    });
    // Disable standard keyboard hard way
    // NOTE There is also an easy way:
    // 'edittext.setInputType(InputType.TYPE_NULL)' (but you will not have a
    // cursor, and no 'edittext.setCursorVisible(true)' doesn't work )
    edittext.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            EditText edittext = (EditText) v;
            int inType = edittext.getInputType(); // Backup the input type
            edittext.setInputType(InputType.TYPE_NULL); // Disable standard
                                                        // keyboard
            edittext.onTouchEvent(event); // Call native handler
            edittext.setInputType(inType); // Restore input type
            return true; // Consume touch event
        }
    });
    // Disable spell check (hex strings look like words to Android)
    edittext.setInputType(edittext.getInputType()
            | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}

}

// NOTE How can we change the background color of some keys (like the
// shift/ctrl/alt)?
// NOTE What does android:keyEdgeFlags do/mean

Comment: More explanation on this: http://www.fampennings.nl/maarten/android/09keyboard/index.htm


Display results from inner join with php and sql

Question: I have the following tables with column names:
rides: id, creator, title, datetime, city, state, details
states: id, state, image
user: id, username, name, password, email, city, state

I have the following php/sql code using inner joins to get info from the tables:
$sql = "select * from ((rides inner join states on rides.state = states.id) inner join user on rides.creator = user.id) where rides.id=" . $ride;
$result = mysqli_query($dbcon, $sql);
$row = mysqli_fetch_assoc($result);

What I'm having trouble with is I want to display the state field from the states table, the username field from the user table, and all the other info from rides, but I'm unsure how to do this. I tried the following to display the state, but it didn't work:
echo $row['state']; //this displays the state field from the rides table
echo $row['states.state']; //this displays nothing

My thinking is that because the different tables have the same column names, it will take the info from the first (rides) table. Is this correct? If so, is there a way to get it to reference the different tables, or do I need to rename the columns so they have different names?
Any help is appreciated.
Answer: Select the fields you want:
select rides.*, states.state, user.username
. . .

Now, the parentheses are not needed for the joins.  And table aliases make a query easier to write and to read.  Finally, you should learn to use parameters.  So, the query should look like this:
select r.*, s.state, u.username
from rides r inner join
     states s
     on r.state = s.id inner join
     user u
     on r.creator = u.id
where r.id = ?

The ? is a placeholder for the parameter.


What Solutions are Available for Marble Floor Etching / Corrosion

Question: Below is a picture of what some of the tiles that have corroded over the past 25 years of use, look like in the our house.
I read this QA post, however, am not comfortable with the solutions provided, it would be expensive & they would have to remove each slap (they are big stones placed on the floor), resurface then put back in. Is there such a thing as marble filler or even transparent fillers which can fill these
corrosions?

Answer: That's too deep to grind flat.  It's somewhat of a "natural" look, so you could consider leaving it as-is unless the holes are big enough to be a hazard.  In that case, I would look at just filling the holes.
You can use clear resin, which will sort of keep the natural look.  A variation is to fill the holes with a mix of resin and marble dust.  If you can find a small piece of marble of a generally similar color (doesn't need to be an exact match), you can make your own dust with a grinder.  A marble supplier may also be a ready source of dust from other jobs.  That will look a little more like natural patterns in the stone (like the light colored blotches that are part of the existing stone).
When it hardens, you grind the filler level and polish it.  Experiment first to learn how the material behaves, and adjust your mixture to achieve the appearance you want.  Buy a few marble scraps to play with.  You can use a Dremel tool to grind out some holes to mimic the floor and practice on that.  Work with small batches so you have plenty of time to get each repair right.
You can also buy kits for repair of marble and other stone.  They tend to be epoxy with colorants that you mix to match the color, or an acrylic gel that you color.  Here are a few links (there are lots of options that a Google search will show):

https://www.homedepot.com/p/Custom-Building-Products-Travertine-Repair-Kit-TRAVRK/203919972
https://marblekareproducts.com/products/mk-hole-repair-kit-white?variant=553746433
https://countertopguides.com/shop/countertop-stone-repair/granite-marble-chip-repair-kit
http://acrylicrepair.com/high-quality-do-it-yourself-marble-repair

Disclaimer: I've never used any of these products, they're just examples as illustrations.  I mix my own.
If it's just a few tiles, you might be able to replace them from a marble supplier.  You won't find an exact match, but you might find something close enough (or what you think is a better match than a few tiles with patterns that don't match the others).
One other thought: If you use the resin and marble dust approach, that material will be almost a tough as stone and you may need an angle grinder and a collection of successively finer grinding heads or pads to smooth and polish the surface in a reasonable time. If you use one of the kits that are just colored resin, that material is much softer. It will scratch more easily, but you will be able to finish the surface quickly with a collection of successively finer sandpapers.
With the resin-only approach, you can put down a shine layer on the whole floor.  There are products like Pledge Floor Care that are a clear acrylic solution that dries to a film. That will get the abuse and you just periodically clean it off and apply a new layer rather than polishing away the repair over time, which would eventually leave dents.
Comment: @Kayote, I added information on kits you can buy that may simplify the task for you.  For the number and size of the holes, it might get expensive, though.
Comment: @Kayote, there's quite a range of prices for available products and I don't know how the quality varies.  There are also differences in hardness, which would be important if it is an area that could get scratched or abraded by traffic, moving furniture, etc.  The demands on walls, table tops, counter tops, and floors are different.  You might want to ask the manufacturer about suitability for a floor repair and ask for a color sample.
Comment: Wonderful suggestions & a post that gives me hope. I will look into all the options mentioned, particularly the clear resin & marble dust. Unfortunately, we have had it confirmed that to find similar colour marble slabs would be near impossible. Also, I am not keen on the 'as-is' option as this doesn't look nice at all. We have been particularly abusive to this floor and it hasn't had polishing done in 25 years! Last time was when it was made ready for the flooring & polished after the installation. Thank you again for the suggestions.
Comment: thank you for the effort & references. I have bookmarked the links for info. And yes, this is expensive, however, still cheaper than the alternative of slab replacement. The area covered by Marble is approx 2000 sq feet roughly & while most of it merely needs polishing, the repair area is still big. I came across this on ebay and I wonder if this cheaper alternative also means cheaper quality? https://www.ebay.co.uk/itm/Tenax-Polyester-Resin-Travertine-Marble-Limestone-Tile-Hole-Filler-Repair-Kit/172765556521?hash=item2839a12f29:g:5KwAAOxyrM5TIugX
Answer: I am professionally experienced in stone restoration, fabrication and polishing.
 That stone  looks like Travertine not marble. Its is naturally full of pits usually they have been filled with a polyresin of some sort.
You can't polish, etch, sand or grind this problem away. It needs to be filled by a professional who can color match and not ruin the stone further. I will not recommend any commercial professional service the few that I know of are not capable of doing this type of job.
I might try to go to a local high end custom stone company. Not one that only does tile or just countertops.
A high end custom place  will most likely have a capable person who can help you.
Don't DIY this or trust some miracle chemical cure it will not work.
Comment: Many thanks for the feedback, @Pismurf. I can confirm this is marble. A lot of the stone slabs are still without any pits / corrosion, however, unaware, we had been using various cleaning agents to clean the floor.


Weird CSS issue involving inline overrides in IE

Question: http://searchdatacenter.techtarget.com/informationCenter/0,296712,sid80_iid371,00.html
On this page the ad on the bottom right with the black background header doesn't pickup the inline styles in IE.  So it's the custom grey and black text in IE but the correct black background and white text in Firefox.
The default styles come from a stylesheet....the overrides come inline.  Any reason why this isn't being picked up by IE?
Edit: Thanks, missed the overrides come inlinedoctype. Any reason why this isn't being picked up by IE?
Comment: Quirks mode + proprietary `` = RUN.
Comment: I hope this is not your website... Chrome comes across 18 major rendering errors. I wont elaborate.
Answer: The style tag is only valid inside the head section of the page, and the linked stylesheet just above it should be in the head as well. You're lucky what you have works in anything.
If this is difficult to change, your best bet is probably removing your style block and using the style attribute on the div instead:


How to populate  choices with already fetched data

Question: In my App component I have a subscriptions Resource with an edit component:
<Resource name="subscriptions" list={SubscriptionList} edit={SubscriptionEdit} />

SubscriptionEdit looks something like this:
 export const SubscriptionEdit = props => (
  <Edit title={<SubscriptionTitle />} {...props}>
    <TabbedForm >
      <FormTab label="Info">
        ...

        <SelectInput
          source="typeSubscription"
          choices={[
            { id: 'monthly', name: 'Monthly' },
            { id: 'anual', name: 'Anual' },
          ]}
          label="Subscription plan"
        />
      </FormTab>
    </TabbedForm>
  </Edit>
);

And the data fetched from the endpoint when you enter this view is a JSON like this:
{
  id: 1,
  typeSubscription: null,
  selectedDay: null,
  daysAvailable: [
      { id: '07-01-2018', name: 'First day` },
      { id: '07-03-2018', name: 'Second day` },
      { id: '07-07-2018', name: 'Third day` },
      { id: '07-08-2018', name: 'Fourth day` },
  ],
}

What I need to do is add another SelectInput using daysAvailable array for the choices, in order to select the day for 'selectedDay'.
<SelectInput
      source="selectedDay"
      choices={NEED TO ADD daysAvailable HERE!}
      label="Select an available day"
 />

This data is already available in the store and in the record prop, but I can't figure out how to properly use it in choices. Trying to use it directly like a prop results in different errors and I think thas is normal because I'm messing with the inners of redux and admin-on-rest.
I tried to use ReferenceInput and leave choices for SelectInput empty as the docs suggested, but as this list of days changes based on the ID of the user I couldn't find a way to add this parameter to the new Resource.
I'm using admin-on-rest but planning to upgrade to react-admin in the near future if that's relevant.
That said, any help will be appreciated.
Cheers!
Answer: This is what ReferenceInput is for. You can supply the name of the resource, like this:
import { ReferenceInput, SelectInput } from 'react-admin'

<ReferenceInput label="Post" source="post_id" reference="posts">
    <SelectInput optionText="title" />
</ReferenceInput>


Why this code doesn't print some values?

Question: i don't understand why when i try to print values in archivio[] with stampa function,this program prints
"studente","matricola","nome","cognome"
correctly, but doesn't print values from stampaEsami.
#include <stdio.h>
#include <stdlib.h>
#define MAXSTUDENTI 20
#define MAXSTRINGA 100
#define MAXESAMI 25

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

typedef char Stringa[MAXSTRINGA];

typedef enum { uno, due, tre, FC
} AnnoCorso;

typedef struct {
    Stringa nomeEsame;
    int voto;
} Esame;

typedef struct {
    Esame listaEsami[MAXESAMI];
    int numeroEsami;
}ListaEsame;

typedef struct {
    int matricola;
    Stringa nome;
    Stringa cognome;
    AnnoCorso anno;
    ListaEsame esami;
} Studente;

void init(Studente[], int);
void acquisisciEsami(Studente, int);
void stampa(Studente[], int);
void stampaEsami(ListaEsame);

void init(Studente archivio[], int n){

    int i;
    int nEsami;

    for(i = 0;  i < n; i++){
        printf("Studente n. %d\n", i+1);
        printf("Inserire matricola: ");
        scanf("%d", &archivio[i].matricola);
        printf("Inserire nome: ");
        scanf("%s", &archivio[i].nome);
        printf("Inserire cognome: ");
        scanf("%s", &archivio[i].cognome);
        printf("Inserire il numero di esami svolti: ");
        scanf("%d", &archivio[i].esami.numeroEsami);
        nEsami = archivio[i].esami.numeroEsami;
        if(nEsami != 0) {
            acquisisciEsami(archivio[i], nEsami);
        }

    }

}

void acquisisciEsami(Studente studente, int n){

    int i;

    for(i = 0; i < n; i++) {
        printf("Inserire nome esame:");
        scanf("%s", studente.esami.listaEsami[i].nomeEsame);
        printf("Inserire voto esame:");
        scanf("%d", &studente.esami.listaEsami[i].voto);
    }

}

void stampa(Studente archivio[], int n){

    printf("\nGli studenti presenti in archivio sono:\n");

    int i;

    for(i = 0; i < n; i++){
        printf("Studente n. %d:\n", i+1);
        printf("Matricola: %d\n", archivio[i].matricola);
        printf("Nome: %s\n", archivio[i].nome);
        printf("Cognome: %s\n", archivio[i].cognome);
        stampaEsami(archivio[i].esami);
    }
}

void stampaEsami(ListaEsame esami){

     int i = 0;
     int n = esami.numeroEsami;

     for(i = 0; i < n; i++){
        printf("Nome esame: %s\n", esami.listaEsami[i].nomeEsame );
        printf("Voto esame: %d\n", esami.listaEsami[i].voto);
     }
}

int main(int argc, char *argv[]) {

    Studente studenti[MAXSTUDENTI] ;
    int n;

    printf("Inserire il numero di studenti da memorizzare in archivio:\n ");
    scanf("%d", &n);
    init(studenti, n);
    stampa(studenti, n);

    return 0;
}

If input is:
Inserire il numero di studenti da memorizzare in archivio:1
Inserire matricola: 13434
Inserire nome: test
Inserire cognome: test
Inserire il numero di numero di esami svolti: 1
Inserire nome esame: asd2
Inserire voto esame: 20

it prints:
Gli studenti presenti in archivio sono:
Studente n.1:
Matricola: 13434
Nome : test
Cognome: test
Nome esame:
Voto esame: 0

Comment: For some specific input, what is the actual output, and what is the expected output? Please include it by copy-pasting the actual input/output.
Comment: You mind creating an [___MCVE___](http://stackoverflow.com/help/mcve)?
Comment: I think that all code i wrote serves to run and understand the problem
Comment: `scanf("%s", &archivio[i].nome);` --> `scanf("%s", archivio[i].nome);` same thing for `cognome` member.
Answer: Your problem is acquisisciEsami function.
It should accept Studente *, instead of a variable passed by value.
void acquisisciEsami(Studente *studente, int n)
{
    int i;

    for(i = 0; i < n; i++)
    {
        printf("Inserire nome esame:");
        scanf("%s", studente->esami.listaEsami[i].nomeEsame);
        printf("Inserire voto esame:");
        scanf("%d", &studente->esami.listaEsami[i].voto);
    }
}

So what is the problem? Your code is compiling a structure that has local scope into acquisisciEsami function and all data will be lost when function ends. So esami member of archivio[i] is not modified.
Passing archivio[i] by reference to acquisisciEsami you can change content of esami memeber of archivio[i]
Obviously the call to acquisisciEsami will be:
acquisisciEsami(&archivio[i], nEsami);

As I commented you have issue to fix:

scanf("%s", &archivio[i].nome); must be scanf("%s",archivio[i].nome);
scanf("%s", &archivio[i].cognome); should be scanf("%s",archivio[i].cognome);


Contextmenu on listview datatemplate not working

Question: I have a simple ListView bound to a collection of Calculations. The view calls the calc Name property in the display. I have set the contextmenu to the individual items in the listview but on right click the context menu shows up as a tiny box with nothing in. What am i missing?
    <ListView x:Name="CalcList" ItemsSource="{Binding Calculations}">
        <ListView.ItemTemplate>
            <DataTemplate DataType="x:Type lib:Calculation">
                <DataTemplate.Resources>
                    <ContextMenu x:Key="CalcMenu">
                        <MenuItem Header="Delete Calculation" Click="MenuItem_Click"/>
                        <MenuItem Header="Another"/>
                        <MenuItem Header="Another"/>
                    </ContextMenu>
                </DataTemplate.Resources>
                <Border BorderBrush="Black" BorderThickness="1" Margin="2">
                    <Border.ContextMenu>
                        <ContextMenu ContextMenu="{StaticResource CalcMenu}"/>
                    </Border.ContextMenu>
                    <TextBlock MouseLeftButtonDown="DisplayCalc" Text="{Binding Path=Name}"></TextBlock>
                </Border>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

Thanks.
Answer: If anything, you have a syntax error the way you define the Border.ContextMenu element. The correct syntax (of the Border Element):
<Border BorderBrush="Black" BorderThickness="1"
        Margin="2"
        ContextMenu="{StaticResource CalcMenu}">
     <TextBlock ... />
</Border>

Saying that, there is a lot of optimization you can do. First, instead of instantiating a context menu for each item, you can move the CalcMenu to the  section (one level up), or even farther up - to the main window.
Second, why do you define a separate context menu for each item? Is it really important context menu won't popu when mouse is in the margin between items? simply set the context menu to the entire list:
<ListView x:Name="CalcList" ContextMenu="{StaticResource CalcMenu}">
    ...

and define the CalcMenu as a main window resources, or inline the ListView element (not a static resource).
Comment: Thanks Uri. I had moved the resource down just to have a look at it but not realised the syntax error.


tvOS 13 AVPlayerViewController live playback timestamp issue

Question: After updating to tvOS 13, I am seeing 18y8m0w4d on the live progress bar when I rewind. This is fixed in a second or so when the progress bar gets updated. I don't see this issue on tvOS 12.
It looks like AVPlayerViewController bug but was wondering if anyone else is facing this issue?
Thanks
Answer: I saw the same issue on tvOS 13.0 and it looks like the latest update tvOS 13.2 has fixed it.


How do I write binary data to a file in Modern C++?

Question: Writing binary data to a file in C is simple: use fwrite, passing the address of the object you want to write and the size of the object.  Is there something more "correct" for Modern C++ or should I stick to using FILE* objects?  As far as I can tell the IOStream library is for writing formatted data rather than binary data, and the write member asks for a char* leaving me littering my code with casts.
Comment: You use the [`std::basic_ostream::write`](http://en.cppreference.com/w/cpp/io/basic_ostream/write) and [`std::basic_istream::read`](http://en.cppreference.com/w/cpp/io/basic_istream/read) functions to write or read e.g. structures or other binary/raw data. And yes, you have to do type-casting to make it work.
Comment: @JoachimPileborg this should be an answer.
Comment: These  casts are a friendly reminder that *you are reinterpreting your data as a sequence of bytes*. If you don't like the litter, wrap `read` and `write` such that te wrappers accept `void*` rather than `char*`, and add error handling while you're at it.
Comment: http://stackoverflow.com/questions/7349689/c-how-to-print-using-cout-the-way-a-number-is-stored-in-memory
Comment: See [this mine answer](http://stackoverflow.com/a/28748914/841108) to a related question.
Answer: So the game here is to enable argument dependent lookup on reading and writing, and make sure you don't try to read/write things that are not flat data.
It fails to catch data containing pointers, which also should not be read/written this way, but it is better than nothing
namespace serialize {
  namespace details {
    template<class T>
    bool write( std::streambuf& buf, const T& val ) {
      static_assert( std::is_standard_layout<T>{}, "data is not standard layout" );
      auto bytes = sizeof(T);
      return buf.sputn(reinterpret_cast<const char*>(&val), bytes) == bytes;
    }
    template<class T>
    bool read( std::streambuf& buf, T& val ) {
      static_assert( std::is_standard_layout<T>{}, "data is not standard layout" );
      auto bytes = sizeof(T);
      return buf.sgetn(reinterpret_cast<char*>(&val), bytes) == bytes;
    }
  }
  template<class T>
  bool read( std::streambuf& buf, T& val ) {
    using details::read; // enable ADL
    return read(buf, val);
  }
  template<class T>
  bool write( std::streambuf& buf, T const& val ) {
    using details::write; // enable ADL
    return write(buf, val);
  }
}

namespace baz {
    // plain old data:
    struct foo {int x;};
    // not standard layout:
    struct bar {
      bar():x(3) {}
      operator int()const{return x;}
      void setx(int s){x=s;}
      int y = 1;
    private:
      int x;
    };
    // adl based read/write overloads:
    bool write( std::streambuf& buf, bar const& b ) {
        bool worked = serialize::write( buf, (int)b );
        worked = serialize::write( buf, b.y ) && worked;
        return worked;
    }
    bool read( std::streambuf& buf, bar& b ) {
        int x;
        bool worked = serialize::read( buf, x );
        if (worked) b.setx(x);
        worked = serialize::read( buf, b.y ) && worked;
        return worked;
    }
}

I hope you get the idea.
live example.
Possibly you should restrict said writing based off is_pod not standard layout, with the idea that if something special should happen on construction/destruction, maybe you shouldn't be binary blitting the type.
Comment: That's looking good, but before I accept, can you tell me why you have declared a forwarding function?
Comment: @hatcat easy ADL.  Call `serialize::read` explicitly and it will still find a local namespace `read` override for a type.  Easier than forcing end users to always be ADL friendly when calling `read`, so I did the work for them.
Comment: @hatcat as an aside, have a not standard layout sfinae tested `std::tuple` overload in details.  Then aggregates can `read(stream,std::tie(my_members...))` and poof, done.
Answer: Since you are already bypassing all formatting, I would recommend using the std::filebuf class directly to avoid possible overheads from std::fstream; it's definitely better than FILE* due to RAII.
You can't escape from the casts this way, sadly. But it's not hard to wrap it, like:
template<class T>
void write(std::streambuf& buf, const T& val)
{
    std::size_t to_write = sizeof val;
    if (buf.sputn(reinterpret_cast<const char*>(&val), to_write) != to_write)
        // do some error handling here
}


Label for input field isn't rendered when ends with non ASCII character

Question: I encountered a strange behavior while using Django forms. In my forms.py I have a user register form, and for each field I have set a label. Then in view I am passing the form into the context. In html file I'm using the form as follows:
{% for field in UserForm %}

    {{field.label_tag}}
    {{field}}

{% endfor %}

my form looks like this:
class UserForm(UserCreationForm):

    first_name = forms.CharField(
        label = 'Imię',
        max_length=255,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'name': 'Name',
                'placeholder': 'Imię',
                'required' : '',

            }
        )
    )

    last_name = forms.CharField(
        label = 'Nazwisko',
        max_length=255,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'name': 'Surname',
                'placeholder': 'Nazwisko',
                'required' : '',

            }
        )
    )

The problem is that for one field a label is not shown,
the  tag is not even generated in output html file.
The problematic label is: label = 'Imię',. I noticed that when a label ends with non ASCII character, the label is not generated. I tested that for other field labels.
I have included # -*- coding: utf-8 -*- at the beginning of the forms.py (otherwise python throws an error about non ASCII characters in file), so that's not the source of this problem. Also I checked in Notepad++ that this file really uses UTF-8 encoding.
I'm using Django 1.9 and python version is 2.7.6.
Any help is appreciated.
Comment: Can you please post the code from your `forms.py`?
Comment: Did you try this: http://stackoverflow.com/questions/1998987/how-do-i-use-django-and-utf-8-content-type-for-template ?
Comment: @IainShelvington the file is here [link]http://pastebin.com/RYjyRsgj
Comment: @LuisAlves I've got this in my html.
Answer: Python 2.7 have 2 types of string, normal and unicode. Normal string (used by default) can't store any unicode characters. In your form you are using normal strings for label. That is causing issues.
You can either use unicode in that string:
    first_name = forms.CharField(
        label = u'Imię',
        max_length=255,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'name': 'Name',
                'placeholder': u'Imię',
                'required' : '',

            }
        )
    )

Or set all strings in this file to be treated as unicode by default, by adding:
from __future__ import unicode_literals

At the very top of the file (right after setting encoding for file).
In python 3 that was changed, so by default all strings are treated as unicode.
Comment: Thank you, it works now! I was not aware that the strings are not treated as unicode by default before python 3. I didn't suspect that may be a problem because other strings which contained unicode characters were working good.


does deductive completeness implies semantic completeness

Question: i wanted to understand godel's $ \ \bf completeness \ $ theorem, so while doing some research on google i found this wikipedia page " https://en.wikipedia.org/wiki/G%C3%B6del%27s_completeness_theorem#:~:text=G%C3%B6del's%20completeness%20theorem%20is%20a,simplest%208%20are%20shown%20left). " saying -

A first-order formula is called logically valid if it is true in every structure for the language of the formula (i.e. for any assignment of values to the variables of the formula). To formally state, and then prove, the completeness theorem, it is necessary to also define a deductive system. A deductive system is called complete if every logically valid formula is the conclusion of some formal deduction, and the completeness theorem for a particular deductive system is the theorem that it is complete in this sense. Thus, in a sense, there is a different completeness theorem for each deductive system. A converse to completeness is soundness, the fact that only logically valid formulas are provable in the deductive system.

Its the 2nd para under  $ \bf Preliminaries \  $ section.
" A deductive system is called complete if every logically valid formula is the conclusion of some formal deduction, and the completeness theorem for a particular deductive system is the theorem that it is complete in this sense. " - does this also means if a formula has a formal deduction then it must be semantically valid    ??
Answer: Yes, this is the soundness theorem. Technically this is a separate result from the completeness theorem, but it is - comparatively - so simple that it's often not mentioned explicitly.
The proof is by induction on the complexity of the deduction. Basically, you need to show that each of the rules of your system are "truth-preserving." Of course the details will depend on your system, but for every system I'm familiar with this is quite straightforward. (Especially in conjunction with the proof of completeness/compactness of propositional logic, this highlights the difficulty in proving the completeness of first-order logic.)
Answer: Complementing Noah's answer, to address the question in your title: Syntactic completeness implies "semantic completeness" (in the sense that every formula is either valid or its negation is) provided the deductive system is sound, i.e. that the deductibility of a formula guarantees its validity. Any useful deductive system has the soundness property, but it is not automatically baked into it just because it is a deductive system, and has to be proven separately.
Comment: ah yes, cuz in sound system only logically valid must be provable... Ok got it...
Answer: Atleast according to godel's completeness theorem, if you can give a formal deduction to a formula, given that the deduction contains axioms or other formally deductable formulas ( thus logically valid ), then that formula too must be logically valid..
so in this condition you can say if the system is deductively complete, all valid formulas have deductions, thus all are logically valid, therefore the system is semantically complete..


Expectation of scaled sum of squares of iid random variables

Question: Let $X_1, \dots, X_n$ be iid standard normal random variables. Consider the vector $X = (X_1, \dots, X_n)$ and the vector
$Y = \frac{1}{\|X\|}(X_1, \dots, X_k)$
for $k < n$. What is $\mathbb{E}[\|Y\|^2] = \mathbb{E}\left[\frac{\sum_{i=1}^k X_i^2}{\sum_{i=1}^n X_i^2} \right]$?
Comment: By symmetry, the result is exactly $$\color{red}{\bf\frac{k}n}.$$
Comment: For every $i\ne j$, the distributions of $(X_i,\|X\|)$ and $(X_j,\|X\|)$ coincide hence $E(X_i^2\|X\|^{-2})=E(X_j^2\|X\|^{-2})$. Summing these from $i=1$ to $n$ yields the expectation of $(X_1^2+\cdots+X_n^2)\|X\|^{-2}=1$ hence $E(X_i^2\|X\|^{-2})=n^{-1}$ for every $i$ and you are done.
Comment: @Did Thanks, that's exactly the result. Could you please elaborate on your symmetry argument? My reasoning was: The numerator is a Chi-square random variable, with expectation $k$, and the numerator is also a Chi-square random variable with expectation $n$. However,  it is not clear to me how to get $k/n$ from this (cc @ecstasyofgold)
Comment: @Cm7F7Bb Thanks for your suggestion, I will edit the question.
Comment: @Did Thanks so much, amazing answer! :)
Answer: I don't know the closed form of this but concentration of measure phenomenon ensures that the expectation will converge to $\frac{k}{n}$ exponentially fast in $k$. So using $k/n$ might be a reasonable approximation.


Multiple Custom Object Detection (Image processing) from a given Image in iOS

Question: I would like to get the custom objects detected with its frame.

I had checked regarding this, I was getting many as ARKit implementations - using that we can get live object detections(ie using the input stream as the camera stream), but my requirement is to get it from a given/static image.
I found the latest iOS guidelines/samples using the camera as the input stream which provides the classifications or rectangle or face detection etc.

There is my problem is I need to get it from a given image with custom multiple Objects.
For example, I need to identify the clocks in a given image(Image of a wall with multiple clocks with different types), here I can provide the sample clock images. So I need to get the identified clocks with its frame.
I had checked using Vision's VNImageBasedRequest with object classification, in which I can get classifications with custom trained CoreML model, but there is not getting the boundingBox property to get the frames, which is available in VNDetectedObjectObservation.

Thanks in advance for your valuable time & response.
Comment: Did you find anything using coreML? i heave the same requirement, the objects are getting detected in coreML application however when i use the same model and in project i see issues. Howeever same code works fine on live images but not on still images
Answer: You can do it making use of Google Cloud AutoML Vision Object Detection. If you want to detect custom objects you need to create your own custom model dataset and train it. Once the model is trained either you can host it on cloud and make an API call from the iOS app to detect the objects from your static image(online) or you can add the trained model to your project to detect the objects from image(offline). You can find the complete documentation here https://cloud.google.com/vision/automl/object-detection/docs/before-you-begin
If you are able to get it done in any other way please let me know how, even I'm working on similar use case.


Data loaded with useEffect hook but don't display

Question: I am loading data from firebase in useEffect and I am trying to display it.
Data are loaded but don't display. I don't understand why.
UserDetails.js:
import React, { useEffect, useState } from 'react'

import { useParams } from "react-router-dom";

import base from '../base';

import { ref, onValue } from "firebase/database";

const UserDetails = () => {

  const { userId } = useParams();
  const [user, setUser] = useState()

  useEffect(() => {
    const usersRef = ref(base, '/users');

    onValue(usersRef, (snapshot) => {
      const users = snapshot.val();
      let user = {};
      if (users !== null) {
        user = users.filter(user => user.id == userId)[0]
        setUser({ user });
      }
    });
  }, [userId]);

  return (
    <>

Hello {user.first_name}

    </>
  )
}

export default UserDetails

Error:

Cannot read properties of undefined (reading 'first_name')
TypeError: Cannot read properties of undefined (reading 'first_name')
at UserDetails
Comment: Hi, are you sure that userId trigger the useEffect?
Answer: user is already an object you just pass it to the setter function of the state you don't need curly braces:
setUser(user);

<>

Hello {user?.first_name}

</>

with
setUser({ user });

you are setting an object with a property user that is an object containing the user info so you have to access the user name this way:

Hello {user?.user?.first_name}

Answer: The effect does not fire until after the first render of your component. So on the first render, in the return statement user has whatever initial value it was assigned in useState, which here is undefined. This causes an error, as we're trying to read a property of an undefined variable.


Create transparent image in opencv python

Question: I am trying to make a transparent image and draw on it, and after I will addWeighted over the base image.
How can I initialize fully transparent image with width and hight in openCV python?
EDIT: I want to make a effect like in Photoshop, having stack of the layers, all stacked layers are initially transparent and drawing is performed on fully transparent layer. On the end I will merge all layers to get final image
Comment: This is very broad. Just use a new image (e.g. white), draw on it and somehow mark where you are drawing (not needed if you don't draw white as you can check for all pixels != white). Then all non-drawed weights are zero, when you combine these two images. (I'm not an opencv user and i made some assumptions about how addWeighted works).
Comment: OpenCV supports alpha channel but doesnt support rendering them.
Answer: For creating a transparent image you need a 4 channel matrix, 3 of which would represent RGB colors and the 4th channel would represent Alpha channel, To create a transparent image, you can ignore the RGB values and directly set the alpha channel to be 0. In Python OpenCV uses numpy to manipulate matrices, so a transparent image can be created as
import numpy as np
import cv2

img_height, img_width = 300, 300
n_channels = 4
transparent_img = np.zeros((img_height, img_width, n_channels), dtype=np.uint8)

# Save the image for visualization
cv2.imwrite("./transparent_img.png", transparent_img)

Comment: Actually it worked out when i added rectangle with 4 channels, with alpha 255 value... thank you
Comment: @MichaelPresečan could you edit the answer and add the rectangle so the example is broader.
Comment: Thank you, I have tried to draw something on the image you have proposed, but it doesnt work. Image is truly created but I cannot draw a simple rectangle on it. Operation is completed, but when image is saved, rectangle cannot be seen.
Comment: @MichaelPresečan Please edit the answer with your addition of the rectangle for others as well
Answer: If you want to draw on several "layers" and then stack the drawings together, then how about this:
import cv2
import numpy as np

#create 3 separate BGRA images as our "layers"
layer1 = np.zeros((500, 500, 4))
layer2 = np.zeros((500, 500, 4))
layer3 = np.zeros((500, 500, 4))

#draw a red circle on the first "layer",
#a green rectangle on the second "layer",
#a blue line on the third "layer"
red_color = (0, 0, 255, 255)
green_color = (0, 255, 0, 255)
blue_color = (255, 0, 0, 255)
cv2.circle(layer1, (255, 255), 100, red_color, 5)
cv2.rectangle(layer2, (175, 175), (335, 335), green_color, 5)
cv2.line(layer3, (170, 170), (340, 340), blue_color, 5)

res = layer1[:] #copy the first layer into the resulting image

#copy only the pixels we were drawing on from the 2nd and 3rd layers
#(if you don't do this, the black background will also be copied)
cnd = layer2[:, :, 3] > 0
res[cnd] = layer2[cnd]
cnd = layer3[:, :, 3] > 0
res[cnd] = layer3[cnd]

cv2.imwrite("out.png", res)

Answer: To convert an image's white parts to transparent:
import cv2
import numpy as np

img = cv2.imread("image.png", cv2.IMREAD_UNCHANGED)
img[np.where(np.all(img[..., :3] == 255, -1))] = 0
cv2.imwrite("transparent.png", img)


jQuery File Upload - get size of uploaded images

Question: I am using the jQuery File Upload to upload product images. There are different "types" of images for each product (different size/dimensions).
I have altered the upload template so that a dropdown of possible image types is shown for each file added.  Before clicking upload, the user must pick from the dropdown to indicate what image type the file being uploaded is.
Some image types are an exact size, some just have a minimum width. What I want to do is compare the actual image size to the type chosen to validate they are indicating the correct type.
I'm attempting to do this via the "fileuploadsubmit" callback where I have already added a check to make sure an option is selected in the dropdown.
<code>$('#fileupload').bind('fileuploadsubmit', function (e, data) {
    $('#uploading_note').removeClass("alert-danger").html("");
    var inputs = data.context.find(':input');
    if (inputs.filter(function () {
        return !this.value && $(this).prop('required');
    }).first().focus().length) {
        data.context.addClass("alert-danger");
        data.context.find('.file_msg').html("Image Type is required!");
    data.context.find('button').prop('disabled', false);
    return false;
}
    var fixed_dimension = 0;
    var wt = 0;
    var ht = 0;
    var image_size = getImageSize(data,function(width, height) {
        wt = width;
        ht = height;
        console.log (wt+'x'+ht);
        return [wt,ht];
    });
   ...........
</code>
This is the getImageSize function.
<code>    function getImageSize(data,callback){
    var img = new Image();
    img.src = _URL.createObjectURL(data.files[0]);
            img.onload = function () {
                var w = this.width;
                var h = this.height;
                console.log(w+'-getImageSize-'+h);
                callback (w,h);
            };

}
</code>
The console.log() in both output correctly but I can't get these numbers outside the functions to use them.  I understand it has to do with the functions be asynchronous but I can't figure out how to get around it.  Or maybe there is a better jQuery File Upload built in option I'm missing.
I understand the asynchronous function issue, this one was attempt at finding a solution to validating the image size.  I have also attempted to do this in the PHP script. It works in that I can prevent the upload of an image but the user experience is poor. So I am still looking for a solution as to how to do image size validation using jQuery File Upload.
Below is an update version of the code.
<code>$('#fileupload').bind('fileuploadsubmit', function (e, data) {
    console.log(data);

    $('#uploading_note').removeClass("alert-danger").html("");
    var inputs = data.context.find(':input');
    if (inputs.filter(function () {
        return !this.value && $(this).prop('required');
    }).first().focus().length) {
        console.log(data.context);
        data.context.addClass("alert-danger");
        data.context.find('.file_msg').html("Image Type is required!");
        //$('#uploading_note').addClass("alert-danger").html("Image Type is required!");
    data.context.find('button').prop('disabled', false);
    return false;
}

    var fixed_dimension = 0;
    var wt = 0;
    var ht = 0;
    var image_size = getImageSize(data,function(width, height) {
        wt = width;
        ht = height;
        console.log(wt+'-getImageSize-function'+ht);
       switch (inputs[0].value){
        case "16x9_background":
        case "16x9":
            var req_width = 1920;
            var req_height = 1080;
            fixed_dimension = 1;
            break;
        case "3x4":
            var req_width = 1600;
            var req_height = 1200;
            fixed_dimension = 1;
            break;
        case "hires":
            var req_width = 1400;
            var req_height = 0;
            break;
        case "lowres":
            var req_width = 200;
            var req_height = 0;
            break;
    }
    if (fixed_dimension){
        if (wt != req_width || ht != req_height){
            data.context.addClass("alert-danger");
            data.context.find('.file_msg').html("Image dimensions must be exactly "+req_width+"x"+req_height+". This image is "+wt+"x"+ht+". Image not uploaded.");
            return false;
        }
    } else {
        if (wt < req_width){
           data.context.addClass("alert-danger");
           data.context.find('.file_msg').html("Image dimensions wrong!! Width must be "+req_width+", not "+wt+". Image not uploaded.");
            console.log(wt+'x'+ht);
            return false;
        }
    }
    d = inputs.serializeArray();
    d.push({ name: "folder", value: $('#barcode').val() });
    d.push({ name: "stock_num", value: $('#stock_num').val() });
    data.formData = d;
    console.log(wt+"xxxx"+ht);
    data.submit();  // SUMBIT THE FORM
    });

    console.log(wt+"xxxx"+ht);
    console.log("imagesize:"+image_size);
    return false;  //STOP THE DEFAULT SUBMIT
});
</code>
Comment: Agreed with @kmoser, the root cause of your problem is that you're not handling asynchronous code correctly, but you might be interested in [this Q/A](https://stackoverflow.com/questions/42540903/sort-by-image-resolution-in-gallery/) too.
Comment: Possible duplicate of *How to return value from an asynchronous callback function*: https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function
Comment: Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)
Comment: Yes I get that the problem is related to asynchronous code, I haven't figured out how to code correctly yet, I will read these links..  But also I was really hoping there was a jQuery File Upload specific solution that I was overlooking.
Comment: Also to be clear, I just need to get the size of an uploaded image.  I don't want it to be asynchronous but it seems this img.onload function is done asynchronously.  How do I force it to be not asynchronous?
Comment: You don't need to force it to be synchronous. You should be doing your validation within the callback which determines the image width and height,
Comment: I tried that.  Where I am attempting to "return [wt,ht]", I got rid of that and put all the validation in there.  When I did that, no errors or anything but it did not actually stop when the validation failed.  I tried just "return false".   It still seems I'm the same issue, I can't get data out of the function and back to the rest of the script. What am I missing?
Comment: What does "it did not actually stop" mean? And why does the rest of the script need the data, when you've told us you've already created a function that has just determined whether the data is valid. At the point you've determined the data is invalid, why not just do this:

    ``data.context.addClass("alert-danger");
    data.context.find('.file_msg').html("Image Type is required!"); ``
Comment: "It does not actual stop" meaning the script continues on and uploads the file.  The first bit of code which checks that the required field is populated, that "return false" stops the script from uploading the file.  So the error msg is displayed to the user and the file is not uploaded.   I can't get that to work with my size validation though.  If I do as you are suggesting, the class will change and the msg displayed BUT it will continue on, upload the file and those on screen changes will go away because the file upload process returns that it was successful.  I appreciate your help!
Comment: In that case, your first bit of code should check for required fields and set a global variable indicating the results, e.g. ``$OK = true;`` or ``$OK = false;``. Regardless of whether it finds errors it should ``return false;`` to stop the form from submitting. When the size validation function runs, it should determine if the file is valid; if so, *and* if ``$OK == true``, then it should submit the form, e.g. ``$( "form" ).submit();``
Comment: @kmoser I added the full code to my post so it is more clear.  I thought I could move the submit logic into the function, basically move the rest of the fileuploadsubmit into the function but it is not working. I always fails since i'm doing return fail.
Comment: You might also need to use https://api.jquery.com/event.preventdefault/ to prevent the form from submitting.
Answer: What I ended up doing was removing the actual form submit button and replace it with a button (not type submit) that calls the validation code.  If it passes, the form is then submitted normally (via data.submit()), if not it returns the error.  I had to remove the file level submit buttons (or I found it easier to do that).
<code>    $('#fileupload').fileupload({
    url: 'process.php',
    previewThumbnail: true,
    sequentialUploads: true,
    acceptFileTypes: /(\.|\/)(jpe?g|pdf|zip)$/i,
    maxChunkSize: 10000000,
    add: function (e, data) {
        $('#start_upload_button').click(function () {
          getImageSize3(data).then(function(dimensions) {
        image validation... return false if any errors

    data.submit() // submit the form
    });
</code>


Custom error message based on SQL Exception code

Question: What would be the best way to catch the SQL exception code, and then use it to produce a custom error message?
I have a login page which fills out a custom connectionstring, then redirects to a page which uses said connection to access a database. On that page, it can throw errors depending on if I entered the correct login info, or if the database entered is wrong.
Can I just test the connection before I get to that page, or can I catch the exception code and bring it back to the login page?
Comment: I would personnally test the connection.
Comment: Yes, but _how_ do I test the connection?
Answer: This question is actually to wide. I will try to add an images to reduce lengthy code. I am considering only UniqueConstraintException in this example and will use C# instead of vb.net. Have to change my lot of code otherwise.
In my scenario, I created a BaseException class which is inherited from Exception class.
public class BaseException : Exception
{
    public BaseException()
        : base()
    { }

    public BaseException(string _exceptionMessage)
        : base(_exceptionMessage)
    {
    }

    public BaseException(string _exceptionMessage, Exception _innerException)
        : base(_exceptionMessage, _innerException)
    {
    }
}

Since I am interested SQL exceptions so I will create few more classes.
See my class diagram below, SqlHelperException is derived from BaseException class. SqlHelperException class object will be thrown by your CRUD operations in DAL hitting database,  should be handled by BAL layer.
public class SqlHelperException : BaseException
    {
        public string ErrorMessage { get; set; }

        public SqlHelperException()
            : base()
        {
        }

        public SqlHelperException(string message)
            : base(message)
        {
        }

        public SqlHelperException(string message, System.Exception innerException)
            : base(message, innerException)
        {
        }
    }

public class SqlHelperUniqueConstraintException : SqlHelperException
{
    public SqlHelperUniqueConstraintException()
        : base()
    {
    }

    public SqlHelperUniqueConstraintException(string message)
        : base(message)
    {
    }

    public SqlHelperUniqueConstraintException(string message, Exception innerException)
        : base(message, innerException)
    {
    }
}

Once my ground work is done, I wrote a translator which accepts SqlException and wraps it into SqlHelperException object
public static SqlHelperException TranslateException(System.Data.SqlClient.SqlException ex)
        {
            SqlHelperException dalException = null;

            // Return the first Custom exception thrown by a RAISERROR
            foreach (System.Data.SqlClient.SqlError error in ex.Errors)
            {
                if (error.Number >= 50000)
                {
                    dalException = new SqlHelperException(error.Message, ex);
                }
            }

            if (dalException == null)
            {
                // uses SQLServer 2005 ErrorCodes
                switch (ex.Number)
                {
                    case 2601:
                        // Unique Index/Constriant Violation
                        dalException = new SqlHelperUniqueConstraintException(ex.Message, ex);
                        //Overwrite Error message with your custom error message, we can use Resource file
                        dalException.ErrorMessage = ErrorMessages.SqlHelperUniqueConstraintException;

                        break;
                    case 18456:
                        // Login Failed
                        dalException = new SqlHelperLoginException(ex.Message, ex);
                        break;
                    default:
                        // throw a general DAL Exception
                        dalException = new SqlHelperException(ex.Message, ex);
                        break;
                }
            }

            // return the error
            return dalException;
        }

Here in this translator, I used ErrorMessages.SqlHelperUniqueConstraintException static property which holds actual error message.
public class ErrorMessages
    {
     public static readonly string SqlHelperUniqueConstraintException;
     static ErrorMessages()
        {
            SqlHelperUniqueConstraintException = "{0} failed, duplicate {1}  already exists.";
        }
    }

Now in my DAL layer where I wrote my CRUD operations, I simply consumed these exceptions
public class Person
{
        public void Create()
        {
            SqlHelper sql = new SqlHelper();
            try
            {
                sql.ExecuteNonQuery()
            }
            catch (SqlEception ex)
            {
                var e =TranslateException(ex);
                e.ErrorMessage = string.Format(e.ErrorMessage, "Creation", "Person");
                throw e;
            }
        }
}

By doing so, at BAL I will get error message saying : "Creation failed! duplicate person already exist."
Answer: What I end up doing was just "trying" to open the connection, and if it failed, catch the exception message, and put it on a label on the page.
    Dim queryString As String = "LOGINPROPERTY ( '" + Username + "' , 'property_name' )"
    Dim connection As New SqlConnection(ConnectionString)
    Dim command As New SqlCommand(queryString, connection)
    Try
        connection.Open()
        Response.Redirect("destination.aspx")
    Catch ex As Exception
        LabelError.Text = ex.Message
    Finally
    End Try