PHP float with 2 decimal places: .00

Question: When I do this typecasting:
(float) '0.00';

I get 0. How do I get 0.00 and still have the data type as a float?
Comment: `0.00` is not a valid float see http://en.wikipedia.org/wiki/IEEE_floating_point
Answer: A float doesn't have 0 or 0.00 : those are different string representations of the internal (IEEE754) binary format but the float is the same.
If you want to express your float as "0.00", you need to format it in a string, using number_format :
$numberAsString = number_format($numberAsFloat, 2);

Comment: I didn't want a string. Wanted a float. But since it's not valid to have 0.00 apparently, I'll have to make do with "0.00" or 0.
Comment: we can't keep float data type after formatting. So not valid answer as per the question.
Comment: @SeniorPHPDeveloper I'm honestly confused what you're saying. Your comment from 2020 says that this is "not a valid answer", implying that you think a different answer *would* be valid; but you seem to agree that the requirement to "keep data type as float" is impossible; so the *only* possible answer is to talk about string representations, which is what this answer does. So what point are you trying to make, exactly?
Comment: @SeniorPHPDeveloper Then your comment from 2020 makes no sense. This answer is as "valid" as it's possible to be: it says you can't do that as a float, but here is how to do it as a string.
Comment: @SeniorPHPDeveloper The question is ill-formed. The format of a floating point number is a binary sequence, which has no concept of decimal digits at all. Saying "how do I format a floating point number as decimal but still keep the data format" is like saying "how do I translate this to French but still keep it as English".
Comment: @IMSoP, yes correct. I explained the same
Comment: @IMSoP, please understand the question first and rethink about it.
Comment: @Denys Séguret , is there is a way to return a decimal value that is not in string? Instead of "0.00" it will return 0.00 Thank you
Answer: As far as i know there is no solution for PHP to fix this. All other (above and below) answers given in this thread are nonsense.
The number_format function returns a string as result as written in PHP.net's own specification.
Functions like floatval/doubleval do return integers if you give as value 3.00 .
If you do typejuggling then you will get an integer as result.
If you use round() then you will get an integer as result.
The only possible solution that i can think of is using your database for type conversion to float. MySQL for example:
SELECT CAST('3.00' AS DECIMAL) AS realFloatValue;

Execute this using an abstraction layer which returns floats instead of strings and there you go.

JSON output modification
If you are looking for a solution to fix your JSON output to hold 2 decimals then you can probably use post-formatting like in the code below:
// PHP AJAX Controller

// some code here

// transform to json and then convert string to float with 2 decimals
$output = array('x' => 'y', 'price' => '0.00');
$json = json_encode($output);
$json = str_replace('"price":"'.$output['price'].'"', '"price":'.$output['price'].'', $json);

// output to browser / client
print $json;
exit();

Returns to client/browser:
{"x":"y","price":0.00}

Comment: Thanks for point to json, If you sure just work with numbers and no contain any `"` chars, so after use `number_format` and json encoding, just can use it: `$json = str_replace('"', '', $json);`
Comment: But then your key may not contain spaces, else your output will not validate. Some people do ;-)
Comment: Sorry, but it is you who is speaking nonsense. You are absolutely right that `number_format` returns a string; and a string is what you need any time you want to see a number. If you looked at the binary representation of an integer or floating point number it would not look like "2", or "2.0", or "2.00", or anything else; those are *human-readable* representations of the number.
Comment: As for JSON (which isn't mentioned in the question), just use [the JSON_PRESERVE_ZERO_FRACTION option documented here](https://www.php.net/manual/en/json.constants.php). Again, this is about how to *represent* the number, not what type it *is*.
Answer: 0.00 is actually 0. If you need to have the 0.00 when you echo, simply use number_format this way:
number_format($number, 2);

Comment: It will make data type string when you convert it to JSON
Answer: You can show float numbers

with a certain number of decimals
with a certain format (localised)

i.e.
$myNonFormatedFloat = 5678.9

$myGermanNumber = number_format($myNonFormatedFloat, 2, ',', '.'); // -> 5.678,90

$myAngloSaxonianNumber = number_format($myNonFormatedFloat, 2, '.', ','); // -> 5,678.90

Note that, the
1st argument is the float number you would like to format
2nd argument is the number of decimals
3rd argument is the character used to visually separate the decimals
4th argument is the character used to visually separate thousands
Answer: Use the number_format() function to change how a number is displayed. It will return a string, the type of the original variable is unaffected.
Comment: Hi @Bart Friederichs is there a wat to return as decimal data type instead of a string ? Thank you
Comment: @natsumiyu PHP does not have a decimal data type, so no there is no way to do that.
Answer: try this
$nom="5695.5";
number_format((float)($nom), 2, '.', ','); // -> 5,695.50

$nom="5695.5215";
number_format((float)($nom), 2, '.', ','); // -> 5,695.52

$nom="5695.12";
number_format((float)($nom), 0, '.', ','); // -> 5,695

//use round()

$nom="5695.12";
number_format((float)round($nom), 2, '.', ','); // -> 5,695.00

$nom="5695.52";
number_format((float)round($nom), 2, '.', ','); // -> 5,696.00

Comment: Not workable with 1.000 or 10.000,12 (other countries currency format)
Comment: echo number_format((float)round(10.000,12), 2, '.', ','); // -> 10.00;
Answer: you can try this,it will work for you
number_format(0.00, 2)

Comment: but in PHP it can't maintain data type
Answer: A number of comments on this page have missed the fundamental point that the question is ill-formed. Floating point is a binary representation, designed for efficient calculations; it fundamentally has no notion of decimal digits of any sort.
So asking this:

How do I get "0.00" instead of "0" and still have the data type as a float?

Is like asking this:

How do I get "deux" instead of "zwei" and still have the language as English?

Whether you specify the input as "2", or "2.0", or "2.000000000", if you ask for a floating point value, what will be stored in memory is this (in IEEE 754 double-precision):

0100000000000000000000000000000000000000000000000000000000000000

If you convert to an integer, the value stored in memory is this (assuming a 64-bit system):

0000000000000000000000000000000000000000000000000000000000000010

(Note that "integer" in this context is not just a synonym for "whole number", it is a specific data type, with its own rules for how values should be represented in memory.)
By contrast, the string "2" would look like this:

00110010

And the string "2.00" would look like this:

00110010001011100011000000110000

(In a PHP program, there would actually be additional information in memory, such as an indicator of the type, but that's not really relevant here.)

So, the question can only be answered by rephrasing it as a conversion: given the input of a floating point number, how do I choose a string representation which has a fixed number of decimals.
As others have pointed out, the answer to that is to use number_format.

The question doesn't mention JSON, but several comments do, so I will also point out that PHP's json_encode function has an option JSON_PRESERVE_ZERO_FRACTION, which will format a floating point number that happens to be a whole number with a trailing ".0", for instance:
$example = ['int' => 2, 'float' => 2.0];
echo json_encode($example);
# => {"int":2,"float":2}
echo json_encode($example, JSON_PRESERVE_ZERO_FRACTION);
# => {"int":2,"float":2.0}

Again, note that this is a string representation of the value.
Answer: You  can use round function
round("10.221",2);

Will return 10.22
Comment: what is the difference between 10.00 and 10
Comment: my use case is to use 2 decimal places to display prices consistently, but I still want it to be a float so I can perform calculations on it. The original question specifically wants the .00 to be shown.
Comment: but in PHP it can't maintain data type
Comment: it's working fine. thanks jewelhuq.
Answer: You can use floatval()
floatval()
Comment: Does not limit to two decimals.
Answer: try this
$result = number_format($FloatNumber, 2);

Comment: but in PHP it can't maintain data type
Comment: Hi @SeniorPHPDeveloper is there a way to maintain the data type? Instead of returning string ? Because using ```number_format()``` it returns string. If using ```floatval()``` if the value is 0 or 123 it will not add .00
Answer: When we format any float value, that means we are changing its data type to string.  So when we apply the formatting on any amount/float value then it will set with all possible notations like dot, comma, etc. For example
(float)0.00 => (string)'0.00',
(float)10000.56 => (string) '10,000.56'
(float)5000000.20=> (string) '5,000,000.20'

So, logically it's not possible to keep the float datatype after formatting.
Answer: You can use this simple function.
    number_format ()
    $num = 2214.56;

    // default english notation
    $english_format = number_format($num);
    // 2,215

    // French notation
    $format_francais = number_format($num, 2, ',', ' ');
    // 2 214,56

    $num1 = 2234.5688;

   // English notation with thousands separator
    $english_format_number = number_format($num1,2);
    // 2,234.57

    // english notation without thousands separator
    $english_format_number2 = number_format($num1, 2, '.', '');
    // 2234.57

Comment: but in PHP it can't maintain data type

PHP float with 2 decimal places: .00


How to fix 'ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY constraint failed' when changing column name

Question: I am developing a Rails web app. I have a table called countries that is associated with two other tables: cities and sites. When I try to change the column code to name in the countries table, I get the following exception:

ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY constraint failed: DROP TABLE "countries"

I have tried adding the dependent: :destroy thing, but I still get the same exception. I tried dropping the table, and recreating it, and still not working. Any help would be greatly appreciated.
Country model:
class Country < ApplicationRecord

    has_many :cities, dependent: :destroy
    has_many :sites, dependent: :destroy

    has_many_attached :photos

    validates :code, uniqueness: true
    validates :about, presence: true

end

Here is the migration code I'm using to change the name of the column in the countries table:
class FixCodeName < ActiveRecord::Migration[5.2]
def change
    rename_column :countries, :code, :name
  end
end

Answer: How are you attempting to rename the column? With a migration like the following?
class ChangeColumnName < ActiveRecord::Migration[5.2]
  def change
    rename_column :countries, :code, :name
  end
end

If you drop your whole database you can edit your older migrations and then recreate it. That's what I usually do if it's early in the development process.
Comment: Yes, through a migration. I am in early stages of the development of my app, but I'm tired of dropping my who database every time something goes wrong or I want to make a small change.
Comment: I don't understand why your code is trying to DROP TABLE "countries" to rename a column. Can you shed any light on this?
Comment: My code is not trying to DROP TABLE "countries", I am not sure why such alleged action is mentioned in the exception text.
Comment: Can you edit your post and add your migration code to it? Maybe that will give us a clue.
Comment: I believe you're getting this error because there's an index on column code. Can you remove the index then try to run the migration?
Comment: How do I remove the index?
Comment: To get the information for the table countries, use the following command from the sqlite command line:     .schema countries, then DROP INDEX index_name.
Comment: You could also try to remove it in a migration by using remove_index :countries, column: :code
Comment: The migration was successful (and I assumed it removed the index, I'm not sure). But the column name change still returns the same exception.
Comment: If you run out of ideas, I will just do what you suggested in the first place; to drop the entire database.
Comment: I would fire up the sqlite cli to check if the index got removed. The clue I'm going off of is from the answer of this post https://stackoverflow.com/questions/6732896/does-rename-column-take-care-of-indexes. I recommend using a different database for development because Sqlite does not always behave like the other options.
Comment: @InsolentWorm old versions of sqlite didn't support renaming columns. The workaround involved copying data to a new table, dropping the original, and renaming the new one. This naturally doesn't play well with foreign keys referring to the column in question. Dealing with that is *really* ugly (see https://www.sqlite.org/lang_altertable.html). The ORM might not even attempt to try.
Comment: Thank you for your help, but I solved it by deleting `fix_code_name` migration and then editing the migration that created the `countries` table then finally running `rails db:drop:_unsafe db:create db:migrate`.
Comment: I've chosen your answer, but I will edit your answer to reflect what I've done.


Ask some search engine to what is this image?

Question: I want to develop some mobile app. Users can put or take their item photos and my app will say this is something.
for example; When I take pictures of my chair and ask it, my app should say this is chair.
I want to query with images and I want to get my results with keyword.
Are there any API to do this ? or What should I use to build this app ?
Any recommendation appreciated.
Have a nice coding !
Comment: look at google cloud vision api
Comment: Thank you. Vision API is ok for me
Answer: What you are looking for is neural networks. Try researching the google neural networks and see if that is something you're interested in exploring.
Warning, it may be a rabbit hole. :)
Some starter links:
Analysis of Neural Networks
Google's TensorFlow
Comment: answer is too generic


Webform confirmation message on same reloaded page

Question: Webform has option to reload the page when submitting the form, but it just refresh the page and doesn't show any confirmation message that the message was sent etc. This might look misleading for simple home user when submitting the form.
Anyway to adding a confirm message on page refresh?
E.g. when submitting it as admin for more than once it actually reload the page and gives message that you already submitted this form. So basically I need the same when visitor submits the form and it would reload the page and show message like 'Thank you, your message was submitted'.
Cheers
Answer: Once you've set up  your webform you have the option to set up how the form responds after asubmission has been made. On the your Webform's Setting page...:

If you click the 'Customize Confirmation' checkbox you can - "Configure your website's actions when a user submits a response to this webform."

Select from the following form submit options in the menu:

Show standard confirmation page - Displays a confirmation page that contains the information you enter in the Page body field.
Redirect to a different page - Redirects users to the page in the Path field. You can also display a confirmation message by selecting the Show a confirmation message check box, and then entering information in the Page body field.
Stay on the same page - Users stay on the webform page. You can also display a confirmation message by selecting the Show a confirmation message check box, and then entering information in the Page body field.

You probably want to select the third option...


MapToStoredProcedures not available

Question: I saw a few questions related to this on stack overflow but none of them helped. I am using VS 2019 community edition, I created an API project on .NetCore 2.1, and added the following nuget packages. (assuming all EF packages will be included by default)

Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design

After some time into the coding I needed to use MapToStoredProcedures in the OnModelCreating function..But its not available,

entitytypebuilder doesnot contain a definition for maptostoredprocedures

after looking for a few solutions, i tried to

install-package Microsoft.EntityFrameworkCore.Relational

which did not work as there was a version conflict issue...

NU1202: Package Microsoft.EntityFrameworkCore.Relational 3.0.0 is not compatible with netcoreapp2.1 (.NETCoreApp,Version=v2.1).

then i tried to install SDK and restart VS, then i again tried to install Microsoft.EntityFrameworkCore.Relational nuget package but the same error was there.
Finally, I installed:
Microsoft.EntityFramework (6.3)
and an older version of Microsoft.EntityFrameworkCore.Relational (2.1.11)
which was successful but the MapToStoredProcedures function is still unavailable.
the using statement in the class also doesnt show Microsoft.EntityFrameworkCore.Relational namespace...
I am very confused as this function used to be available in VS 2013 with EF 6. :S
Answer: So i realize that EF 6 used to have the MapToStoredProcedures function and EF Core doesn't have it. (Not sure why they decided like that).
I changed my target framework to netcoreapp3.0 from netcoreapp2.1 and then i was able to install Tools and Microsoft.EntityFrameworkCore.Relational packages.
Finally, I am calling my sp as follows:
<code>var dbResults = _gecontext.ParameterDetails.FromSqlRaw("EXEC dbo.get_nextParamSummary @UserId={0}", userId).ToList();
</code>

MapToStoredProcedures not available


Reduce the impact of third-party code (zendesk)

Question:


suitable Embedded system to be used for image processing and gps/gsm

Question: i am working on a project, where i would like to install an embedded system in a certain location , the system is provided with a camera , the system has to perform image processing functions on the images obtained from the camera.
The system must be attached with gps and gsm modules.
i am in the process of choosing the hardware needed, i am thinking of using a beagle board or FPGA , which one is more suitable for my application ? do you recommend other boards? do you know any gsm or gps modules that can be interfaced with these modules?
Thank you
Comment: Interesting.. but unfortunately deserves a "too specific" flag and close. sorry.
Answer: If your image processing algorithms are too CPU intensive I'll suggest you consider FPGAs. Otherwise, Beagle board is fine.
Answer: What is the interface to your camera? USB / FireWire / I2C / other? If the Beagle Board supports what you need, and can handle the processing, that's probably the easiest way to go - FireWire and USB interfaces are not exactly trivial to do on an FPGA, unless you can get a board and a matching Linux distro for it, where everything is configured and working out of the box (and it's probably going to be expensive then...).
GPS modules typically connect over a simple serial connection, so that shouldn't be an issue for either solution.


Cannot use Maven Central Repository

Question: Even with the proxy setting in the ../.m2/setting.xml file cannot get access the maven central repository. Was told have to use the local repository. Wondering because of this limitation what would be a good way to get the local repository build and use thereby use Maven effectively?
Answer: You (or your admin) can have your local repo mirror the central repo and set your settings.xml file to use your local repo as the mirror for everything (see the Nexus repo documentation for what to put in your settings.xml). When you build, maven will attempt to pull all resources from your local repo; if they're not there, your repo will automatically pull them from central and store them. The next time you build, all artifacts will come from your local repo and not central.

Cannot use Maven Central Repository


Posterior predictive distributions and predictive intervals

Question: I'm confused about the role of posterior predictive distributions in Bayesian inference and predictive inference.
As I understand it, the frequentist approach would typically involve fitting the MLE, which would return a single estimate of the parameter set for the data - so there is a single distribution for predicting new data points.
As I understand it, in Bayesian inference, the posterior predictive distribution is the probability distribution of a new data point, as opposed to the posterior distribution which is a distribution of the parameter. However, to obtain the posterior predictive distribution, you marginalise over the parameter by integrating over it.
$p(\tilde{x}|\alpha )=\int p(\tilde{x}|\theta ) p(\theta |\alpha )d\theta$
Each possible value of $\theta$ would give you a different distribution.
Marginalising is (broadly) equivalent to taking a weighted average over the uncertainty in the parameter e.g. averaging over all the distributions that would arise from each possible value of the $\theta$, weighted by the probability of that $\theta$. If we imagine the levels within a Bayesian model (from $\alpha$ to $\theta$ to observations) then are we essentially averaging out over that middle layer?
If so, does this not also result in a single distribution for predicting new data points, just one that has accounted for the uncertainty while being determined? Does this not discard (or at least, use and then discard) useful information?
I am struggling to wrap my head around how this links to some other aspects/applications of Bayesian inference - which makes me suspect that I've misunderstood something.

Prediction intervals:
I thought that one of the key advantages of Bayesian inference is that it enabled easier quantification of prediction intervals, which might be needed depending on how the prediction is being used (e.g. what if we are interested in the 95th or 99th quantile of the prediction interval). But by marginalising over $\theta$, have we not lost the information that would have enabled that? I have seen some discussion of posterior predictive intervals, but I don't really understand.

Bayesian neural networks:
Similar to the above, I thought that the key advantage of BNNs is that they allow for the quantification of uncertainty. Would marginalising over the parameters not collapse this uncertainty?

Hierarchical models:
If you are trying to predict a new, unknown, group within a hierarchical model, then it seems to me that you'd want to keep the quantified uncertainty (reflecting you don't know exactly the characteristics of this new group), which would exist in the variance of the second level of the model. Would marginalising for the posterior predictive require you to integrate away this (potentially insightful) uncertainty? Or do you only marginalise over the parameter uncertainty?
Answer: "But by marginalising over
, have we not lost the information that would have enabled that?"
I'll try and provide insight into why the answer to this is no.
If we were to consider the parameters $\theta$ as a single point, we could fit a model (for example) via maximum likelihood estimation to yield
$$
p(y|\theta_{\text{ML}})
$$
Realize that we simply ignore the idea that there is randomness in $\theta$. In a Bayesian treatment, we don't ignore this, and we instead seek to find a distribution over $\theta$ rather than a point estimate for $\theta$. The distribution that takes into account the observed dataset we have at hand is called the "posterior" and I will denote it as $p(\theta|\pmb{\mathsf{y}})$.
Then, if we are interested in prediction, we compute the posterior predictive by marginalizing over all possible settings of $\theta$ contained in the posterior $p(\theta|\pmb{\mathsf{y}})$:
$$
p(y|\pmb{\mathsf{y}}) = \int p(y|\theta)p(\theta|\pmb{\mathsf{y}}) \text{d}\theta
$$
The MLE fitted model $p(y| \theta_{\text{ML}})$ considers a fixed $\theta$ and looks at the distribution over $y$ given such a fixed setting of $\theta$.
The Bayesian posterior predictive $p(y|\pmb{\mathsf{y}})$ considers a random $\theta$ and looks at the distribution over $y$ after considering all possible $\theta$ as per the posterior. Intuitively, it should have "more randomness" or "uncertainty" and it does. Namely, it has introduced "model" or "epistemic" uncertainty -- uncertainty coming from many different settings of $\theta$ that induce a model $p(y|\theta)$ that can explain our dataset at hand.
The variance of $p(y|\pmb{\mathsf{y}})$ will necessarily be greater than or equal to $p(y|\theta_{\text{ML}})$. Maybe the (very simplified) visualization below can help

Also see Pattern Recognition and Machine Learning (Chris M. Bishop) https://www.microsoft.com/en-us/research/uploads/prod/2006/01/Bishop-Pattern-Recognition-and-Machine-Learning-2006.pdf. Specifically, section 1.2.5.


Does a function in $L^2(\mathbb{R_+},\mathbb{C}$ necessarily be $0$ at $\pm \infty$?

Question: if I have $f \in L^2(\mathbb{R_+};\mathbb{C})$ and want to study something like this
\begin{equation}
\int_0^{\infty}f'(x)\overline{f(x)}\,dx
\end{equation}
Then I integrate by parts getting
\begin{equation}
|f(x)|^2 |_0^{\infty}-\int_0^\infty f(x)\overline{f'(x)} \,dx
\end{equation}
can I say that '$f(\infty)=0'$ if I know that $f \in L^2(\mathbb{R}_+;\mathbb{C})$?
EDIT:
I'm sorry I meant that my $f \in H^1(\mathbb{R}_+;\mathbb{C})$ so it has weak derivative
Answer: No, in general you cannot. Also, what does $f'$ mean for an $L^2(\mathbb{R}_+,\mathbb{C})$? Most functions in this space not differentiable.
If however, you have that $f$ has an almost everywhere derivative $f'$ and the fundamental theorem of calculus holds, i.e. $f$ is locally absolutely continuous, and this derivative is also $L^2$, then you can argue as you have that  $|f(x)|^2$ has a limit, in which case yes it must be $0$.
Details: The argument is that since $f$ is weakly differentiable, and this weak derivative is also $L^2$, you have the existence of the following limit,
$$
\langle f,f'\rangle=\lim_{M\to \infty}\int_0^M f'(x)\overline{f(x)}\mathrm dx
$$
Now you integrate by parts and see that
$$
\lim_{M\to \infty}\left(|f(x)|^2
\vert_0^M-\int_0^M f(x)\overline{f'(x)}\mathrm dx\right)
$$
must also exist, being equal to the first. But the second term has an existent limit, as again an inner product of $f$ and $f'$, so the first limit exists (why?). If it does, it must be zero (suppose it isn't, and $||f||_{L^2}$ is finite....).
Comment: I edited my question my f belongs to sobolev space $H^1$ so it has weak derivative in $L^2$. So in this case can I argue that it must have a limit and it is 0?
Comment: Yes, this is what I am referencing. Is this for a course in quantum mechanics out of curiosity?
Comment: but still I didn't understand why it must have a limit and it must be zero if it belongs to that sobolev space..
Comment: a.e. derivative does not imply locally AC
Comment: @zhw. of course, I was imprecise. I will edit
Comment: @zhw. When you have a chance, I believe it is worth responding to my edits in the above. As it stands, op doubts whether this answer suffices based on your of course valid comment (I believe now it is an adequate answer, but feel free to disagree) and this answer is in limbo until you respond.
Answer: If $ f \in L^2 $, then it is not clear that $ f $ admits limit as $ x \to \infty $.
Comment: I thought that if $f \in L^2$ then the area underneath its graph should become zero sooner or later but then I thought that it would be the case of $f \in L^1..$


Vertical-align doesn't work (with table-cell display)

Question: I have this code: http://jsfiddle.net/5qLDz/ inside which I want to have images vertically aligned to bottom of the container (with some padding from container itself). It doesn't work even with li having display: table-cell and both li and img having vertical-align:bottom set. What can it be?
Please stop posting solutions using position: absolute. As you can see in my code, I used text-align: center which is important there.
Comment: Please don't be rude to the responders. If 4 people supply the 'wrong' answer it's because you asked the 'wrong' question. We're not psychics, and we don't have crystal balls. Describe your problem accurately and you will get accurate answers. Also, you're suffering from ["XY problem"](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), where you're focusing on possible solution Y instead of on solving problem X that started it. `display:table-cell` is not going to help you here, it'll just make things messier.
Answer: One simple fix is to set the line-height to be the same as the container height:
ul.thumbnails li {
    box-sizing: border-box;
    text-align: center;
    background: grey;
    padding-bottom: 22px;
    height: 222px;
    line-height: 222px;
    display: table-cell;
}
ul.thumbnails li img {
    border-radius: 5px;
    bottom: 22px;
    vertical-align: bottom;
}

That seems to work, http://jsfiddle.net/audetwebdesign/5qLDz/20/
You only need to declare vertical-align: bottom on the img rule.
However, if you add other elements like captions or social media links this could affect how you implement the solution.
Answer: For the love of god don't use display:table-cell just to vertically align something. Just using relative positioning will also do this far more easily: forked Fiddle.
Only changed the parent to position:relative and the child to position:absolute.
Comment: If you want a solution to meet certain requirements, be sure to actually specify them.
Comment: If I used `text-align: center` it is pretty obvious that I need it, isn't it?
Comment: Your solution doesn't respect `text-align: center`. Images may have different sizes both horizontally and vertically, so I can't position them with `position: absolute`, I need something flexible.
Answer: Update your CSS:
div.left section.box ul.thumbnails {
  margin: 0;
  padding: 0;
}
ul.thumbnails li {

  text-align: center;
  background: grey;
  height: 222px;
  position:relative;
}
ul.thumbnails li img {
  border-radius: 5px;
  bottom: 22px;
  position:absolute;
}


Understanding CDF and its relationship with Probability of r.v.

Question:
I attempted to solve this problem myself. I am trying to solve the problem by applying the fundamental formula of CDF. I.e. $P(X≤x) = F_X(x)$.
Let us see the problem (b).
(i) $P(X \le \frac{1}{4})$
$\Rightarrow F(\frac{1}{4})$  (according to definition)
$\Rightarrow \frac{1}{4} + \frac{1}{2}$
$\Rightarrow \frac{3}{4}$
(ii) $P(0 < X \le \frac{1}{4})$
$\Rightarrow P(X \le \frac{1}{4}) - P(X \le 0)$ (coz, it excludes $0$)
$\Rightarrow F(\frac{1}{4}) - F(0)$    (according to definition)
$\Rightarrow \frac{3}{4} - \frac{1}{2}$
$\Rightarrow \frac{1}{4}$
(iii) $P(X=0)$
$\Rightarrow P(X \le 0) - P(?)$ (couldn't figure out! kindly, help.)
(iv) $P(0 \le X \le \frac{1}{4})$
$\Rightarrow P(X \le \frac{1}{4}) - P(X \le 0) + P(0)$ (am I correct?)
(i) and (ii) are okay. But, I am not sure about (iii), and (iv).
Also, (iii) uses a peculiar notation: $F(0^-)$.
Answer: Not quite sure what you are asking since the answers are in the picture. Here is some reasoning behind iii) and iv).
iii) is given by $P(x\leq 0) - P(x<0)$ since we want the probability that $X=0$. Since $F(x)$ is defined to be $0$ for $x<0$ this gives $\frac{1}{2} - 0 = \frac{1}{2}$.
iv) We want the probability of $0\leq X\leq \frac{1}{4}$. If we take $F(\frac{1}{4}) - F(0)$ only then we leave out the probability that $X = \frac{1}{2}$ so this is added back in by the result in iii).
Update:
$F(0^-)$ simply means $P(X<0)$.
Your answer to (iv) is correct.
Comment: Remember that the cumulative distribution function gives the combined probability of everything to the left of x if you imagine the number line. Usually to find point probabilities using the cumulative distribution function you need to consider the difference between two cumulative probabilities. That is exactly what is done in iii), you start with the cumulative probability of $X$ being less than or equal to $0$ and subtract all the probability that $X$ is less than zero, leaving only the probability of $X$ being equal to zero.
Comment: "Not quite sure what you are asking ..." --- I am trying to solve the problem by applying the fundamental formula of CDF. I.e. $P(X \le x) = F_X(x)$. (i) and (ii) are okay. But, I am not sure about (iii), and (iv).
Comment: @user366312 In that case I believe it is solved as I tried to describe above. If anything is not clear then please ask specifically about what is not clear and I will try to give you an answer
Comment: (1) Can I not use the strange symbol $F(0^-)$ and still solve the problem? (2) How does your "iii" comply with the fundamental formula? (3) Was my attempted "iv" correct?
Comment: Yes, that symbol only means that you are subtracting all cumulative probability up to, but not including $x=0$. You can solve it the way I wrote it in my answer. iii) uses the fundamental formula since you first take $P(X\leq 0)$ which equals $F(0)$ by definition and then you subtract the totalt probability that $x<0$. $F(0^-)$ is the same as $P(X<0)$. Your iv) is correct as far as I can tell.
Comment: Kindly, update your main answer with what you have written in the comment so that I can accept it. Delete comments after update is done.
Comment: Edited, please accept. The comments may benefit others so I do not see the value in deleting them.


How do I clean up my Delegate class to be cleaner?

Question: I am writing an SDK and wanted to know how to write things more cleanly.
For example, I have a GodManager delegate class (which will be the central class that a user can interact with) (this is pseudocode-ish):
public class GodManager {
  private CloudApi cloudApi;
  private SensorApi sensorApi;
  private CacheApi cacheApi;
  .
  . And about 5 more API classes of similar sorts
  .
  GodManager() {
    cloudApi = new CloudApi();
    sensorApi = new SensorApi()
    cacheApi = new CacheApi();
  }

  public void someCloudApiMethodAccess() {
    cloudApi.someCloudApiMethodAccess();
  }
  .
  .
  .  And I have about 25 other methods where GodManager delegates to API classes
  .

}

How do I allow access for my users via GodManager, but remove these 25 methods that are just proxy methods for each Api class?
I know that Android Wear does something with:
public class Wearable {
    public static final com.google.android.gms.wearable.DataApi DataApi;
    public static final com.google.android.gms.wearable.MessageApi MessageApi;
    public static final com.google.android.gms.wearable.NodeApi NodeApi;
}

Where you can access these APIs in your code:
Wearable.DataApi.getFdForAsset(...)

So I'm guessing that I can mimic this and do something like:
class GodManager {
  public static CloudApi CloudApi;

 GodManager {
   CloudApi = new CloudApi();
 }
}

Then in my implementation classes, I can:
class ImplClass {
  public void method() {
    GodManager.CloudApi.someCloudApiMethodAccess()
  }
}

Am I missing anything? Will there be some awkward side-effects that I haven't considered? Any advice would be greatly appreciated in an effort to clean up my GodManager.
Or maybe someone has some other examples that I can look at and learn from?
Comment: What is the reason that the GodManager has to exist at all, if it's just delegating everything? Can the client use the different apis directly? http://sourcemaking.com/refactoring/remove-middle-man
Comment: I will look into removing the middle man, but I am also wondering why and how Google Wear currently does it with their API?
Answer: Creating public fields is usually an antipattern, although there are some legid uses. The danger lies in the fact that if a user has access to your field, it can do ANYTHING with it.
If CloudApi contains public methods or public fields of it's own, that the user should NOT mess with, then te ONLY solution is to make a huge delegate class. If you have full control over CloudApi, and/or you can ensure that it's only public members are those that may be safely, and unconditionally, accessed by others, then you can make the instance public. (which is the legid use)
(Note that making a member private and making a public getter for that method that returns the instance, is exactly the same!)
Even then, you're limiting yourself because you're defining your API (of GodManager) and you're preventing yourself from EVER extending functionality of the referenced instances. For example, you might want to make calls to CloudApi synchronized, or check parameter validity, but don't want (or can) change CloudApi. If you have delegate methods, you can extend the functionality without changing your GodManager API, and existing users don't break.


Programmatically move registry keys

Question: Does anyone know how I can programmaically move a registry from HKEY_LOCAL_MCAHINE to HKEY_CURRENT_USER?
I wrote a recursive function that uses RegEnumKeyEx and RegEnumValue, but it appears that RegEnumValue returns all of the values under the top level key.
For example, if the key is HKEY_LOCAL_MACHINE\SOFTWARE\MyApp\KeyName1 and has 3 values under it and I have HKEY_LOCAL_MACHINE\SOFTWARE\MyApp\KeyName2 and that has 2 values.  It looks like RegEnumKeyEx is returning the proper keys, but when I call RegEnumValue for the first Key (ie. KeyName1) i get all 5 values returned and not just the 3 under that key.
Hope that all makes sense... am I doing something wrong?
Thanks for any help
Here is a snippet, if it helps:
<code>void CArgusApp::RecurseSubKeys(CString csStartKey)
{
    CQERegistry reg;

    HRESULT hr = reg.Open(HKEY_LOCAL_MACHINE, "SOFTWARE\\" + csStartKey, KEY_QUERY_VALUE );

    CStringArray csaDataNames;
    reg.GetAllDataNames(csaDataNames);
    for (int j = 0; j < csaDataNames.GetSize(); j++)
    {
        CString csValueName = csaDataNames.ElementAt(j);
        TRACE(csStartKey + " - " + csValueName);
    }

    CStringArray csaKeys;
    reg.GetAllSubKeys(csaKeys);
    for (int i = 0; i < csaKeys.GetSize(); i++)
    {
        CString csKey = csaKeys.ElementAt(i);
        this->RecurseSubKeys(csStartKey + "\\" + csKey);
    }

    reg.Close();
}
</code>
i.e.  GetAllDataNames above simply calls RegEnumValue and GetAllSubKeys call RegEnumKeyEx.
Answer: Looking through all the registry functions, I found this: SHCopyKey or I can use this: RegCopyTree for Vista and later.
Thanks for the help.
Answer: I am not an expert at this, but try something like this.
<code>  RegistryKey myKey = Registry.LocalMachine.OpenSubKey(
  @"SOFTWARE\\" + csStartKey,
  false);
Registry.CurrentUser.CreateSubKey
        (myKey.ToString());
</code>

Programmatically move registry keys


Not able to set auto increment value in my myql table using spring jdbc template

Question: I have created a simple table with three columns, --> empid, name and location. Here empid has properties primary key, not null and auto increment.
When I set values using jdbctemplate it throws sql exception
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [insert into employees values(?,?)]; nested exception is java.sql.SQLException: Column count doesn't match value count at row 1
My code is as follows
@Override
public boolean addEmployee(EmployeeMO emp) throws EmiratesException {
    boolean isEmployeeAdded = false;
    try {
        String sql = "insert into employees values(?,?)";

        jdbcTemplate.update(sql, new Object[] { emp.getEmpName(), emp.getLocation() });

        isEmployeeAdded = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return isEmployeeAdded;
}

My total exception log is
PreparedStatementCallback; bad SQL grammar [insert into employees values(?,?)]; nested exception is java.sql.SQLException: Column count doesn't match value count at row 1
at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:99)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:870)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:931)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:941)
at com.emirates.dao.EmployeeDAOImpl.addEmployee(EmployeeDAOImpl.java:24)
at com.emirates.service.EmployeeServiceImpl.addEmployee(EmployeeServiceImpl.java:17)
at com.emirates.controller.EmployeeAddController.loginProcess(EmployeeAddController.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

Caused by: java.sql.SQLException: Column count doesn't match value count at row 1

Why the empid is not setting properly? Any ideas
Comment: Shouldn't the SQL be "insert into employees (name, location) values (?,?)"?
Comment: @russianmario, yes you are right. My silly mistake
Comment: that is quite all right - we all make them :)
Answer: You need to specify the names of the columns in your insert statement. The SQL should be:
insert into employees (name, location) values (?, ?)

From the MySQL documentation:

Specify the columns for which the statement provides values as follows:
Provide a parenthesized list of comma-separated column names following the table name. In this case, a value for each named column must be provided by the VALUES list or the SELECT statement.
If you do not specify a list of column names for INSERT ... VALUES or INSERT ... SELECT, values for every column in the table must be provided by the VALUES list or the SELECT statement. If you do not know the order of the columns in the table, use DESCRIBE tbl_name to find out.


Save & Download a Json file in Unity WebGL

Question: I would like to create a system where a player/ user click on a button  to save and download a Json file listing the name and position of game objects in a Unity WebGL scene.
I am able to write the Json file with the required content in the editor. But I dont know How can I do it in WebGL. I was reading about .jslb plugins. But couldnt figure out how I can write one for my requirement.
Many thanks in Advance!
:)
Comment: Download from where? Save where? Sounds strange to first save and the download a file .. wouldn't it be the other way round?
Comment: Hi,
Saving the gameobject name and positions to a Json file from the Webgl build and then download it to the local device. :)
Comment: You looked at e.g. [this plugin](https://github.com/nateonusapps/WebGLFileSaverForUnity)? Currently your question is too broad .. try to solve one problem at a time .. are you asking how to create a JSON file or are you asking how to store a file from WebGL to the local device? ;)
Comment: Thank you for the Plugin link! Shall go through it. I managed to create a Json with the necessary game data.
`saveContent[] sc = new saveContent[objName.Count];`
.
.

`string json = JsonHelper.ToJson(sc,true);`

I would like to create a button now that will allow the user to download the created Json file.
I am totally beginner to Unity and C#, so learning things by doing :)
Answer: I found this nice File browser plugin that basically allowing me to do more or less everything that I was looking for. :) The Github repo also got a nice documentation!
Comment: Note that the linked plugin is mainly for standalone (windows/Linux/Mac) and explicitly states for WebGL `Not well tested, probably not much reliable.`


Learning the Erhu: First Steps

Question: Is there something else I should learn first before attempting to play the chinesse erhu?
I have no prior musical training or experience of any kind - I can't even read sheet music. Nevertheless, I've wanted to learn to play the Erhu for years. I've priced a few instruments and found tutorials and books to learn from as I have been unable to find an instructor in my area (Salt Lake, Utah area).
Given my lack of experience and lack of in-person access to a mentor/instructor, should I learn something more traditional first? I thought maybe the cello, but the truth is that I lack the interest in playing the cello and would prefer to jump right in with the erhu unless it is recommended otherwise.
Answer: I don't think there is such thing as having to learn an instrument before you can learn another. Of course, if you had experience in similar instruments it would be helpful, but since you don't have, there is no point in "torturing" yourself learning an instrument that you have no interest on.
IMO one of the key aspects of learning new instruments is interest. It's what keeps you wanting to play and practice. When you start losing it, you end up quitting right after. If you don't even have it, there is no chance it will work.
Unless you are a maniac and wants to spend your life pursuing the dream of being the best Ehru player in the world, and therefore wants to improve to the maximum level all involved techniques, and learning other instruments would help you achieve this goal, just do what you like and learn Ehru.
TL;DR: No.

Learning the Erhu: First Steps


Fazer um gráfico no R (ggplot) semelhante aos gráficos de barra do Excel

Question: Como posso fazer um gráfico no R (ggplot) semelhante a este gráfico do excel?

Tenho uma tabela em formtao csv com esses dados. Eu consegui subi para o R essa tabela, mas agora não sei como fazer esse gráfico usando o R.
o link da tabela: https://drive.google.com/file/d/1RqQSlupktWMqAD44xs9GgT0UXPyhdnU6/view?usp=sharing
Update:
Segue os dados da tabela em formato de texto separador ";":
Estudo;Vegetação_Nativa;Pastagem;Corpo_Hídrico;Solo_Exposto;Silvicultura;Agricultura
GEOMS 2007;15,71;83,99;0,31;0;0;0
Plano de Manejo 2008;16,99;82,69;0,31;0;0,02;0
Garcia et. al, (2014) - 2011;15,74;76,27;0,3;4,11;3,55;0
Oliveira et. al. (2017);18,24;23,8;0,3;49,47;8,2;0
Finck et al. (2020) - 2018;22,63;62;0,4;6,69;8,28;0
MapBiomas 2019;14,9;75,34;0,26;0,06;8,2;1,13
CART - Sentinel2 2020;21,39;67,89;0,24;0;10,56;0

Comment: Bem-vindo ao [pt.so]! Você colocou uma imagem do código e/ou mensagem de erro. Apesar de parecer uma boa ideia, não é! Um dos motivos é que se alguém quiser responder a pergunta, não pode copiar o código e alterar algo dentro. Clique no link [edit] e **coloque o código/erro como texto**. Veja mais sobre isso nesses links - [Manual de como NÃO fazer perguntas](https://pt.meta.stackoverflow.com/a/5485/3774), [Postar mensagem de erro como imagem](https://pt.meta.stackoverflow.com/q/7816/3774)
Comment: ola Lucas, na verdade nao coloquei código. a primeira imagem refere-se a tabela que possuo. a segunda imagem é aonde desejo chegar, mas não sei como fazer no R. abçs
Comment: Sim. Para replicar o seu problema seria ideal que vc disponibilizase os dados em formato de texto
Answer: library(dplyr)
library(tidyr)
library(ggplot2)

df <- read.csv2('./Tabela_areas_referencias_porcent_2.csv')

df_pivoted <- pivot_longer(
  data = df,
  cols = c("Vegetação_Nativa", "Pastagem","Corpo_Hídrico",
           "Solo_Exposto","Silvicultura","Agricultura"),
  values_to = 'Valores',
  names_to = 'Vegetacao'
)

df_pivoted %>%
  ggplot(aes(Estudo, Valores, fill = Vegetacao)) +
  geom_bar(stat = 'identity', position = 'dodge')+
  theme(axis.text.x = element_text(angle = 15, hjust=1))

Você pode pivotar os dados e utilizar o ggplot.

carregamos os dados
criamos o data.frame pivotado
plotamos o gráfico
Comment: Você pode utilizar o `scale_fill_manual`, após o theme você adiciona um + e adiciona essa linha: `scale_fill_manual(values = c('#D6F9DD','#99F7AB','#ABDF75','#60695C','#C0D7BB','#644536'))`. Você pode mudar os códigos hex para as cores que te agradar. Abraço!
Comment: ola lmonferrari, testei o seu código aqui rodou certinho aqui. Teria alguma forma de mudar as cores? grato pela sua ajuda.


Web (weird)wrapped text to plain text string

Question: I'm trying to convert some wrapped text to a plane text string with endlines and all.
The wrapping is however of some wierd kind I have never seen before.
The text is gained from an xml file CDATA section
My fellow Muppets,

We are sorry to say that Devilish Intetions are not going to work out with The Muppet Brigade sorry guys you are just not active ebough I would how ever like to extend an arm to any players that would like to leave and join DynaCorp. If any of you are intrested just drop me a mail and best of luck in your future endevors.

o7

John Milbroc
--------------------------
The Muppet Brigade CEO

I've tryed the following tough:
z = BeautifulSoup(string)
z.get_text()

However BeautifulSoup does not seem to be doing anything.
I'm rather new to python so sorry if this is a realy easy problem.
I think maybe my BeatifulSoup module is broken because when I do this :
from bs4 import BeautifulSoup

html_doc ="""
Hi.

This is a message.

"""
print(html_doc)

soup = BeautifulSoup(html_doc)

print(soup.text)

It prints:
Hi.

This is a message.

None

After trying that I messed around with other stuff and found that if you do
soup.get_text()

instead of
soup.txt

It wil print the parsed text.
Very wierd but it worked.
Thanks for te encouragement and keeping me on the right track.
Answer: Remove the
,
 and
 tags in the text, and the wrapping should go away.  Those are line breaks in HTML.
Answer: Why not to parse the html using BeautifulSoup? For example:
html_doc = """
 ## you copy here your html text
 """"

Then you parse it :
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)

You extract the text :
print soup.text

My fellow Muppets,We are sorry to say that Devilish Intetions are not
going to work out with The Muppet Brigade sorry guys you are just not active ebough
I would how ever like to extend an arm to any players that would like to leave and join DynaCorp.
If any of you are intrested just drop me a mail and best of luck in your future endevors.
o7
John Milbroc--------------------------

The Muppet Brigade CEO


Non-angular page opened with click - angular not defined using ignoreSynchronization or waiting for Angular without

Question: After a lot of research, and tinkering, I can't seem to actually get my Protractor test to do anything else other than have an Angular related error, even though I am using browser to avoid Angular being detected at all.
The test involves an Angular app, opening a dropdown in it, and clicking on the link for the console; the console opens a non-Angular admin page in a separate window.
So based on the many informative SO posts I found, I first used this...
browser.driver.getAllWindowHandles().then(function(handles) {
    browser.driver.switchTo().window(handles[1]).then(function() {
//expect for new window here
            });
        });

Which appeared to work, as I could get to the window through repl pretty easily.
The issue is when either of the following were added...
browser.driver.getAllWindowHandles().then(function(handles) {
    browser.driver.switchTo().window(handles[1]).then(function() {
        expect(browser.getLocationAbsUrl()).toContain('/console/login.jsp');
        expect(browser.driver.findElement(By.css('th.login')).getText()).toEqual('Login');
            });
        });

One expect check the URL and the other checks for the header element on the page, which is a table header. When I run this, I get the following:

Error while waiting for Protractor to sync with the page: "angular could not be found on the window"

When I decide to use browser.ignoreSynchronization = true, both in the function, or in a beforeEach, with or without a following afterEach setting it to false, I get the following:

JavascriptError: angular is not defined

I can't seem to get any "useful" errors to help me debug it, and trying it in repl does not help, as I get the same issue.
To be comprehensive, trying my URL expect without getting the second window will give me the root, and the other will fail.
Just doing one or the other will cause the same problem.
Changing to regular syntax (element(by.css...)) does not change things.
Comment: The method in which you are trying to get the URL isn't very 'AngularJS', for example it would be much simpler to inject '$state' into your Angular test controller and then get the url from there, $state.href() for example.

You can also use "element" to access DOM elements, here's somewhere you can find it being used:

http://stackoverflow.com/questions/19429025/how-to-access-a-dom-element-in-a-angular-directive
Answer: So much for my first question...
It appears that my use of browser.getLocationAbsUrl() is meant to be used for an Angular page, and was causing my issue...
Essentially, even though I believed I was using pure Webdriver calls, that call still required Angular on the page to work...
As stated in another post, the use of browser.driver.getCurrentUrl() is a non-Angular call using Webdriver, and fixed the problem. Thus, the final code is the following...
browser.sleep(1000); //to wait for the page to load
        browser.driver.getAllWindowHandles().then(function(handles) {
            browser.driver.switchTo().window(handles[1]).then(function() {
                expect(browser.driver.getCurrentUrl()).toContain('/console/login.jsp');
                expect(browser.driver.findElement(By.css('th.login')).getText()).toEqual('Login');
            });
        });

This works without setting ignoreSynchronization, BTW.
I realized it would probably be something relatively simple to fix it, just didn't expect I'd get it that quickly (I intended on submitting the question last night, but posted it this morning instead).
In any case, I hope this will at least be a good reference for anyone else facing the same issue.
Comment: This is relevant: [getLocationAbsUrl vs getCurrentUrl](http://stackoverflow.com/questions/30790032/getlocationabsurl-vs-getcurrentur).
Answer: Seems like getLocationAbsUrl is angular abs url.
Try using the native driver getCurrentUrl instead.
-- expect(browser.getLocationAbsUrl()).toContain('/console/login.jsp');
++ expect(browser.driver.getCurrentUrl() ...
Comment: Thanks, I realized that and was writing up the answer when you posted this. The link to the doc page is definitely helpful though; it was trial and error that led me to find the answer myself.


What does it mean to have negative values for both lower and upper bounds on a 95% Confidence Interval on ANOVA?

Question: My data shows 95% CI = [-1.07, -0.40], what does the negative sign indicate and how do I interpret the data? as I think it is significant for not capturing the value of 0.
Comment: Welcome anna. Could you be more precise? For what parameter is the confidence interval? Usually, if the confidence interval does not include the null value, the result is said to be statistically significant. If the 95%-CI does not include the null, the corresponding $p$-value is < 0.05 and you have evidence that the corresponding parameter is different (in your case smaller) than the null value.
Answer: The interpretation will depend on the specifics of your situation but, generally speaking, the negative sign does not fundamentally change anything. Formally, 95% of these confidence intervals should contain the true parameter. Also, with the same data, the corresponding test would yield a p-value under 5% for all values outside of the confidence interval and over 5% for all values inside this interval.
For example, if this is a confidence interval for a difference (e.g. t-test or contrast/pairwise differences in an ANOVA), you can indeed say that this difference is significantly different from 0 and that the reference group has a higher mean than the other one (not that you should always test if something is different from 0, this is just an habit in many disciplines but by no means a necessity).
Comment: @anna It would depend on how you coded your contrast (or how your software did it for you). You could perhaps add all this information to your question to make it more interesting and attract more attention to it. A little more context could also be useful (what's XECI?)
Comment: I conducted a contrast test on XECI to test whether the average of under 30, 30-39 and 40-49 would have a higher DV than 50+ and it gave me those negative values. Does it necessarily indicate that 50+ has a higher DV?


Where does the $M$ come from? Which parameters are related with this question, $(x_0, y_0)$ or $(x_0, y_0, \gamma, \beta, \alpha, c, k)$?

Question: My question is about Java programming.
The question is .
I struggle with where the $M$ comes from, and I do not understand this question very well.
As in the final, it needs to find the array of $c$.
The above are thoughts of mine. If they are wrong, please figure them out for me.
and help me what this asks for, and what parameters I could use to find $c_j$ (the array)
?
best wishes
Comment: Could you try to be more specific about what you don't understand? Equation (7) is the *definition* of $M$, so there's not much to say about that. And the array $c$ isn't something that you should find, it's the *input* to the function that you're supposed to write.
Comment: Does it match the subject if take xn and yn for the calculation of M (for equation 7)? Or M is got only with parameter yn, without xn, alpha, beta, gamma, k and array Cj?
Comment: As the text says, just compute all $x_j$ and $y_j$ up to $j=k$ (and the values you get will of course depend on all the parameters), then let $M$ be the greatest of the $y_j$.
Answer: Something like this (I do not do Java, but you get the idea...), so you see that array c is an input:
<code>double minimizeM(double[] c, int k)
{
    doube min_M = Inf;
    double min_M_c;
    for (i = 0; i <size(c); i++) {
       this_M = max_M(...., gamma = c[i], ....);
       if min_M > this_M
           min_M = this_M;
           min_M_c = c[i];
    }
     return min_M_c;
}

double max_M(double x0, double y0, double alpha, double beta, double gamma, int k)
{
  // Calculate xn and yn according to equation 4

  ....

  // Return the maximum yn, equation 7.

  return max(yn);
}
</code>
In function max_M, instead of calculating x[n] and y[n] first, you can keep track of the maximum M you get for all 'k' in the loop itself.


Books for self-learning about statistic Simulation?

Question: Preferably an introductory book, i.e. for undergrad (or notes or something like that) that explains concepts with detail and with lots of examples, without losing the formality.
That covers the topics

Random numbers
Generation of discrete random variables
Generation of continuous random variables
Monte Carlo method through Markov chains

Thank you in advance
Comment: I removed `[self-study]` tag, as it is meant for homeworks etc.
Answer: Apart from the bible of simulation techniques,
Devroye, L.  (1986) Non-Uniform random variate generation. Springer
[also available on line],  you may consider

Albert, J. (2009) Bayesian computation with R. Springer
Kurskche, J. (2014) Doing Bayesian Data Analysis with R, Jags, Stan. AP
Gamerman, D. and Lopes, H.  (2006) Markov Chain Monte Carlo: Stochastic Simulation for Bayesian Inference. CRC Press
Turkman, A., Paulino. C. and Müller, P.  (2018) Computational Bayesian Statistics: An Introduction. CRC Press

with the additional mention of my own books:

Robert, C.P. and Casella, G. (2009) Introducing Monte Carlo Methods with R. Springer
Marin, J.-M. and Robert, C.P. (2011) Bayesian essentials with R. Springer
Comment: Thank you. Though not sure why all but one from amazon


If in a group $G$ , $(ab)^2=(ba)^2$ for all $a,b \in G$ , then show that $G$ is abelian .

Question: Initially , I have placed $a^{-1}b$ in place of $b$ , and obtained $a^2b= ba^2$   for all $a\in G$. Consequently, i have obtained $ab^2=b^2a$ . Then what to do ?
Comment: It is true under additional hypotheses, compare [$G$ is Abelian if it has no element of order $2$ and $(ab)^2=(ba)^2$](https://math.stackexchange.com/q/566969/42969) or [Prove that a ring is commutative if $(ab)^2=(ba)^2$](https://math.stackexchange.com/q/83334/42969)
Comment: The quaternion group does obey the law $ab^2=b^2a$.
Comment: Perhaps that you meant $(ab)^2=a^2b^2$.
Answer: You don't. A counterexample is the quaternion group of order $8$.


Inverse function theorem: Lemma 7 from Terence Tao's blog

Question: I'm trying to understand the proof of Lemma 7 from Terence Tao's blog, i.e.,

Let $X$ be an open subset of $\mathbb R^n$ and $f:X \to \mathbb R^n$ be differentiable such that $\partial f (x)$ is invertible for all $x\in X$. Assume that

$f(0)=0$ and $\partial f (0)= I$ where $I$ is the identity map on $\mathbb R^n$.
$|x| = 1 \implies |f(x)| > \frac{1}{2}$.
$|x| = \frac{1}{20} \implies |f(x)| < \frac{1}{10}$.
$x \in B(0, \frac{1}{20}) \implies f(x) \in B(0, \frac{1}{10})$. Equivalently, $f [B(0, \frac{1}{20})] \subset B(0, \frac{1}{10})$.
$x_1, x_2 \in B(0, \frac{1}{20})$ such that $y :=f(x_1) = f(x_2) \in B(0, \frac{1}{10})$.

Let
$$
K_r := \{x \in \Omega : |f(x)-y| \le r\} \quad \forall r \ge 0.
$$
Then $K_r$ is closed and $x_1, x_2 \in K_r$. Let $K_r^1$ be the connected component of $K_r$ that contains $x_1$. Clearly, $r \le s$ implies $K^1_r \subset K_s^1$.
Lemma 5: $K_0^1 = \{x_1\}$.
Lemma 6: $B(0, \frac{1}{20}) \subset K_r^1 \subset B(0,1)$ for all $\frac{2}{10} \leq r \leq \frac{4}{10}$. In particular, $K_r^1$ is compact for all $0 \leq r \leq \frac{4}{10}$, and contains $x_2$ for $\frac{2}{10} \leq r \leq \frac{4}{10}$.

Lemma 7 If $0 \leq r<\frac{1}{20}$ and $\epsilon>0$, then for $r<r^{\prime}<\frac{1}{20}$ sufficiently close to $r, K_{r^{\prime}}^1$ is contained in an $\epsilon$-neighbourhood of $K_r^1$.

Proof of Lemma 7:
By the finite intersection property, it suffices to show that $\bigcap_{r^{\prime}>r} K_{r^{\prime}}^1=K_r^1$. Suppose for contradiction that there is a point $x$ outside of $K_r^1$ that lies in $K_{r^{\prime}}^1$ for all $r^{\prime}>r$. Then $x$ lies in $K_{r^{\prime}}$ for all $r^{\prime}>r$, and hence lies in $K_r \cap B(0,1)$.
As $x$ and $x_1$ lie in different connected components of the compact set $K_r \cap \overline{B(0,1)}$ [recall that $K_r$ is disjoint from $\partial B(0,1)$], there must be a partition of $K_r \cap \overline{B(0,1)}$ into two disjoint closed sets $F$, $G$ that separate $x$ from $x_1$ (for otherwise the only clopen sets in $K_r \cap \overline{B(0,1)}$ that contain $x_1$ would also contain $x$, and their intersection would then be a connected subset of $K_r \cap \overline{B(0,1)}$ that contains both $x_1$ and $x$, contradicting the fact that $x$ lies outside $K_r^1$ ).
By normality, we may find open neighbourhoods $U, V$ of $F, G$ that are disjoint. For all $x$ on the boundary $\partial U$, one has $\|f(x)-y\|>r$ for all $x \in \partial U$. As $\partial U$ is compact and $f$ is continuous, we thus have $\|f(x)-y\|>r^{\prime}$ for all $x \in \partial U$ if $r^{\prime}$ is sufficiently close to $r$. This makes $U \cap K_{r^{\prime}}$ clopen in $K_{r^{\prime}}$ and so $x$ cannot lie in $K_{r^{\prime}}^1$ giving the desired contradiction.

My questions:

Could you explain the reasoning behind "By the finite intersection property, it suffices to show that $\bigcap_{r^{\prime}>r} K_{r^{\prime}}^1=K_r^1$"?

Why does the author consider $K_r \cap \overline{B(0,1)}$, but not $K_r \cap B(0,1)$? It seems to me with $K_r \cap B(0,1)$, we don't know if $F, G$ are closed in $\mathbb R^n$, and thus we can not apply the normality of $\mathbb R^n$ to get $U, V$.

Why does [$K_r$ is disjoint from $\partial B(0,1)$] imply [$x$ and $x_1$ lie in different connected components of the compact set $K_r \cap \overline{B(0,1)}$]?

Why does [$U \cap K_{r^{\prime}}$ clopen in $K_{r^{\prime}}$] imply [$x$ cannot lie in $K_{r^{\prime}}^1$]?

Thank you so much for your help!
Answer: Question 1:
Let $W$ be an $\epsilon$-neighbourhood of $K_r^1$. Assume we know that $\bigcap_{r^{\prime}>r} K_{r^{\prime}}^1=K_r^1$. Since $K^1_r \subset K_s^1$ for $r \le s$, we see that $\bigcap_{4/10 \ge r^{\prime}>r} K_{r^{\prime}}^1=K_r^1$. We have $\bigcap_{4/10 \ge r^{\prime}>r} (K_{r^{\prime}}^1 \setminus W) = (\bigcap_{4/10 \ge r^{\prime}>r} K_{r^{\prime}}^1) \setminus W = K_r^1  \setminus W = \emptyset$. By Lemma 6 $K_{r'}^1$ is compact for $r' \le 4/10$, hence all $K_{r^{\prime}}^1 \setminus W$ are closed in the compact space $K_{4/10}^1$. Their intersection is empty, thus by the  finite intersection property there must be finitely many $r'_1,\ldots,r'_n > r$ such that $\bigcap_{i=1}^n (K_{r_i^{\prime}}^1 \setminus W) = \emptyset$. Denote by $r^*$ the smallest of these $r_i'$. Then $\bigcap_{i=1}^n (K_{r_i^{\prime}}^1 \setminus U) = K_{r^*}^1 \setminus W$. Therefore $K_{r^*}^1 \subset W$ so that $K_{r'}^1 \subset W$ if $r < r' \le r^*$.
Question 2:
Since $K_r$ is disjoint from $\partial B(0,1)$, we have $K_r \cap \overline{B(0,1)} = K_r \cap B(0,1)$. The LHS of this equation shows that this set is compact; using the RHS would not guarantee this. This enables us to use There is a partition of $X$ into disjoint closed sets $F, G$ such that $a\in F$ and $b\in G$.
Question 3:
Concerning the use of "$K_r$ is disjoint from $\partial B(0,1)$" see 2. Since $K^1_r$ is the connected component of $K_r$ that contains $x_1$ and $x \notin K^1_r$, the point $x$ must lie in a different connected component of $K_r$. This makes it impossible that $x, x_1$ lie in the same connected  component of $K_r \cap \overline{B(0,1)} \subset K_r$.
Question 4:
Tao is imprecise here.

By normality, we may find open neighbourhoods $U, V$ of $F, G$ that are disjoint. For all $x$ on the boundary $\partial U$, one has $\|f(x)-y\|>r$ for all $x \in \partial U$. As $\partial U$ is compact ...

Tao does not say in which set $X \supset K_r \cap \overline{B(0,1)}$ the disjoint sets $U \supset F, V \supset G$ are supposed to be open. So let us take $X = \overline{B(0,1)}$ which is compact; then $\partial U \subset \overline{B(0,1)}$ is in fact compact and does not intersect $K_r$. Tao's argument now shows that $U \cap K_{r^{\prime}} \cap \overline{B(0,1)}$ is clopen in $K_{r^{\prime}} \cap \overline{B(0,1)}$ for $r' \le 4/10$ sufficiently close to $r$. We have $x \in F \subset U \cap K_{r^{\prime}} \cap \overline{B(0,1)}$ and $x_1 \in G \subset V \cap K_{r^{\prime}} \cap \overline{B(0,1)}$. Thus $x_1 \notin U \cap K_{r^{\prime}} \cap \overline{B(0,1)}$ and we conclude that $x, x_1$ do not lie in the same connected  component of $K_{r^{\prime}} \cap \overline{B(0,1)}$. But we know that $K_{r^{\prime}}$ is disjoint from $\partial B(0,1)$, thus all connected components of $K_{r^{\prime}} \cap \overline{B(0,1)}$ are also connected  components of $K_{r^{\prime}}$. Therefore $x, x_1$ do not lie in the same connected  component of $K_{r^{\prime}}$. This contradicts the assumption that  $x \in K_{r^{\prime}}^1$ for all $r' > r$.


Questions from Silverman's Complex Analysisv about Conformal Functions

Question:
Prove that the mapping $w=f(z)=\frac{az+b}{cz+d} \hspace{0.5cm} (c\neq 0, ad-bc\neq 0)$ is conformal at the point $\delta =-d/c$  i.e., that it
carries any two curves $C$ and $C^*$ in the $z$-plane forming an angle of $\alpha$ radians with its vertex at $\delta$ into two curves $\Gamma$ and $\Gamma^*$ in the $w$-plane forming an angle of $\alpha$ radians with its vertex at infinity.
Prove that the mapping $w=f(z)=\frac{az+b}{cz+d} \hspace{0.5cm} (c\neq 0, ad-bc\neq 0)$ is conformal at infinity, i.e., that it carries any
two curves $C$ and $C^*$ in the $z$-plane forming an angle of $\alpha$ radians with its vertex at infinity into two curves $\Gamma$ and T* in the w-plane forming an angle
of a radians with its vertex at A =
a/c.
Answer: Part $1$: False. Note that $$w' = \frac{ad-bc}{(cz+d)^2}$$ exists for all $z$ except $z \neq - \dfrac{d}{c}$, we observe that the bilinear transformation is conformal, everywhere except at $z =-\dfrac{d}{c}$, a point at which $w$ is also not defined.

Part $2$: Note that on substitution $z = \dfrac{1}{\epsilon}$, we get: $$w = \frac{a+b\epsilon}{c + d\epsilon} = f(\epsilon)$$ Now, $$f'(\epsilon) = \frac{bc-ad}{(c+d\epsilon)^2}$$ Now, $$\lim_{\epsilon \to 0} \,\,f'(\epsilon) = \frac{bc-ad}{c^2}\neq 0$$
Hence, the bilinear transformation is conformal at $z = \infty$.


Write a pl sql block to fetch distinct department ids

Question: Write a pl sql block to fetch distinct department idsenter image description here
Comment: Please read [ask].
Answer: That would be something like this (read comments within code).
Though, the exercise is just the opposite of what I'd expect because - normally - departments exist, but nobody works in them. With enforced referential integrity constraint, you couldn't have situation as described in the exercise. After all, that's what your homework text suggests.
<code>set serveroutput on
declare
  l_dept_name  dept.dept_name%type;
begin
  -- loop through all distinct DEPT_ID values in the EMP table
  for cur_r in (select distinct e.dept_id
                from emp e
               )
  loop
    -- starting inner BEGIN-EXCEPTION-END block so that
    -- loop goes on in case of an error
    begin
      -- retrieve department details
      select d.dept_name
        into l_dept_name
        from dept d
        where d.dept_id = cur_r.dept_id;

      -- display department info (because SELECT returned something for CUR_R.DEPT_ID)
      dbms_output.put_line('Dept ID: ' || cur_r.dept_id || ' is ' || l_dept_name);

    -- handle errors (because SELECT didn't return anything for CUR_R.DEPT_ID)
    exception
      when no_data_found then
        dbms_output.put_line('Dept ID: ' || cur_r.dept_id ||': no additional info');
    end;
  end loop;
end;
/
</code>


How to put markdown pages onto new PDF pages with Pandoc?

Question: Pandoc allows a user to translate multiple Markdown input files into one PDF file.
pandoc --pdf-engine=xelatex -o test.pdf *.md

With this call, all Markdown pages are continuously listed in the PDF output without any new-page. I would like to start a new PDF page per Markdown file.
How to add a \newpage after or before every inserted Markdown file?
Comment: Or `gawk '1; ENDFILE{print "\\newpage"}' *.md | pandoc ...`
Comment: @Paebbels yes, pandoc supports TeX inside markdown, see https://pandoc.org/MANUAL.html#raw-htmltex
Comment: How about `for f in *.md; do cat "$f"; printf "\\newpage"; done | pandoc --pdf... -o ...`
Comment: Or maybe `pandoc ... <(gawk '1; ENDFILE{print "\\newpage"}' *.md)`
Comment: @MarkSetchell `\newpage` is a LaTeX command. If added to a Markdown file, it won't be interpreted as LaTeX content, right?
Comment: Oh I see. I understood your question to mean that you knew `/newpage` worked but you just weren't sure how to feed it in between markdown documents. I wasn't sure if it would work either, so I just commented rather than answering. I'll think some more today...
Comment: Maybe try this... https://stackoverflow.com/a/29642392/2836621
Comment: @Paebbels see also https://stackoverflow.com/a/52131435
Comment: @MarkSetchell please compose an answer so I can accept it as a solution, because Pandoc accepts embedded LaTeX code.
Answer: If you use GNU awk, i.e. gawk, with multiple files, it has an extension that triggers at the end of each file so you can use that to insert "newpage" commands like this:
gawk '1; ENDFILE{print "\\newpage"}' *.md | pandoc --pdf-engine=xelatex -o test.pdf

The 1 in gawk evaluates to "True" which causes gawk to do its default action, which is to print the current line, so that means all lines get printed, in addition to the "newpage" commands at the end of each file.

You can probably get the same result with GNU sed if you add the -s option to treat each document as separate, so you get a separate "last line" for each document:
sed -se '$a\\\newpage' doc*.md | pandoc ...

Comment: While this answer is correct in adding a raw LaTeX command like `\newpage` into the Markdown file to solve the problem, I would like to see a more neutral answer. Using `awk` or `sed` is a Linux-biased answer not very suitable for Pandoc users on Windows platforms. Otherwise it's a good answer.
Comment: Sorry, I wasn't aware of that from your question. I'll have a think about Windows-specific solutions, but for the moment, I do know you can install `gawk` on Windows easily enough.
Comment: You can add multiple sections to your answer. 1) a gneric answer about `\newpage` and Pandoc accepting embedded raw LaTeX commands. 2) a linux-based answer using `gawk` or `sed`. 3) a Windows suitable answer using e.g. PowerShell commands.
Answer: You can do it without Pandoc with simple Python script like this:
pip install markdown-pdf

from markdown_pdf import Section, MarkdownPdf

pdf = MarkdownPdf()

# each section (content of single md file) starts from new page in pdf file
pdf.add_section(Section(open("file1.md").read()))  # page 1
pdf.add_section(Section(open("file2.md").read()))  # page 2

pdf.save("out.pdf")


Secure LDAP Auth with SSL Cert

Question: I'm wanting to setup secure LDAP authentication with an external service provider.  The end user currently uses unsecured LDAP to the service provider.  The service provider admits they way it had been originally implemented exposes credentials via packet capture.
I've reviewed:
https://support.microsoft.com/en-us/help/321051/how-to-enable-ldap-over-ssl-with-a-third-party-certification-authority
Their local domain is a *.local.  The product manufacturer requires an SSL certificate that is signed by a valid certificate authority.  This is good.  I can create an SSL cert for the domain, but it won't match that the Directory Service has.
I'm not sure exactly how the external auth is presented to the LDAP server, if it's just passing the user name with domain name appended or if it verifies the LDAP server first.
Questions - Do I need to rename the domain to match?  Would adding a UPN suffix allow for a work-around?
Edit:
External access through the Internet is required, thus the desire to secure LDAP.
Update text for clarity
Comment: Does the service provider allow you to provide ANY certificate or must it be signed by a third party?  Does the service provider require a name on the certificate that maches the name of the domain? You can certainly do a .local using an internal CA with whatever other SANs are required.  Do you currently have Exchange in your forest?  If so that will block any attempt to rename a domain/forest .  Any certificate you use will have to be trusted by your domain clients, and use the FQDN of the domain, as well.  A UPN Suffix will most not help you in this scenario.
Comment: @Semicolon - thank you for your input.  Provider says it must be signed by a valid certification authority.  I take that as as third party/public, not an internal CA.  No Exchange - that was retired this year.
Comment: Renaming a forest ist usually a very longlasting pain in the ass and I would avoid it at (nearly) all costs. What exacty ist "Their local domain"? The clients AD or the providers service? It wouldn't make sende, if the provider asks you for a certificate for a .local domain ...
Answer: Put a TLS proxy in between (for example HAProxy in TCP mode) and publish it with a proper DNS name (for example ldap.mycompany.com) and certificate.
Backend LDAP traffic can still be plaintext or use internal name (.local) with self-signed or internal CA certificate.

Secure LDAP Auth with SSL Cert


how to bind data to this by destructuring assignment?

Question: I wanna add new key and value to this object by destructuring assignment, but it falls in error:
Uncaught SyntaxError: Unexpected token :

Let see my example, assume I have obj data object:
const obj = {
    'a':'1',
    'b':'2',
    'c':'3',
};

And now I wanna bind this data to this object, means we wanna have:
console.log(this.a); //=> "1"

So with destructuring assignment I write like these lines:
{
    a: this.a,
    b: this.b,
    c: this.c,
} = obj;

But it falls in error:
Uncaught SyntaxError: Unexpected token :

I don't use const, let or var because the this object has already been declared. How I can reach my desire? is it possible by destructuring assignment?
Simply it is possible by normal assignment:
this.a = obj.a;
this.b = obj.b;
this.c = obj.c;

I just wanna right new and pretty JavaScript codes.
Answer: You need parenthesis to distinguish the destruction object from a block statement.
({
    a: this.a,
    b: this.b,
    c: this.c,
} = obj);

Comment: `this` is the target object. it is the same as `this.a = obj.a;` etc.


How to give the first element inside a class font-size of 150% and the first line of that element red?

Question: Here's the code snippet in HTML below:

.container:first-child::first-line{
font-size: 150%;
}

Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.

Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.

      Fruits
      Vegetables

      Apple
      Potato

      Orange
      Carrot

      Tomato
      Parsnip

      Kiwi
      Onion

      Banana
      Beet

However, I want the first paragraph and the first line to be exactly like the image below:
The final output
Comment: Please show your effort
Comment: What do you mean by "*first line*"?  As rendered?
Comment: The first element which is '' should have the font size of 150%, and for the first line of it should have the red color.
Comment: Which first line? Which sentence? From "Veggies" to "gralic"?
Answer: To make the first child of font size 150%:
.container p:first-child {
  font-size: 150%;
}

To make the first line red:
.container p:first-child:first-line {
  color: red;
}

Comment: Is there a general rule that only selects the first child regardless of the element type for this code above?
Comment: Yes, just replace the tag name with `>`. In the above case replace `p` element with `>` in both styles (`.container>:first-child` & `.container>:first-child:first-line`).
Answer: I think that you should use p::first-line, not :first-child.
::first-line selects only the first line of a paragraph, while first-child selects the first paragraph, which could be shown on multiple lines.
Moreover, you have to set the color property, not background.
.container p::first-line{
    color: red;
}

In this case all the paragraphs will have the first line red. If you want only a specific paragraph, you can assign it an ID and then use first:line.
EDIT:
To have also the first paragraph with font-size 150%, you can use :first-child:
.container p:first-child{
    font-size:150%;
}
.container  p:first-child::first-line {
  color: red;
}

Comment: I also want the font size of this paragraph as I earlier mentioned to to be 150% (the whole paragraph not just the first line).
Comment: you can use the p:first-child to select only the first paragraph. I've edited my answer. Check!


Average distance between consecutive digits of normal number

Question: Let $x\in [0,1)$ be a real number. Let $x=0.a_1a_2a_3\ldots$ be the expansion of $x$ in base $b.$
Consider the average distance between two consecutive digits of $x:$
$$d(x):=lim_{N\to +\infty}\frac{\sum_{i=1}^{N}|a_{i+1}-a_i|}{N} $$
First question: Does anybody study this quantity so far?
More precisley, it is quite easy to construct a real number $x$ for which the above limit does not exist. It just suffices to choose the digits so that the quantity $$X_n:=\frac{\sum_{i=1}^{N}|a_{i+1}-a_i|}{N}$$
oscillates as $N$ increases.
Second question: If we choose a normal number $x$
then does the above limit exist?
Surely if $x$ is normal it is possible to evaluate the expectation
$$\mathbb E(X_n).$$
In fact a simple calculation shows that this is equal to $$\frac{b^2-1}{3b}$$
(to this aim remember that the expectation is linear and consider the possible values assumed by $|a_{i+1}-a_i|$.)
Third question: The variance of $X_n$ seems more difficult. Do you have any idea to find it?
Comment: I'd start by looking through Kuipers/Niederreiter's [**Uniform Distribution of Sequences**](http://web.maths.unsw.edu.au/~josefdick/preprints/KuipersNied_book.pdf). Possibly the notion of "strong normality" in Adrian Belshaw's 2005 Master of Science thesis [**On the Normality of Numbers**](http://people.math.sfu.ca/~numthry/report/2006jan13.pdf) is relevant. **(continued)**
Comment: Incidentally, a question was asked about Belshaw's thesis in Mathematics Stack Exchange --- [What is the intuition behind the definition of a simply strongly normal number?](https://math.stackexchange.com/questions/2761572/what-is-the-intuition-behind-the-definition-of-a-simply-strongly-normal-number) --- that has not generated any answers or comments.
Answer: First we exclude the case of equality, and the case of decreasing (focus only on increasing, as the probability of decreasing by a value is equal to the probability of increasing by it overall) I'll add the case of equality at the end.
Case: $\Delta=9$
Occurrences: $0\to 9 (1)$
Case: $\Delta=8$
Occurrences: $0\to 8, 1\to 9\space(2)$
Case: $\Delta=7$
Occurrences: $0\to 7, 1\to 8, 2\to 9\space(3)$
Case: $\Delta=6$
Occurrences: $0\to 6, 1\to 7, 2\to 8, 3\to9\space(4)$
etc
Case: $\Delta=1$
Occurrences: 9
There are $10$ cases of equality, so the total cases are $$2(1+2+3+4+5+6+7+8)+10=82$$
We have $\frac{2}{82}=\frac{1}{41}$ chance of the difference being $9$
$\frac{4}{82}=\frac{2}{41}$ chance of it being $8$.
and so forth.
Overall we get:
$$\frac{2}{82}\times9+\frac{4}{82}\times8+\frac{6}{82}\times7+\frac{8}{82}\times6+\frac{10}{82}\times5+\frac{12}{82}\times4+\frac{14}{82}\times3+\frac{16}{82}\times2+\frac{18}{82}\times1+\frac{20}{82}\times0$$
$$=\frac{330}{82}\approx4.02$$
Comment: This is the same calculation that i do for the expectation (except that your denominators should be 100 instead of 82: you miss a 9 in the sum). But what about the variance?
Comment: Oh yes of colurse. I made a mistake and realised it after that point... then forgot to amend it


OLEDB and C# bulk insert for Excel spreadsheet creation

Question: I am using C# to read a SQL stored procedure, put the results of the stored procedure into a C# data table and then reading the data table row by row to build up my "Insert into....values "etc.  This creates my Excel spreadsheet with the correct data.  However, instead of inserting row by row, is there a way of doing a bulk insert?
Failing that I was thinking of getting the stored procedure to write the results to a permanent table and therefore is there a way of doing an "Insert into ....select  from ".  When I have tried this in C# the code is unable to find the SQL table name specified "Microsoft database access engine cannot find the object ", what is the correct syntax and where do you specify where/how to access the SQL table?
Thanks

Hi, that link looks like it's using Microsoft.Office.Interop.Excel;
I'm using OLEDB (which i'm now beginning to regret!).  So basically i have a C# class that is called from another component.  This C# class reads a sql stored procedure, puts the results into a data table.  I then set up the table definition using the OLEDBcommand "Insert into  ( []) values ("?").  I then define the parameters e.g. cmd.Parameters.Add(columnHeading, OleDbType.VarChar, size) etc.  Then for each row i find in the data table i set the cmd.Parameters[i].value = row[i], where parameters[i] is incremented for each column in that row.  I then loop round for each data row and set cmd.Parameters[i].value appropriately.  As I have to set the cmd.Parameters[i].Value for each row i find in my dataset and then cmd.ExecuteNonQuery();
, this is quite time consuming.  So is there a way to bulk insert the data from the data table into the OLEDB command, if not, can i insert the data by referencing a SQL table directly and doing a "insert into..select from"?
Comment: can you show the select and insert statements? Are you selecting from Access or SQL Server? are you inserting from C# directly into excel using excel as datasource via connection string or what? is this a C# windows application?
Comment: I will be selecting from SQL Server.  Yes I am inserting from C# directly into excel using    using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + saveFilenameAndLocation + ";Extended Properties='Excel 12.0 Xml;HDR=Yes'"))
Comment: Here is an article which exports data from a database to an excel sheet. http://csharp.net-informations.com/excel/csharp-excel-export.htm But I am not sure whether you have already tried
Answer: You can separate your insert statements with a semicolon and run just 1 command.  For instance ...
<code>string sql = "insert into table (col1,col2) values ('row1','row1');"
sql += "insert into table (col1,col2) values ('row2','row2');"
sql += "insert into table (col1,col2) values ('row3','row3');"
SqlConnection conn = new SqlConnection("some connection string");
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
conn.ExecuteNonQuery();
conn.Dispose();
cmd.Dispose();
</code>
Or something similar.  You are executing all 3 queries with 1 command.  This might not work with databases other than SQL Server, but will definitely work with SQL Server.
Comment: Sorry, i'm using an OLEDBcommand rather than a SQLConnection.  I understand the point regarding executing 3 queries within 1 command, but to do this I would still need to loop round the data table to work out the values for row2, then loop round and read the next record for row3.  I wanted to avoid looping round the data table to read each row and instead bulk insert all the rows on the data table to the OLEDBCommand in one go.  I'm beginning to think that this isn't possible.


Blazor serverside + Cognito Logout?

Question: I'm kinda new to blazor and I'm having issues with logging users out of the application. I've looked at various documents and tutorials but I haven't found anything mentioning logging out. I've tried calling the Cognito logout endpoint (https://docs.aws.amazon.com/cognito/latest/developerguide/logout-endpoint.html) but my application still sees the user as authenticated. I also tried getting the access_token using the answer in this thread How do I get the access token from a blazor (server-side) web app? but it always returns null for me. The isAuthenticated property always return true regardless of what I do. Anyone got any ideas?
In startup
services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect(options =>
            {
                options.ResponseType = "code";
                options.SaveTokens = true;
                options.RemoteSignOutPath = "/signout";

                options.MetadataAddress = Configuration["Authentication:Cognito:MetadataAddress"];
                options.ClientId = Configuration["Authentication:Cognito:ClientId"];
                options.ClientSecret = Configuration["Authentication:Cognito:ClientSecret"];
            });

In LoginDisplay.razor
protected override async Task OnInitializedAsync()
{
    var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
    var user = authState.User;
    identity = user.Identity as ClaimsIdentity;
    var isAuthenticated = identity.IsAuthenticated;

    email = identity!.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")?.Value ?? string.Empty;
    var userData = await userService.GetUserByEmail(email.ToLower());
    userData.Then(u =>
        userRole = u.Role
        , () =>
            userRole = UserRole.Anonymous
        );
}

Answer: According to Microsoft's document AuthenticationStateProvider service, we should not use AuthenticationStateProvider directly since it does not automatically notified of authentication state data changes.
Use AuthrizedView and CascadingStateProvider components instead.

Blazor serverside + Cognito Logout?