Tweakable encryption algorithms vs Key wrapping

Question: I have read many articles about Key wrapping and tweakable cipher modes.
However, I don't understand the main difference between them?
What you recommend for Key storage and Key Archive.
Answer: Key wrapping and tweakable encryption are actually quite different topics.
Key wrapping is more commonly related to keys forage and key archive.
Key wrapping
This is fancy terminology for encryption key with another key.
In key wrapping you have a master key that is used to protect one or more keys. It is generally impossible for (computationally constrained adversary) to decrypt wrapped key with no access to appropriate decryption key.
There are key wrapping mechanisms used with asymmetric cryptography, i.e. encryption and decryption with different key (such as RSA-OAEP), and symmetric cryptography, such as AES-KW. Many key wrapping algorithms provide some level of integrity/authenticity protection in addition to encryption.
For purposes of key storage and key archive, key wrapping is very often used.
Key derivation
(As introduction towards tweakable encryption). Key derivation is kind of counterpart of key wrapping. The master key is not used to protect wrapped key, but instead a key derivation algorithm is used to produce other keys from master key. The algorithm may, for instance, generate the keys based on purpose (as identified by "Label") and possibly, other fields related to context. Key derivation can be useful when many keys are needed, but it is not desirable to store all the keys, but only store the master key. (Thus, for key storage, this algorithm is not ideal.)
Tweakable encryption
In some fields, most notably Full Disk Encryption, it is would be desirable to use very large number of cryptographic keys, for instance, to use different cryptographic key per each sector. Conceptually, this is very close to using key derivation to derive per sector keys. Unlike key wrapping, in tweakable encryption the per sector keys are not (usually) stored anywhere.
The tweakable encryption algorithms have been usually implemented with optimization goal that it is very lightweight to change one parameter (tweak).
For purpose of key storage and key archive, in many cases, current tweakable encryption algorithms are of little use. Tweakable encryption (for instance XTS-AES), is mainly intended to protect (lower value) bulk data, in situations where data size extension to allow for integrity/authenticity checking is not an option.
Comment: It is very helpful for me.I understand that if I want to store one key secure I must use Key Wrapping modes(for example SIV), but when I want to archive all keys I can use tweakable algorithm, like a XTS-AES.
Comment: "keys forage and key archive" $\: \mapsto \:$ "key storage and key archives" $\;\;$ ? $\;\;\;\;\;$
Answer: Key wrapping
Key wrapping is used to... wrap keys :) One example: Suppose you want to encrypt a byte array with a public key algorithm like RSA. Since RSA is slow you would rather choose a random key for a symmetric block algorithm like AES, then encrypt the byte array with AES and just encrypt the AES key with RSA.
Now the question is, how to encrypt the AES key with RSA. The trivial approach is to just convert the AES key into a number (for example by the PKCS#1 standard) and then encrpyt this number with the RSA public key. This has some disadvantages. The biggest disadvantage is, that you have to pad the key, since an AES key is at most 256 bits long while the RSA plain text room is like 1024 bits and above. But padding algorithms are often the source for weaknesses. It is just hard to prove that a specific padding scheme is safe (or at least seems to be safe).
A much smarter way to encrypt the AES key is the following:

Let $(n,e)$ be your public RSA key and $(n,d)$ your private RSA key.
Choose a random number $x$ with $2 < x < n-1$.
Encrypt the random number with $x' = x^e \mod n$ (now $x'$ is what you attach to your encrypted message).
Choose a key derivation algorithm (like PBKDF2) and generate a 256-bit hash of your random number $x$ with $k = hash(x)$.
Encrypt your byte array with $k$.

To decrypt your message just:

Unencrypt $x$ with $x = x'^d \mod n$.
Derive the AES key $k$ from $x$ with $k = hash(x)$.
Decrpyt your byte array with $k$.

This is an example for a key wrapping algorithm. It's not designed to encrypt predefined large byte arrays. It's designed to encrypt short data. In this particular example it just creates and then wrappes a random byte array.
Tweakable encryption
Tweakable encrpytion is a mode for symmetric block ciphers. For example CBC mode encrypts the first block with your key (and some initial vector). The key to encrypt the second block then depends on your first block and so on. For tweakable encryption you almost use the same key for every block. The only difference is, that you incorporate for example the block number in the key.
This way again every block has its own key, but with tweakable encryption you can parallize the encryption, since the key for block number $n$ does not depend on block number $n-1$.
Comment: I think you should make the Tweakable section clearer: CBC mode doesn't change the key each block
Comment: Well your right (http://de.wikipedia.org/wiki/Cipher_Block_Chaining_Mode)... The key itself is not changed, but the plain text block is XORed with the previous cipher text block. Still the point holds: One cannot en- or decrypt a block without knowing the previous block. Tweakable encryption does not have this restriction, since every block is encrypted one its own, but the key is changed (for example by incorporating the block number in the key).
Comment: Indeed, but the implication that the key changes (and that therefore the key schedule would need to be rerun) is unclear.


How do I unlock privacy in multiplayer modes mission settings?

Question: Ever since I started playing Mass Effect 3 Multiplayer, the privacy setting in mission settings is locked. I own the legendary or best edition so if there was a code in there I missed it. Is there something I have to do or get a certain amount of characters to level 20?
Comment: I'm assuming you're not referring to the Quick Match screen, where you can only search for public games (and so there is a lock on the team settings thing).
Comment: The "Private" panel you are referring to is the match type for a custom game. You cannot choose a Private mission when choosing Quick Match from the Multiplayer menu.
Comment: It doesn't look locked to me on your screenshot. Are you sure you can't change it to public?
Comment: Sorry for the confusion, that is not my screen. I searched the net for that so people would know exactly what I was talking about in case my questions was confusing.
On mine, there is an actual lock on the right hand side of the Private panel.
Comment: Well call up Hostess and tell them they have a Ding-Dong missing! Thats the only screen I know of. How do I get to the normal online gaming page?
Comment: I'll double check tonight to make sure, but thank you everyone for your help! When I say make sure, I mean that is unlocked in a non-quickmatch.
Answer: When starting a multiplayer game,you have two options: Quick Match and Create New Match.
With Create New Match, you can choose either private game or public game. Public game means that anyone can join. Private game means that only people you invite can join. (And I think your friends can also join without invitation.)
With Quick Match, you search for a game that already exists. And it doesn't make sense to look for a private game, so the option is locked.
To sum up, if you want to create a private game, use Create New Match, not Quick Match.
Also, there are no requirements for this, you can always do it .


Is it possible for AlphaGo Zero to use recurrent networks to achieve similar performance?

Question: AlphaGo Zero stacks 7 board history along with the current board together to form the input to the network. However, is it possible to use an RNN to replace the input of history and achieve similar performance? Are there any practical reasons for the team to choose stacking history states rather than using a RNN?
Answer: I can't think of any reason why using an RNN wouldn't work in theory.
In practice RNNs are slightly harder to train (they can be unstable, and ever more practically you have to deal with multiple network inputs), so they just went with the easiest solution that worked.
In the followup work MuZero an RNN is used to predict future states from a starting state and played moves, which is a harder task and it does work, so it would be possible to do something similar for AlphaZero too.


How does Python's bitwise complement operator (~ tilde) work?

Question: Why is it that ~2 is equal to -3?  How does ~ operator work?
Answer: Remember that negative numbers are stored as the two's complement of the positive counterpart. As an example, here's the representation of -2 in two's complement: (8 bits)
1111 1110

The way you get this is by taking the binary representation of a number, taking its complement (inverting all the bits) and adding one. Two starts as 0000 0010, and by inverting the bits we get 1111 1101. Adding one gets us the result above. The first bit is the sign bit, implying a negative.
So let's take a look at how we get ~2 = -3:
Here's two again:
0000 0010

Simply flip all the bits and we get:
1111 1101

Well, what's -3 look like in two's complement? Start with positive 3: 0000 0011, flip all the bits to 1111 1100, and add one to become negative value (-3), 1111 1101.
So if you simply invert the bits in 2, you get the two's complement representation of -3.
The complement operator (~) JUST FLIPS BITS. It is up to the machine to interpret these bits.
Comment: One other thing maybe to mention is that the flip is called 1s complement, before adding the 1.
Comment: It might helps others who are not aware of One's Complement and Two's Complement. Read about them here.

http://en.wikipedia.org/wiki/Ones%27_complement
http://en.wikipedia.org/wiki/Two%27s_complement
Comment: How does the machine know it is getting a two complement negative number instead of a higher positive number?  Is it because of the type system of the respective language indicating that the type is a signed int versus unsigned?
Comment: Isn't that the bitwise NOT operator?
Comment: @GL2014 I think you answered your own question there. In my understanding, it's how the machine was designed to work on in the first place.
Comment: Just one question : How can we tell for example that `1111 1101` gives us -3 and not 253. How do we know it's supposed to be negative when just looking at the binary representation ?
Comment: @Ellone your question was addressed in the answer: "The first bit is the sign bit, implying a negative."
Comment: @BradenBest it is often referred to as that, yes. It provides the inverse of the value - i.e. any bits that are NOT value 1 in the operand will be value 1 in the result, the same is true for bits that are NOT value 0 in the operand becoming value 0 in the result.
Comment: Unfortunately this answer didn't clarify things for me. Only now that I understand what's going on, I see what you meant: "`~2 == 0b..101`, `-3 == 0b..101`, therefore `~2 == -3`". It's best to explain things as they happen in real life. `~2 == 0b..101`. It's a negative number (`MSB == 1`). To output a negative number, `ruby` prints `-`, then two's complement of the value. For more details, check out [my answer](https://stackoverflow.com/a/58699443/52499)
Comment: This answer/explanation is very confusing. It leads people to believe that the ~ is taking the two's complement rather than the ones' complement. It makes much more sense to start by saying the ~ operator simply flips the bits (such a simple point to start!) and then state the effect this has in a processor (or number system) that uses two's complement.
Comment: Is there any use of Unary operations in real world programming?
Answer: ~ flips the bits in the value.
Why ~2 is -3 has to do with how numbers are represented bitwise. Numbers are represented as two's complement.
So, 2 is the binary value
00000010

And ~2 flips the bits so the value is now:
11111101

Which, is the binary representation of -3.
Comment: Depends if it represents a signed or unsigned integer.
Comment: Isn't 11111101 == decimal 253 vs -3?
Comment: What is its use in real world programming ? Does it has applications in competitive programming?
Comment: @driis, `System.out.println((byte)(~2));` still outputs -3 instead of 253, may you explain why?
Comment: byte is a signed type the range is -128 .. 127
Answer: As others mentioned ~ just flipped bits (changes one to zero and zero to one) and since two's complement is used you get the result you saw.
One thing to add is why two's complement is used, this is so that the operations on negative numbers will be the same as on positive numbers. Think of -3 as the number to which 3 should be added in order to get zero and you'll see that this number is 1101, remember that binary addition is just like elementary school (decimal) addition only you carry one when you get to two rather than 10.
 1101 +
 0011 // 3
    =
10000
    =
 0000 // lose carry bit because integers have a constant number of bits.

Therefore 1101 is -3, flip the bits you get 0010 which is two.
Answer: This operation is a complement, not a negation.
Consider that ~0 = -1, and work from there.
The algorithm for negation is, "complement, increment".
Did you know?  There is also "one's complement" where the inverse numbers are symmetrical, and it has both a 0 and a -0.
Answer: I know the answer for this question is posted a long back, but I wanted to share my answer for the same.
For finding the one's complement of a number, first find its binary equivalent. Here, decimal number 2 is represented as 0000 0010 in binary form. Now taking its one's complement by inverting (flipping all 1's into 0's and all 0's into 1's) all the digits of its binary representation, which will result in:
0000 0010 → 1111 1101

This is the one's complement of the decimal number 2. And since the first bit, i.e., the sign bit is 1 in the binary number, it means that the sign is negative for the number it stored. (here, the number referred to is not 2 but the one's complement of 2).
Now, since the numbers are stored as 2's complement (taking the one's complement of a number plus one), so to display this binary number, 1111 1101, into decimal, first we need to find its 2's complement, which will be:
1111 1101 → 0000 0010 + 1 → 0000 0011

This is the 2's complement. The decimal representation of the binary number, 0000 0011, is 3. And, since the sign bit was one as mentioned above, so the resulting answer is -3.
Hint: If you read this procedure carefully, then you would have observed that the result for the one's complement operator is actually, the number (operand - on which this operator is applied) plus one with a negative sign. You can try this with other numbers too.
Comment: It's flip, flip, add. First flip for 1's complement. And since, it is stored in 2's complement in the system, when you need to display the number, it will show the 2's complement of the number stored (i.e., second flip and add).
Comment: From what you're describing and everything I've researched, this is not a two's complement, but a "regular" complement, or a bitwise NOT. In logic, `NOT 0 = 1` and `NOT 1 = 0`. In a four-bit system, `NOT 0011` (3) = `1100` (12 unsigned, -4 signed). From what I understand, two's complement is defined as `(NOT n) + 1`, and is used to find the negative counterpart of a number regardless of the number of bits. Thus, `2c(5) = -5`. See, now it makes perfect sense. Just as long as you call this operation what it is: a bitwise NOT.
Comment: Why is it adding twice? I'm seeing `add, flip, add`. `0010` -> `0011` -> `1100` -> `1101`
Comment: But wouldn't flip(flip(2)) just be 2? `0010` `1101` `0010`
Comment: Yes it will be 2 only. But since when the bits are stored in memory the most significant bit was 1 which will make the number negative later on as explained in the answer above.
Comment: Case in point: [1](http://pastebin.com/1nXgd4aQ), [2](http://pastebin.com/smWNtTHN)
Comment: This is the only answer (except [mine](https://stackoverflow.com/a/58699443/52499) :)) that explain things in a non-counterintuitive manner. Although the last comment of the author is confusing. @BradenBest You might want to check out my answer as well. Hopefully, that'll answer your questions. But to brief you, `~` is bitwise NOT (or complement). When `ruby` outputs a negative value, it prints `-`, then two's complement (`~x + 1`) of the value. Therefore, `-(~~x + 1)`. It's flip, flip, add. And minus sign.
Answer: int a=4;
System.out.println(~a);
Result would be :-5
'~' of any integer in java represents 1's complement of the no.
for example i am taking ~4,which means in binary representation 0100.
first ,
length of an  integer is four bytes,i.e 4*8(8 bits for 1 byte)=32.
So in system memory 4 is represented as
 0000 0000 0000 0000 0000 0000 0000 0100
now ~ operator will perform 1's complement on the above binary no
i.e 1111 1111 1111 1111 1111 1111 1111 1011->1's complement
the most significant bit represents sign of the no(either - or +)
if it is 1 then sign is '-'
if it is 0 then sign is '+'
as per this our result is a negative number,
in java the negative numbers are stored in 2's complement form,
the acquired result  we have to convert into 2's complement( first perform 1's complement  and just add 1 to 1's complement).
all the one will become zeros,except most significant bit 1(which is our sign representation of the number,that means for remaining 31 bits
1111 1111 1111 1111 1111 1111 1111 1011  (acquired result of ~ operator)
1000 0000 0000 0000 0000 0000 0000 0100  (1's complement)
                                      1   (2's complement)
1000 0000 0000 0000 0000 0000 0000 0101
now the result is -5
check out this link for the video <[Bit wise operators in java] https://youtu.be/w4pJ4cGWe9Y
Answer: Simply ...........
As 2's complement of any number we can calculate by inverting all 1s to 0's and vice-versa than we add 1 to it..
Here N= ~N produce results -(N+1) always. Because system store data in form of 2's complement which means it stores ~N like this.
  ~N = -(~(~N)+1) =-(N+1).

For example::
  N = 10  = 1010
  Than ~N  = 0101
  so ~(~N) = 1010
  so ~(~N) +1 = 1011

Now point is from where Minus comes. My opinion is suppose we have 32 bit register which means 2^31 -1 bit involved in operation and to rest one bit which change in earlier computation(complement) stored as sign bit which is 1 usually. And we get result as ~10 = -11.
~(-11) =10 ;
The above is true if printf("%d",~0);  we get result:  -1;
But printf("%u",~0) than result: 4294967295 on 32 bit machine.
Answer:
The Bitwise complement operator(~) is a unary operator.
It works as per the following methods
First it converts the given decimal number to its corresponding binary
value.That is in case of 2 it first convert 2 to 0000 0010 (to 8 bit binary number).
Then it converts all the 1 in the number to 0,and all the zeros to 1;then the number will become 1111 1101.
that is the 2's complement representation of -3.
In order to find the unsigned value using complement,i.e. simply to convert 1111 1101 to decimal (=4294967293) we can simply use the %u during printing.
Answer: It's easy:
Before starting please remember that
 1  Positive numbers are represented directly into the memory.
 2. Whereas, negative numbers are stored in the form of 2's compliment.
 3. If MSB(Most Significant bit) is 1 then the number is negative otherwise number is
    positive.

You are finding ~2:
Step:1 Represent 2 in a binary format
       We will get, 0000 0010

Step:2 Now we have to find ~2(means 1's compliment of 2)
                  1's compliment
       0000 0010 =================> 1111 1101

       So, ~2 === 1111 1101, Here MSB(Most significant Bit) is 1(means negative value). So,
       In memory it will be represented as 2's compliment(To find 2's compliment first we
       have to find 1's compliment and then add 1 to it.)

Step3:  Finding 2's compliment of ~2 i.e 1111 1101

                   1's compliment                   Adding 1 to it
        1111 1101 =====================> 0000 0010 =================> 0000 0010
                                                                      +       1
                                                                      ---------
                                                                      0000 0011
        So, 2's compliment of 1111 1101, is 0000 0011

Step4:  Converting back to decimal format.
                   binary format
        0000 0011 ==============> 3

       In step2: we have seen that the number is negative number so the final answer would
       be -3

                                So, ~2 === -3

Answer: Simply speaking, ~ is to find the symmetric value (to -0.5).
~a and a should be symmetric to the mirror in the middle of 0 and -1.
-5,-4,-3,-2,-1 | 0, 1, 2, 3, 4
~0 == -1
~1 == -2
~2 == -3
~3 == -4

The reason for this is due to how computers represent negative values.
Say, if positive value uses 1 to count, negative value uses 0.
1111 1111 == -1

1111 1110 == -2; // add one more '0' to '1111 1111'

1111 1101 == -3; // add one more '0' to '1111 1110'

Finally, ~i == -(i+1).
Answer: I think for most people the confusion part comes from the difference between decimal number and signed binary number, so lets clarify it first:
for human decimal world:
01 means 1,
-01 means -1,
for computer's binary world:
101 means 5 if it is unsigned.
101 means (-4 + 1) if is signed while the signed digit is at position x.
|
x
so 2's flipped bit = ~2 = ~(010) = 101 = -4 + 1 = -3
the confusion comes from mixing up the signed result(101=-3) and the unsinged result(101=5)
Answer: Basically action is a complement not a negation .
Here x= ~x produce results -(x+1) always .
x = ~2
-(2+1)
-3
Answer: tl;dr ~ flips the bits. As a result the sign changes. ~2 is a negative number (0b..101). To output a negative number ruby prints -, then two's complement of ~2: -(~~2 + 1) == -(2 + 1) == 3. Positive numbers are output as is.
There's an internal value, and its string representation. For positive integers, they basically coincide:
irb(main):001:0> '%i' % 2
=> "2"
irb(main):002:0> 2
=> 2

The latter being equivalent to:
irb(main):003:0> 2.to_s
"2"

~ flips the bits of the internal value. 2 is 0b010. ~2 is 0b..101. Two dots (..) represent an infinite number of 1's. Since the most significant bit (MSB) of the result is 1, the result is a negative number ((~2).negative? == true). To output a negative number ruby prints -, then two's complement of the internal value. Two's complement is calculated by flipping the bits, then adding 1. Two's complement of 0b..101 is 3. As such:
irb(main):005:0> '%b' % 2
=> "10"
irb(main):006:0> '%b' % ~2
=> "..101"
irb(main):007:0> ~2
=> -3

To sum it up, it flips the bits, which changes the sign. To output a negative number it prints -, then ~~2 + 1 (~~2 == 2).
The reason why ruby outputs negative numbers like so, is because it treats the stored value as a two's complement of the absolute value. In other words, what's stored is 0b..101. It's a negative number, and as such it's a two's complement of some value x. To find x, it does two's complement of 0b..101. Which is two's complement of two's complement of x. Which is x (e.g ~(~2 + 1) + 1 == 2).
In case you apply ~ to a negative number, it just flips the bits (which nevertheless changes the sign):
irb(main):008:0> '%b' % -3
=> "..101"
irb(main):009:0> '%b' % ~-3
=> "10"
irb(main):010:0> ~-3
=> 2

What is more confusing is that ~0xffffff00 != 0xff (or any other value with MSB equal to 1). Let's simplify it a bit: ~0xf0 != 0x0f. That's because it treats 0xf0 as a positive number. Which actually makes sense. So, ~0xf0 == 0x..f0f. The result is a negative number. Two's complement of 0x..f0f is 0xf1. So:
irb(main):011:0> '%x' % ~0xf0
=> "..f0f"
irb(main):012:0> (~0xf0).to_s(16)
=> "-f1"

In case you're not going to apply bitwise operators to the result, you can consider ~ as a -x - 1 operator:
irb(main):018:0> -2 - 1
=> -3
irb(main):019:0> --3 - 1
=> 2

But that is arguably of not much use.
An example Let's say you're given a 8-bit (for simplicity) netmask, and you want to calculate the number of 0's. You can calculate them by flipping the bits and calling bit_length (0x0f.bit_length == 4). But ~0xf0 == 0x..f0f, so we've got to cut off the unneeded bits:
irb(main):014:0> '%x' % (~0xf0 & 0xff)
=> "f"
irb(main):015:0> (~0xf0 & 0xff).bit_length
=> 4

Or you can use the XOR operator (^):
irb(main):016:0> i = 0xf0
irb(main):017:0> '%x' % i ^ ((1 < "f"

Answer: here, 2 in binary(8 bit) is 00000010 and its 1's complement is 11111101,
subtract 1 from that 1's complement we get 11111101-1 = 11111100,
here the sign is - as 8th character (from R to L) is 1
find 1's complement of that no. i.e. 00000011 = 3
and the sign is negative that's why we get -3 here.
Answer: This operator comes into bitwise operators means those operators which works with bits these operators can manipulate the bits.
There are different type of bitwise operators :

Bitwise AND( & )
Bitwise OR ( | )
Bitwise XOR (^)
Bitwise compliment (~)
Bitwise leftshift (<<)
Bitwise rightshift (>>)

The "~" operator in many programming languages is also called as the bitwise NOT operator. It performs a bitwise inversion on the binary representation of a number.
In most programming languages, including Python, integers are represented using a fixed number of bits, typically 32 or 64.
I am just using example of 8 bit (for fast and better understanding).
The binary representation of 2 is "00000010" (8 bits), and the bitwise NOT of 2 would invert each bit, resulting in "11111101". This binary representation, when interpreted as a signed 8-bit integer, is equal to -3.
[ Here 8-bit are only used only for example you must use 32 or 64 bits].
Binary representation of 2 in 32 bits:  00000000000000000000000000000010
And after using ~ operator
11111111111111111111111111111101
The reason for this is due to the two's complement representation of signed integers. In this representation, the most significant bit (the leftmost bit) represents the sign of the number. If it is 0, the number is positive(+) and if it is 1, the number is negative(-).
When you perform a bitwise NOT on a positive number, it flips all the bits, including the sign bit, resulting in a negative number in two's complement representation.
It's important to note that the actual result may vary depending on the programming language and the number of bits used to represent integers. Which example I provided assumes a 8-bit signed integer representation commonly used in many programming languages for a basic understanding.
Comment: This is not generated by ChatGPT, This is creation of my mind this is my mind solution, you know nothing you are just guessing and I think this is your work on this platform. Do you know who I am, completed BTech in CSE from IIT Delhi,India.
Comment: Could you please edit this for clarity?  I am having trouble parsing it.
Comment: Welcome to Stack Overflow!

Your answer appears likely to have been written (entirely or partially) by AI (e.g., ChatGPT). A heads-up that [posting AI-generated content is not allowed here](//meta.stackoverflow.com/q/421831). If you used an AI tool to assist with any answer, I would encourage you to delete it.

We do hope you'll continue to be a part of our community and contribute with *your own*, quality posts in the future. Thanks!
Comment: **Readers should review this answer carefully and critically, as AI-generated information often contains fundamental errors and misinformation.** If you observe quality issues and/or have reason to believe that this answer was generated by AI, please leave feedback accordingly.
Answer: First we have to split the given digit into its binary digits and then reverse it by adding at the last binary digit.After this execution we have to give opposite sign to the previous digit that which we are finding the complent
~2=-3
Explanation:
2s binary  form is 00000010 changes to 11111101 this is ones complement ,then complented 00000010+1=00000011 which is the binary form of three and with -sign I.e,-3
Answer: The bit-wise operator is a unary operator which works on sign and magnitude method as per my experience and knowledge.
For example ~2 would result in -3.
This is because the bit-wise operator would first represent the number in sign and magnitude which is 0000 0010 (8 bit operator) where the MSB is the sign bit.
Then later it would take the negative number of 2 which is -2.
-2 is represented as 1000 0010 (8 bit operator) in sign and magnitude.
Later it adds a 1 to the LSB (1000 0010 + 1) which gives you 1000 0011.
Which is -3.
Answer: Javascript tilde (~) coerces a given value to the one's complement--all bits are inverted.
That's all tilde does. It's not sign opinionated. It neither adds nor subtracts any quantity.
0 -> 1
1 -> 0
...in every bit position [0...integer nbr of bits - 1]

On standard desktop processors using high-level languages like JavaScript,  BASE10 signed arithmetic is the most common, but keep in mind, it's not the only kind. Bits at the CPU level are subject to interpretation based on a number of factors. At the 'code' level, in this case JavaScript, they are interpreted as a 32-bit signed integer by definition (let's leave floats out of this). Think of it as quantum, those 32-bits represent many possible values all at once. It depends entirely on the converting lens you view them through.
JavaScript Tilde operation (1's complement)

BASE2 lens
~0001 -> 1110  - end result of ~ bitwise operation

BASE10 Signed lens (typical JS implementation)
~1  -> -2

BASE10 Unsigned lens
~1  -> 14

All of the above are true at the same time.
Answer: Here is a way it can be explained :
let's take the case of why ~2 = -3,(explained using the 8-bit system for simplicity)
1)we've 2 ---> 00000010
2)we can get ~2 ---> 11111101 #by simply switching the bits.
[but the common mistake is that some try to convert the binary value of ~2 obtained directly to decimal(base 10) numbers, in this case, it's 253. This is not how we find complements.]
3)now we find a binary number which on adding to the binary value of 2~ gives 0 (00000000) as the result.
In this case, it is 00000011 (which is 3), since if we add 00000011 to 11111101 that we have, we get 100000000, but since we are using the 8-bit system and the 1 is in the 9th position, it is ignored completely, so we end up with 00000000.
4)From point (3) we can say ~2+3 = 0, and hence we can say, ~2 = -3
Note: The value of -3 is simply 11111101 and can be explained in the same way.


QPainter DrawImage CenterAligned

Question: Is there any way to draw an image on QPainter center aligned? I see QPainter::drawText gives us this provision but drawImage does not. I have one source rect, target rect and an image. when the source size is small the image gets drawn on the left side of the page. I want it to be printed center aligned.
Answer: The painter doesn't have a size, but the device() it paints on does. You can use QRect(painter.device()->width(), painter.device()->height()) as the rectangle where you want to center your image in.
Then you'd paint the image centered like so:
QImage source;
QPainter painter(...);
...
QRect rect(source.rect());
QRect devRect(0, 0, painter.device()->width(), painter.device()->height());
rect.moveCenter(devRect.center());
painter.drawImage(rect.topLeft(), source);

Answer: I would try to do the following (please follow the source code comments):
The sample image that should be drawn
// The image to draw - blue rectangle 100x100.
QImage img(100, 100, QImage::Format_ARGB32);
img.fill(Qt::blue);

In the paint event handler
[..]
QRect source(0, 0, 100, 100);
QRect target(0, 0, 400, 400);

// Calculate the point, where the image should be displayed.
// The center of source rect. should be in the center of target rect.
int deltaX = target.width() - source.width();
int deltaY = target.height() - source.height();

// Just apply coordinates transformation to draw where we need.
painter.translate(deltaX / 2, deltaY / 2);

painter.drawImage(source, img);

Of course you should check whether source rectangle is smaller than the target before applying this approach. I omitted that code for simplicity reasons just to demonstrate how you can center your image.
Answer: I wanted to show a more complete example with a variable image size that stays within the bounds of the area provided to add to the other great answers.
void ImageView::paintEvent(QPaintEvent*)
{
  if (this->imageBuffer.empty()){ return; }

  double widgetWidth = this->width();
  double widgetHeight = this->height();
  QRectF target(0, 0, widgetWidth, widgetHeight);

  QImage tempQImage = *this->imageBuffer.at(this->imageBuffer.count()-1);
  tempQImage = tempQImage.scaled(rect().size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);

  double imageSizeWidth = static_cast<double>(tempQImage.width());
  double imageSizeHeight = static_cast<double>(tempQImage.height());
  QRectF source(0.0, 0.0, imageSizeWidth, imageSizeHeight);

  int deltaX = 0;
  int deltaY = 0;
  if(source.width() < target.width())
      deltaX = target.width() - source.width();
  else
      deltaX = source.width() - target.width();

  if(source.height() < target.height())
      deltaY = target.height() - source.height();
  else
      deltaY = source.height() - target.height();

  QPainter painter(this);
  painter.translate(deltaX / 2, deltaY / 2);

  painter.drawImage(source, tempQImage);
}

QPainter DrawImage CenterAligned


How to check if my data fits log normal distribution?

Question: I'd like to check in R if my data fits log-normal or Pareto distributions. How could I do that? Perhaps ks.test could help me do that, but how could I get the $\alpha$ and $k$ parameters for Pareto distribution for my data?
Comment: For the last question see also https://stats.stackexchange.com/questions/392629/variance-of-unbiased-estimator-for-the-shape-parameter-of-pareto-distribution/392893#392893
Answer: ... I've just noticed you have the 'regression' tag there. If you do have a regression problem you can't look at the univariate distribution of the response to assess the distributional shape, since it depends on the pattern of the x's. If you're asking about checking whether a response (y) variable in some kind of regression or GLM has a lognormal or a Pareto distribution where the means differ across observation, that's a very different question (but basically comes down to similar kinds of analysis on the residuals). Can you please clarify if it is a regression problem. My answer, at present, relates to assessing univariate lognormal or Pareto
You have some quite different questions there.

How to check if my data fits log normal distribution?

Take logs and do a normal QQ plot. Look and see if the distribution is close enough for your purposes.

I'd like to check in R if my data fits log-normal or Pareto distributions

Accept from the start that none of the distributions you consider will be am exact description. You're looking for a reasonable model. This means that at small sample sizes, you won't reject any reasonable option, but with sufficient sample size you'll reject them all. Worse, with large sample size, you'll reject perfectly decent models, while at small sample sizes you won't reject bad ones.
Such tests aren't really a useful basis for model selection.
In short, your question of interest - something like "what's a good model for this data, one that is close enough that it will make subsequent inference useful?" is simply not answered by goodness of fit tests. However, in some cases goodness of fit statistics (rather than decisions coming out of rejection rules based on them) may in some cases provide a useful summary of particular kinds of lack of fit.

Perhaps ks.test could help me do that

No. First, there's the issue I just mentioned, and second, a Kolmogorov-Smirnov test is a test for a completely specified distribution. You don't have one of those.
In many cases, I'd recommend Q-Q plots and similar displays. For right skew cases like this, I'd tend to work with logs (a lognormal will then look normal, while a Pareto will look exponential). At reasonable sample sizes it's not hard to distinguish visually whether data looks more nearly normal than exponential or vice versa. First, get some actual data from each and plot those - say half a dozen samples at least, so you know what they look like.
See an example below

how could I get the alpha and k parameters for pareto distribution for my data?

If you need to estimate parameters, use MLE... but don't do that to decide between Pareto and lognormal.
Can you tell which of these is lognormal and which is Pareto?

Note that with the normal Q-Q plots (left column) we see the logs of data set 1
gives a fairly straight line, while data set 2 shows right skewness. With the exponential
plots, the logs of data set 1 show a lighter right tail than exponential, while data set 2 shows a fairly straight line (the values in the right tail tend to wiggle about a bit even when the model is correct; this is not unusual with heavy-tails; it's one reason why you need to plot several samples of similar size to the one you're looking at to see what plots typically look like)
Code used to do those four plots:
qqnorm(log(y1))
qqnorm(log(y2))
qex <- function(x) qexp((rank(x)-.375)/(length(x)+.25))
plot(qex(y1),log(y1))
plot(qex(y2),log(y2))

If you have a regression type problem - one where the means change with other variables, you can really only assess the suitability of either distributional assumption in the presence of a suitable model for the mean.
Answer: This is a matter of model selection, of course, assuming that you just want to check whether your data comes from one model or the other and that your goal is not finding the right model among the infinite dimensional ocean of distributions. So, one option is to use AIC (which favours models with the lowest AIC value, and I will not attempt to describe here). Have a look at the following example with simulated data:
rm(list=ls())

set.seed(123)
x = rlnorm(100,0,1)

hist(x)

# Loglikelihood and AIC for lognormal model

ll1 = function(param){
if(param[2]>0) return(-sum(dlnorm(x,param[1],param[2],log=T)))
else return(Inf)
}

AIC1 = 2*optim(c(0,1),ll1)$value + 2*2

# Loglikelihood and AIC for Pareto model

dpareto=function(x, shape=1, location=1) shape * location^shape / x^(shape + 1)

ll2 = function(param){
if(param[1]>0 & min(x)> param[2]) return(-sum(log(dpareto(x,param[1],param[2]))))
else return(Inf)
}

AIC2 = 2*optim(c(1,0.01),ll2)$value + 2*2

# Comparison using AIC, which in this case favours the lognormal model.

 c(AIC1,AIC2)

Answer: Maybe fitdistr()?

require(MASS)
hist(x, freq=F)
fit<-fitdistr(x,"log-normal")$estimate
lines(dlnorm(0:max(x),fit[1],fit[2]), lwd=3)

> fit
meanlog     sdlog
3.8181643 0.1871289

> dput(x)
c(52.6866903145324, 39.7511298620398, 50.0577071855833, 33.8671245370402,
51.6325665911116, 41.1745418750494, 48.4259060939127, 67.0893697776377,
35.5355051232044, 44.6197404834786, 40.5620805256951, 39.4265590077884,
36.0718655240496, 56.0205581625823, 52.8039852992611, 46.2069383488226,
36.7324212941395, 44.7998046213554, 47.9727885542368, 36.3400338997286,
32.7514839453244, 50.6878893947656, 53.3756089181472, 39.4769689441593,
38.5432770167907, 62.350999487007, 44.5140171935881, 47.4026606915147,
57.3723511479393, 64.4041641945078, 51.2286815562554, 60.4921839777139,
71.6127652225805, 40.6395409719693, 48.681036613906, 52.3489622656967,
46.6219563536878, 55.6136160469819, 62.3003761050482, 42.7865905767138,
50.2413659137295, 45.6327941365187, 46.5621907725798, 48.9734785224035,
40.4828649022511, 59.4982559591637, 42.9450436744074, 66.8393386407167,
40.7248473206552, 45.9114242834839, 34.2671010054407, 45.7569869970351,
50.4358523486278, 44.7445606782492, 44.4173298921541, 41.7506552050873,
34.5657344132409, 47.7099864540652, 38.1680974794929, 42.2126680994737,
35.690599714042, 37.6748157160789, 35.0840798650981, 41.4775827114607,
36.6503753230464, 42.7539062488003, 39.2210050689652, 45.9364763482558,
35.3687017955285, 62.8299659875044, 38.1532612008011, 39.9183076516292,
59.0662388169057, 47.9032427690417, 42.4419580084314, 45.785859495192,
59.5254284342724, 47.9161476636566, 32.6868959277799, 30.1039453246766,
37.7606323857655, 35.754797368422, 35.5239777126187, 43.7874313667592,
53.0328404605954, 37.4550326357314, 42.7226751172495, 44.898430515261,
59.7229655935187, 41.0701258705001, 42.1672231656919, 60.9632847841197,
60.3690132883734, 45.6469334940722, 39.8300067022836, 51.8185235060234,
44.908828102875, 50.8200011497451, 53.7945569828737, 65.0432670527801,
49.0306734716282, 35.9442821219144, 46.8133296904456, 43.7514416949611,
43.7348972849838, 57.592040060118, 48.7913517211383, 38.5555058596449
)

Comment: Although this solution *fits* a lognormal to the data, it doesn't tell *whether* the fit is any good or whether a Pareto is a better choice.


Understanding the 'finally' block

Question: I've written seven test cases for understanding the behavior of the finally block. What is the logic behind how finally works?
package core;

public class Test {
    public static void main(String[] args) {
        new Test().testFinally();
    }

    public void testFinally() {
        System.out.println("One = " + tryOne());
        System.out.println("Two = " + tryTwo());
        System.out.println("Three = " + tryThree());
        System.out.println("Four = " + tryFour());
        System.out.println("Five = " + tryFive());
        System.out.println("Six = " + trySix());
        System.out.println("Seven = " + trySeven());
    }

    protected StringBuilder tryOne() {
        StringBuilder builder = new StringBuilder();
        try {
            builder.append("Cool");
            return builder.append("Return");
        }
        finally {
            builder = null;
        }
    }

    protected String tryTwo() {
        String builder = "Cool";
        try {
            return builder += "Return";
        }
        finally {
            builder = null;
        }
    }

    protected int tryThree() {
        int builder = 99;
        try {
            return builder += 1;
        }
        finally {
            builder = 0;
        }
    }

    protected StringBuilder tryFour() {
        StringBuilder builder = new StringBuilder();
        try {
            builder.append("Cool");
            return builder.append("Return");
        }
        finally {
            builder.append("+1");
        }
    }

    protected int tryFive() {
        int count = 0;
        try {
            count = 99;
        }
        finally {
            count++;
        }
        return count;
    }

    protected int trySix() {
        int count = 0;
        try {
            count = 99;
        }
        finally {
            count = 1;
        }
        return count;
    }

    protected int trySeven() {
        int count = 0;
        try {
            count = 99;
            return count;
        }
        finally {
            count++;
        }
    }
}

Why builder = null is not working?
Why does builder.append("+1") work whereas count++( in trySeven()) does not work?
Answer: Once you do the return, the only way to override that is to do another return (as discussed at Returning from a finally block in Java, this is almost always a bad idea), or otherwise complete abruptly.  Your tests don't ever return from a finally.
JLS §14.1 defines abrupt completion.  One of the abrupt completion types is a return.  The try blocks in 1,2,3,4, and 7 abruptly complete due to returns.  As explained by §14.20.2, if the try block completes abruptly for a reason R besides a throw, the finally block is immediately executed.
If the finally block completes normally (which implies no return, among other things), "the try statement completes abruptly for reason R.".  In other words, the return initiated by the try is left intact; this applies to all your tests.  If you return from the finally, "the try statement completes abruptly for reason S (and reason R is discarded)." (S here being the new overriding return).
So in tryOne, if you did:
finally {
            builder = null;
            return builder;
        }

this new return S would override the original return R.
For builder.append("+1") in tryFour, keep in mind StringBuilder is mutable, so you're still returning a reference to the same object specified in the try.  You're just doing a last minute mutation.
tryFive and trySix are straight-forward.  Since there is no return in the try, the try and finally both complete normally, and it executes the same as if there was no try-finally.
Answer: Let's start with use case you'll see more often - you have a resource that you must close to avoid a leak.
public void deleteRows(Connection conn) throws SQLException {
    Statement statement = conn.createStatement();
    try {
        statement.execute("DELETE * FROM foo");
    } finally {
        statement.close();
    }
}

In this case, we have to close the statement when we're done, so we don't leak database resources.  This will ensure that in the case of an Exception being thrown, we will always close our Statement before the function exits.
try { ... } finally { ... } blocks are meant for ensuring that something will always execute when the method terminates.  It's most useful for Exception cases.  If you find yourself doing something like this:
public String thisShouldBeRefactored(List<String> foo) {
    try {
        if(foo == null) {
            return null;
        } else if(foo.length == 1) {
            return foo.get(0);
        } else {
            return foo.get(1);
        }
    } finally {
        System.out.println("Exiting function!");
    }
}

You're not really using finally properly.  There is a performance penalty to this.  Stick to using it when you have Exception cases that you must clean up from.  Try refactoring the above to this:
public String thisShouldBeRefactored(List<String> foo) {
    final String result;

    if(foo == null) {
        result = null;
    } else if(foo.length == 1) {
        result = foo.get(0);
    } else {
        result = foo.get(1);
    }

    System.out.println("Exiting function!");

    return result;
}

Answer: The finally block is executed when you leave the try block. The "return" statement does two things, one it sets the return value of the function and two it exits the function. Normally this would look like an atomic operation but within a try block it will cause the finally block to execute after the return value was set and before the function exits.
Return execution:

Assign return value
run finally blocks
exit function

Example one (primitive):
int count = 1;//Assign local primitive count to 1
try{
  return count; //Assign primitive return value to count (1)
}finally{
  count++ //Updates count but not return value
}

Example two(reference):
StringBuilder sb = new StringBuilder();//Assign sb a new StringBuilder
try{
    return sb;//return a reference to StringBuilder
}finally{
    sb.append("hello");//modifies the returned StringBuilder
}

Example three (reference):
   StringBuilder sb = new StringBuilder();//Assign sb a new StringBuilder
   try{
      return sb;//return a reference to StringBuilder
   }finally{
      sb = null;//Update local reference sb not return value
   }

Example four (return):
   int count = 1;   //assign count
   try{
      return count; //return current value of count (1)
   }finally{
      count++;      //update count to two but not return value
      return count; //return current value of count (2)
                    //replaces old return value and exits the finally block
   }

Answer: builder = null and builder.append("+1") are working.  It's just that they're not affecting what you're returning.  The function returns what the return statement has, regardless of what happens afterward.
The reason there is a difference is because builder is passed by reference.  builder=null changes the local copy of builder.  builder.append("+1") affects the copy held by the parent.
Answer: Why builder = null is not working?Because you are setting the local reference to null which will not change the content of the memory. So it is working, if you try to access the builder after finally block then you'll get null.Why builder.append("+1") work? Because you are modifying the content of the memory using the reference,that's why it should work.Why count++ does not work in testFive()? It is working fine with me. It outputs 100 as expected.
Answer: Consider what the compiler is actually doing for the return statement, for instance in tryOne(): it copies a reference to builder back to the calling function's environment.  After it's done this, but before control goes back to the calling function, the finally block executes.  So you have something more like this, in practice:
protected StringBuilder tryOne() {
    StringBuilder builder = new StringBuilder();
    try {
        builder.append("Cool");
        builder.append("Return");
        StringBuilder temp = builder;
        return temp;
    } finally {
        builder = null;
    }
}

Or, in terms of the order that statements actually get executed (ignoring possible exceptions, of course), it looks more like this:
protected StringBuilder tryOne() {
    StringBuilder builder = new StringBuilder();
    builder.append("Cool");
    builder.append("Return");
    StringBuilder temp = builder;
    builder = null;
    return temp;
}

So setting builder = null does run, it just doesn't do anything useful.  However, running builder.append("something") will have a visible effect, since both temp and builder refer to the same (mutable) object.
Likewise, what's really happening in trySeven() is something more like this:
protected int trySeven() {
    int count = 0;
    count = 99;
    int temp = count;
    count++;
    return temp;
}

In this case, since we're dealing with an int, the copies are independent, so incrementing one doesn't affect the other.
All that said, the fact remains that putting return statements in a try-finally block is quite clearly confusing, so if you've got any kind of choice in the matter, you'd be better off rewriting things so that all your return statements are outside any try-finally blocks.

Understanding the 'finally' block


Django - How to sort queryset by number of character in a field

Question: MyModel:
name = models.CharField(max_length=255)

I try to sort the queryset. I just think about this:
obj = MyModel.objects.all().sort_by(-len(name)) #???

Any idea?
Answer: The new hotness (as of Django 1.8 or so) is Length()
from django.db.models.functions import Length
obj = MyModel.objects.all().order_by(Length('name').asc())

Answer: you might have to sort that in python..
sorted(MyModel.objects.all(),key=lambda o:len(o.name),reverse=True)
or I lied ( A quick google search found the following)
MyModel.objects.extra(select={'length':'Length(name)'}).order_by('length')

Answer: You can of course sort the results using Python's sorted, but that's not ideal. Instead, you could try this:
MyModel.objects.extra(select={'length':'Length(name)'}).order_by('length')

Answer: You'll need to use the extra argument to pass an SQL function:
obj = MyModel.objects.all().extra(order_by=['LENGTH(`name`)'])

Note that this is db-specific: MySQL uses LENGTH, others might use LEN.


Difference between Variable Speed Compressor and Variable Speed Condenser(Fan controlled)?

Question: Are these pieces of equipment independent from each other, or one requires also the other one to be in a system (chiller)?
Answer: They are 2 distinct pieces of equipment that both utilize variable speed drives. and one is not a requirement for the other.
The compressor is used to adjust the pressure/flow rate of the working fluid in the system, adding a variable speed drive gives highly efficient control over this. This can make the system more efficient at part load.
At the condenser the variable speed drive controls fans that pass air (not the working fluid) over an atmospheric heat exchanger, effectively allowing you to alter its thermal conductivity. This gives additional control over the temperature at the condenser exit.
Comment: In the modeling phase of these compressors, what is the difference then? How can I model a variable compressor compared to a fixed one, so that it is more efficient at the part load? Should it be the compressor polynomials which make the difference? I would think, for instance, that the fixed speed compressor can not utilize the variable speed condenser fans?


Why aren't multimedia codecs included by default?

Question: Are there any legal reasons for that?
Comment: I would rephrase the question as either "Why aren't multimedia codecs included by default?" or "Why are multimedia codecs not included by default?". As it now stands, a double negative is used and thus should be read as "Why are multimedia codecs included by default?"
Answer: Some are for legal reasons - some video/audio formats require further license agreements or don't quite fit under the Ubuntu license schema. You can read more about this on the Ubuntu Wiki: Restricted Formats page.
I know that Ubuntu Studio comes with a lot of these codecs and "drivers" already installed. However for an average desktop user it's a lot of overkill as it's designed for multimedia market.
Answer: Medibuntu.org provides an easy way to install many "non-free" codecs and multimedia applications that are not available in the main distribution for legal or philosophical reasons.  It is up to you to ensure that it is legal to use such codecs in your country.
Comment: According to https://help.ubuntu.com/community/Medibuntu, looks like Medibuntu is gone: "Medibuntu has now been shut down, the packages were either obsolete, unnecessary or moved to the official Ubuntu archive. " Also see: https://en.wikipedia.org/wiki/Medibuntu


Can't export HEVC videos from Photos app

Question: I have a late 2012 iMac running Catalina (10.15.7) as it's too old to upgrade to Big Sur. Photos are synced from my phone with iCloud.
I'm unable to export HEVC videos to other formats. When I drag and drop to the finder, the cursor shows a green plus sign but nothing happens. No error, but no video either.
When I choose File > Export > Export 1 Video… I get an unable to export error: Unknown error (0).
The videos play fine in Photos. I can export them using File > Export > Export Unmodified Original, and they show up as HEVC videos in .mov containers. They play fine in the Finder with Quicklook, and I can open them in Quicktime Player, although File > Export As has all its options greyed out.
This seems to apply to every HEVC video in my library. Other formats (e.g. H.264) work normally. I have a newer iMac running Big Sur synced to the same iCloud library, and I can export normally there.
Apple says HEVC support was introduced in High Sierra, so Catalina should be fine. And there must be some support, since I can watch the videos.
What could be causing this and how can I fix it?
Answer: As an alternative, you may take the original video out of the library by right click on Photos Library.photoslibrary > show package contents and search by filename or extension.
Be careful to not modify anything that can mess up the library. Best to just do copy-paste.


How to suppress exp_spawn translating " to \?

Question: I am using tcl8.5 on windows 7. I need to use spawn with openssh. The username has double-quotes (e.g. abc"). I can use openssh to login the remote device with this account when I am using it in a command window:
D:\Program Files\OpenSSH\bin>ssh 192.168.0.253 -labc"\""

...
abc"@192.168.0.253's password:
(the correct username is displayed by openssh)
However, when I use spawn ssh with the same syntax in a script, the " is translated to \
When I enter the correct password, access is denied.
exp_spawn "$sshClient" "192.168.0.253" -labc\"\\\"\"
=>
abc\\""@192.168.0.253

The following attempt also shows " being translated to \
exp_spawn "$sshClient" "192.168.0.253" -labc\"
=>
abc\@192.168.0.253

Could anyone show me the correct syntax please? Or is there any option in exp_spawn I need to enable?
Answer: Try
exp_spawn $sshClient 192.168.0.253 {-labc"}


Electric field and current

Question: When we provide a potential difference in a circuit it does nothing more than provide an electric field to the conductor,When an electric field is provided in a conductor the free electrons move to the opposite direction of the field and hence there is an accumulation of charge on the ends of the conductor.Due to the accumulation of charges,the negative charge and the positive charges produce an internal electric field on the opposite direction of the external electric field.At some point these will be of equal magnitude and the Enet will be zero.So,how will electrons move in such as situation and have drift velocity?
Comment: Does this answer your question? [Dependence of current on eletric field and vice versa in a circuit](https://physics.stackexchange.com/questions/411018/dependence-of-current-on-eletric-field-and-vice-versa-in-a-circuit)
Comment: what kind of conductor you are assuming? when we place a conductor in external field there will be a redistribution of charge, that is how dielectric work.if you can add a figure it will benefit you!
Answer: Your description is correct, and this is exactly why open circuits don't work.

If you connect a conductor to one end of a battery but keep the other end free, then charges will accumulate at the far end setting up an opposing electric field. Soon, no charges will move anymore.
In order to keep a steady current that doesn't stop at some point, you cannot allow accumulation of charge anywhere. You must take the charges away from that other end as they arrive. You take them away by attaching this other end to the other battery pole.

A battery is an electrochemical "machine" which moves charges from one pole to the other (roughly speaking). By letting charges arrive at the opposite battery pole, they will be moved back to the starting point, ready to take another lap through the circuit.
There is now no accumulation but a circular loop of charge flowing (with their drift velocity) in steady current, as race cars on a racing track. Without a closed track, you will indeed see accumulation somewhere in the circuit, and charge flow will eventually (this happens extremely quickly) stop.
Comment: Thanks a lot steeven
Answer: What you are describing sounds like a battery connected to a wire where the other end of the wire is not connected to the other battery terminal. Or it could also describe the charging of a capacitor by a voltage source (e.g., battery). The battery voltage removes electrons from one plate of the capacitor and deposits them on the other plate unit the accumulation of charge on the plates creates a voltage equal and opposite to the battery voltage.  Then the current stops.
In general, however, charges don't accumulate in conductors in a complete electrical circuit unless there is an electrical energy storage device. The voltage source, such as a battery,  continues to supply electrical potential energy to the charges so that current continues to flow.
Hope this helps.
Answer: The situation you described is seen in case of conductors when net E inside it becomes 0 due to external field and induced field

In such cases as the field is 0 the electric potential on the surface becomes constant and the surface is called equipotential surface due to which there isnt any motion of charges which require a potential to move

Electric field and current


How to add one entity reference field that can reference either a node or a user?

Question: I'm looking to create an entity reference field that can reference either nodes from a specific bundle, or users. Is their a way to do this either with a module , or programmatical,y?
Comment: You don't. Entityreference doesn't support it, and it's a sign of a bad architecture. Have two separate fields.
Answer: I do not think you can do this with the Entity reference module.  Look at its code:
<code>/**
 * Implements hook_field_info().
 */
function entityreference_field_info() {
  $field_info['entityreference'] = array(
    'label' => t('Entity Reference'),
    'description' => t('This field reference another entity.'),
    'settings' => array(
      // Default to the core target entity type node.
      'target_type' => 'node',
      // The handler for this field.
      'handler' => 'base',
      // The handler settings.
      'handler_settings' => array(),
    ),
    'instance_settings' => array(),
    'default_widget' => 'entityreference_autocomplete',
    'default_formatter' => 'entityreference_label',
    'property_callbacks' => array('entityreference_field_property_callback'),
  );
  return $field_info;
}
</code>
I suggest you try a work-around.  For example, you could create a content type that includes two entity-reference fields, one of type Node and one of type User.  Maybe, for convenience, include a boolean or integer field indicating which of the two to use.  Then use references to your new content type where you want to use node-or-user entity references.
Alternatively, you could use the Field collection module, which works the same way, creating node types to handle collections of fields:  https://drupal.org/project/field_collection.
Answer: For D8 this is now possible with the Dynamic Entity Reference field:
https://www.drupal.org/project/dynamic_entity_reference


Not every open set in $\mathbb{R}^n$, for $n\geq2$, is a disjoint union of countable open balls.

Question: I know that every open set in $\mathbb{R}$ can be decomposed as the union of countably many disjoint open intervals and I'm trying to show that this property no longer holds in higher dimensions. For this I'm trying to show that there is no countable, pairwise disjoint open balls whose union is the
open square $(0, 1)^2 ⊂ \mathbb{R}^2$. I know that it is because of the corners, but I don't know how to write this in mathematical terms. Thanks for any help.
Answer: If any connected open set is written as a countbale disjoint union of open bals then all but one of them  must be empty (because of conncetedness) so the original open set must itself be an open ball. So an open rectangle would be a counter-example.
Answer: Any open subset $O$ of $\Bbb R^n$ is a finite or countable disjoint union of open connected sets  and that's all that can be said, really. This is true in any separable locally connected space. In $\Bbb R$ those open connected sets can only be intervals or segments. In $\Bbb R^n, n>1$ there can be more variation (open rectangles minus finitely many points, interiors of closed curves in all sorts of shapes etc) but you do know the connected open sets are path-connected too.


Is heat a practical way to kill structual mold?

Question: So heating the whole house or affected rooms up to 45 50 degrees C for long enough to also heat and kill any mold in exterior walls as well as mold on the surface?
Comment: what is `structural mold`? ... is that a mold that is keeping your house from collapsing?
Comment: why don't you ask here instead? https://biology.stackexchange.com/
Comment: What has caused the mold - if you don't treat that then it will return.
Comment: Actually, *cold* is used to remove mold, e.g. https://backtonormalrestoration.com/calabash-restoration-services/dry-ice-cleaning/ , but as mentioned, it only removes *surface* mold.
Comment: All natural wood products are full of mold spores with dimensional lumber it is sprayed with a biocide after the finish cuts so it doesn't turn black right away. Plywood is heated to cure the glue and this process kills the mold. Keeping the humidity low is the best way to keep mold from growing. First of all don't panic most mold is not a "killer".  Their are mold foggers, mold bombs if you want to kill surface mold but nothing you can do will totally eliminate mold spores from structural lumber.
Answer: I have to agree with Solar Mike. Sure, it might kill existing mold, by drying everything. But, it will reactivate if its cause isn't addressed...you may just need to run the air conditioner or exhaust fans more often or plug-in a dehumidifier.
Although, is there a concern? Not really. Mold is literally everywhere and in every breath you take and run-of-the-mill mold concealed in walls has no effect on people nor building products.
Now, if you mean Black Mold that's even showing up inside rooms in little patches. Then, you really MUST rip out the walls and professionally remediate it from the property.
Black Mold is EXTREMELY serious and also means you have a very blatant construction problem or water leak that's been ignored too long. In order to avoid PERMANENT health problems the issue(s) must be fixed entirely and ASAP.
Comment: There are non toxic black mold even Stachybotrys the bad boy of molds is not always toxic , I live in Oregon and we have all kinds of different mold(s) a mold fogger will kill surface molds . I just use 3%hydrogen peroxide and water. So many people have been scared by black mold when most household molds are black and not toxic testing is the only way to know for sure.
Comment: Point well taken. I wouldn't doubt there's a dozen black molds of toxic and not. But, to just wipe off what's visible or only kill what can be killed (not getting much inside walls & insulation) doesn't fix anything nor does it stop damage or health problems...what's the "joy" of that fogger stuff, I wouldn't want it anymore than the mold. A multitude of cases of exceedingly sick people ultimately revealed mold behind their pristine walls to be the cause of their symptoms and even permanent conditions. So, even the non-disturbance safety claim is debunked when it comes to certain molds.
Comment: I agree there are some that are more sensitive, just like nut allergies, shellfish and some that say they are allergic to emf.  So anything is possible.
Comment: Even if it's not toxic, the house crumbling on top of you because the leak that caused the mold also made the wood structure rot and snap is kind of a problem too ;)


Mobius transformation produces either a circle or a line...

Question: The exercise (from H A Priestley) required a transformation that sent $\:0, 1, {\infty}$ to $1, 1+i, i$. I knew the transformation that sent $z_1, z_2,z_3,$ to $0, 1,  {\infty}$ ie
$$\frac{(z-z_1)(z_2-z_3)}{(z-z_3)(z_2-z_1)}$$
So I found the inverse using $z_1=1,\ z_2=1+i,\;  z_3=i\;$ which I made $$\frac{(z+1)}{(1-iz)}$$
The question required one to use this transformation on various objects which all seemed to work perfectly until I came to the last one which was the imaginary axis. The result seemed to be neither a circle (it went through ${\infty}$) nor a straight line.
Brains have been racked in vain: please, where have I gone wrong?
Comment: Why don't you tell us what result you got from transforming the imaginary axis, not just what the result isn't?
Comment: Sorry. I got infinity for -i, 1 for zero and 1+i for 1. Which would be fine. But for ki where k is bigger than 1 or less than -1 the points aren't on that line at all.
Comment: 1 isn't on the imaginary axis as far as I know.
Comment: Sorry—muddle: I should have said that 1 and -1, the inverse points for the imaginary axis, went to 0 and i+i, giving a line that is the perpendicular bisector of 0 to 1+i. Then I thought I'd try a few imaginary points with the transformation—and found 2i, 3i etc weren't on the line.
Answer: Imaginary axis has the equation $z=it$. After transformation new curve will have the equation
$$z=\frac{1+it}{1+t},\qquad x=\mathrm{Re}\ z =\frac{1}{1+t},\qquad y=\mathrm{Im}\ z =\frac{t}{1+t} = 1-x$$
One can see that it is an equation of a line.
Comment: I used the inverse point equation of the imaginary axis as that was what Priestly using in this chapter. Your way is so much neater—and works! But I'd really like to know where I went wrong...
Comment: I've just checked: the line you found is the same as mine—which has the inverse points 0 and 1+i. Problems arose when I tried out the transformation on some points on the imaginary axis which didn't seem to be on the line but I see now, thanks to your straightforward equation y=1-x, that they are. Thank you for clearing up my muddle!


Word choice for "Educationally Enriched"

Question: Is there any word which replace the phrase "Educationally enriched"? I was trying  to write an essay where I defined a state where every people are educated. To define that I was taking help of phrase "Educationally enriched". Now I want to replace it with some better English.
Comment: What do you think *educationally enriched* means (aside from each individual word)? How is is it different than simply *educated* (a word that you use in your own question)?
Comment: With "educated" do you mean simply that people "receive an education" or that they are e.g. accomplished, cultured, erudite, etc? I posted an answer but that assumed the first one to some degree. Also do you mean a state as in a "situation" or a "nation-state"?
Comment: Can you give an example of a sentence/short passage you've written where you have currently used "educationally enriched", for context?
Answer: "universal education"
(e.g. World of 7 Billion)

Benefits of universal education
In the world's more developed countries, school attendance is compulsory and public schools provide a free education for children and adolescents
[...]
Education is a human right and a strong catalyst for social progress. According to UNICEF, getting every
  child in school and learning is essential to reducing global poverty, improving health, fostering peace,
  bolstering democracy, improving environmental sustainability and increasing gender equality.

Universal education refers to attendance at school (in the 'younger years' at least) for everyone, rather than just a privileged elite.
"universal access to education"
(e.g. Wikipedia)

the ability of all people to have equal opportunity in education, regardless of their social class, gender, ethnicity background or physical and mental disabilities.2 The term is used both in college admission for the middle and lower classes, and in assistive technology[3] for the disabled.

This relates to [a policy of / situation of] having education available in theory to all, despite potential hindrances such as disabilities, disadvantaged social class, etc.
It's different from "universal education" in that it isn't compulsory or even widespread, but is about people being able to take up the opportunity if they want to. (I don't think this meets your criteria of 'a state where everyone is educated' though..)


How flexible is kinship taxonomy in Jewish communities?

Question: Recently I read this article, which describes the flexible use of the word cousin in African-American and Latinx communities. It made me wonder: historically, have Jewish communities have had similarly flexible family taxonomies?
Comment: Possible fit for Mi Yodeya.SE.
Comment: @AaronBrick They sent me here.
Comment: @Denisdebernardy - General discussion of kinship taxonomy is *probably* too broad (unless there are underlying principles of which I'm not aware).  I assume Jewish is the community that interests crmdgn.
Comment: Why single out Jewish communities explicitly? Why not WASP or Catholic Irish or Chinese or what have you communities?
Comment: Purged a bunch of comments because the comment has been expanded to an answer.
Answer: Converting from comment to answer:
Genesis 11:29
Mainstream medieval French Jewish commentator, Rashi, holds that Sarah (Abraham's wife) is the same as his niece, Iscah.
19:2 Abraham tells Abimelech that Sarah is his sister. (In a a similar incident,in Egypt, Abraham tells Sarah to say this, implying that it is a fabrication, or at least misleading)
20:12 Abraham justifies what he says as being technically true
"And also, indeed, she is my sister, the daughter of my father, but not the daughter of my mother, and she became my wife."
Rashi comments:

...Now if you ask: Was she not the daughter of his brother? [The answer is that] grandchildren are considered like children (Tosefta, Yev. 8:8; Talmud Bavli, Yev. 62b); therefore, she was (considered as) Terah's daughter.
And so did he say to Lot, "For we are kinsmen" (אֲנָשִׁים אַחִים) [lit. men, brothers] (although, in fact, Lot was his brother Haran's son). - [from Pirkei d'Rabbi Eliezer, ch. 36]

Abraham is taking advantage of the loose meaning of the words "sister and brother" to avoid admitting to the King that he lied. At this point, Abraham has no fear of reprisal because the King only found out that something was amiss because God threatened him. Abraham has a big, bad, deity on his side. He could simply tell the king that he lied because the Philistines are a bunch of savages who would try to kill him to take his wife and then flip the King the bird and move his tent somewhere else.
In short: A universally regarded Jewish commentator from 1100 asserts, using older sources (approximately 1000 years older), that Abraham used the words brother and sister in broader terms. These older sources refer to even older traditions.
Comment: To clarify, Jews do not call each other brother and sister in common parlance.
Comment: In modern Israel, young men on the  street call each other אחי "my brother" all the time.
Comment: That's because they're trying to be cool
Answer: Hebrew in general, and biblical Hebrew especially are very metaphorical languages.
A well-known phrase is "כל ישראל אחים" meaning "All Israel are brothers".
Essentially, the word for brother is easily and commonly used metaphorically to mean kinsman, or even more broadly. Two people in the same shelter can be said to be "brothers in their trouble". Some of these phrases, like "brothers in arms" have passed through into English as well.
As an aside, in modern Hebrew, Arab people are occasionally referred to as "cousins", because the tradition is that they are children of Ishmael, son of Isaac, whereas Jews are children of Jacob, Ishmael's younger twin. This makes the two peoples cousins.


Using SVM Classifier with C=0 and C=infinity ,what would be the effect on classifying this data?

Question:
I want to know the effect of applying different C values on SVM Classifier margin
Comment: [![enter image description here](https://i.stack.imgur.com/k3417.jpg)](https://i.stack.imgur.com/k3417.jpg)
If i applied large C value could this happen? (shown in graph)
Comment: Sorry for the inconvenience , i didn't have an account yet , so the the answer would be the same for both cases c=0 and c= infinity [![enter image description here](https://i.stack.imgur.com/v8siR.jpg)](https://i.stack.imgur.com/v8siR.jpg)
Answer: C value is like lambda, the L2/L1 regularization hyper parameter, but in reverse manner. Whenever C is large, means there is high probability that your model overfit the data in hand. Whenever it is small, your model endure some errors in order to avoid producing small margin and consequently you will have a model less prone to overfitting. The first one is called hard SVM and the latter one is soft SVM. In your case, I guess there will be no difference because your model is linearly separable. If X4 was between X2 and X3 you would have different result for each hard and soft. Soft and hard differ in cases which the data is not linearly separable or maybe they are separable but the margin would be narrow or wide if SVM discards some samples. Soft tries to make the separator space, margin, as large as possible by discarding those minority data which hinder a large margin to be crated but hard tries to separate the data to reduce the error as much as possible. In your case, you will get same result.

For illustrating more, look at the left figure. It tries to discard the sample which hinders the large margin to be created but large margin, considers all the samples.


When I disable the poll module my add content page doesn't work. Why?

Question: Im on d7. I no longer want to have a poll on my site. For some reason when I disable the poll module, the add content page becomes blank and says I have not yet created any content types. I have three other content types on my site and they display fine in the admin panel, just not on the node add page. Anyone have any suggestions? Thanks.
Answer: Cache can often be a source to weird problems, clearing it could help. The poll module won't effect if other content types are active or not, so the problem shouldn't be related to the poll module directly.
Answer: I figured it out, it was due to the weird bug in the navigation menu that creates multiple empty add content links. Thanks
Comment: Can you elaborate on this "weird bug"? You could also post a screenshot. Thanks!


How to connect QSFP+ transceiver with MPO connector and SFP+ transceiver with LC connector?

Question: In data center application, 40G QSFP+ transceivers with MPO connector and 10G SFP+ transceivers with LC connectors are most common transceivers. But, with two different connectors, how can we make a connection between these transceivers? And how long the distance the network connection can possibly reach?
Comment: Did any answer help you? if so, you should accept the answer so that the question doesn't keep popping up forever, looking for an answer. Alternatively, you could post and accept your own answer.
Answer: You need a breakout cable - MPO to 8x LC. The reach of the cable depends on the PHY that is used, e.g. 400 m for 10GBASE-SR over OM4, or 10 km for 10GBASE-LR over OS2.
Make sure that the transceivers on each end support matching PHYs, that the QSFP+ port supports breakout in your scenario, and that you match the breakout/patch cable type to the fiber type.
Of course, you can alternatively use a DAC breakout - go directly from QSFP+ to 4x SFP+.
Product recommendations are off-topic here, I'm afraid.


MySQL Code implementation of locking and transactions

Question: I am trying to understand the internals of how MySql (using InnoDB) implements locking and transactions in code. I understand the different types and concepts of locks and transactions, but I really want to deep dive into understanding how MySQL internally implements in code. I tried going through the documentation and MySQL open source code, but could not find a good starting point. Google was no help either. All search results were talking about the different types of locks, but not how they are implemented actually. Any help here?
Answer: InnoDB uses MVCC as concurrency control mechanism. Yo can get some more details about it here.
Since you mentioned you want to take a look at the code, I'd suggest downloading the current source code and browsing a bit in the InnoDB directory (storage/innobase). Transactions are implemented in the trx and locking in the lock subfolder. The easiest way is probably to use an IDE and do some kind of keyword search or even build MySQL from source code and debug the execution of a query. Therefore you probably need some kind of knowledge about the interface between the MySQL core and the InnoDB storage engine. You can find these details here: https://dev.mysql.com/doc/internals/en/custom-engine.html


How do I emphasize his superiority?

Question: A boy(3 years) I saw in a fun-fair was trying to play in mickey mouse bounce house(precisely speaking clambering a steep slope) suitable for kids older than him, say more than 5 years. I am trying to find a phrase which would mean that he did something which the older kids do because he was determined. I have heard of a phrase head and shoulders above his peers but that emphasizes that he is superior to his peers but I want a term which focuses on the equality between him and his seniors. Looking at him, we feel proud that as a young kid, he is doing really great and is equal to big kids playing with him.
Answer: You could say he was holding his own among the big kids.

Hold your own (idiom):
  (1) to maintain your position or condition despite difficulties
  (2) to be as successful as other people or things in a situation
  - http://dictionary.cambridge.org/us/dictionary/english/hold-your-own
Hold one's own
  (1) be sufficiently competent in a certain situation; "He can hold his own in graduate school"
  (2) maintain one's position and be in control of a situation
  - http://www.thefreedictionary.com/hold+one%27s+own
Comment: @AndyT I'll remove it.  It was marked as "American" in the references I checked, and I'm not familiar enough with British English to be sure.
Answer: It seems "he could keep up with older kids" would work.

Keep up: to manage to do as much or as well as other people

(Longman)
Answer: That guy was precocious.
Precocious is an adjective, an aberration, that person has attained certain traits at an earlier age than expected in general for his age..It is a neutral word,can be used for both in negative and positive sense..
Comment: Thanks but I was looking for a colloquial term and also essentially one which has a positive sentiment attached to it. :)
Comment: _Precocious_ is fine in colloquial speech. I also don't recall hearing anyone using it negatively, except inasmuch as **any** positive word can be used negatively, as in "Oh, little miss _perfect_ is so _beautiful_ and _smart_ and can do _everything_ so well… God I hate her!", where both _perfect_, _beautiful_, and _smart_, normally very positive words, are being used disparagingly and become negative in the context. That is of course possible with _precocious_, but barring that type of usage, it generally has quite a positive ring to it, I'd say.
Comment: Other than in the song Supercalifragilisticexpialidocious, I don't think I have ever heard *precocious* used in a non-disparaging way. That said, I never knew its definition either.

How do I emphasize his superiority?


What is the name of this 5-pin connector?

Question: What kind of connector is in the images?

Comment: @ToddMinehardt  Molex connectors come in *many* different varieties; the vast majority have pin counts other than 4.
Comment: @toddminehardt I think you stand connected :)
Comment: @ToddMinehardt didn't molex have 4 pins?
Comment: I stand corrected!
Answer: It's a MATE-N-LOK connector

Header: https://www.te.com/usa-en/product-640467-1.html (Mouser: 571-6404671)

Plug: https://www.te.com/usa-en/product-1-480763-0.html (Mouser: 571-14807630)
Comment: Commonly these are known (slightly inaccurately) as Molex connectors. https://en.wikipedia.org/wiki/Molex_connector explains why. But MATE-N-LOK is technically the correct term.
Comment: @Bergi I believe the original 1960s Molex connectors which predated and are not compatible with MATE-N-LOK are no longer used. I understand Molex's range now includes a range of connectors which are compatible with a subset of MATE-N-LOK (e.g. the 4x1 connector for 5.25" drives) - but there are plenty of MATE-N-LOK connector types Molex does not make. So calling them Molex is still (technically) wrong.
Comment: @abligh How do you distinguish them? Are the original Molex connectors no longer in use? Wikipedia only writes "*The [Mate-n-Lok] connector was similar to the patented Molex connectors but not interchangeable. Both were widely used in the computer industry and the term "Molex connector" is often inaccurately used to refer to all nylon plugs and receptacles.*"
Answer: I think it's the TE MATE-N-LOK series. Here's an example socket and plug, though there's too many varieties to sort through to say if that's the exact one.


Why $di/dt$ in inductor circuit reduces gradually after closing the switch?

Question: When we close circuit having an inductor, an induced emf is generated across the inductor which opposes change in current through the circuit. This back emf depends on rate of change of current $di/dt$. Thus when rate of change current starts decreasing , back emf also starts decreasing and eventually becomes zero. But what does the rate of change of current depends on?
Answer: The rate of change of current depends on the inductance of the coil- lots of inductance means the rate changes slowly (for no inductance at all, the rate of change is very high!) and the voltage of the source. the higher the voltage, the faster is the rate of change.
Answer:
But what does the rate of change of current depends on?

The inductance of the inductor coil.
The relationship between the voltage across and current through an ideal inductor are
$$v_{L}(t)=L\frac{di_{L}(t)}{dt}\tag{1}$$  Or
$$\frac{di_{L}(t)}{dt}=\frac{v_{L}(t)}{L}\tag{2}$$
From equation (2) we see that the rate of change of current in an inductor is inversely proportional to its inductance for a given voltage across the inductor. The greater the inductance, the lower the rate of change of current.
You might find a mechanical analog helpful. From Newton's second law we have
$$a(t)=\frac{F_{net}(t)}{m}\tag{3}$$
The analogies between equations (2) and (3) are:  1, current analogous to velocity 2. Rate of change of current is analogous to acceleration 3. voltage is analogous to force, and 4. inductance is analogous to mass.
Just like mass has inertia that resists a change in velocity, the inductance $L$ of a coil is electrical  "inertia" that resists a change in current.
Hope this helps.
Comment: But inductance is constant for a given inductor. Then why does di/dt change(reduce) gradually? di/dt should also remain constant.
Comment: @DevdattaJoglekar Sorry. I don't understand your comment.
Comment: You said di/dt depends on L. But L is constant for an inductor. Then why does rate of change of current flowing through the circuit gradually decreases after closing the switch. Rate of change of current should also remain constant.
Comment: I'm not sure what you're getting at, but would you agree that the larger the inductor, all other things being equal, the lower the rate of change in current? Yes or no.
Comment: I got that. I am talking about a scenario where other things are not equal
Comment: I am asking why does back emf in the circuit decreases? I think it is because rate of change of current decreases. And if that is the case why rate of change of current decreases in the first place?
Comment: Whether the emf increases or decreases depends on the circuit particulars. Provide a circuit diagram so we can have some context.
Answer: First,
$$\frac{dI}{dt} = -\frac{\epsilon_L}{L}$$
where $L$ is the inductance and $\epsilon_L$ is the induced emf. As the current starts to increase in the circuit when the switch closes, an induced emf opposes this increase in the current. Therefore, this opposition decreases the rate at which the current is increasing throughout the circuit. Therefore, the rate of change of the magnetic flux decreases, which will consequently decrease the induced emf. Therefore, as time passes, the induced emf decrease, and the rate of change of the current approaches $0$ (equilibrium value), which is the point where the source current flows with no induced emf that opposes its motion.
Hope that helps!
You can also check this wikibooks article, which shows step-by-step process of what happens.
Answer: When you close the circuit the current starts to rise, and it wants to rise very fast, ideally as a step function. But there are two phenomena that prevent this sudden rise: the first is that the current in the wires generate a magnetic field, and the second is that this changing magnetic field results in a changing magnetic flux linked by the coil.
According to Faraday's law, this change in magnetic flux results in an electric field that superpose, inside the wire the coil is made of, to the electric field that was causing the fast rise in current at the beginning.
We express this effect in the form of an emf that counters the voltage applied to the coil. The result of this compensation is that instead of an abrupt change we see an exponential approach.


How much do Star Trek episodes have in common with Shakespearean plays?

Question: I was recently told that Star Trek episodes are built on a structure inspired by Shakespeare's plays. I tried to verify this claim, but have been unable to find a reference that compares the two. So, my question - how much do Star Trek episodes have in common with Shakespearean plays?
Comment: [The Conscience of the King](http://memory-alpha.org/wiki/The_Conscience_of_the_King_(episode)) is the first thing that popped into my head. While references to Shakespeare can be found with a quick search on Memory Alpha, finding out what plot elements are lifted from Shakespeare will require someone who knows Trek as well as the Bard. Calling @Martha F. ?
Comment: Plots that strain credibility ☑ —  Dialogue impenetrable to regular people ☑ — Fanatically beloved by a cohort of nerds ☑ — Provides employment for otherwise-useless RSC graduates ☑ — Persists in pop culture long past when it was actually relevant ☑ — Star Trek is Shakespeare!
Comment: "Requiem for Methuselah" loosely adapts Shakespeare's "The Tempest", and "Elaan of Troyius" loosely adapts "Taming of the Shrew".
Answer: It's hard to tell what you're referring to exactly, but all shows generally follow the same format Shakespeare (and indeed, all normal plays) take: a series of acts (usually 3 for 30 minute shows and 5 for 60 minute shows) broken into scenes.
For TV, acts generally have a central aspect tying them together, just like a play. Acts are usually separated by commercial breaks: a plot point will generally resolve itself before the commercial break, or transition into a different plot point (e.g. via the use of a commercial break cliffhanger).
But it's a bit of a misdirect to say something's based on Shakespeare because it shares similar elements. The reason many things relate to Shakespeare is because Shakespeare created well-crafted plays based on centuries of knowledge on the subject dating all the way back to Antiquity. It's no different than in music where almost everything generally follows the same principles used in classical music.
Answer: There are lots of Shakespeare quotes in Star Trek if that's what you mean. See these references:

SHAKESPEARE IN THE STAR TREK UNIVERSE
Memorable quotes for Star Trek VI: The Undiscovered Country
William Shakespeare at Memory Alpha

My personal favorite, from Star Trek VI is: "You haven't heard Shakespeare until you've heard it in the original Klingon." (Chancellor Gorkon)
Comment: @blueberryfields: after re-reading your question I'm not sure if this answer is appropriate. This answer matches the title but not the word "structure". If this does not help please post that here and I will delete this answer.
Answer: Structure. Shakespeare's plays have been divided into more acts. Lots of screenwriting now has been formalized to 3 act structure. Some very old movies used a Shakespearean structure. Some episodes of the original Star Trek seem to have that kind of structure. Action with a comic relief secondary plot or vice versa. Suspense heightened by switching between settings. We wonder what's happening on the planet while we're on the ship. Will the ship be destroyed while we're on the planet? Formalized structure is a little like putting dots on a painting but it can be helpful to know before writing. I like the 5 act structure as a way to think about it.


Fixing the maximum size of a JList and changing the look of empty cells

Question: I'm working on UI stuff with a JList that can contain at most 8 items. Logically I have prevented the application from adding to the JList once it has reached it's limit, however, I was wondering if there was a way to perhaps explicitly set a limit on the JList itself. Which would help with the next thing I want to do, which is to repaint empty cells (up to 8 cells at most) to indicate that they are empty slots that can be filled. I'm trying to find a way to do this (perhaps by extending ListUI) which does not involve adding placeholder elements into the JList to represent empty spaces.
Answer: I think the most simple way is to implement a list model (using DefaultListModel or AbstractListModel) My idea is that the model will always have 8 items. All of them with a empty message.
If you add a new item to the model you can replace the empty text with a specific text for that item. The model will keep the track about how many items are added to the model. If you try to add more that MAX_ITEMS you can thow an exception or something like that.
Implement DefaultListModel is really easy and you have a lot of samples on Internet.
Answer: You can try the approach shown here, which limits growth to N entries, with scrolling enabled thereafter. A ListCellRenderer, shown here, may be used to alter the item's appearance.


Difference between "convert" and "transform"

Question: In the dictionary, the words "convert" and "transform" both have the meaning of changing the form of something. So how should I distinguish them? In what situation they are of the same meaning, and in what situation they are different?
Comment: Is there any particular context in which you are using them? For example, there is a big difference between converting and transforming electrical current, but not for converting or transforming a spare bedroom.
Comment: @Diansonn: [electric power conversion](http://en.wikipedia.org/wiki/Electric_power_conversion), [electric transformer](http://en.wikipedia.org/wiki/Transformer)
Comment: Could you please explain to me what the difference between "converting electrical current" and "transforming electrical current" is? Thank you.
Answer: As stated previously, the electrical example, though different from most usage, makes an easier case for distinction.  A transformer only changes one attribute, so that the result is the same basic type, but of a different capacity or intensity (voltage for example).  A converter, on the other hand makes the resulting object different in type from then initial condition, for example changing alternating current to direct current.
If we could apply this in general, then most of us would be in error in our usage of the two words.  Convert would mean something's natural attributes were changed, transform would mean the the size, shape, color, or some other attribute was changed, but the root nature of the item (or attitude or belief) was not changed.
Answer: Transform stands on its own. Convert implies convert to or convert from. A native-speaker's brain expects more information, a second part to the concept, with convert.

The house was transformed.
The cell was transformed.
She went through a remarkable transformation.
The empty nesters converted their kids' rooms into a library and a painting studio.
You've almost converted me to your way of thinking.

(They are generally synonymous, so depending on context a native speaker may expect more information with transform as well, but the expectation is not inherent as it is with convert.)
Answer: They are largely , and in most cases do mean the same thing (Though as stated in the question comments, electric transformation and electric conversion are quite different).
There are a number of other special contexts for each word, and you can read them both here and here.
Their primary definition (the first definition in both these links) is largely the same though.  In fact, looking at the root for both words, they both appear to come from Middle English and Old French, making them quite similar indeed!
So the difference then must be in how they are used in speech.
Pardon me, for I am about to use a very peculiar example of the word "transform".
In America, there was once a cartoon show called "Transformers", which you may have heard of.  It features robotic life forms that can transform into various different things, cars, radios, animals, et cetera.  Now, what if that show were instead called "Converters"? It sounds a bit wrong, doesn't it?  It sounds as if they are not so much beings that change shape, but rather beings that cause a change in shape to others.
It is true that "transformer" could also mean "one who causes a change in shape of another" though.  This is why it is a connotative difference, rather than a definitive one.  You will note that in the definition for "convert", it is stated to "change(something)", which implies an action upon another thing.  It does not necessarily mean that 'other thing' is not the thing doing the converting, but it implies that it is.  Likewise, 'transform' does not explicitly mean that one is transforming oneself, or another, but is better suited to imply a self-alteration.
This is NOT, however, always the case.  In fact, they say in religion that when one chooses to pick a religion different than their original choice, that they are a 'convert' or that they 'converted', even though that choice can be entirely in their own power.  It would be equally valid to say they "transformed" their beliefs, but it is rarely said that way.
Two words that have the same meaning can often be used to mean different things depending entirely on the context in which they are said, and in a larger sense, the context in which those words are used in the english language.
Answer: The normal verb for the idea of "to change the form of sth" is "to transform" from Latin trans over and forma form.
"To convert" from Latin vertere to change direction is used in special contexts such as
in religion: He converted to Buddhism
in linguistics: a noun can convert to a verb without change of form
and a lot of other sectors (architecture, electricity, mathematics etc).