Dialog Fragment crash when phone system language change?

Question: I have a DialogFragment to display a list of options. So, I try to do several tests on my apps. I found a problem when changing phone system language in the phone settings while beforehand the DialogFragment is opening in my apps then go back into my apps. It caused a null pointer exception on the DialogFragment.
Basically, the repro is like this :

Opening an activity
The activity will open DialogFragment after some user actions
The user exits the application and enters the phone setup
The user changes the phone system language and then go back to the apps
The DialogFragment still appears, but not in a proper format.
The user presses the back button and the apps will crash automatically.

I've been trying several examples and solutions, but still the apps will crash after the repro stated above.
What should I do to tell the activity to close the DialogFragment when the user changes the phone system language? Do I need to put Flags? but How?
Here's the log :
<code>java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.MainDialogFragment$MainDialogListener.onDestroyMainDialogFragment()' on a null object reference
        at com.example.MainDialogFragment.onDestroy(MainDialogFragment.java:152)
</code>
Before changing the phone system language :

After changing the phone system language and go back to the apps, the dialogfragment still appears, then the user presses the back button :

My Line 152 is :
<code>@Override
public void onDestroy() {
    myMainListener.onDestroyMainDialogFragment();
    myMainListener = null;
    super.onDestroy();
}
</code>
Here's my full code :
https://codeshare.io/DZZRWO
Thanks in any advance
Comment: So why does your DialogFragment not appear 'in the proper format'. Why does your app crash when you press the back button? Your first priority should be to fix those problems, but you've included no details on your DialogFragment code or the stack trace of the crash you're experiencing.
Comment: @ianhanniballake
I've edited my description , please kindly take a look, Thank you
Comment: So where are you populating your list of options (and why isn't doesn't that list exist after process death and recreation)? How are you setting up your `myMainListener` (and why isn't that set correctly after process death and recreation)? Have you done any testing with the "Don't keep activities" developer option, which is specifically available to test these cases?
Comment: @ianhanniballake I have set a listener both when the fragment is created and when the fragment is already in the onDestroy stage. I think that the flow becomes like this: Activity Open -> OnCreateDialog -> Dialog appears -> Change Phone Language Settings -> previous init disappeared -> recreate fragment -> but becomes null.

Please take a look at my full code : https://codeshare.io/DZZRWO
Answer: I've found several solutions that I thought would be fit to my case :

Checking and detecting whether the phone system settings have changed, then do something to dismiss the dialog fragment.
adding

setRetainInstance(true)

inside the method onCreateDialog / onStart / setDialogContent (Depends on the case)


How to Simplify $\prod_{k=1}^{p-1}k^{2k-p-1}$

Question: I've been trying to complete a problem recently, and have been bashing my head against this particular product
$$Q(p)=\prod_{k=1}^{p-1}k^{2k-p-1}$$
The problem states that for any prime $p$, $Q(p)\ \epsilon\ \mathbb{N}$
And while the "$-p-1$" can be simplified into $\frac{1}{((p-1)!)^{p+1}}$, I can't at all make progress with the part that is $k^{2k}$. All it gives me is this numerator:
$$1^2\cdot 2^4\cdot 3^6\cdot 4^8\cdots (p-1)^{2(p-1)}$$
Is there any nice way to simplify this expression? My previous attempts yielded far-too-convenient answers that turned out to be wrong. They all really considered the prime factors of each and trying to leverage the fact that $\nexists s \in \{2\ldots (p-1)\}\quad s \mid p$.
Comment: Your product needs motivation. Where does it come from, what larger problem would be aided by knowing your product, etc.
Comment: *Mathematica* gives:  $$A^2 \Gamma (p)^{-p-1} e^{2 \zeta ^{(1,0)}(-1,p)-\frac{1}{6}}$$, which involves the gamma, zeta, and Gleisher functions... so this is rather difficult!
Comment: @WinterSand Welcome to Math SE. FYI, using [Approach0](https://approach0.xyz/search/?q=OR%20content%3A%24%5Cprod_%7Bk%3D1%7D%5E%7Bp-1%7Dk%5E%7B2k-p-1%7D%24&p=1), I found the somewhat related [Proofs of identity for product of binomial coefficients](/q/964267), with this asking about $\prod_{k=1}^{n-1}\binom{n-1}{k}=\prod_{k=1}^{n-1}k^{2k-n}$, but where the powers on the RHS are $1$ larger than what you're dealing with.
Comment: @DavidG.Stork. Just for the fun : make $p=10$ and evaluate the result. What do we do with the "small" imaginary part ? Cheers :-)
Answer: I do not think there is a simple closed form. However, you can express it using the $K$-function or the Barnes $G$-function ($+$ the gamma function):
$$
\prod\limits_{k = 1}^{p - 1} {k^{2k - p - 1} }  = \frac{1}{{(\Gamma (p))^{p + 1} }}\left( {\prod\limits_{k = 1}^{p - 1} {k^k } } \right)^2  = \frac{{K^2 (p)}}{{(\Gamma (p))^{p + 1} }} = \frac{{(\Gamma (p))^{p - 3} }}{{G^2 (p)}} = \frac{{(\Gamma (p))^{p - 1} }}{{G^2 (p + 1)}}.
$$


Get handle of the running instance of an app

Question: In my program I'm checking if an instance of the app is already running using mutex.
Now I would like to know how I could get an handle on the already running instance of the app to bring it to front.
Answer: You could use FindWindow to get the handle of the window and the SetWindowPos to bring it to the front.
Comment: Yeah bu the Window name can change depending on many parameters that the other instance hasn't ...
Comment: That is true. If you know the window class will be unique the you can use FindWindow(szClassName, NULL) to match all window names.
Comment: I managed to make it work! The main problem was that I didn't know the name of the class! I used a tool to determine it and then it's working well! (http://www.codeproject.com/Articles/34981/FindWindow)


Vhost access control

Question: How do I make it that only a certain address can access one of my vhosts?
I have tried:
<VirtualHost *:80>
    DocumentRoot "C:\Web Server\phpmyadmin"
    ServerName localhost

    <Directory />
    Require all granted
    Require ip 192.168.0.10
    </Directory>

    # Other directives here
</VirtualHost>

And:

    DocumentRoot "C:\Web Server\phpmyadmin"
    ServerName localhost
<Directory />
<RequireAll>
Require all granted
Require ip 192.168.0.10
</RequireAll>
</Directory>

# Other directives here

But Apache refuses to start.
Answer: Once I did try the same via the vhost configuration and failed because of dependencies to other apache configuration files. I ended up using the .htaccess file to restrict access to only my IP - it worked in all scenarios I had until now:
Sample htaccess configuration:
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.php
RewriteCond %{REMOTE_ADDR} !=126.96.36.199
RewriteRule ^.*$ /maintenance.php [R=302,L]

It will redirect any user, whose IP is not 184.108.40.206 to the maintenance.php file, where you can leave a message to the users that access is blocked.
I give you this example because I saw that the question is also tagged with ".htaccess".
Comment: In your specific case, you should not use the 302 status code, but [503](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4).
Answer: This should do the trick:
<VirtualHost *:80>
  DocumentRoot /var/www/test
  <Directory /var/www/test>
    Order deny,allow
    Deny from all
    Allow from <IP>
  </Directory>
</VirtualHost>

Update in 2.4 use:
<Directory /var/www/test>
    Require ip <IP>
</Directory>

Comment: I forgot to mention, I am using Apache 2.4.
Comment: Thanks, but even if I allow my IP it still gives me forbidden, and won't let anything connect to it now.

Vhost access control


Use LG UltraFine 4K with PS4 Pro (And probably Xbox One X)

Question: I'm interested in getting one of these displays (21.5 inch 4k variant) to replace my old 1440p one. I have also pre-ordered an Xbox One X and would like to know if it's gonna work with the display.
As the Xbox One X has barely started shipping I'm not expecting people to have tested this configuration yet but has anyone tried to get the PS4 Pro working with one of these? If it works with the PS4 Pro (through an adapter of course) without performance hits then it should already work with Xbox X.
Answer: I see no reason for it not to work is just a monitor, as long as you have the proper adaptor you will be fine.
(4k in a 21.5" display is a bit too much thou, there is no point in processing extra pixels that you can barely see, I would suggest 24" or 27" at least)
edit
there is some discussion here:https://www.reddit.com/r/apple/comments/5fan7e/lg_ultrafine_4k_compatible_with_windows_10_on_a_pc/
Basically its a usb type c monitor. even being designer thinking in Apple products it still has to respect the protocol. You just need to make sure to get the right cable and the right adaptor. (not every cable or adaptor supports 4k)
Plus apparently some feature such as the light sensor seem not to work in windows 10 because there are no drivers for it.
Comment: this is a possible adaptor https://www.currys.co.uk/gbuk/phones-broadband-and-sat-nav/mobile-phones-and-accessories/mobile-accessories/sandstrom-usb-c-to-hdmi-adapter-10156292-pdt.html?istCompanyId=bec25c7e-cbcd-460d-81d5-a25372d2e3d7&istItemId=xmttpalwlw&istBid=tztx&srcid=198&cmpid=ppc~gg~1022%20(PLA)%20PC%20COMPONENTS%20-%20Adaptive~1022%20(PLA)%20PC%20COMPONENTS%20-%20Adaptive%20ad%20group~Exact&mctag=gg_goog_7904&kwid=GOOGLE&device=c&ds_kids=92700027890037021&PLA=1&tgtid=1022%20(PLA)%20PC%20COMPONENTS%20-%20Adaptive&gclid=EAIaIQobChMIvtiHy5ax1wIViBbTCh30WA4MEAQYBSABEgI0ffD_BwE&gclsrc=aw.ds
Comment: Thanks for the link but because it's an Apple product and the brand isn't really known for cross-compatibility, I wan't to see a working example beforehand. 4k in 21.5" gives a very decent dpi which will help things (especially text) look crisp and I appreciate that as I'm a developer
Comment: there is some info online https://www.reddit.com/r/apple/comments/5fan7e/lg_ultrafine_4k_compatible_with_windows_10_on_a_pc/
Comment: I agree with your answer, but 4k in a small monitor does have its advantages. I have a 17" laptop with a 4k screen (I didn't need the 4k but on discount it was literally cheaper than its 1080p brother), and I like the finer detail you can get. Not so much from games (graphics can't support 4k), but working with the computer on a day to day basis is nice in 4k.
Comment: @RapazAtrevido seems it's not likely to work, but I still like to hear someone say "I tried it on PS4 Pro/Xbox One X and it didn't/did work".
Answer: I can confirm Ultrafine 21.5 monitor is not working with ps4 pro via typec-hdmi adapter from Apple https://www.apple.com/shop/product/MJ1K2AM/A/usb-c-digital-av-multiport-adapter?fnode=8b
It looks like adapter only works in one side if we connect external monitor via hdmi-hdmi cable but doesn't in opposite site if we put adapter to monitor(ultrafine) and connect HDMI-to-HDMI cable from PS4.
Probably that can works with typeC-to-Hdmi cable without adapters, but really not sure, and not ready to buy cable additionally.
Edit: based on https://www.reddit.com/r/apple/comments/7z17jq/connect_lg_ultrafine_display_4k5k_to_a_ps4_or/ it doesn't work even via typeC-to-HDMI cable.


How do I make all vowels in the second half of a string uppercase?

Question: I am trying to make all vowels in the second half of a string uppercase. This is what I did so far, I can't seem to get the result I want.
#Ask user for word
word = str(input("Please enter a word: "))

#Count word length
wordLen = len(word)

#Count half of word length
halfWordLen = int (wordLen/2)

#Obtain 1st and 2nd half of the word
firstHalf = word[:halfWordLen]
secondHalf = word[halfWordLen:]

#Determine vowels
vowels = set(['a','e','i','o','u'])

#Iterate through 2nd half to find vowel.
#Then, uppercase the vowels, and display new word.
for char in secondHalf:
    if char in vowels:
        newWord = firstHalf + secondHalf.replace(char,(char.upper()))
        print ("The new word is: ",newWord)

Results:
Please enter a word: abrasion
The new word is:  abrasIon
The new word is:  abrasiOn

It's supposed to be:
Please enter a word: abrasion
The new word is:  abrasIOn

Answer: There are two issues with your code. First, when you are replacing the vowel in your second half, you are only doing it temporarily. You need to perform that operation in a separate line and save it in the second half variable.
Also, you are printing the your temporary result each time you go through the loop. If you only want it to only print once, just decrease the level of indent so that it is outside the loop. Here is how I would restructure it.
for char in secondHalf:
    if char in vowels:
        secondHalf = secondHalf.replace(char,(char.upper()))
newWord = firstHalf + secondHalf
print ("The new word is: ",newWord)


How to select certain indices from a list? (i.e. the 1st, 6th and 13th value)

Question: I have an enumerate for loop inside another enumerate loop and I want to use certain items from the inner list. I thought the following:
list1 = ['a','b','c','d','e'],['one','two','three','four','five'],['1','2','3','4','5']

for number, list in enumerate(list1):
    for num, item in enumerate(list[0, 1, 4]):
    print item

would print out:
a
b
e
one
two
five
1
2
5

But instead I get the error TypeError: list indices must be integers, not tuple. I know I can select a range using list1[0:5] for example so I assumed I could explicitly select items as well.
Can anyone explain how to achieve this print out?
Comment: For me, your question is not clear. The title is different from the content. Also, are you sure you did not make a typo in `list1`?
Answer: The error is in the second loop:
for num, item in enumerate(list[0, 1, 4]):

What you have written - list[1, 2, 5] was wrong in two accounts - list() is a reserved keyword you reassigned in the previous loop (not critical, but you shouldn't do it, period :), and you are passing a wrong slice construct - this is not the syntax how to select these 3 members. Plus, the indices are 0 based - the 1st element is 0, and so on.
Here's revised code based on your approach:
list1 = ['a','b','c','d','e'],['one','two','three','four','five'],['1','2','3','4','5']

for sub_list in list1:
    for num in (0, 1, 4):
        print sub_list[num]

No need to use enumerate(), as you're not using its index anyways.
Comment: Yes you are correct it is a method, but I named my list `list1` not `list`. I have fixed up the indices ordering. However I am now getting the error `TypeError: 'list' object is not callable` when I place my list items inside parenthesis like above
Comment: I've realized a crucial mistake in my initial understanding of your code (you were reassigning `list` to a local variaboe), and have edited my answer. The final loop is actually the "longer" version of the list comprehansion answers given below.
Answer: Try this:
>>> list1 = [['a','b','c','d','e'],['one','two','three','four','five'],['1','2','3','4','5']]
>>> index1 = [1,2,5]
>>> [j for i in list1 for index,j in enumerate(i) if index+1 in index1]
['a', 'b', 'e', 'one', 'two', 'five', '1', '2', '5']

Answer: If you know the indexes you want, you simply need to index said list at the specific indexes, and print the values.
You should also note however, that list are zero indexed. The first value is at index 0. That means you want 0, 1, 4, and not 1, 2, 5
>>> list1 = [['a','b','c','d','e'],['one','two','three','four','five'],['1','2','3','4','5']]
>>>
>>> for lst in list1:
        a, b, c = lst[0], lst[1], lst[4]
        print a
        print b
        print c

a
b
e
one
two
five
1
2
5
>>>

If you need a more general solution, you can iterate over the indexes you want to access, and print them out:
>>> def print_elements_at_indexs(indexes, lst):
    for sublst in lst:
        for index in indexes:
            print(sublst[index])

>>> print_elements_at_indexs([0, 1, 4], list1)
a
b
e
one
two
five
1
2
5
>>>

Answer: Check this
[v for _list in list1 for i,v in enumerate(_list) if i in [0,1,4]]

Answer: list1 = [['a','b','c','d','e'],['one','two','three','four','five'],['1','2','3','4','5']]

for number, lst in enumerate(list1):
    for num, item in enumerate(lst):
        if num in [0,1,4]:
            print item

Note : try avoiding built-in keyword as variable in your program.


How do I get to the laboratory for Scent of Incense?

Question: I'm working on the Scent of Incense quest in Flotsam (Chapter 1). I got the real recipe and talked with the scholar. I refused to be blindfolded, so he marked the location of his laboratory on my map.
Unfortunately, I can get close to the marker, but I can't seem to find a way to actually reach it. I've gone up and down the path with the two bandit groups (the way to the field full of Kayran mucus.
I also tried searching around the other path in the area, which leads to the graveyard area a little ways outside town. All to no avail.
How do I get to the laboratory and get my reward?
Comment: I let myself be blindfolded, but I remember that it was a cave that was a bit uphill. I don't think you have to go up the path with the bandits, the path to the laboratory branches out somewhere at the foot of the hill.
Answer: The laboratory is in a cave, and the entrance is nowhere near the marker on the map.
Exit town along the south-east path.
Go left, toward the big rock face.
Ta-da! Cave.
This is the location of the cave entrance on the map.
Comment: I'm playing the game already, but am still amazed at how gorgeous the screens look.
Comment: @Bora It does look nice, but I'm hoping there are some brighter areas later on. So far it's nothing but dark forest and blue light everywhere. I need some color!
Comment: I suppose this cave is sealed after the quest? I opted to be blindfolded and now want to go back there to take a look but the it's all rocky cliff side; no cave in that area.


Unique evolute for arc-parameterized plane curve.

Question: Let $a(s)$ be an arc paramterized plane curve. The goal of this problem is to show that that the unique evolute for $a(s)$ that is in the same plane as $a(s)$ is given by:
$b(s)= a(s) + \frac{N}{\kappa}$
where $N$ is the unit normal vector for $a(s)$ and $\kappa$ is the curvature.
Since $b(s)$ is the evolute of $a(s)$, $a(s)$ is the involute of $b(s)$. I showed earlier that this means that $a(s)$ is of the form:
$a(s)= \frac{b'(s)}{|b'(s)|}(c-s)+b(s)$
Also:
$a'(s) \cdot b'(s)=0$.
where $b'(s)$ is given by:
$b'(s)=a'(s) + \frac{N'}{\kappa}-\frac{N\kappa'}{\kappa^2}$,
Anyway, I would appreciate some insight into this. How do i show uniqueness?
So:
$a'(s) \cdot b'(s)=a'(s)\cdot a'(s)+a'(s) \cdot \frac{N'}{\kappa}- a'(s) \cdot \frac{N\kappa'}{\kappa^2}$
= $1+a'(s) \cdot \frac{(-\kappa a'(s))}{\kappa}+0$
= $1-1=0$
so $b(s)$ appears be an evolute of $a(s)$... but how do we show uniqueness? and what gaurentees that $b(s)$ is in the same plane as $a(s)$?
Answer: Let $b$ be a evolute lying in the plane of $a$. Since $a' \cdot b' = T \cdot b' = 0$, by the fact that $T$ and $N$ are perpendicular and $b$ lies in $span\{T, N\}$, $b'$ and $N$ are parallel.
Say $b - a = \mu N$ for some scalar function $\mu(s)$, differentiate both side we obtain $$b' - a' = b' - T = \mu' N + \mu (-\kappa T)$$
Again, since $b'$ and $N$ are parallel and $\{T, N\}$ is linearly independent, we know $\mu = 1 / \kappa$.
Hence, any $b$ should suffice that $b = a + \frac{N}{\kappa}$.


In terraform, is it possible to only add an optional resource argument if a particular variable is set

Question: On my concrete example:
I want to create a rancher environment resource with preconfigured members. But the number of members is supposed to be depending on a variable list. I'd imaging something like
resource "rancher_environment" "renv" {
  name = "renv"
  project_template_id = "atmplid"

  member {
    count = "${length(var.memberlist)}"
    external_id = "${var.memberlist[count.index]}"
    external_id_type = "exttype"
    role = "owner"
  }
}

This obviously doesn't work. Is there a trick to achieve this behaviour?
Answer: You can use null_resource for this. Try this
resource "null_resource" "memberlist" {
    count = "${length(var.memberlist)}"
    triggers {
        external_id = "${var.memberlist[count.index]}"
        external_id_type = "exttype"
        role = "owner"
    }
}

resource "rancher_environment" "renv" {
    name = "renv"
    project_template_id = "atmplid"

    member = ["${null_resource.memberlist.*.triggers}"]
}

Answer: At long last, Terraform has just released v0.12.0-alpha1, which contains a more elegant way of solving this exact problem.


Preserve treated wood?

Question: What should I use, if anything, to preserve these steps made of treated wood? These are on my townhome's back porch. Two of the steps are directly exposed to weather. They were filthy but cleaned up fine with Murphy's Oil Soap and some scrubbing. Should I preserve them with something or just leave them alone?
Answer: It basically depends on how long the steps have been there for one. You can stain fresh new pressure treated wood, but if its still wet, it doesn't take well. If it has been seasoned and is dry, as it looks like it is, you can stain it.
They make stain, for pressure treated wood even, which helps prolong it. Between that and keeping water from pooling on it, it should last quite a while.

Preserve treated wood?


16.04: Desired key remapping won't load at startup

Question: Running Ubuntu 16.04. I got a compact keyboard without a Menu key. They included a bunch of fluff keys, so I want to make the "web" (XF86HomePage) key be my Menu key. (One can run xev | grep keycode to find key names and codes by pressing the keys.)
I can:

Execute xmodmap -e "keycode 180 = Menu" in a terminal. This works fine for the rest of the session.
Save a file ~/.Xmodmap with the content keycode 180 = Menu and execute xmodmap ~/.Xmodmap. This also works fine for the rest of the session.

But I have not been able to get this to happen without my intervention at startup, which is what I want. I've tried adding a script to "Startup Applications" but no joy and I've also gone so far as to edit my /usr/share/X11/xkb/symbols/pc file to include:
key <XF86HomePage> {[ Menu ]};
but all that did was make my keyboard not work at all after rebooting, and I had to come back and undo the change with a rescue disc.
Advice and insight, as always, much appreciated.
Comment: `key  {[ Menu ]};` in that "pc" file may well have worked! Worth trying sometime when there aren't a bunch of other things on the go.
Comment: Nope, it didn't work. Back to the evdev file.
Answer: The thing to do, per this answer, is to edit /usr/share/X11/xkb/keycodes/evdev and reboot. I made <COMP> = 180 (<MENU> is an alias for <COMP>) and commented out the line where <I180> = 180. Downside is that if I plug in a different keyboard, the real Menu key won't work, but the compact keyboard I'm using doesn't have one at all and it's not an absolutely necessary key anyway (if you have a mouse) so I'm good with this.


wpf which features?

Question: I need to prepare a presentation about what's WPF, my audiences are mostly project managers and system analyzers . I intend to show them most important features of WPF like DataBinding . Can you suggest me a list of features which you think will be interesting for my audiences . and also does anybody know any website where I can find presentations about introducing WPF ?
thanks
Answer: In my opinion the killer features for WPF are (in no particular order):

Strict separation of UI layout, style and functionality
Templates
Styles
Data Binding

The combination of those features enables really fun ways of crafting application UI. Such as this example of a list box with templates and data binding or a slightly different TreeView visualization. Especially the ItemsControl is way overrepresented which just demonstrates its versatility :-)
Answer: Have you surfed through MSDN? A good place to start: http://msdn.microsoft.com/en-us/library/ms754130.aspx
Answer: Here's a question and its duplicate with compelling reasons to use WPF - these reasons can easily be mapped to the most important features since they represent the advantages of using WPF compared to other options (mainly WinForms).
Note: DataBinding is not one of the most important features of WPF in my opinion! you can easily do that with WinForms.
Comment: thanks for the links and the answers are great, sure I'll use them but one thing that I think make this question different from those you linked is that my target group (audiences) are project managers so I don't want to explain about technical points .
Comment: Databinding is more technical than the whatever is on those answers (things such as separation between UI and development) - I know because I wrote one of those answers :)
Answer: Other answers already mentioned the technical advantages. Since your target group consists of managers, you might want to throw in a few non-technical points:
WPF is the new "Microsoft standard" for developing rich client applications in .net.

You won't need costly migration to another technology anytime soon and
there's quite a large user base out there (for example, here on Stackoverflow), so your developers won't be "left alone" when facing technical problems.

WPF has useful features for designing user interfaces:

It allows the user interface design to be separated from coding (UI designers can use Expression Blend).
It's very easy to do eye candy that impresses customers during presentations of your products. (Yes, this is important for the sales people.)

(Well, the Visual Studio Designer support is not so great yet, but I've heard that this improves drastically in VS 2010.)
Answer: WPF supports XAML the declarative language which encourages a separation of front-end appearance and back-end logic.

wpf which features?


How Microsoft SAL can prevent off-by-one error

Question: Here's an example given on MSDN (http://msdn.microsoft.com/en-us/library/hh916383.aspx) that tried to explain SAL annotation could help find a common off-by-one error.
wchar_t * wmemcpy(
_Out_writes_all_(count) wchar_t *dest,
_In_reads_(count) const wchar_t *src,
size_t count)
{
   size_t i;
   for (i = 0; i <= count; i++) { // BUG: off-by-one error
      dest[i] = src[i];
}
return dest;
}

I don't quite get this example. In this example, it looks like the function signature contains a parameter called count, so we can use In_reads_(count) to make sure the memory space that src is pointing to has at least such number of bytes.
My question is, what if there is a function with signature like this
memcpy_example(wchar_t* dest, wchar_t* src)

In this case, the signature does not contain any information about the sizes. Can I use SAL to tell debugger that dest should be same size or 1-byte larger than src?
Comment: `memcpy` has a `size` parameter that specifies how many bytes are to be copied.  How many bytes do you expect your `memcpy_example` function to copy?
Answer: The correct annotation would be:
memcpy_example(
    _Out_writes_z_(_String_length_(src) + 1) wchar_t *dest,
    _In_z_ const wchar_t *src)

However, the analysis is much less precise in this case, since the analyzer does not know the actual string-length in most cases (tested with VS 2013):
void test_sal()
{
    wchar_t out[10];
    auto in1 = L"12345678901234";
    auto in2 = _wcsdup(L"12345678901234");

    memcpy_example(out, in1); // SAL warning
    memcpy_example(out, in2); // No warning!
}


How does "dancing" work?

Question: How many points does one get when you "dance"?  How many seconds does this last? I'd like to know so I can cram as many of these into open parts so I can get more points.
Do points received from dancing also play into difficulty level? Does playing on Just Right give less points than playing on Hard?
Answer: Dancing is first unlocked at Level 2-1.  You simply press the button "A" on a keyboard, and it performs a dance move.
The key issue of a dance move is that when "dancing", you cannot do any other action (sliding, jumping, blocking, and kicking), so be careful when dancing; with great dancing comes great responsibility.
Dancing nets you different points based on what score multiplier you have. The following levels show what points you receive for each time you "dance" at which multiplier.

Hyper - 2000 points
Mega - 4000 points
Super - 6000 points
Ultra - 8000 points
Extra - 10000 points

Dancing does pay off though.  This is from 1-1 (The very first level) on the Just Right mode.  Look at the score comparison between me, @badp, and a buddy of mines:

As you can see, even without the Bonus Challenge (50k points, for skipping checkpoint) the difference between badp's score and mines is substantially a lot more.

How does "dancing" work?


Detecting voltage at garage door opener control panel wire

Question: I've removed our previous 20 year old garage door opener and am installing a new one. I'm now at the step of wiring the new control panel to the wall. The garage is finished, and the old control had wiring behind the drywall. There is a brown cable and inside it is a black and white wire, one end going to the control panel on the wall, and the other end coming out of the middle of the ceiling in the garage (to go to the old garage door opener).
I'm using a contactless voltage detector and it's detecting voltage on both of those black and white wires, even though there is no garage door opener (let alone one that is plugged in), and the voltage is detected at both ends of both of these wires. Why would this be? The control panel on the wall is just above a light switch, is it perhaps detecting some "phantom" voltage from that or something? I dont think that would explain why it is detected at the ceiling, where there is no light switch (there is a light, but a few feet away).
My new garage door opener came with a new control panel cable, so I can use that. But I wanted to reuse this wire if possible so that I dont need to put unsightly wires stapled to the drywall. However, I dont want to damage the new garage door opener with improper wiring.
Answer: Contactless testers are notoriously unreliable.
The best thing to do is to locate the other end of the wire, which should have been connected to your old opener, and check continuity between the BLACK on each end and the WHITE on each end.  There should also be no continuity between the BLACK and the WHITE wires.
These are typically just a simple momentary pushbutton switch that shorts the BLACK and WHITE and that triggers the opener to cycle.
Unlike furnace control wires and doorbell wires, garage door opener controls do not have external power supplies.
Comment: And then invest in an inexpensive proper multimeter. Every homeowner should have one.
Comment: @isherwood -- keep in mind that "proper" puts you around $70-$100, BTW -- you don't need something super-expensive, but Cheese-pipeline DMMs do not fare well vs mains surges and such
Comment: I'm not sure what you're saying. My $30 model does everything I need it to do as a homeowner.


Lubuntu on Ubuntu. Auto choose Lubuntu

Question: Can I install Lubuntu on Ubuntu and when the PC boots up, it chooses Lubuntu as default?
Comment: Feel free to correct me, but instead of installing 2 different flavours of ubuntu and choosing in grub which to auto-boot, wouldnt it be easier to maintain just 1 ubuntu install which offers both desktop environments (Unity & LXDE and in addition even Gnome and mate if you feel lucky)? This reduces disk-usage and in general simplifies the setup. I am assuming here you are not forced to have 2 seperate installations on that machine.
Comment: In case you want to installations there is as well the method to just tell grub to remember the last option via 'GRUB_DEFAULT=saved' and 'GRUB_SAVEDEFAULT=true' in /etc/default/grub. You would need to update grub then via  'sudo update-grub'
Answer: you can use Grub Customizer
on the "List configuration" tab, move lubuntu to the top,
and on the "General setting" tab, insert 0 Second in "Boot default entry after" option
Comment: inserting 0 second in the option is optional if you need time to choose another OS

Lubuntu on Ubuntu. Auto choose Lubuntu


Select maximum value from all previous rows (oracle sql)

Question: I have a table that looks as follows:
personid  opendate  fraud
       1  20190105      0
       1  20190715      1
       1  20191011      0
       5  20181205      0
       5  20190105      0
       5  20190705      1

I want to get the maximum value of fraud up until each date grouped by personid. That is, I want to get the following table:
personid  opendate  fraud  ever_fraud
       1  20190105      0           0  <-  no preceding frauds yet
       1  20190715      1           1  <-  fraud committed
       1  20191011      0           1  <-  fraud committed in previous credit
       5  20181205      0           0
       5  20190105      0           0
       5  20190705      1           1

Answer: You can use window functions:
select
    t.*,
    max(fraud) over(partition by personid order by opendate) ever_fraud
from mytable t

Demo on DB Fiddle:

PERSONID | OPENDATE | FRAUD | EVER_FRAUD
-------: | -------: | ----: | ---------:
       1 | 20190105 |     0 |          0
       1 | 20190715 |     1 |          1
       1 | 20191011 |     0 |          1
       5 | 20181205 |     0 |          0
       5 | 20190105 |     0 |          0
       5 | 20190705 |     1 |          1
Answer: It seems like suggesting lag() analytic function :
with t2 as
(
select t.*,
       lag(fraud,1,0) over (partition by personid order by opendate) as ever_fraud0
  from t
)
select personid, opendate, fraud,
       case when fraud = 1 then fraud else ever_fraud0 end as ever_fraud
  from t2

Demo


How do I see the beginners' grimoire after I have bought the more expensive one?

Question: I have already bought the more expensive one, but now I can't see the cheaper one. I need the teleporting spell to get stuff from chests in the hole.
Comment: I bought the expensive one first and I could buy the cheaper one later =/
Comment: When you say "see", do you mean in the Witch's hut or seeing the actual spells you get from it?
Comment: Screenshot may be helpful in this case.
Answer: If you're looking for the actual book inside the Sorceress' hut, it's on the top shelf to the left of the book that has the number 666 on the bottom of it. If you can't actually find the book in that exact location, then it must be an in-game problem, so I suggest that you should contact aniwey (the developer) about this problem. You can find his email in the CFG  section of the game. Hope this helps.
Comment: Please don't put line breaks like that.


Ubuntu 17.04 keyboard not responding after suspend

Question: I have a Sony Vaio SVF142C1WW with 64-bit Ubuntu 17.04 installed. Every time it resumes from being suspended, neither the keyboard nor touchpad work for a few seconds. Then the touchpad becomes responsive but the keyboard still remains non-responsive.
I recently upgraded from Ubuntu 16.10 where both the keyboard and touchpad did become responsive after a few seconds of non-responsiveness. I've tried answers to this and this but nothing worked. What else can I try?
Comment: Switched to kernel version 4.8 and the keyboard works fine now. Will I run into any troubles because of this change?
Answer: @Saif has found the underlying driver which is behind the issue. However setting dumbkbd and direct is unnecessary / disables system control of LEDs like Caps-Lock.
For most vaios instead resetting the controller will also correct the problem whilst maintaining this functionality. I.e. in the grub config file -
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash i8042.reset"

Then
sudo update-grub

Comment: Can confirmed this with a laptop - model N150RF1 (Brand varies). Have never been able to use the keyboard after a shutdown before this
Comment: NOTE : This does not work on Sony Vaio SVF series. Only i8042.dumbkbd works, and there is no way around the led bug.
Answer: Basically, run this in a shell to confirm you are applicable to this solution:
dmesg | grep i8042

and confirm you get this output
[ 1.514469] i8042: PNP: PS/2 Controller [PNP0303:KBC,PNP0f13:MOUE] at 0x60,0x64 irq 1,12
[ 1.525273] serio: i8042 KBD port at 0x60,0x64 irq 1
[ 1.525287] serio: i8042 AUX port at 0x60,0x64 irq 12
[ 1.526035] input: AT Raw Set 2 keyboard as /devices/platform/i8042/serio0/input/input3
[ 21.927438] input: SynPS/2 Synaptics TouchPad as /devices/platform/i8042/serio1/input/input10

then, add the boot parameters i8042.direct and i8042.dumbkbd to /etc/default/grub. For example, run
sudo nano /etc/default/grub

Find the line that begins GRUB_CMDLINE_LINUX_DEFAULT= and edit it to include the new parameters, so that after your edit it looks something like
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash i8042.direct i8042.dumbkbd"

Save by pressing Ctrl+O, exit by pressing Ctrl+X, and run
sudo update-grub

Source: Some time traveler here on Ubuntu Forums
Comment: Because I was facing the issue yesterday, with latest kernel and latest distro release. And it was hard to find a solution specific for Vaio laptopts. This might be handy for other victims like me, since this solved the issue.
Comment: Worked on Ubuntu 20.10 with Sony Vaio SVF series laptop, there is no way around led light no bug, touchpad touch click not working bug , so restart is needed to restore fully working system.
Comment: That's an old post. Why do you think it will work here?
Comment: It worked but CapsLock, NumLock lights always on. So something is wrong here!
Comment: so it worked for you? that's great if so! :)
Comment: Worked for my (slightly aged) Sony Vaio running 64-bit Ubuntu 17.04. Great!
Comment: I have HP elitebook and it didn't work for me :(
Comment: Worked on an old Sony Vaio with a touchscreen and Ubuntu 20. Thanks!!
Answer: My ThinkPad E531 mouse and suspend functions works again after:
GRUB_CMDLINE_LINUX_DEFAULT="atkbd.reset=1 i8042.nomux=1 i8042.reset=1 i8042.nopnp=1 i8042.dumbkbd=1 quiet splash"

sudo update-grub

Answer: For the VAIO model vjf152 sold in Japan only, the solution is to replace content in GRUB_CMDLINE_LINUX_DEFAULT with atkdb.reset i8042.nomux quiet splash and then do sudo update-grub.
Found this on a Japanese forum: https://obelisk.hatenablog.com/category/Linux?page=1483896200
Answer: I had same issue on my PC with Ubuntu 16.04. After returning from Suspend mode the password input box was not responding to keyboard events (was not even blinking). Reconnecting USB keyboard did not help. I could switch with Ctrl+F2 to terminal. The keyboard worked - just the input box did not.
Open grub default config file:
sudo gedit /etc/default/grub

Change line:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash atkbd.reset"

run
sudo update-grub

and then reboot ubuntu.
Answer: Although I couldn't get any proper permanent solutions to this problem, I could find a workaround.
What I did was,  turn on On-Screen Keyboard, Press CapsLock on the On-Screen Keyboard,  and turn it back off.
And Voila, the keyboard started working Again!!!
But as I said, it's not permanent, you have to do this Everytime.
Answer: There is one weird thing that worked for me.
My laptop is HP Elitebook 8460p.
When I have such a problem, I press Power button on the laptop to make it sleep again. Then I press Power button again to wake it up. And the keyboard works..
I have no idea why it is so...
Answer: I have the exact same problem on my Hp pro book running ubuntu 21.10. Everytime I suspend the computer and resume it the keyboard doesn't work, i simple just press the power button to go back into suspend and resume it again and voila the keyboard works again.
Hope this helps.


Nvidia drivers and external connections via HDMI not working when using a dual card laptop, but works with Intel card

Question: I recently installed Ubuntu 15.04 (coming from Linux mint 17 for gnome shell). Everything works fine with the exception of my second monitor, attached to my laptop via HDMI. I installed the proprietary drivers (and nvidia prime). Switching from intel to nvidia and back again works very well. However when using nvidia the HDMI port seems to not want to play nice. I plug in the cable and the main screen (on the laptop) and the external monitor flash on and off (or black and off). When using the intel card the external monitor works fine.
In Mint, I was using nvidia-prime and prime-indicator to make the enter setup run on one card or another. This is the setup I would like to use. I would like to run. I want to run the entire Xorg server using either Nvidia or Intel switch as I see fit. Using prime-select nvidia or prime-select Intel has always worked very well for me in the past. I generally run Nvidia and switch to Intel when traveling for better battery life.
What I have done is

set the video driver for the Intel card to "modesetting" - X would not start at all
Downgraded the Nvidia drivers - No change
Disabled gpu-manager - No change or X wouldn't start (as expected)
Used the open source drivers for nvidia  - Work as expected but performance is horrid and there are other massive issues that prevent this from working well.
Disable Kernal Mode Setting - Xorg would not load

I am not sure what to try next. It worked just fine in Linux Mint, so I know it should work, but I compared configs to those I had in the pre-install backup and every thing looks the same, except kernel version and driver version, those are newer in Ubuntu.
lspci (important parts)
04:00.0 3D controller: NVIDIA Corporation GK107M [GeForce GT 745M] (rev ff)
00:02.0 VGA compatible controller: Intel Corporation Haswell-ULT Integrated Graphics Controller (rev 09)

xorg log has nothing of value except maybe: (last line repeats a lot)
[    82.779] have a master to look out for
[    82.820] need to create shared pixmap 1reporting 4 5 24 192
[    82.861] reporting 4 5 24 192
[    82.862] reporting 4 5 24 192
[    82.862] reporting 4 5 24 192
[    82.863] reporting 4 5 24 192
[    82.864] reporting 4 5 24 192
[    82.864] reporting 4 5 24 192
[    82.864] reporting 4 5 24 192
[    82.865] reporting 4 5 24 192
[    82.865] reporting 4 5 24 192
[    82.865] reporting 4 5 24 192
[    82.866] reporting 4 5 24 192
[    82.866] reporting 4 5 24 192

Answer: You can use bumblebee instead of nvidia-prime for switching GPUs.
In this case DE will use Intel and HDMI will work.
You will be able to start specific applications using NVIDIA GPU with optirun command. Or add this command to .desktop shortcuts.
Comment: I do not wish to use Bumblebee. I wish to use nvidia prime. Bumblebee does not seem to work well on this laptop. Even if it did, it would still not be the best option to me. Thanks though
Comment: Exacly the same problem, by chance I found the HDMI port and external display to be working if I plug it AFTER reboot. YMMV.


Showing Menu in one of the fragments of View Pager

Question: I am having Viewpager with 3 fragments. I want to show menu in only one of the fragments.
1st, I don't know why toolbar.inflateMenu doesn't work.
2nd, the menu works, if I have onPrepareOptionsMenu method and do
getMenuInflater().inflate(R.menu.add_user, menu); but the menu is displayed in all the fragments.
So, according to other questions in stack overflow, I implemented the below code, but it doesn't show the menu, it enters the method but menu is not shown.
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
    //getMenuInflater().inflate(R.menu.add_user, menu);
    info("Menu=>${tabs_viewpager.currentItem}")
    val menuItem = menu?.findItem(R.id.addUserMenu)
    menuItem?.setVisible(tabs_viewpager.currentItem == 1)
    return true
}

The control comes to this method and shows currentItem. But it doesn't display the menu. Menu is there with id. Can someone direct me what can I correct to get this work?
Answer: try calling setHasOptionsMenu(true); in oncreate() of the fragments where you want the menu to show (you can set it to false in the fragments where you do not want the menu to show).
also include:
@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    // your code
}

in the fragments where you want to set/change the menu. this is called everytime before the menu is shown.
you can also call invalidateOptionsMenu() or supportInvalidateOptionsMenu() (if you're using the support library) to force onPrepareOptionsMenu(menu) to be called.
you may want to check out  this menus tutorial
good luck
clive


How can you build a REST client, given that the client should have no prior knowledge excepting a starting url?

Question: I've started work on a pre existing REST application and am having trouble understanding how one would go about making a RESTful  client?
The page on wikipedia states the following
"Clients make state transitions only through actions that are dynamically identified within hypermedia by the server (e.g. by hyperlinks  within hypertext). Except for simple fixed entry points to the application, a client does not assume that any particular actions will be available for any particular resources beyond those described in representations previously received from the server."
If all the client can assume is a starting url then apart from a pure HTTP rest service running in a browser how would it be possible for the client to know how to display any information returned.
For example a java/flash client would have to make an assumption about what data is returned in order to know how to display it, ad then of course the implementation would cease to be restful??
Thanks for any insight.
Piers
Comment: I see what way you read it, but I would take it simply as meaning that you should ensure your app is robust in it's locating of the resources and in how it tolerates errors (such as lacking resources etc.), and not actually that you shouldn't make assumptions on the data. For example, if you're making a microbloggin app, you can expect the data to be in the format defined by the platform, but try to ensure your app is smart about resolving URIs to the resources you're looking for and tolerating discrepancies/errors.
Answer: There is a difference between state transitions and telling the client how to display the information. In HTTP the data type is usually determined by the Content-Type header field based on which the client decides on how to display it (e.g. a browser would request text/html and render the result). REST does not make the assumption that the data are self describing, just that they should be semantically connected through URIs. What the wiki page states is that if you are requesting application/json at http://example.com it will return something like this:
{
    "users" : "http://example.com/users",
    "todos" : "http://example.com/todos"
}

Now you know what URI to request to get a list of todos and a request to http://example.com/todos might return something like this:
[
    {
        "description" : "Do dishes",
        "user" : "http://example.com/users/20"
    },
    {
        "description" : "Do dishes",
        "user" : "http://example.com/users/42"
    }
]

Instead of just returning an id, the user key references the actual URI for the connected user resource, so you can directly request it.
Comment: It's probably worth noting that in reality, for most popular REST APIs that I've dealt with anyway, the trend tends to be to provide a list of objects (as the todos in this example) with basically the complete objects and not just a URI, paginated if necessary. It would be impractical to require 100+ separate requests to display a list of 100 todos... the single item URI would tend to be mostly used solely for _update_ and _delete_ calls.
Comment: Cheers Daff & garmur, I feel like I'm at least one step closer to getting my head around this thing!
Comment: Alternatively you could also create a user object with the data you need for displaying it but still keeping the reference (to stay with the actual REST spirit): `"user" : { "href" : "http://example.com/users/42", "username" : "John Doe" }`


Windows 7 and Ubuntu work together

Question: I used to have in my laptop two OS: Windows 7 and Ubuntu, and I was able to choose from  them what would I use when I booted the laptop. Now I have re-installed Windows 7 but after I finished the installation I found that I could not choose anymore the OS at the boot time, and Windows 7 would boot directly. I want to be able to choose the system a last time. Do anybody know what I do to fix this problem?
Answer: boot-repair should help you out. Just boot ubuntu out of a LiveCD, do not install it bust just "try it out", and install boot-repair (explained here: https://help.ubuntu.com/community/Boot-Repair). Click on recommended repair, and that's it!
Comment: @biozalp: Yes, but that'll make the procedure more complicated and (user) error prone. It's better to keep it simple and tweak the minor settings once things are working again.
Comment: i think advanced settings works better because i don't like waiting for 10sec for boot menu, although you can select your preffered os from advenced setting

Windows 7 and Ubuntu work together


Possible to host ASP.NET MVC controllers+views within a webforms project...?

Question: We have a legacy ASP.NET webforms application that we're engaged in stabilising and removing technical debt from.  Is it possible to take a hybrid approach - ie, can ASP.NET MVC coexist with webforms within the same web-project?
Are there any gotchas for that?  If it is possible, I assume one just has to initialise the routes table, register the ASP.NET MVC handlers, and that's hopefully it...?
Answer: See this question.


White Mortar-like material oozing out of Chimney's brickwork (pictured)

Question: We do have a masonry expert coming to evaluate the nature of the pictured problem, but I thought I'd pose the question here to get some information and possibly, a second opinion.
There is some white mortar-like material oozing out of the joints of our brick chimney. What is the cause of this?
Thanks for looking.
Answer: It is efflorescence. Water picks up minerals in the mortar and transports them until the water evaporates, leaving the minerals behind. Other than cosmetic issues, this is normally harmless, though if the process continues for a long period, enough minerals can be removed that the mortar sort of rots.
Only close inspection will indicate if the mortar is compromised. If it is, it's likely superficial and can be corrected by repointing. The deposits can be removed with muriatic acid. The mortar can be protected from more water incursion by applying any of various sealing products available.


No route matches {:action=>"bands", :controller=>"users"}

Question: When a user signs up for my site, they are redirected to '/welcome', which includes these links:
<%= link_to "Create Band Page", bands_user_path %>
<%= link_to "Complete Profile", edit_user_path(current_user) %>

The 'Complete Profile' link shows up and works fine.  However, the page won't display with the 'Create Band Page' link, and results in this error:
No route matches {:action=>"bands", :controller=>"users"}

I have that link on the user's page and it works fine tho.
My users_controller includes this bit:
def bands
  @band = current_user.bands.build
  @bands = current_user.bands.all
  @user = current_user
end

And the relevant routes.rb parts look like this:
resources :users do
  member do
    get :following, :followers, :bands
  end
end
match '/welcome', to: 'static_pages#welcome'

As I said before, when I use the link on a user's show page it works fine, and rake routes includes the appropriate link:
bands_user GET    /users/:id/bands(.:format)      users#bands

What am I missing here?
Answer: You're not passing it the user you want to display bands of.
Your route matches /users/:id/bands(.:format). The format is an optional segment (that's what the parentheses mean), but :id is required. It expects you to pass in a valid user_id or user object to inflect a user_id from.
Try <%= link_to "Create Band Page", bands_user_path(current_user) %> and it should work.


Why bother getting larger soul gems in Skyrim?

Question:
Possible Duplicate:
What difference do gems make in enchanting weapons?

I have a filled black soul gem and I am not sure what value it gives me over a petty soul. When enchanting, I see the same "Target takes 11 points of frost damage" message no matter which soul gem I choose to use. Why should I bother collecting larger gems and filling them?
Comment: I think this is a duplicate of a question I posted awhile back.  I'll look that up for you.
Comment: Found it:  http://gaming.stackexchange.com/q/43515/6274
Comment: Perfect; thanks. For some reason I couldn't find your question when searching.
Comment: It's ok.  Happens to me all the time.
Answer: For armor, the quality of the soul gem affects its magnitude. For weapons, the quality affects how many charges it can hold.
A Petty Soul Gem filled with a petty soul with only give you 1/12 the effect as Black/Grand Soul Gem with a grand soul. The means a weapon dealing frost damage based on a Petty Soul Gem will need to be refilled 12 times as often and will require the expenditure of at least 12 souls to do so, whereas a weapon enchanted using a Grand Soul Gem may only need a single, powerful soul to recharge once during that time.
It's not as pronounced an effect as for armor, definitely, but it's still nice to not have to recharge as often.
Comment: "How many charges it can hold" was the crucial bit. Thanks much!


About linux v5.4 kernel arm64_memblock_init() / fdt_enforce_memory_region()

Question: Q: What is the use of linux,usable-memory-range property?
Background:
Recently I am analyzing how Linux kernel initializes memory. When I go to arm64_memblock_init function in arch/arm64/mm/init.c, I meet a function called fdt_enforce_memory_region().The function handles linux,usable-memory-range property of chosen node in device tree.
The function call chain is: arm64_memblock_init() -> fdt_enforce_memory_region() -> memblock_cap_memory_range().
void __init arm64_memblock_init(void)
{
    const s64 linear_region_size = BIT(vabits_actual - 1);

    /* Handle linux,usable-memory-range property */
    fdt_enforce_memory_region();
    ...
}
static void __init fdt_enforce_memory_region(void)
{
    struct memblock_region reg = {
        .size = 0,
    };

    of_scan_flat_dt(early_init_dt_scan_usablemem, &reg);

    if (reg.size)
        memblock_cap_memory_range(reg.base, reg.size);
}
void __init memblock_cap_memory_range(phys_addr_t base, phys_addr_t size)
{
    int start_rgn, end_rgn;
    int i, ret;

    if (!size)
        return;

    ret = memblock_isolate_range(&memblock.memory, base, size,
                        &start_rgn, &end_rgn);
    if (ret)
        return;
    /* codes below this line make me confused */
    /* remove all the MAP regions */
    for (i = memblock.memory.cnt - 1; i >= end_rgn; i--)  /*-- 1 --*/
        if (!memblock_is_nomap(&memblock.memory.regions[i]))
            memblock_remove_region(&memblock.memory, i);

    for (i = start_rgn - 1; i >= 0; i--)                 /*-- 2 --*/
        if (!memblock_is_nomap(&memblock.memory.regions[i]))
            memblock_remove_region(&memblock.memory, i);

    /* truncate the reserved regions */
    memblock_remove_range(&memblock.reserved, 0, base); /*-- 3 --*/
    memblock_remove_range(&memblock.reserved,          /*-- 4 --*/
            base + size, PHYS_ADDR_MAX);
}

After reading some patches and /Documentation/devicetree/bindings/chosen.txt,I have learned linux,usable-memory-range property is related with crash dump kernel. It should have some relationship with kdump. But why memblock_cap_memory_range() remove 'memory' and 'reserved' type memory which are marked above the function from 1 to 4, and it only reserves memory from [base, base + size]? I can't understand this.
But from some books, they say "linux,usable-memory-range" prop is the usable range of memory, and memblock_cap_memory_range() remove memory beyond this range. If this saying is true,I can understand this. However, as I show above, some patches and this article as well as /Documentation/devicetree/bindings/chosen.txt said the prop is related with kdump.
So, What is the use of linux,usable-memory-range property?
Comment: Thanks for prettifying my question! My sincere gratitude.
Comment: Put the code excerpt inside the question. Now it's blurry what you are talking about.
Comment: @0andriy Thanks for your suggestion.I have added the code now.
Answer: First some background:
Kexec allows Linux to act as a bootloader and run another kernel (not necessarily a Linux kernel). A user-space tool (kexec from kexec-tools) creates a kexec image including the new kernel and any other binaries needed for booting, such as an initrd/initramfs image, a device tree image, some helper code to jump to the new kernel (purgatory) etc. The kimage also includes information on where those binaries are to be re-located on the new system's memory if needed. The tool then loads the kimage on the running kernel (kexec -l), and when requested (kexec -e) the current kernel will exit, unpack the kimage on memory and jump to the new kernel.
Kdump allows the running kernel, in case of a system crash, to use kexec and jump to another kernel instead of hanging or performing a hw reboot. The new kernel's purpose (also known as crash kernel or dump-capture kernel) is to dump debug data from the crashed kernel's memory and then re-use kexec to re-boot to the normal system (aka primary kernel). The main kernel provides an ELF Core header to the crash kernel and the crash kernel uses it to provide /proc/vmcore as a portal to the crashed kernel's memory. It's a very cool feature that allows for quick recovery from OS crashes (hw reboot can be very slow) while also providing log data for debugging each crash.
For more info on kexec/kdump: https://www.kernel.org/doc/Documentation/kdump/kdump.txt
Now for your question:
It is very important when we jump to the crash kernel, to preserve the contents of the crashed kernel and not overwrite anything. For this reason in order to use kdump we need to pre-allocate a continuous memory region on the primary kernel using the crashkernel= command line property. The crash kernel will only be able to use that reserved memory region, that means the whole kimage must fit in there, not just the kernel. This also makes jumping to the new kernel simpler since no re-location of the various parts of the kimage is needed, it's already "unpacked".
However the crash kernel needs to know about this somehow, if it re-uses the device tree from the primary kernel nothing prevents it from messing with the crashed kernel's memory. So we have a couple of options:
a) Override /memory node on the crash kernel's device tree so that in only includes the memory region we reserved through crashkernel= on the primary kernel. However when we try to re-boot to the primary kernel we won't know how to restore /memory node to its original value.
b) Use the linux,usable-memory property (see early_init_dt_scan_memory) that will override the reg property of the /memory node and allow the crash kernel to only see the reserved memory region instead. We can then remove that property from the device tree of the crash kernel and re-boot to the primary kernel using the original /memory region.
c) Go with ARM's way and for some reason introduce a new binding, linux,usable-memory-range, that goes to the /chosen node and used for exactly the same thing. Only now since the system has already parsed the /memory node and is ready to use the whole memory, we need to exclude the memory of the primary kernel asap, that's what memblock_cap_memory_range() is for.
Note that it's the userspace tool that adds linux,usable-memory, linux,usable-memory-range and linux,elfcorehdr properties on the crash kernel's device tree when creating the kimage. Those properties are missing under normal operation and you won't see them on /sys/firmware/fdt.
Now that you have an idea of what memblock_cap_memory_range() is all about, in order to better understand the code I guess you should start with memblock_isolate_range(). Have in mind that memory may be split to multiple memblocks, since the /memory node may include an array of regions, or the device tree may have multiple /memory nodes (aka sparse memory layout). So memblock_cap_memory_range() will get called with the start / end address of the crash kernel's reserved region, and will then call memblock_isolate_range() which will walk through the memory memblocks and will make sure that the start / end address are memblock barriers.
As an example think of a memory range 1-10 and 3 memory blocks A[0-3], B[4-8], C[9-10], with crash kernel being on 2-6. In this case memblock_isolate_range() will split A to two blocks A1[0-1] and A2[2-3], and B to B1[4-6] and B2[6-8], and will put the index of A1 on start_rgn and index of B2 on end_rgn. So between start_rgn and end_rgn we'll get A2[2-3] and B1[4-6] that include the reserved region.
The next part of the code will remove the memblocks before and after the reserved region from the set of memory memblocks, so in our example it'll remove A1, B2 and C. Since the memory blocks marked with the no-map flag won't be used anyway, a check with memblock_is_nomap() is done to skip them.
The last part deals with the reserved memblocks outside the crash kernel's region. Have in mind that reserved memblocks marked with nomap will not be present on the set of reserved memblocks / memory memblocks so no special treatment is needed here.
I hope this was more helpful than confusing.


Ignore parentheses with string tokenizer?

Question: I have an input that looks like: (0 0 0)
I would like to ignore the parenthesis and only add the numbers, in this case 0, to an arraylist.
I am using scanner to read from a file and this is what I have so far
    transitionInput = data.nextLine();
    st = new StringTokenizer(transitionInput,"()", true);
    while (st.hasMoreTokens())
    {
        transition.add(st.nextToken(","));
    }

However, the output looks like this [(0 0 0)]
I would like to ignore the parentheses
Comment: could you give a few more input-examples? Is it just the first and last characters, then you could do `input = input.substring(1, input.length() - 1);`
Comment: what does comma (",") do in your token rule?
Answer: How about
 for(String number: transitionInput
       .replace('(', ' ').replace(')', ' ').split("\\s+")){
    transition.add(number);
 }

Answer: You are first using () as delimiters, then switching to ,, but you are switching before extracting the first token (the text between parentheses).
What you probably intended to do is this:
transitionInput = data.nextLine();
st = new StringTokenizer(transitionInput,"()", false);
if (st.hasMoreTokens())
{
    String chunk = st.nextToken();
    st = new StringTokenizer(chunk, ",");
    while (st.hasMoreTokens())
    {
        transition.add(st.nextToken());
    }
}

This code assumes that the expression always starts and ends with parentheses. If this is the case, you may as well remove them manually using String.substring(). Also, you may want to consider using String.split() to do the actual splitting:
String transitionInput = data.nextLine();
transitionInput = transitionInput.substring(1, transitionInput.length() - 1);
for (String s : transitionInput.split(","))
    transition.add(s);

Note that both examples assume that commas are used as separators, as in your sample code (although the text of your question says otherwise)
Answer: Another variant
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

public class simple {

 public static void main(String[] args)
 {

  List transition = new ArrayList();
     String transitionInput="(0 0 0)";
     transition = Arrays.asList((transitionInput.substring(1,transitionInput.length()-1)).split("\\s+"));
     System.out.println(transition);
 }
}

Output : [0, 0, 0]
Answer: import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

public class simple {

 public static void main(String[] args)
 {

  List transition = new ArrayList();
     String transitionInput="(0 0 0)";
     transition = Arrays.asList((transitionInput.substring(1,transitionInput.length()-1)).split("\\s+"));
     System.out.println(transition);
 }
}


Adding elements to a hashmap with numeric keys

Question: I am using a hashmap to keep track of a series of data paris over time, and I would like to know how you can keep appending them to the main hashmap.
Here is an example:
library(hash)

a = 2
h = hash(a, "V")
ls(h)
h[["2"]]

Here a gets coerced into using its numerical value as a character. As expected the result is the pair: 2-V.
Here is where I don't understand how this works. I want to add more key value pairs to the hashmap (I don't know the all at the beginning so I cant make a general list, and then make a hash out of it.
For example:
b = 67
h$b = "x"
h[[b]] = "x"

The first method gives me the pair b-x rather than 67-x, and the second method doesnt actually work...
Any suggestions?
Answer: You can try converting the number to a character type using as.character():
b <- 67
h <- hash(b, "V")
h[[as.character(b)]]
[1] "V"

This will also work:
h$"67"

But the hash library does not appear to support referencing the hash this way using a numeric variable.
Comment: I had tried that and gotten nowhere...tried again and it works.lol must have been bad syntax on my end :) TNX!


Minecraft 1.14 - Kill two random arrows when shot from a crossbow with multishot enchantment

Question: I'm trying to create a command that will kill two random arrows shot from a multishot enchanted crossbow (that shoots 3). I wanted to make a bow that would either shoot only left, middle or right. I tried this by adding a scoreboard called
CBOW which detected when a crossbow is shot and ran this command on a repeating command block:

execute as @a[scores={CBOW=1}] run kill
  @e[type=minecraft:arrow,limit=2,sort=random]

this does not work for me, so does anyone have any suggestions or fixes?
Answer: Just Fixed it. For some reason, the command block that had the commands in it was not working, so I rewrote the command in another command block and it worked!
Comment: This might be caused by [this bug](https://bugs.mojang.com/browse/MC-149038). Nobody knows yet what exactly causes it.


How can I structure my classes which usually need to be called together?

Question: I have some related classes that implement the same method
class Dog {
    public void speak() { System.out.println("Bark") }
}
class Cat {
    public void speak() { System.out.println("Meow") }
}

90% of the time, users would want both the dog and the cat to speak. They don't want to know the details. When we add a new animal, they'll want it to speak too. The idea is to avoid:
// All animals need to be explicitly told to speak every time
new Dog().speak();
new Cat().speak();

// But we just added Birds, and the users need to remember to add this call everywhere
new Bird.speak();

I could do something like
class Animals {
    public void speak() {
        new Dog().speak();
        new Cat().speak();
        new Bird().speak();
    }
}

So that users can just call new Animals().speak() every time.
However, 10% of the time, it does need to be configurable. What I want is a way for users to do something like this
// Used most of the time
Animals.withAllAnimals().speak();

// Sometimes they don't want cats, and they want the dogs to woof instead
Animals.exclude(Cat)
  .configure(Dog.sound, "Woof")
  .speak();

How can I structure my classes to accomplish this?
Answer: I know that it is question tagged with java. However, let me show an example with C# as these languages have many common things.
The first thing is I would use inheritance and create abstract class Animal as common behaviour Speak() is used. So, abstract class should define behavior, and the derived classes should implement that behavior:
public abstract class Animal
{
    public abstract void Speak();
}

Then just use inheritance and override behaviour in derived classes:
public class Bird : Animal
{
    public override void Speak()
    {
        System.Console.WriteLine("I am a bird!");
    }
}

public class Cat : Animal
{
    public override void Speak()
    {
        System.Console.WriteLine("I am a cat!");
    }
}

public class Dog : Animal
{
    public override void Speak()
    {
        System.Console.WriteLine("I am a dog!");
    }
}

Then we need a class that allows to speak for all animals. Let's create Choir  class for this purpose:
public class Choir
{
    private List<Animal> choristers;

    public void AddChoristers(IEnumerable<Animal> choristers)
    {
        if (choristers == null)
            choristers = new List<Animal>();

        choristers.AddRange(choristers);
    }

    public void SpeakAll()
    {
        foreach (Animal animal in choristers)
            animal.Speak();
    }

    public void Speak(Func<Animal, bool> filter)
    {
        IEnumerable<Animal> filteredAnimals = choristers
            .Where(filter ?? (animal => true));
        foreach (Animal animal in filteredAnimals)
            animal.Speak();
    }
}

Pay attention to Speak() method. It can take a predicate as a parameter, so you can choose desired animals to speak().
Answer: Here are some ideas.
import java.util.*;
import java.util.function.Consumer;

/**
 * An animal can either speak with its own voice, or another supplied
 */
interface Animal {
    String speak();
    String speak(String voice);
}

/**
 * Base class for animal implementations.
 *
 * An animal is added to a Menagerie when created.
 */
abstract class BaseAnimal implements Animal {
    private final String defaultVoice;

    public BaseAnimal(Menagerie menagerie, String defaultVoice) {
        this.defaultVoice = defaultVoice;
        menagerie.add(this);
    }

    public String speak(String voice) {
        return voice;
    }

    public String speak() {
        return speak(defaultVoice);
    }
}

/**
 * A Dog. Even when given a voice the dog does things slightly differently.
 */
class Dog extends BaseAnimal {
    public Dog(Menagerie menagerie) {
        super(menagerie, "Bark!");
    }

    public String speak(String voice) {
        return voice + " (and drools)";
    }
}

/**
 * A collection of animals. We can do something side-effectful to each, or create a new collection where
 * some classes of animal are excluded or have different behaviour.
 */
interface Animals {
    void forEach(Consumer<Animal> action);
    Animals exclude(Class<Animal> clazz);
    Animals configureVoice(Class<Animal> clazz, String voice);
}

/**
 * An Animals instance which can contain only a single animal of each class
 * (an arbitrary decision based on the code in the question)
 */
class Menagerie implements Animals {
    Map<Class<? extends Animal>,Animal> animals = new HashMap<>();

    public Menagerie() {
    }

    public Menagerie(Map<Class<? extends Animal>, Animal> animals) {
        this.animals = new HashMap<>(animals);
    }

    public void add(Animal animal) {
        animals.put(animal.getClass(), animal);
    }

    public void forEach(Consumer<Animal> action) {
        animals.values().forEach(action);
    }

    @Override
    public Animals exclude(Class<Animal> clazz) {
        Menagerie m = new Menagerie(animals);
        m.animals.remove(clazz);
        return m;
    }

    /**
     * Return an Animals instance which contains a proxy for a particular type of animal
     * which will behave differently when speak() is called.
     */
    @Override
    public Animals configureVoice(Class<Animal> clazz, String voice) {
        Menagerie m = new Menagerie(animals);
        Animal a = m.animals.get(clazz);
        if (a != null) {
            m.animals.put(clazz, new Animal() {

                @Override
                public String speak() {
                    return voice;
                }

                @Override
                public String speak(String voice) {
                    return a.speak(voice);
                }
            });
        }
        return m;
    }
}


DCPCrypt to Lockbox3 migration

Question: I'm a newbie on encrypting/decrypting routines.
I'm trying to use Lockbox3, which I want migrate my app to, in order to decrypt a string encrypted by using DCPCrypt.
Let's say I have this function to encrypt:
function TfrmMain.Encrypt(value: string): string;
var
  CipherR : TDCP_rijndael;
  m, sm, Key, IV: string;
  Data: string;
begin
  Key := PadWithZeros(m, KeySize);
  IV := PadWithZeros(sm, BlockSize);
  Data := PadWithZeros(value, BlockSize);
  m := 'SOMEWORDSOMEWORD';
  sm := 'WORDSOMEWORDSOME';

  Key := PadWithZeros(m, KeySize);
  IV := PadWithZeros(sm, BlockSize);
  CipherR := TDCP_rijndael.Create(Self);
  if Length(m) <= 16 then
    CipherR.Init(Key[1], 128, @IV[1])
  else if Length(m) <= 24 then
    CipherR.Init(Key[1], 192, @IV[1])
  else
    CipherR.Init(Key[1], 256, @IV[1]);
  CipherR.EncryptCBC(Data[1], Data[1], Length(Data));
  CipherR.Free;
  FillChar(Key[1], Length(Key), 0);
  code := Base64EncodeStr(Data);
  Result := code;
end;

I would like now to decrypt strings encrypted this way using Lockbox3, but I should use the values used in encrypt function as m and sm and I know how I can do it - if I can.
I thought to use the sm value to set Codec1.Password but this doesn't work.
Any idea?
Thanks to all for any advice.
Answer: How about ...
function TfrmMain.Encrypt( const value: string): string;
var
  Codec: TCodec;
  Lib  : TCyptographicLibrary;
  Ciphertext: ansistring;
begin
Codec := TCodec.Create( nil);
Lib   := TCyptographicLibrary.Create( nil);
Codec.CryptoLibrary := Lib;
Codec.StreamCipherId := BlockCipher_ProgId;
Codec.BlockCipherId := 'native.AES-256'; // AES-256 cipher
Codec.ChainModeId := CBC_ProgId;         // CBC chaining
Codec.Password := 'WORDSOMEWORDSOME';
Codec.EncryptString( Value, Ciphertext); // Assumes UNICODE supporting compiler.
result := Ciphertext; // Implicit utf8string --> unicode string coersion here.
Codec.Burn;
Lib.Free;
Codec.Free;
end;

function TfrmMain.ShowCiphertextOfSomeWords;
begin
ShowMessage( 'base64 of ciphertext = ' + Encrypt( 'SOMEWORDSOMEWORD'))
end;

All this is shown in the bundled Demo program and online help. The bundled demo program and the online help should be your first point of reference. Please examine these before going to Stackoverflow or forums, as answerers will tend to repeat what was already written for your benefit.
Comment: Thank you very mutch, Sean. And let me say your Lockbox is really easy to use! Cheers
Comment: I fear to have not been clear. My problem is not encrypting the string 'SOMEWORDSOMEWORD'. Using DCPCrypt I used the function above to encrypt a string. With DCPCrypt, I have to set two values, called Key and IV (see the snippet). To decrypt it I have to use the same values for Key and IV and the decryption works fine. Now I wnat to migrate to Lockbox3 and I need to decrypt the same string encrypted by DCPCrypt using Lockbox, but in Lockbox I can set a password (so the same value of Key or IV, I think) but I don't know how use the other value.
Comment: If you are starting from your own IV and key, what you are asking for can't be done. Although you could certainly go the other way and DCPcrypt decrypt a string encrypted with LB3. LB3 manufactures a binary key by hashing (SHA1) the password. When encrypting, LB3 generates a random 64 bit number (the nonce). This nonce is zero extended to be used as the IV. The nonce is prepended to the output stream. When LB3 is decrypting, the nonce is picked up and prepended to form the IV. So as far as IV is concerned, you could decrypt from  LB3 by prepending the IV, but this only works if the high ...
Comment: ...64 bits of your DCPcrypt IV was zero. Also the problem of converting a binary key into a password string remains. Your problem could be solved if you allowed control over how you did the DCPcrypt encryption, but as the question is currently framed, it is not solvable.
Comment: "Your problem could be solved if you allowed control over how you did the DCPcrypt encryption": Don't know if I understand what you mean, but I didn't anything more than what is in the function I posted above: Email := Encrypt(EmailAddress); I have no other code to encrypt my string. I'm sorry if I'm saying stupid things, but I really don't know anything about encryption... Anyway, if you think to have to know something other, tell me precisely and I'll try to give any info... Otherwise, I'll migrate to Lockbox clearing old data and ask my clients to register new data.
Comment: If your messages are already encrypted with DCPcrypt, and so you do not have the freedom to choose your own key and IV, then you are going to have to, as you say, clear your old data and ask your clients to register new data.

DCPCrypt to Lockbox3 migration


Port forwarding

Question: how to configure local ports to allow connections from other hosts in LAN, in order to reach a web application through my ssh tunnel ?
I have something like this:
ssh -L1000:localhost:80 10.10.10.1

Other hosts must be able to use: http://my_ip_address:1000 to reach 10.10.10.1:80
Thanks!
Answer: You need to use your public IP in the connection line, so the other hosts can connect to this connection. Also specifying the -g switch will allow others to connect to your forwarded port. If you use localhost as in your example, only you can connect:
ssh -g -L1000:my_ip_address:80 10.10.10.1

You also might need to check you firewall configuration.
Comment: I've been trying, it's not working. I need to NAT the my_ip_addres into localhost to make it work but I don't know how do that on linux.
Comment: That's how I solved:

ssh -g -L 1000:localhost:80

Port forwarding


Low grahic mode 12.04

Question: I have been trying to get Ubuntu 12.04 to launch on my Emachine 2828. I was able to load it and use the dual setup with windows xp. I am able to run windows, but I have not been able to run ubuntu. I get the low graphic mode message.. My processor is amd sempron 2800+, and video is via/s3g unichrome igp. I have tried most of the tips posted for low graphics...any help appreciated
Comment: Actually what graphic card do you have? Can you post the output of lspci | grep VGA in your question's description?(Remember that when you get the low graphic message, just press Ctrl+Alt+F1 to drop into a tty session. There you need to give your user name and password and then you have to try the above command I have mentioned)
Comment: VIA/S3G UNICHROME IGP
Answer: Maybe driver for your GPU is missing. Do you know what package in it is? If yes, use the Ctrl+Alt+F1 combination to switch to a TTY. Log in (if you've installed Ubuntu), and type:
sudo apt-get update; sudo apt-get -y install NAME_OF_THE_PACKAGE

After the successful installion, type:
sudo reboot

Check the result.
If you don't know the package's name, please look at this question&answer. If you need any further help, please write a comment!
Comment: I downloaded the package with windows, not sure how to get it to ubuntu tty to load
Comment: The quickest way is to place that driver to a pendrive. If you connect it, it will mount somewhere to /media. Install 'mc' program(`sudo apt-get -y install mc`), and run it: `sudo mc /media` - it is very similar to Total Commander. Install that driver. I hope that's a .deb, than you can just run a command: `sudo dpkg -i NAME.deb; sudo apt-get install -f`

Low grahic mode 12.04


Do you need to trade Boldore to reduce the candy requirement for evolution to zero?

Question: In the original Pokemon games, there were several Pokemon that required a trade to evolve. Examples are Machoke (to Machamp), Haunter (to Gengar) or Boldore (to Gigalith). Niantic mimicked this behaviour by reducing the candy cost to zero to evolve certain Pokemon to their final evolution. In the original games, it requried you to trade Boldore. Trading Roggenrola (the first in the evolution line) would not evolve anything. How does this work in Pokemon Go, and which Pokemon are affected?
Answer: In Pokemon Go, it is a bit different implemented than the original series. I traded a Roggenrola with a friend (so not a Boldore), evolved the Roggenrola myself, and then evolved it freely to Gigalith. So you do not have to trade the form that gets the free evolution. It does not matter if you trade the Roggenrola or Boldore, both get a candy-free Boldore -> Gigalith evolve.
A list of the current Pokemon that have this free evolve after a trade are:

Kadabra
Machoke
Haunter
Graveler
Boldore
Gurdurr
Shelmet
Karrablast
Comment: This also applies to other Pokemon with a simple trade-to-evolve option like Kadabra. Curiously, it also works if the Pokemon was traded before the trade-to-evolve option became available.
Comment: @MBorg thanks. I expanded the question a bit, so I could include the list of all Pokemon that evolve like this
Comment: @MBorg [Niantic](https://pokemongolive.com/en/post/trade-evolution/) confirmed that Pokemon traded before trade evolution was released would be retrofitted and allow for free evolution :)


Prove that $\angle{EPF}$ is right angle.

Question: $D$ is any point on side $BC$ of $\triangle{ABC}$. Points $E, I, F$ are respectively the incentres of $\triangle{ADB},\triangle{ABC},\triangle{ADC}$. $P$ is the foot of perpendicular from $I$ on $BC$. Prove that  $\angle{EPF}$ is right angle.
I have two approaches to solve this question. first, since $\angle{EDF}$ is right angle, if we prove that quadrilateral $EFDP$ is cyclic then we are done. secondly, if $\angle{EPI}=\angle{FPC}$ then the question is solved. I tried both the approaches but I could not get the solution.
Comment: because $DE$ is internal bisector and $DF$ is external bisector(or vice and versa)
Comment: @use236182 now it is true for both the cases.
Answer: Fact#1) By considering tangent lengths, we have $a' = s – a$ where s = semi-perimeter of $\triangle ABC$.

Fact#2) By applying Fact-1 and by considering tangent lengths again, we have $I'J' = DK'$ with $I'D$ as the common portion.

Let O be the midpoint of EF. Then, O is the center of the circle EDF with OE = OD = OF.

Through O, draw $OM \bot E'F'$ cutting $E'F'$ at M. By intercept theorem, M is the midpoint of $E'F'$. Then, by Fact#2, M is also the midpoint of the common portion DP. These make OD = OP. Therefore, P is also a point on the circle EDF.
Comment: @MichaelRozenberg Thankyou.
Comment: Amazing solution! +1


Infinite dimensional reps of the rotation group

Question: $\mathbf{Background:}$
The following is paraphrased from ``Representations of the rotation and Lorentz groups and their applications,'' by Gel'fand.
Consider a finite-dimensional representation $T: SO_3 \to GL_n$ of the rotation group.  Label elements of $SO_3$ as $(\theta_1,\theta_2,\theta_3)$.  We have (for real $s,t$):
\begin{align}
T_{jk}[s \cdot (\theta_1,\theta_2,\theta_3)] \cdot T_{kl}[t \cdot (\theta_1,\theta_2,\theta_3)] = T_{jl}[(s+t)\cdot (\theta_1,\theta_2,\theta_3)]
\end{align}
Applying $\frac{d}{ds} \rvert_{s=0}$ to both sides (assuming $T$ is such that we can do this), we get:
\begin{align}
\theta_a \cdot A^a_{jk} \cdot  T_{kl}[t \cdot (\theta_1,\theta_2,\theta_3)] = \frac{d}{dt} T_{jl} [t\cdot (\theta_1,\theta_2,\theta_3)]
\end{align}
where:
\begin{align}
A^a = \frac{\partial}{\partial \theta_a} \rvert_{\theta_1 = \theta_2 = \theta_3 = 0}\ T[(\theta_1,\theta_2,\theta_3)]
\end{align}
The solution of these differential equations is:
\begin{align}
T_{jk}[t\cdot (\theta_1,\theta_2,\theta_3)] = (\exp [ t \cdot \theta_a \cdot A^a ])_{jk}
\end{align}
Setting $t=1$, we see that the representation $T$ is completely determined if we are given the matrices $A^1,A^2,A^3$.
$\mathbf{Question:}$
Consider an infinite dimensional rep $T : SO_3 \to C^\infty(\mathbb{R}^3)$.  Can the above argument be made rigorous in this case, with $A^1, A^2, A^3$ as differential operators?
One problem is that the equation
\begin{align}
\theta_a \cdot A^a \cdot  T[t \cdot (\theta_1,\theta_2,\theta_3)] = \frac{d}{dt} T [t\cdot (\theta_1,\theta_2,\theta_3)]
\end{align}
is no longer a system of (finitely many) ordinary differential equations.  Also, I'm not sure if $A^a = \frac{\partial}{\partial \theta_a} \rvert_{\theta_1 = \theta_2 = \theta_3 = 0}\ T[(\theta_1,\theta_2,\theta_3)]$ is well-defined.
Writing rotation vectors ($\theta_1,\theta_2,\theta_3$) in spherical coordinates instead of cartesian, Gel'fand gets, for instance, $A^z \sim \frac{\partial}{\partial \phi}$, where $\phi$ is the azimuthal angle.  That's what I'm trying to justify.
Answer: I don't know where gel'fands answer comes from; I believe that the initial equation should be placed by composition, wich generalizes matrix multiplication:
$$T(s \cdot (\theta_1,\theta_2,\theta_3))\circ T(t \cdot (\theta_1,\theta_2,\theta_3))=T((s+t) \cdot (\theta_1,\theta_2,\theta_3))$$
This time taking the derivative gives
\begin{align}
\theta_a \cdot A^a \circ  T[t \cdot (\theta_1,\theta_2,\theta_3)] = \frac{d}{dt} T [t\cdot (\theta_1,\theta_2,\theta_3)]
\end{align}
Where $A^a$ is given by the same equation. Does this sound right? If so, $A^a$ is a function and not an operator.
Comment: Note that T is now a function of six variables, three thetas and then three coordinatee for R^3.


Set of n dice are thrown...

Question: I need help with this question:
A set of n dice is thrown. All those that land on six are put aside and the others are again thrown. This is repeated until all the dice have landed on six. Let N denote the number of throws needed. Let $m_{n} = E[N]$.
Let $X_{i}$ denote the number of dice rolled on the ith throw. Find $E[\sum_ {i=1}^{N} X_{i}]$.
Here is a solution I was provided with but do not understand the reasoning behind it:
$E[X_{i}] = E[E[X_{i}|X_{i-1}]] = E[X_{i-1} - (X_{i-1}*(1/6))] = (5/6)*E[X_{i-1}] = n(5/6)^{i-1}$
Then, $E[\sum_ {i=1}^{N} X_{i}] = \sum_ {k=1}^{n} ([1-(5/6)^{k}]/(1/6))(k)P(N=k)]$.
Where, $P(N=1)=(5/6)^{n}$ and $P(N=2) = \sum_ {X=0}^{n-1} \binom {n}{x} (1/6)^{n} (25/36)^{n-x} = (31/36)^{n} - (1/6)^{n}$.
Could someone please explain this too me? I appreciate any help. Thanks
Comment: The first line (beginning with $E[X_i]$) makes sense. The second one doesn't. There's an unbalanced square bracket, it's unclear why $k$ has been placed in parentheses, and it seems unlikely that the same index $k$ is intended to run up to $n$, the number of dice, and simultaneously serve as a possible value of $N$, the number of throws.
Answer: This is a double counting question. Note that
$$\sum_{i=1}^N X_i = \sum_{i=1}^n N_i,$$
where $N_i$ is the number of times the $i$th die is rolled.
Try to finish the solution from here.

 The answer is $6n$.

Set of n dice are thrown...


how do i display a DataTable in a wpf window c#?

Question: I can't seem to find a clear solution for this here or google.
i basically have a DataTable that i added rows with data according
to my needs, and i want to display it as a table in a wpf Window.
Any ideas how?
Thanks in advance.
i tried this, but i got this exception: " System.NullReferenceException: 'Object reference not set to an instance of an object.'
ListViewData was null."
this is the method,and inside, the creation of the DataTable:
private void ShowAllPlayersbutton_Click(object sender, RoutedEventArgs e)
    {
        AllPlayersTable = new DataTable("test");
        AllPlayersTable.Columns.Add("Played games",typeof(int));
        AllPlayersTable.Columns.Add("Wins", typeof(int));
        AllPlayersTable.Columns.Add("Losses", typeof(int));
        AllPlayersTable.Columns.Add("Ties", typeof(int));
        AllPlayersTable.Columns.Add("Wins precentage",typeof(int));

        MsServiceClient proxy = new MsServiceClient(new InstanceContext(Callback));
        UserD[] usersArr = proxy.GetAllUsers();

        foreach(UserD uD in usersArr)
        {
            AllPlayersTable.Rows.Add(uD.PlayedGames, uD.Wins, uD.Losts, uD.Ties, uD.VictoryPercent);
        }

        DisplayUsersWindow displayWindow = new DisplayUsersWindow(AllPlayersTable);
        displayWindow.Show();

    }

this is the window's:
    public partial class DisplayUsersWindow : Window
{
    public DisplayUsersWindow()
    {
        InitializeComponent();
    }

    public DataTable Datas { get; set; }
    public DisplayUsersWindow(DataTable dataTable)
    {
        Datas = dataTable;
        ListViewData.ItemsSource = Datas.DefaultView;//<<<< exception happens here

    }

}

}
Comment: where is the InitilaizeComponent() method
Answer: The NullReferenceException occurs because you didn't initialize your window in the constructor that is taking the DataTable, meaning ListViewData is not set to an object. To fix it, just add a call to InitializeComponent():
public DisplayUsersWindow(DataTable dataTable)
{
    InitializeComponent();
    Datas = dataTable;
    ListViewData.ItemsSource = Datas.DefaultView;
}


Assertion error when trying to lemmatise text (python, StanfordNLP)

Question: I want to lemmatise text in one column of a data frame. My script seems to work with a short test data frame, but every time I try to run it on my actual project file, I get an assertion error. I think it may have to do with the length of the text, but am not sure how to deal with it.
My code:
import pandas as pd
import stanfordnlp
nlp = stanfordnlp.Pipeline(lang = "en", processors='tokenize,mwt,pos,lemma')

def lemmatize(text):
    '''lemmatize'''
    count = 0
    fout = open('text_lemmatized.txt', 'w+')
    doc = nlp(text)
    for sent in doc.sentences:
        for word in sent.words:
            word = word.lemma
            fout.write(str(word))
            fout.write(" ")
            count = count + 1
            fout = open('text_lemmatized.txt', 'r')
            text = fout.read()
            print(text)
            return text

lemmatizing = lambda x: lemmatize(x)

data = pd.read_csv("data.csv")
data_lemma = pd.DataFrame(data.text.apply(lemmatizing))
data_lemma.to_csv("lemma-text-en.csv")

The Traceback I get is:

Traceback (most recent call last):
    File "lemmatize.py", line 28, in
      data_lemma = pd.DataFrame(data_clean.corpus.apply(lemmatizing))
    File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/series.py", line 4042, in apply
      mapped = lib.map_infer(values, f, convert=convert_dtype)
    File "pandas/_libs/lib.pyx", line 2228, in pandas._libs.lib.map_infer
    File "lemmatize.py", line 25, in
      lemmatizing = lambda x: lemmatize(x)
    File "lemmatize.py", line 11, in lemmatize
      doc = nlp(text)
    File "/opt/anaconda3/lib/python3.7/site-packages/stanfordnlp/pipeline/core.py", line 176, in call
      self.process(doc)
    File "/opt/anaconda3/lib/python3.7/site-packages/stanfordnlp/pipeline/core.py", line 170, in process
      self.processors[processor_name].process(doc)
    File "/opt/anaconda3/lib/python3.7/site-packages/stanfordnlp/pipeline/pos_processor.py", line 31, in process
      for i, b in enumerate(batch):
    File "/opt/anaconda3/lib/python3.7/site-packages/stanfordnlp/models/pos/data.py", line 120, in iter
      yield self.getitem(i)
    File "/opt/anaconda3/lib/python3.7/site-packages/stanfordnlp/models/pos/data.py", line 91, in getitem
      assert len(batch) == 6

What seems to be the problem? If it's the length of the text, what could be an efficient way to deal with it? (I only have two cells in that column, but quite a lot of text in these two cells that needs to be lemmatised).
Thank you for any suggestions!
Answer: The error is happening in the Part-Of-Speech Tagger, pre-lemmatization. Try adding pos_batch_size as a parameter to Pipeline, and give it a number equal to or larger than your longest sentence. According to this Github issue,

If you tag sentences longer than pos_batch_size, method chunk_batches
  creates empty batches that subsequently trigger an assertion: assert len(batch) == 6

Update your code as follows, where max_sent_len is longer than your longest sentence:
max_sent_len = 4096
nlp = stanfordnlp.Pipeline(lang="en", processors='tokenize,mwt,pos,lemma', pos_batch_size=max_sent_len)

Note: I also use the depparse processor, and had to update depparse_batch_size as well.


Error page is not getting displayed

Question: Error page is not getting displayed. Below is my configuration.
[HttpGet]
public ActionResult Index(string name)
{
throw new ArithmeticException();
}

//Handle Error attribute
public override void OnException(ExceptionContext filterContext)
{
//logging
filterContext.ExceptionHandled = true;
base.OnException(filterContext);
}

<customErrors mode="On" defaultRedirect="~/Error">
      <error statusCode="404" redirect="~/Error/NotFound"/>
</customErrors>

I have placed "error" and "Notfound" views in "Error" folder. However, "Notfound" view is getting displayed if I type in invalid url. But for the arithmetic exception, default error page is not getting displayed, only blank page is displayed with same url. Could you anyone please suggest.
Answer: I'm not sure but, if you set filterContext.ExceptionHandled = true; then errorhandler will not redirect you to error page. So try remove it.
Comment: Thank you. Yes, that was missing statement.

Error page is not getting displayed


Rails validate based on associated record

Question: I have two classes, Deposit and Bid, which are associated as:
class Bid < ActiveRecord::Base
   belongs_to :deposit
end

and
class Deposit < ActiveRecord::Base
   has_many :bids
end

The depositions has a fixed amount which is set at creation. The bids also have amounts and I'm trying to use a validation to make sure that bid.amount is smaller than the deposits' amount that it belongs to.
I tried achieving this through:
class Bid < ActiveRecord::Base
    validates :amount, numericality: { only_integer: true, less_than_or_equal_to: self.deposit.amount }
end

But it gives me NoMethodError. I also tried using a codeblock but couldn't get that to work either. I'm guessing part of the problem is that the records are not fully created yet but I cannot find any information regarding the problem.
How should this kind validation based on associated record values be done?
Answer: By adding your own validation method with validate (note: singular).
class Bid < ActionRecord::Base
  validate :my_thing

  def my_thing
    unless self.my_condition
      errors.add :field, :message
    end
  end
end

See http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations
Comment: Thanks! Got the validation working. Cannot upvote because of low rep
Comment: This is fine unless the deposit is updated to a lower amount after the bid is validated. There also needs to be a corresponding validation on deposit so its amount can't be set below its bids. Then if the system needs to be bullet-proof you have to account for race conditions and use transactions.
Answer: As pduersteler says you can use a validation method. Here's the one that would specific to your question:
class Bid < ActionRecord::Base
  validates :amount, numericality: { only_integer: true }
  validate :amount_not_more_than_deposit_amount

  def amount_not_more_than_deposit_amount
    if amount > deposit.amount
      errors.add :amount, "cannot be greater than the deposit amount"
    end
  end

end

But when you validate on object based on the value in an associated object you must consider what happens if that associated model gets edited. In this case a bid amount should never be greater than the associated deposit amount, but what happens if the deposit that already has bids attached gets edited to a lower amount. ActiveRecord will allow this without any warnings or errors, so to prevent this when validating the Deposit you should also validate any associated Bids
class Deposit < ActiveRecord::Base
   has_many :bids
   validate_associated :bids
end

This way a deposit who's amount is set below one of its bids will be invalid. This will bring some extra robustness to the app.
The one way this can still fail is with a race condition. The amount of the deposit is being changed at the same time a bid is being created. The validation for Deposit checks the bids before the bid has finished being created so it is not accounted for, but the Bid is in the process of being created and its validation checks the amount in the Deposit before it gets changed. both validations pass then the bid is created and the deposit amount changed to be below that of the new bid, and the invalid state is created with no errors or warnings.
To avoid this you need to put a lock on the relevant record in the deposits table while the bid is being created or updated, and conversely you need to put a lock on all the relevant records in the bids table while a deposit is being updated.


16.04, kernel 4.15.0-33, Audio device: NVIDIA Corporation Device 10f1 - no sound

Question: When using kernel 4.15.0-33, then I have no sound on my computer
Sound is working if I start with kernel 4.4.0-134
Here are output showing that the Soundcard is not recognized by 4.15.0-33
Using "old" kernel 4.4.0-134
lspci -v

00:1b.0 Audio device: Intel Corporation 6 Series/C200 Series Chipset
  Family High Definition Audio Controller (rev 05)  Subsystem: Gigabyte
  Technology Co., Ltd 6 Series/C200 Series Chipset Family High
  Definition Audio Controller   Flags: bus master, fast devsel, latency
  0, IRQ 5  Memory at fbff8000 (64-bit, non-prefetchable) [size=16K]
    Capabilities:

aplay -l

device_list:270: no soundcards found...

Using "new" kernel 4.15.0-33
lspci -v

01:00.1 Audio device: NVIDIA Corporation Device 10f1 (rev a1)
    Subsystem: eVga.com. Corp. Device 6161  Flags: bus master, fast
  devsel, latency 0, IRQ 17     Memory at faffc000 (32-bit,
  non-prefetchable) [size=16K]  Capabilities:    Kernel
  driver in use: snd_hda_intel  Kernel modules: snd_hda_intel

aplay -l

The sound card is recognized (forgot to copy the exact output)

Anyone who could could fixing this issue?
Answer: I installed 18.04.1 and the sound is working with 4.15 kernel