How to convert signed to unsigned integer in python

Question: Let's say I have this number i = -6884376.
How do I refer to it as to an unsigned variable?
Something like (unsigned long)i in C.
Comment: Python doesn't have builtin unsigned types.
Comment: @AliSAIDOMAR no, `abs` function doesn't give what `(unsigned)` cast gives you in C, which is `(uint32_t)a = (1LL << 32) - a` for 2's complement
Comment: you can use abs() function.
Comment: Also, what is the problem you're trying to solve by doing this?
Comment: Python's integer type has an unlimited precision and is not dependent on underlying fixed size types. As such, it cannot differentiate between unsigned and signed types. You will have to do the conversion yourself.
Comment: What is it you mean by "I want the unsigned representation?" In your example, what do you expect the result to be?
Comment: It might be worth noting that whilst pythons int is not signed / unsigned and has unlimited precision, Python itself does in places understand the difference between signed and unsigned integers, for example in array.array. @ThePeacefulCoder - your solution will change the data, i.e. a byte which has been misinterpreted you have just removed a bit.
Comment: You can probably do something with the `struct` library, but like BrenBarn said; Python doesn't separate signedness.
Comment: @saidomar no, it won't give me the unsigned value, but the absolute value.
Comment: @BrenBarn I'm doing some kind of calculation that gives me a negative value, but I want the unsigned representation.
Comment: @poke How do I do it by myself?
Comment: Do `i = int(str(i).lstrip('-'))`. Boo, you've got unsigned `i`!! :D
Answer: Assuming:

You have 2's-complement representations in mind; and,
By (unsigned long) you mean unsigned 32-bit integer,

then you just need to add 2**32 (or 1 << 32) to the negative value.
For example, apply this to -1:
>>> -1
-1
>>> _ + 2**32
4294967295L
>>> bin(_)
'0b11111111111111111111111111111111'

Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.
Nobody but you can say what your hidden assumptions are, though.  If, for example, you have 1's-complement representations in mind, then you need to apply the ~ prefix operator instead.  Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of "sign bits").
And to duplicate what the platform C compiler does, you can use the ctypes module:
>>> import ctypes
>>> ctypes.c_ulong(-1)  # stuff Python's -1 into a C unsigned long
c_ulong(4294967295L)
>>> _.value
4294967295L

C's unsigned long happens to be 4 bytes on the box that ran this sample.
Comment: I didn't know you could use `_` to refer to the result of the previous line!
Comment: @HelloGoodbye, using `"_"` to retrieve a previous result is not a feature of the language itself, but a convenience implemented by some (most? all?) interactive Python shells.  They have to grab the most recent result regardless, in order to display it.  The language itself does no such thing.
Comment: Just in case anyone else stumbles on this answer I recommend checking out [@Duncan's answer instead](https://stackoverflow.com/a/20766900/1609514) which will convert any Python integer into an `unsigned long` equivalent. Simply adding 2**32 or 1 << 32 only works with negative integers in a certain range I think.
Comment: @Bill, I nevertheless prefer this answer. The answer you linked to hides the likely error if the bits masked away aren't all (a conceptually infinite string of copies of) the sign bit. The answer here leaves a goofy-looking result in goofy cases ;-) For example, `-1000000 & 0xff` returns 192, leaving no clue that information was lost (the result always fits in 8 bits). But `-1000000 + 256` returns -999744, a clear clue that something went wrong if you assumed no meaningful bits would be lost. YMMV.
Comment: @Yay295 Right! Is this only possible in interactive mode or can it be used in non´-interactive mode as well?
Answer: To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if unsigned long is 32 bit:
>>> i = -6884376
>>> i & 0xffffffff
4288082920

or if it is 64 bit:
>>> i & 0xffffffffffffffff
18446744073702667240

Do be aware though that although that gives you the value you would have in C, it is still a signed value, so any subsequent calculations may give a negative result and you'll have to continue to apply the mask to simulate a 32 or 64 bit calculation.
This works because although Python looks like it stores all numbers as sign and magnitude, the bitwise operations are defined as working on two's complement values. C stores integers in twos complement but with a fixed number of bits. Python bitwise operators act on twos complement values but as though they had an infinite number of bits: for positive numbers they extend leftwards to infinity with zeros, but negative numbers extend left with ones. The & operator will change that leftward string of ones into zeros and leave you with just the bits that would have fit into the C value.
Displaying the values in hex may make this clearer (and I rewrote to string of f's as an expression to show we are interested in either 32 or 64 bits):
>>> hex(i)
'-0x690c18'
>>> hex (i & ((1 << 32) - 1))
'0xff96f3e8'
>>> hex (i & ((1 << 64) - 1)
'0xffffffffff96f3e8L'

For a 32 bit value in C, positive numbers go up to 2147483647 (0x7fffffff), and negative numbers have the top bit set going from -1 (0xffffffff) down to -2147483648 (0x80000000). For values that fit entirely in the mask, we can reverse the process in Python by using a smaller mask to remove the sign bit and then subtracting the sign bit:
>>> u = i & ((1 << 32) - 1)
>>> (u & ((1 << 31) - 1)) - (u & (1 << 31))
-6884376

Or for the 64 bit version:
>>> u = 18446744073702667240
>>> (u & ((1 << 63) - 1)) - (u & (1 << 63))
-6884376

This inverse process will leave the value unchanged if the sign bit is 0, but obviously it isn't a true inverse because if you started with a value that wouldn't fit within the mask size then those bits are gone.
Comment: @MB I extended my answer, hope that helps.
Comment: Why on earth does this work? (and what would be the inverse operation)
Comment: +One: Simple, no imports
Comment: The inverse has proven quite useful. Some python libraries writeen in C return a signed 64bit value and this ends up as a long in python
Answer: Python doesn't have builtin unsigned types.  You can use mathematical operations to compute a new int representing the value you would get in C, but there is no "unsigned value" of a Python int.  The Python int is an abstraction of an integer value, not a direct access to a fixed-byte-size integer.
Answer: Since version 3.2 :
def unsignedToSigned(n, byte_count):
  return int.from_bytes(n.to_bytes(byte_count, 'little', signed=False), 'little', signed=True)

def signedToUnsigned(n, byte_count):
  return int.from_bytes(n.to_bytes(byte_count, 'little', signed=True), 'little', signed=False)

output :
In [3]: unsignedToSigned(5, 1)
Out[3]: 5

In [4]: signedToUnsigned(5, 1)
Out[4]: 5

In [5]: unsignedToSigned(0xFF, 1)
Out[5]: -1

In [6]: signedToUnsigned(0xFF, 1)
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
Input In [6], in <cell line: 1>()
----> 1 signedToUnsigned(0xFF, 1)

Input In [1], in signedToUnsigned(n, byte_count)
      4 def signedToUnsigned(n, byte_count):
----> 5   return int.from_bytes(n.to_bytes(byte_count, 'little', signed=True), 'little', signed=False)

OverflowError: int too big to convert

In [7]: signedToUnsigned(-1, 1)
Out[7]: 255

Explanations : to/from_bytes convert to/from bytes, in 2's complement considering the number as one of size byte_count * 8 bits. In C/C++, chances are you should pass 4 or 8 as byte_count for respectively a 32 or 64 bit number (the int type).
I first pack the input number in the format it is supposed to be from (using the signed argument to control signed/unsigned), then unpack to the format we would like it to have been from. And you get the result.
Note the Exception when trying to use fewer bytes than required to represent the number (In [6]). 0xFF is 255 which can't be represented using a C's char type (-128 ≤ n ≤ 127). This is preferable to any other behavior.
Comment: To me this is by far the most pythonic approach.
It even allows for beginner friendly byte packing/unpacking and does check the input, if it is even representable with a given amount of bytes and much more. See https://docs.python.org/3/library/stdtypes.html int.from_bytes and int.to_bytes for more.
Answer: You could use the struct Python built-in library:
Encode:
import struct

i = -6884376
print('{0:b}'.format(i))

packed = struct.pack('>l', i)  # Packing a long number.
unpacked = struct.unpack('>L', packed)[0]  # Unpacking a packed long number to unsigned long
print(unpacked)
print('{0:b}'.format(unpacked))

Out:
-11010010000110000011000
4288082920
11111111100101101111001111101000

Decode:
dec_pack = struct.pack('>L', unpacked)  # Packing an unsigned long number.
dec_unpack = struct.unpack('>l', dec_pack)[0]  # Unpacking a packed unsigned long number to long (revert action).
print(dec_unpack)

Out:
-6884376

[NOTE]:

> is BigEndian operation.
l is long.
L is unsigned long.
In amd64 architecture int and long are 32bit, So you could use i and I instead of l and L respectively.

[UPDATE]
According to the @hl037_ comment, this approach works on int32 not int64 or int128 as I used long operation into struct.pack(). Nevertheless, in the case of int64, the written code would be changed simply using long long operand (q) in struct as follows:
Encode:
i = 9223372036854775807  # the largest int64 number
packed = struct.pack('>q', i)  # Packing an int64 number
unpacked = struct.unpack('>Q', packed)[0]  # Unpacking signed to unsigned
print(unpacked)
print('{0:b}'.format(unpacked))

Out:
9223372036854775807
111111111111111111111111111111111111111111111111111111111111111

Next, follow the same way for the decoding stage. As well as this, keep in mind q is long long integer — 8byte and Q is unsigned long long
But in the case of int128, the situation is slightly different as there is no 16-byte operand for struct.pack(). Therefore, you should split your number into two int64.
Here's how it should be:
i = 10000000000000000000000000000000000000  # an int128 number
print(len('{0:b}'.format(i)))
max_int64 = 0xFFFFFFFFFFFFFFFF
packed = struct.pack('>qq', (i >> 64) & max_int64, i & max_int64)
a, b = struct.unpack('>QQ', packed)
unpacked = (a << 64) | b
print(unpacked)
print('{0:b}'.format(unpacked))

Out:
123
10000000000000000000000000000000000000
111100001011110111000010000110101011101101001000110110110010000000011110100001101101010000000000000000000000000000000000000

Comment: Note that it wont work for any integer size (>64bits / 128bit)
Comment: @hl037_ Thank you for mentioning it. That's a good point. However, I've mentioned about 32bit in the [NOTE] part. Nevertheless, I will update my answer with the cover of int64 and int128 as well.
Answer: I can't believe that no one has brought up ctypes, which I think the the correct answer for converting to a c-like (generally this means 2's complement) unsigned value.
import ctypes
myvalue = -23

ctypes.c_uint32(-23)
Out: c_uint(4294967273)

ctypes.c_uint8(-23)
Out: c_ubyte(233)

ctypes.c_uint8(-22)
Out[15]: c_ubyte(234)

For a sane sized and correct representation it might be a good idea to use the module whose job it is to interface with C
Answer: just use abs for converting unsigned to signed in python
 a=-12
b=abs(a)
print(b)

Output:
   12
Comment: but he asked only for integer.
Comment: This isn't what `(unsigned long)i` does. This is just plain wrong.
Comment: unsigned is very different from abs. Unsigned just changes the way of reading a set of bit values by not considering the first bit to be signed. abs on the other hand changes the signed bit to unset (by taking 2's complement) hence changing the bit representation
Comment: I feel like this is only partially true. As the [python MDN](https://docs.python.org/2/library/functions.html) states > `abs()`  Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned. **This by definition doesn't return an `unsigned` variable all the time**


Clash of clans bluestacks to original?

Question: I started playing Clash of Clans on my mobile with Town Hall level 2. Then I uninstalled it and I started playing a new Clash of Clans account on my laptop with BlueStacks. When I click on the 'Link a device' button it showed whether I wanted to load my previous account, but I want to link my new account to the phone again but not the original account.
Answer: So let me get this straight...
You started playing Clash of Clans on your phone with the Google account email of, let's say: email@example.com
Then you started a new base on Bluestacks.
Now you want to link the new base on Bluestacks to the phone, and get rid of the original one on the phone?
Okay, so make sure that on Bluestacks, you are linked to a new Google account in settings (email@example.com), then on your phone, unlink your game with the original account (Google email, firstname.lastname@example.com) and click the button again to link a new Google account, add the account from Bluestacks (firstname.lastname@example.com) if not already there. If it asks for a confirmation, type "CONFIRM". Boom, now the devices should be synced and linked.

Clash of clans bluestacks to original?


Prepend custom block body text

Question: I have a custom block with text in the body field. I need to prepend some text to this body field, either using php in a theme_hook function or in a twig file. How can I get just the text of the body field of a custom block so that I can alter it?
Answer: Here are three possible approaches to achieve your desired effect.
1. Hardcoding into a twig template for the custom block
If you don't need to modify the actual content defined within the body field of the custom block, and just want to hardcode the prepended text before the body content, creating a custom twig template for the block itself is probably easier for maintaining in the long run. This way it's easy to find and modify without the need to do any theme_hook function editing.

In your theme's template folder, add a block--[machinename-with-hyphens].html.twig template.
Copy the contents of the block.html.twig template that already exists in your theme or from a theme included with Drupal Core such as Bartik or Classy (/core/themes/classy).
Then in the template, add your markup and desired text before the <code>{% block content %}</code> section.  If your custom block has more than a body field, you can also render just the body field data using {{ content.body }}, and the other fields as {{ content.[field_machinename] }}

2. Hardcoding the text into a theme hook preprocess function
If you would rather avoid setting up a custom one-off twig template for the block and just want to hardcode the prepended text using a preprocess hook, you could:

Add a [custom_theme]_preprocess_block function. If your function doesn't explicitly inlcude the block's machine name in the function name, be sure to check the block machine name before prepending text and setting the content.
Create a variable for your custom markup/formatted text.
Concatenate that with the existing block content.
Set the 'content' variable in the preprocess function

See Drupal.org documentation for template_preprocess_block or hook_preprocess_block
3. Recommended Approach: no template or preprocess code required.
The easiest method to approach this might be to just add a custom field to the custom block type with the default value reflecting the prepended text. To do this:

Go to Structure > Block Layout
Select the Custom Block Library tab
Select Block Types
Choose Edit next to your existing custom block type or Add custom block to add a new custom block type.
In the Manage Fields section, add a field for the predefined text (or markup) to prepend.
In the Manage Display section, set the desired order for the fields to render.

Prepend custom block body text


Is it possible to recover an email that has been clicked "delete forever" in the trash folder?

Question: Is it possible to recover an email that has been clicked on "delete forever" in the trash folder?
I have accidentally clicked delete forever for an email but now I need to recover it.
Answer: I am sorry to say it is not possible to do so from within Gmail.
If the email was downloaded using Mozilla Thunderbird, Microsoft Outlook, or any similar software, and the mail client has not been synced since deletion, the messages can then be restored.
Answer: Unfortunately, there isn't an easy way to recover deleted email once you've done it forever.
The other answer on here is right - if you used another tool it might be possible.
Another option that might work (but is less likely), is to fill out a report of missing messages for the Gmail team to process: https://support.google.com/mail/bin/bin/request.py?&ctx=bugflow_receive31&contact_type=bugs
Gmail's help article says:

If you've deleted a message permanently, by clicking Delete Forever in
  your Spam or Trash, you won't be able to recover the message using the
  Gmail interface.

But you could use that bug request tool to describe directly to the team which email message(s) you need to recover and they might be able to help. Since this is meant for accounts that have been compromised, it might not work, but it's worth a shot.
Good luck :)
Comment: Important Note, while you can restore permanently deleted within the past 25 days for work/school accounts you can NOT recover messages deleted from the spam folder, that seems to be truly permanent.
[https://support.google.com/a/answer/6052340?hl=en]
Answer: If this Gmail account was part of a work or school Google Apps domain, your admin can restore deleted email or Drive files for up to 25 days by following the step provided in this Google help article: Restore a user's Google Drive or Gmail data
This does NOT apply to consumer @gmail.com accounts.


Is travel date change possible in between validity of schengen visa?

Question: I recently got my Schengen visa from Czech Republic Embassy UAE, Validity of visa is from 7 to 30 May with permitted duration of stay is 9 days, my original plan was 7 to 15 may but I want to change date to 10 to 17 may is it possible ?
Comment: As I read it, your new plan is within the limits of the visa you were given, and as such it is possible.
Comment: So as per my understanding with your answer is there won't be any problem if I'll follow new plan which is well inside visa validity dates ?
Answer: You have been given extra days of validity for just this purpose. Business meetings may be shifted on short notice, etc.

You must comply both with duration and validity. Partial days count. 10th to 17th are 8 days, which means you have one day to spare.
The purpose and itinerary should be recognizably the same. You can change flights and even the airport and country of arrival in the Schengen area, but you should go to the Czech Republic for the purpose you applied for and spend most of the days in the Czech Republic.
Answer: Your visa allows you to stay for up to nine days, between 7 and 30 May. Your plan is to stay for eight days from 10 to 17 May. That is up to nine days and between 7 and 30 May. Of course that is valid.


How to find $\lim_{x \to 0} ( \frac{1}{\sin(x)}- \frac{1}{\arcsin(x)})$

Question: I want to do the problem without using L'Hopitals rule, I have
$$\frac{1}{\sin(x)}- \frac{1}{\arcsin(x)} = \frac{x}{\sin(x)}\frac{x}{\arcsin(x)}\frac{\sin(x)-\arcsin(x)}{x^2}$$
and I'm not quite sure about how to deal with the $\dfrac{\sin(x)-\arcsin(x)}{x^2}$, apparently its limit is $0$? In which case the whole limit would be $0$. But how would I show this without using l'Hopitals rule. Thanks for any help.
Comment: If you can't use L'Hopital, you can use the power series for $\sin x$ and $\arcsin x$...
Comment: Without L'Hopital's rule and without the full power of Taylor series, you can note that $\sin(0)=\arcsin(0)=0$ (so the numerator is $o(1)$) and $\sin'(0)=\arcsin'(0)=1$ (so the numerator is $o(x)$). Now $\sin''(0)=0$ is clear, so all that's left to be done is checking that $\arcsin''(0)=0$ to conclude that the numerator is $o(x^2)$ and so the whole thing goes to 0.
Comment: @Ian: The whole point of not using L'Hospital and Taylor is to avoid differentiation and instead find a solution using rules of limits and some manipulation of the expression under consideration. I have presented an answer along these lines.
Answer: Using Taylor's theorem:
$$\color{blue}{\sin x=x-x^3/6+x^5/120+O(x^7)}$$
$$\color{red}{\arcsin x=x+x^3/6+3x^5/40+O(x^7)}$$
So:
$$\begin{align}\left( \frac{1}{\color{blue}{\sin(x)}}- \frac{1}{\color{red}{\arcsin(x)}}\right)&=\frac{\color{red}{\arcsin x}-\color{blue}{\sin x} }{\color{blue}{\sin x}\arcsin x}\\&=\frac{\color{blue}{\color{red}{(x+x^3/6+O(x^5))}-(x-x^3/6+O(x^5))}}{\color{blue}{(x-x^3/6+O(x^5))}\color{red}{(x+x^3/6+O(x^5))}}\\&=\frac{+x^3/3+O(x^5)}{x^2+O(x^6)}\end{align}$$
So:
$$\lim \limits_{x \to 0}\left( \frac{1}{\sin(x)}- \frac{1}{\arcsin(x)}\right)=0$$
Answer: When $x\rightarrow0$

$\sin x\sim x-\frac{x^3}{6}$
$\arcsin x\sim x+\frac{x^3}{6}$
$\sin x-\arcsin x \sim (x-\frac{x^3}{6})-(x+\frac{x^3}{6})=-\frac{x^3}{3}$

$$\displaystyle \lim_{x\rightarrow 0}\frac{\sin x -\arcsin x}{\sin x \cdot \arcsin x }=\lim_{x\rightarrow 0}\frac{-\frac{x^3}{3}}{\sin x \cdot \arcsin x }=\lim_{x\rightarrow 0}\frac{-\frac{x^3}{3}}{ x ^2 }=\lim_{x\rightarrow 0}\frac{\frac{-x}{3}}{ 1 }=0\\
$$
Answer: Let $x \to 0^{+}$ and then we know that $\cos x < \dfrac{\sin x}{x} < 1$ (this is pretty standard from geometric arguments commonly used in proof of $\lim\limits_{x \to 0}\dfrac{\sin x}{x} = 1$ see this answer) and then we get $$\cos x - 1 < \frac{\sin x - x}{x} < 0$$ which further means that $$\frac{\cos x - 1}{x} < \frac{\sin x - x}{x^{2}} < 0\tag{1}$$ Now we can see that $$\frac{\cos x - 1}{x} = -\frac{2\sin^{2}(x/2)}{(x/2)^{2}}\cdot\frac{(x/2)^{2}}{x} \to 0 $$ as $x \to 0^{+}$. Hence by using squeeze theorem on $(1)$ we get $$\lim_{x \to 0^{+}}\frac{\sin x - x}{x^{2}} = 0$$ and hence $$\begin{aligned}\lim_{x \to 0^{+}}\frac{\arcsin x - x}{x^{2}} &= \lim_{x \to 0^{+}}\frac{\arcsin x - x}{(\arcsin x)^{2}}\cdot\frac{(\arcsin x)^{2}}{x^{2}}\\
&= \lim_{t \to 0^{+}}\frac{t - \sin t}{t^{2}}\cdot\frac{t^{2}}{\sin^{2}t}\text{ (}\arcsin x = t)\\
&= 0\end{aligned}$$ It is now clear that $$\lim_{x \to 0^{+}}\frac{\sin x - \arcsin x}{x^{2}} = \lim_{x \to 0^{+}}\frac{\sin x - x}{x^{2}} - \frac{\arcsin x - x}{x^{2}} = 0$$ If $x \to 0^{-}$ then we can put $x = -y$ and $y \to 0^{+}$ and again the limit is $0$.
This is a nice example which shows that most usual limit problems don't need advanced tools like L'Hospital's Rule and Taylor series.
Comment: you showed $L_1=\frac{\sin x-x}{x^2}\to0$ and $L_2=\frac{\arcsin x-x}{x^2}\to0$ when $x\to0$ in both but that doesn't mean $L_1-L_2\to0$
Comment: @Aditya: Your comment is weird and i find hard to believe it is coming from you. If $f(x) \to A$ and $g(x) \to B$ as $x \to a$ then $f(x) - g(x) \to (A - B)$ as $x \to a$. Here $a = A = B = 0$ and $f(x) = (\sin x - x)/x^{2}$ and $g(x) = (\arcsin x - x)/x^{2}$.
Comment: Oh! I may be wrong, If possible I'll use a contradiction, If I'm wrong I apolize.
Comment: @Aditya: No need for apology, but I believe you are thinking in haste. Its basic algebra of limits $$\lim_{x \to a}\{f(x) \pm g(x)\} = \lim_{x \to a}f(x) \pm \lim_{x \to a}g(x)$$ provided both limits on right side exist. Here in our question both the limits on right side are $0$ so that the limit of $f(x) - g(x)$ is also $0$.
Comment: Yes I was thinking of this, but a closer looks make me reveal that I'm wrong: $L_1=\frac{\sin x-x}{x^2}=-x/6+...\to0$ and $L_2=\frac{\cos x-1}x=-x/2+...$; I was thinking of $L_1+L_2/3$ which would cancel $x$ but that'll leave us with $x^2$ that also goes to zero.ii) As I was wrong I suddenly recongnized this basic algebra, thanks for reclarification


PCB Routing Considerations for multiple USB Port Types for USB 1.1 Full Speed

Question: I wanted to make a device that has a USB A and a USB C connector on apposing sides of the PCB, similar to the attached image.  These USB connectors would be connected to the same USB port, the MCU I am using has only one USB port. The connection type would be USB 1.1 full speed. One of the connections can be made under the critical length, the other one I would have to run matched impedance controlled traces to. I am just wondering if I have to worry about the traces for the connection that is not being used, acting as a capacitor or inductor. Is there anything else I have to worry about?
Comment: *"One of the connections can be made under the critical length, the other one I would have to run matched impedance controlled traces to."* You do realize that the data lines are a differential pair, and should be routed as such? (In parallell, equal length) Regarding impedance matching, I wouldn't worry about it for full speed USB if the traces are less than like 200 mm or so.
Comment: USB 1.1 Full speed does not care about HF impedance much, especially when the traces are not very long. Remember, we are talking about 6MHz here (IIRC).
Comment: The question is, why do you want to do that? USB connections can't be split into two connectors so it makes no sense to do that, unless you can mechanically enforce that only one connector can be used at one given time. Even having just an extra cable connected in addition to the one you want to use will cause problems. Will the MCU be a USB host or device? It might be simpler to just use an USB mux to switch between connectors.
Comment: @Klas-Kenny it's not true that diff pairs must be routed together. Length matches yes, but routing in parallel is a *deliberate choice* and nothing prevents perfect functionality and EMC even if the traces are far apart or even on different layers. Most return current anyway flows in the reference planes.
Answer: USB Full Speed is simply symmetrical* 12MHz LVCMOS logic levels.  It's very far from a signal quality concern; fast enough to need proper cables, low enough voltage to need shielding, but at the PCB level, trace width, and length (up to a generous limit) are largely irrelevant.
*Except when they're not; the start and stop symbols are asymmetrical (both lines moving in the same direction, not complementary).  Which is another reason why USB is difficult to filter noise off of, and why contiguous shields are mandatory.
You will have no problems, with a board sized as pictured.
However, if you're expecting performance up at High Speed, these concerns are more justified.  Still not a problem on a board that size, I think (the stub length of either connector will be, what, a cm or two, at most?).  Super Speed will probably not work with such stubs.  (But, since SS isn't supported by USB-A, it would be quite strange to route those pairs to a connector that doesn't even have pins for them. :) )
The deciding factor is if a stub length or mismatch length is a substantial fraction of a bit-time: for High Speed, this is in the low ~cm.  Trace mismatch isn't extreme in most situations: the usual worst case is thin traces on a thick substrate (i.e. 2-layer board): the differential impedance is in the 150-200 ohm range, when 90 or so is required; so, it's only a 2:1 mismatch, not at all extreme.  Mismatch becomes proportionally more significant when it's worse -- but it's hard to even conceive of a situation with, like, 600 ohm twin lead, on a PCB with ground plane (good luck with that?!), and even then that's a ~5x mismatch so only 5x more sensitive, or a problem for "low ~cm" / 5 -- say, >3mm worth.
In general, when mismatch is some factor, the critical length is shorter by the same factor; for example, we can apply this to the layout of switching converters, where the impedance might be a mere 5 ohms ballpark (say for a 5V 1A converter).  Relative to say ~100 ohm traces, that's a mismatch of 20x.  If the converter's maximum harmonic frequency is ~200MHz (typical for modern switching regulators), the critical length is a wavelength of ~4GHz.  So, a cm or so -- hence why we minimize layout area of these circuits.  The same logic applies to most digital communications, and so we minimize the layout area for them as well, with the scale factor (for what counts as "minimized") given thusly.


dbgrid autofit to a form

Question: I have used DBGrid in BDS 2006.It has 6 columns which are populated during runtime.
The datatype for for one column is char(150) in mysql database. since while retriving from database to dbgrid it takes the length and the columns become wider with a scroll bar and  some coloumns remain hidden.
so my question is how to fit these coloumns of the dbgrid to the form?
Comment: @DorinDuminica i dint get the answers to previus questions.
Answer: You can use the free JVCL JEDI Visual Component Library
Use the TJvDBGrid and set AutoSizeColumn to True.  It will all allow the columns to fit for the DBGrid width and show no horizontal scroll bar.

dbgrid autofit to a form


Change brightness Vaio FZ

Question: I can't change the brightness on my Vaio VGN-FZ340E.  There isn't even a slider on the screens window. The only way I've found to do it is to use smartdimmer throught the command line, however this is pretty inconvenient.  any help would be appreciated.
Comment: Relevant bug report: [No Screen Backlight Control; Notebooks with Nvidia Geforce8/Geforce9/Quadro series graphics](https://bugs.launchpad.net/ubuntu/+bug/95444)
Answer: (SOLVED) Please see the link
http://ubuntuforums.org/showthread.php?t=1004568&page=3
I have Sony Vaio VGN FZ340E and after long search I found the solution in the following link
http://doube.org/karmic-vaio
and now its working perfect without any problem I've only changed the (the SPIC to SNC) for both files
sony-brightness-up
sony-brightness-down
Shown expression

for sony-brightness-up file
event=sony/hotkey SPIC 00000001 00000011

I used the following expression
event=sony/hotkey SNC 00000001 00000011

for sony-brightness-down file
event=sony/hotkey SPIC 00000001 00000010

I used the following expression
event=sony/hotkey SNC 00000001 00000010

Backlight
Backlight support for Vaios is now incorporated in nvclock
Make sure you have nvclock installed for basic backlight control, and until HAL has been updated you have to specify the hotkey event manually.
sudo apt-get install nvclock
nvclock -S 100
nvclock -S 15
nvclock -S +10

Enable the "brighter" hotkey:
sudo gedit /etc/acpi/events/sony-brightness-up

put this text into it:
event=sony/hotkey SNC 00000001 00000011
action=/usr/bin/nvclock -S +10

And the "dimmer" hotkey:
sudo gedit /etc/acpi/events/sony-brightness-down

put this text into it:
event=sony/hotkey SNC 00000001 00000010
action=/usr/bin/nvclock -S -10

Make the scripts executable
sudo chmod +x /etc/acpi/events/sony-brightness-*

Restart acpid
sudo /etc/init.d/acpid restart

If you have a different model, you might have different keys controlling your backlight. To check the event ID, run
acpi_listen

Answer: Other Solution Which is better visit this link :
Brightness not working after installing NVIDIA driver
Just Download the following file
https://github.com/downloads/guillaumezin/nvidiabl/nvidiabl-dkms_0.72_all.deb
Then run the following in the terminal
echo "nvidiabl" | sudo tee -a /etc/modules

Change brightness Vaio FZ


I have 3 folders in IE favourites that I am unable to remove/delete. Help please

Question: I have 3 folders in IE favourites that I am unable to remove or delete.I keep getting a message for each folder "This is no longer located in C:\Users\Bob\Favourites. Verify the item's location and try again." But when I open C:\Users\Bob\Favourites they are all there. I cannot delete them from this folder either without getting the same message. I think this has to be a registry issue but I don't know what to do to eradicate these 3 'ghost' folders.
Comment: What makes you think it's a registry issue? It's more likely a file-system issue (Favorites are just shortcuts (.LNK), which are files). Have you done a disk check yet to ensure you don't have file system corruption?
Comment: There a reason Favorite isn't spelled right?
Comment: Sorry about spelling Ramhound - I'm in UK and used to British English, but it isn't my spelling causing the problem!
Comment: It is spelt right, the US spells it wrong. ;)
Comment: Techie007 - should I just run Glarysoft Utilities then, do you think it might pick this up? Bob
Comment: No, you should use [Windows' in-built disk checker](http://windows.microsoft.com/en-ca/windows-vista/check-your-hard-disk-for-errors) to start (ps: make a full backup before allowing utilities to do any repairs to the disk).
Answer: I very well could be registry, First I would run a disk cleanup and a chkdsk and make sure to rebuild your icon cache. Info about that is HERE and Here.
Second, You can try to add a take ownership to the file or folder, and try to delete it, Info about that is Here. (P.S. This is great to have for several situations.)
Third, if it is registry, Try to run CCleaner which is found Here, and It has a registry tool.
If those don't work, we can get some more information and go from there, Also, are you making sure you are running as Administrator, and that in the control panel, the display protected system files is unchecked, if that is ticked, you will see all kinds of system files that you don't want to see.
Comment: Also I just verified that I can delete the same files on my system with no problem, they are not even ghost hidden files.
Comment: Hi trenten, thank you for giving me some ideas. I did the disk cleanup and chkdsk and also the take-ownership trick, but alas, to no avail. CCleaner didn't 'see' the files and I also tried shredding them with Glarysoft, but that didn't work either. However I have managed to get rid of one of them by downloading Unlocker from Filehippo and zapping them each with it. Finally I had to boot into Linux (Zorin) to delete the remaining two there. When I rebooted into W7 all the blasted things had finally disappeared. Once again, many thanks for your trouble. Much appreciated.
Comment: No problem, at least you were able to get them deleted.


How to calculate Hat matrix for penalized spline regressions?

Question: The book "Semiparametric Regression" by Ruppert et al. (2003) provided a computationally fast algorithm for Penalized Spline Regression. I put a part of the algorithm here. Does anybody can do algebra to prove equation that is mentioned on step 4? Any help would be much appreciated.
Answer: I get an ever so slightly different formula, but it only differs in where a transpose is placed.
Let's start with the expression $$C^t C + \alpha D $$ and use the hypothesized decomposition $$C^t C = R^t R$$ to write:
$$\begin{align*}
  C^t C + \alpha D &= R^t R + \alpha D \\
  &=  R^t R + \alpha R^{t} R^{-t} D R^{-1} R \\
  &= R^t ( I + \alpha R^{-t} D R^{-1} ) R \\
  &= R^t ( I + \alpha U \text{diag}(s) U^t ) R
\end{align*}$$
In the last step we've used $R^{-t} D R^{-1} =  U \text{diag}(s) U^t$, another hypothesis.  Note that $U^t U = I$, since $U$ is an orthogonal matrix.
Breaking down the inverse:
$$\begin{align*}
  ( I + \alpha U \text{diag}(s) U^t )^{-1} &= ( U U^t + \alpha U \text{diag}(s) U^t ) \\
  &= ( U (I + \alpha \ \text{diag}(s)) U^t)^{-1} \\
  &= U^{-t} ( I + \alpha \ \text{diag}(s) )^{-1} U^{-1}
\end{align*}$$
Now the matrix $I + \alpha \ \text{diag}(s)$ is itself diagonal, so its inverse is as well.  We can write its inverse conveniently as
$$ \frac{1}{1 + \alpha \ \text{diag}(s)} $$
Now put it all together to get:
$$\begin{align*}
  C ( C^t C + \alpha D )^{-1} C^t y &= C R^{-1} U^{-t} \frac{1}{1 + \alpha \ \text{diag}(s)} U^{-1} R^{-t} C^{t} y \\
  &= C R^{-1} U^{-t} \frac{1}{1 + \alpha \ \text{diag}(s)} ( C R^{-1} U^{-t} )^t y \\
  &= A \frac{1}{1 + \alpha \ \text{diag}(s)} A^{t} y
\end{align*}$$
which, up to a substitution of $U^t$ with $U$, is the formula quoted.
Comment: @A.Gh You're very welcome, I quite like this subject.  I'd much appreciate it if you accepted my answer if it was what you were after.  Thanks.


SRTM mosaic elevations

Question: My SRTM tiles have their elevations ranging from sea level i.e. 0m to 5,300m in Tanzania. My problem is that when I mosaic any two or more tiles, the elevation  displayed on the Table of contents changes and the range becomes unbelievably high e.g. 0 - 65,000 and so the mosaic can't represent the terrain in my country.
Comment: The range of allowable values in an unsigned 16-bit raster is 0-65535.  If you haven't constructed statistics, the software is unlikely to know the actual range.
Answer: SRTM data have pixel type of signed integer and pixel depth of 16 bit. The following image shows the property of an SRTM sample covering a region in Tanzania:

When you mosaic the data using Mosaic to New Raster tool, you need to define the output pixel type to be similar to the input raster data type which are signed integer and pixel depth of 16 bit, as you can see below:

The output should be correct:

Here is the property of the output final DEM:

SRTM mosaic elevations


SVN use for Team development with Intel XDK New

Question: I have installed Intel XDK New by registering with my email ID. I work with a fellow developer on the same project, It seems I can grant access to my team mate email in http://appcenter.html5tools-software.intel.com/
Does it share code on cloud to him? How can we make use SVN for team development? I know that Intel XDK NEW does not have SVN features on its own.
Please advice. Thank you.
Answer: The cloud part of the new XDK only provides build and debug services (push to the cloud to build and facilitating weinre via the Test tab). With the old XDK it would also populate your local directory with projects that had been pushed to the cloud, but this is not the case with the new XDK.
The XDK today does not include any revision control services. However, since your project files are all local to your dev system, you can use whatever remote version control and/or sharing service you like to share source files. For example, you could use dropbox or something similar to share your sources directly or you could use a git repo on github to share them. It's up to you to manage that process.


Download your Twitter followers' avatar pictures

Question: I'm looking for a way to download all my followers' profile pics (48x48 px or bigger) in one run using either the Twitter API or some scripted scraping on twitter.com
Answer: twilk does this: http://twilk.com/
So a week ago I found someone who gave the source code in a .Net application could not find it so quickly via Google but if you search for this combo you will find the source code.
Answer:
Get your list of friends
Loop through each friend and get their profile pic
Comment: This obviously helped the Asker, but the goal of Stack Exchange is to build a repository of questions and answers that will help the many people who have the same question. That's not going to help if these links go away. Granted, they're from the Twitter dev site, and that will likely be around as long as Twitter, but sites have been known to re-organize and not redirect old links to new content.


Wine 1.6.2 sound not working

Question: I'm using an Ubuntu 14.04 and a Wine 1.6.2. I successfully installed and ran GTA III from it and it works, except that there is no audio. I changed the setting from "speaker" to "headphone"(what I use) and even tried changing the in-game hardware options. It should be noted that I have never used Wine before this so it would most probably be a problem regarding Wine.
Answer: Wine is notorious for having problems with Pulseaudio, Ubuntu's default sound server. As a result, it is necessary for you to switch to ALSA. To do that, follow the below instructions.

Run sudo apt-get autoremove pulseaudio from terminal
Run sudo apt-get install gnome-alsamixer

Done! You can find more information here.
Additionally, Wine 1.6.2 seems to be outdated. Since you are trying to run games, you probably want the latest version. To install it, follow the below steps.

Run sudo apt-add-repository ppa:ubuntu-wine/ppa
When asked, hit Enter
Run sudo apt-get remove wine wine1.6
Run sudo apt-get install wine1.7

After that, you should be running the latest Wine.
Comment: Thanks for the answer, but when I installed alsamixer, do I have to add it in Wine's settings or does it work without anything? In Wine's audio settings, I am unable to find it. I can only see "Default System" and pulseaudio.
Comment: From my experience, it works out of the box, provided it is your system default.

Wine 1.6.2 sound not working


How to write a scene from multiple peoples perspectives?

Question: I want to write a scene from multiple peoples perspectives without making it incredibly long, or repetitive.  Is there a correct way to go about this?
Comment: Why do you want to write it from multiple people's perspective? This is important, because any technique you use depends on the effect you are trying to create for the reader.
Comment: I've red a book where a battle scene was written out multiple times, from start to finish, each time from someone else's perspective. Another way to do it is to have breaks in the writing, and to switch point of view often while maintainins a focus on the group as a whole.
Comment: I wanted to write it from multiple peoples perspectives to point out how the same event can affect different people, completely differently.  Such as one may have a positive view on things, while another takes it negatively, etc.
Answer: Writing (exposition) is subjective. There is no correct way to achieve your effect. I have used multiple perspectives several times.
Effectively you are playing with time so you will require one or more anchors.
The simplest anchor is an active anchor. An active anchor is an ongoing event: a speech, a thunderstorm, etc . . .
Example.
My character is running in the Olympic 400m relay final. Her grandfather is in his hospital bed, watching the event on TV. Her boyfriend is in a taxi, listening to the event on the radio. Her brother is watching the event on his phone. That's four POVs. I can switch between them at will.
The static anchor is more complicated because you have to play with time.
Example.
I have three anchors: (1) a church bell rings. (2) A gunshot rings out. (3) Another gunshot is heard.
A family are having dinner. The church bell rings (signifying 12.00) The father leaves the table because 'the game' has started on TV. The aunt is shot.
Change POV.
A sniper is watching a family eat. He has his target in the cross-hairs. The church bell rings. He squeezes the trigger.
Change POV.
A woman is boarding the 12.00 train. The church bell rings. She hears the faint sound of a gun-shot. She smiles. "Job done."
Answer: I usually cheat, by having the second or third character look back from a period in the future. For instance if I am describing a car wreck, I might write:
Bob was driving his car through the intersection when suddenly a truck appeared out of nowhere and crashed into his door. Then I would later describe the passenger waking up in the hospital and have him try to remember how he got there. Then realizing the last thing he remembered was, noticing that bob wasn't stopping for a red light.
Answer: One of the best ways I have seen this done is have the scene play out normally, and then when you come to an end point where you can pause and switch views, go back from a different angle and repeat until you have all the view points covered.  Then usually it is blended nicely back together to the original perspective to continue on from that time point.  Honestly I wish you the best as this will be really tricky to do and pull off as it can easily become confusing and intertwined poorly.  It's also a lot harder to do this in writing than it is in cinema.  There are a lot of smart people here to help :)


Chainlink VRF fulfillRandomness doesn't use enough gas to perform function - how to get it to use more?

Question: Chainlink VRF allows users to get a random number by calling requestRandomness and then waiting for the fulfillRandomness callback to be called by the Chainlink contract.
I have a function testWorstMint that mints some NFT's, given an amount. I want my NFT distribution to be random, so I'm simulating what would happen if the loop had to iterate over thousands of NFT's already assigned.
I am using 5000 for the MAX_NFT_SUPPLY, and I minted 1 token, which in this case would be the token with ID 4999. This costs roughly 600k in gas.
function testWorstMint(uint256 amount) public
{

    testWorstMint(msg.sender, amount);
}

function testWorstMint(address owner, uint256 amount) public
{

    uint256 total = totalSupply();
    for (uint256 x = 0; x < (MAX_NFT_SUPPLY - total); x++)
    {
        if (x >= MAX_NFT_SUPPLY - total - amount)
        {
            _mint(owner, x);
        }
    }
}

The issue I'm having is that fulfillRandomness does not estimate gas properly (at least, that's what I think is happening).
function request(uint256 amount) public {
    require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - contract will be funded soon");

    bytes32 requestId = requestRandomness(keyHash, fee, 0);
    owners[requestId] = msg.sender;
    amountToMint[requestId] = amount;
}

function fulfillRandomness(bytes32 requestId, uint256 randomness) internal  override {

    testWorstMint(owners[requestId], amountToMint[requestId]);
}

Calling request() does the exact same as what I described above, but it does it through a callback. It costs roughly 60k in gas for the request call, and increasing it is futile since it'll just be returned (and it's not like it goes to fulfillRandomness anyway).
fulfillRandomness does the exact same thing as the function above, but it fails, presumably because of gas. From the contract, it seems that gas limit for all VRF fulfillments is capped at 500k, well below what I need to mint one token at random in the worst-case scenario.
Answer: According to the Chainlink VRF Documentation:

If your fulfillRandomness function uses more than 200k gas, the transaction will fail.

The maximum gas for a callback function can only be 200k, so the callback function isn't being triggered due to this.


If I insert a Japanese SIM into my Nexus 4, can I have unlimited access to the Japanese Google Play Store?

Question: I read this thread (How does Google Play determine the region on a tablet without SIM card) and it seems like the region is determined by IP, but if I insert a SIM purchased in Japan into my Nexus 4, will I be able to purchase Japanese apps, games, books, etc even if I don't have a Japanese credit card, or will I need that as well?
Answer: No, having a SIM card from a particular country does not get you that country's Play Store. See this answer on a related question for instructions from Google Play support about moving to a different country.


What is the difference between profilers that need recompiling and those that do not?

Question: What are the differences between using profilers that need to recompile the source code with debugging options(like gprof) and profilers that do not need recompiling(like Valgrind, OProfile, ...)?
Answer: I can speak on Valgrind and gprof at least.
The primary differences between using the two is basically what you already said.  For gprof, you have to compile it specially to include the profiling code.  When you then run your executable, the profiling code is executed (since it's built into your program), and a gmon.out file is created that can then be processed by gprof to show you runtime statistics of your program.
Valgrind is different in that you don't need to compile your program in any special way (except to add debug symbols if you want the output to be useful).  Valgrind dynamically translates your program into an internal format that is run on a simulated CPU (although this is slow).  This means that any program can be run through Valgrind without needing the special compilation.
Another important difference is that Valgrind can report a lot more information than gprof does, but that's not specifically related to using it.
Answer: I'm not familiar with the named profilers but there are two major approaches to profiling:
Instrumentation, this method usually requires recompiling (not always, for example java and .Net applications can be instrumented dynamically). With this method it is possible to measure exactly how often a routine is called, or how many iterations a certain loop makes.
Sampeling is a method that does not require any recompiling, it simply takes a snapshot of the stack with set intervals. This has proven to be an effective way to find bottlenecks.
There is some more info about the two strategies here
Answer: Any profiling technique is going to need symbol table information, so that has to be requested in the compilation and linking.
Other than that, some profilers work by compiling-in calls to record-keeping routines at the beginning and possibly end of each function.
Those functions can attempt to record the time used by the function, and some record of where it was called from.
Its timing figures are made inaccurate by the overhead of calling those recording functions.
Other profilers do not need to do that, instead relying on periodic samples of the call stack.
Such a profiler has lower overhead.
Its timing figures are made inaccurate by the statistical nature of its sampling.
Implicit in this is that accuracy of timing is necessary for locating "bottlenecks", which has never, to my knowledge, been shown to be true.
The method I've always used to get orders of magnitude speedup relies on insight into what the program is doing as it spends time, rather than on precisely how much time is spent. If you're interested in the statistical rationale, you could look here.


Abbreviating authors' names in a paper

Question: I'm writing a rebuttal to a paper that was recently published. Since I refer to the authors very frequently, I've abbreviated their names to WW for their last names Williams and Wang (I made up these names, they aren't the real names). Is this appropriate for a scientific journal? Should I write W and W or W&W instead of WW?
Comment: W&W might work if the journal permits it. But Williams & Wang is likely better.
Answer: It depends entirely on the journal's style - each journal should have a 'style sheet'/'style guide' that says exactly how they expect everything to be formatted and cited. You should check the journal's website for this.
(IMHO, unless you're really short on space, I always think it's nicer not to abbreviate... but there are different opinions on this both on a personal level and on a field level.)
Answer: I hope they are not Williams and Coleman, or that you are not writting a rebuttal on Holocaust themes on the paper of Schutz and Saponer ...
Jokes apart, I would say that if you have so much to rebutt on one single paper, either you are spreading out the discussion of some sentence/ideas on too many sentences/part of your rebuttal, or that you should investigate previous work of Williams and Wang to understand why they say something.
Be concise, rebuttal works are often desk rejected because too long, then refused by editors, and finally required to be way shorter than you would possibly, so saving some hundred of characters from the names is not what will help you ...
Comment: On the other hand, if this is a reply to Cox and Zucker's famous paper, perhaps, CZ would be better?
Comment: @XanderHenderson I am sure there is a joke, but I am missing it :D
Answer: Another way to deal with this is through the use of a) Pronouns (they, them, their) and b) Terms such as "the authors" or "the article" and so on.
But the ultimate answer, of course, is what @PFD said: "It's up to the journal". And if their style sheet doesn't cover this, then I wouldn't worry too much. The journal isn't going to make their decision about publishing your rebuttal based on whether you abbreviate their names. They'll just tell you to revise.  This would be a very easy revision.
Answer: At least in economics, it is fairly common that a paper which extensively discusses another paper will abbreviate the authors' names in such a manner. It would not be unusual to see a paper cited formally at the first mention along with an abbreviation for subsequent mentions, for example, "Williams and Wang (2022, henceforth WW) ...".
It would be difficult to say if this style will be accepted in a different field (or even a different publication), but it is evidently accepted in at least some places.
Comment: Good to know that this is common. I ended up using WW and waiting for the Journal (which didn't have any published advice on this) to potentially ask us to change it.

Abbreviating authors' names in a paper


Sleeping Barber Problem (with multiple barbers)

Question: The Sleeping Barber Problem is a classical synchronization problem that many of you may be familiar with or at least heard of.
It's based on the premise that a barber (a thread) sleeps when there are no customers (each customer is a thread) in the waiting room (which is a semaphore). If there is someone, he cuts his hair (symbolizing some processing) and the costumer leaves. If, then, there is no one in the waiting room, the barber goes to sleep. When another customer arrives, he then must wake up the barber.
I have made a implementation of this using the following basic-idea (pseudo-code, only using sem_wait and sem_post1 for smooth reading)
Semaphore Customers = 0;
Semaphore Barber = 0;
Mutex accessSeats = 1;
int NumberOfFreeSeats = N;

Barber {
    while(1) {
        sem_wait(Customers) // waits for a customer (sleeps)
        sem_wait(accessSeats) // mutex to protect the number of available seats
        NumberOfFreeSeats++ // a chair gets free
        sem_post(Barber) // bring customer for haircut
        sem_post(accessSeats) // release the mutex on the chair
        // barber is cutting hair
    }
}

Customer {
    while(1) {
        sem_wait(accessSeats) // protects seats so only 1 thread tries to sit in a chair if that's the case
        if(NumberOfFreeSeats > 0) {
            NumberOfFreeSeats-- // sitting down
            sem_post(Customers) // notify the barber
            sem_post(accessSeats) // release the lock
            sem_wait(Barber) // wait in the waiting room if barber is busy
            // customer is having hair cut
        } else {
            sem_post(accessSeats) // release the lock
            // customer leaves
        }
   }
}

However, now that I'll implement this problem with multiple barbers, my head got stuck. I went on Wikipedia to see if I could find something about it, but the only thing that I found there was this

A multiple sleeping barbers problem has the additional complexity of coordinating several barbers among the waiting customers.

and I couldn't figure this out by myself. In which case I'd have this complexity? By several barbers going to the waiting room to see if there is anyone there and then taking (more than one barber) a single customer? Would I need an extra semaphore here?
1sem_wait() locks the semaphore. sem_post() unlocks it
Answer: With one barber, you only need a message queue (the waiting room). Semaphores are embedded in it.
With multiple barbers, coordination aims at:

preventing several barbers from cutting hair of the same customer.
preventing from having only one busy barber while the others sleep all day long.


Why are aircraft piston engines are so low rpm lazy engines?

Question: I understand that the propeller speed should not be too much otherwise it will stall at the tip and be useless so higher rpm engine would be useless when we first think about it. However, we can put a single speed gearbox between the crankshaft and the propeller to reduce the speed of the propeller so that it will not stall at the tips. We can have an engine running at 6000 rpm making lots of power and through a 6:1 reduction gearbox the propeller will rotate at 1000 rpm and im guessing at that rpm the propeller tips wont stall. Why is this not done? Why are the aircraft engines so lazy low rpm engines with low power output? For example the 5 Liter GO-300 engine  makes a peak power of 175hp at 3200 rpm , what would be the downsides of putting a 4 Liter Porsche 911 GT3 flat 6 engine that makes 500hp at 8500 rpm and then through a reduction gearbox decrease the speed of the propeller so that the propeller tip wont stall? Also im giving the porsche engine as an example because that engine is also used in 24 hour races constantly and they are extremely reliable.
Comment: Running an engine for 24 hours isn't "extremely reliable" at all. An ordinary car engine goes for 5,000-7,500 hours without any internal maintenance. And then, when people's car engine stop, you normally don't have a crash or fatality.
Comment: Low RPM is good b/c it means less friction generated heat.  Engine life is largely a function of distance traveled by the piston rings. Low RPM means more flying time for a given distance of piston ring travel.  You want direct drive for the reasons Jan gives in his answer, and that means you generally relay on displacement, and get 1/2 hp per cubic inch in order to achieve a torque peak under 3000 rpm. An aircraft engine's environment is closer to an industrial engine.
Comment: @Dave Those links are nice thanks for sharing.
Comment: @user71659 These engines generally require full rebuild after around 100 hours not 24. The regular car engine you are talking about that lasts 7500 hours pretty much never sees the redline in its entire life. It makes no sense to compare a regular car engine that realistically never goes above 3000 rpm to this engine to say "its not reliable". This engine is constantly abused to extreme levels in that 100 hour interval. But yes now looking at O-300 it says interval is at 1200hr , so i guess reason why a high rpm high hp engine is not used is due to much more frequent rebuild interval and cost.
Comment: To add on to @JohnK the idea of small-displacement high-revving engines comes in a large part from obsolete European and Asian car taxes based on pure displacement. There have been examples of car engines brought to the US are modified to be slower and larger, and save fuel. Viscous drag from engine oil and moving parts scales to the square of velocity. As mentioned, it also affects wear, which is also compounded by the use of lighter oils to compensate for high speeds, but is hidden by European vehicles driving significantly less per year than the US.
Comment: [You absolutely can put a Porsche 911 motor in a plane](https://en.wikipedia.org/wiki/Porsche_PFM_3200) and it will [absolutely make a terrible plane](http://www.seqair.com/Other/PFM/PorschePFM.html)
Comment: There are really only three automotive based aircraft engines with a modest record of success; the VW Beetle engine, the Subaru EJ-22 4 cyl, and, wait for it... the Corvair. The Sub requires a reduction drive, but the core engine as an opposed design with cast-in-one-piece case and barrels, is extremely rigid and it seems to be able to handle extended high stress. The Corvair works very well direct drive, up to 3000 rpm where it will make close to 100 hp, when an extra support bearing is added for the propeller. Similar for the VW, although it has to spin up faster & uses smallish propellers.
Answer: A reduction gearbox is a non-trivial piece of fine machinery that needs to be maintained and can fail. And since reliability and low maintenance cost are important design goals for aircraft engines, especially engines for small aircraft, it makes sense to design the engine without need for a gearbox and just accept the need for a bigger cylinder volume for the same power.
But the newer deigns, like the Rotax or Austro Engines ones, all do have reduction gearbox. These designs are derived from automotive designs and those generally run at slightly higher speeds.
Note that the difference isn't that huge. Typical small aircraft propellers have maximum RPM 2,700, with maybe 2,400 RPM being usual cruise setting, and the automotive engines don't normally go over 4,500 RPM, with 3,000–4,000 being typical cruise speeds.
The main obstacle to newer engine designs for aircraft is the certification. While the engines themselves are pretty reliable these days, they are all electronically controlled these days and that adds failure points that all need to be carefully validated, and backup sources of electric power need to be provided and such, which is a huge effort. So instead a lot of light aircraft still use the older tried and tested simpler ungeared engines.
Side note: the tips of a propeller won't stall by spinning faster. Rather they will generate more drag, wasting power, and once the tips go supersonic (close enough to supersonic to start causing shock waves to form), vastly more drag, wasting even more power.
Comment: There's also torsional resonance issues, the bigg bugaboo for geared engines with few cylinders.  Molt Talyor, for his flying car that he certified in the early 50s using a Lyc O-320, used Flexidyne dry fluid couplings used in washing machines etc, a housing with a wavy plate filled with ball bearings, to provide the compliance in the  drive line to absorb resonant pulses. Rotax relies on rubber couplings and/or slip clutches, and careful tuning of the system.
Answer:
Why are aircraft piston engines so low rpm?

The fuel consumption of a typical aeronautical piston engine depends, all the rest being equal, only on the rotating speed rpm with a typical bell-shaped curve (source):

As visible in the previous plot, there's a range of rpm (more or less from 3'000 to 5'000) where the fuel consumption is minimised. The design goal of a gearbox is to supply the propeller with the needed rotating speed so that the engine's rpm remain inside that optimal range. This minimise not only the fuel consumption but also the engine's wear. Making the engine run at a higher rpm simply consumes more fuel plus requires a bigger and heavier gearbox.

I understand that the propeller speed should not be too much otherwise it will stall at the tip.

The limiting factor is the onset of transonic speeds on the tip which greatly increases aerodynamic drag and therefore the needed torque.


Vector representation of documents for text classification

Question: I'm looking for proper method of document embeddings. I know that doc2vec will give me the vector representations for given corpus, but how do I embed new documents? I need to train neural network that will classify text, but I have no idea how new documents should be embedded properly.
Answer: Not necessarily. Documents embeddings are constructions from (sub)word embeddings. Nowadays, you should always start from a pre-trained model. Please check tensorflow Hub or Hugging Face. Even without retraining, as long as your text is not too specific, the pre-trained encoder should capture enough relations.
Comment: Thank you, that is saving me!


Python Class __init__ Confirmation

Question: Im trying to understand Python Classes. I am a little confused around defining the __init__. If I have 4 functions created all taking various input variables. Do I have to assign each variable in the __init__?
 class Thing:
     def __init__(self, arguments, name, address, phone_number, other):
         self.arguments = arguments
         self.name = name
         self.address = address
         self.phone_number = phone_number
         self.other = other

     def First(self, name):
         print self.name

     def Arguments(self, arguments):
         print self.arguments

     def Address(self, address, phone_number):
         print self.address + str(self.phone_number)

     def Other(self, other):
         print self.other

The above is completely made up so please excuse its pointlessness (arguably its point is to illustrate my question so guess its not pointless).
No doubt im going to get loads of down marks for this question for some reason but I have been reading various books (Learning Python The Hard Way, Python For Beginners) and been reading various tutorials online but none of them actually confirm "You must add every variable in the init function". So any help understanding the __init__ a little better would be appreciated.
Answer: Firstly: The __init__() function is special in that it is called for you while creating a new instance of a class. Apart from that, it is a function like any other function, you can even call it manually if you want.
Then: You are free to do what you want with the parameters passed to a function. Often, the parameters passed to __init__() are stored inside the object (self) that is being initialized. Sometimes, they are used in other ways and the result then stored in self, like passing a hostname and using that to create a socket - you then only store the socket. You don't have to do anything with the parameters though, you can ignore them like you do in your First() function, which receives a parameter name which is ignored. Note that this parameter name and the similar attribute self.name are different things!
Notes:

It is uncommon to ignore parameters passed to __init__() though, just as it is uncommon to ignore parameters in general. In some cases, they are "reserved" so they can be used by derived classes but typically they are unintended (as with your First() function, I guess).
Check out PEP8, which is a style guide. Adhering to it will make it easier for others to read your code. E.g. First() should be first() instead.
Upgrade to Python 3. I don't think there's any excuse nowadays to learn Python 2 and littley excuse except maintenance to use it in general.
Answer: If the variable is logically connected to the object itself, it's good to set it in constructor:
class Student:

    def __init__(self, name):
        self.name = name

    def print_name(self):
        print(self.name)

If the variable is just a temporary parameter to some function, then, well, just pass it just as a parameter:
class Cafeteria:

    def __init__(self):
        pass # nothing

    def process(self, student_name):
        print(student_name + " got lunch")

In Python you don't have to declare all possible object attributes like you have to do in C++, C#, Java etc. I think it's still good idea to initialize them in constructor to some null value (None, 0), but it's not necessary. This is just fine:
class Cafeteria:

    def set_today_menu(self, menu):
        self.menu = menu

    def process(self, student_name):
        print(student_name + " got " + self.menu)

Comment: Thanks Messa, this along with @Ulrich's answer have been insightful. I appreciate helpful responses rather than ridicule and down marking for a change ^_^
Answer: You don't have to,  but to access them they need to set somewhere...you can also set defaults outside of any of the defs in a class if you want.
def Class:
    RandomVariable = 5
    def __init__(self, val):
        self.RandomVariable = val

Answer: This method is known as your initializer where you insatiate an object and then add attributes to it. A human object, if we were to create a class, may contain a name, age, and gender attributes all of which are bound to the object using the self pointer in the initializer. Also, an initializer may modify global variables as well. If you wanted to count the number of babies born, you would add to a global counter variable from our fictitious human class initializer.

Python Class __init__ Confirmation


Source for the act of completing Shas if every daf is distributed and completed individually by a group of people?

Question: There is an unsourced claim I am seeking to verify. There is a claim that, if every daf of a masechet (and, by extension, Shas) is learned by a group of people - through the means of every person being assigned a daf (or as many are needed for the entire volume to be finished in aggregate), it is equivalent to each person in that group who learned their assigned daf finishing that particular masechet (and, by extension, Shas, if all masechtot have been learned). I am unable to find a source for this claim.
Answer: The source is the Sdei Chemed Mareches mem:198 on communal syium hashas.
Text:
Comment: He does write mashecet,but the idea is that you are finishing as one unit so you are all like one. I think a daf would fit in same category.
Comment: Thank you. I'm not fluent in the text but does the Sdei Chemes davka mean each person must finish a Masechet ? His text reads - ״ומחלקים הש״ס בין כמה בני אדם שכל אחד לוקח מסכתא אחת״  . If this is the case, then perhaps just for splitting the masechtot there is a source, but not a further division of dafs.


Can i use a pci express 1.0 card in a pci express 2.0 x16 slot?

Question: I am runing out of sata connections and need to expand using a pci card, however, i only have a pci express 2.0 slot available, will a pcie 1.0 (pci express 1.0) expansion card work in a pci express 2.0 slot?
Comment: I have a PCIe 2.0 card in a PCIe 1.0 slot and it works fine.  So, the slot - by that example - is *forwards compatible*: newer cards work in older slots.  I don't see any reason why not that they aren't *backwards compatible* as well: older cards work in newer slots.  You may not be able to get the maximum performance you could have out of the combination but it should still work.
Answer: TL;DR;  Yes, you can.
Slightly longer:
PCI express is backward compatible. You can run a PCI-e version 1 device is a PCI-e version 2 slot. You will only get PCI-e version 1 speeds though (which is up to 2.5 megabit per lane).
As to the X16:
You can run any card in any slot into which it fits.  It will use the maximum available combination of lanes.
Answer: It depends from your host: the compatibility is not really complete. For example, I tried an old network card on a DELL PowerEdge T30, but it did not work. Finally I found the problem was at the PCIe level. The user manual of T30 states NOTE: All the PCIe slots support Generation 2 and 3 PCIe expansion cards. As you see, there is no mention of PCIe 1.0 nor 1.1.
And, in my case, the network card box only mentioned require a PCIe compatible bus. I had to look for the chipset datasheet in order to find the PCIe version required.


iPhone - Where is the brightness/backlight level setting in the file system?

Question: I have an iPhone that was dropped in water. Once the backlight level goes below a certain point, the screen is completely black/useless. I need to go in iFile or some other file system browsing software to set the brightness level to 80% or something high. I've looked around and found the backlight level for SB Settings but I'm not sure if that will work. Anybody know where that setting is?
Comment: Well I got the phone working again. I found the "SBBacklightLevel2" property in "com.apple.springboard.plist". I set it to .9, rebooted the phone and the screen worked. I'd still like to know where the system brightness property is though. THanks!
Comment: That's the file and property that you're looking for. I saw this question as was about to post exactly what you had already found, but then I saw your comment.
Comment: Oh ok, for some reason I was thinking the property I found was referring to a SBSettings property and not for the system. Thanks!
Comment: No problem! (In fact, most SBSettings toggles directly modify values in system `.plist`'s such as this.)
Answer: User > Library > Preferences. The property is called "SBBacklightLevel2" in the com.apple.springboard.plist file.
Thanks @Andrew Larsson for the confirmation of this.


SVT algorithm and the value of tau.

Question: SVT stands for singular value thresholding. It is an algorithm used in "matrix  completion" problems. see http://svt.stanford.edu/ for basics.
What is the meaning of "for large values of [tau]..." without actually stating what a "large" value is relative to? I often see such references in mathematical literature and it leaves me puzzled.
Thanks
Answer: Referring to (P3) on your link:
$$\min_{X \in C} \tau \lVert X \rVert_{*} + \frac{1}{2} \lVert X \rVert_{F}^2$$
A sufficiently large value of $\tau$ would be any value that causes the nucular norm term to be significantly larger than the Frobenius norm term such that omitting the Frobenius norm term will not result in a significantly different result relative to the result obtained from the sum of the nuclear and Frobenius norm terms.
Comment: Ah, Thank you - that was easy to understand and seems so relatively more obvious now.

SVT algorithm and the value of tau.


Maximum current in MIL-spec D38999 circular connectors

Question:
Talking about d38999, does a current/contact heat diagram exist?
What a normal d38999 contact temperature can reach before getting damaged?
Datasheet of various vendor display a nominal ampacity that I suppose is referring to a steady state current but I am not sure about it.
Comment: Power-BreechTM connectors are rated up to 900 amps. These shell size 33 – 57 solutions utilize MIL--DTL--38999 Series IV derived coupling mechanisms.  Ask supplier for max temp rise of the gold plated contacts.
Answer: Amphenol rate max current with ambient temperature which combined reaches the same contact temperature for excessive corrosive stress and reduced MTBF.
E.g. https://www.amphenol-aerospace.com/resources/literature/view/38999-connectors-with-power-contacts
However you must request validation test reports to ensure this also includes aging and contact stress from such contaminants as space dust and gamma radiation.  Arhennius law dictates acceleating failure rates with temp rise and loss of rated margin with the application to compute FIT rates.  I would expect field experience of such failure rates must exists from Mil-Std 883 data.


Eclipse/LibGDXgame doesn't load textures

Question: Our LibGDX project doesn't load textures after building on PC/Android but when it's built from Eclipse using  Ctrl + F11 (Run/Debug) everything is fine. What could be causing that?
Comment: Typically you should include error messages for this type of situation. In fact, had you looked at the error messages, you'd probably find that they were errors about not being able to find the textures and you might have been able to solve this yourself. Simple troubleshooting is always easier than posting to the web and waiting for a response.
Answer: You are probably running your application from different working directories. Check the project settings in Eclipse and look for "Debug Directory" or similar. If you run you program from withing that same directory outside Eclipse it will probably work fine.


Can a daughter give zakat to her mother ...?

Question: if a mother is financial week and other side a daughter is financially strong then is this right to support her mother and give her money as zakat, because zakat start from your family.is this right or not....?
Answer: If your mother is poor, then it is obligatory for you to spend on her anyways, you can not combine and eliminate this obligation with Zakat.  Zakat can not be given to parents or children, but can be given to brothers and sisters and other relatives on whom it is not obligatory to spend upon.
https://islamqa.info/en/answers/81122/it-is-not-permissible-to-give-zakaah-to-one-on-whom-you-are-obliged-to-spend
Answer: We have people and relatives who are poor; For example, if our parents are poor, or some parents ask and say that our children and grandchildren are poor, can we pay zakat al-fitr to these people?
These people are called obligatory alimony, that is, they are people who, if they are poor, we have to provide for them in terms of livelihood and expenses.
According to all the authorities of imitation, we cannot pay our zakat al-fitr to the people who are our obligatory alimony; That is, if our parents or children are poor, we can not give zakat al-fitr to these people, it does not matter if this single girl and boy are married, live with their parents or have an independent life, live in another city, no One of these cases is no different in paying zakat al-fitr.
If these people are poor and we have the financial means, it is obligatory to provide them financially; But they cannot be helped with the money of zakat al-fitr and atonement, but there is no problem in paying zakat al-fitr to aunts, uncles, brothers and sisters, brides and grooms.
Ref: https://www.ana.press/news/385556/


What is the d3.js v4.0 equivalent for d3.scale.category10()?

Question: I'm trying to learn d3 with the Interactive Web Visualization book, but a lot has changed with version 4.0. One thing I really can't figure out is if there is an equivalent for d3.scale.category10() to get an easy mapping to colors. Is there something like that in the new version or do we need to use math.random and code up something ourselves?
Answer: Instead of
d3.scale.category10()

use
d3.scaleOrdinal(d3.schemeCategory10);

Create a color scale like this:
var color = d3.scaleOrdinal(d3.schemeCategory10);

use the color like this in the code same as in V3:
svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 100)
.attr("height", 100)
.style("fill", color(3))

read here
Reference here
working code here
Comment: This seems to be a solution, to what I was expecting: `color = d3.scaleOrdinal(d3.schemeCategory10).domain(d3.range(0, 9));`
Comment: Thanks! I was just scrolling through the change document and finally found the explanation.
Comment: No matter what number you supply to `color()`, in your working code, the output is always blue and orange - is that the expected behaviour? What if I want purple?
Comment: ` in your working code, the output is always blue and orange - is that the expected behaviour?` No thats not expected i am getting green here https://plnkr.co/edit/2DzxaDg1SjidDkz5v2P4?p=preview
Answer: A straight-forward solution is to use the following color scales in version-4 of d3.js :
var colorScale_1 = d3.schemeCategory10;
var colorScale_2 = schemeCategory20;
var colorScale_3 = d3.schemeCategory20b;
var colorScale_4 = d3.schemeCategory20c;

colorScale_1, colorScale_2, colorScale_3, colorScale_4 are the arrays of different colors. So, you can use their different indices to fill the shape. For example
svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 100)
.attr("height", 100)
.style("fill", colorScale_1[2])

For reference, take a look here: http://bl.ocks.org/emmasaunders/f4902478bcfa411c77a412c02087bed4
Hope that helps.


How much time needed to rebuild your body after long pause?

Question: Let's say some average person was doing bodybuilding for a year or so. He gained some muscles, increased his weights in all exercises from 1.5 to 3 times. Then he had to do a break for a half a year. After this period, he sees that his muscles are mostly gone and probably the exercise weights are also lower. How long after this break will it take him to get back to the previously achieved results? Another year or less? May be there is some formula to calculate this or may be someone had this kind of experience that he can share?
Comment: Without injury, it shouldn't take him as long as the first time. The body will readily adapt the second time than during the first time *(I think it's called muscle memory)*
Answer: It shouldn't take as long as the first time getting into it. The benefit you have now is that muscle memory is there. In essence, your muscles have adapted and can now "remember" the movement to perform the exercises you once performed. So when you go back to it, that whole element of learning the movement is gone. This will hasten your results.
However, intensity is important and is solely up to the individual. If you're going back into weightlifting, and your intensity is not there, you're not going to reap the rewards of the muscle memory.
I'm sure some people will debate this, but keeping your diet in check is also going to be a huge attribute to your success. Depending on your goals, to lose weight for example, start with a 500 calorie deficit. Use a tracker like myfitnesspal - this will ensure that you don't go overboard on your caloric intake. Calorie tracking + intense workouts + muscle memory = results.
Previously achieved results are subjective, I noticed after a 6 month break, I came back to the gym doing 2 compound lifts (i.e. bench + deadlift, or squat + pull up) per workout with accessory exercises....I got my results back and was stronger within 1 month of 3 workouts per week. Again, it's about intensity.
Hope this helps! Best of luck!
Comment: This. Also, you will be able to make larger incremental increases in weight than the first time. Just keep the increments going and don't miss workouts and you'll get to within 20% of previous max pretty fast (assuming you were beginning/intermediate - advanced bodybuilding is a whole other world).


How is "Humans need not apply" a correct sentence?

Question: I saw this expression as a title of a short documentary on Youtube and was wondering, because it makes no sense to me grammatically.
Comment: Can you explain why you think it's ungrammatical? Seems perfectly standard to me.
Comment: @Catija never saw that construction before, the way I would say it  "Humans don't need to apply"
Comment: I suppose that you could consider it a form of shorthand. The context for this text is generally on a sign or placard, so brevity is preferred.
Answer: It is a correct sentence.  Compare it to "You need not apply for this job.".  It's the same thing, but with the "for this job" implied.
Historically this phrase was used in a context (classified ad, window of a shop) that made it clear what the undesired group was not to apply for.  So a shop might have had a sign up saying "Irish need not apply".


Why do many Arabic letters look exactly like other letters except for dots, yet have no similarity in sound?

Question: Why do many Arabic letters look exactly like other letters except for dots, yet have no similarity in sound?
Examples:
Answer: The first thing to understand is that the Arabic alphabet derives from the form of the Aramaic alphabet used by the Nabataeans, itself derived from the Phoenician alphabet, and ultimately Egyptian Hieroglyphs.
Comparing the Aramaic alphabet (I'm specifically using the Hebrew form of it here, because Nabataean unicode isn't, and Hebrew is generally better known and supported than Syriac) in the traditional abjadi order with the Arabic alphabet we see the following Arabic letters missing:

Ṯāʾ ث
Ḫāʾ خ
Ḏāl ذ
Ḍād ض
Ẓāʾ ظ
Ġayn غ
Hamzah ء

The first six correspond to phonemes lost in Aramaic:

Ṯāʾ ث merged with tāʾ ت (with the pronunciation depending on position)
Ḫāʾ خ merged with ḥāʾ ح in Phoenician (they remained phonemically
distinct in Aramaic for a period, but this wasn't represented in
writing)
Ḏāl ذ merged with dāl د (with the pronunciation depending
on position)
Ḍād ض merged with ṣād ص in Phoenician (in Aramaic it remained phonemically distinct for a while, but was represented with and eventually merged into ʿē ע)
Ẓāʾ ظ merged with ṭāʾ ط (it remained phonemically distinct for a while in Old Aramaic)
Ġayn غ merged with ʿayn ع in Phoenician (they remained phonemically
distinct in Aramaic for a period, but this wasn't represented in
writing)

In these cases, there is (or was) some similarity in sound, although it may not be clear comparing the modern Arabic sounds of these letters. In particular, whilst most of these differ only in a single feature even today, ḍād ض ṣād ص are generally reconstructed as something like *tɬ' *ts' in the earliest stages of Semitic (when the merger occurred in Phoenician), whilst ẓāʾ ظ ṭāʾ ط are generally reconstructed as something like *tθ' *t' at that same stage, meaning they also differed only by a single feature ([+lateral] in the case of ḍād ض ṣād ص, and [+spirant] in the case of *tθ' *t')
Originally, Arabic writers mostly didn't distinguish between these letters (all letters were written without dots of any kind). This sort of underspecification is not very unusual cross-linguistically (look at English not distinguishing θ & ð in spelling, with both being <th>).
Later, people wanted to be able to ensure that they were reciting the Qurʾān with the correct pronunciation, and not accidentally reading dāl where they should be reading ḏāl etc. Because of this the system of dots developed* to disambiguate between the multiple phonemes represented by each letter. In each case, the Aramaic pronunciation does not receive a dot, and the pronunciation particular to Arabic does (in this respect, we can compare to Modern Hebrew use of geresh).
Prior to the system of dots, Arabic had also used šīn ש for both the sounds now written sīn س and šīn ش (this is likely due to the complicated correspondence between sibilants between Arabic and Aramaic, but that's a topic for another question), and Aramaic semkaṯ ס was not used. With the system of dots, sīn س (which represents the same sound) was given its position in the abjadi order. In this instance however, note that sīn س is the letter without the dot, despite the fact that Aramaic šīn ש (from which both letters derive) had the sound of šīn ش.
The other big category of dot distinctions arose because the Arabic alphabet descends from an especially calligraphic form of the Nabataean script, and this resulted in a bunch of other letters being written the same (or very similarly), despite being pronounced in multiple ways even in Aramaic.

Bāʾ ب and tāʾ ت and nūn ن
Jīm ج and ḥāʾ ح
Fāʾ ف and qāf ق
Zāy ز and rāʾ ر

Here the correspondences have no phonetic basis, and occurred purely due to visual similarity in earlier stages.
When dots were introduced to disambiguate the letters for Arabic phonemes not present in Aramaic, they were also introduced to disambiguate these letters.
Lastly, there is hamzah ء. This one is complicated, and appears to have developed as a result of dialect mixing within Arabic between Old Hejazi (the dialect represented in the Consonantal Text of the Qur'an), which had lost the sound originally represented by ʾalif ا in many or most positions, and started to use the letter to mark long vowels, including those without an etymological ʾalif ا, and other varieties that had preserved them. Thus it became necessary to indicate which instances of ʾalif ا should actually be pronounced, and this was indicated with a small copy of the letter ʿayn ع (which later developed into the modern hamzah ء).
Marijn van Putten is an expert on the development of the Arabic alphabet, especially in relation to the Quranic text, and has written a much more in-depth explanation here (in particular discussing different stages and scripts within Arabic).
* This is the common narrative, but as van Putten notes, doesn't match the historical evidence perfectly. It seems that the system of dots actually predates the standardisation of the Quranic text. It may still have provided motivation behind the system becoming near universal.
N.b. the diagram in the question is in Hijāʾī order, and uses a non-standard Romanisation of Arabic. I have generally used more typical "scholarly" Romanisations of Arabic, but always included the letter in the original script as well to avoid confusion. As is fairly common, I have in many instances used the name of the modern Arabic letter to stand for the Arabic phoneme and its antecedents. I hope it is sufficiently clear when I have done so.


Can't save proxy settings after installing AdBlock Plus

Question: I installed the AdBlock Plus app and I need to modify the proxy settings, but the "Save" button is disabled and I cannot do anything. Could you please help me out? I have an LG P970 running Android 4.0 ICS.

Screenshot (click image for larger variant)
Comment: I don't see any proxy settings in AdBlock Plus. Are you referring to the WiFi proxy settings, or something else?
Comment: AdBlock Plus software depends on root access to modify files. Do you have this? Without it, modifications to internal files are prevented.
Comment: The screenshot suggests so. Am I assuming correctly that you try to set ABP as system-wide proxy via Android's native network settings? I might be wrong here as "Proxy settings" in your screenshot is still set to "None". And no, I have no idea whether that would be possible even ;)
Comment: Change the proxy settings to manual and fill the settings and it will enable
Answer: Its not about adblock i guess.
Its is just that you have to give proxy server ip instead of hostname ( it looks something like 10.X.X.X ). it will enable save button.
So you put that ip in proxy hostname and save button will be enabled.
( It worked for me in my android)
Answer: I have a LG G Pad and had the same problem. All I needed to do was type the correct WiFi password again and the Save button was became enabled, allowing me to set my manual proxy settings for Adblock Plus.
Answer: I just did it, according to ADP instructions.
Tap on app, which should have an error message about your proxy settings.
When you find your network, hold it until Modify Network appears.

Show advanced options (need tablet in vertical position to see this).
  Look for proxy settings and set to Manual.
  Proxy settings should be localhost.
  Set port to 2020.
  On my page, I had to fill in every line, in order for the save button to appear.
  Hit Save.
Answer: On some devices, the Save button will be grayed out until you re-type your Wi-Fi password.
Answer: I also had the same issue but not long after I figured the proxy number given was a mirror image I mean the number was not actually typed but instead you had to type the given number in the box. and change the proxy host to localhost but after this you will have an issue with chrome  connecting to the proxy  server. the solution for me to this was I went to settings in chrome and went to advanced, bandwidth and management and selected reduce data usage and enable it.
Answer: Simply put do this....
host name : LocalHost
Proxy: 2020
Proxy reason: adblock.com
Proxy setting DHC25 (or watever just not static)
Click save and re-enter ur wifi password and ur done


Is there a triangle like this?

Question: This is my question that I posted at https://mathematica.stackexchange.com/questions/32338/is-there-a-triangle-like-this "I want to find the numbers $a$, $b$, $c$, $d$ of the function $y = \dfrac{a x + b}{c x + d}$ so that the triangle $ABC$ with three points  $A$, $B$, $C$  have integer coordinates and lies on the graph of the given function, then the centroid of the triangle $ABC$ (have also integer coordinates) is also lies on the graph". The anserw at that site is yes. But, he said "I think I was just lucky to get an integer solution since I haven't imposed all the constraints".
Answer: My student found a function $y = \dfrac{93 x + 6}{x+2}$. Then, $A(-6,138)$, $B(8,75)$, $C(-62,96)$ and centroid $G(20,103)$.

Is there a triangle like this?


D700 clipping all my images

Question: I have had this D700 for 6 years.  Now it is clipping the top of all my images.  please see the image below
Comment: Is this consistent with every different lens that you have?
Comment: Do you hold the camera upside down when shooting?
Answer: Interesting... Try taking the lens off the body and taking a time exposure. Look into the camera body through the lens mount. See if the sensor is 'clear' with nothing projecting in front of it. Since the issue is at the top of the frame the blockage will be at the bottom of the sensor. I think the autofocus system is mounted in the bottom of the mirror box, and there may be something going on there... If you -do- see something, you can try to gently nudge it to see if it unsticks, but if it were mine I'd probably just send it back to Nikon for repairs.
Comment: OMG!  You are a genius!  I gently nudged the bottom of the mirror box and this piece in the shape of the clipping became unstuck.   The problem is resolved.  Thank you soon much!
Comment: You're welcome! Please mark my answer as the correct one...
Comment: I went to  use my D700 to take halloween pics and now it  doesn't autofocus   and in manual focus the shutter doesn't release consistently.  I tried different lenses with the same problem.  With the lens off the body, there isnt a problem with the shutter.
Comment: Time to send it in for repairs...
Answer: I don't know, but my guess is that the mirror is not quite raising all the way. What else could it be?  You can remove the lens, and watch the mirror as you press the shutter button, and probably can see it not quite raising all the way.  Sounds like a repair is necessary.
Comment: The mirror is at the 'bottom' of the inverted image as it is projected onto the sensor. If the mirror were hanging down slightly it would cast a shadow at the bottom of the photo (unless the camera is being held upside down when the photo was taken). For something to shade the top of the photo it would be in the bottom of the light box when the camera is held upright.

D700 clipping all my images


Is one required to convert any database used with previous SQL server version when using with newer one i.e 2012

Question: I am setting up a dev environment on a my local PC, however when deployed the project I am working on will be using SQL Server 2008. Could I install SQL server express 2012 for local testing and not have to convert the older version database(s) for use with it? Which if I recall correctly would then not allow me to use them with SQL server 2008 ?
Answer: You can restore a database backup from an older version (say 2008) into a newer one (2012), but you can't go back. You can not restore a backup from 2012 into 2008.
The conversion from the 2008 backup during the restore in 2012 happens automatically and you can not prevent it.
The compatibility level is something else and doesn't help you here.
If you would like to use 2012 as a local dev-database, you need to apply your local changes to the production database in some other way. You could script all your changes manually or use schema or data comparison tools to sync the two databases.
Comment: Well, given that in the real world hardly anyone works on a copy of the production database for production (because this CHANGES during development) that gets copied back to the production after development (overwriting the changes done in production in the mean time, delta scripts etc. are a standard of operation anyway.
Comment: What @TomTom said.  You should have a schema upgrade script for any changes that need to be made to bring the production DB to functional parity with the dev DB, but other than that you **can*** use SQL Server Express 2012 for development.  Best practices would dictate not doing so however: You ***SHOULD*** develop on a system as close to production as possible, and using the same DB server release is an important aspect of that...
Answer: If it's a simple database and not using any services which are only available in say Developer or Enterprise version of Microsoft SQL Server then you can definitely use it in 2012 Express version of SQL Server.
Here's the comparison of what version could do what... http://msdn.microsoft.com/en-us/library/cc645993.aspx
Comment: I think you may have missed the point of the question.


Cribbage Tournament play

Question: Two player competition. Player one miscounted her hand points, and moved her peg. As player two was counting her hand points, player one realized her error and wanted to add the discovered points. Was it too late? Did player two have a valid objection ? ( No muggins)
Answer: Quoting from the American Cribbage Congress Official Rules:

8.3 Pegging Incorrectly to the Player's Disadvantage
If the wrong number of points is pegged to the pegger's disadvantage (ie underpegging a forward score or overpegging a backward penalty), a correction is not permitted after the player's fingers are removed from the peg.

However, these are tournament rules. If you are choosing to not play Muggins, I recommend that all irregularities be treated more generously than in these rules. A good guideline for this might be:
<code>If it is reasonably possible to restore the correct game state,
then such corrections are allowed. Usually this means "before the
next hand has been commenced by initiating the deal for it; and
before the game has ended by a correct peg into the final hole."
</code>
Either agree to play cut-throat, with muggins; or play generously all round.
Finally - you claim this to be "Tournament Play". If so, why are there no judges appointed to adjudicate according to the official tournament rules? Your claim there seems dubious.

Cribbage Tournament play