Black wallpaper is not black (possible driver issue)

Question: I recently upgraded my dead GPU to a brand new nvidia gtx 1060, the swap-over wasn't as smooth as i hoped, anyway only some solid colors in random areas are not displaying correctly, especially noticeable on the purple login screen and my black background (built in solid color). all my drivers are up to date and all AMD drivers removed, screenshot shows the difference in blacks between wallpaper and terminal (ubuntu 18.04) tia screenshot
Comment: Possible duplicate of [My computer boots to a black screen, what options do I have to fix it?](https://askubuntu.com/questions/162075/my-computer-boots-to-a-black-screen-what-options-do-i-have-to-fix-it)
Comment: @GabrielaGarcia The OP is talking about the colour black, not a black boot screen...  **;-)**  *Voted to leave open*
Comment: @Fabby Correct and sorry. The intention was to provide a guide, not exactly a duplicate but I used the duplicate search for that.
Comment: @GabrielaGarcia No worries: You're only human (unlike me: I'm a [Vorlon](https://en.wikipedia.org/wiki/Vorlon) **;-)**
Answer: "In the Gnome Tweak tool under appearance you can set the adjustment for background and lock screen as 'None'. This fixed the problem for me."- John Cullen's answer to a different issue worked for this also

Pixelated wallpaper/background
Comment: The answer you linked is a bad answer. What you should have done is install the Nvidia drivers. Ubuntu won't do it for you because it by default uses an open source driver that's inadequate for most of the new and newish high-end cards.
Comment: I did  install the most up to date drivers from the nvidia website with no change to the issue,  gnome tweak tools does iradicate the issue
Comment: Nvidia drivers are in the Ubuntu repositories up to a certain version. If it needs newer - it doesn't - then there's also a graphics drivers PPA. The generic drivers at Nvidia website don't install properly sometimes and they require steps that many users often do not do correctly.
Comment: Follow the instructions in the duplicate above to access the TTY (command line), remove the drivers you installed with `sudo apt remove --purge nvidia*`, reboot and then `sudo ubuntu-drivers autoinstall`.
Comment: If it works, it works (+1 on both Q & A).  Yes, there are *better* ways of accomplishing this, but as a workaround, it's a good answer. (my personal and *totally subjective* opinion)  **;-) ¯\\_(ツ)_/¯**


Formula for $E(X^4)$ as integral of complementary CDF of random variable $X$

Question: So the question I have is
Let S be a non-negative random variable. By writing the probability as an expectation and using Fubini's theorm, show that
$ES^4=\int_0^\infty4t^3P(S>t)dt$
so I found on wikipedia http://en.wikipedia.org/wiki/Expected_value#General_definition

but it does not show how to prove it.
My attempt is somehow using the chain rule but i don't know how do you change S into t.
Comment: $$S^4=\int_0^S4t^3\,dt=\int_0^\infty4t^3\mathbf 1_{S>t}\,dt$$
Comment: This comment is to link this post as one of the [(abstract) duplicates](https://math.meta.stackexchange.com/questions/1868) to the current choice of [mother post](https://math.stackexchange.com/questions/172841).
Answer: Hint: Note that for $X$ non negative random variable, and $x>0$ and $\alpha > 1$

$$x^\alpha = \int_0^x\alpha u^{\alpha-1}du$$
$$E[X^\alpha] = \int_0^\infty x^\alpha dF(x)= \int_0^\infty \int_0^x\alpha u^{\alpha-1}du dF(x)$$
$$ = \int_0^\infty \int_0^\infty\alpha u^{\alpha-1}1_{\{u \leq x\}}du dF(x)$$

Swap the integrals using Fubini Tonelli theorem, get rid of the indicator function and you will have your result. Try the steps for yourself and let me know if you have problems.
Comment: No. It evaluates to $\int_0^\infty 1_{\{u\leq x\}} dF(x) = \int_u^\infty  dF(x) = P[X  > u]$
Comment: Yes it is. Steps are all correct.
Comment: Actually there is serious mistake in the *very first step*, which should read $$E(S^4)=\int_\Omega S^4dP.$$ Note that this first step is unnecessary, one can do all that follows keeping the form $E(\cdots)$.
Comment: then $$\int_0^\infty1_{\{u \leq x\}}dF(x) = 1-F(u\leq x)=P(u>x)$$ ?
Comment: Another way to understand this is to see that it is same as $E[1_{\{u \leq X\}}] = P[X > u]$
Comment: So my answer now would be using the symbols above would be $$E[S^4] \\ = \int_0^{\infty} S^4 dP \\ = \int_0^{\infty} \int_0^{\infty} 4t^3 1_{s>t} dtdP \\ =\mbox{Fubini} \int_0^{\infty} \int_0^{\infty} 4t^3 1_{s>t} dPdt \\ = \int_0^{\infty} 4t^3 \int_t^{\infty}  dPdt \\ = \int_0^{\infty} 4t^3 P(S>t) dt$$
Comment: amazing thank you Gautam !
Answer: I'm typing this on my phone so I hope there won't be that many typos.
If you assume that your random variable is nice enough, then it has a density function $f (t)$ and a distribution function $F(t) = P ( X \leq t)$ such that
$$\frac {d}{dt} (1 - F) = -f$$
In this case you can compute
\begin{align*}
E [X] &= \int X dP = \int t^{\alpha} dP_X = \int t^{\alpha} \cdot f (t) dt \\
& = - \int t^{\alpha} (1-F)'(t) dt = -[t^{\alpha}(1-F(t))]_{t=0}^{\infty} + \int \alpha  t^{\alpha - 1} (1-F(t)) dt \\
& = \alpha \int t^{\alpha-1} P (X > t ) dt
\end{align*}
Comment: thanks for your input but Fubini's Theorem needs to be applied


Blue-green deployment: how do you keep test data out of production?

Question: I understand that blue-green deployment means having two versions of production code deployed. It allows us to test in production.
Assume that we have an e-commerce application, and both deployments are sharing a database.
Then someone testing the green deployment makes a purchase. This purchase will be recorded in the production database even though it was just a test.
How do you deal with this scenario? How do blue-green deployments handle database interactions in general?
Answer: I'm not sure what resources you're looking at, but at least in our organization, using Kubernetes, blue-green deployments are not used for "canary testing", which is what you're referring to.  Blue-green deployments are used to facilitate smooth deployment switches.  During the process of deployment, the existing pods in the "current color" are still running while the pods in the "target color" are starting up and reaching readiness state.  The service doesn't switch over to the target color until the new pods in the target color are all ready.
Regarding how you would do that sort of thing with "canary testing", I'd say that is completely application-specific.
Comment: A canary deployment would also be connected and write to production database. If OP doesn't want to write data to production, while still somewhat processing production traffic: this is a SHADOW deployment. Shadow testing would require application-specific changes. Canary deployment usually won't / mostly relies on different headers or FQDNs routing requests to your canary, which then processes and answers your request as any other legacy/production workload


Steam starts to open for a few seconds, then closes

Question: I just barely installed Kubuntu and installed steam for the first time. When I try and run it it closes after a few seconds. When I run it in the Konsole I get this message.
<code>Running Steam on ubuntu 16.04 32-bit
STEAM_RUNTIME is enabled automatically
/bin/bash: /home/ryker/.local/share/Steam/ubuntu12_32/steam-runtime/i386/lib/i386-linux-gnu/libtinfo.so.5: no version information available (required by /bin/bash)
grep: symbol lookup error: grep: undefined symbol: pcre_jit_stack_alloc
grep: symbol lookup error: grep: undefined symbol: pcre_jit_stack_alloc
grep: symbol lookup error: grep: undefined symbol: pcre_jit_stack_alloc
Installing breakpad exception handler for appid(steam)/version(1468023329)
libGL error: unable to load driver: nouveau_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: nouveau
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
</code>
I just barely installed Linux for the first time so im sorry if I have made a novice mistake. Thanks in advanced for any help!
Comment: can you run it from a terminal with the command `LD_PRELOAD='/usr/$LIB/libstdc++.so.6' DISPLAY=:0 steam` ? if so try [this](http://askubuntu.com/questions/812040/lubuntu-16-04-steam-only-runs-from-terminal/812114#812114)
Answer: It looks like you didn't install the appropriate graphics card drivers,go to Settings->Software&Updates->Additional Drivers and install the latest one's
Comment: Im not exactly sure where to find this. Im running Kubuntu and my settings doesnt seem to have the Software&Updates. Again sorry for my being novice to this.
Comment: Try this http://askubuntu.com/a/761545/226056
Comment: Okay I updated my drivers successfully and now I am getting this error STEAM_RUNTIME is enabled automatically
/bin/bash: /home/ryker/.local/share/Steam/ubuntu12_32/steam-runtime/i386/lib/i386-linux-gnu/libtinfo.so.5: no version information available (required by /bin/bash)
grep: symbol lookup error: grep: undefined symbol: pcre_jit_stack_alloc
grep: symbol lookup error: grep: undefined symbol: pcre_jit_stack_alloc
grep: symbol lookup error: grep: undefined symbol: pcre_jit_stack_alloc
Installing breakpad exception handler for appid(steam)/version(1468023329)
Comment: try  this http://askubuntu.com/questions/812040/lubuntu-16-04-steam-only-runs-from-terminal


How to print a unicode string properly in Azure DevOps using powershell

Question: I want to log the stdout to the logging of an Azure DevOps task.
This is a part of my powershell script:
    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = "msiexec.exe"
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = "/i `"<<my-msi-file>>`" REBOOT=ReallySuppress /L*v+ $logFile /qn"
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
    $p.WaitForExit()
    $stdout = $p.StandardOutput.ReadToEnd()
    Write-Host "stdout: $stdout"

I do get the output, but it is displayed wrong. I am not able to copy and paste it properly, but this is what it more or less looks like (I don't know the exact character, it might be null-charaters as well):

Example text

How can I display the text like "Example text"?
EDIT:
To get an error text on stdout, just fill in for <<my-msi-file>> a nonexistent filename, e.g. c:\dev\null\nofile.msi.
Comment: Please [edit] your question to improve your [mcve]. In particular, share `$stdout | Format-Hex -Encoding  UTF8` as well as `$stdout | Format-Hex -Encoding Unicode`…
Comment: `install-package .\file.msi`
Comment: @JosefZ I explained a little bit more how to get text on stdout. But maybe your comment is the answer I am looking for. Within 12 hours I will try the `Format-Hex` command and let you know if that works.
Comment: @JosefZ Here the result:
`2023-08-03T12:44:28.9553160Z stdout: 00000000   54 00 68 00 69 00 73 00 20 00 69 00 6E 00 73 00  T.h.i.s. .i.n.s.
2023-08-03T12:44:28.9657942Z 00000010   74 00 61 00 6C 00 6C 00 61 00 74 00 69 00 6F 00  t.a.l.l.a.t.i.o.`
As I already suspected, they are all null-characters in between.
Answer: Thanks to JosefZ I was put in the right direction.
The output of msiexec.exe is apparently in unicode.
I added two lines to my script and now the output is shown correct:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "msiexec.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
###################################################################
$pinfo.StandardOutputEncoding = [System.Text.Encoding]::unicode
$pinfo.StandardErrorEncoding = [System.Text.Encoding]::unicode
###################################################################
$pinfo.Arguments = "/i `"<<my-msi-file>>`" REBOOT=ReallySuppress /L*v+ $logFile /qn"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
Write-Host "stdout: $stdout"


How do you make a button alert() the text of a textbox?

Question: In "Introduction to Nitrogen", there is this example:
body() ->
    #panel { style="margin: 50px;", body=[
        #h1 { text="My Page" },
        #label { text="Enter Your Name:" },
        #textbox { },
        #button { id=mybutton, text="Submit" }
    ]}.

Then they have you add an event that alert()'s hello:
body() ->
    [
        #button { text="Submit", actions=[
          #event{type=click, actions=#alert { text="Hello" }
        ]}
    ].

so I came up with this:
%% -*- mode: nitrogen -*-
%% vim: ts=4 sw=4 et
-module (my_page).
-compile(export_all).
-include_lib("nitrogen_core/include/wf.hrl").
-include("records.hrl").

main() -> #template { file="./site/templates/bare.html" }.

title() -> "Hello from my_page.erl!".

body() ->
    wf:wire(#event{
        type=click,
        trigger=mybutton,
        actions="alert('hello')"
    }),
    #panel{ style="margin: 50px;", body=[
        #h1{ text = "My Simple App..." },
        #label{ id=mylabel, text="Enter your name:"},
        #textbox{ id=mytextbox },
        #button{ text="Submit", id="mybutton"}
    ]}.

It would only seem natural that the guide would show you how to alert() a name that is entered in the textbox.  I tried:
body() ->
    wf:wire(#event{
        type=click,
        trigger=mybutton,
        actions="alert(obj('mytextbox').text)"
    }),
    #panel{ style="margin: 50px;", body=[
        #h1{ text = "My Simple App..." },
        #label{ id=mylabel, text="Enter your name:"},
        #textbox{ id=mytextbox },
        #button{ text="Submit", id="mybutton"}
    ]}.

...but the alert() says undefined.  I can't even find the docs for the obj() function.
I also tried using pure js for the action because the guide says:

What is a Nitrogen Action?
An action can either be Javascript, or some record that renders into
  Javascript.

body() ->
    wf:wire(#event{
        type=click,
        trigger=mybutton,
        actions="alert(document.getElementById('mytextbox').innerHTML)"
    }),
    #panel{ style="margin: 50px;", body=[
        #h1{ text = "My Simple App..." },
        #label{ id=mylabel, text="Enter your name:"},
        #textbox{ id=mytextbox },
        #button{ text="Submit", id="mybutton"}
    ]}.

But, no alert() pops up.  Can anyone help?
Edit:
Well, when I look at the page source, the html looks like this:
<input type="text" class="wfid_temp182655 wfid_mytextbox textbox" value="" />
<input type="button" value="Submit" class="wfid_temp182684 wfid_mybutton button" />

I notice that even though the button and textbox records have an id field, nitrogen does NOT set the id attribute for those html elements--which makes no sense to me.
Answer: According to the docs:

Event Action - #event {}
  ...
  Within the Javascript, you can use obj('id') where id is the id of a
  Nitrogen element. You can also use obj('me') to refer to the target of
  the current action.

Using the value property (rather than the textContent or innerHTML property--yeah, my js is rusty!) in conjunction with obj('mytextbox') works:
body() ->
    wf:wire(#event{
        type=click,
        trigger=mybutton,
        actions="alert( obj('mytextbox').value )"
    }),
    #panel{ style="margin: 50px;", body=[
        #h1{ text = "My Simple App..." },
        #label{ id=mylabel, text="Enter your name:"},
        #textbox{ id=mytextbox },
        #button{ text="Submit", id=mybutton}
    ]}.

Elsewhere, the docs say:

trigger - (atom) The id of the Nitrogen element that will trigger this action. Set automatically.
target - (atom) The id of the Nitrogen element to be referenced by obj('me'). Set automatically.

So, if I set the target to 'mytextbox', then I should be able to write:
"alert( obj('me').value )"

but no alert() pops up when I try the following code:
%% -*- mode: nitrogen -*-
%% vim: ts=4 sw=4 et
-module (my_page).
-compile(export_all).
-include_lib("nitrogen_core/include/wf.hrl").
-include("records.hrl").

main() -> #template { file="./site/templates/bare.html" }.

title() -> "Hello from my_page.erl!".

body() ->
    wf:wire(#event{
        type=click,
        trigger=mybutton,
        target=mytextbox,
        actions="alert( obj('me').value )"
    }),
    #panel{ style="margin: 50px;", body=[
        #h1{ text = "My Simple App..." },
        #label{ id=mylabel, text="Enter your name:"},
        #textbox{ id=mytextbox },
        #button{ text="Submit", id=mybutton}
    ]}.

And if I try just:
actions="alert( obj('me') )"

still no alert() pops up.


Mouse sensitivity in 14.04 dissapeared

Question: If I go to "Settings -> Mouse & Touchpad" in Ubuntu 14.04 all the options are gone! How can I bring them back?
Answer: Well, it's a bug...you can sign up here for this bug report gain visibility https://bugs.launchpad.net/ubuntu/+source/gnome-control-center/+bug/1303086
Meanwhile, you can tweak xset through startup apps to gain mouse speed.
In my case, this works:

xset m 20/12 0

Mouse sensitivity in 14.04 dissapeared


Can't start Software Center or Software Updater in Ubuntu 15.10

Question: Several days ago, I started seeing a red circle with a white line stating :
"The was a problem when checking for the updates"
When I select "Show Updates" in that menu, I see the following in the syslog:
May 23 10:00:05 scorpio gnome-session[2032]: Traceback (most recent call last):
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/bin/update-manager", line 38, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from UpdateManager.UpdateManager import UpdateManager
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/UpdateManager/UpdateManager.py", line 57, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from .MetaReleaseGObject import MetaRelease
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/UpdateManager/MetaReleaseGObject.py", line 25, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from .Core.MetaRelease import MetaReleaseCore
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/UpdateManager/Core/MetaRelease.py", line 25, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: import apt
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apt/__init__.py", line 26, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from apt.package import Package
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apt/package.py", line 42, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: import apt.progress.text
May 23 10:00:05 scorpio gnome-session[2032]: ImportError: No module named 'apt.progress'
May 23 10:00:05 scorpio gnome-session[2032]: Error in sys.excepthook:
May 23 10:00:05 scorpio gnome-session[2032]: Traceback (most recent call last):
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
May 23 10:00:05 scorpio gnome-session[2032]: from apport.fileutils import likely_packaged, get_recent_crashes
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from apport.report import Report
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: import apport.fileutils
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from apport.packaging_impl import impl as packaging
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: import apt
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apt/__init__.py", line 26, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from apt.package import Package
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apt/package.py", line 42, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: import apt.progress.text
May 23 10:00:05 scorpio gnome-session[2032]: ImportError: No module named 'apt.progress'
May 23 10:00:05 scorpio gnome-session[2032]: Original exception was:
May 23 10:00:05 scorpio gnome-session[2032]: Traceback (most recent call last):
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/bin/update-manager", line 38, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from UpdateManager.UpdateManager import UpdateManager
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/UpdateManager/UpdateManager.py", line 57, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from .MetaReleaseGObject import MetaRelease
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/UpdateManager/MetaReleaseGObject.py", line 25, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from .Core.MetaRelease import MetaReleaseCore
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/UpdateManager/Core/MetaRelease.py", line 25, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: import apt
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apt/__init__.py", line 26, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: from apt.package import Package
May 23 10:00:05 scorpio gnome-session[2032]: File "/usr/lib/python3/dist-packages/apt/package.py", line 42, in <module>
May 23 10:00:05 scorpio gnome-session[2032]: import apt.progress.text
May 23 10:00:05 scorpio gnome-session[2032]: ImportError: No module named 'apt.progress'

I get similar errors (about the apt.progress Python module) when running Software Center.
I've seen lots of issues with the Software Updater while searching for answers but none of them seem to address this issue.
This started happening after I clicked "upgrade" in the updater but then did not upgrade.  I also recently installed mysql using apt-get from the command line.  I'm well versed at commoand line (Solaris, OSX) and intermediate in Linux.  I'm not sure what I need to do with Python to fix this.  I recently migrated my day to day workflow from OSX -> Ubuntu and loath trying to re-install and reconfigure everything if I don't have to.
Comment: Alright. In that case I'll convert my comment to an answer.
Answer: It seems a package was corrupted and misses some important files. You need to reinstall the packages python3-apt and, just to be safe, ubuntu-desktop:
sudo apt-get install --reinstall ubuntu-desktop python3-apt

To detect corrupted packages early and even automatically in the future you can refer to "Is there a Ubuntu sanity check?".
Comment: As you're a reputation 1 user: if this answers your question, don't forget to click the grey ☑ under the "0" at the left of this text to [accept it](/help/someone-answers), which means "yes, this answer is valid"!


Why do some languages need semicolons?

Question: I understand that semicolons indicate the end of a line in languages like Java, but why?
I get asked this a lot by other people, and I can't really think of a good way to explain how it works better than just using line breaks or white space.
Comment: Duplicate : http://stackoverflow.com/questions/10254588/why-they-used-to-end-statements-in-java-c
Comment: I believe the practice started with [ALGOL](https://en.wikipedia.org/wiki/ALGOL) and was simply copied from there.
Answer: They don't signal end of line, they signal end of statement.
There are some languages that don't require them, but those languages don't allow multiple statements on a single line or a single statement to span multipile lines (without some other signal like VB's _ signal).
Why do some languages allow multiple statements on a line? The philosophy is that whitespace  is irrelevant (an end of line character is whitespace). This allows flexibility in how the code is formatted as formatting is not part of the semantic meaning.
Comment: Well, you could make the semicolon optional and use it if you want to have multiple statements in one line. This is what JavaScript does.
Comment: Ah, yes. I do know some languages that still allow multiple statements on one line, but by separating with a special character:

    statement1 | statement2 | statement 3,

and I know some that allow one statement across multiple lines:

    statement 1/3 +
    statement 2/3 +
    statement 3/3 (comments don't allow multiple lines apparently, so just imagine this was 3 separate lines!)
Answer: First of all, the semicolon is a statement separator, not a line separator. Some languages use the new line character as statement separator, but languages which ignore all whitespace tend to use the semicolon.
Why do languages ignore whitespace?
A language ignores whitespace to allow the programmer to format the source code as he likes it. For example, in Java there is no difference between
if (welcome)
    System.out.println("hello world");

and
if (welcome) System.out.println("hello world");

This is not because there is one separate case for each of these in the grammar of the language, but because the whitespace is simply ignored.
Why does a programming language need a statement separator?
This is the core of the question. To understand it, let's consider a small language without any statement separator. It contains the following statement types:
var x = foo()
y[0, 1] = x
bar()

Here, y is a two-dimensional array and x is written to one of the entries of y.
Now lets look at these statements like the compiler would see them:
var x = foo() y[0, 1] = x bar()

Because there is no statement separator, the compiler has to recognize the end of each statement by itself, to make sense of the input. Is the compiler able to do so? I guess in the above example the compiler can do it.
Now, lets add another type of statement to out language:
[x, y] = ["hello", "world"]

The multi assignment allows the programmer to assign multiple values at once. After this line, the variable x will contain the value "hello" while the variable y contains "world". This  might be really handy to allow multiple return values from a function. Now how does this work together with the remaining statement types?
Consider the following sequence of statements:
foo()
[x, y] = [1, 2]

First, we call the method foo. Afterwards, we assign 1 to x and 2 to y. At least this is what we meant to do. Here is what the compiler sees:
foo() [x, y] = [1, 2]

Is the compiler able to recognize each statement? No. There are at least two possible interpretations. The first is the one we intended. Here is the second one:
foo()[x, y] = [1, 2]

What does this mean? First, we call the method foo. This method is supposed to return a two-dimensional array. Now, we write the array [1, 2] at the position [x, y] in the returned array.
The compiler cannot recognize the statements, since there are at least two valid interpretations of the given input. Of course, this should never happen in a real programming language. In the given example, it might be easy to resolve, but the point is that it is hard to design a programming language without a statement separator to be not ambiguous. It is hard, because the language designer has to consider all possible permutations of statement types to be sure the language is not ambiguous.
Thus, the statement separator helps the language designer to initially design the language, but more importantly it allows the language designer to easily extend the language in the future, for example by adding new statement types. This is a big thing, since once code is written in your language, you cannot simply change the grammar for existing statement types, because this will cause all the existing code to not compile anymore.
TL;DR
Summing it all up, the semicolon was introduced as statement separator in whitespace ignoring languages, because it is easier to design and extend a language which has a statement separator.
Answer: Many languages allow you to put as much spacing as you like. This allows you to be have control over how the code looks.
Consider:
 String result = "asdfsasdfs"
               + "asdfs"
               + "asdfsdf";

Because you are allowed to insert extra newlines you can split that line across several lines without problem. The language still needs to know the line is finished that is why you need a semicolon.
Comment: JavaScript allows this with optional semicolons, so they are not needed per se
Comment: If you put the + sign at the end of each line then the syntax could parsed easily without the use of semicolon.
Comment: Right - and then you have imposed arbitrary layout restrictions so that you can sometimes omit semicolons.  To me, that is a net loss in usability.
Answer: The languages do it, as it signifies the end of a statement, not an end of the line, which means that you can compress code, to make it smaller and take up less space.
Take the C++ code (#include <iostream>):
for(int i = 0; i < 5; ++i){
    std::cout << "did you know?" << std::endl;
    std::cout << "; signifies **end of statement**" << std::endl;
    std::cout << "**not the end of the line**" << std::endl;
}

It could also be written
for(int i = 0; i < 5; ++i){std::cout << "did you know?" << std::endl; std::cout << "; signifies **end of statement**" << std::endl; std::cout << "**not the end of the line**" << std::endl;}

Answer: Some programming languages use it to signify the end of a statement thus making the language oblivious to white-space from a statement standpoint. One thing to bear in mid is that if at compile time you are checking for either a new line or a semicolon and then you have to asses several different "situations" the compiler might get what you wanted to do wrong, and it would take a it longer to look for those situations rather than simply looking for a semicolon at the end of the statement. Some higher level languages try to reduce semicolon use or remove it altogether in order to save a few keystrokes, this languages are more oriented toward the comfort of the programmer and generally come with all sort of syntactic sugar; one could argue that not using semicolons is a kind of syntactic sugar.
The use or not of a semicolon in a language should be in according to what the language is trying to accomplish, Languages like C and C++ are mostly about performance, Java and C# are a bit higher in the abstraction sense than C and C++ and then we have things like Scala, Python and Ruby, which are made mostly to make programming more comfortable a the cost of performance,(Ruby openly admits this, and it's very pronounced on Python).
So why do some languages "need" semicolons?

Makes compiling easier
The designer of the language thinks it's more consistent
Historical reasons (Java, C# and C++ are also C's children for example)

and one last thing is that Javascript actually adds the semicolons during compile or before IIRC, so it's not actually semicolon free.
Answer:
Short answer:

Because everyone else does it.

Not, nor everyone. Furthermore, many popular languages like Python, Ruby, or Visual Basic, don't use semicolon as end of statement but line breaks. Many, not "everyone", still uses semicolon because historical reasons, not rational argumentation: semicolons had a important role to replace the punched-card format in first age of computation, but today it can be totally discarded.
In fact, there're two popular ways of specify an end of statement:

Using a semicolon.
Leaving as is. This makes the compiler read a line break as end of statement. When you want extend your statement to more of one line, you simply use a special character (like \ in Python) to say that the statement has not finished.

In order to make a code more readable, using a special character to specify an end of statement should be an exception, not the rule.
Comment: That sounds like a very opinion-based answer to me.
Comment: Perhaps my comment was a bit strong. Your answer is quite informative, but while you point out there is no rational reason for a language to favor semicolon over line-break instruction ends, you don't point out any reason to prefer the opposite other than "readability". To me, semicolons looks closer to English punctuation than having each sentence on its own line. In any case, the worst idea is to have the interpreter guess where instructions end, like with JavaScript, which sometimes guesses wrong.
Comment: It seems very easy to criticize an answer, but did not explain why, dude.

Indeed, the only opinion was my last sentence ("In order to make a code more readable, using a special character to specify an end of statement should be an exception, not the rule.")

But I wonder why the whole comment is "very opinion-based answer" to you..
Answer: Short answer:

Because everyone else does it.

In theory a language's statement is whatever the language designer is able to syntactically interpret when they parse your file. So if the language designer did not want to have semicolons they could have periods, dashes, spaces, newlines, or whatever to denote the separation of a statement.
Language designers often make the syntax easy to understand so that it can become popular.
Wikipedia: Semicolon Usage in Computer Languages
So if some language designer created a language that used ':-)' to denote the end of a statement it would, 1) be hard to read; 2) not be popular with people who already are used to using a ';'.
echo "Take Care" :-)
Comment: Partially that, but JavaScript has optional semis which are nice because you CAN separate multiple statements one line if you want to. But it also produces some gotchas where not using one can lead to confusion with popular JS patterns like using parens around functions to evaluate and fire them immediately after definition. I actually enjoy white-space end-of-statements but it's never bothered me in JS where I tend to write after every line just to be explicit and avoid confusion for the next dev. It's an extra character here and there but we format in whatever fashion we like. That fits JS.
Comment: I see how it'd be pretty to a typical programmer, but I feel like that's only because they're used to this design. Why would the very first programming language to use semicolons, use it? Is it easier for the compiler?
Comment: It's not "easier" to the compiler, it's easier for the programmer.  I imagine we agree that it's necessary to be able to tell where a statement ends.  If that is always "at the end of a line" then you're limited in layout, so it's useful to also have a separator that works within a line.  Now we can have more than one statement per line, but we can't have more than one line per statement, again an annoying and unnecessary restriction. We can handle this by adding a statement-continuation character; now we've got a mess of three things to worry about. Saying "use a semicolon" is easy.

Why do some languages need semicolons?


I cant install sdl because it has unmet dependencies

Question: My input is:
sudo apt-get install libsdl1.2-dev libsdl-image1.2-dev libsdl-mixer1.2-dev libsdl-ttf2.0-dev

and the output is:
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies.

libsdl-image1.2-dev : Depends: libjpeg-dev
Depends: libtiff4-dev but it is not going to be installed

libsdl1.2-dev : Depends: libglu1-mesa-dev but it is not going to be installed

Depends: libpulse-dev but it is not going to be installed
Depends: libxt-dev but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

How do I fix this?
Answer: Try this one:
sudo apt-get install libsdl1.2-dev libsdl-image1.2-dev libsdl-mixer1.2-dev libsdl-ttf2.0-dev libpulse-dev libxt-dev

If that doesn't work you may use aptitude:
sudo apt-get install aptitude
sudo aptitude install libsdl1.2-dev libsdl-image1.2-dev libsdl-mixer1.2-dev libsdl-ttf2.0-dev libpulse-dev libxt-dev

Comment: i typed it in however when i try to compile an sdl program it wont compile;
Comment: the output of the command is: Need to get 0 B of archives. After unpacking 0 B will be used.
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
 LANGUAGE = (unset),
 LC_ALL = (unset),
 LANG = "en_GB.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
Comment: @rahman can you edit your question instead please.
Answer: To fix unmet dependencies, use sudo apt-get -f install.
Comment: i did that already and it doesnt work
Answer: You may have to enable the "Source code" repository in the Software and Updates program.
Comment: i enabled the source code and repeated what you said however im still ending with the same output
Comment: Try running `sudo apt-get update` before trying again.


How to make materialize Dropdown work in React?

Question: How do I make this materialize Dropdown work in React?
   Drop Me!

one

two

three

Materialize Dropdown documentation
I've already included the materialize.js so that's taken care of. I'm guessing that it's something to do with the data-activates attribute. I'm not getting any error, but is there any other way to declare this attribute to make it work in React?
Comment: That's the way you declare data attributes. There must be something else going on.
Comment: This might be related: http://stackoverflow.com/questions/29662350/why-is-materialize-not-working-with-reactjs
Comment: The problem you are facing is not because of react not allowing hyphen attributes. React allows data-* attributes (https://facebook.github.io/react/docs/tags-and-attributes.html)

Without more information it is unclear what might be the problem though I believe it would be in including materialize properly.
Comment: Any solution to this problem?
Answer: Try dataActivates.
 Drop Me!

Ok, I found this at react.docs;
React supports all data-* and aria-* attributes as well as every attribute in the following lists.
Note:
All attributes are camel-cased and the attributes class and for are className and htmlFor, respectively, to match the DOM API specification.
For a list of events, see Supported Events.
Comment: Welcome to Stack Overflow! Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. It's also recommended that you don't post an answer if it's just a guess. A good answer will have a plausible reason for why it could solve the OP's issue.
Comment: dataActivates doesn't work, data-activates is valid.
Answer: $('.dropdown-button').dropdown({
                                inDuration: 300,
                                outDuration: 225,
                                constrain_width: true,
                                hover: false,
                                gutter: 0,
                                belowOrigin: false
                              });

Answer: Old post, but I ran into a number of issues using materializecss with React and spent far too long trying to find workarounds. Check out React Materialize, the link goes to their included Dropdown Component. Great library, simplifies things, and fixes a few other problems such as onClick handlers with some elements. You can also use them in together, and just add in React Materialize Components when you hit a road block.
Answer: $('.dropdown-button').dropdown({
           inDuration: 300,
           outDuration: 225,
           constrain_width: true,
           hover: false,
           gutter: 0,
           belowOrigin: false
           }
      );
Comment: Hi Emel, instead adding the answer formated for a second time you shoud just edit it.


How do I extract a URL from plain text using jQuery?

Question: I'm a beginner with jQuery.
I simply want to pass a block of text to a function and return an array of urls contained within.
"I need to grab a url like http://www.something.com from text, and if therearemore.com then grab those too".
Any help? Is there a .GetUrl()?
Note: I suck with regular expressions!
Comment: possible duplicate of [Jquery Extract URL from Text](http://stackoverflow.com/questions/4189124/jquery-extract-url-from-text)
Comment: This has more to do with Javascript the language than jQuery the library.
Comment: I also asked a similar question: http://stackoverflow.com/questions/4308732/regex-replace-url-with-links
Comment: fudgey's is way over my head. I get it but I'm still blocking on applying it...
Answer: The jQuery Wiki Text plugin (http://www.kajabity.com/jquery-wikitext/) includes Regular Expressions to find URls in text which can be used for the purpose.
So, you asked for a function - well here it is:
<code>/**
 * A utility function to find all URLs - FTP, HTTP(S) and Email - in a text string
 * and return them in an array.  Note, the URLs returned are exactly as found in the text.
 *
 * @param text
 *            the text to be searched.
 * @return an array of URLs.
 */
function findUrls( text )
{
    var source = (text || '').toString();
    var urlArray = [];
    var url;
    var matchArray;

    // Regular expression to find FTP, HTTP(S) and email URLs.
    var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;

    // Iterate through any URLs in the text.
    while( (matchArray = regexToken.exec( source )) !== null )
    {
        var token = matchArray[0];
        urlArray.push( token );
    }

    return urlArray;
}
</code>
Hope it helps.
Comment: really bad answer.  Never, _ever_, _ever_ attempt to guess what a legal domain-name is using a regexp.
Comment: @Alnitak which is your proposal?
Answer: RegExp is probably the way to go, and this should do the trick for you:
<code>var searchText = $('yourElement').text(),

    // urls will be an array of URL matches
    urls = searchText.match(/\b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})\b/ig);

// you can then iterate through urls
for (var i = 0, il = urls.length; i < il; i++) {
    // do whatever with urls[i]
}
</code>
See demo →
Comment: really bad answer.  Never, _ever_, _ever_ attempt to guess what a legal domain-name is using a regexp.
Answer: You will have to use a regular expression. Try:
<code>/\i\b(http|https):\/\/(\S*)\b/i
</code>
If you aren't good with regular expression, I'd recommend taking a look at this online tool for building them: http://rubular.com/.
Answer: Try this to get all type of links
http://aaa.aaa.aaa
www.aaa.aaa
www.aaa.aaa/aaa
string.match(/(www|http|https|ftp|ftps)?:?/?/?[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/\S*)?/gi);


How do I properly add a MouseHandler to my JFreeChart-FX to drag the chart from left to right

Question: I managed to create a Candlestick Chart using JFreeChart-FX and display it using the fxgraphics2d API. But I am pretty much confused on how to enable any interaction with my chart and need some help to this.
I'd be very grateful for any help in the right direction.
I started with this example to get up my initial Chart and altered it so that it uses my data. Then I use a custom Canvas, which utilizes fxgraphics2d to make the JPanel component accessable as a node for my JavaFX applicaiton.
So I know there is for example a specific PanHandlerFX class, but I am lost to utilize this. As far as I was able to research (e.g. here), I need to add the PanHandlerFX class to the list of availableMouseHandlers of my ChartCanvas. But my canvas does not offer anything like availableMouseHandlers. I feel lost now, since there is so few tutorials and information to find regarding the JFree-FX charts and the documentation does not help me either.
Here is my custom canvas class:
import javafx.scene.canvas.Canvas;
import org.jfree.chart.JFreeChart;
import org.jfree.fx.FXGraphics2D;

import java.awt.geom.Rectangle2D;

public class ChartCanvas extends Canvas {

    JFreeChart chart;
    private FXGraphics2D graphics2D;

    public ChartCanvas(JFreeChart chart) {
        this.chart = chart;
        this.graphics2D = new FXGraphics2D(getGraphicsContext2D());
        // Redraw canvas when size changes.
        widthProperty().addListener(e -> draw());
        heightProperty().addListener(e -> draw());

    }

    private void draw() {
        double width = getWidth();
        double height = getHeight();
        getGraphicsContext2D().clearRect(0, 0, width, height);
        this.chart.draw(this.graphics2D, new Rectangle2D.Double(0, 0, width, height));
        //(this.graphics2D,, new Rectangle2D.Double(0, 0, width, height));
    }
}

Here is my custom JFreeChart:
import javafx.collections.ObservableList;
import org.ezstrats.model.chartData.Candlestick;
import org.ezstrats.model.chartData.Exchange;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.HighLowItemLabelGenerator;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.ohlc.OHLCSeries;
import org.jfree.data.time.ohlc.OHLCSeriesCollection;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

public class JFreeCandlestickChart extends JPanel {

    private static final DateFormat READABLE_TIME_FORMAT = new SimpleDateFormat("kk:mm:ss");

    private OHLCSeries ohlcSeries;
    private TimeSeries volumeSeries;
    private JFreeChart candlestickChart;

    public JFreeCandlestickChart(String title) {
        ObservableList<Candlestick> candlesticks = Exchange.getCandlesticks();
        // Create new chart
        candlestickChart = createChart(title, candlesticks);
        // Create new chart panel
        final ChartPanel chartPanel = new ChartPanel(candlestickChart);
        chartPanel.setPreferredSize(new Dimension(832, 468));
        chartPanel.getChart().getXYPlot().getDomainAxis().setAutoRange(false);
        chartPanel.getChart().getXYPlot().getDomainAxis().setLowerBound(candlesticks.get(candlesticks.size() - 300).getTimestampOpen());
        chartPanel.getChart().getXYPlot().getDomainAxis().setUpperBound(candlesticks.get(candlesticks.size() - 1).getTimestampOpen());
        // Enable zooming - not workign?! ...
        chartPanel.setMouseZoomable(true);
        chartPanel.setMouseWheelEnabled(true);
        chartPanel.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                // process before
                super.mouseDragged(e);
                chartPanel.getChart().getXYPlot().getDomainAxis().configure();
                // process after
            }
        });

        add(chartPanel, BorderLayout.CENTER);
    }

    public JFreeChart createChart(String title, ObservableList<Candlestick> candlesticks){

        /**
         * 1st:
         * Creating candlestick subplot
         */
        // Create OHLCSeriesCollection as a price dataset for candlestick chart
        OHLCSeriesCollection candlestickDataset = new OHLCSeriesCollection();
        ohlcSeries = new OHLCSeries("Price");
        candlestickDataset.addSeries(ohlcSeries);

        // Create candlestick chart priceAxis
        NumberAxis priceAxis = new NumberAxis("Price");
        priceAxis.setAutoRangeIncludesZero(false);

        // Create candlestick chart renderer
        CandlestickRenderer candlestickRenderer = new CandlestickRenderer(CandlestickRenderer.WIDTHMETHOD_AVERAGE,
                false,
                new HighLowItemLabelGenerator(new SimpleDateFormat("kk:mm"), new DecimalFormat("0.00000000")));

        // Create candlestickSubplot
        XYPlot candlestickSubplot = new XYPlot(candlestickDataset, null, priceAxis, candlestickRenderer);
        candlestickSubplot.setBackgroundPaint(Color.white);

        /**
         * 2nd:
         * Creating volume subplot
         */
        // creates TimeSeriesCollection as a volume dataset for volume chart
        TimeSeriesCollection volumeDataset = new TimeSeriesCollection();
        volumeSeries = new TimeSeries("Volume");
        volumeDataset.addSeries(volumeSeries);

        // Create volume chart volumeAxis
        NumberAxis volumeAxis = new NumberAxis("Volume");
        volumeAxis.setAutoRangeIncludesZero(true);

        // Set to no decimal
        volumeAxis.setNumberFormatOverride(new DecimalFormat("0"));

        // Create volume chart renderer
        XYBarRenderer timeRenderer = new XYBarRenderer();
        timeRenderer.setShadowVisible(false);
        timeRenderer.setDefaultToolTipGenerator(new StandardXYToolTipGenerator("Volume--> Time={1} Size={2}",
                new SimpleDateFormat("kk:mm"), new DecimalFormat("0")));

        // Create volumeSubplot
        XYPlot volumeSubplot = new XYPlot(volumeDataset, null, volumeAxis, timeRenderer);
        volumeSubplot.setBackgroundPaint(Color.white);

        /**
         * 3rd:
         * Adding Candles to this chart
         **/
         for (Candlestick candle: candlesticks){
            addCandleToChart(candle.getTimestampOpen(),
                    candle.getPriceOpen(),
                    candle.getPriceHigh(),
                    candle.getPriceLow(),
                    candle.getPriceClose(),
                    candle.getVolumeQuote());
        }

        /**
         * 4th:
         * Create chart main plot with two subplots (candlestickSubplot,
         * volumeSubplot) and one common dateAxis
         */
        // Creating charts common dateAxis
        DateAxis dateAxis = new DateAxis("Time");
        dateAxis.setDateFormatOverride(new SimpleDateFormat("dd.mm.yy kk:mm"));
        //dateAxis.setRange();
        // reduce the default left/right margin from 0.05 to 0.02
        dateAxis.setLowerMargin(0.02);
        dateAxis.setUpperMargin(0.02);
        dateAxis.setLabelAngle(0);

        // Create mainPlot
        CombinedDomainXYPlot mainPlot = new CombinedDomainXYPlot(dateAxis);
        mainPlot.setGap(10.0);
        mainPlot.add(candlestickSubplot, 4);
        mainPlot.add(volumeSubplot, 1);
        mainPlot.setOrientation(PlotOrientation.VERTICAL);
        mainPlot.setDomainPannable(true);

        JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, mainPlot, false);
        //chart.removeLegend();

        // Einbetten in JScrollPaenl??? um Scrollen zu ermöglichen...
//        ChartPanel chartPanel = new ChartPanel(chart);

        return chart;
    }

    /**
     * Fill series with data.
     *
     * @param c opentime
     * @param o openprice
     * @param h highprice
     * @param l lowprice
     * @param c closeprice
     * @param v volume
     */
    private void addCandleToChart(long time, double o, double h, double l, double c, double v) {
        // Add bar to the data. Let's repeat the same bar
        FixedMillisecond t = new FixedMillisecond(time);
        //READABLE_TIME_FORMAT.parse(String.valueOf(time)));
        ohlcSeries.add(t, o, h, l, c);
        volumeSeries.add(t, v);
    }

    public void setOhlcSeries(OHLCSeries ohlcSeries) {
        this.ohlcSeries = ohlcSeries;
    }
    public void setVolumeSeries(TimeSeries volumeSeries) {
        this.volumeSeries = volumeSeries;
    }
    public OHLCSeries getOhlcSeries() {
        return ohlcSeries;
    }
    public TimeSeries getVolumeSeries() {
        return volumeSeries;
    }
    public JFreeChart getCandlestickChart() {
        return candlestickChart;
    }
}

And this is how I print the chart (main.class):
    // Switching Views
    public void drawNewChart(JFreeChart newChart){
        centerChart.getChildren().removeAll();

        ChartCanvas chartCanvas = new ChartCanvas(newChart);

        centerChart.getChildren().add(chartCanvas);
        chartCanvas.widthProperty().bind(centerChart.widthProperty());
        chartCanvas.heightProperty().bind(centerChart.heightProperty());

    }

Answer: As shown here, construct a ChartViewer with your  JFreeChart to create an interactive chart. The viewer's enclosed ChartCanvas will manage the PanHandlerFX for you. As a concrete example, add the following line to the example, and drag as described here:
plot.setDomainPannable(true);

Original:

After drag right:

As an aside, you may find the JavaFX Demos helpful in this context.
Comment: Whoooopdidu! Thank you so much! I got my first interactable chart now. I will dig deeper in how to customize that now. Thank you very much!! :)
Comment: You are welcome. More interactive features are listed [here](https://stackoverflow.com/a/44151032/230513).


PCL replace point clouds with pointers?

Question: I have a point cloud defined as pcl::PointCloud<pcl::PointXYZI> cloud_xyzi_;. Sometime later, I read in data from a file and push it back into this point cloud; everything works fine. My task however requires me to filter the point cloud, and the filtering methods require pointers.
Can I simply replace my above declaration with something like this pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_xyzi_p;, initialise it in the constructor of the class and then have a pointer on its own,  rather than creating a pointer just to pass it to a function? Of course change the . to -> when I use it otherwise. I ask this because I am getting unexpected behaviour when trying to implement this.
Here is my abridged class, with the current code which seems both redundant and not working great.
class P400toPointcloud {
public:
    P400toPointcloud():
    callback_counter_(0),
    sensor_model_created_(false)
    {
        // Setup pointers for later use
        cloud_xyzi_p = cloud_xyzi_.makeShared();
        cloud_xyzi_fp = cloud_xyzi_f.makeShared();
    }

    ~P400toPointcloud()
    {
    }

private:
    pcl::PointCloud<pcl::PointXYZI> cloud_xyzi_;
    pcl::PointCloud<pcl::PointXYZI> cloud_xyzi_f;
    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_xyzi_p;
    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_xyzi_fp;

    std::vector<unsigned int> value_idx_;

};

Answer: The code that you have in the constructor have a different effect from what you probably expect:
// Setup pointers for later use
cloud_xyzi_p = cloud_xyzi_.makeShared();
cloud_xyzi_fp = cloud_xyzi_f.makeShared();

The call to makeShared() allocates memory for a new point cloud, copies the contents of the old one inside, wraps the pointer to the new cloud into boost::shared_ptr and returns. Effectively, you get a completely independent copy that can be used in functions that accept pointers. Any modifications done to it will not affect the original cloud.
Since you know you will need to work with the point cloud via its pointer, you should just have a pcl::PointCloud<pcl::PointXYZI>::Ptr. But don't forget to allocate memory for it in the constructor:
class P400toPointcloud {
public:
    P400toPointcloud():
    callback_counter_(0),
    sensor_model_created_(false),
    cloud_xyzi_(new pcl::PointCloud<pcl::PointXYZI>),
    cloud_xyzi_f(new pcl::PointCloud<pcl::PointXYZI>)
    {
        // From now on you pass
        //   cloud_xyzi_ to functions that expect pointer to a point cloud
        //   *cloud_xyzi_ to functions that expect (raw) point cloud
    }

    ~P400toPointcloud()
    {
    }

private:
    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_xyzi_;
    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud_xyzi_f;

    std::vector<unsigned int> value_idx_;

};

Comment: thank you for the good explanation - when I was trying to make sense of the docs it said it made a deep copy somewhere. wish i could upvote that more than once.
Comment: To which specific doc are you referring? We may refine it to avoid confusion in future.
Comment: ".. Note that deep copy is performed.." http://docs.pointclouds.org/1.7.1/classpcl_1_1_point_cloud.html.

PCL replace point clouds with pointers?


Does voltage in my PC's case indicate a circuit grounding problem?

Question: Today I was on my computer, and I wanted to plug in an external battery powered speaker to my PC's front audio jack using an AUX cable.
I noticed as soon as I plugged it in the familiar burning smell when something like a capacitor or resistor burns out, so I immediately unplugged everything and noticed that the AUX cable was very hot. After I had a poke around inside my computer, I couldn't really see anything that looked damaged. After I had a go turning it on again, the audio still worked (through the rear jack) so it looks like it didn't blow the sound part of my motherboard.
However, after doing some more investigating, I noticed I could feel a slight tingle on my computer case when touching the case and what I think is a grounded point in my house (touching the shielding of a coax cable coming out of my wall). After making sure my PC was plugged into a grounded socket, I still felt this sensation. Even weirder, when I unplugged the case, I still felt the sensation when touching the grounded point.
Could this mean there is something wrong with my ground and it always has some potential running through it?
Comment: It might be worth borrowing a voltmeter instead of risking your life using yourself as one.  Electricity is fickle (or to be more precise, conductivity of things *not made* to be conductors or insulators is highly variant).
Comment: Do you have a volt meter?  Can you check the voltage from an unpainted part of the computer to the ground hole of the outlet?  The speakers wouldn't be grounded anyway, so not sure how that plays into this.
Comment: Shielding of a coax. cable is **not** necessarily "ground of the house". Logically it should be. But logic doesn't always work when cable companies are involved. The real test is to the ground of an *electric outlet* - but better with a multimeter than your finger.
Comment: When it went wrong, what was connected to the battery powered speaker? Only the audio cable, or was it also plugged to its own charger? If the speaker was plugged into its charger, the charger could be the culprit.
Comment: @JPhi1618 I'm going to the shops tomorrow to pick up a multimeter and a socket tester.
Comment: @manassehkatz-Reinstate Monica I'll try measuring it with a multimeter next.
Comment: @peufeu It was only the audio cable, that's what led me to believe it was something with the computer itself being live, so the grounding of the case was connected to the grounding of the AUX cable.
Comment: If the AUX cable was hot it means high current ran through it. However current flows in a loop. If the speaker was not connected to anything except the PC then what is the loop ? AUX jacks aren't supposed to be connected to circuits capable of high-current... Another hypothesis... Is the speaker's enclosure made of metal, and did it make contact with the PC ground?
Comment: @peufeu The speaker is not made of metal, and is not connected to the ground. My hypothesis is that the case itself is under power, so anything grounded to the case is also under power. This means the ground of the AUX cable is also under power, then the power ending up having a place to go, the speaker.
Comment: If the case is under power, for example case shorted to mains, that would be dangerous. You can test this with a multimeter, measure voltage between PC case and Earth, take precautions. But it wouldn't fry your audio cable... the cable connects the speaker's ground to the PC ground, so they will be at the same potential, but that doesn't mean current will flow in the cable. Where would the current go? It needs a loop, and I wonder what it is...
Comment: @pefeu Yeah it's really strange. I'll get the multimeter tomorrow to measure it, and I'll report back here what I've found.
Comment: was your "battery powered speaker" connected to anything other than the computer?
Comment: I suspect that you may have connected the front audio jack to the wrong place inside the PC, perhaps to a USB or firewire  header.
Comment: Did you ever get this resolved? If so, please give a check-mark to the answer or write up your own answer explaining what you did to get it fixed and give yourself a check mark. That will help others with this kind of problem know that this has a resolution and is a good place to look for their answer.
Answer: I concur with your theory that the case is under power.  This may be due to a ground fault in the PC's power supply.  It could also be some other appliance raising ground due to its ground fault combining with a gap in the grounding system.
It's possible to have "islanded grounds" where a bunch of equipment grounds connect to each other, but do not connect to the actual earth. In an islanded-ground situation, you have the lowest common denominator; a ground fault on any of them lights up all of them.
The Equipment Safety Grounding System (outlet to panel), combined with the Grounding Electrode System (panel to ground rods), should be handling that properly.  I'd say it's time to give both systems a heavy inspection with a 10 foot pole... sorry, I mean with a fine-tooth comb.
If your grounding electrode system is faulty, that's where the 10-foot poles come in.


React+Redux - Uncaught Error: Expected the reducer to be a function

Question: I tried simple react,redux,ajax working example and followed Reddit API tutorial, but I cannot create store and get error:
Uncaught Error: Expected the reducer to be a function.

index.jsx
...
import { createStore, applyMiddleware } from 'redux'
var thunkMiddleware = require('redux-thunk');
var createLogger = require('redux-logger');
var rootReducer = require('./reducers.js');

        const loggerMiddleware = createLogger();

        function configureStore(initialState) {
            return createStore(
                rootReducer,
                initialState,
                applyMiddleware(
                    thunkMiddleware,
                    loggerMiddleware
                )
            )
        }

        const store = configureStore();

...
rootReducer.js
import { combineReducers } from 'redux';

function products(state = {
    isFetching: false,
    didInvalidate: false,
    items: []
}, action) {
    switch (action.type) {
        case 'REQUEST_PRODUCTS':
            return Object.assign({}, state, {
                isFetching: true,
                didInvalidate: false
            })
        case 'RECEIVE_PRODUCTS':
            return Object.assign({}, state, {
                isFetching: false,
                didInvalidate: false,
                items: action.posts,
                lastUpdated: action.receivedAt
            })
        default:
            return state
    }
}

function specialPosts(state = { }, action) {
    switch (action.type) {
        case RECEIVE_SPECPOSTS:
        case REQUEST_SPECPOSTS:
            return Object.assign({}, state, {
                req: true
            })
        default:
            return state
    }
}

const rootReducer = combineReducers({
    products,
    specialPosts
});

export default rootReducer;

Type of rootReducer is object, but why? Should I change createStore function to rootReducer.default?
return createStore(
    rootReducer.default,
    initialState,
    applyMiddleware(
        thunkMiddleware,
        loggerMiddleware
     )
)

package.json
"redux-logger": "^2.6.1",
"react-redux": "^4.4.1",
"react-redux-provide": "^5.2.3",
"redux": "^3.3.1",
"redux-thunk": "^2.0.1",

Comment: @dandavis wrong snippet. I already edited it.
Comment: I require rootReducer `var rootReducer = require('./reducers.js').default;`
Answer: const rootReducer = combineReducers({
    products,
    specialPosts
});

const store = createStore( rootReducer, applyMiddleware( thunkMiddleware ));

The initial state is then created automatically from the initial states returned by the individual reducer functions. These individual states can be accessed as state.products and state.specialPosts
Comment: maybe add an explanation of what your changing?
Comment: you might need to add more explanation to make sense to others who seeks similar resolution.
Answer: The problem was due to rootReducer being imported by "require" (ES5):
var rootReducer = require('./reducers.js');

If you import it via the ES6 method, it will correctly save the rootReducer.js' default automatically into rootReducer as you expected:
import rootReducer from './reducers';

I see you are mixing ES5 (require) and ES6 (import) in that file...I was mixing in my project as well, which is why I ran into this problem. More information can be found here: https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0#.2x2p2dx3m
Answer: When you create store first argument must be function that means reduce(()=>[]) parameter
Error:
import {createStore,applyMiddleware} from 'redux';

export default function configureStore(initialState) {
  return createStore(
    [],
    {},
    applyMiddleware()
  );
}

Solution:
import {createStore,applyMiddleware} from 'redux';

export default function configureStore(initialState) {
  return createStore(
    ()=>[],
    {},
    applyMiddleware()
  );
}

Answer: When you see the error:

Uncaught Error: Expected the reducer to be a function

It does not necessarily mean that the reducer is not a function. If you experience this error, you should try creating the store with just the reducer. So like this:
createStore(reducer)
Which might be working.
In my case, the second parameter was wrong, because I didn't call compose and applyMiddleware in the correct order. So this is a correct setup that seems to have worked in my case:

export const createDebugStore = () => {
    const options: EnhancerOptions = {}
    const composeFunc = (typeof window !== 'undefined' && composeWithDevTools(options)) || compose;
    const enhancer = composeFunc(applyMiddleware());

    return createStore((state: any) => state || {}, enhancer);
}

Answer: rootReducer
/* index.js */

import AppReducer from './reducers';
// import {AppReducer} from './reducers';
// bugs : must be a root reducer, can not be use as a module

/* reducers.js */

// initial state
const initialState = {
    angular: 0,
    react: 0,
    vuejs: 0
};

// reducers update state
const AppReducers = (state = initialState, action) => {
    switch (action.type) {
        case 'VOTE_ANGULAR':
            console.log("Vote Angular!");
            return (
                Object.assign(
                    {},
                    state,
                    {
                        angular: state.angular + 1
                    }
                )
            );
        case 'VOTE_REACT':
            console.log("Vote React!");
            return (
                Object.assign(
                    {},
                    state,
                    {
                        react: state.react + 1
                    }
                )
            );
        case 'VOTE_VUEJS':
            console.log("Vote Vue.jsc!");
            return (
                Object.assign(
                    {},
                    state,
                    {
                        vuejs: state.vuejs + 1
                    }
                )
            );
        default:
            return state;
    }
};

export {AppReducers};
export default AppReducers;

Comment: `import {AppReducer} from './reducers';` will be error!
Answer: I use VS Code Insiders and sometimes changes are not saved correctly. So if you followed all of the above and  the error is still there go to each file and press STRG+S. It solved the issue for me.
Answer: i have faced the same problem and it is solved by
const redux = require('redux');
const store = redux.createStore(reducer);

and my reducer is
const reducer = (state = initailState, action)=>{
    if(action.type === 'BUY_CAKE'){

        return {...state, numOfCake : state.numOfCake + 1}
    }
    if(action.type === BUY_ICECREAM){

        return {...state, numOfIceCream : state.numOfIceCream + 1}
    }
}

Answer: When you see this error: Uncaught Error: Expected the reducer to be a function, you must make sure that in src/index.js file, the second argument of the createStore() method must be a function.
This is wrong: const store = createStore(rootReducer, applyMiddleware)
This is ok: const store = createStore(rootReducer, applyMiddleware())
For new updated please use configureStore instead:
This is ok: const store = configureStore(rootReducer, applyMiddleware())


Ubuntu 22.10 display issue on laptop

Question: I have loaded Ubuntu 22.10 on a laptop.  While the install is progressing all looks well.  Afterwards when I boot up the screen does not display correctly.  The resolution is poor, images are distorted, and everything is showing in triplicate spaced out along the screen.  Does not run.
Using the same USB drive I have loaded Ubuntu 22.10 onto another laptop.  It works well, except for the mouse pad doesn't work.  I have to use a usb trackball instead.
Answer:
if possible try:
1)make sure you are connected to the internet.
2)applications==>Software & Updates==> additional drivers and then click on the driver then Apply changes

Ubuntu 22.10 display issue on laptop


Menu organization : conventional or domain-specific?

Question: I'm building a desktop application that is a tool to mount some very domain-specific graphic structures that in the tool's context are called "sequences" (it's not important here I guess).
To help with answering this I must say that the target user of the application is familiar with any visual manipulation tool like Photoshop, Illustrator, Inkscape, Premiere, and mostly any Adobe application. Some of the target users are familiar with other mountage tools and 3D graphic tools.
Each instance of the application allow to edit one unique Project. Each Project contains an unlimited number of Sequences. Once a Project is open, you need to open a Sequence to start editing. You can open several Sequences but only one can be graphically edited at the same time and all the edition views displays informations only for the currently selected Sequence.
This tool is meant to be cross-platform : Windows, MacOS and Linux.
I'm trying to organize the application menu to show the possible actions and I'm having a hard time choosing between a conventional organisation like this one :
File                Edit           Project           Sequence          Views
    New                 Copy           Properties        Properties        ...
        Projet          Cut            ...               ...
        Sequence        Paste
        ...             ...
    Open
        Project
        Sequence
    Close
         Project
         Sequence
    Preferences
    ...
    Quit

... and this less conventional organization that I feel might be more natural for the task ("Designer" is name of the tool):
Designer            Project               Sequence           Edit       Views
    New Project         New Sequence          New Object        Copy       ...
    Open Project        Open Sequence         ....              Cut
    Close Project       Close Sequence        Properties        Paste
    ...                 ...                                     ...
    Preferences
    Quit                Properties

What do you think? I have doubts because I'm not sure if not using the convention will or will not makes the user lost.
Comment: great discussion point, as you have already mentioned this one is for advanced users who are familiar with photoshop .etc kind of application.. as you said going with second options makes it easy for users.
Answer: Does the 'domain-specific' organization actually match the way users naturally model their activities? Would a designer refer to 'projects' and 'sequences' when not using the application? Will they actually understand that a "designer" menu contains project controls (not account / author property data)? There are lots of questions, and I think the only reliable way to answer them is with a real-world A/B test.
That said, I like the idea of your 'domain specific' menu (especially making the first, primary menu deal with the first, primary object - the project, not the individual sequence). I also think it's a good idea to separate the add/remove/close controls for projects and sequences (though you can still do that in a single menu). Still, I really do think convention might mean users accept the 'normal' menu more readily.
Comment: As the tool is meant to allow the users to reach a new field in their domain, that they cannot reach easily at this time, making it uncommon, I guess I cannot answer your first questions without, as you said, real testing.
Comment: I've decided to go with this : I develop each actions separately and make sure there is a single point in the code that tells where should be each action in the menus. Once done, I'll first organize the menus in the domain specific way. When I'll get feedbacks, it will be easy to tweak the menus organisations without having to change too much things. This answer suggesting to first check with real world tests, I'll consider it the best answer.
Answer: The conventional menu seems somewhat forced and unnatural.
I like your unconventional menu much better. It seems much closer to what a user's mental model would be like. Personally I would put the Edit menu as the second after the Designer menu, as the Designer menu sort of maps to the conventional File menu and having Edit as the second menu is something people really expect.
In this case and for such a specific problem domain, I wouldn't worry about not sticking to a convention. Providing a menu that much maps more closely to the concepts they work with is a big plus.
And don't forget that MS is now "hiding" the file menu with its Ribbon interface (it now sits in the app button). In fact you could say that the Ribbon has overthrown the whole conventional menu thing.
Comment: I'm tempted to not have menus but I guess I should still have it at least for the first release.
Comment: Don't just use menus because everyone else does. If you use menus, have a reason. I've found that sometimes a menu just doesn't fit with the flow of an application and toolbars or a ribbon-like interface can work better, or sometimes even something quite different from that (though I would recommend caution in doing something very different - convention *is* very strong and disappointingly often stronger than a distinctly better interface).
Comment: I agree with @Marjan, the conventional menu feels like it's there _to be there_.

Something I've noticed increasingly is that, often, users (power- or otherwise) _don't always know which top level menu item contains the sub-item their looking for_. Typically it's a visual relationship and not a semantic one.
Answer: I would say stick with convention.
Without knowing what a Project/Sequence/Object is, I find the conventional one automatically familiar and I could have a good guess at what to do first - File > New > Project.
In your domain-specific version it seems strange that New Project is not under Project. If I wanted to create a project I would first click on Project, I wouldn't assume that its under Designer.
Also to me it looks ugly to have the 'New' word appended to everything, not that you have any other choice with the layout.
So if you want to stick with the domain-specific, I would:

Remove the Designer menu
Add an Object menu
Put all the Project menu items in the Project menu etc.
Put Preferences under the Edit menu

If you want to stick with the Conventional one, preferences should go under the Edit menu - that's a fairly standard linux convention.


ModelValidationException when models inherit from BaseEntity

Question: I have some models classes that inherit from a single abstract class, which in turn is deriving from BaseEntity
public abstract class Item: BaseEntity
When I try create an Entity Data Model on my context I get the following error:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:
DataLayer.EntityAspect: : EntityType 'EntityAspect' has no key defined. Define the key for this EntityType.
DataLayer.EntityKey: : EntityType 'EntityKey' has no key defined. Define the key for this EntityType.
DataLayer.MetadataStore: : EntityType 'MetadataStore' has no key defined. Define the key for this EntityType.
DataLayer.Validator: : EntityType 'Validator' has no key defined. Define the key for this EntityType.
DataLayer.DataType: : EntityType 'DataType' has no key defined. Define the key for this EntityType.
DataLayer.StructuralType: : EntityType 'StructuralType' has no key defined. Define the key for this EntityType.
DataLayer.ValidationError: : EntityType 'ValidationError' has no key defined. Define the key for this EntityType.
DataLayer.ValidationContext: : EntityType 'ValidationContext' has no key defined. Define the key for this EntityType.
DataLayer.StructuralProperty: : EntityType 'StructuralProperty' has no key defined. Define the key for this EntityType.
EntityAspects: EntityType: EntitySet 'EntityAspects' is based on type 'EntityAspect' that has no keys defined.
EntityKeys: EntityType: EntitySet 'EntityKeys' is based on type 'EntityKey' that has no keys defined.
MetadataStores: EntityType: EntitySet 'MetadataStores' is based on type 'MetadataStore' that has no keys defined.
Validators: EntityType: EntitySet 'Validators' is based on type 'Validator' that has no keys defined.
DataTypes: EntityType: EntitySet 'DataTypes' is based on type 'DataType' that has no keys defined.
StructuralTypes: EntityType: EntitySet 'StructuralTypes' is based on type 'StructuralType' that has no keys defined.
ValidationErrors: EntityType: EntitySet 'ValidationErrors' is based on type 'ValidationError' that has no keys defined.
ValidationContexts: EntityType: EntitySet 'ValidationContexts' is based on type 'ValidationContext' that has no keys defined.
StructuralProperties: EntityType: EntitySet 'StructuralProperties' is based on type 'StructuralProperty' that has no keys defined.
at System.Data.Entity.Core.Metadata.Edm.EdmModel.Validate()
   at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized()
   at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at Microsoft.DbContextPackage.Handlers.ViewContextHandler.ViewContext(MenuCommand menuCommand, Object context, Type systemContextType)
If I remove the BaseEntity inheritance and create an Entity Data Model, it completes successfully.  What is BaseEntity doing to break my model?
The real world problem is that when I am attempting to return the metadata from the DataService.Metadata() call it hits this error too.
Any ideas how to get around this?
Thanks
Comment: Ended up using a "hack" whereby my server side entity models did not derive BaseEntity, but my client side entity models did.  I accomplished this by using partial classes, and file links in VS.
Comment: Attach your entity classes...
Comment: You can create any POCO entity and derive from BaseEntity. If that entity is used in your DbContext it will fail model validation.
Answer: Ended up using a "hack" whereby my server side entity models did not derive BaseEntity, but my client side entity models did. I accomplished this by using partial classes, and file links in VS


Waterproof access door for electrical panel

Question: I had an electrician upgrade my old fuse electrical panel with a new breaker panel. I was trying to save a bit of money and decided I would build the external access door for the main shutoff. However, it seems to be a bigger challenge than I was anticipating.
From the picture you can see the bottom of the panel barely clears the framing stud that runs diagonal when you open it -- circled in red. I originally was just going to frame around the box and attach a door but now that the diagonal board is there I'm not sure what to do.
Does anyone have any suggestion on what I can do here?
Comment: Presuming you are dealing with PG&E here, section 5.4.6 of [their Greenbook](https://www.pge.com/includes/docs/pdfs/mybusiness/customerservice/startstop/newconstruction/greenbook/servicerequirements/greenbook_manual_full.pdf) requires meter shop preapproval of your proposed meter equipment enclosure setup, in addition to any AHJ approvals that may be required....
Comment: Threephase good catch on the PG&E I did not zoom in on the panel.  But since the meter is set and powered up they did not stop them. I did have problems with them back in the 70's for placement, they wanted them readable from the front yard but the feed was from the back in that track of homes.+
Answer: That enclosure is a NEMA 3R, it is designed to be out in the weather. It should be set out to the outside edge of the stucco or cement siding. With it inset, water will get inside the structure because you need to open the panel by Code. Code does allow for a box to hang outside the structure and have a hole drilled in the outside bottom for drainage.
Since your panel is inset, you need to make a water tight cover that can be removed without tools. Since it looks to be your main disconnect, it will have be labeled, and in most cases the meter must be visible for the power company to read. I would never install a panel like this and if you have a contract I don't think this meets most of the service panel requirements in the states I have worked in. A cover that can be opened without tools may be legal but your electric utility may disagree because the meter is not fully exposed.
Comment: Thanks Ed. I'm going to try what Harper mentioned and see what happens.
Comment: He is saying the same as I did make a cover, I was not sure if they would power it up , but notice my comment on three phases post, since they powered it up it must be ok. In Sonoma county in the 70's they (PG&E) would not have powered it up.
Answer: Since you've already installed it, you're "in for a penny, in for a pound".
First, deal with that cross brace. That is designed to prevent that wall from falling down sideways in wind or earthquake.  Pull it out and lop off 1/2" of one end (on the diagonal, of course). Reinstall it and it should sit about an inch lower.  Then go ahead and fit up  horizontal cross braces exactly where you need it to finish your cabinetry.  Or if you have access to the backside you may be able to put cross braces in adjacent spaces, and get rid of that one altogether.
Rather than overthink this, I would just build it like a standard door, weatherproofing and all.  Heck, you could even put an entry lockset in there. A key is a key, not a tool.
Yes, according to their Green Book you will need to get signoff/approval on it, but I have a feeling if you build a competent door frame, they'll be fine with it.  Also your house will have an adorable faerie door (and unfortunately a bunch of iron behind it, so the fae won't like it.)
Comment: Thanks! This is very helpful. Now to figure out how to weatherproof it.


Specs satisfying the `app_settings (from `.symlinks/plugins/app_settings/ios`)` dependency were found, but they required a higher minimum deployment

Question: I run pod install for my Flutter app, I'm getting this error:
[!] CocoaPods could not find compatible versions for pod "app_settings":
  In Podfile:
    app_settings (from `.symlinks/plugins/app_settings/ios`)

Specs satisfying the `app_settings (from `.symlinks/plugins/app_settings/ios`)` dependency were found, but they required a higher minimum deployment target.

Pre-downloading: `FirebaseFirestore` from `https://github.com/invertase/firestore-ios-sdk-frameworks.git`, tag `10.12.0`
cloud_firestore: Using user specified Firebase SDK version '10.12.0'
cloud_functions: Using user specified Firebase SDK version '10.12.0'
firebase_analytics: Using user specified Firebase SDK version '10.12.0'
firebase_auth: Using user specified Firebase SDK version '10.12.0'
firebase_core: Using user specified Firebase SDK version '10.12.0'
Ignoring ffi-1.15.5 because its extensions are not built. Try: gem pristine ffi --version 1.15.5
Ignoring ffi-1.15.1 because its extensions are not built. Try: gem pristine ffi --version 1.15.1
Ignoring ffi-1.15.0 because its extensions are not built. Try: gem pristine ffi --version 1.15.0
Ignoring ffi-1.12.2 because its extensions are not built. Try: gem pristine ffi --version 1.12.2
Ignoring nio4r-2.5.7 because its extensions are not built. Try: gem pristine nio4r --version 2.5.7
Warning: firebase_app_id_file.json file does not exist. This may cause issues in upload-symbols. If this error is unexpected, try running flutterfire configure again.
firebase_crashlytics: Using user specified Firebase SDK version '10.12.0'
firebase_dynamic_links: Using user specified Firebase SDK version '10.12.0'
firebase_messaging: Using user specified Firebase SDK version '10.12.0'
firebase_remote_config: Using user specified Firebase SDK version '10.12.0'
firebase_storage: Using user specified Firebase SDK version '10.12.0'
[!] CocoaPods could not find compatible versions for pod "app_settings":
  In Podfile:
    app_settings (from `.symlinks/plugins/app_settings/ios`)

Specs satisfying the `app_settings (from `.symlinks/plugins/app_settings/ios`)` dependency were found, but they required a higher minimum deployment target.

Podfile version:
platform :ios, '11.0'

Flutter 3.10.6 • channel stable • https://github.com/flutter/flutter.git
Framework • revision f468f3366c (3 weeks ago) • 2023-07-12 15:19:05 -0700
Engine • revision cdbeda788a
Tools • Dart 3.0.6 • DevTools 2.23.1

Answer: if you check the pubspec of app_settings 5.0.0, it mentions iOS 15 being the min deployment target.
If you want to use 5.0.0, you must change your podfile. otherwise, ensure your pubspec file limits the version up to 4.2.1
Answer: I fixed it by running flutter precache --ios.
Answer: Dont know if this will help but mine got fix cause I downloaded the arm64 flutter version where as required


C# Unity 3D add point every full rotation

Question: So i have been looking for about an hour for a solution to my problem and i haven't yet found on so i am on here.
My problem is that i want to count how many full rotations i do, i have a spinning object, and every full rotation i want to keep a score, i cant calculate the time it takes and then add points on like that, because the speed of the spinning object will be constantly changing, so that wont work. I would ideally also be able change the angle at which you gain a point. Or if say every 1 degrees i rotate, it would add a point on like that, anything i would just like to calculate how many times i have rotated. Any help will be greatly appreciated.
Answer: You can get the current x y or z rotation from your gameobject and then in update you can look if it rotated.
Example for 10 unit for one point:

Your gameobject has rotation equals 20 - save that value in a variable called rot outside the update method.
Update is called. Your game objects rotation is now 25 - in update you look if the 10 is fitting in 25 - rot. 25 - rot is 5 - so doesn t fit.
Update is called. Your gameobject rotation is now 42 - calculate: 42 - rot is equals 22. You see it fits. Now calculate how many times 10 fits into 22. It fits 2 times. So add 2 points to the score. Now set rot equals old rot value plus 2 times 10.
Comment: I do not understand how rotating from 20 degrees to 42 degrees works out to 2 full rotations.
Comment: this doesn't work for what i am doing as it is going to be spinning extremely fast, like 50 full rotations per second, but thanks though
Comment: i am completely confused by what you mean with this
Comment: Wait a moment i will try to explain it again
Comment: Not to 2 full rotations. I mean 2 rotations that are giving points. So 20 units.
Comment: Can you post your solution so other people can see how it works?


using htmlspecialchars in value attribute of text input

Question: My question is similar to this question but I'm not using code igniter. I'm echoing variables obtained from a database into the value attribute of a text input. The variables may contain ' or " or any other special chars.
I tried:
<input type="text" name="myTextInput" value="<?= htmlspecialchars($dbValue, ENT_QUOTES); ?>" />

but it outputs quotes as " or ' which is not what I want. I want the text input to actually contain the quotes as typed by the user.
should I be using a php function or a javascript function to escape the string? if I don't escape it I get a javascript error because the quotes inside the $dbValue string are interacting with the value attribute quotes.
Comment: Same problem. I resolved t by using only htmlspecialchars($value); and that's perfect even with é, ô, ñ mixed with '' and "
Answer: That's exactly what you DO want, however. e.g.
if your inserted data is
Davy "Dead Pirate" Jones

and you insert that into an input field literally, you'd end up with
<input type="text" name="..." value="Davy "Dead Pirate" Jones" />

which will be interepreted as follows:
<input> field with attributes:
    text -> 'text'
    name -> '...'
    value -> ' '   (a single space)
    Dead ->
    Pirate ->
    " ?   danging quote
    Jones ->
    " ? -> another dangling quote

By comparion, after doing an html_entities, you'd have
 Davy "Dead Pirate" Jones

and that can be inserted into the <input> field without issue.
If the input field's value contains a literal " that's visible to the user, then you've got some double-encoding going on.
Answer: You'll want to use html_entity_decode. Here's an example for the documentation:
<?php
$orig = "I'll \"walk\" the dog now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll "walk" the <b>dog</b> now

echo $b; // I'll "walk" the dog now
?>

Reference: http://www.php.net/manual/en/function.html-entity-decode.php
Answer: Your looking for the opposite of htmlspecialchars, try using html_entity_decode.
Here is your code using html_entity_decode.
<input type="text" name="myTextInput" value="<?= html_entity_decode($dbValue, ENT_QUOTES); ?>" />

Here is a link to the manual -> http://www.php.net/manual/en/function.html-entity-decode.php
If you have any problems using this you might want to check out this question, which has a common encoding problem -> https://stackoverflow.com/a/4638621/1065786
Answer: To display single, double quotes and html tags as text field value try to use:
<?php
$formVal = htmlspecialchars($dbValue, ENT_COMPAT, 'utf-8');
// or this:
// $formVal = htmlspecialchars($dbValue);
?>

<form>
<input type="text" name="myTextInput" value="<?php echo $formVal; ?>" />
</form>

http://www.sitepoint.com/form-validation-with-php
https://www.inanimatt.com/php-output-escaping.html


What's the use of vertical guide lines when filling out forms using handwriting?

Question: I'm quite fast making shopping lists via handwriting, and I think I'm not alone using small notes instead of trying to make lists in my phone. But when I come to the store and they give me a discount if, and only if, I fill out a form with my personal details. More than once these handwriting forms have vertical support lines which I feel makes my handwriting worse, since I need to concentrate on the horizontal spacing as well as the horizontal size of my handwritten letters.
Are the vertical support lines useful – or could they be omitted altogether making the handwriting easier?
Comment: Harder to write within comb field = Takes longer time to fill out = Clearer handwriting ?
Comment: @JeroenEijkhof Good one - didn't think of it that way :-)
Answer: The vertical support lines, generally, aren't there for the person completing the form, but instead for the person / computer reading it. So that they can ensure they have the correct data, it needs to be as clear as possible, that's why they ask you to complete each word letter by letter spaced significantly so as to determine what the character might be.
Unfortunately, many people's handwriting in this day and age (myself included) is pretty poor. Without the vertical separation, it would be hard for a human (let alone a computer) to decipher what was actually written on the form.
Comment: this is be particularly true for doctors :) I never get a single word from their notice...
Comment: It has been shown that combs do not improve legibility (see my main reply to the original question, below), so while the logic in your thinking seems plausible, it doesn't play out in real life.
Comment: +1, I had a teacher in 2003 that wrote almost everything using a squiggly line.  No loops or anything like you should see in cursive...  It was impossible to read anything handwritten he gave us.
Comment: @FormulateInformationDesign Thanks for your comment (and the downvote), but I would disagree. I know you have referenced a study, and the findings cannot be denied. But the study was conducted a fair while ago now. OCR systems have improved over this time. We have to remember that the use of comb fields is predominantly for the transfer of form information onto a database, usually via an OCR system. Joined handwriting differing from person to person would make it impossible for the OCR to decipher, whereas separated capitals provide a constant for the OCR to recognise.
Comment: Hi Daniel. Yes, the study was conducted a while ago, but that would only be relevant if a) people's handwriting has gotten better over time (which I doubt) and b) OCR systems had gotten worse over time (which, as you acknowledge, they haven't).
The point is that *combs do not improve legibility*. Thus, **combs do not make the data any easier for OCR to decipher**. Put this together with the fact that they slow people down, and combs = bad UX. I'm sorry about the downvote but I think it's important to encourage answers based on research & knowledge of how systems work, not opinion.
Answer: These are known as "Comb fields" and make it easier for your handwriting to be recognized by OCR software. Combed fields also slow down the writer, often making each character easier to read whether OCR is used or not.
Comment: Except the person filling out that particular form seems to be really bad at it. They placed an `I` right on a line, and the numbers in the year missed the boxes entirely.
Answer: In 1980, a researcher named Pam Wright investigated the combs issue and found that:

combs slow the user down; and
combs do not improve legibility.

The published article was "Strategy and Tactics in the Design of Forms", in Visible Language, Vol. 14, No. 2 and it can be requested from the Medical Research Council in the UK and is mentioned in Rob Barnett's comprehensive book "Forms for People".
Hope this helps,
Jessica
Answer: In addition to being easier to scan for OCR systems, such comb fields may also be used to give a hint about the required/expected length.
E.g. in your example it is clear that "DAY" should be 2 characters long and "YEAR" should be 4 characters long (I'm curios why they don't want a numerical month here).
So it's some kind of "validation", especially for fixed-length fields.
Comment: That's another issue with these.  If you happen to have a really long name, it might not fit, even though there might not actually be any technical restriction on the length of the field where the data ends up being stored.

What’s the use of vertical guide lines when filling out forms using handwriting?