text:
Q: Vmware missing last snapshot data file what now? Hi we had some problems with our server filling up because of snapshots then failing to turn on,
I have managed to copy everything across and repair the snapshot descriptor files (hopefully).
The problem is the last snapshot data file in the chain no longer exists.
I have been trying to turn the vm on using Workstation but it gives an error saying it can't find that last file.
What options do I have now?
Vm was created in vmware esxi 4.1 and is an Ubuntu 10.10 64bit vm.
I have tried mounting the vm, but it only mounts the flat file which has really old data on it.
The main .vmdk file contains this, there was 13 snapshots (i know bad), with the 13th one missing.
# Disk DescriptorFile
version=1
encoding="UTF-8"
CID=3fdc2270
parentCID=ffffffff
isNativeSnapshot="no"
createType="vmfs"

# Extent description
RW 1468006400 VMFS "Ubuntu 10.10 64bit-flat.vmdk"

# The Disk Data Base
#DDB

ddb.toolsVersion = "8290"
ddb.adapterType = "lsilogic"
ddb.thinProvisioned = "1"
ddb.geometry.sectors = "63"
ddb.geometry.heads = "16"
ddb.geometry.cylinders = "16383"
ddb.uuid = "60 00 C2 9b 77 97 73 b0-1a 8a 88 8d 95 86 63 92"
ddb.longContentID = "683825f0bd3ea08938742a933fdc2270"
ddb.virtualHWVersion = "7"
ddb.uuid.image = "cb1659d9-62ae-4869-90ea-9690fa7c9adc"
ddb.uuid.modification = "4fe52ccf-d698-488f-970d-369aa3571eb2"
ddb.uuid.parent = "00000000-0000-0000-0000-000000000000"
ddb.uuid.parentmodification = "57854f45-ab17-44d4-aa0a-92c2ba69128c"
ddb.geometry.biosCylinders = "1024"
ddb.geometry.biosHeads = "255"
ddb.geometry.biosSectors = "63"

The .vmk file
#!/usr/bin/vmware
.encoding = "UTF-8"
config.version = "8"
virtualHW.version = "7"
pciBridge0.present = "TRUE"
pciBridge4.present = "TRUE"
pciBridge4.virtualDev = "pcieRootPort"
pciBridge4.functions = "8"
pciBridge5.present = "TRUE"
pciBridge5.virtualDev = "pcieRootPort"
pciBridge5.functions = "8"
pciBridge6.present = "TRUE"
pciBridge6.virtualDev = "pcieRootPort"
pciBridge6.functions = "8"
pciBridge7.present = "TRUE"
pciBridge7.virtualDev = "pcieRootPort"
pciBridge7.functions = "8"
vmci0.present = "TRUE"
nvram = "Ubuntu 10.10 64bit.nvram"
virtualHW.productCompatibility = "hosted"
powerType.powerOff = "soft"
powerType.powerOn = "hard"
powerType.suspend = "hard"
powerType.reset = "soft"
displayName = "Ubuntu 10.10 64bit"
extendedConfigFile = "Ubuntu 10.10 64bit.vmxf"
floppy0.present = "TRUE"
numvcpus = "1"
scsi0.present = "TRUE"
scsi0.sharedBus = "none"
scsi0.virtualDev = "lsilogic"
memsize = "500"
scsi0:0.present = "TRUE"
scsi0:0.fileName = "Ubuntu 10.10 64bit-000007.vmdk"
scsi0:0.deviceType = "disk"
ide1:0.present = "TRUE"
ide1:0.fileName = ""
ide1:0.deviceType = "atapi-cdrom"
floppy0.startConnected = "FALSE"
floppy0.fileName = ""
floppy0.clientDevice = "TRUE"
ethernet0.present = "TRUE"
ethernet0.virtualDev = "e1000"
ethernet0.networkName = "VM Network"
ethernet0.addressType = "generated"
svga.autodetect = "TRUE"
chipset.onlineStandby = "FALSE"
guestOS = "ubuntu-64"
uuid.location = "56 4d 2d 91 89 e0 42 a5-51 dc bf 0f 96 37 99 24"
uuid.bios = "56 4d 2d 91 89 e0 42 a5-51 dc bf 0f 96 37 99 24"
vc.uuid = "52 55 6d 32 84 61 28 32-6d 24 ef ed f8 6f ce d6"
snapshot.action = "keep"
sched.cpu.min = "0"
sched.cpu.units = "mhz"
sched.cpu.shares = "normal"
sched.mem.minsize = "0"
sched.mem.shares = "normal"
ide1:0.startConnected = "FALSE"
ethernet0.generatedAddress = "00:0C:29:01:63:A3"
svga.vramSize = "16777216"
vmci0.id = "1610703779"
tools.syncTime = "FALSE"
cleanShutdown = "TRUE"
replay.supported = "FALSE"
unity.wasCapable = "FALSE"
sched.swap.derivedName = "/vmfs/volumes/4cb58377-099d6cba-3e29-f04da206751f/Ubuntu 10.10 64bit/Ubuntu 10.10 64bit-ef71d4e1.vswp"
scsi0:0.redo = ""
pciBridge0.pciSlotNumber = "17"
pciBridge4.pciSlotNumber = "21"
pciBridge5.pciSlotNumber = "22"
pciBridge6.pciSlotNumber = "23"
pciBridge7.pciSlotNumber = "24"
scsi0.pciSlotNumber = "16"
ethernet0.pciSlotNumber = "32"
vmci0.pciSlotNumber = "33"
vmotion.checkpointFBSize = "33554432"
ethernet0.generatedAddressOffset = "0"
hostCPUID.0 = "0000000b756e65476c65746e49656e69"
hostCPUID.1 = "000106a510100800009ce3bdbfebfbff"
hostCPUID.80000001 = "00000000000000000000000128100800"
guestCPUID.0 = "0000000b756e65476c65746e49656e69"
guestCPUID.1 = "000106a500010800809822010febfbff"
guestCPUID.80000001 = "00000000000000000000000128100800"
userCPUID.0 = "0000000b756e65476c65746e49656e69"
userCPUID.1 = "000106a510100800009822010febfbff"
userCPUID.80000001 = "00000000000000000000000128100800"
evcCompatibilityMode = "FALSE"
checkpoint.vmState.readOnly = "FALSE"
checkpoint.vmState = ""
replay.filename = ""
debugStub.linuxOffsets = "0x0,0xffffffff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0"
ide1:0.clientDevice = "TRUE"
scsi0:0.mode = "persistent"
sched.scsi0:0.shares = "normal"
sched.scsi0:0.throughputCap = "none"
vcpu.hotadd = "TRUE"
mem.hotadd = "TRUE"

Sorted by filename
File Name-parent    Actual chain order
1          -4                 main
2          -1                  3
3          -main           11
4          -13                 12
5          -2
6          -5
7          -6
11         -3
12        -11

    The missing snapshot is 13

A: The snapshot file contains all new data written to disk since the snapshot was took. If you do not have the last snapshot you will lose all data written since the last snapshot. You will need to edit the vmdk file (the small text file, not the *flat.vmdk) and remove the snapshot reference.

A: It is very complicated task. One time I had a same situation.
One snapshot was missed. The missed snapshot was one of the very first (made long time ago).
So what I did: I just copied another one snapshot file and renamed it. And it just worked. But maybe I was very lacy...
But it was not ESX/ESXi, it was VMWare Workstation.
And of course make a backup of all files of the VM before doing anything.


text:
Q: For an L-structure $M$, and a formula $\phi$, in which of the cases does $M \models \phi(x/2)$? For
a) $\phi(x)$ is $(\forall y(y=1+1 \implies x=y))$
b) $\phi(x)$ is $(\forall x(x=1+1 \implies x=y))$
The answer is supposed to be a) but I don't know why. I guess I don't fully understand the notation $M \models \phi(x/2)$ and am therefore not really sure what I am meant to be doing. Any help would be appreciated, thanks!

A: $\phi(x/2)$ means the formula obtained fron $\phi(x)$ (with $x$ free) when the number $2$ is assigned as value to the variable $x$.
Thus, the question :

in which case $M \vDash \phi(x/2)$,

often written as : $M \vDash \phi(x)[2]$, ask if the formula $\phi(x)$ is true in $M$ when the value $2$ is assigned to the free variable $x$.
Now, for
a) when $\phi(x)$ is $∀y(y=1+1 \rightarrow x=y)$
we have that :

$∀y(y=1+1 \rightarrow x=y)[2]$

is $∀y(y=1+1 \rightarrow 2=y)$, which is true in $\mathbb N$.
For
b) when $\phi(x)$ is $∀x(x=1+1 \rightarrow x=y)$
instead, $x$ is not free in $\phi(x)$ and thus we cannot assign $2$ s value to it.
Thus, $\phi(x)[2]$ is simply $\phi(x)$ which is not true : it is enough to assign $1$ to $y$ and we get : $∀x(x=1+1 \rightarrow x=1)$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Drawn current of heating elements in parallel won't add up I have three heating elements (12, 40W) that I want to connect to a single power source (12V, 16A). If I attach one of the heating elements directly, it draws 2,3A @ 12V. But If I attach 3 heating elements in parallel, they draw only 4,3A @ 12V. Can you tell my why its not 2,3A x 3 = 6,9A and how I could achieve that? I am using these heaters. Thanks for your help, appreciate any hint.

A: Ok guys I figured it out! Turned out the wires I have been using were just not ment to deliver that much current. Using some proper wires solved the problem. Thanks everyone for your help!


text:
Q: If a curve $c$ can be reparametrized by arc length, then is $c$ regular? My book is Connections, Curvature, and Characteristic Classes by Loring W. Tu (I'll call this Volume 3), a sequel to both Differential Forms in Algebraic Topology by Loring W. Tu and Raoul Bott (Volume 2) and An Introduction to Manifolds by Loring W. Tu (Volume 1).
I refer to Section 2.1, Section 2.2, Volume 1 Section 8.6 (Part 1), Volume 1 Section 8.6 (Part 2) and this question: Does "$s'(t_0) = ||c'(t_0)||$" actually mean "$s'(t_0) \cong ||c'(t_0)||$" or "$\dot s(t_0) = ||c'(t_0)||$"?

Question: Proposition 2.3 says if $c$ is regular, then $s$ is a diffeomorphism. Conversely, If $s$ somehow is a diffeomorphism, then is $c$ regular?

*

*Context: I'm wondering if Proposition 2.4 should instead start "A regular curve is parametrized..." To be clear, I think Proposition 2.4 says:

*

*
Let $c$ be a (not sure if regular or not) parametrized curve. If $c:[a,b] \to M$, for real numbers $a$ and $b$, can be reparametrized by arc length, i.e. we can define a (regular I guess) curve $\gamma := c \circ t: [\alpha,  \beta] \to [a,b] \to M$ for some diffeomorphism $t$ and for some real numbers $\alpha$ and $\beta$, then $\gamma$, the reparametrized $c$, is also regular and has unit speed and $\alpha = 0.$ (Of course, we later show $\beta = l$.) Conversely, if $c:[a,b] \to M$, for real numbers $a$ and $b$ is such that $c$ has unit speed and $a=0$, ($b=l$ is not used here, but I have a feeling $b=l$ can substitute for $a=0$. Not sure.) then the parameter $t$ of $c=c(t)$, is actually arc length.

*

*I also assume the condition, in Proposition 2.4, "is parametrized by arc length" (or "can be reparametrized by arc length", depending on your version) is equivalent to the conclusion of Proposition 2.3, which is the existence of (Note: Edited to add the word smooth) smooth $s^{-1}$. If this assumption is wrong, then the question in the title is different from the one in the body.

*Updates:

*

*A. I forgot to mention in the previous paragraph that I think the the conclusion of Proposition 2.3 is that $s^{-1}$ exists and is smooth.

*B. I'm actually not sure $t$ is a diffeomorphism for the "is parametrized by arc length". It could be that $t$ is just smooth. But maybe $t$ is a diffeomorphism based on Section 2.1.

*C. I'm actually not sure $s^{-1}$ exists and is smooth is equivalent to "$s$ is a diffeomorphism". Actually, if $c$ is regular, then $s$ is smooth and has a smooth inverse too. If $s$ has an inverse that is smooth (or even just differentiable) and $s$ is smooth, then $c$ I guess is regular, as pointed out in answer below. However, If $s$ has an inverse that is smooth (or even just differentiable) but $s$ is not necessarily smooth, then I'm not sure $c$ is regular. Waiting for response in comments in answer below. I think we need $s$ at least differentiable, which I think follows from FTC, assuming the hypotheses of FTC are satisfied. (I actually ask about the use of FTC here.)

*More context:

*

*Can speed be defined for a parametrized curve that is not regular/not an immersion?

*Does a curve parametrized by arc length have unit speed and its parameter starting at 0 even if not regular/not an immersion?

A: I think one of the issues is that there is no explicit definition of what it means for a curve to be "parametrized by arc length".  The implicit definition use in the proof of 2.4 is that a curve is parametrized by arclength if it is given as   $\gamma(s)=c(t(s))$  for some regular curve $c$, with $t(s)$ the inverse of the arclength function $s(t)$ of $c$. Since Prop 2.3 guaratees that $t(s)$ exists only when $c$ is regular, this definition a priori only makes sense under the assumption that  $c$ is  regular (and of course then $\gamma$ can be proved to is regular as in the second part of Prop 2.4 (in fact $|\gamma'(s)|=1$ so $\gamma'(s)\neq 0$)).
Now your question can be interpreted as "can $t(s)$ exist for non-regular $c$"?
The answer is that if you require $t$ to be differentiable (which is part of saying that $s$ is a diffeomorphism), then it follows that $c$ is regular, since $s(t(s))=s$ and differentiating $s'(t)t'(s)=1$, and by main thm of calculus $s'(t)=|c'(t)|$, so $|c'(t)||t'(s)|=1|$, so $c'(t)\neq 0$ (on the other hand, if you only require $t$ to be a continuous inverse for $s$ then you can find plenty of examples where $c$ is non-regular, and they can then be "reparametrized by a continuous change of parameter"; however the resulting $\gamma(s)$ has no reason to be continuous, much less smooth (but can be arranged to be smooth in some cases)). In summary, if $c$ is regular all the definitions make sense and and resulting $\gamma$ is smooth. If $c$ is not regular, $t(s)$ can not be smooth, but sometimes can still exists, however other things will usually break.


text:
Q: why undefined returns in getElementByTagName I use below code to get the count of p tags in my html document.I have 2 p tags, but this code returns "undefined" for me :
document.write(document.getElementsByTagName('p').childElementCount);

A: childElementCount returns the number of children an individual Node contains.
document.getElementsByTagName() returns a HTMLCollection - containing a collection of Node objects - which doesn't have a childElementCount property.
To get the total number of elements contained within a HTMLCollection, you can simply use its length property:
document.getElementsByTagName('p').length;

A: This should work for you.
console.log(document.getElementsByTagName('p').length)

You can also do this, if you want to get the childElements:
var paragraphs = document.getElementsByTagName('p');
console.log(paragraphs[0].childElementCount);

The problem you're facing is that getElementsByTagName is returning an array-like object of paragraph elements. You need to get one of those elements and then you can call childElementCount on that element.
Paste the above in to the Chrome Console debugger and you should see a value output.
http://jsfiddle.net/bryanray/pwaj4yjd/


text:
Q: Rails dosn't reload class under ajax request I start up rails server like this:
$rails server thin -d

My env is development, for sure.
If request isn't ajax, classes reload.
On client side, I use jQuery for ajax requests.
Snippet on client-side:
$.ajax({
    url: '/products/all',
    success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
 }

});
How to force Rails reload classes under ajax request?


text:
Q: How to remove the space between the header and the beginning of collapsible al Jquery Mobile? I would remove the space between the header and the beginning of the collapsible, I would appreciate if you can help

Test

Title

Content

Title 2

Content 2

[Here is a link with a picture. I would remove the space between the header and the beginning of the collapsible][1]
  [1]: http://afines.com/foro/space.jpg

A:
"There's a 15px padding .... on the content div"

This appears to have been answered here to some extent.  Also, when inspecting the .ui-collapsible-set element using Chrome's Developers tools option I found that there is provision for margin which is set at .5em.
In order to completely remove the space between a header and a collapsible-set the margin requires adjusting using the


text:
Q: 'TemplateDoesNotExist at /' Error in django? The server is working fine, however while using extend for this 'home.html' file unable to link the template :
In 'home.html':
{ % extends "/template1/personal/header.html" % }
While loading localhost:
Django tried loading these templates, in this order:
`Using engine django:

*

*django.template.loaders.app_directories.Loader: /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/ffgg/home.html (Source does not exist).

*django.template.loaders.app_directories.Loader: /usr/local/lib/python2.7/dist-packages/django/contrib/auth/templates/ffgg/home.html (Source does not exist)`

A: 1) Check what is in TEMPLATE_DIRS Variable in settings.py. That is the folder Django looks up in every app in order to find your template.
2) Try remove the leading slash:
{% extends 'template1/personal/header.html' %}
3) if template1 is in TEMPLATE_DIRS, then 'app/template.html' would be enough
{% extends 'personal/header.html' %}
Read on:
https://tutorial.djangogirls.org/en/template_extending/
https://docs.djangoproject.com/en/1.7/topics/templates/


text:
Q: How to set up VS Code for imported modules to work in both debug and test? I am trying to set up a workspace in VS Code and I want to be able to run it in venv.
root
- app
-/- modules
-/-/- __init__.py
-/-/- myModule.py
-/-/- myModule2.py
-/- __init__.py
-/- myApp.py
- test
-/- myTest.py
- venv

myApp.py
import random
import numpy as np

import modules.myModule as mm

x = mm.main()

myModule.py
from app.modules import myModule2

def main():
    x = myModule2()
    return x

myTest.py
import unittest
from app.modules.myModule import main

class Test_Foo(unittest.TestCase):
    def test_bar(self):
        x = main()
        assertEqual(x, 'foobar', 'not equal')

if __name__ == '__main__':
    unittest.main()

The issue I'm having is that my own modules can either be run in debug or in test (as unit test) but the same set up can not run for both. When I have from app.modules import myModule2 I can run test but not debug and when I have from modules import myModule2 I can run debug but not test.
my launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}

my setting.json
{
    "python.testing.unittestArgs": [
        "-v",
        "-s",
        "./test",
        "-p",
        "*test.py"
    ],
    "python.testing.pytestEnabled": false,
    "python.testing.unittestEnabled": true,
    "python.analysis.extraPaths": [
        "./app"
    ]
}

How do I set up my workspace to be able to run both?
I run debug on the file myApp.py, and I run the test from test explorer.
The error I get when running debug is:
Exception has occurred: ModuleNotFoundError
No module named 'app'

The exception is caught in the file myModule.py in line from app.modules import myModule2.

A: The problem with running the test by executing python test/myTest.py is, that the app folder is not on the python path. The unittest module, if launched via its CLI takes care of this automatically if the folder structure is setup accordingly. Detailed information can be found in this post
Long story short:

*

*Add an empty __init__.py file to your /test folder

*Run python -m unittest test/myTest.py
To run all tests that are contained in multiple files named test/*test.py, use the discover option of the unittest package with matching arguments:
python -m unittest discover -s "test/" -p "*test.py"
I set up a VSC project matching the files you described, added the file test/__init__.py and created a virtual environment python venv.
The above option of running tests, I can achieve by adding following configurations to the launch.json file:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: run single test",
            "type": "python",
            "request": "launch",
            "module": "unittest",
            "args": [
                "test/my_test.py"
            ]
        },
        {
            "name": "Python: run all tests",
            "type": "python",
            "request": "launch",
            "module": "unittest",
            "args": [
                "discover",
                "-s",
                "./test",
                "-p",
                "*test.py"
            ]
        }
    ]
}

which worked with debug enabled. I didn't create a setting.json file, so the python.unittest settings were set to default values.

A: Change "program": "${file}" to "module": "app.myApp".
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
//          "program": "${file}",  // Change this
            "module": "app.myApp", // to this
            "console": "integratedTerminal"
        }
    ]
}

Basically, the difference is that:

*

*With "program", Python adds the final directory in ${file} (i.e. /path/to/root/app/) to sys.path (so you can only import modules).

*With "module" or -m, Python adds the current directory (i.e. /path/to/root/) to sys.path (so you can import app) and imports the containing package of app.myApp (i.e. app).

For detailed comparisons, see What is the purpose of the -m switch? (Ctrl+F "Detailed Comparisons").
References:

*

*https://code.visualstudio.com/docs/python/debugging#_module

*https://docs.python.org/3/using/cmdline.html#cmdoption-m

*https://www.python.org/dev/peps/pep-0338/#proposed-semantics


text:
Q: Two dices are rolled 10 times. What is the probability of (1,1) to appear exactly once? Two dices are rolled exactly 10 times. What is the probability for (1,1) to show up :
a) Exactly one time?
b) At least one time? (Two ways of solving b would be helpful)
What I thought would be for:
a)
This is a binomial distribution, therefore, for the (1,1) case to appear exactly once.
It should be:
$(\frac{35}{36})^9  * \frac{1}{36} * {10\choose 1} = \frac{35^9}{36^{10}}*10$ ?
b)
First solution would be calculating the cases when there is no (1,1):
$1 - (\frac{35}{36})^{10}* {10 \choose 1}$.
The second solution would be by calculating all the correct cases (we will use the first point a)):
$\frac{35^9}{36^{10}}* {10 \choose 1} + \frac{35^8}{36^{10}} * {10 \choose 2} + ... + \frac{35^0}{36^{10}}* {10 \choose 10}$

A: The probability of getting any pair of dice values is $\frac{1}{36}$
The probability of rolling snake eyes exactly once in ten rolls is the probability of rolling 9 non-snake eyes and one snake eyes. There are ten orders this can occur in.
$(\frac{1}{36}(1 - \frac{1}{36})^{9}) * {10\choose1} $ ~ .20958
The probability of rolling atleast one snake eyes in ten rolls is one minus the probability of not rolling any snake eyes in ten rolls.
$(1-(1 - \frac{1}{36})^{10})$ ~ .2455


text:
Q: Using UL in place of DIVS - recommended, where to use 1 or the other? been experimenting with unordered list UL and i have seem varios examples of using them in place of divs..
So i a bit confused, when should i use divs and ul..
for example if i have a 3 column layout then i presume i used divs here, although i can use UL
Also on the right column i have lots of formatting to do, the idea was to place divs with divs with in divs ...
can anyone point out when to use one over the other and are there any browser compatibility issues?
I have seen some sites say that ULs are cleaner than divs, but is this the case?
and also people stating you can build a complete layout with ULs and LIs but you would never do it - why?
I think you see where i am going with this, i am just confused about when to use one over the other.
One example is that in my 3rd column (right) - its a div but inside i need to put a rounded BOX so i was think of putting more divs inside this with corner images?
Any help would be really appreciated

A: ULs are list elements. So if you have a set of items that are a list, you would use a UL. A good example is a set of menu options - these work well as ULs.

A: <DIV> is just a block element that is to be formatted by css. <UL> has an additional semantic property; it tells the browser that you are listing things. This may be important for screen readers, text-only browsers etc.

A: UL stands for unordered list. Use it for lists of items where order is irrelevant.
DIV stands for division. Use it to group items.
ULs are cleaner than divs---IF you're doing a list. A menu is mostly a list of links. A gallery has a list of images. A forum has a list of messages, and a list of users.
RE: rounded corners: There's HTML, and there's more semantical HTML. You could use <div> for anything, and you'd hardly note a difference, but using the proper elements will make it easier to understand (both by you when putting the design together, by screen-scrapers trying to find the proper item in the page, and sufficiently-smart search engines identifying fragments of content and navigation elements).
So, in order to do rounded corners, you should consider wether a corner deserves its own content-free div (which, sadly, due to today's rendering engines, it does), or if you can use a better solution (ie, if the sidebar is a fixed size, you can get by with a single background; if you need it to expand in one dimension, you can use two: a top-aligned ceiling, and a bottom-aligned floor on its own "mobile" div (theorically you could avoid the extra div by modifying the bottom element of the div)).

A: personally, I use divs and spans most places for layout, whereas ul's are used for list of links, menu items, thumbnails, etc.

A: People tend to use UL instead of DIV when the elements they are styling are more semantically equivalent to lists (for instance, navigation bars or contents pages), especially in the case where the length of the content may change (when you edit the list later).  In practical terms there is not much difference, although screen readers and other accessible technologies may have an easier time reading a navigation bar if its a list as opposed to a bunch of divs.

A: They are not even close to being identical. A DIV is about as close as you can get to a "clean" element, meaning one that doesn't come with a lot of baggage: padding, margin, etc. To clarify, a DIV acts about the same in Firefox as it does in IE. But a UL (with LI children especially) has different amounts of padding and different behaviors. Try to get the bullets in the LI elements to look the same and you will see what I'm talking about.
One thing that the UL with LI elements is good for, and which hasn't been mentioned here, is to make a wrapping "breadcrumb" trail. You have to set the elements to display inline, but it's a cheap and easy way to get a horizontal flow of boxes without floating a bunch of divs. Yet even here the mileage varies among different browsers. Caveat erector, I guess.


text:
Q: Why are neutrino flavour eigenstates expressed in terms of the elements of the complex conjugate of the PMNS matrix? If we have
$$
                \begin{pmatrix}
                \nu_e\\ \nu_{\mu} \\ \nu_{\tau}
                \end{pmatrix}
                =\begin{pmatrix}
                  U_{e1} & U_{e2} & U_{e3} \\
                  U_{\mu1} & U_{\mu2} & U_{\mu3} \\
                  U_{\tau1} & U_{\tau2} & U_{\tau3}
                  \end{pmatrix}
                  \begin{pmatrix}
                  \nu_1 \\ \nu_2 \\ \nu_3
                  \end{pmatrix},\tag{1}
$$
then why are flavour eigenstates expressed using the complex conjugated elements of the PMNS matrix:
$$
                 |\nu_{\alpha}\rangle=\sum_{i=1}^3U_{\alpha i}^*|\nu_i\rangle,
$$
(where $\alpha = e,\ \mu,\ \tau$) rather than
$$
                 |\nu_{\alpha}\rangle=\sum_{i=1}^3U_{\alpha i}|\nu_i\rangle,
$$
as suggested by $(1)$. Wouldn't it make more sense to define the PMNS matrix as its complex conjugate in the first place?


text:
Q: Conditional Styling in Pandas using other columns I've searched and can't seem to find an answer on this anywhere, so hopefully it's possible.  I have a dataframe, for simplicity I'll include an abbreviated version below.  What I'd like to do is apply a custom formula for styling, or style one particular column based on the values in another column.

Using this as an example, I'd like to highlight the Current column's cells where the Diff > Historic Standard Dev in that row.
I've explored the style.apply approaches, but can't seem to find one that works.  Any help would be greatly appreciated.
Thanks!

A: You can create DataFrame of styles by Styler.apply:
def select_col(x):
    c1 = 'background-color: red'
    c2 = ''
    #compare columns
    mask = x['Diff'] > x['HistoricStandardDev']
    #DataFrame with same index and columns names as original filled empty strings
    df1 =  pd.DataFrame(c2, index=x.index, columns=x.columns)
    #modify values of df1 column by boolean mask
    df1.loc[mask, 'Current'] = c1
    return df1

df.style.apply(select_col, axis=None)


text:
Q: MySQL: обновление счета, при попытке вставки уже существующего игрока Есть запрос:
INSERT INTO `DonateCoins` (`player`, `donateCoins`) VALUES ('test', '20202')

Как сделать, чтобы при выполнении данного запроса, если такой player присутствует в таблице, то к его количеству коинов добавлялось 20202?
В самой таблице есть player - test и donateCoins - 0

A: Можно поступить следующим образом: индексируем столбец player уникальным индексом
ALTER TABLE
  DonateCoins
ADD UNIQUE KEY
  player (player);

Это не позволит вставлять в таблицу DonateCoins дублирующие записи. Вставку новых данных осуществляем INSERT-запросом с ON DUPLICATE KEY UPDATE, в которой прописываем логику обновления поля при обнаружении вставки записи с уже существующим игроком.
INSERT INTO
  DonateCoins (`player`, `donateCoins`)
VALUES
  ('test', '20202')
ON DUPLICATE KEY UPDATE
  donateCoins = donateCoins + VALUES(donateCoins);

В результате, если запись уже существует, donateCoins будет увеличиваться на 20202 (тип столбца должен быть числовым, а не текстовым).


text:
Q: Access Violation: Cannot apply indexing with [] to an expression of type 'object' I have the following variable: _Data.
The variable contains the following info:
_Data Variable
How can i access the message field?
I tried _Data["messages"][0] - but it not wokring.
I recieved the following error: Cannot apply indexing with [] to an expression of type 'object'
What am i doing wrong?
Thanks.

A:
What am i doing wrong?

_Data["messages"]

is returning type object. You need to cast it to List<string> or IList<string> in order to use an indexer.
var indexable = _Data["messages"] as IList<string>; // The image is cut off - not sure if this should be string or not
if (indexable != null)
    return indexable[0];


text:
Q: Trust Relationship between the Primary Domain and the Trusted Domain exception on SecurityIdentifier.Translate In a script task within SSIS, I am running this block of code
SecurityIdentifier sid = new SecurityIdentifier(memberDN.Substring(0, memberDN.IndexOf(",")).Replace("CN=", ""));
try
{
    NTAccount acct = sid. (NTAccount)sid.Translate(typeof(NTAccount));
    LogonName = acct.Value;
}
catch (Exception ex)
{
    Dts.Events.FireError(0, "Example script task", ex.Message + "\n" + ex.StackTrace + "\n Failed MemberDN:" + memberDN, String.Empty, 0);
    Dts.TaskResult = (int)ScriptResults.Failure;
}

This works fine on my local PC in dev environment, but when deployed to the server and run I get this error:
The trust relationship between the primary domain and trusted domain failed at SecurityIdentifier.TranslateToNTAccounts
Failed MemberDN: CN=S-1-5-21-2347892348791324etc.. CN=ForeignSecurityPrincipals,DC=mlol,DC=local
I'm not really sure how to proceed from here, and how to trace this error further.


text:
Q: How to detect when an attribute is modified by calling reflection methods I have the following class
public class MyClass {
   private int myAttr;

   public void setAttr(int a) {
      myAttr = a;
      Thread.dumpStack();
   }
}

That way I can detect any attempt to modify myAttr. Well, almost any. It does not work when someone modifies myAttr using Field.set() method. How can I trap Java reflection usage?

A: You can't. You're at the mercy of the SecurityManager, if one is around, to prevent anyone else from doing nasty things to you.
Related question

*

*How to limit setAccessible to only "legitimate" uses?

A: First you need to ask yourself what you are really worried about here.  Sure - if someone really wanted to, they could subvert your stack tracer.  But why do you really care?  And if you do really care, why are you prepared to run their code at all?
If you really need to do this, you need to create a security sandbox in which to run code that might subvert your stack tracer.  Specifically, you need to create a security manager for which
    securityManager.checkPermission(ReflectPermission("suppressAccessChecks"))

will throw a SecurityException for untrusted code.  Then you create a new classloader using the security manager.
Unfortunately, there doesn't appear to be a way to restrict setAccessible(...) for particular target fields, methods or classes.


text:
Q: PHP using $this when not in object context I have the following class:
class Decode {
    public $code;
    public $codeStore;
    public $store;
    public $varName;
    public $storeNew = array();
    public $storeNew = array();

    public function __construct($code) {
        $this->code = $code;
        $this->codeStore = $code;
        $this->varName = substr($this->code, 0, 30);
        $this->varName = str_replace("var ", "", $this->varName);
        $this->varName = substr($this->varName, 0, strpos($this->varName, "=[\""));
    }

    public function chrToVar() {
        // The line below is line 38
        $this->code = preg_replace_callback('/'.$this->varName.'\[([0-9]+)\]/', function($matches) { return $this->storeNew[$matches[1]]; }, $this->code);
    }
}

$script = new Decode('stuff');
$script->chrToVar();

When I run this code, I get the following error:

Fatal error: Using $this when not in object context in
  /var/www/programs/decode.php on line 38

Why is this happening? I suppose it has something to do with the parameter that has the function in preg_replace_callback, but I have no idea how to fix it.

A: Since PHP 5.4 $this can be used in anonymous functions and it refers to the current object, simple example:
class Decode {
    public $code;

    public function __construct( $code ) {
        $this->code = $code;
    }

    public function chrToVar() {
        $this->code = preg_replace_callback( '/\w+/',
            function( $matches ) {
                var_dump( $this );
            }, $this->code
        );
    }
}

$script = new Decode( 'stuff' );
$script->chrToVar();

For version 5.3 you may use a workaround but it only works with public properties:
$self = $this;
$this->code = preg_replace_callback( '/\w+/',
    function( $matches ) use ( $self ) {
        var_dump( $self );
    }, $this->code
);

My advice is to upgrade at least to 5.4 if possible.
More info: PHP 5.4 - 'closure $this support'


text:
Q: Fill property in raphael js I want to create a sphere in Raphael which should look like

I am using Paper.ellipse with equal horizontal and vertical radius to draw sphere.
I think I need to tweak fill attribute to achieve effect as shown in image. Also I want sphere in different color with same effect.
Can anybody point out any helpful link about fill property in Raphael as I couldn't find enough information?

A: Used
function ball(x, y, r, colour) {
    paper.ellipse(x, y, r, r).attr({
        fill: "r(.3,.25) white-" + colour,
        stroke: "none"
    });
};

You can use any color like yellow or color code like #00CC33 for hue.
Demo.
Demo Source Code.

A: You can watch the source of this page: http://raphaeljs.com/ball.html. Basically, it consists in drawing several ellipses to simulate a single enlightened sphere.
You can learn more about gradient in Raphael on this topic.


text:
Q: Chrome Helper process...without Chrome running Recently I've noticed instances of Google Chrome Helper remaining running in my activity monitor long after I've shut Chrome down completely. Are these just hung processes because Chrome Helper is buggy like that, or should I be worried? They don't show as non-responsive, just... running all by themselves without Chrome itself.

A: It is safe to stop any process named "Google Chrome Helper" as it is only associated with Google Chrome. Since Google Chrome is not open, it is safe to stop them. This answer may help.


text:
Q: Rotação sobre um ponto sobre um pivor 2D em Java Estou tentando descobrir como rodar um vetor sobre um ponto (outro vetor) como um PIVOR tentei em alguns sites que me deu o seguinte código:
public Vector2 rotate_point(float cx,float cy,float angle,Vector2 p)
{
  float s = (float) Math.sin(angle);
  float c = (float) Math.cos(angle);

  // translate point back to origin:
  p.x-= cx;
  p.y -= cy;

  // rotate point
  float xnew = p.x * c - p.y * s;
  float ynew = p.x * s + p.y * c;

  return p;
}

Mas não estou entendendo o que seria essa variável float angle.

A: Esse angle são quantos graus você deseja rotacionar um ponto com relação ao outro.
Dá uma olhada nessa resposta aqui também, ensina uma forma de fazer: https://stackoverflow.com/questions/9985473/java-rotate-point-around-another-by-specified-degree-value


text:
Q: move everything after the 6th backslash up one line with a linux script http://www.somesite/play/episodes/xyz/fred-episode-110
http://www.somesite/play/episodes/abc/simon-episode-266
http://www.somesite/play/episodes/qwe/mum-episode-39
http://www.somesite/play/episodes/zxc/dad-episode-41
http://www.somesite/play/episodes/asd/bob-episode-57

i have many url's saved in a txt file like show above
i want to move everything after the 6th backslash up one line with a script
the txt after the 6th backslash is the title and always different
i need to select the title so i can play it
so i need it to look like this
fred-episode-110
http://www.somesite/play/episodes/xyz/fred-episode-110
simon-episode-266
http://www.somesite/play/episodes/abc/simon-episode-266
mum-episode-39
http://www.somesite/play/episodes/qwe/mum-episode-39
dad-episode-41
http://www.somesite/play/episodes/zxc/dad-episode-41
bob-episode-57
http://www.somesite/play/episodes/asd/bob-episode-57

i have
sed
awk
wget
can this be done

A: Use this command:
awk -F/ '{print $7; print $0}'

E.g.:
awk -F/ '{print $7; print $0}' < file.txt > new-file.txt

A: just to add to this
awk -F/ '{print $7; print $0}' < file.txt > new-file.txt

is there anyway to remove all the hyphens from just the title and leave a space
some of the titles have lots of hyphens
and it makes it a bit hard to read with the hyphens there
change these
simon-episode-2-playing-football-in-the-park
fred-episode-110-the-big-clash-tonight
bob-episode-57

to
simon episode 2 playing football in the park
fred episode 110 the big clash tonight
bob episode 57

thanks for your expertise and time


text:
Q: Likelihood at MLE and transformations, the multivariate normal case Given a univariate sample $\vec X = X_1, ..., X_n$ with standard deviation 1 and a strictly monotone transformation $t: R \to R$ with the property that the standard deviation of $t(\vec X)$ is also 1 (where $t(\vec X)$ is $t$ applied to each $X_i$). If one know fits a normal distribution to $\vec X$ and $t(\vec X)$, one observes the following fact: the likelihood at the respective MLEs of $\vec X$ and $t(\vec X)$ is the same. The reason for that is, that the standard deviation is the MLE for the $\sigma$ parameter of the normal distribution, so just the mean changes, which does not change the likelihood.
In some computations with multivariate data I observed the same fact, using transformations such that $\det(cov(t(\vec X)))=1)$. But I did not see a straightforward proof for that! Note that in the multivariate case, the MLEs for the variance parameters do change, even if the above determinant is always 1.
I am sure I am not the first to notice, but my (somewhat limited) literature on the multivariate normal distribution does not give me a clue how to prove the above statement, i.e. that the multivariate normal likelihood does only depend on the determinant of the $cov(t(\vec X))$, regardless of choice of $t$.
A proof boils down to looking at the terms of the form $x'\Sigma x$ for $\det \Sigma  =  1$.
Do you have more clue?
Thanks, Philipp

A: This is due to the invariance property of MLEs.  It is an elementary exercise in calculus to show that if $E_{MLE}$ maximises the function $F(E)$ then any monotonic function of $E$, say $g=g(E)$ will also be maximised at $g_{MLE}=g(E_{MLE})$.
$F(E)=F[g^{-1}(E)]$ and therefore the maximum occurs at $F_{MAX}=F(E_{MLE})=F[g^{-1}(E_{MLE})]$, which means that $g_{MLE}=g(E_{MLE})$.
If $g(.)$ were not monotone (1-to-1 so that $g^{-1}(.)$ is well defined), then the above argument would not hold.
EDIT: I think this is why the MLE's change for the determinant transformation, perhaps the $t(.)$ function is not a  1-to-1 function.  It is all about the functional properties of your $t(.)$ function (whether it is 1-to-1 or not).
EDIT#2: After some discussion, the transformation $t(.)$ may be 1-to-1, but if the inverse transformation $t^{-1}(.)$ doesn't have a Jacobian of 1, then the value of the likelihood at its maximum will be different.  Fixing the variance to be 1 may one way of achieving this property.
The class of transformations $t(X)$ has a approximate (exact for normals?) covariance of $$cov[t(X)]\approx (\frac{\partial t(x)}{\partial t})_{x=X_{MLE}}^T cov[X](\frac{\partial t(x)}{\partial t})_{x=X_{MLE}}$$.
Fixing the determinant to 1 fixes (approximately)
$$|\frac{\partial t(x)}{\partial t}|^{-2}_{x=X_{MLE}}\approx |cov[X]|$$
Now if $t(.)$ is invertible, the jacobian of the inverse transformation is just the inverse of the jacobian.  SO we have:
$$|\frac{\partial t(x)}{\partial t}|^{-1}_{x=X_{MLE}}=|\frac{\partial t^{-1}(x)}{\partial t}|_{x=X_{MLE}}\approx |cov[X]|^{\frac{1}{2}}$$
Now in the normal distribution, the likelihood evaluated at the MLE, the exponential part just becomes 1.  So the maximised likelihood  for X is given by
$$f_X(x_{MLE}) = \frac{1}{(2\pi)^{\frac{N}{2}} |cov[X]|^{\frac{1}{2}}}$$
using the Jacobian rule for transforming to $T=t(X)$ gives
$$f_T(t_{MLE}) = \frac{|\frac{\partial t^{-1}(x)}{\partial t}|_{x=X_{MLE}}}{(2\pi)^{\frac{N}{2}} |cov(X)|} \approx\frac{|cov[X]|^{\frac{1}{2}}}{(2\pi)^{\frac{N}{2}} |cov[X]|^{\frac{1}{2}}} = (2\pi)^{-\frac{N}{2}}$$
Which is a constant, as your analysis shows (you could even check my calculations, by comparing the likelihood you get with $(2\pi)^{-\frac{N}{2}}$, and see if it is right).  I would imagine that either the approximation is exact for normals, or exact for certain transformations $t(.)$, or becomes exact as $N\rightarrow\infty$, or the approximation error is in decimal places which you checked (or can't calculate), OR the computer you use to get the MLEs of $T$ uses the same approximation technique as I have (called the delta method).


text:
Q: EditText with selectable text is unfocusable My app contains a popup with an EditText. I want the user to be able not to only type and delete text, but to also copy & paste from and to the EditText box.
After searching online I found that the following xml tag should do the trick.
android:textIsSelectable="true"

I added the line but then I can't open the keyboard by clicking on the EditText box.
I found many solutions that open the keyboard explicitly but that isn't what I'm looking for, I want it to open on a click and to allow copying and pasting text with a long click, just like an EditText in the browser, for example.
Adding one of the following doesn't work as well:
<requestFocus />

edit_text.requestFocus();

xml:
        <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textIsSelectable="true"
        android:text=""
        android:textSize="25sp"
        android:gravity="center_horizontal"
        android:inputType="text"
        android:layout_weight="0.1"
        android:id="@+id/editTextPopup_input"
        android:layout_marginEnd="20sp" />

Java:
    public static void inflateEditTextPopup(int parent_id, String content_text, String edit_text_text, String act_button_text)
{
    LayoutInflater layoutInflater = (LayoutInflater)Main.main_activity.getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
    final View popupView = layoutInflater.inflate(R.layout.edit_text_popup, null);
    final PopupWindow window = new PopupWindow(popupView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    window.setFocusable(true);
    final EditText input = (EditText)popupView.findViewById(R.id.editTextPopup_input);
    input.setText(edit_text_text);
    input.setFocusable(true);
    input.requestFocus();

    TextView content = (TextView)popupView.findViewById(R.id.editTextPopup_content);
    content.setText(content_text);

    Button btnClose = (Button)popupView.findViewById(R.id.editTextPopup_cancel);
    btnClose.setOnClickListener(new Button.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            window.dismiss();
        }
    });

    Button btnAct = (Button)popupView.findViewById(R.id.editTextPopup_ok);
    btnAct.setText(act_button_text);
    btnAct.setOnClickListener(new Button.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            handleEditTextPopupInput(window, input.getText().toString());
            window.dismiss();
        }
    });

    LinearLayout parent = (LinearLayout)Main.main_activity.findViewById(parent_id);
    window.showAsDropDown(parent);
}

logcat:
W/TextView: TextView does not support text selection. Selection cancelled.

A: After a lot of searching online I found that there is no answer, because this is a bug in Android, an EditText is not selectable from a PopupWindow.
In my case I used something like a "Paste" button, which is not very comfortable, but good enough for me.


text:
Q: Как сделать низкий fps для видеокамеры на Android Studio? Подскажите пожалуйста, существует ли способ как можно снимать видео с очень низким fps 1-5 кадров/сек? Да, я могу сделать .setCaptureRate(fps), это прекрасный способ, он простой и рабочий как молоток, но он мне вообще не годится. И ладно видео при воспроизведении мелькает как вся жизнь перед смертью - это можно исправить замедлением воспроизведения при просмотре (что уже сулит костылями), но что гораздо хуже - это полное отсутствие хоть какого то звукового сопровождения.
Т.к. я начинающий, то крайне желателен способ попроще и без библиотек, ну а там как будет - харчами не перебирают. .getSupportedPreviewFpsRange() выдал показания моего телефона вот так: l@29f4daf5. Ещё раз, что я хочу: записывать видео с фпс 1-5 к/с и со звуком. Желательно, что бы потом оно ещё и адекватно воспроизводилось.
P.S. Для старых кнопочных Nokia была программа SymDVR - божественное воплощение моих мечт. Вот это то, что я хочу, но в своём приложении.


text:
Q: Why is the baud rate on my port automatically getting updated to match the one on my device? I am making a C# application that talks to a hardware device using the .NET System.IO.Ports.SerialPort interface (the device is connected to the USB port on my laptop using a serial -> USB converter) and one of the steps my application needs to do is change the baud rate from the factory default (38400) to the the one it will eventually need to be using (19200).
So I open the port using the initializer, set the port's baud rate to 38400; everything connects fine, I get coherent messages from the hardware. When I go to change the baud rate on the device to 19200, again, everything works perfectly, I get back a non-garbled message even though I didn't change the baud rate on the port (on my PC side). I feel like they should be speaking different languages at this point.
But when I manually change the port's settings after I change the device's settings (long after the port is open), I then get garbled messages, even though the baud rates should now be aligned. My question is: does .NET somehow automatically know the baud rate changed on the hardware side? Am I fundamentally misunderstanding how all this works?


text:
Q: LAN not working in Ubuntu with Realtek My internet on Ubuntu is not working, but on Windows it is.
I know that my drivers are Realtek.
EDIT
Re-installed Ubuntu.
Internet is working when I edit /etc/resolv.conf
from
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 127.0.1.1
search home

to
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 127.0.1.1
search home
nameserver 8.8.8.8
nameserver 8.8.8.4

How can I make my internet work permanently?
ifconfig -a:
enp2s0    Link encap:Ethernet  HWaddr fc:aa:14:06:2e:84
          inet addr:192.168.2.6  Bcast:192.168.2.255  Mask:255.255.255.0
          inet6 addr: fe80::af5f:9d3e:709e:a2c8/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:38 errors:0 dropped:0 overruns:0 frame:0
          TX packets:57 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:4287 (4.2 KB)  TX bytes:7111 (7.1 KB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:201 errors:0 dropped:0 overruns:0 frame:0
          TX packets:201 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:14922 (14.9 KB)  TX bytes:14922 (14.9 KB)

sudo lshw -C network
[sudo] password for jarno:
  *-network
       description: Ethernet interface
       product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:02:00.0
       logical name: enp2s0
       version: 06
       serial: fc:aa:14:06:2e:84
       size: 100Mbit/s
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=full firmware=rtl8168e-3_0.0.4 03/27/12 ip=192.168.2.6 latency=0 link=yes multicast=yes port=MII speed=100Mbit/s
       resources: irq:30 ioport:e000(size=256) memory:f7c00000-f7c00fff memory:f0000000-f0003fff

lspci | grep Ethernet
02:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 06)


text:
Q: -Objc -lz other linker flag in xcode What does the -lz mean for the other linker flags in xcode. I have often seen this being used with -Objc or can it be used independently also ? What is it's usage ? I am using xcode 7.0.0

A: @Mozilla answered the question for me so closing this issue


text:
Q: Decomposition of 3-dimensional mapping torus into connected sum In the following article
https://www.math.cornell.edu/~hatcher/Papers/3Msurvey.pdf
Hatcher mentioned that there is only one prime
closed 3-manifold with infinite cyclic fundamental group, which is
$S^1\times S^2$.
This implies that the 3-torus $T^3$ can be decomposed as a direct sums of three $S^1\times S^2$. Is it true that $T^3=S^1\times S^2\# S^1\times S^2\# S^1\times S^2$?
This also implies that the 3-dimensional mapping torus $M^3$: $T^2 \to M^3 \to S^1$ (with $S^1$ as the base manifold and $T^2=S^1\times S^1$ as the fiber) can be decomposed as a direct sums of $S^1\times S^2$. How such decomposition is achieved?
In general, I would like to to know the decomposition of 3-dimensional mapping torus into connected sum. In particular the connected sum decomposition of a torus bundle $E^3$: $T^2 \to E^3 \to S^1$.

A: The first part of this answer is merely an elaboration on Marc Kegel and T. Amdeberhan's comments, and addresses the question before the edit. As they say, $T^3$ is prime by virtue of being irreducible (a stronger condition) -- since $\pi_2(T^3)$ is trivial, every embedded 2-sphere is null-homotopic in $T^3$ and it follows that it bounds a ball. This wikipedia page may be helpful for you.
While it is true that $S^1\times S^2$ is the only prime closed 3-manifold with fundamental group $\mathbb{Z}$ (and all infinite cyclic groups are isomorphic to $\mathbb{Z}$), this does not imply that $T^3$ is not prime. (On the off chance this helps, note that $\mathbb{Z}^3$ is not a cyclic group).
In the language of Hatcher's paper, $T^3$ is a prime 3-manifold of type III: it is $K(\mathbb{Z}^3,1)$.  Note also that $T^3$ is a Seifert manifold, thus the following statement in Hatcher's paper is consistent with this:

The only Seifert manifold that is not prime is $\mathbb{RP}^3\#\mathbb{RP}^3$, the sum of two copies of real projective 3-space.

I believe the edit of your question is addressed in the answers to this question.  Namely, torus bundles are irreducible, so they admit no nontrivial connected sum decomposition.


text:
Q: npm run client & npm run server not running properly (won't run at the same time) In the image you can see the scripts I am using, and on the left side is the folders hierarchy.
According to the defined script when I am running npm run watch, it should run server script and client script as well. But it's only running one script server. It never actually runs the client script.
Same thing happens if I put it like npm run client & npm run server in watch script. It runs only client script and never reaches server script.
One more: If I run npm install it doesn't install as defined in the script. Throws error EISDIR (error shown in image).
Please explain why is this happening and how I can fix this.
Thank you

A: there is a npm package called concurrently, you can install it as dev dependency and use it to run your watch script.
first install concurrently: "npm isntall concurrently --save"
then on your script:  "watch": "concurrently "npm run server" "npm run client""
you can now run both server and client from one script.
source: https://www.npmjs.com/package/concurrently

A: Try running this script:
"watch":"npm-run-all --parallel server client"


text:
Q: React Hooks fetch post request memory leak I'm trying to post a login form to my API after a validation callback (useForm) and set the response data in my authentication context (dispatch({ type: "SET_AUTH", payload: responseJson }). It works fine but I still get a memory leak warning. I've been working on this problem for a few days and i think i'm going crazy. I tried using ref and AbortController but can't fix this warning. Thanks for your help !
const Signin: React.FC = () => {
    const { dispatch } = useAuthContext()
    const isMountedRef = useRef<any>(null)

    const defaultValue = {
        email: '',
        password: ''
    }

    const signinDefaultState = {
        loading: false,
        error: undefined,
        data: undefined
    }

    type SigninState<T> = {
        loading: boolean,
        error?: string,
        data?: T
    }

    const [signinState, signinSetState] = useState<SigninState<any>>(signinDefaultState)
    const [validFormData, setValidFormData] = useState(defaultValue)

    const validFormCallback = () => {
        setValidFormData(values)
    }

    const { values, errors, handleChange, handleKeyup, handleSubmit } = useForm(
        defaultValue,
        validFormCallback,
        validate,
    )

    useEffect(() => {

        const abortController = new AbortController()
        isMountedRef.current = true

        if (validFormData.email !== "") {

            const postSignin = async () => {
                const options = {
                    ...authJsonHeader,
                    method: "POST",
                    body: JSON.stringify(validFormData),
                } as any
                try {
                    signinSetState({ ...signinState, loading: true })
                    const response = await fetch(`${process.env.REACT_APP_API_HOST}/signin`, { ...options, signal: abortController.signal })
                    const responseJson = await response.json()
                    if (!response.ok) {
                        throw responseJson
                    }
                    if (isMountedRef.current) {
                        dispatch({ type: "SET_AUTH", payload: responseJson })
                    }
                    //signinSetState({ ...signinState, data: responseJson as string, loading: false })
                } catch (err: any) {
                    console.log(err)
                    if (!abortController.signal.aborted) {
                        signinSetState({ ...signinState, error: err as string, loading: false })
                    }
                }
            }
            postSignin()
        }

        return () => {
            isMountedRef.current = false
            abortController.abort()
        }

    }, [validFormData])

    return (
        <form>

Connecte-toi pour retrouver toutes tes popotes favorites et découvrir celles de tes proches

                <InputField
                    id="email"
                    label="Email"
                    type="email"
                    name="email"
                    value={values.email}
                    onKeyUp={handleKeyup}
                    onChange={handleChange}
                    error={(errors as any).email}
                />

                <InputField
                    id="password"
                    label="Password"
                    type="password"
                    name="password"
                    value={values.password}
                    onKeyUp={handleKeyup}
                    onChange={handleChange}
                    error={(errors as any).password}
                />

                <Button type="primary" onClick={handleSubmit}>Sign In</Button>
                {signinState.error && <InfoBlockStyled>{signinState.error as any}</InfoBlockStyled>}
                {signinState.loading && <LoadingInline />}

        </form>
    )
}

const InfoBlockStyled = styled(InfoBlock)(({ theme }) => ({
    marginTop: theme.spacer.m,
}))

export default Signin


text:
Q: Create materialized view without aggregation using Python Client for Google BigQuery I'm trying to use the Python Client for BigQuery to create a materialized view. The documentation has this example code:
from google.cloud import bigquery

bigquery_client = bigquery.Client()

view_id = "my-project.my_dataset.my_materialized_view"
base_table_id = "my-project.my_dataset.my_base_table"
view = bigquery.Table(view_id)
view.mview_query = f"""
SELECT product_id, SUM(clicks) AS sum_clicks
FROM  `{base_table_id}`
GROUP BY 1
"""

# Make an API request to create the materialized view.
view = bigquery_client.create_table(view)
print(f"Created {view.table_type}: {str(view.reference)}")

When I adapt this code, it creates a table, rather than a materialized view in BigQuery.
There is a table_type attribute for the google.cloud.bigquery.table.Table object, currently set to None.  If I try to set this to "MATERIALIZED_VIEW" before running the create_table() method I get an error:

(AttributeError: can't set attribute)

I can successfully create a materialized view from the Cloud Console just using the following SQL but I need to be able to create the table using a Python deployment.
CREATE MATERIALIZED VIEW  project-id.my_dataset.my_mv_table
AS SELECT product_id, SUM(clicks) AS sum_clicks
FROM  project-id.my_dataset.my_base_table

I'm using google.cloud version 2.1.0, Python version 3.7.6

A: The problem was the version of google-cloud-bigquery was too old.  I updated to 2.6.0 where support was added for materialized views, as documented here and it worked as expected.


text:
Q: Fatal Error while call method from another class I have two view controller.
I have one test method in first view controller as follow
class ViewController: UIViewController {

   @IBOutlet weak var myLabel: UILabel!

   override func viewDidLoad() {
       super.viewDidLoad()
       myLabel.hidden = true

   }

   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }

   func showLabel(){
       myLabel.hidden = false
   }

}

If i call showLabel from another class it give me fatal error: unexpectedly found nil while unwrapping an Optional value
Another viewController is as follow
class SecondViewController: UIViewController {

   override func viewDidLoad() {
       super.viewDidLoad()
   }

   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }

   @IBAction func Save(sender: AnyObject) {
       ViewController().showLabel()
   }
}

If i call showLabel Method from ViewController the its works fine but if i call it from SecondViewController then i got error.

A: Both your view controllers use storyboard/xib; when you create such view controller instance in code (as you do in Save function) you need use UINib class or instantiateViewControllerWithIdentifier method of UIStoryboard class, since default initializers (like init() you used for ViewController) know nothing about outlets and storyboard/xib associated files (outlet property myLabel will always be nil).
If your code not just template, then you should refactor it, because performing UI changes in view controller that not presented on screen (and never will be) not have sense

A: You need use delegate:
1-Creat a protocol with a function describes with you are planning to do.
protocol ViewControllerDelegate: AnyObject {
  func showLabel()
}

2-Add a delegate in your SecondViewController with the type if the protocol ViewControllerDelegate.
class SecondViewController: UIViewController {
  weak var delegate: ViewControllerDelegate? // add delegate
  override func viewDidLoad() {
    super.viewDidLoad()
  }

  @IBAction func Save(sender: AnyObject) {
    delegate?.showLabel() // call the method from delegate
  }
}

3-Implement the ViewControllerDelegate in your ViewController.
class ViewController: UIViewController, ViewControllerDelegate {

3-Set the delegate in the first view controller inside prepareForSegue:
class ViewController: UIViewController {

   @IBOutlet weak var myLabel: UILabel!

   override func viewDidLoad() {
       super.viewDidLoad()
       myLabel.hidden = true

   }

   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }

   func showLabel(){
       myLabel.hidden = false
   }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if let viewController = segue.destinationViewController as? SecondViewController {
            viewController.delegate = self
        }
    }

}

A: It's because your label "myLabel" is always nil.
Your label is part of your first ViewController. The label loads when the view loads. Since the ViewController view has not loaded, the label has not loaded either, and therefore will be nil

A: just add class before function:
class Math{

    class func addition(numberOne: Int, numberTwo: Int) -> Int{

        var ans: Int = numberOne + numberTwo
        return ans
    }
}

Then you can call it from another Swift class like this:
Math.addition(40, numberTwo: 2)

To assign it to a variable i:
let i = Math.addition(40, numberTwo: 2) // -> 42


text:
Q: PyCharm - Is there a way to display the detected file type? Sublime Text uses Ctrl+Alt+Shift+P for this. This shortcut responds with a popup widget which says e.g. text.html.mako. Is there a similar shortcut in the JetBrains family of products?

A: There is a third-party plug-in Override File Language which shows the file type in the status bar and allows to quickly change it.


text:
Q: What is quantum local "unrealism"? Bell's theorem is often interpreted to have destroyed local realism. This means something like the properties of the particle do not exist until they are being measured. I am not sure what does this exactly mean. Can there still be an algorithm to predict those measurements? Can anyone give me an example of a toy theory that is local but non-realist? How such "unreal" variable would be computed and what would the difference with local hidden variables be.
I am not asking for a quantum mechanical theory, just a local no real theory, how is a prediction made? is there an algorithm at all? if there is no algorithm, then what is it, a noncomputable law? a random law? what other options am I missing?

A: An explanation is local if the behavior in one part doesn't depend on the actions in the other part. For example, local operations should commute if they are spacelike separated. You should be able to create two (classical) computer programs that simulate the system, and they don't need to communicate the actions they are taking to each other to produce correct output.
An explanation is realist if the state of the whole system can be described by some probability distribution. You should be able to reproduce the behavior of a local realist system by tallying up how the local computer programs you wrote from before respond to each of the probabilistic cases from the distribution.
An example of a non-realist system is... instead of the various cases from the probability distribution being independent, and adding up the usual linear way, they interact with each other in complicated ways. For example, you might see the system perform behavior like "if the chance that X happened is greater than 10%, cut the chance that Y happened in half" (which is not a valid probabilistic operation because it isn't linear; there is no way to turn it into a stochastic matrix with X and Y as basis vectors).

A: Short answer: the question puts into sharp focus the fact that there are various definitions of the term "local" and "realist", which are in need of careful disambiguation.
It's not possible to give a thorough treatment, but let's give a quick review of the most common definitions.
What is a local theory?
There are two main meanings given to the term local:

*

*Local in the sense of EPR and Bell.
This means "no spooky action at a distance", i.e. the probabilities for the results of a process/procedure are not dependent on procedures performed far away (at space-like separations).

*Local in the sense of no-signaling.
This means no information can be communicated faster than light from one observer to another.
Quantum theory is non-local in the first sense and local in the second. In particular, it's noteworthy that Bohm's pilot wave theory is deterministic and local (in the 2nd sense).
What is a realist theory?
Here there is even more definitional confusion. Let's list a few noteworthy definitions:

*

*Realist in the sense of preexisting information about measurement results.

This means that the system "knows" the value of any property, such as position, momentum etc. prior to measurement. This corresponds to Einstein's notion of "elements of reality".
Another way to say it would be: measurements of properties have definite numerical outcomes, which follow deterministically from the prior state of the system.
A shorthand would be to say that the theory includes hidden variables. Copenhagen quantum mechanics is not realist, but the pilot wave theory is realist in this sense.

*Realist in the sense of determinism.

You might be wondering how the previous definition is different from determinism. The big difference is that determinism does not presuppose that measurements of properties have definite numerical outcomes.
For example, the many world theory is deterministic, but not realist in the first sense, because measurements do not result in definite numerical outcomes, but instead in the branching of the world, with all numerical outcomes existing simultaneously.
A further distinction is that strictly speaking the first definition does not require that the time evolution between measurements be deterministic, only that measurements be deterministic.

*Realist in the sense of "indistinguishable from realist".

Unlike the first definition, where the theory's formalism must already include hidden variables, according to this definition a theory is realist if its predictions can be reproduced by another theory with hidden variables. According to this definition, Copenhagen quantum mechanics would be realist because its predictions are indistinguishable from those of the pilot wave theory.
Any physical theory can be reproduced by a realist2 (deterministic) theory because any source of randomness in the theory's formalism can be reproduced by a deterministic "simulation" of randomness. Therefore any physical theory that has a notion of definite numerical measurement outcomes (so not the many worlds theory) is realist in this third sense.

*Philosophical realism.

To satisfy this definition, the theory needs to be interpreted as describing the actual reality, as opposed to, for example, our subjective experience or epistemological state.
This is not so much an attribute of the theory itself, but a philosophical position on what a theory is, or an interpretation of the relationship between a given theory and reality.
What is local realism?
With so many definitions of the two separate terms floating around (and I certainly haven't covered them all!), it might seem like the combined term is even more ambiguous. However, the situation is not as dire. There seems to be far less disagreement on the meaning of the combined term.
A local realist theory is typically understood to be a theory which is Bell-local (i.e. local in the first sense) and realist in the first sense (measurements are not "chancy"). A shorthand would be to say that the theory includes local hidden variables.
(One alternative definition in the literature involves, instead of "normal", deterministic local hidden variables, having local but stochastic ones. I won't spend too much time on the explanation, but it's not too hard to show that this definition reduces to the theory just being Bell-local.)
What did Bell prove?
There are two opinions floating around. Bell's own opinion was that he proved that the results of quantum mechanics cannot be reproduced by a local (in the sense of Bell/Einstein, i.e. the first sense) theory.
Others think that he proved that they cannot be reproduced by a local realist theory.
Philosopher Tim Maudlin, among others, agrees with Bell. I also agree (see my other answer and comments below it for more details).
What about the original question, about a toy example of a local theory which is not realist?
Now that we have disambiguated the definitions, it should not be too hard to find such an example once we decide which exact definition we will be using.
If we decide to use the first definitions of both terms, then the Mystery Particle would be a good example of a simple local non-realist theory. This particle would be a local object that doesn't have a definite color before we shine our flashlight on it. Once we do, it randomly "chooses" the color to become/show.
Further reading.
Great reading resources have been provided by @MaximalIdeal and @gIS in the comments below the original question.

A: The simplest and most used example would be, within quantum mechanics, the standard scenario of Bell's inequalities (in the CHSH form, for simplicity).
You have two boxes. Each one has two buttons, and according to some internal rule, it can respond to pressing a button with one of two outcomes (think two led lights on top of each box turning on or off).
Denote the probability of observing the outcomes $a$ and $b$ when you press the buttons $x$ and $y$ with $p(ab|xy)$.
You can prove that there are probability distributions $p(ab|xy)$ which cannot be described by any kind of local, realist theory. This means that there is no hidden variable $\lambda$ with distribution $p(\lambda)$ such that
$$p(ab|xy) = \sum_\lambda p_\lambda p_\lambda(a|x) p_\lambda(b|y),\tag1$$
where $p_\lambda(a|x)$ is the the probability of observing the outcome $a$ on the first box when you pressed the input $x$ and the hidden variable is $\lambda$.
One can prove that an entangled quantum state such as $|00\rangle+|11\rangle$, when using appropriate measurement bases, results in a probability distribution which cannot be written as (1). This proves that to describe measurement results in QM you need a theory that is either non-local or non-realist. See e.g. here for the proof.

A: It' important to understand the exact question:

Can anyone give me an example of a toy theory that is local but non-realist?

It seems some people have misinterpreted it as asking for just a non-realist theory, but the question crucially asks that the example also be local.
Here is very familiar example of such a theory, which most people seem to hold to: libertarian free will. This theory says:

*

*Your decision (for example to choose between vanilla and chocolate ice cream) is caused by YOU (your brain/soul), and not by something or somebody far away - locality.

*Your decision is not completely deterministic. Your exact prior state doesn't completely rob you of a "free choice", there is still a chance that you will choose either option - non-realism.
The trouble with this, and any other local non-realist theory, is that it cannot be distinguished from a local theory with hidden variables. For example, maybe there is some kind of invisible deterministic computer above your head that is responsible for your seemingly purely "free", random choices.
Of course, we could come up with many other examples of local non-realistic theories, and they don't have to involve complicated entities like free agents.
For example: suppose there is a Mystery Particle, and whenever you shine your flashlight on it you can see its color. The colors of ordinary objects are determined before you look at them, but suppose this Mystery Particle is different. Suppose that before you shine your flashlight on it it's in some specific definite state O, but the moment you shine the flashlight it probabilistically "decides" to become/show a random color.
But again, if you encountered such a local non-realist particle, you could never rule out that maybe there is some kind of hidden variable, which is responsible for the seemingly random colors.
Finally, you asked about the possibility of predicting the results of measurements:

how is a prediction made? is there an algorithm at all?

Sure, for example by observing many Mystery Particles we can learn that if we prepare it in state O, then whenever we shine a flashlight on it it will become green with probability 12.5%, red with probability 73%, etc.
ADDENDUM. This is less relevant to the actual question, but if you know about Bell's inequalities, you might be wondering if they contradict this claim I made:
"The trouble with this, and any other local non-realist theory, is that it cannot be distinguished from a local theory with hidden variables".
To contradict this claim, we would need to have an example of a theory with two properties:

*

*It's local non-realist

*It cannot be a result of some deeper, local hidden variable theory.

So didn't Bell prove that quantum mechanics is such an example?
No, he proved that quantum mechanics has the second property, not both properties! In fact, not only did he not prove property 1, he actively advocated for its exact opposite - namely for Bohmian pilot wave theory, which is non-local and deterministic!
Note that a pair of entangled particles separated by a large distance is not described in QM by a combination of two local states, i.e. the entangled state is not a tensor product of two one-particle states. (Also note that this statement is not just an idiosyncrasy specific to the Copenhagen interpretation.)
Here is what Wikipedia has to say on the matter:

Quantum nonlocality has been experimentally verified under different physical assumptions.[1][2][3][4][5] Any physical theory that aims at superseding or replacing quantum theory should account for such experiments and therefore must also be nonlocal in this sense; quantum nonlocality is a property of the universe that is independent of our description of nature. Quantum nonlocality does not allow for faster-than-light communication,[6]

A: I am not sure what you mean by "unrealism", unless it is the philosophy (adopted by many physicists) that the reality underlying quantum mechanics cannot be described, and that we should not even try to describe it. In this case one accepts the algorithm that probabilities for the results of measurement are given by the calculations of quantum mechanics (sometimes known as "shut up and calculate").
However, one should distinguish between realism and naive realism. Bell's theorem  does not actually refute realism (local or otherwise) but it does refute naive realism, which I think is what you mean by "local realism". Indeed naive realism is already refuted by the mathematical structure of quantum mechanics even without Bell's theorem. Bell's theorem just underlines the fact in a way which is harder to dispute.
Naive realism means that reality is modelled by our perception, or our classical understanding, that particles always have location in space. Quantum mechanics shows that this is not true. The properties we observe (including the property of position) are not the inherent properties of particles, but they are properties of the way in which particles interact with other matter to produce our observations (and in particular the results of measurements).
Realism simply means that there exists a material reality which is responsible for our perceptions, but it does not say that this material reality is as described by our perceptions. This distinction was made as early as Plato, in his allegory of the cave. I think what you mean by an "unrealist" theory is what I would call a realist theory, but not a naive realist theory.
Perhaps the first such model was Levcippus' notion of atoms in the void. In the original form of this theory the void has no properties. In particular it contains no notion of place, or location.
Interestingly enough, this corresponds precisely to the view (held by Feynman himself) that Feynman diagrams actually do describe underlying reality. Mathematically Feynman diagrams are graphs. A graph means a collection of vertices or nodes and a collection of edges represented as lines connecting pairs of vertices. In a graph, only the connections between lines and vertices have meaning. The position on the paper of the nodes and lines is meaningless (a familiar graph is a map of the London underground, which does not show the geographical relationship of stations). Feynman diagrams are graphs showing a consistent physical structure in which space has no properties. This is a local theory in the sense that particles only have contact when they interact (as shown in vertices).
Then I think that the type of theory you are looking for is that underlying reality is described in this diagram, and the algorithms for predicting measurement results are as given in quantum electrodynamics.

I have given a mathematical account of this view in Mathematical_Implications_of_Relationism


text:
Q: buscar entre dos números en mongodb Tengo una aplicación, que uso mongodb.
{
"_id" : ObjectId("5d70d9152cedd422e4cb648c"),
"budget" : [
    {
        "_id" : ObjectId("5d7129a926a0fe24084a80ca"),
        "price" : [
            {
                "_id" : ObjectId("5d714683576eb13114c93f80"),
                "pricea" : "5",
                "priceb" : "10"
            }
        ]
    }
]
}

{
"_id" : ObjectId("5d70d9152cedd422e4cb648c"),
"budget" : [
    {
        "_id" : ObjectId("5d7129a926a0fe24084a80ca"),
        "price" : [
            {
                "_id" : ObjectId("5d714683576eb13114c93f80"),
                "pricea" : "5",
                "priceb" : "10"
            }
        ]
    }
]
}

Necesito hacer una consulta que muestre todos los documentos, que existan entre los dos precios
Explicación:
cada presupuesto tiene un rango de precio, precioa  y preciob
Un usuario necesita buscar un presupuesto con precioX.
Ese precio X tiene que existir entre (precioa y preciob)
precio del usuario es 7,
La consulta muestra los dos documentos, ya que el precio existe entre precioa y preciob
¿Se puede hacer esto?

A: Si se tiene que poder, prueba con la query siguiente:
precio_usuario = 7

query = {'$and': [{'pricea': {'$lt': precio_usuario}},{'priceb': {'$gt': precio_usuario}}]}

df = db.collection.find(query)

for d in df:
    print(d)

Básicamente lo que le tienes que decir es que se tienen que cumplir las dos condiciones (and), que pricea sea menor (lt) que el precio_usuario, y que priceb ea mayor que el precio_usuario.
Yo lo he hecho con pymongo, pero la query que es lo que tu necesitas suele ser similar o igual (eso creo).
Si quisieras incluir el valor de 'pricea' si también es igual pon $lte (less than equal) y lo mismo con 'priceb' ($gte)


text:
Q: Inconsistent logarithm and rounding Recently while developing a calculator to simplify a game (reactoridle), I ran into one persistent problem. The problem was that when an input number in the GUI was changed into a number between certain boundaries it would immediately snap back to the number below it when pressing enter, sometimes it would even repeat if you pressed enter again.
I figured that one part of the code was somehow inconsistent with another piece, even though the maths behind it were solid.
The first piece of code calculates the heat produced by heat cells, the second recalculates the upgrades required in each component to process that heat.
So say the upgrade you're at right now is right at the boundary of the code working and conflicting, if you then increment the upgrade, it will immediately snap back. As the first piece of code calculates the heat, and the second decides that you could do with one less upgrade to still achieve that heat.
The relevant bits of code are:
double insulationMultiplier = 1 + insulationPerCell * (insulationUpgrades + 1) * INSULATION_HEAT_MODIFIER;
            double upgradeMultiplier = Math.pow(Cell.HEAT_MULTIPLIER, cellUpgrades);
            this.heat = cells * insulationMultiplier * upgradeMultiplier * cell.heat * (1 + 0x4p-50d); //???
                                                                                //avoid trouble when calculating cellUpgrades

            this.calculate(START_FROM_HEAT);

double insulationMultiplier = 1 + insulationPerCell * (insulationUpgrades + 1) * INSULATION_HEAT_MODIFIER;
            double circulatorMultiplier = circulators ? CIRCULATOR_HEAT_MODIFIER * Math.pow(CIRCULATOR_HEAT_MULTIPLIER, circulatorUpgrades) : 1;

            cellUpgrades = (int) ((Math.log(this.heat) - Math.log(insulationMultiplier * cells * cell.heat)) / Math.log(Cell.HEAT_MULTIPLIER));

As you can see, I solved the problem by multiplying the heat calculated in the first part by 1 + 0x4p-50d, this is so that the heat is adjusted just enough to prevent the second part of the algorithm from rounding the upgrade down again and as small as possible to avoid displaying a much different heat value.
The same problem occurs in a parallel piece of code, relevant to the two other components, however on a much larger scale, so that it jumps down multiple numbers at once. I'd prefer not solving it the same way as I've done for the first component, as that would likely collide with other things in turn.
Is there a more rigorous so to speak way to approach this problem?
Thanks in advance.


text:
Q: Bring Live Drupal site to Local Host I've made a local version of my companies live website. My problem is that none of the links work and I can't sign into the admin control panel. I think it has something to do with clean-urls module. Any Ideas? The error I'm getting is url request was not found on this server.

A: If you made a full copy including the database, you must clear all caches, e.g. directly in the database, or using the Devel-Module. If no other settings have changed in the .htaccess, and there is no fixed url given in the settings.php (the $base_url), it should work.


text:
Q: WoCommerce get all variation with price I am trying to get all product variation along with price. I am using below code but price is not coming
$terms = wc_get_product_terms( $product->get_id(), $attribute, array( 'fields' => 'all' ) );

Any idea how i can get price as well along with price as DESC order
Thanks

A: Depending on your need use
$product = wc_get_product(1234); // product ID
$variations = $product->get_available_variations('objects'); // get variations as obj

//Both return array
$variations = $product->get_available_variations();
$variations = $product->get_available_variations('array');

A: You can use this code for variation with the price. I check here if product type variable then it shows.
function show_product_variation(){
    global $product;
    if($product->product_type == 'variable' ){
        $available_variations = $product->get_available_variations();
        $count = count($available_variations)-1;
        echo "
";
        $total = count($available_variations);
        $total -= 1;
        for($i=0;$i<$total;$i++){
            echo $available_variations[$i]['attributes']['attribute_pa_color']."=>".$available_variations[$i]['display_price']."
";
        }
        echo "
";
    }
}
add_action('woocommerce_share','show_product_variation');

Here I attach also a screenshot.

Note: If you want to show it another location you learn about single product hook.


text:
Q: Is there any way to get the single value from HashMap?
When I try to retrieve the values from HashMap I use getValue method. but the getValue method is inside the iteration tag in Struts2 so, it is displaying even unwanted values.
How can I avoid this? here in my JSP page i am creating table, where i want to set the orderdate from database inside the   tags. I mean from HashMap i am receiving orderdate, result, dataamount, count. in  I want orderdate to go and sit and in
 I want remaining three values to go and sit.  How do I do that?
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class JanuaryAction {
    private String from; // creating variables to access input values.
    private String to; // creating variables to access input values.
    Map abc1 = new HashMap(); // Getting the map objects to store tha values

    public Map getAbc1() { /* Creating the setters and getters */
        return abc1;
    }

    public void setAbc1(Map abc1) {
        this.abc1 = abc1;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public Map<String, String> getAbc() {
        return abc;
    }

    public void setAbc(Map<String, String> abc) {
        this.abc = abc;
    }

    Map<String, String> abc = new HashMap<String, String>();

    Map<String, List<ReportClass>> map = new HashMap<String, List<ReportClass>>(); // Using
                                                                                // Map
                                                                                // interface
                                                                                // implementing
                                                                                // hashmap

    public Map<String, List<ReportClass>> getMap() {
        return map;
    }

    public void setMap(Map<String, List<ReportClass>> map) {
        this.map = map;
    }

    public String execute() throws Exception {

        String fromdate = getFrom();
        System.out.println(fromdate);
        String todate = getTo();
        System.out.println(todate);

        Connection con = GetCon.getCon();
        Statement statement = con.createStatement();

        ResultSet resultset = statement
                .executeQuery("SELECT MarketPlace,OrderDate, ROUND(SUM(Total),2), COUNT(*) , ROUND(ROUND(SUM(Total),2)/ COUNT(*),2) FROM vend_printed WHERE OrderDate >='"
                        + fromdate + "' AND OrderDate <='" + todate + "' GROUP BY OrderDate,MarketPlace");

        while (resultset.next()) {
            String marketplace = resultset.getString(1);// get the first column
                                                        // in marketplace
            String orderdate = resultset.getString(2);// get the second column
                                                        // in orderdate
            Double datamount = resultset.getDouble(3);// get the third column in
                                                        // datamount
            Integer count = resultset.getInt(4);// get the fourth column in
                                                // count
            Double result = resultset.getDouble(5); // get the fifth column in
                                                    // result
            ReportClass a = new ReportClass(); // create an object to access
                                                // pojo class.

            a.setMarketplace(marketplace); // setting the values in pojo class
            a.setOrderdate(orderdate);
            a.setDataamount(datamount);
            a.setCount(count);
            a.setResult(result);

            if (map.get(marketplace) != null) { // if the value in marketplace
                                                // is null then go to else
                                                // statement or go to if
                                                // statement.
                map.get(marketplace).add(a); // using the key add one complete
                                                // row values from a to
                                                // marketplace
            } else {
                List<ReportClass> optionsVO = new ArrayList<ReportClass>(); // create
                                                                            // a
                                                                            // list
                                                                            // optionsVo
                optionsVO.add(a); // store Reportclass values in List.
                map.put(marketplace, optionsVO); // storing it in map.
                /* System.out.println(map.get(marketplace).toString()); */
            }

        }
        Set s = map.entrySet(); // A map entry (key-value pair).creating Set
                                // interface.
        Iterator i = s.iterator();
        while (i.hasNext()) {

            List<ReportClass> tempList = (List<ReportClass>) ((Entry) i.next()).getValue(); // creating
                                                                                // a
                                                                                // temporary
                                                                                // list

            for (ReportClass reportClassObj : tempList) {
                System.out.println(reportClassObj.getMarketplace());// display
                                                                    // values.
                System.out.println(reportClassObj.getDataamount());
                System.out.println(reportClassObj.getOrderdate());
                System.out.println(reportClassObj.getCount());
                System.out.println(reportClassObj.getResult());
            }
        }

        /* System.out.println(map.size()); */
        return "success";
    }
}

in my JSP I have a code:
<s:iterator var="studentEntry" status="stat" value="map.entrySet()">
Key: <s:property value="%{#studentEntry.getKey()}"/>
Value: <s:property value="%{#studentEntry.getValue()}"/>

</s:iterator>

A: Whether you group entries you have to iterate groups first, then other entries by group through get all values or choose the group which you want to iterate.
<s:iterator value="map">
 <s:iterator var="studentEntry" value="value">
  ReportClass: <s:property value="%{#studentEntry.toString()}"/>

 </s:iterator>
</s:iterator>

A: Actually you don't need to use entrySet just use map variable as value attribute of <s:iterator> tag and value keyword as value of second iterator. Then you can directly reference properties of your ReportClass inside the iterator in <s:property> tag.
<s:iterator value="map">
  <s:iterator value="value">

<s:property value="orderdate"/>

        <s:property value="dataamount"/>
        <s:property value="count"/>
        <s:property value="result"/>

  </s:iterator>
</s:iterator>

A: try the below code, it must work.
<s:iterator value="map">
<s:iterator value="key">
<s:iterator value="value">
<s:property value="orderdate"/>
<s:property value="marketplace"/>

 <s:property value="dataamount"/>

<s:property value="count"/>

<s:property value="result"/>

</s:iterator>
</s:iterator>
</s:iterator>


text:
Q: Android PreferenceScreen onChangeListener not invoked i wrote a simple PreferenceScreen, looks as follows:
public class SettingsActivity extends PreferenceActivity implements OnPreferenceChangeListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);

    PreferenceScreen prefScreen = getPreferenceScreen();
    prefScreen.setOnPreferenceChangeListener(this);

}

@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    if (preference.getTitle().equals(getString(R.string.settings_diverse_about))) {
        // TODO open about dialog
    }

    return super.onPreferenceTreeClick(preferenceScreen, preference);
}

private static String PATTERN_EMAIL = "[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
private static String PATTERN_TWITTER = "[a-zA-Z0-9_-]+";

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    String prefTitle = preference.getTitle().toString();

    // phone will be fully handled by inputType

    String newStr = newValue.toString();

    if (prefTitle.equals(getString(R.string.settings_contact_email))) {
        return newStr.trim().matches(PATTERN_EMAIL);
    } else if (prefTitle.equals(getString(R.string.settings_contact_twitter))) {
        return newStr.trim().matches(PATTERN_TWITTER);
    }

    return true;
}

The problem is, the onPreferenceChange method gets never invoked.
Furthermore, what do you think about the way of validating the attributes?
I think it's not really optimal.
preference.getTitle().equals(getString(R.string.settings_diverse_about))

A: I had the same problem. I tried to set up a onPreferenceChangeListener but that was wrong. What I really needed was an onSharedPreferenceListener.
OnSharedPreferenceChangeListener listener;

Write this in the onCreate() of your Preference activity:
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        // Here you can work.
        // IMPORTANT:  Beware that at this point the preference has already been changed!
    }
};

SharedPreferences prefs = getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE);
prefs.registerOnSharedPreferenceChangeListener(listener);


text:
Q: Match lines between two patters using sed just once Given: sed -e '/pattern1/,/pattern2/!d' file.org
How can I match the first occurrence of the lines between pattern1 and pattern2, but not the rest?
For example:
pattern1
aaaa
pattern2
pattern1
bbb
pattern

should output:
aaa
Alternatives solutions (using grep, awk or whatever) are welcomed.

A: $ cat input
a
b
c
a
b
c
$ sed -n '/a/,/c/p;/c/q' input
a
b
c

Searches for the range to print, and then quits after seeing the first 'end' marker.
awk makes it a little easier to exclude the start and end points:
$ awk 'BEGIN { p=0 }  /c/ { p=0; exit } p {print} /a/ { p=1 }' input
b


text:
Q: NullPointerException in JUnit I am running this JUint test method, and while running getting an exception NullPointerException. How to handle this exception over here?
@Test
public void testDivision1() {
    System.out.println("testDivision");`
    Operation instance = new Operation(100, 2, null);
    int res = instance.calculate();
    assertEquals(50, res);

}

A: As you pass null for EnumOp operator here
Operation instance = new Operation(100, 2, null);

I assume this operation fails
return operator.calculate(firstOperand, secondOperand);

You should set a valid EnumOp for the test.


text:
Q: I would like to keep first link as default selected with javascript I would like to keep first link as default selected with javascript, here is my code. currently it shows the active state and hover state. But I would like to keep the first link as by default selected and when user click on second link the first link will come at its normal state.:

   Basic

   Network

   Basic3

var selectedElement;
function selectElement(elem) {
    /* Select new element */
    elem.attributes["class"].value = "linkbolds";
    /* Unselect currently selected */
    if (selectedElement) {
        selectedElement.attributes["class"].value = "linkbold";
    }
    selectedElement = elem;
}

A: perhaps this is what you need -
var selectedElement;
function selectElement(elem) {
   /* Select new element */
   elem.className = "linkbolds";//used className instead of attributes["class"].value

   /* Unselect currently selected */
   if (selectedElement) {
      selectedElement.className = "linkbold";//used className instead
   }

   selectedElement = elem;
}

A: If you're using ExtJS, then you can do this like this:
Ext.select('a').on('click', function(e, target){
    Ext.select('a').removeCls('linkbold');
    Ext.get(target).addCls('linkbold');
}, null, {preventDefault:true});

This assumes markup like:

1

2

3

And let's say some CSS like:
a {
    display: block;
    background-color: #ccc;
    color: #fff;
    padding: 2px;
    text-decoration: none;
}

a.linkbold {
    background-color: #c00;
}

See http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Element for more documentation on manipulating Ext elements.

Edit
Updated JavaScript:
Ext.onReady(function(){

    Ext.select('table a').on('click', function(e, target){
        Ext.select('table a').removeCls('linkbold');
        Ext.get(target).addCls('linkbold');
    }, null, {preventDefault:false});

});

Updated HTML:

   Basic

   Network

   Basic3


text:
Q: Can database fields be dragged and dropped (as textboxes, not a gridview) into an ASP.Net form? In VisualStudio, when you drag and drop a table or an individual column from a data connection in server explorer, a gridview is created.
What I want to be able to do is drag and drop the columns to make a quick and dirty detail form to display an individual record.  Is this possible in any way?
An even better way to do this would be via a custom T4 or LLBLGen template but I have no clue how to do this.
Any other suggested approaches?
UPDATE:  A DetailsView is the type of thing I am looking for, in that you can select a data source and the specific columns you want, but I'd like to be able to have manual control of the layout and formatting after the initial drag and drop.

A: I suggest binding a DetailsView to the table using a data source (SqlDataSource) instead. You might find these tutorials, especially this one helpful.
In response to your update, have a look at the FormView control. It gives you complete control of the layout using templated sections.

A: There appears to be literally no way to do this in VS that I have come across.