present modal with navigation bar twice, unable to get the first modal

Question: I have two view controllers to present modal, one on top of another, both are embedded in navigation view controller
In ChatListViewController: Level 1
- (IBAction)ui_mass_message:(id)sender {

    UIViewController *viewController = (UIViewController *)[CocoaHelper viewControllerWithIdentifier:VC_MASS_MESSAGE];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
    [self presentViewController:navController animated:YES completion:nil];

}

In MassMessageViewController: Level 2
    SelectContactViewController *viewController = (SelectContactViewController *)[CocoaHelper viewControllerWithIdentifier:VC_CONTACT_SELECT];
    [viewController setupWithType:SelectContactTypesMassMessage preSelectedContacts:self.contacts];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
    [self presentViewController:navController animated:YES completion:nil];

In SelectContactViewController: Level 3
When I dismiss, I need to pass a parameter to Level 2 (MassMessageViewController), and go 1 level down:
    //TODO: controller is nil
    //I have tried self.navigationController.presentingViewController as well

    MassMessageViewController *controller = (MassMessageViewController *)self.presentingViewController;
    [controller refreshContacts:self.selectedContacts];

    [self.navigationController dismissViewControllerAnimated:YES completion:nil];

Comment: This answer maybe help you
http://stackoverflow.com/questions/6606355/pass-value-to-parent-controller-when-dismiss-the-controller
Comment: @NguyenTran no it's not working
Comment: This is what the delegate pattern is for: http://stackoverflow.com/q/626898/1445366
Comment: the delegate is a bit less human readable when passing the parameter since passing and receiving parts are located in separated chunks of codes. i only use it when i don't have other choices (e.g. core data and networking)
Comment: plus, delegate is more for broadcasted messages when 'multiple' 'unknown' view controllers are listening, while in this case only one view controller is the recipient. i don't want my code to grow too large
Comment: Delegation isn't for broadcasting.  It's for communication between classes through a protocol so they don't need to know about each other.  Your current approach is creating a dependency between your data model and your view hierarchy - if you stick another view controller in between, everything will need to be rewritten.  You should have a separate object for managing data; the view controllers should talk to this object instead of to each other.
Comment: @AaronBrager oic, i think i confused delegation and observation/notification patterns.
Answer: please try this code in last method
UINavigationController *presentingNav = self.presentingViewController;
MassMessageViewController *controller = (MassMessageViewController *)presentingNav.viewControllers[0];
[controller refreshContacts:self.selectedContacts];

[self.navigationController dismissViewControllerAnimated:YES completion:nil];

Comment: worked. self.navigationViewController.presentingViewController also works
Comment: i think both of them returns the navigation controller
Answer: The normal way is to use a delegate or call back when you want to pass data back. It's sensible to make the presenting view controller responsible for dismissing the presented viewController.
I would most likely try and get something that looked like this:
- (IBAction)ui_mass_message:(id)sender
{
  UIViewController *viewController = (UIViewController *)[CocoaHelper viewControllerWithIdentifier:VC_MASS_MESSAGE];

  __weak __typeof(self) weakSelf = self;
  viewController.onCompletion = ^(UIViewController *viewController){
    [weakSelf dismissViewControllerAnimated:YES completion:nil];
  };

  UINavigationController *navController  = [[UINavigationController alloc] initWithRootViewController:viewController];
  [self presentViewController:navController animated:YES completion:nil];
}

This will handle dimissing the viewController when the next viewController has "completed". Then you do a similar thing for the next viewController.
SelectContactViewController *viewController = (SelectContactViewController *)[CocoaHelper viewControllerWithIdentifier:VC_CONTACT_SELECT];
[viewController setupWithType:SelectContactTypesMassMessage preSelectedContacts:self.contacts];

__weak __typeof(self) weakSelf = self;
viewController.onCompletion = ^(UIViewController *viewController, NSArray *selectedContacts){
  weakSelf.contacts = selectedContacts;
  [weakSelf dismissViewControllerAnimated:NO completion:nil];
  if (weakSelf.onCompletion) {
    weakSelf.onCompletion(weakSelf);
  }
};

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[self presentViewController:navController animated:YES completion:nil];

This will again call back to say the viewController has finished but in this case you can also pass back the selectedContacts.
Following simple patterns can really simplify your code base. You could do this with blocks like I have shown or delegates they will both give the same result.


Print Excel VBA code in Word with same color

Question: Is it possible to export my VBA code into Microsoft Word in order to print it. Is there a way to keep the same color formatting? I can copy/paste it, but i must select and change the text-color every single time for all the lines (it's long!).

Is there a tricky way to keep the color formatting?
Is there a software that I can paste the code into it and just print it.

I wonder how the pros do it...
Comment: Take a look at this post:
http://stackoverflow.com/questions/2578057/how-to-pretty-print-vba-code
Answer: If you don't fancy installing anything, you could try https://tohtml.com/vbasic/ which I just found.
Copy and paste all your code into the box, press 'Highlight', and copy and paste the result from the preview area.
Comment: Good link. Thanks !


What is it called when you organize a grid of sequential integers in a way that any range within that sequence is clustered together?

Question: I have tried hard to search for this and I'm starting to think I am imagining that it exists. I may have come across this in an old XKCD comic. Imagine crumpling up a number line on a 2d plane. The goal of this format is to keep numbers that are close in value to be close in proximity to each other. I know my example is not going to be perfect, since I don't know the name or exactly how it is done. Any help would be appreciated.
Examples of wrong formats:
If you chose the range of 4-6, to group these together you would have to wrap to the new line
1  2  3  4
5  6  7  8
9  10 11 12
13 14 15 16

This spiral seems a little better, but if you wanted to choose 2-9, it would be a donut shape around the 1.
13 14 15 16
12  3  4  5
11  2  1  6
10  9  8  7

The format I am looking for would probably end up more like this for the numbers 1-16. I kind of remember it snaking back and forth while kind of spiraling out from the middle.
7   6  1  2
8   5  4  3
9  10 11 12
16 15 14 13

Comment: Whatever the name is, it's closely related to [space-filling curves](https://en.wikipedia.org/wiki/Space-filling_curve) such as the [Hilbert curve](https://en.wikipedia.org/wiki/Hilbert_curve), and the [Hilbert R-tree](https://en.wikipedia.org/wiki/Hilbert_R-tree).
Comment: Wow, that's got to be it, I think I found the XKCD I mentioned too:
https://xkcd.com/195/
Can you add this as an answer so I can mark it correct?
Answer: It's a variant of the Hilbert R-tree, which is related to the Hilbert curve.


What's a good substitution to solve this integral?

Question: Is there a good substitution (or other simple method) to more easily solve this integral?
$$\int \frac{1}{\left(1-\sqrt{1-(\frac{r}{R})^2}\right)^{\frac{3}{2}}}dr$$
Honestly, I was trying  $\frac{r}{R}=\sin(\alpha)$, but the result was complicated...
I appreciate anyone's hints or good ideas.
Comment: Hint: make ur substitution and use $1-\cos(x)=2\sin(x/2)^2$ in the denominator to kill the noninteger exponent
Comment: Did you find a simple integration after apply  $1-cosx= 2 sin ^2 (x/2) $?
Comment: it is not nice but rather straightforward
Answer: HINT:
$$\int\frac{1}{\left(1-\sqrt{1-\left(\frac{r}{\text{R}}\right)^2}\right)^{\frac{3}{2}}}\space\text{d}r=\int\frac{1}{\left(1-\sqrt{1-\frac{r^2}{\text{R}^2}}\right)^{\frac{3}{2}}}\space\text{d}r=$$
$$\int\frac{1}{\left(1-\sqrt{\frac{\text{R}^2-r^2}{\text{R}^2}}\right)^{\frac{3}{2}}}\space\text{d}r=\int\frac{1}{\left(1-\frac{\sqrt{\text{R}^2-r^2}}{\text{R}}\right)^{\frac{3}{2}}}\space\text{d}r=\int\frac{1}{\left(\frac{\text{R}-\sqrt{\text{R}^2-r^2}}{\text{R}}\right)^{\frac{3}{2}}}\space\text{d}r=$$
$$\int\frac{1}{\frac{\left(\text{R}-\sqrt{\text{R}^2-r^2}\right)^{\frac{3}{2}}}{\text{R}^{\frac{3}{2}}}}\space\text{d}r=\text{R}^{\frac{3}{2}}\int\frac{1}{\left(\text{R}-\sqrt{\text{R}^2-r^2}\right)^{\frac{3}{2}}}\space\text{d}r=$$

Substitute $u=\text{R}-\sqrt{\text{R}^2-r^2}$ and $\text{d}u=\frac{r}{\sqrt{\text{R}^2-r^2}}\space\text{d}r$:

$$\text{R}^{\frac{3}{2}}\int\frac{\text{R}-u}{u^2\sqrt{2\text{R}-u}}\space\text{d}u=\text{R}^{\frac{3}{2}}\int\left[\frac{\text{R}}{u^2\sqrt{2\text{R}-u}}-\frac{u}{u^2\sqrt{2\text{R}-u}}\right]\space\text{d}u=$$
$$\text{R}^{\frac{3}{2}}\left[\int\frac{\text{R}}{u^2\sqrt{2\text{R}-u}}\space\text{d}u-\int\frac{u}{u^2\sqrt{2\text{R}-u}}\space\text{d}u\right]=$$
$$\text{R}^{\frac{3}{2}}\left[\text{R}\int\frac{1}{u^2\sqrt{2\text{R}-u}}\space\text{d}u-\int\frac{1}{u\sqrt{2\text{R}-u}}\space\text{d}u\right]$$
Comment: "Hint" of what, exactly?


PHP how to get spesific data from an array based on id list in another array

Question: I am having problems summing specific data from an array based on an ID list in another array. Let's say I have an array like this:
[
    [
        "student_id" => "1",
        "score" => "10",
    ],
    [
        "student_id" => "1",
        "score" => "10",
    ],
    [
        "student_id" => "2",
        "score" => "10",
    ],
    [
        "student_id" => "3",
        "score" => "10",
    ],
]

Then I have a list of students' IDs in the array
$list = [1, 2, 3];

1 = 20
2 = 10
3 = 10

What I want to achieve is to sum the score based on the student's ID, then push it to a new array 1 = 20, 2 = 10, 3 = 10. I do this with a nested loop but it's not working. I have no idea how to do this.
Please give me a hint of how to solve this.
Answer: // assuming your first array is $data.
$result = collect($data)
->whereIn('student_id', $list)
->groupBy('student_id')
->map(function ($group) {
    return $group->sum('score');
})
->toArray();

print_r($result);

the output will be:
Array
   (
      [a] => 20
      [b] => 10
      [c] => 10
   )

Comment: wow this way really simple and really good for the performance
Answer: You can use a combination of loops and conditional statements in PHP.
// Initialize empty array to store the sums
$sums = [];

// Iterate over the original array
foreach ($array as $item) {
    $studentID = $item["student_id"];
    $score = (int)$item["score"]; // Convert score to integer

    // Check if the student ID is in list
    if (in_array($studentID, $list)) {
        // If the student ID already exists in the sums array, add the score
        if (isset($sums[$studentID])) {
            $sums[$studentID] += $score;
        }
        // If the student ID doesn't exist in the sums array,
        // initialize it with the score
        else {
            $sums[$studentID] = $score;
        }
    }
}

// Print the sums
print_r($sums);

Comment: thanks for your referense this work really good also
Answer: $scores = [];
foreach ($data as $student) {
    if (in_array($student['student_id'], $list)) {
        if (!isset($scores[$student['student_id']])) {
            $scores[$student['student_id']] = $student['score'];
        } else {
            $scores[$student['student_id']] += $student['score'];
          }

    }
}
print_r($scores);


'handleSubmit' is not defined

Question: Line 111:22:  'handleSubmit' is not defined. Where and how do I call the handleSubmit
  const MyForm = ( handleSubmit, setvalues, values, handleBlur, handleChange, touched, errors ) => {

  const formik = useFormik({
  initialValues: {
    NameoftheUPSIProject: '',
    InformationSharedBy: '',
    InfoSharedwithrespectto: '',
    InsiderTypes: '',
    ContactPerson: '',
    NameoftheOrganization: '',
    DateofSharing: '',
    ParticularofInformationShared: '',
    PurposeofSharing: '',
    ModeofSharing: '',
  },
  validationSchema: formValidation,
  onSubmit: (values) => {
    apple(values);
  },
});

}
I have removed earlier errors, but I am now facing this error:
https://docs.google.com/document/d/1uwfZR36JMvscNMvdSyB9g6AZE3Gj_sdnuU2-c-XcwTM/edit?usp=sharing
Comment: Does this answer your question? [handleSubmit is not defined](https://stackoverflow.com/questions/71068135/handlesubmit-is-not-defined)
Answer: You should either use props to take in all props to your component, like so:
const MyForm = (props) => {...}

And then access each prop using props.handleSubmit and so on.
Or you can use destructuring likes this:
const MyForm = ({ handleSubmit, setvalues, values, handleBlur, handleChange, touched, errors }) => {...}

You were missing curly braces in your code, which could be why you can't read any of the props
Comment: not working bro
Comment: Did you call the handleSubmit in your code? Because in the provided code, handleSubmit isn't called anywhere.
Comment: yes handle submit called error gone
Comment: So it is working now? If it is, and my answer helped you, you can accept my answer. If its still not working take a look at this https://stackoverflow.com/questions/55237482/formik-onsubmit-function-is-not-working-on-my-code
Also this https://github.com/jaredpalmer/formik/issues/1733
Comment: sorry bro i didn't use props

'handleSubmit' is not defined


Where is the Linked apps page

Question: In this tutorial, it was saying about the Linked apps page.
May I know where is that page?
https://developers.google.com/games/services/console/enabling#a_create_a_linked_application
Answer: "To link your game to a Google API Console project, open the Linked apps page, and then follow the instructions specific to your platform."
Seems that there is no that page any more, instead there is
<code>Play Games Services -> Setup And Management -> Configuration
</code>
menu option in google play console https://play.google.com/console/developers
On that page you can chose either to link your app to new or existing Google APIs project.

Where is the Linked apps page


Are there any ring homomorphisms from $\mathbb{Z} \times \mathbb{Z}$ to $\mathbb{Q}$?

Question: The operations on $\mathbb{Z} \times \mathbb{Z}$ are $(a,b) + (c,d) = (a + c, b + d)$ and $(a,b)(c,d) = (ac,bd)$ respectively. For context, this is to solve the problem on my homework assignment: "Let $R=\mathbb{Z}\times\mathbb{Z}$, $P$ be the prime ideal $\{0\}\times\mathbb{Z}$ and $S=R-P$. Prove that $S^{-1}R\cong \mathbb{Q}$".
My first impression is to use the uniqueness theorem of fraction rings to construct a homomorphism $\Psi: S^{-1}R \to \mathbb{Q}$ using some homomorphism $\psi: R \to S$ so that $\psi = \Psi \circ \pi$ where $\pi: R \to S^{-1}R$ is the projection. I need a homomorphism $\psi$ for this to work, though. Does such a homomorphism even exist, though? After writing and rewriting this answer a few times, my best guess would be the homomorphism $(m,n) \mapsto m$ but I'm not sure if such a homomorphism would work. Do any of you have any ideas? Thank you!
Comment: so $(1,0)(0,1)=(0,0)$?
Comment: @J.W.Tanner I believe so unless my notion of the direct product of rings is mistaken.
Comment: I think what @J.W.Tanner was trying to say is that $\{0\}\times \mathbb{Z}$ is not a prime ideal in $R$. In fact, for two commutative rings $A$ and $B$ with one, the only prime ideals in $A\times B$ are of the form $\{1\}\times \mathfrak{p}$ and $\mathfrak{q}\times\{1\}$, for $\mathfrak{p}\in Spec(B)$ and $\mathfrak{q}\in Spec(A)$.
Comment: in my comment above, it should be the one ideal, not just the one element.
Answer: The map you propose is certainly a homomorphism: it is the composition of the projection $\mathbb{Z}\times\mathbb{Z}\to (\mathbb{Z}\times\mathbb{Z})/(\{0\}\times\mathbb{Z})$, and the embedding
$$\frac{\mathbb{Z}\times\mathbb{Z}}{\{0\}\times\mathbb{Z}} \cong\left(\frac{\mathbb{Z}}{\{0\}}\right)\times \left(\frac{\mathbb{Z}}{\mathbb{Z}}\right) \cong\mathbb{Z}\hookrightarrow\mathbb{Q}.$$
Moreover, an element of $S$ is of the form $(r,s)$ with $r\neq 0$, and so maps to $r\neq 0$, which is invertible in $\mathbb{Q}$.
So you have all the ingredients you need.
Answer: To answer the question in the title...
Let $\phi: \mathbb{Z} \times \mathbb{Z} \to \mathbb{Q}$ be a ring homomorphism. We don't require that $\phi(1,1)=1$.
Let $e_1=(1,0)$ and $e_2=(0,1)$. Then $\phi$ is determined by the images $q_1=\phi(e_1)$ and $q_2=\phi(e_2)$. Indeed, $\phi(a,b)=aq_1+bq_2$, by additivity.
Now, by multiplicativity, $e_1 e_2=0$ implies $q_1=0$ or $q_2=0$. Also $e_i^2=e_i$ implies $q_i \in \{0,1\}$.
Therefore, there are only three possibilities:

$\phi(a,b)=0$ for all $(a,b)$
$\phi(a,b)=a$ for all $(a,b)$
$\phi(a,b)=b$ for all $(a,b)$


Disabling UIBarButtonItems in Nav Bar and Stopping Secondary Popvers

Question: The issue is as follows: I have an iOS 9 app (Swift) with a nav bar that houses a bunch of UIBarButtonItems with segues to several UINavigationControllers that finally display tables, views etc. as popovers. Of course tapping one of these buttons does not automatically disable the other UIBarButtonItems in the nav bar and the user is free to tap them. With a popover already displaying however we get the following warning as this is against the HIG and also grounds for rejection:
<code>Attempt to present UINavigationControllerViewController which is already presenting (null)
</code>
To take care of the issue once a popover is displaying a) the remaining UIBarButtonItems need to be disabled and b) displaying additional popovers needs to be halted.

So what is the best cause of action here? The isBeingPresented flag of the popover's view controller is not available in the governing view controller because one can't create outlets of one view controller in another and the navigationController's viewControllers array doesn't include external navigation controllers or their descendants.
My lame workaround involves a global appIsPresentingPopover Bool which is set to true in viewDidLoad and to false in viewDidDisappear in the mentioned view controllers. That Bool is then tested in the governing view controller's prepareForSegue method to stop additional popovers from displaying. It is also kvo'ed to disable any enabled UIBarButtonItems which now all have an outlet. Ugly!
What is the standard way of handling this common scenario?
Comment: Can you detect when a new popover is presented, and close the other one?  IMO it's best to handle it this way if you can, rather than disable a button. Users would expect to be able to toggle between popovers without having an annoying tap in between.
Comment: Thanks, I completely agree as for the UX and one would of course avoid updating the enabled status of any UIBarButtonItems altogether. The main issue however remains as it is crucial to first close existing popovers before doing anything else to avoid the mentioned warning.
Answer: Surprisingly simple solution and much more elegant than my initial attempt. I added segue identifiers for all involved popups and a UIViewController class variable. In prepareForSegue I set the variable to the destination view controller. Then in shouldPerformSegueWithIdentifier I simply check whether that popover variable is nil. If it is not, I dismiss the UIViewController and set it to nil. Finally I also followed Beau Nouvelle's suggestion and kept those buttons lit so users can switch directly between popovers. Thanks again.
Comment: Brilliant. May as well give your own answer a nice big tick!
Comment: Heh, yeah - works like a charm and is easily extensible.


jQuery menu broken when moving between list items

Question: I've created a custom jQuery horizontal menu with drop downs. Initially it just faded a sub-menu in when hovering on a list item, and faded it out when moving away.
However I want to create an effect where if you move the mouse out of the sub-menu, it  doesn't disappear instantly (e.g. if you overshoot it by a pixel). I was made aware of the hoverIntent plugin in a previous question, but it has an annoying delay when opening sibling sub-menus. So I started from scratch with my own functionality in mind.
My HTML is a standard nested list, ul#menu > li > ul > li. My Javascript is as follows:
var menuVisible = false;
var cancelTimeout = false;

$(document).ready(function(){
  $('ul#menu > li').hover(
    function(){
      menuMouseOver( $(this) );
    },
    function(){
      menuMouseOut( $(this) );
    }
  );
});

function menuMouseOver( $li )
{
  // if one of the menus is down, check which one we're hovering
  if ( menuVisible ) {
    cancelTimeout = true;
    if ( $li.find('>ul').css('display') == 'block' ) {
      // do nothing if we're hovering over current menu
    }
    else {
      // turn off all menus
      $li.parent().find('>li').each( function() {
        menuOff( $li )
      });
    }
  }

  menuOn( $li );
  menuVisible = true;
}

function menuMouseOut( $li )
{
  setTimeout(
    function(){
      if ( !cancelTimeout ) {
        menuOff( $li );
        menuVisible = false;
      }
      cancelTimeout = false;
    },
    2000
  );

}

function menuOn( $li )
{
  $li.css('background-position', 'left bottom');
  $li.find('>ul').fadeIn('fast');
}
function menuOff( $li )
{
  $li.css('background-position', 'left top');
  $li.find('>ul').fadeOut('fast');
}

The following things work:

Moving over a top-level li opens the sub-menu.
Moving away from the sub-menu closes it after 2 seconds (for testing purposes; will be reduced in the final version).
Moving away from the sub-menu and back cancels the timeout and therefore stops the menu from disappearing

However, these don't work:

When moving from one top-level list item to the next, the previous sub-menu doesn't disappear. I want it to fade out straight away, without the normal delay.
If I move across two top-level list items, menuVisible is set to false, which screws up the system. This is because cancelTimeout is set to true when you move over the first sibling, and it is still true as you move to the second sibling.

I'd appreciate any insight into why this happens, and of course, how to fix it.
Answer: Have you tried the Superfish menu jQuery plugin?
I've used it in my project and I think it will solve these problems for you.
Comment: @fudgey: that doesn't do what I want at all. The menu disappears the instant you move your mouse away. I already did that in 5 minutes (by which I mean the jQuery is dead simple).
Comment: Thanks Daniel, the Superfish plugin works pretty well. I'm normally a stickler for plugins with superfluous functionality, but Superfish is pretty minimal even with drop shadows and other pointless crap.
Comment: @DisgruntledGoat: Cool, I'm glad I could help. I've noticed that it's been a week without a better answer. Perhaps you could accept this answer to help others out there who might be looking for questions without accepted answers.
Comment: "Accepted Sep 22 at 23:50" - maybe you're missing the green background color, too?


Binary Data Type in H2, Sql-Server, MySql

Question: I need to store a serialized Object as binary data in a H2 table (also in MySql, SqlServer, Hsqldb, etc, as the app have options to select the database). This object only weights few bytes, it is just a POJO with some Strings, Integers and Boolean values, nothing extraordinary.
I create the VARBINARY(1000) column set the value with a PreparedStatement and save it to the table. My question and my concern is that, this code works in a website and as I read the definition in the H2 official site about the BINARY data type, there they say:

BINARY Type:
  Represents a byte array. For very long arrays, use BLOB. The maximum
  size is 2 GB, but the whole object is kept in memory when using this
  data type. The precision is a size constraint; only the actual data is
  persisted. For large text data BLOB or CLOB should be used.

What worries me is that statement where they say "but the whole object is kept in memory when using this data type". So, how much time actually is this object hold in memory? Until application shutdown?
What I don't (obviously) want is to have this column eating the memory by keeping this column endlessly. I tried to find any other source of information but no luck whatsoever.
Answer: The BLOB type won't be kept fully in memory, so if you are concerned about memory usage you could use that. How much data are you storing anyway?
H2 is an embedded database, I don't think its intended to scale to large amounts of data. If you are talking about the other databases, you should refer to their documentation for details as they are unlikely to behave the same way.
Comment: As I understand `BLOB` data type is for columns beyond the 2GB and as I said, the data only weights few bytes because it is only the serialization of a POJO.
Comment: when you say also in mysql, etc. are you just using `h2` for testing?
Comment: No, the app let the final user to select the final database to use, so I test the same code for all MySql and Sql-Server as well. I only need to store a small amount of bytes but not to keep it in memory as the H2 documentation says. This is why I think `BLOB` is like using a canyon for a fly.
Answer: The best data type for HSQLDB and MySQL is VARRBINARY(max_bytes_length). BINARY(fixed_bytes_length) takes the same amount of space even for the smallest saved object, while VARBINARY takes exactly the length of the saved object. The max_length parameter can be set to a value that is much larger than the maximum anticipated size of the object. Withe these databases, the value is held in memory only when the row of data is accessed.
Comment: Thanks for your answer. One last question: for data type `VARBINARY(max_length)`, what is the measurement of the `max_length` variable? Is it measured in `bytes`, `kilobytes`, `bits` (I don't think `bits` but just in case)?
Comment: OK, good. Thank you. In the respective documentations, they mention some information about the `VARBINARY ` and `BINARY` but they don't mention the unit of measurement, very important though. They may think it is already understood, but terrible mistake, a documentation must always keep a *complete* description of the object trying to describe.


Como pegar item do meio com javascript ou css?

Question: Galera, tenho a seguinte situação:

Esse bloco de divs é gerado randomicamente e nao posso adicionar mais nada nele. Quero arranjar um jeito de saber qual o "item" do meio, com javascript ou css. Tipo no do meio quero uma borda laranja e nos dois laterais quero uma borda verde.
Alguem tem uma solução?
Answer: Pode utilizar js, através do método getElementsByClassName

1

2

3

Esse método irá armazenar todas as ocorrências em um array, e pode acessá-lo pela chave numérica.
Answer: Se a div tiver somente 3 itens, pode ser feito assim:

    .item{
        border: 1px solid green;
    }

    .item:nth-child(even) {
        border-color: orange;
    }

1

2

3

Answer: Você pode usar dessa forma também, caso exista mais de um elemento no centro que necessite de borda laranja:

.corpo .item:first-child,
.corpo .item:last-child {
  border: 1px solid green;
}

.item {
    border: 1px solid orange;
}

Testo 1

Testo 2

Testo 3

Testo 4


How to get multiselect dropdown in AgGrid using Angular

Question: We have AgGrid and we need a multiselect dropdown for one of the column, and we are using Angular 7.
I am able to find multiselect dropdown but not for agGrid Cell.
Please help.
I a able to produce agGrid, tried using below link but unable to get.
https://www.c-sharpcorner.com/blogs/how-to-add-combobox-in-aggrid-or-edit-grid-coloumn-with-combobox
Expected : multi select dropdown in agGrid cell
Comment: Did my answer solve your problem? If yes, please mark me in answer.
Answer: I'll make it simple. It took me 2 days to make one with plain javascript. You can adjust it to your Angular needs.
Include

Style

Customize
var selectedComments = [];

class CommentCellRenderer {
    init(params) {
        this.eGui = document.createElement('span');
        if (params.value !== "" && params.value !== undefined && params.value !== null) {
            this.eGui.innerHTML = params.value;
        }
    }

    getGui() {
        return this.eGui;
    }
}

class CommentPopupCellEditor {
    init(params) {
        this.container = document.createElement('div');
        this.container.setAttribute('class', 'input-widget-popup');
        this._createTable(params);
        this.params = params;

        var commentUids = '';
        var commentNames = '';
        var rowSelectedComments = selectedComments.filter(comment => comment.rowId === params.node.id);
        for (var i = 0; i < rowSelectedComments.length; i++) {
            if (i > 0) {
                commentUids += ',';
                commentNames += ',';
            }
            commentUids += rowSelectedComments[i].uid;
            commentNames += rowSelectedComments[i].name;
        }
        this.selectComment(commentUids, commentNames);
    }

    selectComment(commentUids, commentNames) {
        this.commentList = commentNames;

        var rowNode = gridOptions.api.getRowNode(this.params.node.id);
        rowNode.setDataValue('comment_uid', commentUids);
        rowNode.setDataValue('comment_name', commentNames);
        setTimeout(() => {
            App.autoSizeAll(gridOptions);
        }, 1000);
    }

    getGui() {
        return this.container;
    }

    afterGuiAttached() {
        var that = this;
        $('#commentSelection').multiselect({
            buttonWidth: '100%',
            onChange: function(element, checked) {
                var x = element[0];
                var commentUid = $(x).val().toString();
                var commentName = $(x).text().toString();

                if (checked) {
                    var index = selectedComments.filter(comment => comment.rowId === that.params.node.id).map(function(e) { return e.uid; }).indexOf(commentUid);
                    if (index === -1) {
                        selectedComments.push({
                            rowId: that.params.node.id,
                            uid: commentUid,
                            name: commentName
                        });
                    }
                }
                else {
                    selectedComments = selectedComments.filter(comment => comment.rowId !== that.params.node.id || comment.uid !== commentUid);
                }

                var commentUids = '';
                var commentNames = '';
                var rowSelectedComments = selectedComments.filter(comment => comment.rowId === that.params.node.id);
                for (var i = 0; i < rowSelectedComments.length; i++) {
                    if (i > 0) {
                        commentUids += ',';
                        commentNames += ',';
                    }
                    commentUids += rowSelectedComments[i].uid;
                    commentNames += rowSelectedComments[i].name;
                }
                that.selectComment(commentUids, commentNames);
            }
        });
        this.container.focus();
    }

    getValue() {
        return this.commentList;
    }

    isPopup() {
        return true;
    }

    _createTable(params) {
        this.container.innerHTML = `

        <?php echo COMMENTS; ?>

            <select id="commentSelection" multiple="multiple">
            </select>

`;
        this.commentDropdown = this.container.querySelector('#commentSelection');
        for (let i = 0; i < comments.length; i++) {
            const option = document.createElement('option');
            option.setAttribute('value', comments[i].uid.toString());
            var index = selectedComments.filter(comment => comment.rowId === params.node.id).map(function(e) { return e.uid; }).indexOf(comments[i].uid);
            if (index !== -1) {
                option.selected = true;
            }
            option.innerText = comments[i].name;
            this.commentDropdown.appendChild(option);
        }
    }
}

Reference
{headerName: '', field: 'comment_name', editable: true, cellEditor: 'commentPopupCellEditor', cellRenderer: 'commentCellRenderer'},

Option
components: {
    commentCellRenderer: CommentCellRenderer,
    commentPopupCellEditor: CommentPopupCellEditor,
},

How it looks like
Comment: hey, would you please include by any chance the versions you are using for bootstrap and jquery? I am trying to use your code, it seems to work but the dropdown doesn't get rendered properly, if you could please clarify the include part it would be fantastic :)  at the moment you only have bootstrap-multiselect twice, while I think you have boostrap js and css, jquery js and css, boostrap-multiselect js and css. many thanks.
Comment: Sorry for my late answer. Chosen Version 1.8.7, Typeahead Version 0.11.1, Bootstrap Multiselect Version 2.0, jQuery UI Version v1.12.1
Answer: I have been working with Ag-grid for months and I can tell you it is very difficult to put something customized onto Aggrid cells.
Firstly, you can you use frameworkComponents parameter of GridOptions belonging to the related Ag-grid table.
Usage description:
You have a independent component that providing you to select multiple item in a dropdown element. Let's name this component as MultiSelectComponent
Firstly, import GridOptons from any type of Ag-grid modules. I am using Enterprise.
import { GridOptions, ... } from '@ag-grid-enterprise/all-modules';
import { MultiSelectComponent} from './multi-select-component';

And inside Component class, declare details.
export class Component implements OnInit {
...
columnDefs: any;
...
gridOptions: GridOptions;
this.gridOptions = {
 frameworkComponents: {
  cellCustomComponent: MultiSelectComponent
 }
}

Here we define columns and their options we want. First column definition is containing our custom component in it. According to my  Custom component can shown on Ag-grid in two ways:
1) It can be shown as the grid is ready. It is used with cellRenderer.
2) It can be displayed right after cell is clicked to edit. For this, you must declare the column to be editable as true. Also it is used with cellEditor and cellEditorParams.
Now We are using 1st option. I mean, cellRenderer one. I recommend you the same way too.
this.columnDefs = [
  {
    headerName: 'Names', field: 'names',
    cellRenderer: 'cellDatePicker', pinned: 'left',
  },
  // other columns definitions here
]

Now it is almost ready to display our own custom component right inside the cells under 'Names' column we just defined above. If our custom component is a datepicker, then it is shown as that datepicker. If it is an emoji selector picker, then it is as that is. (For example, click the link for cellEditor and cellRenderer)
My own custom component, datepicker:

Click resource on Aggrid site
Comment: if my answer solved your problem, you kindly can mark it as the answer @akshay-krishna.


Why is my bass clef inverted?

Question: I have downloaded an early printed Beethoven sonata where the bass clef is upside down and looks more like a C?  Why?  What am I missing?
Comment: Can we see a picture?
Comment: Is it https://vmirror.imslp.org/files/imglnks/usimg/6/60/IMSLP51970-PMLP01446-Beethoven_-_Piano_Sonata_No.1_(Artaria).pdf ?
Comment: Voting to close as "needing details or clarity"
Comment: Not sure what you're missing, but we're missing a picture!
Comment: We need a picture. This could be one of the C-clefs.
Comment: "What am I missing"?  Nothing.
Comment: @ttw I am not aware of Beethoven using C clefs in piano music, but at any rate C clefs stopped resembling the letter C several centuries before Beethoven.
Comment: I'm not either, but that was my guess. Of course, irregular engraving practice is another option.
Comment: Please [edit] your question to include an image of the notation and perhaps a link to where you downloaded it from, then your question can be re-opened.
Answer: That's common in old scores. I am quite sure I saw it on 19th century orchestra scores, although I cannot state one in particular.
Wikipedia has the answer.
Check Wikipedia's page on clefs, there is a picture of an "inverted" F-clef:

It is said the F-clef "was, until as late as the 1980s in some cases (such as hymnals), or in British and French publications, written like this".
Comment: @Bonner Well, as I had remarked many times this fancy shape, I felt the question was sufficiently clear. I will post some examples.
Comment: But keep in mind that we're answering *the user's* question. The Wikipedia example curves in the opposite direction from today's F clef, i.e. with the concavity to the right. In that sense it's "like a C." But the 1st edition Beethoven score I linked to still has the concavity to the left, but curves more than a modern F clef (but less than this curlicue); its curvature makes it too "like a C." The question simply isn't clear yet, although as I said the answer is still probably "it was just a practice."
Comment: @Bonner Then I'll wait before posting any example. Which are like the one in Wikipedia, not the one you posted, actually.
Comment: Thanks for contributing! It would be best to wait until the question is clear enough to answer, though. The wikipedia clef example looks quite different than the one on op 2 no 1 (although the main point is the same, that "it was just done that way").

Why is my bass clef inverted?


Get a array of class files inside a package in Java

Question: I need a Class[] of all the class files contained in one of my source packages in Java.
I could n't find a standard method to do it in one shot. If someone can write a function to fetch that list would be really helpful.
Class[] myClasses = yourfunction();  // Return a list of class inside a source package in the currently working project in java

Comment: See here for a manual workaround (it's not fool proof) - http://stackoverflow.com/questions/176527/how-can-i-enumerate-all-classes-in-a-package-and-add-them-to-a-list
Comment: There is no standard way to enumerate all classes in a given package. In some cases it's not even possible (think of an URLClassLoader loading classes from a HTTP URL: there's no standardized way to enumerate files in a folder).
Answer: I am able to solve this problem using normal file I/O and search mechanism. You can check the answer as posted here.
private static List<Class> getClassesForPackage(Package pkg) {
    String pkgname = pkg.getName();

    List<Class> classes = new ArrayList<Class>();

    // Get a File object for the package
    File directory = null;
    String fullPath;
    String relPath = pkgname.replace('.', '/');

    //System.out.println("ClassDiscovery: Package: " + pkgname + " becomes Path:" + relPath);

    URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);

    //System.out.println("ClassDiscovery: Resource = " + resource);
    if (resource == null) {
        throw new RuntimeException("No resource for " + relPath);
    }
    fullPath = resource.getFile();
    //System.out.println("ClassDiscovery: FullPath = " + resource);

    try {
        directory = new File(resource.toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(pkgname + " (" + resource + ") does not appear to be a valid URL / URI.  Strange, since we got it from the system...", e);
    } catch (IllegalArgumentException e) {
        directory = null;
    }
    //System.out.println("ClassDiscovery: Directory = " + directory);

    if (directory != null && directory.exists()) {

        // Get the list of the files contained in the package
        String[] files = directory.list();
        for (int i = 0; i < files.length; i++) {

            // we are only interested in .class files
            if (files[i].endsWith(".class")) {

                // removes the .class extension
                String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);

                //System.out.println("ClassDiscovery: className = " + className);

                try {
                    classes.add(Class.forName(className));
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException("ClassNotFoundException loading " + className);
                }
            }
        }
    } else {
        try {
            String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
            JarFile jarFile = new JarFile(jarPath);
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String entryName = entry.getName();
                if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {

                    //System.out.println("ClassDiscovery: JarEntry: " + entryName);
                    String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");

                    //System.out.println("ClassDiscovery: className = " + className);
                    try {
                        classes.add(Class.forName(className));
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("ClassNotFoundException loading " + className);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e);
        }
    }
    return classes;
}

Comment: Soooo big, there must be an easier way...
Comment: @Illidanek ya you can definitely reduce some lines of code from this code and also a better solution might exists, even I would like to see some shorter and more efficient code that does the same job.
Comment: Good answer...saved my lot's of time
Answer: Did not try this on all VMs, but on a recent Oracle VM there is a shorter way:
Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources("package/name/with/slashes/instead/dots");
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        System.out.println(url);
        System.out.println(new Scanner((InputStream) url.getContent()).useDelimiter("\\A").next());
    }

This will print out the names of the resources in the package, so you can use getResource(...) on them. The call url.getContent() will return an instance of sun.net.www.content.text.PlainTextInputStream which is a VM specific class.
Comment: This doesn't work with jar under jdk 1.8. `sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream` throws NPE on attempt to read from it.


java Parameter index out of range (1 > number of parameters, which is 0 with mysql - simple login

Question: Im trying to check a username and password in  Java (in j creator) but cant get the syntax right.
How do I implement a simple check in the database by passing username and password? Here is the code thats gicing me the problems:
      try
    {
String userN, passW, host, database;
userN = "Michael";
passW = "Blaine22";
host = "localhost";
database = "maintenance_work";

        Connection conn = DriverManager.getConnection
    ("jdbc:mysql://"+host+":3306/"+database, userN, passW);

    conn.setAutoCommit(false);
    ResultSet rs = null;
    PreparedStatement pst = null;

    Boolean user_Check_pass;

    String sql =("SELECT * from operators where user_name = " + user + " and pass_word= " + pass);

        pst = conn.prepareStatement(sql);

        pst.setString(1, user);
        pst.setString(2, pass);
        rs = pst.executeQuery();

        if (rs.next())
        {
             System.out.println ("Username and Password correct");
             user_Check_pass = true;
        }
        else
        {
              System.out.println ("invalid username and password");
               user_Check_pass = false;
        }
    }
   catch (SQLException e)
   {
    e.printStackTrace();
}
    return false;

Comment: Please read a JDBC tutorial or javadoc explaining `PreparedStatement`...
Answer: You need to change your query as follows -
String sql = "SELECT * from operators where user_name = ? and pass_word = ?";

?s are what the setXXX(index, value) methods replace.
Answer: I just needed to change the SQL query string to below in order to pass the parameters! Doh!
String sql = "SELECT * from operators where user_name = ? and pass_word = ?";


Before the primo passaggio is there another passaggio?

Question: I have tried to sing the tune "Twinkle, Twinkle Little Star" in the key of E. It seems to be the easiest key for me. The highest note is C#4.
Something seems to happen on D4. It is like I start losing chest voice and moving into head voice. But I won't call it the passaggio note that some of you guys refer to. That note seems to be on E4.
So before the primo passaggio there is another passaggio?
Answer: Since there are three vocal registers (chest voice, middle voice, and head voice), there are naturally two transition points for a singing voice. These are known as the primo (first) passaggio and the secondo (second) passaggio.
It's possible that what you're experiencing on D4 is a transition between your chest voice and middle voice. However, it's important to note that every individual's voice is unique and can have different passaggi. It might be helpful to work with a vocal coach to better understand your own vocal range and passaggi.
Comment: Three? Richard Miller said that there are five, I think.
Comment: @harryjansson People disagree on how many registers there are and which should be called which, Basically this shows you that registers do not really have a physiological reason.
Answer: Keep in mind that a trained voice should not actually have a passaggio at all! Your vocal apparatus consists of muscles (vocals muscles) and ligaments (vocal cords). Pitch is determined by the tension as well as the weight. This is the reason why our voice get lower if we are sick (as inflammations cause blood to be pumped into the vocal muscles and thus increase the weight).
Now we can control the vocal muscles to have it soft enough to vibrate fully, partially or to only have the vocal cords vibrate. The more vocal muscle vibration we add the stronger heavier and lower our voice gets, the less we add the lighter, more flexible and higher our voice gets.
The concepts of vocal registers is nothing but a few extremes in this: Chest voice is what happens when you have a lot of vocal muscle vibrating, head voice is when you have little to no vocal muscle vibrating. Then you have the voix mixte which is when you have have some amount of vocal muscle vibration.
As I said already pitch depends on weight, so there is a limit on how high or low you can get in some register, which means you need to change into a different register, which is the passaggio. Now as these are just arbitrary points in vocal configuration there can be more registers and thus more passaggios, but traditionally we consider a lower and an upper passaggio.
But this is not a necessity, but a habit. If we can develop control over our vocal muscles we can steplessly add and take mass as we go along. So instead of taking one vocal control to its limits and then having to change we can change the configuration continuously on the way there, eliminating the very concept of registers (not exactly, because we still get registers formed by different techiques, but this is not relevant for the concept of passagio) and instead forming a single, big register that can effortlessly go from the lowest to the highest notes.
Comment: Perhaps trained singers should not have passaggii but I hear how some opera tenors talk about choosing a specific note at which they go into head coice
Comment: I think eliminating passaggios is only feasible for women (and maybe children?) - far too many questions on here bring up chest, head, and mixed voice for me to think that passaggios can be eliminated for men. (I speak as a woman who regularly sings and has a tough time finding any distinction between my chest and head voices.)
Comment: @harryjansson Tbf. not all singing schools follow try to attempt this, and it is hard even if you attempt it to completely get used to habits. But the point still stands, that is, the passaggio is something that is not necessary, but happening because a configuration is kept fixed.
Comment: @Dekkadeci That is not true. But the concept of registers is quite deeply engraved in language of singing, and often no effort is made to get there. Anyone can remove strict registers from their voice, but it takes work. You should be able for example to sing a low note, glissando up an octave, glissando up another octave and glissando back down again without feeling like you hit a wall or break. Then you know you have a good sense of control of your vocal muscles. If you cannot find distinction between registers maybe you naturally have a good feeling for adjusting your voice properly.
Answer: Passaggio can be a region rather than a single pitch.
Some interesting ideas HERE


Under what circumstance can dy/dx be equal to - 0.11/1 where dy = dx

Question: I'm reading through the book "Calculus Made Easy" by Silvanus P. Thompson
In the page 12, there's an example of a ladder of 181 inches resting against a vertical wall and calculating how much the top end of the ladder goes down as we separate the bottom end of the ladder from the wall, i.e. the ratio where dy decrease while we increase dx
At the end of the example. Silvanus says:

And the ratio of dy to dx may be stated thus:
$ \frac{dy}{dx} = - \frac{0.11}{1} $
Its also easy to see that (except in one particular position) $ dy $ will be of a different size from $ dx $

I understand that if $ dy = dx $ then:
$ 1 = - \frac{0.11}{1} $
And this doesn't make sense. What particular position is the author referring to?
Comment: At the right isosceles moment, the top of the ladder is falling at the same rate as the foot of the ladder is moving away from the wall.
Comment: Take a look at:https://www.matheno.com/calculus-1/related-rates/how-fast-is-the-ladders-top-sliding/
Comment: @NoChance In your link the horizontal movement of the ladder's bottom end is also different of the vertical movement of the ladder's top end
Comment: @AndrewChin could you explain further? I agree that at the right isosceles moment the horizontal distance to the ladder's bottom is the same as the vertical distance to the ladder's, but as x changes, y doesn't change at the same rate.
Comment: Consider posting a picture of what you have in the book
Comment: @NoChance Added the pdf (the book is free) as I think it can give better context. Page 12.
Comment: You are correct. There is no way $dy$ can be equal to $dx$. One can prove this since the equation:$\:\left(180-k\right)^2+\left(19+k\right)^2-181=0$ has no real roots, where $dy=dx=k$.
Comment: So the "particular position" stated by the author doesn't exist?
Comment: What the above shows is that $dy,dx$ can't be equal given the values of $x=19$ and $y=180$. The phrase "particular position" may refer to a different value of $x$, which will change the value of $y$ since the ladder has the same length, in which case we'll have a different equation that I don't assume it would be easy to solve. As a result, I can't be sure. Maybe if you make your question like is there a value for $x$ where $dy=dx$, it would be more clear.
Comment: Changing the value of $ x $ will always give the same $ dy/dx $ rate for a ladder of 181 inches
Comment: @Jon No, that's wrong. Redo the calculation as the top of the $181$-inch ladder goes from $180$ to $179$ inches above the ground and you'll get a different value for $dy/dx$, and another different value as it goes from $179$ to $178$, and so on. The "particular position" is not when $y=181$ or when $y=180$, but it does exist. As the ladder continues to slide down the wall, $dy$ and $dx$ are always "of a different size" except at one particular position. That position, as has already been said, is at the right isosceles moment.
Answer: Let the vertical height of the ladder be $y$ and the horizontal length be $x$
Now, whatever position the ladder may be in, the following is always true by pythagoreas theorem.
$$x^2+y^2=181^2$$
Now when you differentiate the equation with respect to $x$, you get
$$2x+2y{dy\over dx}=0$$
$${dy\over dx}=-{x\over y}=-{\cot}{\theta}$$
Now, this rate of change is equal to the instantaneous slope of the ladder. When the ladder is steep (${\tan{\theta}}$ is large), a small increase in $x$ will result in a large decrease in $y$. You can experiment this at home by taking a slab of cardboard and sliding it along the wall and floor of a room. Clearly, the rate of change is equal (${dy\over dx}=1$) only when $x$ is equal to $y$.
Comment: When you take the derivative with respect to $x$ you get $d/dx(x^2)+d/dx(y^2)=2x+0=0$. Also, Note that when $x=y$ $dy/dx=-1$ not $+1$.
Comment: Your differentiation is wrong.
Comment: Isn't $ tan \phi $ = y/x instead of $ x/y $?
Comment: My differentiation is correct. However, if you consider that change in $x,y$ is function of time $t$, then $d/dt(x(t)^2)+d/dt(y(t)^2)=2x(dx/dt)+2y(dy/dt)=d/dt(181)=0$. Check this link:https://www.matheno.com/calculus-1/related-rates/how-fast-is-the-ladders-top-sliding/
Comment: You may refer to your own link to see that my answer is correct. If you think that ${d\over dx}y^2=0$ then please learn some calculus.


Error list that all methods of a package return in Go language

Question: Is there an easy way to know about all errors that methods of a package in Go return?
For example, the net package returns several error types such as AddrError, DNSConfigError, DNSError, and so on. These error types are declared in the net package. However, the net package also returns os.PathError, syscall.* errors, which are errors declared in other packages, in its methods.
I want to categorize all error types the net package returns, and do something for each of these errors as well as writing log message. But, I noticed that http://golang.org/pkg/ site does not provide these returning error types like "ERRORS" sections in http://pubs.opengroup.org/onlinepubs/009695399/functions/write.html page.
Please let me know if there is a way to know these information.
Thanks.
Answer: You would have to write something that:

Parse the package, list all obvious errors (anything that defines Error() string).
Parse all functions that returns error and check all their return paths.

You can look into using go/ast and go/parser.


Android Emulator says "...App isn't responding"

Question: After displaying a new Dialog (actually it is a ContentView) my Android Emulator says "...App isn't responding" with a "Close App"- and a "Wait"-Button.
Is this probably something I screwed up or is this an Emulator related issue? Is there anything I can do to prevent or fix this?
I am a bit affraid that is my fault with something I did not handle correctly so that the App runs into issues on the real device not just the emulator.
I am working with VS 2022 and the "Pixel 5 - API 33 (Android 13.0 - API 33)" Emulator started in Debug of VS.
Any hints?
Comment: Do you add breakpoints in debugging? If so, don't mind this and just click "Wait". If it's ok, could you provide some code so that I can reproduce your situation.
Answer: This can happen even if your code is good. Once it happens, its likely to keep happening.

After you click "Wait", are you able to interact with the dialog? If so, then its likely just emulator has gotten messed up.

Fixes to try:
(1) Delete app from emulator, download it again. This helps ensure a clean start.
(2) IF still happening, Use Tools / Android / Android Device Manager. Select emulator, Stop it if running, do "Reset to Defaults" (just clears some internal settings) or "Factory Reset" (completely resets device to original factory condition). Quit and Restart Visual Studio.
Comment: Restarting studio did it for me. Thx!
Answer: My app was very simple and it worked on physical devices without any problems. But on an emulator, I was receiving this message every couple of seconds ("App isn't responding").
My emulator was set to have only 1 GB of RAM. I increased the amount to 2GB and the problem disappeared. I was emulating Pixel 5 with API 33.
Answer: There is also another possible source of this issue. A very serious one.
If you start receiving this - you need to check that

all the code that interacts with UI is doing it on the UI thread.
all objects that are passed to methods of the UI elements you are
calling are created on the UI thread as well.

Otherwise your UI will become unresponsive at some point and there'll be trouble. MainThread.BeginInvokeOnMainThread is your frined here
Also another important thing is avoiding setting control properties manually and instead using bindings wherever possible.


How to design a contrast matrix with combined levels for a categorical variable?

Question: I wish to make a contrast matrix in the case of a linear model.
I have one factor with three levels: T, N and A.
I want the contrasts T vs N, T vs A and T vs (N and A combined).
It is the last contrast with combined levels that cause troubles.
The "correct" result I can get by redefining N and A to a new combined level L and then make a one column contrast matrix T = 1, L = -1.
But how to do it when this level is split into two?
The T = 2, N = -1, A = -1 column does not give the result of the above one col contrast.
I'm implementing it in R.
The number of observations are T=30, N=14, A=15
Answer: If the correct result is obtained by T=1 and L=-1, then I would consider using T=1,N=-1,A=-1.


Angular2 - Accessing parent component's variable from child component

Question: I want to access a variable on the parent component from the child component and do something with it. Here is how I am doing it but it looks like its not working as it suppose to:
parent.ts
import {Component,DynamicComponentLoader,ElementRef,AfterViewInit} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ChildComponent} from './child.ts';

@Component({
    selector: 'app',
    template: `<div #child></div>`
})
class AppComponent implements AfterViewInit{

    public parentValue = "some value."

    constructor(private _loader:DynamicComponentLoader,private _elementRef:ElementRef) {}
    ngAfterViewInit(){
        this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child').then(child => {
            child.instance.log = this.callback;
        });
    }

    callback(){
        console.log(this.parentValue);  //logs undefined rather than "some value"
    }

}

bootstrap(AppComponent);

child.ts
import {Component} from 'angular2/core';

@Component({
    selector: "child-component",
    template: "<button (click)='logParentValue()' >Log Value</button>"
})
export class ChildComponent{
    log:any;
    logParentValue(){
        this.log();
    }
};

When I try to log the value of parent component's variable from the child component it always logs undefined. Any solution to this?
Answer: It seems the scope of the method is not preserved the way you pass it.
It works when passed as closureized arrow function
ngAfterViewInit(){
    this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child').then(child => {
        child.instance.log = () => this.callback();
    });
}

https://plnkr.co/edit/VQ3c2Lv5KEzHUa2ZbGLk?p=preview
Comment: The `=>` works like `.bind(this)`. `() => this.callback()` makes `this.callback()` execute with `this` being `AppComponent` while without it `this` is `ChildComponent`
Comment: You can change the signature like `(x) => this.callback(x);`
Comment: Wow that worked but I don't get it how is it working?
Comment: Your solution worked but it produced another problem now I am not able to pass argument to the parent in the callback. Any argument passed to the log function from child is `undefined` in parent. Why is that so?


drupal 7 default table to store form values

Question: I am new to drupal and creating a module consist of a form. Now I want to store values in database, please tell me what is the default table in drupal to store form values?
Like in WordPress we have wp_option table to save data.
Is there any default table in drupal or I have to create new one?
What is the exact use of node table?
Comment: Where you got the idea there is any default table for form data? Each module provides it's own forms and it's own db tables. For example there is core node.module, but it's tables have nothing to do with anything else. Have you read docs and seen Examples project?
Answer: You can use Drupal variable system, please read the following article: https://www.drupal.org/node/1111260
You can create you own table, just use hook_schema for it: https://api.drupal.org/api/function/hook_schema/7
If you to get information from your users by form and store it, please check the module webform:  https://www.drupal.org/project/webform
Node table used for storing main information about nodes (it's some type of content). Node can by "Article" or "News", etc. More you can read here: https://www.drupal.org/documentation/modules/node
Answer: The default table to store values in database is the variable table; you can use variable_set() to store values and variable_get() to get those values.
//Example:
variable_set('app_id', $form_submit['values']['app_id']);
variable_get('app_id');

function test_form_submit($form, &$form_state) {
  $app_id = $form_state['values']['app_id'];
  $app_secret = $form_state['values']['app_secret'];
  $app_code = base64_encode($app_id . ':' . $app_secret);

   if ($form_state['values']['app_id'] && $form_state['values']['app_secret']) {
     variable_set('app_id', $form_state['values']['app_id']);
     variable_set('app_secret', $form_state['values']['app_secret']);
     drupal_set_message(t('App Code data Saved app_id= ' . variable_get('app_id') . ' app_sec=' . variable_get('app_secret')));
  }
}


Outlook 2010 Room list empty but

Question: I've created a room list and added rooms to it using this method http://blogs.technet.com/b/exchange/archive/2010/04/14/3409791.aspx but as in the room finder, i can see the group i created in the show room list, but in Choose available room it's empty, although in the suggested times i can see them.
As soon as i remove the cached mode for outlook i can see the rooms, and as soon as i re-enable the cached mode, they disappear. Any thoughts?
Comment: Did you rebuild the GAL and download it to Outlook? If not it runs on a schedule and will happen *eventually*, though forcing them will make this much quicker.
Comment: unfortunately i did it...  [edit] i did it twice and it seems to work!
Comment: Worked for me! thanks! don't know why it wasn't working first time.
Answer: I had a similar issue. It may have appeared by now, but the issue is related to the address book needs to be downloaded to the client.

Outlook 2010 Room list empty but


CI for logistic regression

Question: What does it means if no CI was given for binary logistic regression analysis in SPSS output?
Comment: If you made a screenshot of SPSS output, post it on [imgur](http://imgur.com) and give us the link or we can insert the picture in your post for you. It would also be better to [register](http://stats.stackexchange.com/faq#login) your account.
Comment: I would suggest you probably have linear separation of your data.  The "signature" of this is large coefficients followed by extreme standard errors.  You have categorical variables, so this usually means that one of the categories has either $0\text{%}$ or $100\text{%}$ response.
Answer: I expect that you have discovered the Hauck-Donner effect in logistic regression where the likelihood flattens out and gives a much too large estimate of the standard error using Wald techniques.  You need to find a tool that will give results based on likelihood ratios rather than Wald techniques when this happens.
Answer: It looks like that the standard errors for your coefficients (B) are so large (look at the column named S.E.) that the values of $\exp(B + SE)$ are practically infinite. You probably need a larger sample size or more relevant variables. Basically you couldn't reject the null hypothesis (no effect) with your model.
Comment: I also would suggest to investigate the existing data base for anomalies...
Comment: In addition to what @user765195 wrote about overall sample size, you probably need to watch out for specific categories of predictors that have sample sizes in the single digits.

CI for logistic regression


TypeScript Interface incorrecly extends interface. Types of property 'then' are incompatible

Question: Before voting down for unknown reasons, please read my profile or explain, help to edit the question or asking me for further information. That would even help me further.
I searched stackoverflow and googled the internet, but I didn't find any solution
I am trying to create an angular app with typescript but when I try to build:

typings/angularjs/angular.d.ts:1419:15 - error TS2430: Interface 'IHttpPromise<T>' incorrectly extends interface 'IPromise<IHttpPromiseCallbackArg<T>>'.
        Types of property 'then' are incompatible.
tsc --version
  message TS6029: Version 1.5.3

bower.json
{
  "name": "AngularTypeScript101",
  "version": "1.0.0",
  "dependencies": {
    "angular": "~1.4.0",
    "angular-route": "~1.4.0"
  }
}

tsconfig.json file:
{
  "compilerOptions": {
    "module": "none",
    "target": "ES5"
  },
  "files": ["app.ts"]
}

I must use Angular 1.4. This is also my first typescript project. Please help.
Comment: Is it possible that promise chaining didn't exist in AngularJs 1.4? I remember back when I worked with this library and there was a point where you could call 'success' instead of 'then' on a promise.
Comment: Hi @Mickers. I don't know but perhaps tsc 1.5 doesnt work with angular 1.4. What do you think?
Comment: In my opinion I'd never use anything lower than 1.5.6 in AngularJs as that's when components came into play. Currently the latest version is 1.7.8 but I'm not sure what all has changed.
Comment: I have to use 1.4 because of legacy
Comment: I found [this](https://stackoverflow.com/questions/47937374/ihttppromise-incorrectly-extends-ipromise-with-typescript-2-5) which may solve your problem
Answer: Install a newer version of your typing file. You can find one here.
Comment: I will accept your answer but you  should provide a example to how   to get the latest version for angular 1.4 in my case. thanks


Adding working checkboxes to a contact form

Question: I am trying to add checkboxes to my contact form. I have a working contact form that with 3 checkboxes. When I place the php code that I found on this page (send checkbox value in PHP form) then my checkboxes are no longer clickable BUT when the email sends all three checkboxes appear in the email. I think that there must be a simple fix somewhere but I have spent the whole live long day working on it and this is as far as I have been able to get.
How do I get the checkboxes clickable AND have the selected box be included in the email?
Here is my html

    <form id="contact" action="html_form_send.php" method="post">
    <fieldset title="About you">
    <legend>About you</legend>
    Name
    <input type="text" name="name" id="name" tabindex="10"   class="txtinput" placeholder="Your name" required>
  Email
  <input type="email" name="email" id="email" tabindex="20" class="txtinput" placeholder="valid email" required>
  </fieldset>
  <fieldset title="Your turn">
  <legend>Your turn</legend>

What, exactly then, are you after?

checkbox1

   <input type="checkbox" id="checkbox-1" class="regular-checkbox big-checkbox" value="Yes" />

checkbox2

    <input type="checkbox" id="checkbox-2" class="regular-checkbox big-checkbox" value="Yes" />

checkbox3

    <input type="checkbox" id="checkbox-3" class="regular-checkbox big-checkbox" value="Yes" />

      Write your comments here
     <textarea id="discourse" name="discourse" tabindex="30" class="txtinput" rows="7" placeholder="This is where your thoughts go">
     </textarea>

   <input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset">
   <input type="submit" name="submit" id="submitbtn" class="submitbtn" tabindex="40" value="Send away!">

And here is my php
          <?php
if(isset($_POST['email'])) {

          // CHANGE THE TWO LINES BELOW
          $email_to = "email@example.com";

          $email_subject = "website feedback";

          function died($error) {
          // your error code can go here
        echo "We're sorry, but there's errors found with the form you submitted.

";
         echo $error."

";
         echo "Please go back and fix these errors.

";
         die();
         }

          // validation expected data exists
         if(!isset($_POST['name']) ||
         !isset($_POST['email']) ||
         !isset($_POST['discourse'])) {
         died('We are sorry, but there appears to be a problem with the form you submitted.');
    }

         $name = $_POST['name']; // required
         $email_from = $_POST['email']; // required
         $discourse = $_POST['discourse']; // not required  $comments =    $_POST['comments']; // required

         $error_message = "";
         $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
         $error_message .= 'The Email Address you entered does not appear to be valid.
';
          }
          $string_exp = "/^[A-Za-z .'-]+$/";
          if(!preg_match($string_exp,$name)) {
          $error_message .= 'The Name you entered does not appear to be valid.
';
           }
          if(strlen($discourse) < 2) {
          $error_message .= 'The Comments you entered do not appear to be valid.
';
          }
          if(strlen($error_message) > 0) {
    died($error_message);
           }
          $email_message = "Form details below.\n\n";

          function clean_string($string) {
          $bad = array("content-type","bcc:","to:","cc:","href");
          return str_replace($bad,"",$string);
          }

          $email_message .= "Name: ".clean_string($name)."\n";
          $email_message .= "Email: ".clean_string($email_from)."\n";
          $email_message .= "checkbox1: ".clean_string($checkbox-1)."\n";
          $email_message .= "checkbox2: ".clean_string($checkbox-2)."\n";
          $email_message .= "checkbox3: ".clean_string($checkbox-3)."\n";
          $email_message .= "Comments: ".clean_string($discourse)."\n";

          $checkbox1= $_POST['checkbox1'];
          if ($checkbox1!= 'Yes') {
          $checkbox1= 'No'; }

          $checkbox2= $_POST['checkbox2'];
         if ($checkbox2!= 'Yes') {
         $checkbox2= 'No'; }

         $checkbox3= $_POST['checkbox3'];
         if ($checkbox3!= 'Yes') {
         $checkbox3= 'No'; }

         // create email headers
         $headers = 'From: '.$email_from."\r\n".
         'Reply-To: '.$email_from."\r\n" .
         'X-Mailer: PHP/' . phpversion();
         @mail($email_to, $email_subject, $email_message, $headers);
         ?>

          <?php
         $checkbox = $_POST['value']
          //Will return either "checkbox1" or "checkbox2" or "checkbox3".
          ?>

         <?php
          }

         die();
           ?>

Answer: If the checkboxes aren't clickable then it is most likely that some other element(s) are sitting above them. Using your browser's developer tools is the quickest way to discover this. The PHP does not affect whether they are clickable or not.
If I were to guess it would be that their labels are sitting above them. (Note that empty elements like these should be avoided.)
The checkboxes (and other form elements) must have a name attribute in order to be submitted with the form.
Comment: I have added and removed different elements all day and it really has not changed anything so maybe the bigger problem is about what you said that the labels are sitting above and empty elements. I again added the "name" element as you said to do, but when I tried to remove the divs and move the label above instead then the checkboxes disappeared altogether. Or rather it appeared that my labels were sitting on unclickable boxes so I put things back the way they originally were. How can I use the label without losing the checkbox?
Comment: Use your browser's developer tools to discover whether something is above the checkboxes. (Right click and Inspect Element, or similar). You could also type something in the labels, or remove them. If something is above them then you use CSS to correct this.
Comment: When I change the elements to the following then the boxes are selectable. However, instead of marking them with a checkmark, the content of the "value" element automatically appears in the box and the box contents do not appear in the email.
Comment:
checkbox1
Comment: I have tried and tried to make code above post here correctly. I don't get it. It won't work.
Comment: The `type` should be `checkbox`, you seem to be using class-names.
Comment: I found another good example of what I am trying to do. I keep trying different things but nothing is working right. With this example I have the checkboxes working but I removed the php for them because I was getting error messages.
Comment:

Which buildings do you want access to?
Acorn Building
Brown Hall
Carnegie Complex
Comment: I have spent another whole day working on this and gotten nowhere. No matter what I try, or whose code I try from all the examples on the internet, the selected checkbox info does NOT append to the email. So there must be something else going on since this coding works for other people.
Comment: Presumably your code has changed a lot since your original post? (At least, it should now include the name attributes.) In which case, you might start a new question, so that we can see more clearly the code you are now working with. Unfortunately, there is a chance that it might be closed as a duplicate, but I think it should have changed significantly enough to prevent this. (I can't guarantee it!)


Java - continuously check if the new value in an arraylist is unique

Question: I have an arraylist full of usernames that I am hoping to display on a webpage. At the moment my arraylist looks like this:
[user=johndoe, user=sampletest, user=johndoe, user=myusername, user=myusername, user=terryh, user=terryh, user=johndoe]
How do I get my arraylist to look like this:
[user=johndoe, user=sampletest, user=myusername, user=terryh]
I've tried other answers but none of them seem to work for me
Comment: Use a `Set`. Not a `List`.
Comment: "I've tried other answers but none of them seem to work for me" - then they are being used out of context and/or incorrectly. It would be beneficial to describe the *actual* problem/symptoms encountered (preferably with real code), not merely the task.
Comment: @BoristheSpider This recommendation is correct. If you are 100% dead set on using a List, then you must call `contains(element)` before adding, but this is expensive O(n) operation where `n` is the size of your list. A `Set` will handle this automatically in constant time.
Comment: Use a data structure that makes this easier, e.g. a `Map`.
Answer: You may want to simply stop using ArrayList and rather, use a Set. Since all of the element are users, you can discard user= before each element, but I'll keep it in the following code for continuity.
Set<String> userSet = new LinkedHashSet();

For example, in the code below:
public static void main(String[] args) {

    Set<String> userSet = new LinkedHashSet<String>();

    userSet.add("user=johndoe");
    userSet.add("user=sampletest");
    userSet.add("user=johndoe");
    userSet.add("user=myusername");
    userSet.add("user=myusername");
    userSet.add("user=terryh");
    userSet.add("user=terryh");
    userSet.add("user=johndoe");

    for (String user : userSet) {
        System.out.println(user);
    }
}

The output is just:
user=johndoe
user=sampletest
user=myusername
user=terryh


Are those that fish more often more likely than a one-timer to catch a specific fish?

Question: I live in the Northern Territory, Australia where for the second year running the government and commercial entities have created a 1 million AUD fish competition to encourage tourism. One tagged and released barramundi if caught anywhere in the many waters within the NT will net the fisher $1 million. My question is given we are talking about a single fish with free reign to travel, are the odds of catching it increased by the number of times someone has a go? I'm inclined to think a person fishing for one day in a single spot has as much chance as a person who goes to a number of places even daily, as this fish is a moving target with a huge playing field. But I am not a statistician. Please enlighten me! PS I think for statistical purposes we would have to disregard the skill of the fisher and their knowledge of waters. Or does that come into play?
Comment: Probabilistically it seems to be the same question as this one: http://stats.stackexchange.com/questions/137711/are-your-chances-of-dying-in-a-plane-crash-reduced-if-you-fly-direct/138195#138195
Answer:
My question is given we are talking about a single fish with free reign to travel, are the odds of catching it increased by the number of times someone has a go?

Almost certainly yes. Compare trying to catch the fish on $n$ days at a given spot compared to trying to catch it on $n - 1$ days. It seems possible to me that even if the fish happened to be present every time, you happened to miss it $n - 1$ days in a row and have a new chance to catch it on the $n$th.

I'm inclined to think a person fishing for one day in a single spot has as much chance as a person who goes to a number of places even daily

That seems to require the fish to be so mobile that its position on one day is totally unrelated to its position on the previous day, which seems very unlikely.


Custom output for user profile list

Question: I have a "user list" view, which displays an "unformatted list" of user accounts.
While the row display is controlled via views-view-unformatted.tpl.php and customizing it works, the row plugin "user" in views/modules/user/views_plugin_row_user_view.inc directly outputs the user profile into the row.
Now as I already have a customized user-profile.tpl.php I cannot customize it for both view row and user profile page...
How do I implement custom display of user profiles in the user list, then?
Answer: It's trivial, but—did you try changing the row plugin to Fields instead of User?
With fields, you have granular control over the display of the user profile, so this might in effect be what you're looking for.

Custom output for user profile list


generator learns generating features in GAN

Question: In Image generation using GAN, what if image features are given as input instead of Image to the discriminator? will generator generates features?
Any kind of reference is helpfull
Comment: That definition would need to be differentiable, otherwise propagating discriminator gradients to the generator would be almost infeasible (not impossible, though)
Comment: What do you mean by "image features"?
Comment: edges lines and any other features instead of an image directly
Comment: @Firebug Thank You
Answer: Consider the following GAN, where $\mathcal D$ is a discriminator and $\mathcal G$ is a generator.
$$\min_{\theta_\mathcal D, \theta_\mathcal G} \mathcal {L}_{\mathcal D}(\mathcal D(X),\mathcal D(\mathcal G(Z)))$$
$X$ represents batches of real data and $Z$ represents batches of random generated numbers.
If $X$ are "image features" as you defined them, i.e. description of lines and other geometric features, then yes, $\mathcal G$ can theoretically learn how to generate them.
This represents two issues, however: (1) you need to represent these features at once for the real images, with tensor notation, which invariably leads to loss of information, and (2) you need to reverse the process to check the quality of generated images.
Non purely convolutional architectures, such as Graph Neural Networks, may ameliorate the issues however (though I'm not sure how to represent a curved contour in a graph embedding).
Comment: @SSVarshini yes, the generator will learn to generate whatever you feed as real data to the discriminator
Comment: Is the output of the generator is features of input data after training?
Comment: In this case how to evaluate the generator. If we give Image input we can use the inception score to evaluate the generator


Why do we sample from the uniform distribution in Metropolis-Hastings for acceptance?

Question: For each iteration of the MH, sample $x'=q(x|x')$, then the acceptance probability is computed:$$A=\min(1,a)$$
where
$$
\alpha=\frac{p(x')q(x|x')}{p(x)q(x'|x)}
$$
Now, I've seen that the algorithm samples from a uniform distribution $$
u\sim U(0,1)
$$to set the new sample as$$
x=x'
$$if $u≤A$, retain $x=x$ otherwise.

I have seen some derivation on how the MH algorithm samples from the target distribution $p$ as the stationary distribution of the Markov chain:
$$
p(x'|x)=q(x'|x)A
$$ if $x'≠x$, otherwise$$
p(x'|x)=q(x|x)+\sum_{x≠x'}q(x'|x)A
$$
Now what does the sampling from the uniform distribution have to do with deciding whether to accept the proposal $x'$ or retain $x$?
Isn't it sufficient to accept the proposal if $A>0.5$?
Answer: The (simplest) validation of the Metropolis-(Rosenbluth-)Hastings algorithm is that the associated Markov kernel $K$ satisfies the so-called detailed balance equation
$$\forall\ x,x^\prime,\quad p(x)K(x,x^\prime)=p(x^\prime)K(x^\prime,x)\tag{1}$$
since (1) implies that $p(\cdot)$ is stationary. This Markov kernel measure writes as the mixture
$$K(x,\text dx^\prime)=q(x^\prime|x)\alpha(x,x^\prime)\,\text dx+\int\{1-\alpha(x,y)\}q(y|x)\,\text dy\,\delta_x(dx^\prime)\tag{2}$$
where $\delta_x(dx^\prime)$ denotes the Dirac measure at $x$. This representation means that the acceptance probability $\alpha(x,x^\prime)$ is crucial for the stationarity property (1) and cannot be replaced with
$$\displaystyle{\mathbb I_{\displaystyle\alpha(x,x^\prime)>0.5}}$$
which would lead to another stationary distribution, as can be checked on a simple example.
Here is for instance a Binomial target $\mathcal B(.1)$ and a Uniform $\mathcal U(\{0,1\})$ proposal, where the
$$\displaystyle{\mathbb I_{\displaystyle p(x^\prime)>0.5p(x)}}$$
acceptance step is failing to recover the target:
p=function(x)ifelse(x,.1,.9)
x=y=sample(0:1,N<-1e3,rep=TRUE)
for(t in 2:N)x[t]=ifelse(p(y[t])>.5*p(x[t-1]),y[t],x[t-1])

since it returns a point mass at zero instead:
summary(x)
Min.   Median  Mean   Max.
0.000  0.000   0.001  1.000

the explanation being that $0$ is a fixed (or cemetery) state, $1$ being transient.
In practice, implementing a simulation from the kernel $K$ means

selecting between the Dirac (reject) and the non-Dirac (accept) parts of the kernel in (2), and then
simulating from the selected part (which is immediate when the Dirac part is selected).

The non-Dirac part is selected with probability
$$\int \alpha(x,x^\prime)\, q(x^\prime|x)\,\text dx\tag{3}$$
whose unbiased estimator is
$$\mathbb I_{\displaystyle U<\alpha(x,X^\prime)}\qquad \text{when}\ U\sim\mathcal U(0,1)\,,\ X^\prime\sim q(x^\prime|x)$$
Hence simulating the Uniform variate $U$ is a practical (and standard) way to achieve the realisation of an event with probability (3). In simulation terms, $U$ is called an auxiliary variable in the sense that it is not connected with the original problem of generating a Markov chain from the kernel $K$.
Note that the above explanation inverts the usual steps of a Metropolis-(Rosenbluth-)Hastings algorithm, where $X^\prime$ is first generated, then used to decide between the Dirac (reject) and the non-Dirac (accept) parts of the kernel. This double use of $X^\prime$ is both correct and more efficient than generating an independent $X^\prime$ from
$$q(x^\prime|x)\alpha(x,x^\prime)\Big/ \int \alpha(x,y)\, q(y|x)\,\text dy$$
which most often multiple rejections.
Comment: Accepting the kernel measure part for now, they now makes sense to me. I will take my time understanding this answer particularly the formalism involved in the kernel measure (which was not introduced in my book) thank you very much


Generate a video stream from Basler camera grabbing loop

Question: I am a beginner in video streaming and handling.
I need to take the stream from a Basler GiGE camera and display it in a web container.
I am using the Basler.Pylon C# API to access the camera and grab images one by one. from the IGrabResult object returned, I can access various parameters such as width, height, stride, and of course the byte buffer.
On my PC, I can easily display that in an image window, but what do i need to do to display that in an ASP.NET web application?
EDIT
I am not looking for code but more for guidelines, if someone could explain how video streaming works in general, that would work too
Comment: There is a quite good overview of the "whole video streaming works" here: https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Live_streaming_web_audio_and_video - you can then google on RTSP or HLS C# for example
Answer: Video streaming is quite specialised and in general I would say if you want to stream high quality video over the internet to multiple end suers, its easiest to use a dedicated video streaming server rather than try to build one yourself.
Dedicated video streaming servers can be provided via a hosted service (e.g Vimeo), be a commercial server you install and run (e.g. Wowza) or a freeware streaming server you install and rune (e.g. GStreamer), so you have options there.
A a general rule, the streaming server will break your video into chunks and create multiple bit rate copies of your video. This allows a client to use Adaptive Bit Rate streaming (ABR) and download your video chunk by chunk, selecting the bit rate version for the next chunk depending on the current device and network conditions. HLS and MPEG-DASH are exmaples of ABR streaming protocols.
On a web page you then need a HTNML5 player which can understand this streaming protocol - again there are many examples such as the freeware Shaka and Dash.js players. Integrating these into a web page is very straightforward.
You can observe these in use on services like Netflix and YouTube which will often start at a lower bit rate to ensure a fast start and then 'step up' to higher bit rates until the optimal one for the current network conditions and device is reached. See here for some info on how you can see a graph of this when watching YouTube, for example:

https://stackoverflow.com/a/42365034/334402

Having said all the above, it is worth nothing that your case seems to be dealing with a stream of still images. Although all video is really a stream of still images under the covers, it may be that your image is changing infrequently, and hence you may not need some of the techniques above - a lot of the technology of video streaming is to deal with the very large amount of data streaming 30 or 60 high quality frames per second from a server to a client.
If your stream of images, for example, was one every 30 seconds then it may, as Nisus says, be just as easy to simply display the images in your web page and have the web page or app poll the server every 30 seconds (using ASP.NET AJAX in your case) to download the new image.
Answer: You have at least two options - first one is producing series of jpeg-images every few seconds and show them one by one on client using  tag and simple javascript code. Second option is to generate and stream mp4-video and show it on client with some COM-windows media player or html5 control.


Will upgrading my database from 2005 --> 2008 make my applications fail?

Question: We have a couple of databases on our server.
We would like to upgrade these databases to sql 2008.
Is there any chance that some application features won't work on 2008 that did work on 2005?
I was told that sql 2008 was 100% backward compatible with 2005.
Answer: No release of SQL is 100% backward compatible. With every release, there is a well documented list of deprecated and discontinued features, and SQL Server 2008 is no different. The list is published at SQL Server Database Engine Backward Compatibility. This contains a list of features no longer supported on SQL 2008, like:

sp_addalias
DUMP and LOAD statements
BACKUP LOG WITH NOLOG/BACKUP LOG WITH TRUNCATEONLY
BACKUP TRANSACTION
DBCC CONCURENCYVIOLATION
sp_addgroup/sp_dropgroup/sp_changegroup/sp_helpgroup
sp_makewebtask/sp_dropwebtask/sp_runwebtask
sp_enumcodepages

In addition, no SQL Server feature is ever discontinued without ample heads-up warning. All features discontinued in SQL 2008 were on the list of deprecated features in SQL 2005. You can use SQL Profiler to monitor your SQL 2005 application and watch for the events:

Deprecation Announcement Event Class
Deprecation Final Support Event Class

The first event will fire every time your application uses a feature on the 'endangered' list. The second event will fire when you use a feature that will be discontinued in the next release.
Finaly there is the SQL Performance counter for deprecated features, see What deprecated features am I using?:
<code>select instance_name as [Deprecated Feature]
  , cntr_value as [Frequency Used]
from sys.dm_os_performance_counters
where object_name = 'SQLServer:Deprecated Features'
and cntr_value > 0
order by cntr_value desc
</code>
Between all the available documentation and infrastructure to monitor for deprecated features, you have plenty of means to figure out if your application is using any discontinued features.
Now that being said, unless you use features from dark ages of SQL Server 6.0, your application will likely run unaffected on SQL Server 2008. There are plenty of reasons to upgrade, and primarily I always cite page compression, which is literally a big performance boost at free cost (I exaggerate for dramatic effect, but only slightly).
You should go ahead and upgrade, but do it smart:

Run the upgrade advisor, read its advice
Have a test environment, deploy your application on test first
Have a comprehensive battery of functional tests to perform, validate that your product still does work as advertised. If you can measure test code coverage try to reach some 85-90% coverage
Have an exit strategy if things go bust. Keep in mind that an upgraded database can never be downgraded back. So keep safe copies of the SQL 2005 database files in case you are forced back. Have a technology plan for how to apply post-upgrade transactions back to 2005 if needed, or have a business plan to explain why transaction were lost (I'm not kidding, it may be a perfectly acceptable solution).

So depending on how precious your data is you want to apply all, some, or none of the above. I may say that if you were in the 'all' boat, you probably wouldn't have asked the question to start with ;) so probably some of the advice above applies to you.
Comment: thx mate
best answer!!
Answer: There's no way we can tell you what your applications will do.
I think your best course of action is to have a second server which runs SQL Server 2008, migrate the databases to it (perhaps one at a time, slowly), and if there are any problems switch back to the SQL Server 2005 server.
This does require two servers (physical or virtual), but gives you perfect recoverability in either case.
Comment: This should really happen in a test environment first - which assumes you have test plans for the applications as well. Also when is the point of no return? The ability to go back to the previous version assumes that the problems are struck immediately or soon after cutting across. What happens if you hit a problem a week after the cutover - is going back to a week old data acceptable?
Comment: well we are actually running one db on sq 2008 now but the application is that large we can't run through all the possible scenario's.
but until now no problems whatsoever.
thx for the response (+1)
Comment: Have you run the upgrade advisor & taken it's advice?
Answer: One good test is to run the Microsoft SQL Server 2008 Upgrade Advisor.  Microsoft SQL Server 2008 Upgrade Advisor analyzes instances of SQL Server 2000 and SQL Server 2005 in preparation for upgrading to SQL Server 2008. Upgrade Advisor identifies feature and configuration changes that might affect your upgrade, and it provides links to documentation that describes each identified issue and how to resolve it.
You can download it for free here: http://www.microsoft.com/downloads/details.aspx?FamilyID=f5a6c5e9-4cd9-4e42-a21c-7291e7f0f852&displaylang=en
You can run this in production, but as was said above, a test environment is always best.
Comment: thx i'll try this for sure


Gtest: Access auto variable globally across multiple tests

Question: I need to set global variable type that can be used by multiple tests and ideally by all tests in multiple test files.
Please find my script below because of which I am getting the following error: error: non-static data member declared 'auto'.
Ideally I would like to know how I can declare this global variable such that it can be used across multiple .cpp files. Any help would be highly appreciated!
Thanks
customerTest.cpp:
namespace {
    class custTest : public ::testing::Test {
    protected:
        custTest() {
            type = new TYPE();
        }
        virtual ~custTest() {
            delete type;
            type = nullptr;
        }
        auto type; //this is the global variable that I would like to use across multiple tests
    };

    TEST_F(custTest, openPort) {
        type->defineMap();
        ...
    }

}

Comment: How should the compiler deduce the type of that class member variable? What about using a template?
Comment: I think the problem is that the compiler doesn't have any way of knowing what type of data should be contained in your class member `type`. If you don't know what type of variable to use, you might want to write a __template__ or if the type is one of a small set of possibilities you might want to use a `std::variant`. But `auto` isn't going to work here, because it's intended for cases where the compiler can deduce the actual type of the object from the context, and you haven't provided any.
Comment: @TimRandall sounds good. Thank you explaining
Comment: @TimRandall : you should post your comment as answer
Comment: It's unclear what you're asking. How is `TYPE` to be determined? Edit your question
to explain this.
Answer: I think the problem is that the compiler doesn't have any way of knowing what type of data should be contained in your class member type. I'm afraid auto isn't going to work here, because it's intended for cases where the compiler can deduce the actual type of the object from the context, and you haven't provided any. (We the readers can look elsewhere in the class and find type = new TYPE(); and infer something from that, but as far as I know auto can only look at the statement initializing its object.)
How to proceed, then? If you don't know what type of variable to use, you might want to write a template, or if the type is one of a small set of possibilities, you might want to use a std::variant.
As for making it available as a global variable: I don't think you need to do anything special, beyond what you'd normally do for a global: declare it in a header file, define it in a source file, and include the header wherever needed. The usual considerations apply. Think about whether it truly needs to be global. Put it in an appropriate namespace so as not to pollute the global namespace. And so on.
Comment: I understand the issue with auto. Proceeding with that, I have been trying to find how I can create a global variable such that the same variable can be shared among files. I read it somewhere that it can be done by setting variable in AddGlobalTestEnvironment(Environment * env);
Do you have any information related to this?
Comment: @MonaS That sounds like it should be in a separate question. Feel free to ask another one, although I imagine it has already been asked and answered. In the meanwhile, if you're happy with this answer, please accept it. If not, please ask for improvements or clarifications and I'll do my best.
Comment: I have asked this question above as well. Just because it did not get answered, I clearly restated it here again


How do I scale the font size in android studio?

Question:
How do I scale the font size above?
Answer: Click on File -> Settings -> Editor and check the field: Change font-size with CRTL + Mouse Wheel and the press control and adjust font size using mouse wheel!
Answer: For MacBook Users:
To change font size:

Select Android Studio menu (which is present next to Apple icon)
Preferences
Editor
Font
Size(give size)-->ok

To zoom in and out in Editor:

Select Android Studio menu
Editor
General
change font size (zoom) with command and mouse wheel-->ok