Binding data to view using ngHandsontable

Question: I am using ngHandonstable directive and binding data as show below in my view:

<hot-table settings="{colHeaders: colHeaders, contextMenu: ['row_above', 'row_below', 'remove_row'], afterChange: afterChange, fillhandle : fillHandle}"
           rowheaders="true"  minsparerows="minSpareRows"    datarows="db.lens" height="300"    width="700">
    <hot-column data="code" title="'Code'" type="grayedOut" readonly></hot-column>
    <hot-column data="description" title="'Description'" width="250" type="grayedOut" readonly></hot-column>
    <hot-column data="lastCost" title="'Previous Price'" type="grayedOut" readonly width="100"></hot-column>
    <hot-column data="currentCost" title="'Current Price'" type="'numeric'" width="100" format="'0,0.00 '"></hot-column>
    <hot-column data="percentageChange" title="'% Increase'" type="'numeric'" width="120" format="'% 0,0.00'" fillhandle="vertical"></hot-column>
</hot-table>

In my controller, I have this code below:
 app.controller('plasticController', ['$scope', '$location',  'toaster', 'plasticService', function ($scope, $location,  toaster, plasticService) {
    $scope.minSpareRows = 0;
    $scope.colHeaders = true;
    $scope.fillHandle = true;

    $scope.db = [];
   var dataLoad2 = function() {
        plasticService.getPlastic().then(function(results) {
            $scope.db = results.data;
            $scope.totalItems = results.totalCount;
            $scope.currentPage = results.currPage;
            $scope.totalPages = results.totalPages;

        }, function(error) {
            //alert(error.data.message);
        });
    };

My view does not show any data from my controller. How do I push the data to the UI when the async call is complete with json data?
Answer: The attribute datarows should be db not db.lens as you have it currently
datarows="db"

Comment: @Sithelo Ngwenya The answer looks correct to me. Please accept it if it worked for you.


What heroes have voice lines when destroying arcade machines?

Question: In Hanamura, the attackers spawn inside a room full of arcade machines, which everyone proceeds to blow up. I have noticed that when playing as D.Va, she will say, "No one can beat my high scores" when destroying them. Are there any other heroes besides D.Va that have voice lines when destroying the arcade machines?
Comment: Are you sure those lines are triggered by D.Va destroying the machine, and not just her initial spawn in? Several characters make reference to the arcade machines at some point during the pre-game
Comment: They're *arcade* machines. Arqade is this website, arcade is a place with games things/class of games machine.
Comment: @Unionhawk it was an intentional spelling.
Comment: At least Genji also has an attack specific line for Hanamura that can play and irregular times. I don't think this necessarily means D.Va is responding to destroying the arcade machines.
Comment: @twobugs I've only heard it while she is destroying the machines. And I have played her on defense and she hasn't made the quote, so I believe it is from destroying them, though I could be wrong.
Answer: The quote is map specific but doesn't require you to break any arcades.
I'm saying this from both personnal experience and the fact that the source doesn't mention the specificity of destroying arcade booths.
So no heroes have voice line whilest destroying arcade machines.


How to create a recursive join in snowflake

Question: I have a query with a bunch of left joins to get a hierarchal list of managers for an employee. I know snowflake has a recursive functionality but having trouble following. Does anyone know how something like this can be written recursively?
select
    d1.employee_id,
    d1.employee_id1,
    d1.employee_id2,
    d1.employee_id3,
    d2.employee_id1 as employee_id4,
    d2.manager_name as employee_id4_name,
    d3.employee_id1 as employee_id5,
    d3.manager_name as employee_id5_name,
    d4.employee_id1 as employee_id6,
    d4.manager_name as employee_id6_name,
    d5.employee_id1 as employee_id7,
    d5.manager_name as employee_id7_name
from employees d1
left join employees d2
on d1.employee_id3 = d2.employee_id
and d1.report_effective_date = d2.report_effective_date
left join employees d3
on d2.employee_id1 = d3.employee_id
and d2.report_effective_date = d3.report_effective_date
left join employees d4
on d3.employee_id1 = d4.employee_id
and d3.report_effective_date = d4.report_effective_date
left join employees d5
on d4.employee_id1 = d5.employee_id
and d4.report_effective_date = d5.report_effective_date

Edit with what I've tried - and from my understanding the way I want this formatted doesn't seem possible? I'm looking to get an individual's manager hierarchy but with each manager in a new column.
What I tried was like this, but it would give me the hierarchy in rows and would require that I have an anchored query filtered to someone.
with cte as (
  select
    employee_id,
    employee_name,
    employee_id1,
    manager_name
  from employees
  where employee_name = <name>

  union all

  select
    employee.employee_id,
    employee.employee_name,
    employee.employee_id1,
    employee.manager_name
  from employees
  join cte
  on employee.employee_id = cte.employee_id1
)
select * from cte

Comment: Recursive queries are documented extensively in the Snowflake documentation (and elsewhere) - so what have you tried and what specific issue are you facing?
Answer: You are correct that you would get back rows instead of columns. You are also correct that you would need to anchor the query on someone, or some group. Consider, as an anchor, an employee that has no employee_id1 assigned (The top most person in the org, if I understand your data).
As for the "Data in rows" consider building a hierarchical path that you can split to an array or what-have-you:
with cte as (
  select
    employee_id as employee,
    employee_name,
    employee_id1 as manager,
    manager_name,
    CAST(employee_id AS VARCHAR(500)) as path,
    1 as depth
  from employees
  where employee_id1 IS NULL

  union all

  select
    employee.employee_id,
    employee.employee_name,
    employee.employee_id1,
    employee.manager_name,
    cte.path || '>' || employee.employee_id,
    cte.depth + 1
  from employees
  join cte
  on employee.employee_id = cte.employee_id1
)
select * from cte

Now you have the full path for the employee as well as the depth of that employee, which should help plenty.
Comment: Glad it was helpful. `path` and `depth` is something I add to nearly every recursive query I build. `Path` can be especially helpful to hold in a table as it allows you to query, in this case, every person that is aligned under a particular manager regardless of the level in the org of the employees or manager, with something as simple as `SELECT * FROM this_result_set WHERE path LIKE  '*45>*'`  "45" being the manager's id.


Infinite list with context propagation

Question: I want to build an infinite list, I tried using Data.List.iterate, but I need a context to be propagated (the context changes while propagated).
The Data.List.iterate is of type (a -> a) -> a -> [a]
I need something like ((a, context)->(a->context)) -> (a, context) -> [a]
Until now I only obtained [(a, context)] and I can't do map fst because I will get something like [1, 12, 123, 1234...] instead of [1, 2, 3, 4....].
Comment: Why `map fst` does not suit you? It precisely removes the context, and only that.
Comment: `fst` does but return pair's left element. If it does not return what you expected then your pair computation is wrong.
Answer: I think unfoldr is exactly what you want:
Prelude> import Data.List(unfoldr)
Prelude Data.List> :t unfoldr
unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
Prelude Data.List> let nrs = unfoldr (\n -> Just (n,n+1)) 1
Prelude Data.List> take 10 nrs
[1,2,3,4,5,6,7,8,9,10]

it works like this:
you have to give it a function which takes a state/context (the type b above) and either:

returns Just (output,newState) if you want to go on
return Nothing if you want to stop

so if you always return Just ... you get an infinite list of [output]s
Answer: Update: I missed the map fst comment in the question, yet I can't see why it's not producing the expected result.

You can use iterate and discard the context later:
iter :: ((a, context)->(a, context)) -> (a, context) -> [a]
iter f x = map fst $ iterate f x

Laziness makes the map not to be applied further than necessary. Just make sure that fst . f is strict in the context argument, so that this does not build up large thunks.
It can also be used inline, since it's quite short:
> take 15 $ map fst $ iterate (\(a,b) -> (b,a+b)) (0,1)
[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377]

Comment: based on the OPs last comment I think he knows this but he kind of wants the *very last* element (the fixpoint ;)) of this list
Comment: @Carsten Oh, I missed that... But I don't understand it.

Infinite list with context propagation


Can't custom Tab bar native-base

Question: I'm trying to custom the colors of my tab bar, but the colors aren't changing, I still have the default blue on my tab bar.
I'm using the 2.1.5 version of native-base.
I followed the examples on the V.2.0 documentation of native-base, used properties like tabBarBackgroundColor either on <Tabs> or <Tab> but got no results.
I have this code :
import React, { Component } from 'react';
import { Container, Content, Tab, Tabs, Header, TabHeading, Icon, Text } from 'native-base';
import PageTwo from '../pages/PageTwo';

export default class PageThree extends Component {
    render() {
        return (
            <Container>

              <Tabs
               textStyle='#ED9D19'
               tabBarUnderlineStyle='#ED9D19'
               tabBarIconContainerStyle='#ED9D19'
               tabBarBackgroundColor='white'>
                  <Tab
                  tabBarBackgroundColor={{backgroundColor : '#ED9D19'}}
                   heading={ <TabHeading><Icon name="camera" /><Text>Camera</Text></TabHeading>}>
                    <PageTwo/>
                  </Tab>
                  <Tab heading={ <TabHeading><Text>No Icon</Text></TabHeading>}>

                  </Tab>
                  <Tab heading={ <TabHeading><Icon name="apps" /></TabHeading>}>

                  </Tab>
              </Tabs>
            </Container>
        );
    }
}

As you can see, I tried to use different properties but no one seems to work, except for tabBarPosition which does.
Answer: I have tried this and it worked for me , i have added backgroundColor to TabHeading style={{backgroundColor : '#1B2443'}}
<Tab heading={<TabHeading style={{backgroundColor : '#1B2443'}}>
    <Text style={styles.textColor}>PRIVATE KEY</Text></TabHeading>}>
    <Text>Change tab color</Text>
</Tab>

Answer: I managed to resolve my problem by bringing a theming file, as suggested in the documentation, here is my code :
import React, { Component } from 'react';
import { Container, Content, Tab, Tabs, Header, TabHeading, Icon, Text, StyleProvider } from 'native-base';
import PageTwo from '../pages/PageTwo';
import getTheme from '../native-base-theme/components';
import commonColor from '../native-base-theme/variables/commonColor';

export default class PageThree extends Component {
    render() {
        return (

        );
    }
}

Right now, I just have to change the values in the commonColor.js file that I need.
However, I still don't understand why I can't change the properties directly in my code...
Comment: Which variables did u change for tab color?

Can't custom Tab bar native-base


Verifying installation: 'apt-cache policy' vs 'which'

Question: I have searched for every variation of this question for days and I have not been able to find a clear explanation therefore I come to the collective knowledge here in the hopes of resolving my installation questions on a Linux distro.
I have installed(or at least attempted to) a couple of packages from github and I think I may have installed them properly because when I use which <package> or <package> -h I can see the path (all are in /usr/bin/) and the commands associated with the correct programs, however, when I use apt-cache the packages cannot be found.
My question is this: what exactly is the difference in apt-cache policy, which, and using -h when checking the installation of packages? I installed each package slightly differently and neither of them I installed using the software center for Ubuntu.
For one package:
git clone "package.git"
make
sudo ln -s ~/path/to/package_clone /usr/local/bin/.

for another:
git clone https://github.com/package.git
cd pkg.dir/
sudo python setup.py install
pkg.dir -h

Comment: By the way, `type ` is also useful for this sort of thing, and will show functions, aliases, and bash builtins as well.
Answer: apt-cache is an information tool of the package manager apt/dpkg. It only has information about packages you installed through them (note that the Software Center is just a GUI front-end for them) i.e. regular .deb packages (including everything from the official repositories and PPAs).
If you install applications manually by either just copying their folders or running installation scripts or make commands, those are not regular packages and therefore not managed by the package manager. That's why apt-cache can not find any information about the packages - they simply are no packages at all.

The which command on the other hand is not related to packages, it simply shows you which executable would get run if you type a specific command by searching all directories specified in the $PATH environment variable for executable files of a matching name.
Answer:
By running apt-cache policy <package. You display an information about the priority selection of the named package.
The package in question must be installed by apt-get beforehand. It will not be aware of the packages you installed manually (for example with git command).
By running which command you ask your system what would be the exact path of a program if you tried to execute it.
Each user has a PATH environment variable defined which contains the list of the directories the OS will search (one by one) for the exact match of the program name you typed. You can display the value of PATH with the following command:
echo "$PATH"

You might get a result similar to: `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/snap/bin".
If you type:
which mail

The system will check:

does /usr/local/sbin contain mail? -- No.
does /usr/local/bin contain mail? -- No.
does /usr/local/bin contain mail? -- No.
does /usr/bin contain mail? -- Yes. So print /usr/bin.

It means if you tried to run:
mail

The system will run the /usr/bin/mail program.
The most common use of which command is to ensure you are running the correct version of a program in case you have several versions installed. Or verifying whether a program can be run at all.
By running a program with -h argument you in fact try to execute it. Depending on the exact implementation it might display help, for example:
mail -h

However, remember that -h is a customary argument, it is up to the program itself to respond. Not all programs display help with this argument, some might return an error, some might ignore and run, some might use it for a very different purpose.

There is no "official" way of verifying if a manually installed program is installed properly, but the two latter commands (which and trying to execute a program directly) will give you the best approximation.
Instead of help you might try running a program with --version (or -v) argument which is a customary way to ask an executed program to display its version.


get node name by partial text in javascript

Question: I need to seperate values before and after column(:).before column as key and after column as value
Ex:
Product Name: Product 15
Product code: 1234
if i search for product it should give product name and product code as key and product 15 and 1234 as value by using javascript

var text1=document.documentElement.innerHTML;
 var res = text1.match(/Product/g);

 for(j=0;j<res.length;j++)
 {
    console.log(res[j]);
 }

Product name: Product 15

product code: 1200

    product category : bag
Comment: I stuck in getting parent node of the partial text.how can i get that ?.also how to get complete text .
Comment: node name will differ .
Comment: values will not be in same li or span it will differ.
Comment: Your question and explanation is unclear. Please clarify it properly. Also, I'll keep my answer as reference. Hope it helps!
Answer: When you do document.documentElement.innerHTML;, you are retrieving HTML string from DOM and searching it. If you do this, it is difficult to go back to parent node as you do not have a node relation. You should look for necessary elements you need to search and loop over them to search.
Also, text1.match will search the pattern in text and give you matching words. Hence, you are only getting Product and not full sentence. Instead, use regex.test to check if string has the necessary word/pattearn. Also, run it over individual text and not in complete HTML string as you need the parent node.

var elements = document.querySelectorAll("li,span");
var regex = /product/i

for (var j = 0; j < elements.length; j++) {
  var text = elements[j].textContent;
  if (regex.test(text)) {
    console.log(text);
  }
}

Product name: Product 15

product code: 1200

 product category : bag
Answer:  var arr=[];
 $('li').each(function(item){var item_text = $(item).text().split(':'); arr.push({[item_text[0]]:item_text[1]})});

// show results
console.log(arr);

js
var options = document.getElementsByTagName('li');
var arr=[];
Array.from(options).forEach(function(item){var item_text = item.innerText.split(':'); arr.push({[item_text[0]]:item_text[1]})})

// show results
  console.log(arr);

Comment: I am asking in javascript not jquery.
Comment: If you are already using jQuery, you can use `$.each`. You do not need `Array.from`
Comment: Thanks. Corrected


Can a Tactical Insertion be destroyed by another player?

Question: I'm intrigued by Tactical Insertion. It seems it could be very fun in some game types. I've never really seen it used though, in game.
Can other players see your Tactical Insertion? If so can they destroy it?
Answer: A tactical insertion can be destroyed by an opponent when it's found. It can be found significantly easier with the 'hacker' perk.  In addition to that, enemy players will sometimes claymore or camp a tactical insertion for a free kill.  There is a 'cancel' tactical insertion button, but the actual functionality of it seems to be very flawed (so don't rely on it).
The power of the tactical insertion should not be underestimated though.  Specifically in tactical games (capture the flag comes to mind) you can lay your tactical insertion near your objective and muscle your way in.  I have also found it very useful in maps with questionable spawns (like Nuketown) as it can prevent you from getting repeatedly spawn killed.
Hope this helps!
Answer: Yes you can see them although they're really hard to see without hacker pro. And you can destroy them with lots of things.
They're mainly useful in objective based games.
A good example is demolition. What me and my team will often do is put out tactical insertions close to the bombs plant. This allows us to return back to defending/attacking the bomb more quickly.
Answer: They can see it; people with the Hacker perk can even see it highlighted.
In CoD: MW2, you could destroy them. I have never seen one in Black Ops, so I never could test it.
Answer: Yes and Yes on both questions.
Regarding fun/value: not so much. Maps are too small and respawn system is pretty borked right now for this feature to have any serious use.
Comment: When an enemy sees it is it glowing like it does from my point of view?
Comment: I don't think so, unless they have hacker perk. Not 100% sure though.


Ubuntu 18.10 GRUB2 wont recognize APFS filesystem

Question: Is there any way for GRUB2 to recognize the APFS filesystem for booting? If not is there a menu entry configuration that would allow manual loading of macOS?
Im suprised not to find anyone else having this issue. I guess everyone is using rEFInd? I'd prefer not to use rEFInd as GRUB was taking over half the time anyway which was probably due to the fallback.efi (which I don't want to bother with)
Ubuntu 18.10 is currently installed on a 256 Gb SD card and GRUB was installed to the unpartitioned primary macOS drive /dev/sda
Answer: APFS file system is currently not supported on Linux at all, there is only an experimental FUSE (not kernel) driver to mount it in read-only - https://github.com/sgan81/apfs-fuse an commercial driver by Paragon
So, there is obviously no support for APFS in GRUB2 too.
Comment: So GRUB and Linux kernel are separate, correct? That is, even with Paragon's driver, GRUB would still not recognize the APFS, right?
Comment: Yes, of course. Thing is that Grub uses Linux kernel code (partially) to make its use of various filesystems, but since there is no kernel support for APFS then GRUB dev have nothing to work with.
Commercial drive will grant you only ability to mount APFS partition for read\write.
Comment: Darn, is support for APFS something foreseeable? Or will devs just stick with the support for HFS for good?
Comment: I dont see even mention of APFS in GRUB2 mailing list and given that its quite fresh FS and Apple didnt posted (yet) any documents about its structure its very hard to predict anything.
Comment: Ahh I see, well thank you for all your insight - hope Apple will post soon
Answer: Just want to share with you all that I had both high sierra and Linux Mint on my old 2012 iMac and out of nothing I can't make use of the "alt/option" key command to choose High sierra (on that grey window at startup that is gone)
Now I can only use Mint. Grub never worked and couple weeks ago I understood why none of my moves worked.
Later on (like you all), I realized that (grub) UBuntu/Mint does not recognize APFS file system. And for some reason that screen is gone and no keyboard shortcut allows me to access the recovery mode to reinstall High Sierra...
What I am going to do is, take my ssd out take to someone whith HSierra installed back important recordings I have made that day and format the drive and install a HPSF+ File system so I can access files and make grub work.
Just use Mac OS for some few audio applications (professionally)
I don't believe that APFS file system will get supported that soon...


Number Theory: Show that $o_n(a)=m$ odd implies $o_n(-a)=2m$.

Question: I have this homework problem assigned but I'm confused as to how to solve it:
For $n>2$ and $a\in\mathbb{Z}$ with $\gcd(a,n)=1$, show that $o_n(a)=m$ is odd $\implies o_n(-a)=2m$.
(where $o_n(a)=m$ means that $a$ has order $m$ modulo $n$).
We were also given this hint: Helpful to consider when $o_p(-a)$ is odd and when it is even.
Thanks for any help!
Answer: Since $a$ has order $m$, by definition $a^m\equiv 1\pmod{n}$, but $a^i\not\equiv 1\pmod{n}$  if $1\le i\lt m$.
Note that $(-a)^{2m}\equiv 1\pmod{n}$. We show that no smaller positive power of $-a$ is congruent to $1$ modulo $n$.
Suppose to the contrary that there is a positive $k\lt 2m$ such that $(-a)^k\equiv 1\pmod{n}$. Note that $k$ divides $2m$. We cannot have $k=2m/3$, for then we would have $(-a)^{2m/3}=a^{2m/3}\equiv 1\pmod{n}$. But $m$ does not divide $2m/3$. Also, we cannot have $k\ne m$, since $(-a)^m=-(a^m)\equiv -1\pmod{m}$, and $-1\not\equiv 1\pmod{n}$m because $n\gt 2$.
So $k\lt m/2$. But then $a^{2k}=(-a)^{2k}\equiv 1\pmod{n}$. Since $2k\lt m$, this contradicts the fact that $a$ has order $m$.
Comment: Thank you very much, that makes a lot of sense.
Comment: You are welcome.
Comment: There is also the possibility that $k=\frac{2m}{3}$ (if $m$ is divisible by $3$), but that case is also easy to take care of.
Comment: @Dylan: Thanks for the $2m/3$ comment, dealt with.
Answer: Well, we have $a^m\equiv1\pmod{n}$.
Let the order of $-a$ be $k$, then $(-a)^k\equiv1\pmod{n}$
Then $(-a)^{2k}\equiv1\pmod{n}$ which means $a^{2k}\equiv1\pmod{n}$ so $m\mid2k$.
(1) $k={m\over2}$ is not possible since $m$ is odd.
(2) $k=m$, in this case $(-a)^k\equiv1\pmod{n}$ where $k$ is odd which means $a^k\equiv-1\pmod{n}$ contradicts $a^m\equiv1\pmod{n}$
(3) $k={3m\over2}$ is not possible since $m$ is odd.
(4) $k=2m$. This works and is the smallest.


Is there a limit to the number of holes bored in a joist?

Question: I already know that a hole bored in a sawn lumber joist cannot be within 2" of any edge or any other notch or hole. And that the hole can only be a maximum of 1/3 the depth of the member (International Residential Code 2012 R502.8). Given all this, is this a code compliant joist?

For more detail on the code used to determine the dimensions mentioned above, see this answer.

After doing more research, I've found sources that recommend not placing holes closer to each other than the maximum hole size. For example, in a 2x10 holes should be at least 3 5/64" away from each other.
Comment: _"Code or no, you know the inspector would reject."_ ...Well, that's not how it works. There are codes in place for safety and a building's structural integrity, and it's the inspectors job to enforce them. NOT make up his own.
Comment: Code or no, you know the inspector would reject. There is an implied obligation (and maybe an express general provision) to use sound building materials, and swiss cheese boards are obviously a material (pun intended) compromise of that obligation.
Comment: From what I can tell, that meets code. The subjective question remains as to whether it will pass inspection. Personally, I'd prefer all those holes to a single notch, anywhere.
Comment: Are we sure it's not [42](https://www.google.com/?gws_rd=ssl#safe=strict&q=the+answer+to+life+the+universe+and+everything)?
Comment: What you say is true speedy_petey - it might be semantically wrong, but it is generally the case that  the term 'inspector' is used in place of 'authority having jurisdiction' Either way, it is not safe to assume that the code being enforced is a published standard, unless you are certain that the AHJ has made no changes to that standard. In the USA the Government will often make laws for Federal lands that render any existing published codes null and void. Tester did not mention that the IRC solely and completely applied in his case. Thanks to his comment, we now know this is the case.
Comment: Electrical or building?
Comment: @bib There's nothing in NEC about notching and boring joists, that's all covered in building code. Specifically, International Residential Code applies for me.
Comment: @bib This is an extreme case, but where is the limit?
Comment: @bib - 33 is the limit.
Comment: Interesting Question, one I am keeping an eye on, for a definitive answer, however, the structures strength is coming from the edges of the material. You are mostly increasing the strength to weight ratio here. This is exactly what I did with my Off Road Trailers load beam (Metal I-Beam), and it seems to have stood the test of time. You will want to maintain at least 2" between holes though. So maybe the answer is the Length / # holes with 2" on either side?.  I personally would not trust that lumber could have that many holes... possibly double the 2" standard.
Comment: While not a practical question, I think this is a fun one. Sadly, I think @bib likely has the answer there "it's really up to the inspector"
Comment: Source for:  *2" of ANY edge* ?
Comment: @SpeedyPetey actually, it is how it works. If the inspector sees something that is too unusual, (like a knothole too close to the drilled hole,) he'll find a reason to reject it...and probably justified.
Answer: If there is nothing in the code of practice which specifies a limit to the number of holes, then there is no limit to the number of holes.
From an engineering standpoint, this is because a beam with holes in it can act like a truss (see e.g. the bailey truss). The minimum hole sizes and minimum spacing is to allow enough timber to act as the vertical/inclined "truss elements". Therefore if it is ok to have two large, closely spaced holes at any arbitrary position along the beam, then it is ok to have holes of that diameter and spacing the whole way along the beam.
Comment: OP's link should answer any code questions. Nice to have a civil engineer chime in on this one ;)
Answer: Structural engineer here. This answer is late, but better late than never.
Notches (cut-aways from the edge) have more requirements due to the flexural (bending) nature of beams: the upper and lowest most fibers of the wood member take the most stress and control the design strength of a beam. See the figure linked below for specific requirements, taken from the IRC.
While the hole locations are less strictly controlled in the IRC, you want to avoid them in the outer ~1/4 of the joist span, as that is where the maximum shear occurs which is designed using the bulk of the wood material, not just the top and bottom fibers like in flexure. I don't think this is codified anywhere, but it's a good rule of thumb.
In summary: Holes should be limited to D/3 in the middle (1/2) of the span  and I would limit holes to 1" or D/8, whichever is smaller (this is not codified, but is reasonable), for the outer (1/4) of the span. Holes should never be outside the middle (1/3) of a member. Weyerhaeuser recommends 2x[Hole Diameter] minimum clear distance between holes for their TJI products, which would be a conservative rule of thumb to apply moving forward. I also wouldn't drill holes above each another.
Comment: Professional input is definitely welcome! To address the question specifically, as I read your answer, it would be OK to bore a series of holes meeting the `D/3` size guideline, spaced `D/3` apart, in the center 1/2 of the joist, while a series of 1" max holes (spaced a minimum of ?? apart) could be bored in the outer 1/4 span. Is that correct? It would be good to [edit] that into your answer.
Answer: You need to provide more information before your question can be properly answered.
Yes, the location of the holes are code compliant.
But that is only 1 aspect of a code compliant joist.
As you know, meeting the limits on one section of code does not exempt you from the others.
--
Can you please provide:
The requirements for a joist used in the intended location. (Specific use center 1st floor or roof on a 3 story house is just 1 example that location of use could change the answer.)
The type of wood, and information about any treatments that is being used in the joist in enough detail to be able to determine its load bearing properties under the code that applies to lumber strength. (Oak vs Pine as an example)
The calculations used to determine that the holes in the joist do not have a negative effect on its strength. (Not only deadweight loading, but things like empty holes allowing for more rapid spreading of fire, will be critical)
I am sure there are other variables, but as only the IRC applies, these items are critical, and will hopefully allow you to be given an answer with a high degree of confidence.
Thanks
Comment: @xavier is correct. Yes, the Code May allow a hole placed in a certain position, but it doesn't mean you "should" if there's a knothole or check in the joist, not to mention draftstops, intermediate walls, duct hanger location, etc.   That's why allowable stress loads are used, not ultimate loads. Then, when someone "follows the Code" and drills a hole that "meets Code" But is adjacent to a giant knothole, there isn't a failure.


Loops with two arrays (or 2 dimension arrays) in python

Question: I have two arrays that I want to work with  and use in a calculation. The two arrays are:
 [50, 55, 60, 65, 70],
 [.00001, 10, 20, 30, 40]

I apply the the calculation, and I want the bottom array to give me answers across, and indexed by the top array. It should look something like this:
50     168.31     167.52     165.21     161.57     156.88
55     168.01     167.33     165.51     141.57     155.88
60     178.31     178.52     178.21     178.57     178.88
65     188.31     188.52     188.21     188.57     188.88
70     191.31     191.52     191.21     191.57     191.88

I have tried several things including using the statement
if vel in   [50, 55, 60, 65, 70,]:
    print ( some formula in here)

and I tried putting in a second loop with the bottom array but of course it didn't work because the print had to be outside the first loop OR the second array would print every time the inside loop was executed.
How could I fix this program?
UPDATE
Sorry guys I tried to simplify it because it seamed like the arrays were to large in and of themselves to fit on the page and format correctly when put into the matrix.   My fault... which I will attempt to fix now.
Oh and this whole program supposed to calculate the maximum length of a wire antenna given the takeoff angle of the signal(theta) and the velocity factor of the wire used (velocity)
First I had been trying to use two separate arrays the first one is:
[50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]  <--- Velocity
and the second one is:
[.00001, 10, 20, 30, 40, 50, 60, 70, 80, 89.9999]  <--- theta
Ok, now the two are related by the following equation:
wire length= ("{:3.2f}".format(WL_feet(freq)/(4*(100/velocity)-(Hamath.cos_d(theta)))),end=" ")
I tried to put both arrays into a loop but like I said before the last print statement was in the wrong place and of course it didn't work,
something like this:
for velocity in [50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]:
print("     ",end=" ")
`for theta in [.00001, 10, 20, 30, 40, 50, 60, 70, 80, 89.9999]:`

    `print ("{:3.2f}".format(WL_feet(freq)/(4*100/velocity),           -(Hamath.cos_d(theta)))),end=" ")`

`print(velocity)`

Unfortunately the editor changes the format of the text and messes up the white space and and flow making it harder read. I tried to use the editor to help format the program text.
So again I want the type of matrix shown above but of course with the entire contents of both arrays.
Hope this helps,
Poe
Comment: What is the role of `list2` in generating result `50 168.31 167.52 165.21 161.57 156.88`. I see the 0th index item is from `list1. But I am not clear about relationship between list 1 and 2
Answer: The array you have written is a 5 by 2 array, it is two dimensional. I think an easier way to do this problem is to have two different arrays, rather than one two dimensional array.
I also don't think you can end up with a 5 by 6 array with only two 5 by 1 arrays.


Netplan with 2 NICs each connected to a different gateway

Question: I'm a bit confused on how to configure my Ubuntu 18 server with two NICS using Netplan. Each NIC is on a separate subnet.  They are directly connected to separate router interfaces on the router (this is a SMB router so each interface is configurable as a different subnet).
So for example on my server I have two NICs named below with the appropriate information they need:
eth0 - 192.168.2.2/24
       gateway - 192.168.2.1
       dns - 192.168.2.1

eth1 - 192.168.22.2/24
       gateway - 192.168.22.1
       dns - 192.168.22.1

I was playing around with the source routing example at netplan.io, but its not quite what I want.  I don't want to route all outgoing traffic through just one interface.  I need to be able to route traffic out of eth0 through eth0's gateway and I need to be able to route traffic out of eth1 through eth1's gateway.
I'll let the router handle routing between the two subnets via firewall rules.  I just need Neplan to play nice with my two NICs and let me setup two subnets each with its own gateway information.  Any ideas?
Comment: Looks like this question for https://serverfault.com/ community.
Answer: Edit:  Unfortunately, my own answer is incorrect after further testing.
The way the below is setup, it's still routing all traffic destined for an external IP (internet traffic) through the eth1 device which is not want I wanted.  I needed traffic routed out of each NIC respectively.  So, if eth1 needs to get out to the internet, it needs to send those packets out of the gateway that is directly connected to eth1.  Likewise, if eth2 needs to get out to the internet, then it also needs to send its own packets to the directly connected gateway that is connected to eth2.
I ended up dumping Netplan and went back to standard networking tools (ifconfig and /etc/network/interfaces) and setup a routing table/policy that does want I want. I'll never go back to Netplan.  They made it way too complicated for what should be simple stuff.  I spent days trying to get Netplan to work only to give up on that abortion of an abstraction layer.  I'm leaving my incorrect answer below for documentation.
**** Wrong answer below ****
So it appears this seems to work:
ethernets:
eth0:
  addresses:
    - 192.168.2.2/24
  routes:
   - to: 0.0.0.0/0
     via: 192.168.2.1
     metric: 100
     table: 101
  routing-policy:
   - from: 192.168.2.0/24
     table: 101
eth1:
  addresses:
    - 192.168.22.2/24
  gateway4: 192.168.22.1
  nameservers:
    addresses: [192.168.22.1]

I was attempting to list a gateway4 for each NIC stanza and that was incorrect from what I've been reading.  One must setup static routes to 0.0.0.0/0 for the other NICs/subnets attached directly to different gateways.  You only need one gateway4 listing if you do it this way.
Hope this helps someone else in the future (or me when I need to set this up again a few years later and will have forgotten it).


Tensor product of two finitely-generated modules over a local ring is zero

Question:
If $R$ is a local ring and $M$ and $N$ are finitely generated $R$-modules such that $M\otimes N=0$ then how does it follow from Nakayama's lemma that either $M=0$ or $N=0$?

This is an exercise in Atiyah and Macdonald. The part I could not show in the hints is $({M{\otimes}_R N)}_{k}=0$ implies $M_{k}{\otimes }_{k} N_{k}=0$, where $k=R/\mathfrak m$ and $\mathfrak m$ is the maximal ideal of $R$.
Answer: From $M\otimes_RN=0$ we get $R/\mathfrak m\otimes_R (M\otimes_R N)=0$. Then it follows that $(R/\mathfrak m\otimes_R M)\otimes_{R/\mathfrak m}(R/\mathfrak m\otimes_R N)=0$. But $R/\mathfrak m\otimes_R M\simeq M/\mathfrak mM$ and similarly $R/\mathfrak m\otimes_R N\simeq N/\mathfrak mN$. Since $M/\mathfrak mM$ and $N/\mathfrak mN$ are $R/\mathfrak m$-vector spaces, it follows that $M/\mathfrak mM=0$ or $N/\mathfrak mN=0$, that is, $M=\mathfrak mM$ or $N=\mathfrak mN$, so by Nakayama we have $M=0$ or $N=0$.
Edit. For proving $$R/\mathfrak m\otimes_R (M\otimes_R N)\simeq(R/\mathfrak m\otimes_R M)\otimes_{R/\mathfrak m}(R/\mathfrak m\otimes_R N)$$ use the associativity and the following property of tensor product: $L\otimes_SS\simeq L$, where in this case $S=R/\mathfrak m$ and $L=R/\mathfrak m\otimes_RM$.
Comment: I'm looking for a counterexample (with $M$ or $N$ not finitely generated) where the implication $M = 0$ or $N = 0$ does not hold. Do you have any ideas?
Comment: associativity of different tensor product is not true, in that case it is true because the $R/m$ module is bi $(R/m, R)$ module.
Comment: @mathcourse: Take $R = k[\![x]\!]$, $M = k$, $N = \operatorname{Frac}(R)$. Then, $M$ is f.g., $N$ is not, $M \otimes_R N$ is zero because $M$ is torsion.


Proving that any submodule of a semisimple module has a simple submodule.

Question: Proving that any submodule of a semisimple module has a simple submodule.
To prove the above statement is it necessary and sufficient to show that any semisimple module has a simple submodule. That is because submodule of a semisimple module is semisimple
or we cannot do that because after proving the above statement only we are able to show that submodule of semisimple is semisimple
Comment: Just a minor correction: you need the submodule of the semisimple module to be non-zero.
Comment: which definition of semisimple are you using? because some of the definitions give it to you directly
Comment: Every submodule is direct summand. I was assuming this definition and showing that semisimple module is sum of simple modules.
Answer: Let $A$ be a semisimple module, i.e. every submodule is a direct summand. We first show that every submodule $B\subset A$ is semisimple. Suppose $C\subset B$ and $A=B\bigoplus D=C\bigoplus E$. We claim that $B=C\bigoplus B\cap E$. First, take any $b\in B\subset C\bigoplus E$ and write $b=c+e$, $c\in C, e\in E$. $e=b-c\in B$ so every $b\in B$ is the sum of two elements respectively from $C$ and $B\cap E$. We then prove that $B\cap E\cap C=(0)$
. This is obvious since $C\cap E=(0)$. Therefore, any submodule of $B$ is a direct summand. $B$ is semisimple.
Let's now show that $A$ always has a simple submodule. Take any $a\in A$. By Zorn's lemma, find a maximal $B\subset A$ where $a\notin B$. By definition, write $A=B\bigoplus C$.
We claim that $C$ is simple. Suppose $C$ has a proper submodule $D$. $C$ is also semisimple so $C=D\bigoplus E$. $A=B\bigoplus D\bigoplus E$. Note that $a\notin B\bigoplus D\cap B\bigoplus E$. Otherwise, write $a=b+d=b'+e$ so $(b-b')-e+d=0$. This relation is not possible since $B\bigoplus D\bigoplus E$ is a direct sum. We assume WLOG that $a\notin B\bigoplus D$. This is absurd since $B$ is maximal among submodules not containing $a$. So $C$ is indeed a proper simple submodule of $A$.
Answer: Seems simplest to directly prove submodules are semisimple.
Let $N$ be a submodule and $A$ be a submodule of $N$, and we will show $A$ has a complement in $N$. Of course, $A$ has a complement in $M$, say $A\oplus B=M$. Then (it is easy to check that) $M\cap N=(A\oplus B)\cap N=A\oplus(B\cap N)$, and since $B\cap N$ is a submodule of $N$, we have our complement.
Now we can go further and show a nonzero semisimple module necessarily contains a simple submodule.
Now if $m$ is a nonzero element of $M$, we can examine its cyclic submodule $mR$, which is necessarily isomorphic to $R/T$ for some right ideal $T$.  We know by Zorn that $R$ has a maximal right ideal $T_{max}$ containing $T$, and therefore that $mR$ has a maximal submodule $C=T_{max}/T$.  We know $mR$ is semisimple (because it's a submodule of $M$), so we can write $mR=C\oplus D$. Owing to $C$'s maximality, we know that $mR/C\cong D$ is a simple $R$ module.  So $D\subseteq mR\subseteq M$ is a simple submodule of $M$.
Comment: "*We know by Zorn that $$ has a maximal right ideal $$ containing ,*" that one? While I do see now I accidentally recycled $M$ for a maximal ideal, it is still not anything to do with $m$. I will pick a different symbol for the maximal ideal.
Comment: nice explaination, thanks a lot for clearing and just an edit, your maximal ideal is $m$ not $M$
Comment: @permutation_matrix I don't understand your suggestion. As I wrote, $m$ is a nonzero element of $M$, not a maximal ideal...
Comment: look after by zorn's lemma
Answer:
Assume $M$ is a semi-simple module and $M=\oplus _AT_{\alpha}$.If
$$0\rightarrow K\overset{f}{\rightarrow}M\overset{g}{\rightarrow}N\rightarrow 0$$ is a
$R$-module exact sequence, then it is  a split exact sequence. In fact, there exists $B\subset  A$ such that $N\cong \oplus _BT_{\beta}$ and $K\cong \oplus _{A\backslash B}T_{\alpha}$.

Proof:

$\mathrm{Im}~f$ is a submodule of $M$, so there exists $B\subset A$
such that $M=\mathrm{Im}~f~\oplus (\oplus _BT_{\beta})$. So the exact
sequence is split and $N\cong M/\mathrm{Im}~f\cong \oplus
> _BT_{\beta}$.
Furthermore, we can get $K\cong \mathrm{Im}~f\cong \oplus _{A\backslash B}T_{\alpha}$

Use the theorem, we can get every submodule and every factor module  of a semi-simple module are semisimple.
You may also refer to Anderson and Fuller's book: Rings and Categories of Modules.


Copying Multiline Text in JavaScript

Question: I know there are a lot of discussions out there about copy and pasting not working when there are multiple lines as it just pastes all on the same row.  I found a lot of fixes when using JQuery, but I am not using JQuery. Was wondering if somebody could help me out?  I am looking for it to paste like this
Copy1
Copy1
Copy1

instead of
Copy1Copy1Copy1

Thanks
<!DOCTYPE html>

<title>Central</title>

<meta name="viewport" content="width=device-width">

js
function GetCopy() {
var data = '
 \

 \
Title	 \
	 \
Verbiage	 \

 \

Row 1	 \
<input type="button" class="CopyButton" value="Copy" onclick="" />	 \
Copy Me 1
Copy Me 1
Copy Me 1	 \

 \

Row 2	 \
<input type="button" class="CopyButton" value="Copy" onclick="" />	 \
Copy Me 2
Copy Me 2
Copy Me 3	 \

 \

'
document.getElementById('Table').innerHTML =data; }

UPDATE - Here is my updated code that is not pasting correctly for me when I try to pull in a js table

js
function GetCopy() {
var data = '
 \

 \
Title	 \
	 \
Verbiage	 \

 \

Row 2	 \
<input type="button" class="CopyButton" value="Copy" onclick="" />	 \
Copy Me 1
 \
Copy Me 1
\
Copy Me 1
	 \

 \

Row 2	 \
<input type="button" class="CopyButton" value="Copy" onclick="" />	 \
Copy Me 2
\
Copy Me 2
\
Copy Me 3
	 \

 \

'
document.getElementById('Table').innerHTML =data; }

Comment: upt - Copy1 should be pasted as 3 different rows
Answer: You can simply use line breaks to separate the text and display it with white-space: pre-wrap to preserve whitespace instead of displaying all on one line. Additionally, you can use template literals (delimited by backticks) to easily create multiline strings without needing to use \ to escape the newline character.
Live Example:

window.onload = function() {

GetCopy();

var a = document.getElementsByClassName('CopyButton');

for (var i = 0; i < a.length; i++) {
  a[i].addEventListener('click', function() {
    var b = this.parentNode.parentNode.cells[2].textContent;

    copyToClipboard(b);

  });
}

}

function copyToClipboard(text) {
  var dummy = document.createElement("textarea");
  document.body.appendChild(dummy);
  dummy.value = text;
  dummy.select();
  document.execCommand("copy");
  document.body.removeChild(dummy);
}

function GetCopy() {
var data = `

Title

Verbiage

Row 1
<input type="button" class="CopyButton" value="Copy" onclick="" />
Copy Me 1
Copy Me 1
Copy Me 1

Row 2
<input type="button" class="CopyButton" value="Copy" onclick="" />
Copy Me 2
Copy Me 2
Copy Me 3

`
document.getElementById('Table').innerHTML =data; }
td {
  white-space: pre-wrap;
}

Paste Text Here:
<textarea></textarea>
Comment: Thanks so much I got it working now.  I used \n in the js table and allowed me to paste multiple lines.
Comment: sorry about that :)
Comment: Thanks so much for the response hev1.  I got this to work when the function GetCopy was on the HTML, but am unable to paste multiple lines when I have a .js table that loads on the page. Do I need to make some tweaks on the js file to make it paste correctly?
Comment: Please create a [mcve] in that case. However, I would recommend modifying your JavaScript to match the code I have provided as an example.
Comment: Dev1 - I updated my code at the top.  Thanks again for the help.
Comment: @RickD You haven't matched the code I used in my answer; you should be using literal line breaks instead of ``. That is the issue.
Comment: @RickD Happy to help. (Also, my username is "hev1".)

Copying Multiline Text in JavaScript


Is there an Android reference for common resource identifiers?

Question: Where can one find a list of resource identifiers for common Android elements and their attributes?
For example:
getResources().getIdentifier("status_bar_height", "dimen", "android")

Comment: You always have [android.R](https://developer.android.com/reference/android/R.html) Which work the same way as R but contains android's constants.
Comment: This question needs more upvotes. It's shame that in a lot of examples, even in the Android docs, we see code snippets like above with hardcoded values like "status_bar_height", but there is no documentation page describing all such constants and we must guess, search or imagine what there might be.
Answer: you can identify the commom resouces by using one of these methods.
Using xml for exemple set heigth to statusbar:
android:minHeight="?attr/actionBarSize"

Or by java code:
toolbarinfocasa.setMinimumHeight(android.R.attr.actionBarSize);


Splitting a 240v Outlet: Between a Heat Pump Dryer (3-4a) and Stove (typical use 17-18a max)

Question: Thank you for the help. Please feel free to tell me how I'll melt myself. But really I just want to use a low-power way to dry clothes while not using the stove.
Summary:
The dryer itself (heat pump) is low-amp (max < 3.5a @ 220v), and the stove that will share the outlet pulls ~17a with two burners set to max.
Details:
1 — Wall plug is 14-50
2 — Amps at the breaker
= 40a, dedicated, handlebar-tied
3 — Amps typically used by the dryer @ 220v: 3.2-3.5 amps max (measured on two friends' units).
4 — Stove amps / my max use:
Two burners use 17-18a total.
• Given the 80% rule: recommended max draw is ~7,500 watts / 32a at a time.
• The dryer running with two burners at max (won't use at the same time anyway) = ~20a
My concerns:
(1) If the dryer is made for a 30a service, would that pose an issue re: internal wiring somehow (despite the low 3 amp / 750w draw)?
(2) The outlet splitter is UL listed, made my a US company, manufactured in China (of course). Any bad ideas there?
I can't change the wall service or upgrade at the box, as I'm renting. Fortunately, it was renovated a couple of years ago, is a big building, is in a major city.
14-50 splitter I'm considering — www.amazon.com/dp/B079JPWSZT/
Comment: Splitting 220/240 is iffy best of times.  Doing it when renting is getting into illegal/lawsuit territory.
Comment: That splitter cord doesn't appear to be UL listed. Parkworld also sells a bunch of sketchy adapters that are a Bad Idea, such as 14-50P to three 5-15 outlets.
Comment: What 80% rule? Neither of these are continuous loads.
Comment: Thank you all, for the honesty. I won't do this if it's unsafe. I suppose my question is now: due to the splitter being a point of failure itself, and that the 30a washer would be on a 40a circuit (not a good idea absent a way to stop current to the dryer if it starts to encroach 20+ amps), it's an idea that could go wrong, and the wrong is big enough to be an issue.
Comment: I can't pay to have things rewired because I'm in a rental and won't be able to get permission. Otherwise I would love to do it right regardless of the cost. Looks like I'll spend $1500+ ($1k extra than the open-box 240v heat pump dryer) and get a 120v Miele model. Which is the only 120v I can find that's available in the US. Thank you again for educating me. Though I had a bias, and wanted it to work, I knew I had to understand better. You have all helped.
Answer: You have to do Load Calculations the official way
No, you don't get to "make up" your own method of provisioning circuits. You have to follow the official methods documented in NEC.

The dryer is provisioned based on the data on the nameplate, which indicates its operating amps or VA.  Heat pump dryers are entirely motor loads (but multiple motors) so NEC 230 applies. Hopefully the nameplate will state a minimum and maximum breaker size.  I do not believe a 125% derate is applied to dryers.
The range also has a nameplate.  You must run that through NEC 220.55 to compute the size of the circuit required, however if the documentation specifies min or max breakers that too must be respected.

We can help with these calculations if you post nameplate data.
It seems extremely unlikely that both accept the same circuit breaker size.
As such you will need a subpanel to give them independent power behind their own breakers. You're not allowed to under-fuse a range or dryer, but you are allowed to oversubscribe the subpanel.
Beware 3-wire connections
Note also that "classic" 3-prong connections for ranges and dryers are dangerous as all getout, because the 3rd wire *is not ground, it is neutral.  They tie the machine chassis to neutral, so when the neutral wire has a problem, it energizes the chassis of the machine and kills people - usually children who squeeze behind the dryer to fetch a ball or something, their muscles twitch madly but it doesn't push them out of contact because of the confined space.  What a way to die.
If you have 4-wire supply, by all means use it.
However if you are stuck with 3-wire connections, here's a trick.  Heat pump dryers don't need neutral.  Ranges don't need neutral. Ovens need neutral, but only for the oven light and sometimes electronic controls.  So try NOT hooking up neutral to the oven. If it still works (sans oven light) then you don't need neutral. Convert the 3rd wire to ground only and don't connect neutral.
In that case, the subpanel can be wired 3-wire with no neutral. Leave the neutral bar empty. Buy an accessory ground bar, paint it green in an obvious way, and use that for grounds. Remove the neutral bond. That way if some half-wit fits a 120V circuit later, it won't work.
Don't buy electrical gear mail order

14-50 splitter I'm considering — (link)

Well, Mr. Rockefeller, if you can afford that pricey thing you can afford to do the job properly.  Clearly, cost is no object.
The problem is, that item is certainly not UL listed, and is illegal to use in this case because it will put the 10-20A heat pump dryer on a 40/50A breaker.
But the universal problem with mail order electrical (aside from being wildly overpriced when it is legitimate) is that an awful lot of what is sold is dangerous junk straight from China. It's being sold direct mail because that bypasses our product-safety apparatus (UL, FTC, all that stuff).  Amazon protests that things in the Amazon Fulfillment Centers might ship to Mexico or the Virgin Islands, and FTC/CPSC has no standing to enforce Mexican codes. Then they say "well, if we shipped one to USA that was a clerical error by the 3rd party seller, who should have clicked the box to disable US sales".  The lawyers have every angle figured out. The consumer safety agencies have said flat out that they don't have the annual budget for a legal fight with Amazon.  But eBay, Banggood, wish.com, Aliexpress, all that is the same garbage.   And overpriced too, SMH, at least you'd think dangerous junk would be cheap.
Comment: @Eats Well, answers around here follow Code, and I certainly couldn't possibly tell you to build your own "octopus cord" using a 2-space subpanel as an enclosure and using a quadplex breaker therein. Nope, can't say that!
Comment: I love to learn, and not endanger myself or others. I really, really admire your restraint while detailing, with levity, why this would be a *bad* idea and how to do it correctly. I can't pay to have things rewired because I'm in a rental and won't be able to get permission. Otherwise I would love to do it right regardless of the cost. Looks like I'll spend $1500 ($800 extra) and get a 120v Miele model. Which is the only 120v I can find that's available in the US. Thank you again for educating me. Though I had a bias, and wanted it to work, I knew I had to understand better.
Comment: I'm so glad that you would never do that, because I would never call-in a favor with an IEEE doctorate friend so he can teach me a few more useful things about this. I'm very, very glad that you've saved him from spending time with me, on this breakered, subpanel, safe octopus cord. (But really, thank you, I'll likely just spend the extra $1k for the only 120v option available in north america).
Answer: The correct way to do this would be to install the appropriate circuits.
You didn't specify the brand or model of dryer, but I can guarantee that whatever it is, it's designed for use on a 30 amp or smaller circuit. You're putting it on a 40 amp circuit. If it has a fault, it could end up failing in unexpected ways such as catching fire, since the internals are all engineered to work with 30 amp over current protection.
This will probably 'work'. It is a risky choice, and you will be liable if it goes wrong.
Comment: Thank you for the clarity and honesty. I won't do this if it's unsafe. I'm just wondering if there's a way. And this is perhaps my biggest issue, seeing as how the breaker is meant to protect wires (and the LG 24" heat pump dryer is a 30a design). Is there a safe way to trip the circuit between the dryer and the splitter, if the amps pulled ever begin to exceed 20-30a?
Comment: How about a 120v dryer instead? The Miele TXI680WP is a heat pump dryer that you can plug in to a normal outlet. It's not cheap but compared to other heat pump dryers it's also not that expensive. Installation needs a drain and a wall outlet, that's it. Or you could go with an all-in-one washer/dryer. LG makes a couple, maybe Samsung does as well. Those hook up to the usual washer connections, with no extra connections needed for the dryer function. You put in dirty clothes, clean dry clothes come out.
Comment: This is exactly what I'm thinking. It's only a question because I had a line on an open-box LG, that's $1k less than the Miele — which is the only 120v dryer sold in the US, far as I can find. The issue with the all-in one is the chorus of people who say that they constantly break down and don't dry very well. But that really opens things up, if I can get over that aspect. Thanks again for your help — it's not the answer I'd hoped for but I feel much better educated now. I can't thank you all enough.
Comment: Two of my friends own the all-in-ones and love them. You just have to be realistic about how they behave: it takes a long time to do a load of laundry, you can't pack them full, and they do have a lot more stuff to go wrong on them. If you do small loads a little more often, do the loads overnight, and do maintenance like cleaning the filters, they can work great. And it's tough to beat the convenience.


converting 110V chandelier to 220V

Question: I have a Kathy Ireland chandelier bought in the US with 110V.  Can I use this chandelier in the Philippines having 220V Electricity?
Answer: Yes.
The bulbs required for most chandeliers are either the candelabra type, or Edison base type.  Just need to order some rated @ 220v.  Rewiring the chandelier is not necessary.
If using a dimmer, take note of the dimmers maximum wattage rating which here in the US are usually rated at 600 watts. 10 bulbs x 40 watt is 400 watts regardless if the voltage is 120V or 240V.

converting 110V chandelier to 220V


Camera unresponsive in Witcher 2; how can I get it unstuck?

Question: I'm playing the Prologue quest in Witcher 2 (via Steam). I've descended into the well, and drank the cat potion as the tutorial prompt suggested.
Everything went greyscale, I hear a heartbeat, and I see the red glowing outline of a human's skeleton/blood vessels in the distance, which I assume are the effects of this potion. Cool. So I'm walking around in the dungeon, and I drop down a hole in the floor to a lower level.
Suddenly my camera is stuck. I know the game itself isn't stuck because the potion countdown timer is still ticking. I still hear the heartbeat. I can see a dead body on the floor, and the red glowing outline is standing above it not moving.
I can still move Geralt around, but it's a little hard when the camera isn't following him. He can draw his sword and attack things (well, the air anyhow.) Attacking the red glowy person doesn't seem to help. According to the tutorial prompt, I can exit out of the potion's effect by meditating, but the ctrl hotkey that would allow me to access meditation appears to have no effect. Basically any command that would pop up a dialog or overlay isn't working -- inventory, character gen, journal, tutorial (tab), etc.

Thinking it might be a problem with the potion itself, I let the timer run out. The monochrome display effect disappeared, but my camera is still stuck. Turns out the red glowy thing was some sort of weird fish person -- I can't interact with them at all other than bump into them, and whacking them with a sword does nothing.

I can't quick save (F5 causes a message that says that I can't save here). There a really old thread on GoG that suggests reloading an old save, though the "stuck camera" described there doesn't quite match what I'm experiencing (they can't move at all; I can technically move I just can't see what I'm doing). I really don't want to lose my progress -- is there any solution to this other than finding a previous save that isn't bugged out?
I have no mods (does this game even have mods?) and this is my first play through. No customization of anything. Normal difficulty.
Answer: It indeed seems to be a rare problem, and whenever a solution is given, its fix, like you say, is to reload an old saved game. So, we have to look into possible indirect fixes.
To answer one of your other questions in the process - which might have been rhetorical - the game does have mods, and this one, called 'Enhanced Camera', changes the in-game camera, so I'd suggest installing that, and see if it changes anything. It will overwrite the default camera behaviour, so if that is where the bug lurked around, it ought to be dead now.
(According to this Projekt Red thread, that camera mod was taken from Rise of the Sword, which actually has a better implementation, so I'd suggest downloading the file from here, and only drag the folder characters/templates/camera (with the file camera_graph.w2beh) to your Witcher 2 installation folder).
If that fails, or alternatively, you might want to give 'Better Camera for Master Witcher Redux' a try. It's meant as an addition to 'Master Witcher Redux', but using only the camera_graph.w2beh file ought to work perfectly fine.
If this method fails, I might look for other options. Good luck!
Comment: I ended up having to go back several auto-saves to find one that didn't bug out in the same way at the same spot, which ended up having to redo the last 2/3 of the prologue. If it happens again I'll definitely try out one of those mods. (I try to do my initial play-through without mods, to get a feel for how the game was meant to be played.) Thanks!


D3.js Pie-chart: how to automatically create and assign gradual scale of colors based on my own categorization

Question: I hope the title is not too confusing, but I am having a hard time to formulate this problem in a clear way. I'll give it a try anyway. Firstly,
this is my pie chart, and this is my data:
DATA.CSV
voce;categoria;val2015
amministrazione;funzioni;404571081
sociale;funzioni;235251679
territorio e ambiente;funzioni;286164667
viabilità e trasporti;funzioni;144185664
istruzione;funzioni;168774925
cultura;funzioni;55868045
sport;funzioni;27219432
turismo;funzioni;9544845
sviluppo economico;funzioni;14790363
servizi produttivi;funzioni;4334
polizia locale;funzioni;99007202
giustizia;funzioni;12147068
anticipazioni di cassa;rimborso prestiti;304323808
finanziamenti a breve termine;rimborso prestiti;0
prestiti obbligazionari;rimborso prestiti;38842996
quota capitale di debiti pluriennali;rimborso prestiti;0
quota capitale di mutui e prestiti;rimborso prestiti;128508755
spese per conto terzi;altro;232661261
disavanzo di amministrazione;altro;0

This chart is supposed to show how the government allocates budget to different functions. Each data point is characterized by:

"voce": the function to which a part of the budget is allocated
"categoria": the macro-category of each expense. There are three of these: "funzioni"; "rimborso prestiti"; and "altro"
"val2015": the absolute value of money allocated to that function for year 2015

In my visualization I created two pies on top of each other. The innerPie divides the budget over the three macro-categories. The outerPie divides it over the 19 different functions.
I would like to assign a color to each macro-category (say green, red, and blue respectively). Then I would like to have all the functions of category to be colored in gradual shades of their macro-category's color.
For example, if "funzioni" gets green, then I would like the 12 functions that belong to that category to be gradual shades going from light-green to dark-green.
First, I thought I would assign colors manually. However, I could not find a color brewer that would provide twelve shades of a given color.
Then I thought I would alternate colors. If macro-category1 has green, then function1 would be light-green, function2 dark-green, function3 light-green and so on.. But some functions have an absolute value of 0 (i.e. for that year no budget was allocated to that function). Since these do not appear in the pie, two functions of the same color may appear next to each other. Here is the code:
var color = d3.scale.ordinal()
            .domain(["amministrazione", "sociale", "territorio e ambiente", "viabilità e trasporti", "istruzione", "cultura", "sport", "turismo", "sviluppo economico", "servizi produttivi", "polizia locale", "giustizia", "anticipazioni di cassa", "finanziamenti a breve termine", "prestiti obbligazionari", "quota capitale di debiti pluriennali;", "quota capitale di mutui e prestiti", "spese per conto terzi", "disavanzo di amministrazione"])
            .range(["rgb(116,196,118)", "rgb(35,139,69)", "rgb(116,196,118)", "rgb(35,139,69)", "rgb(116,196,118)", "rgb(35,139,69)", "rgb(116,196,118)", "rgb(35,139,69)", "rgb(116,196,118)", "rgb(35,139,69)", "rgb(116,196,118)", "rgb(35,139,69)", "rgb(251,106,74)", "rgb(103,0,13)", "rgb(251,106,74)", "rgb(103,0,13)", "rgb(251,106,74)", "rgb(116,196,118)", "rgb(0,68,27)"]);

var colorInner = d3.scale.ordinal()
            .domain(["funzioni", "rimborso prestiti", "altro"])
            .range(["rgb(0,68,27)", "rgb(203,24,29)" , "rgb(33,113,181)"]);

A solution would be to use three-shades for each macro-category. That would solve the problem, but I am looking for a more flexible solution.
Since I plan to add more years in my dataset, how can I make a function that:

Takes the macro-category's color as input
Counts the number of functions in that category with value bigger than 0
Assign x shades of colors to the functions

-----EDIT-----
Now that I created a color scale, I need to assign the colors to each path based on its category (for the macro-color) and its index (for the shade of macro color).
I tried two things but neither works.
var greenRange = ["rgb(199,233,192)", "rgb(0,68,27)"];
var redRange = ["rgb(252,187,161)", "rgb(103,0,13)"];
var blueRange = ["rgb(198,219,239)", "rgb(8,48,107)"];

OPTION 1
function draw () {

//(1) count the number of data points with value > in each category
var countFunzioni=0;
dataset.forEach (function (d) {if (d.categoria=="funzioni" && d.val2015>0) { countFunzioni += 1;}})

var countRimborso=0;
dataset.forEach (function (d) {if (d.categoria=="rimborso prestiti" && d.val2015>0) { countRimborso += 1;}})

var countAltro=0;
dataset.forEach (function (d) {if (d.categoria=="altro" && d.val2015>0) { countAltro += 1;}})

//(2) create a color method for each category based on a the count calculated above and the range I determined
var colorFunzioni = d3.scale.linear()
         .domain([0, countFunzioni])
         .range(redRange);

var colorRimborso = d3.scale.linear()
         .domain([0, countRimborso])
         .range(redRange);

var colorAltro = d3.scale.linear()
         .domain([0, countAltro])
         .range(blueRange);

//draw the chart
chart = d3.select("#visualizationInner")
      .append("svg")
      .attr("id", "visualization")
      .attr("width", w)
      .attr("height", h)
      .append("g")
      .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");

//draw and color the paths
var path = chart.datum(dataset).selectAll("path")
            .data(pie)
            .enter()
            .append("path")
            //(3) return the appropriate color method depending on the datum's category
            .attr("fill", function(d, i) {
              if (d.categoria=="funzioni") {return colorFunzioni(i);}
              else if (d.categoria=="rimborso prestiti") {return colorRimborso(i);}
              else if (d.categoria=="altro") {return colorAltro(i);}
            })
            .style("fill-opacity", 0.75)
            .attr("d", arc);
}

OPTION 2
function draw () {

//(1) same as above

//(2) create a color method that adapts to each category's count and range
  var color = d3.scale.linear()
        .domain([0, function (d) {
          if (d.categoria=="funzioni") {return countFunzioni;}
          else if (d.categoria=="rimborso prestiti") {return countRimborso;}
          else if (d.categoria=="altro") {return countAltro;}
        }])
        .range(function (d) {
          if (d.categoria=="funzioni") {return greenRange;}
          else if (d.categoria=="rimborso prestiti") {return redRange;}
          else if (d.categoria=="altro") {return blueRange;}
        });

////(3) return the appropriate color method depending on the datum's category
        .attr("fill", function(d, i) {return color(i);}

}
Answer: Pick a color and select a light shade and dark shade, this becomes your range.  Then, your domain is [0, N] colors.  For example, for green we could do:

var N = 12;
var greenRange = ['#cce0cc', '#001e00'];

var color = d3.scale.linear()
  .domain([0, N])
  .range(greenRange);

  d3.select('body')
    .append('div')
    .selectAll('.color')
    .data(d3.range(N))
    .enter()
    .append('div')
    .attr('class', 'color')
    .style('height', '50px')
    .style('width', '50px')
    .style('background-color', function(d,i){
      return color(i);
  })

Re-run this with a different N to get a feel for how it produces colors.
EDITS
I imagine option 1 isn't working because when you call return colorFunzioni(i); (or the others), i will be out of range.  What you really need is an index for each color.  Here's a quick refactor:
var countFunzioni = 0,
    countRimborso = 0,
    countAltro = 0;
dataset.forEach(function(d){
    if (d.categoria=="funzioni" && d.val2015>0){
        d.colorIdx = countFunzioni;
        countFunzioni += 1;
    } else if (d.categoria=="rimborso prestiti" && d.val2015>0){
        d.colorIdx = countRimborso;
        countRimborso += 1;
    } else if (d.categoria=="altro" && d.val2015>0) {
        d.colorIdx = countAltro;
        countAltro += 1;
    }
});

var colors = {};
colors.funzioni = d3.scale.linear()
    .domain([0, countFunzioni])
    .range(redRange);

colors.rimborso = d3.scale.linear()
    .domain([0, countRimborso])
    .range(redRange);

colors.altro = d3.scale.linear()
    .domain([0, countAltro])
    .range(blueRange);

Later:
...
.attr("fill", function(d, i) {
    return colors[d.categoria](d.colorIdx);
});

Comment: Thanks it was exactly what I needed but now I am stuck at the subsequent step. I edited the question above, any ideas?


Lunar logs me out when I switch to regular Minecraft launcher? (Minecraft java)

Question: So, for example, if I play on Lunar client, then I switch to the Minecraft launcher I'm logged out and have to log back in, then when I'm logged into the Minecraft launcher and switch to lunar client it logs me out of lunar client please help me find a fix.
Comment: I suggest not using lunar, its quite shady.
Comment: @valkyrie_pilot I would disagree because joining a single game of hypixel bedwars and pressing tab shows that 70% - 80% of people in-game are using Lunar. Not only that but it is really useful.
Comment: If all your friends jumped off a bridge, would you too? their privacy policy allows them to take a screenshot of your computer at *any* time
Answer: Currently I believe there is no fix, as I am also experiencing the same problem. Make sure your logging in with your email on lunar as I made that mistake before.
Answer: This happened to me. I would get logged out of normal launcher and Lunar, the fix for me was closing lunar with the X inside of the client not the premade windows one.
Answer: There is a fix: make a new lunar client directory that's not in <code>.minecraft</code>.
To do this, go into Lunar Client launcher, and open the settings. Change the "Launch Directory" by creating a new empty folder and click the choose that new folder in the Lunar Client Launcher.
Comment: Can you expand a little on this?


Segmentation Fault (Core dumped) Wt With Qt helloqt

Question: I Wrote before but the details was not explained.
I explain step by step what I do;

Witty installation Guide Ubuntu
I did in order what ever said in this page.
sudo apt-get install gcc g++ libboost-all-dev cmake make
sudo apt-get install libssl-dev libfcgi-dev
sudo apt-get install libpq-dev libmysqlclient-dev firebird-dev
sudo apt-get install libpng12-dev libgraphicsmagick1-dev libhpdf-dev libpng12-dev libpango1.0-dev mesa-common-dev
sudo apt-get install asciidoc libqt4-dev
sudo apt-get install doxygen graphviz
wget -c http://kent.dl.sourceforge.net/sourceforge/witty/wt-3.3.4.tar.gz
tar xvxf wt-3.3.4.tar.gz
cd wt-3.3.4
mkdir build
cd build
cmake ..
make
make -C examples

and Test helloqt.wt test
./helloqt.wt --http-port 10000 --http-addr 0.0.0.0 --docroot .

Every things work fine
and then I changed someline for Qt events loop working
// Needed when using WQApplication with Qt eventloop = true
#include <QApplication>

Dictionary::Dictionary(const WEnvironment& env)
  : WQApplication(env , true )
{
  /*
   * Note: do not create any Qt objects from here. Initialize your
   * application from within the virtual create() method.
   */
}

.
.
.
int main(int argc, char **argv)
{
  // Needed for Qt's eventloop threads to work
  QApplication app(argc, argv);

  return WRun(argc, argv, &createApplication);
}

still result is fine everything OK. eventloops( signal/slot working )
and I clean everything with
make clean

add line to cmakefiles.txt QtNetwork
.
.
.
IF(ENABLE_QT4)
  FIND_PACKAGE(Qt4 REQUIRED QtCore QtGui QtNetwork)

  IF(QT_FOUND)
    INCLUDE(${QT_USE_FILE})
  ENDIF(QT_FOUND)
ENDIF(ENABLE_QT4)
.
.
.

and also add to wtwithqt examples cmakelist.txt ${QT_QTNETWORK_LIBRARY}
  FIND_PACKAGE(Qt4 COMPONENTS QtCore QtGui QtNetwork )

  SET(QT_USE_QTNETWORK true)

  INCLUDE(${QT_USE_FILE})

to below
IF(COMMAND cmake_policy)
  CMAKE_POLICY(SET CMP0003 NEW)
ENDIF(COMMAND cmake_policy)

SET(BUILD_WTWITHQT true)
IF (NOT MULTI_THREADED_BUILD)
  SET(BUILD_WTWITHQT false)
ENDIF (NOT MULTI_THREADED_BUILD)
IF (NOT QT_FOUND)
  SET(BUILD_WTWITHQT false)
ENDIF (NOT QT_FOUND)

IF (NOT BUILD_WTWITHQT)

  MESSAGE(STATUS "** Not building wtwithqt example.")
  MESSAGE(STATUS "   wtwithqt example requires a Qt4 installation.")

ELSE (NOT BUILD_WTWITHQT)

  MESSAGE("\n\n " + ${QT_QTCORE_LIBRARY} + " \n" + ${QT_QTGUI_LIBRARY} + "\n" +  ${QT_QTNETWORK_LIBRARY} + "\n" +    ${QT_LIBRARIES}  + "\n\n" )

  FIND_PACKAGE(Qt4 COMPONENTS QtCore QtGui QtNetwork )

  SET(QT_USE_QTNETWORK true)

  INCLUDE(${QT_USE_FILE})

  SUBDIRS(lib)

  ADD_DEFINITIONS(-DWT_NO_SLOT_MACROS)

  QT4_GENERATE_MOC(${CMAKE_CURRENT_SOURCE_DIR}/QtObject.h
                   ${CMAKE_CURRENT_BINARY_DIR}/moccedQtObject.C)

  WT_ADD_EXAMPLE(helloqt.wt
    hello.C
    QtObject.C
    ${CMAKE_CURRENT_BINARY_DIR}/moccedQtObject.C
  )

  TARGET_LINK_LIBRARIES(helloqt.wt
    wtwithqt
    ${QT_QTCORE_LIBRARY}
    ${QT_QTGUI_LIBRARY}
    ${QT_QTNETWORK_LIBRARY}
    ${QT_LIBRARIES}
  )

  #
  # If you have Wt installed somehwere, you should use the
  # installed Wt header files for your own Wt projects.
  # e.g. INCLUDE_DIRECTORIES(/usr/local/wt/include)
  # instead of the following:
  #
  INCLUDE_DIRECTORIES(
    ${WT_SOURCE_DIR}/src
    ${CMAKE_CURRENT_SOURCE_DIR}/lib
    ${QT_QTCORE_INCLUDE_DIR}
    ${QT_QTNETWORK_INCLUDE_DIR}
    ${QT_INCLUDE_DIR}

  )

ENDIF (NOT BUILD_WTWITHQT)

and add to QTcpSocket to function below
QtObject.h
// This may look like C code, but it's really -- C++ --
#ifndef QTOBJECT_H_
#define QTOBJECT_H_

#include <QThread>
#include <QTcpSocket>

class Dictionary;

/*! \class QtObject
 *  \brief A simple Qt object with sample signal and slot.
 *
 * This simple object class demonstrates that the Qt signal/slot
 * mechanism may be used alonglisde Wt's signal/slot mechanism.
 */
class QtObject : public QObject
{
  Q_OBJECT;

public:
  QtObject(Dictionary *wt_, QObject *parent = 0);

  void passGreet(const QString&);

  QTcpSocket* socket;

signals:
  void greet(const QString&);

public slots:
  void doGreet(const QString&);
  void Connected();

private:
  Dictionary *wt_;
};

#endif // QTOBJECT_H_

QtObject.C file
 #include "HelloApplication.h"
#include "QtObject.h"
#include <QHostAddress>

QtObject::QtObject(Dictionary *wt, QObject *parent)
  : QObject(parent),
    wt_(wt)
{

    socket = new QTcpSocket();

    QHostAddress adr;

    adr.setAddress("192.168.0.2");

    socket->connectToHost(adr,17776);

    QObject::connect(socket,SIGNAL(connected()),this,SLOT(Connected()));

}

void QtObject::passGreet(const QString& name)
{
  emit greet(name);
}

void QtObject::doGreet(const QString& name)
{
  wt_->doGreet(name);
}

void QtObject::Connected(){

    std::cout << "\n\nCONNNECTED\n\n";
    emit greet(QString("QString"));
}

From this time
cml@cml-All-Series:~/wt-3.3.4/build$ make clean
cml@cml-All-Series:~/wt-3.3.4/build$ cmake ..
cml@cml-All-Series:~/wt-3.3.4/build$ make -j8
cml@cml-All-Series:~/wt-3.3.4/build$ make -C examples/wtwithqt

cml@cml-All-Series:~/wt-3.3.4/build/examples/wtwithqt$ ./helloqt.wt charts.wt --http-port 10000 --http-addr 0.0.0.0 --docroot .
[2015-Aug-22 10:34:04.692004] 3116 - [info] "WServer/wthttp: initializing built-in wthttpd"
[2015-Aug-22 10:34:04.693292] 3116 - [info] "wthttp: started server: http://0.0.0.0:10000"

when click on browser 0.0.0.0:10000
page is incoming and
socket emitting Connected() signals and Connected() SLOT Work
print screen to std::cout << "\n\nCONNNECTED\n\n";
and application
crashed. Segmentation fault and Core Dumped
I can not find what is wrong?
I Debug Qt Creator
WWebWidget.C file stopped there
    bool WWebWidget::canOptimizeUpdates()
    {
->      return WApplication::instance()->session()->renderer().preLearning();
    }

Qt Creator Debugger says ->
The inferior stopped because it received a signal from the Operating System.

Signal name :
SIGSEGV
Signal meaning :
Segmentation fault

Comment: Did you run it in a debugger?
Comment: how can i debug it? I don't know how debug it
Comment: run ldd ./helloqt.wt and found all necessary library
Answer: There talking about the solution
in my code I delete WText object after there is no fail seg fault...
this is not solution for me but I can use it
Answer: Wt::WApplication* app = Wt::WApplication::instance();

app->enableUpdates(true);

Wt::WApplication::UpdateLock uilock(app);

if( uilock ){
   button->setText("Test"); //Here is Editable Widget
   app->trigerUpdate();
   app->enableUpdates(false);
}

For a big work you lock application and
control if locked change any thing
ServerPUSH.c


rails 3 + jquery + ajax - dont discard flash upon ajax request which redirects

Question: Normally, I call flash.discard if my request is xhr. I do this as an after filter in the application controller.
However, I dont want to call flash.discard in the event that I have an ajax call which sets a flash and then redirects to another page.
How do I achieve this?
Answer: If I understood it right, you need to know if a response is a redirect. Create an after filter in application controller to check the response status.
<code>after_filter :discard_flash_message

def discard_flash_message
  if request.xhr? and response.status == :found
    //do not call flash.discard
  end
end
</code>
Comment: Flash is discarded when there is a js redirect because js redirect is not actually a redirect. I am doing a js redirect window.location = <%= path %>.
Comment: moreover, if i redirect_to on an xhr request, the flash is discarded. following is my after filter code: flash.discard if (request.xhr? and response != :found)


Finding the pdf of an estimator

Question: We have a set of unidimensional data, $X_1, \ldots , X_n$ drawn from the positive reals. We define a model for its distribution:
The data are drawn from a uniform distribution on the interval $[0, b]$. This model
has a single positive real parameter, $0 < b$.
now consider the estimator:
$$\hat \mu = \frac{x^{(n)}(n+1)}{2n}$$
where $x^{(n)}$ is the $n^{th}$ order statistic in the distribution of $X_i$. How do I go about finding the pdf of this estimator ?
Answer: The probability that the $N$th order statistic is less than $x$ is the joint probability of the union of mutually exclusive events where at least $k \geq N$ of the samples are less than $x$ but the remaining $n-k$ samples are greater than $x$ -- where there are ${n}\choose{k}$ different combinations satisfying this condition. The probaiblity of this union is a sum of probabilities for $k=N$ to $k=n$.
Assuming an iid sample of size $n$, the distribution function for $\hat{\mu}$ is
$$\mathbb{P} (\hat{\mu}\leq x) = \mathbb{P} (X_{(N)}\leq \frac{2nx}{n+1}) = \sum_{k=N}^{n} {{n}\choose{k}}\Big[F\Big(\frac{2nx}{n+1}\Big)\Big]^k\Big[1-F\Big(\frac{2nx}{n+1}\Big)\Big]^{n-k}$$ where F is the uniform distribution function
$$F(x) = \frac{x}{b} \ (0 \leq x \leq b)$$
Take the derivative with respect to x to find the density function.
$$f_{\hat{\mu}}(x) = n {{n-1}\choose{N-1}}\Big[\frac{2nx}{(n+1)b}\Big]^{N-1}\Big[1-\frac{2nx}{(n+1)b}\Big]^{n-N}\frac{2n}{(n+1)b}$$
You can prove that an order statistic distribution can be expressed as
$$\mathbb{P} (X_{(N)}\leq x)= F_{(N)}(x) = n {{n-1}\choose{N-1}}\int_{0}^{F(x)}t^{N-1}(1-t)^{n-N}dt$$
which makes the derivation of the density more apparent:
$$f_{(N)}(x)= F'_{(N)}(x)= n {{n-1}\choose{N-1}}\Big[F(x)\Big]^{N-1}\Big[1-F(x)\Big]^{n-N}f(x)$$
Comment: can you please also provide an intuitive explanation so as to how we arrived at the distribution function?
Comment: Hopefully that makes sense.
Comment: Yes that does make sense. But Is there any explanation for passing $2nx/(n+1)$ term into $F(x)$? Also Now if I try to find the expected value, I am guessing the integration bounds will not be $[0,b]$ any longer?
Comment: We have $\hat{\mu} \leq x$ iff $X_{(N)} \leq \frac{2nx}{(n+1)}$ because you rescaled the order statistic -- I am following your original notation where $n$ is the sample size and $N$ is the order statistic of interest.  You might just find the expected value of the unscaled order statistic and then multiply by the scale factor afterwards.  That would make it simpler.

Finding the pdf of an estimator


Transparent BufferedImage shows with a black background while painted on a JLabel

Question: I've got a BufferedImage which is created from a png file. When creating it I set the type to be TYPE_INT_ARGB which should give me a transparent image. When I use paintComponent inside a JPanel to paint the image, I get the image with a black background. I really need to get it transparent so any help will be useful. Here is the code for clarity:
public class ImagePanel extends JPanel {

    private static final long serialVersionUID = 1L;
    private BufferedImage image;

    public ImagePanel() {
        this.image = null;
    }

    public void createImage(String fileName) {
        this.image = ImageUtilities.getBufferedImage(fileName, this);
        this.repaint();

     }

    public void paint(Graphics g) {
        g.drawImage(this.image, 0, 0, this);
    }
}

Here is how I load the image:
public class ImageUtilities {

/** Create Image from a file, then turn that into a BufferedImage.
*/

   public static BufferedImage getBufferedImage(String imageFile, Component c) {
       Image image = c.getToolkit().getImage(imageFile);
       waitForImage(image, c);
       BufferedImage bufferedImage = new BufferedImage(image.getWidth(c), image.getHeight(c),
                    BufferedImage.TYPE_INT_ARGB);
       Graphics2D g2d = bufferedImage.createGraphics();
       g2d.drawImage(image, 0, 0, c);
       return(bufferedImage);
   }

And one last thing to add is that this ImagePanel is inside another Panel, if that has any significance.
Answer: Not sure if this will solve your problem, but:

override paintComponent instead of paint (http://download.oracle.com/javase/tutorial/uiswing/painting/closer.html)
consider to use the newer javax.imageio API
make sure the panel is not opaque (opaque = false)
Comment: The new IO API did the trick, though it would be nice to see a solution with the old method (if we assume the method I use is considered old), thanks :).
Answer: Are you restricted to using an older version of Java? Try using ImageIO.read(fileName) to load the image file.
Comment: As I said in the previous comment, the ImageIO.read did it, now just of curiosity I'll try and poke to see how it can be done the old way. Thanks :)
Comment: No worries :) If trying the old way, try opening the image using Toolkit.getDefaultToolkit().createImage("myimage.png") and just draw the returned image directly to the component rather than creating a BufferedImage first.
Comment: ok, but will I be able to perform image processing techniques on the image opened that way. I am writing an app for a demonstration to show how is blurring, sharpening, etc. performed in Java.
Comment: No, you wouldn't be able to dry into the Image object, you'd have to create a BufferedImage if you wanted to draw into it.
Answer: Try this (i.e. setComposite()):
g2d.setComposite(AlphaComposite.SrcOver);
g2d.setPaint(backgroundColor);
g2d.fillRect(0, 0, w, h);


arangodb aql effectively tarversing from startvertex through the endvertex and find connection between them

Question: i'm very new to graph concept and arangodb. i plan to using both of them in a project which related to communication analysis. i have set the data to fit the need in arangodb with one document collection named object and one edge collection named object_routing
in my object the data structure is as follow
{
  "img": "assets/img/default_message.png",
  "label": "some label",
  "obj_id": "45a92a7344ee4f758841b5466c010ed9",
  "type": "message"
}
...
{
  "img": "assets/img/default_person.png",
  "label": "some label",
  "obj_id": "45a92a7344ee4f758841b5466c01111",
  "type": "user"
}

in my object_routing the data structure is as follow
{
  "message_id": "no_data",
  "source": "45a92a7344ee4f758841b5466c010ed9",
  "target": "45a92a7344ee4f758841b5466c01111",
  "type": "has_contacted"
}

with _from : object/45a92a7344ee4f758841b5466c010ed9 and _to : object/45a92a7344ee4f758841b5466c01111
the sum of data for object is 23k and for object_routing is 127k.
my question is, how can i effectively traversing from start vertex through the end vertex, so that i can presumably get all the connected vertex and its edge and its children and so on between them untill there is nothing to traverse again?
i'm afraid my question is not clear enough and my understanding of graph concept is not in the right direction so please bear with me
note : bfs algorithm is not an option because that is not what i need. if possible, i would like to get the longest path. my arangodb current version is 3.1.7 running on a cluster with 1 coordinator and 3 db servers
Comment: What is the outcome you want from the query traversal? Do you want to find all possible edges between two vertices, or all possible vertices?  Have a look at [the traversal page](https://docs.arangodb.com/devel/AQL/Graphs/Traversals.html) on the ArangoDB web site and see if that helps. The command will give you an array of vertex documents and an array of edge's. You can still filter that result with something like `FILTER LAST(vertex).obj_id == 'something'` where the `LAST` value of the array of vertices will be the originating vertex for an `INBOUND` traversal path. What are you needing?
Comment: hi @DavidThomas sorry for the late reply, i think it is "find all possible edges between two vertices", with that i can also have all possible connected vertices between the given two vertices, no? the output i want is all connected vertices and edges between two given node, so that i can draw graph with the result and hopefully tell end user that if the two given vertices is somewhat connected in any way
Comment: but i am unsure how to accomplish this, is this can be achieved by implementing some algorithm? or just by using graph traversal only is enough in arangodb? once again, any pointer would be very helpful
Answer: It is worth trying a few queries to get a feel for how AQL traversals work, but maybe start with this example from the AQL Traversal documentation page:
FOR v, e, p IN 1..10 OUTBOUND 'object/45a92a7344ee4f758841b5466c010ed9' GRAPH 'insert_my_graph_name'
  LET last_vertex_in_path = LAST(p.vertices)
  FILTER last_vertex_in_path.obj_id == '45a92a7344ee4f758841b5466c01111'
  RETURN p

This sample query will look at all outbound edges in your graph called insert_my_graph_name starting from the vertex with an _id of object/45a92a7344ee4f758841b5466c010ed9.
The query is then set up to return three variables for every path found:

v contains a collection of vertices for the outbound path found
e contains a collection of edges for the outbound path found
p contains the path that was found

A path is consisted of vertices connected to each other by edges.
If you want to explore the variables, try this version of the query:
FOR v, e, p IN 1..10 OUTBOUND 'object/45a92a7344ee4f758841b5466c010ed9' GRAPH 'insert_my_graph_name'
  RETURN {
    vertices: v,
    edges: e,
    paths: p
  }

What is nice is that AQL returns this information in JSON format, in arrays and such.
When a path is returned, it is stored as a document with two attributes, edges and vertices, where the edges attribute is an array of edge documents the path went down, and the vertices attribute is an array of vertex documents.
The interesting thing about the vertices array is that the order of array elements is important. The first document in the vertices array is the starting vertex, and the last document is the ending vertex.
So the example query above, because your query is set up as an OUTBOUND query, that means your starting vertex will always be the FIRST element of the array stored at p.vertices' and the end of the path will always be theLAST` element of that array.
It doesn't matter how many vertices are traversed in your path, that rule still works.
If your query was an INBOUND rule, then the logic stays the same, in that case FIRST(p.vertices) will be the starting vertex for the path, and LAST(p.vertices) will be the terminating vertex, which will be the same _id as what you specified in your query.
So back to your use case.. if you want to filter out all OUTBOUND paths from your starting vertex to a specific vertex, then you can add the LET last_vertex_in_path = LAST(p.vertices) declaration to set a reference to the last vertex in the path provided.
Then you can easily provide a FILTER that references this variable, and then filter on any attribute of that terminating vertex. You could filter on the last_vertex_in_path._id or last_vertex_in_path.obj_id or any other parameter of that final vertex document.
Play with it and practice some, but once you see that a graph traversal query only provides you with these three key variables, v, e, and p, and these aren't anything special, they are just arrays of vertices and edges, then you can do some pretty powerful filtering.
You could put filters on properties of any of the vertices, edges, or path positions to do some pretty flexible filtering and aggregation of the results it sends through.
Also have a look at the traversal options, they can be useful.
To get started just make sure your have your documents and edges loaded, and that you've created a graph with those document and edges collections in it.
And yes.. you can have many document and edge collections in a single graph, even sharing document/edge collections over multiple graphs if that suits your use cases.
Have fun!
Comment: hi @David, thanks for keeping up with me! i tried your query but it keeps executing and not giving any result, why is it took long time? any suggestion to make it faster? it is almost a half hour and the query still did not giving any result
Comment: Make sure you have at least a Hash index on any column that you do a equality test on, so if you do a test on `.obj_id` make sure you have an index on that attribute. That can make a huge difference, use the explain feature in the UI to ensure your index is being used.


JQuery Accordion Activation

Question: Is there another way to activate an accordion menu besides the
.accordion('activate', indexval);  method? In IE7 this changes my header DIV formatting (it smashes it). The accordion is at the base of the page so when it is activated my header disappears. Can anyone offer me some help with this?
Here's what I have.. The the activation is causing top header div to disappear.
 var targetOffset = $('.HwContentInformation').offset().top;
                $('#content,#header').animate({ scrollTop: targetOffset }, .5);

                $("#HwReferences").accordion('activate', 0);

Thanks
Nick
Comment: Provide a demo, or code.
Comment: Yup, we are fighting in the dark without a demo, unless you expect us to try and recreate it..!
Comment: Here's an example. Basically I am auto scrolling to the activating accordion and then activating it. When the accordion expands (activates) my header is squished.
Comment: I should note: It only happens when I activate the accordion programmatic. If I click on the accordion header it expands and all formatting is fine.
Answer: Turns out that my content page had some faulty Javascript that was subtracting the height of the header from the content area. This was setting the header to '0' thus hiding it when the page refreshed. Thanks for the attempt.
Answer: I once had a similar problem, by default accordion will use
 tags for it's header elements.  Your page header probably has an
 tag in it that you aren't expecting to be in the accordion.
What you could do, is change the headers in #HwReferences to
 and then do something like this:
$("#HwReferences").accordion({'header': 'h5'}).accordion('activate',0)

HTH
Comment: Thanks for the attempt but the header does not actually contain a  of any type.

JQuery Accordion Activation


android widget button crashes

Question: i am doing a widget that has 3 buttons. i need to call a function for every button. i am doing like this:
<code>public class myWidget extends AppWidgetProvider {

@Override
public void onReceive(Context context, Intent intent) {

    final String action = intent.getAction();
    if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
        final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
            this.onDeleted(context, new int[] { appWidgetId });
        }
    } else {
  // check, if our Action was called
         if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
                String msg = "null";
                try {
                    msg = intent.getStringExtra("msg");

                    if(msg.equals("nextpage"))
                        callFunction1();

                    if(msg.equals("prevpage"))
                                       callFunction2();

                    if(msg.equals("ref"))
                                         callfunction3();
                } catch (NullPointerException e) {

                }
         }

        super.onReceive(context, intent);
    }
}

@Override
public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds ) {

    remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
    this.appWidgetManager = appWidgetManager;
    thisWidget = new ComponentName(context, SteauaWidget.class);

    Intent active = new Intent(context, MyWidget.class);
    active.setAction(ACTION_WIDGET_RECEIVER);
    active.putExtra("msg", "ref");

    PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 1, active, 0);

    remoteViews.setOnClickPendingIntent(R.id.button3, actionPendingIntent);

    Intent nextPage = new Intent(context, MyWidget.class);
    nextPage.setAction(ACTION_WIDGET_RECEIVER);
    nextPage.putExtra("msg", "nextpage");

    PendingIntent pendingNextPage = PendingIntent.getBroadcast(context, 2, nextPage, 0);

    remoteViews.setOnClickPendingIntent(R.id.button2, pendingNextPage);

    Intent prevPage = new Intent(context, MyWidget.class);
    prevPage.setAction(ACTION_WIDGET_RECEIVER);
    prevPage.putExtra("msg", "prevpage");

    PendingIntent pendingPrevPage = PendingIntent.getBroadcast(context, 3, prevPage, 0);

    remoteViews.setOnClickPendingIntent(R.id.button1, pendingPrevPage);

}
</code>
but my widget crashes with this message in the logcat:
java.lang.RuntimeException: Unable to start receiver my.widget.MyWidget: java.lang.NullPointerException
what is the problem?
Comment: Can you tell me what line the null pointer is?  Post the actual logcat.  If there is nothing there, I would put LOG messages in and see where it is crashing.
Answer: Kaediil is right, you've got to narrow down the failure point by placing Log.d() statements throughout your code. I see quite a few places where a pointer could still be null and thus throwing the error. The line:
thisWidget = new ComponentName(context, SteauaWidget.class);
looks weird. Also, since the error specifically mentions
my.widget.MyWidget it stands to reason that MyWidget.class is not getting instantiated correctly or isn't given time to finish loading thus producing the following NullPointerException.

android widget button crashes


How to implement the New Android 11 Double Tap Back Gesture, on Flutter application?

Question: I would like to use the the new android 11 double tap back gesture, on my app which I'm working on. I got this idea from an app Tap, Tap Github Repository. I tried to find some related package in https://pub.dev, but I guess I couldn't get the right keyword to find it.
Any Help will be appreciated, thanks in advance.
Edit: After some research, I found that this android 11 feature is available under accessibility, so maybe it available in flutter accessibility widgets
Answer: I think I finally, figured it out. We can use the gyro sensor and accelerometer to achieve the same result, but I guess it will be less accurate. Further more we all also use Machine Learning to  increase the accuracy of the double tap feature.
Hope this answer will help my curious fellow developers.
Answer: I recommend this dependency library to you, it supports the following functions and is simple and lightweight
https://pub.dev/packages/flutter_close_app

✅ Press back 2 times to close app

✅ Custom time interval
✅ Customize the prompt message
✅ Customize matching conditions
✅ Support Android

✅ One click to close app

✅ Support iOS
✅ Support MacOS
✅ Support Windows
✅ Support Linux