DIY shower install

Question: I am in the process of finishing my basement. I will be installing a 32x60 shower pan. Walls are already framed out and plumbing is roughed in. I will be using Hardiebacker. I have a few questions:

The pan instructions recommend a 1/4" gap between the pan and Hardiebacker. Is this filled with thinset mortar or silicone?

Is Hardiebacker OK installed on ceiling to be painted?

Assuming no gaps between Hardiebacker panels or corners and all panels are butted up tight right everywhere, I use thinset mortar and alkali tape on seams and screws, correct? Same process for the niche?

Then I will be two coating everything with Redgard or a similar product.

Any additional tips or suggestions?
Comment: Just a thought - the Hardiebacker has a texture on it. That texture will show through the paint unless you skim coat it with plaster, thinset, or something. If you _want_ the pattern, I believe you're fine, but if not, you'll have to coat it with _something_.
Answer:
The pan instructions recommend a 1/4" gap between the pan and Hardiebacker. Is this filled with thinset mortar or silicone?

Neither, leave this gap open. See image here from FamilyHandyman.com showing the different layer elements.

Is Hardiebacker OK installed on ceiling to be painted?

Yes, but you still need to finish it like a normal ceiling (mud, texture, paint) and this is generally considered overkill considering how heavy it is and more expensive than drywall. Typically moisture-resistant drywall would be used for non-tile areas like above tile and the ceiling.

Assuming no gaps between Hardiebacker panels or corners and all panels are butted up tight right everywhere, I use thinset mortar and alkali tape on seams and screws, correct? Same process for the niche?

I have not used Redgard but a quick search revealed you can tape and thinset the seams, and don't need to do anything to the screws. I did find a warning that "hardiebacker is thirsty" and you may have better luck "priming" the hardiebacker with a thinned-out Redgard before applying the actual coat to prevent it from sucking all the moisture out.

DIY shower install


Execute multiple tests in the same context managers

Question: I have a test setup like this:
def test1():
    with Manager1() as m1, m1.get_m2() as m2:
        do_test1(m1, m2)

def test2():
    with Manager1() as m1, m1.get_m2() as m2:
        do_test2(m1, m2)

which I run with nosetests. Now it turns out that the context managers' __enter__() and __exit__() methods are expensive, so I would like to change to a setup like:
def test():
    with Manager1() as m1, m1.get_m2() as m2:
        do_test1(m1, m2)
        do_test2(m1, m2)

but I would like nose to still report separately for each test. I looked into module level and class level setup() and teardown() methods, but they don't seem to provide the same guarantees for cleanup in the case of exceptions. Is there a clean way to get nose to collaborate with context managers?
Answer: Have a look at nose test generation. It might work if you change the code to use yield, something like:
from nose.tools import nottest

@nottest
def do_test1(m1, m2):
    m1.write('do_test1 f1')
    m2.write('do_test1 f2')

@nottest
def do_test2(m1, m2):
    m1.write('do_test2 f1')
    m2.write('do_test2 f2')

def test():
    with open('f1.txt', 'wb') as m1, open('f2.txt', 'wb') as m2:
        yield do_test1, m1, m2
        yield do_test2, m1, m2

Running tests gets you:
$ nosetests context.py -v
context.test(<open file 'f1.txt', mode 'wb' at 0x06A5BF40>, <open file 'f2.txt', mode 'wb' at 0x06A5BF98>) ... ok
context.test(<open file 'f1.txt', mode 'wb' at 0x06A5BF40>, <open file 'f2.txt', mode 'wb' at 0x06A5BF98>) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.004s

OK

Comment: Thanks, this is a good idea but I suppose I will lose the capability to selectively run a single test like: `nosetests tests.py:test1`, which I would also like to keep. Or do you have an idea how to preserve that as well?
Comment: Also, have a look at  http://nedbatchelder.com//blog/201508/using_context_managers_in_test_setup.html
Comment: Thanks for the link, but the show-stopper comes at the end: "One caveat about this technique: a context manager's `__exit__` method can be called with information about an exception in progress. The mechanism shown here will never do that." It seems `ExitStack` is just the way to use context managers _with_ correct exception handling if some library like `nose` prevents us from using a `with` block.
Answer: If you are worried about an exception being raised in the setup causing the teardown method not to be called then you could use the ExitStack class in contextlib. The ExitStack can make sure Your manager classes are closed properly if the case of an exception in setup.
from io import StringIO
from contextlib import ExitStack

managers = []
close_managers = None

def setup():
    global close_managers
    with ExitStack() as exit_stack:
        managers[:] = [exit_stack.enter_context(StringIO()) for _ in range(2)]
        # any exception raised before this line will will cause all the __exit__
        # methods of the given context managers to be called. So this should
        # be the last part of setup
        close_managers = exit_stack.pop_all().close

def teardown():
    m1, m2 = managers
    assert m1.getvalue() == 'test1 m1\ntest2 m1\n'
    assert m2.getvalue() == 'test1 m2\ntest2 m2\n'
    close_managers()

def test1():
    m1, m2 = managers
    m1.write('test1 m1\n')
    m2.write('test1 m2\n')

def test2():
    m1, m2 = managers
    m1.write('test2 m1\n')
    m2.write('test2 m2\n')

Comment: Thanks, this seems to be the exact use case for `ExitStack` (which is in the contextlib2 package for python2). Works nicely to ensure that `m1.__exit__()` is still called if `m1.get_m2()` raises an exception, while preserving all the functionality of `nosetests`.


use KML , address lookup, directions and 'share map' on the same map

Question: I want to use my kml (or xml) file with places, but at the same time be able to search for places, use directions or 'share map' functionality. At the moment when I try to do that in Google or Bing, once I use KML file and search for a new place, I loose my KML placemarks..
Is there a way to do that with Google or Bing maps?
Comment: What exactly do you mean by "lose" your KML placemarks. You mean they all disappear and are replaced by placemarks matching the user's search? Or something else?  Can you share your code so we can see what's going on? A link to your implementation if it's available on the Internet too?
Answer: Google can only handle one query at a time. There is no way of overlaying queries (IE you're KML and search term) by default.
You could do it yourself by using JavaScript and the Google Maps API.
http://code.google.com/apis/maps/documentation/javascript/


General solution of the first order differential equation $y'=(x+y−1)^2,$ where $x, y$ are real?

Question: Can someone help me solve this.
Which one of the following is the general solution of the first order differential equation

$$\dfrac {dy}{dx}=(x+y−1)^2, \text { where } x, y \text { are real }$$

(A)  $Y=1+x+\tan^{-1}(x+c)$, where $c$ is a constant.
(B) $ Y=1+x+\tan(x+c)$, where $c$ is a constant.
(C)  $Y=1-x+\tan^{-1}(x+c)$, where $c$ is a constant
(D)  $Y=1-x+\tan(x+c)$, where $c$ is a constant.
Comment: It's better to post your attempt...
Comment: I don't know how to approach this ODE because of square in RHS.
Comment: Well I gave  a substitution then separate and integrate Nikh
Answer: Hint:
$$y'=(x+y−1)^2, \text { where } x, y \text { are real }$$
Substitute $z=x+y-1 \implies z'=1+y'$
Comment: You should be able to solve your DE....Just substitute in your original equaion $z,z'$ @Nikh
Comment: $z'=\frac {dz}{dx}$ in my post @Nikh Once you substitute you only have z z' and $x$ variable.
Comment: Oh   Thank you ..
Comment: You're welcome @Nikh


How to remove lines in a Matplotlib animation?

Question: I want remove the graph in animation,
when the text line is more then 19 lines..
My code has referred to this video
If the text line is more than 19 lines, the graph is remove.
I was use the remove() and del, but this isn't working because using remove() and del in this code will not automatically delete the graph.
When the text line is more than 19 lines, the graph remove when the matplotlib is re-executed.
I also tried use plt.cla, plt.clf but this things..
removing the label too.. i don't want remove the label and title
how can i fix it? .
Here is my code :
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
plt.xlim(-190,190)
plt.ylim(-190,190)

def animate(i):
    graph_data = open('data.txt', 'r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []

    for line in lines:
        if len(line) > 1:
            x, y = line.split(',')
            xs.append(x)
            ys.append(y)

    ax1.plot(xs, ys, 'r')

    if (graph_data.count(' \n')+1) >=19:
       ax1.lines[0].remove()
       ##del ax1.lines[0]
       ##plt.cla()

ani = animation.FuncAnimation(fig, animate,interval=1, frames=2, repeat=True)
plt.show()

Comment: Did you ever fix this? I have the same issue.
Answer: Try assigning a variable to the value of the lines count function as in:
return_value = graph_data.count(' \n')+1

Print this value and see if the count function is working properly as you add lines
hope this helps.
Comment: count is walking, and Among remove(), del, and plt.cla, only plt.cla works.


How to enable dojox.data.JsonRestStore access struts2's action to retrieve data? I mean how to configure 'target' or others

Question: I tend to use dojox.data.JsonRestStore as my grid's store, but I am always failed to access struts2 action, I am unfamiliar in REST, is it only can be used in servlet rather than struts2, etc.
Currently, My project is using struts2 + spring as backend skill and dojo as front-side skill, have you any ways for me to make dojox.data.JsonRestStore access a structs2 action class?
Thanks in advance.
Answer: to get the data, all you need is an HTTP GET that returns an array of JSON objects. The return value from the action must be a string with something like:
[
   {
      "penUser":"Micha Roon",
      "submitTime":"12.03 13:20",
      "state":"Eingang",
      "FormNumber":"001001"
   },
   {
      "penUser":"Micha Roon",
      "submitTime":"12.03 13:20",
      "state":"Eingang",
      "FormNumber":"001001"
   }
]

If you want to be able to update objects you have to have a method that reacts to PUT with the same URL as the one you used for GET and if you need to delete, DELETE will be used. The important part is that it must be the same URL.
In order to have JsonRestStore pass the ID in a GET parameter instead of appending it to the URL, you could specify the URL like so:
target:"services/jsonrest/formstore?formId="

When you call yourStore.get("123") the request will try to get http://yourserver:port/AppContext/services/jsonrest/formstore?formId=123
REST is nothing more than a convention.
You can use a RESTFull API like jersey.java.net in order to make your life easier and your URL more RESTFull.


What does this hammer icon next to Roblox usernames mean?

Question: What does this symbol/icon next to a username mean?
Answer: Source: Roblox Playerlist Updates
It's the new owner icon. It means they own the game they are in.
Comment: It can also mean that they have editing permissions on that game they are in.


Kubuntu 18.04 no more GUI after upgrade from 17.10

Question: I upgraded Kubuntu from 17.10 to 18.04 LTS today. Upgrade went well, until the system rebooted. I got the Kubuntu splash screen, but then: nothing. Black screen. I can however enter TTY 2-6 (1,7,8 not responding). I'm using a laptop with both Intel integrated graphics and NVidia GeForce GT 520 MX graphics card.
I tried:

apt update && apt dist-upgrade
reconfigure sddm (dpkg-reconfigure sddm)
installing different NVidia drivers, as I had problems with the driver last time I installed ubuntu. (nvidia-304- not able to install,nvidia-driver-390, didn't help. nvidia-340: and nouveau, also didn't help
Adding 'nomodeset' to /etc/default/grub: no help
startx to start the Xserver myself. This results in an error, being that Xserver is not able to start. kstart plasma-desktop shows the following error

cannot connect to X server

What would be the right way to do it?
Comment: Shameless Plug: There are other reasons why you could also end up without a GUI. [This post](https://askubuntu.com/q/1029509/535457) may also be relevant and/or of interest.
Answer: After a few hours of trying, I got the GUI working again, thanks to these two posts:

https://ubuntuforums.org/showthread.php?t=2391150
https://devtalk.nvidia.com/default/topic/1033140/kubuntu-18-04-gives-black-screen-when-sddm-starts-no-login-/?offset=6

So, this turned out to be a NVidia-driver issue. I reinstalled the NVidia 390 driver, and added the lines suggested in the posts above to the /usr/share/sddm/scripts/Xsetup-file, and in the /etc/X11/xorg.conf-file, a line (Driver "nvidia") in Section "Device" was commented-out, which I enabled again. Rebooted succesfully into the GUI.
Comment: Please improve your answer such that if the remote URLs cease to exist your answer here will continue to be useful independently of them.


Wireless dropping out periodically on laptop

Question: Recently a problem has started occurring on my laptop where the wireless connection is slow to connect and after about 30 seconds it disconnects. The Internet is also very slow when of works. It works fine on Windows and on my phone. Any help fixing this problem would be appreciated. (Or instructions on how to roll back a few days since this seems like a recent update has broken something)
Edit: never mind, it seems to have fixed itself. I guess it'll be a mystery that we'll never solve. Perhaps it was fixed by an update.
Edit2: I ran that script but it's being annoying and working at the moment. The output is here: http://paste.ubuntu.com/10593061/ when it breaks again I'll post the script and we can compare. Thanks for your help.
Comment: To try to keep this short and quick, follow instructions from http://ubuntuforums.org/showthread.php?t=370108 to run the wireless script and use paste.ubuntu.com to copy the wireless-info.txt file to and post the URL it gives
Comment: Please don't post information-free comments. This is a Q&A which is focused on working together on solutions. People will notice that you don't answer automatically.
Comment: This always happen or is usually after a resume from suspend? I'm asking because I had a bad experience with my wifi only after resume from suspend (then I had always to run a `sudo service restart network-manager`). It was so frustrating that I just added this command to run automatically at every resume.
Comment: @Rael always happening even after reboot.
Comment: @jeremy thanks. I'll post that when I get in from work.
Comment: any progress?  Or haven't you made it home?
Comment: @Jeremy31 yeah, I added an edit to the question but actually it has broken again so I'm just running that script as we speak (type)
Answer: On what you posted, you only have two nearby access points broadcasting at higher signal strengths than yours!  Try changing channels, maybe the 2462 Frequency, with only weak signals present (at the time you ran the script).
Comment: And if that doesn't work, download the latest version of the driver from a mirror site from http://packages.ubuntu.com/utopic/amd64/bcmwl-kernel-source/download
Comment: Yeah, that didn't seem to work, I think it made it worse somehow. We'll try the driver tomorrow.


ReactJs how to show list with load more option

Question: I am tring to show todo list with load more option. I am appling limit.Limit is apply to list.But when i add loadmore()function. then i get error this.state.limit is null Wher i am wrong.Any one can suggest me.
here is my code
todoList.jsx
var TodoList=React.createClass({
    render:function(){
    var {todos}=this.props;
    var limit = 5;

    function onLoadMore() {
        this.setState({
            limit: this.state.limit + 5
        });
    }
    var renderTodos=()=>{
            return todos.slice(0,this.state.limit).map((todo)=>{
                return(
                        <Todo key={todo.todo_id}{...todo} onToggle={this.props.onToggle}/>
                );
            });

    };

    return(

            {renderTodos()}
            Load

        )
}
});
module.exports=TodoList;

Answer: Changes:
1. First define the limit in state variable by using getInitialState method, you didn't define the limit, that's why this.state.limit is null.
2. Define all the functions outside of the render method.
3. Arrow function with renderTodos is not required.
4. Use this keyword to call the renderTodos method like this:
{this.renderTodos()}

Write it like this:
var TodoList=React.createClass({

    getInitialState: function(){
        return {
            limit: 5
        }
    },

    onLoadMore() {
        this.setState({
            limit: this.state.limit + 5
        });
    },

    renderTodos: function(){
        return todos.slice(0,this.state.limit).map((todo)=>{
            return(
                <Todo key={todo.todo_id}{...todo} onToggle={this.props.onToggle}/>
            );
        });
    };

    render:function(){
        var {todos} = this.props;
        return(

                {this.renderTodos()}
                Load

        )
    }
});

Comment: ```.filter((e,i) => i>=0 && i<=this.state.limit)```

better use this to prevent the bug in mobile
Comment: Thank you Mayank Shukla sir
Comment: The problem with this approach is that all todos up to `limit` will get rendered. Suppose you have a list of books, each with it's own image etc. Each time the load more button is clicked will render them all. Any suggestion on how to render only added items?
Comment: we can use `shouldComponentUpdate` lifecycle method in `Todo` component, and skips the rendering of old items.
Comment: can you please edit answer with functional component as well ?
Answer: This is witout button click.
As you all know react components has a function componentDidMount() which gets called automatically when the template of that component is rendered into the DOM. And I have used the same function to add the event listener for scroll into our div iScroll.
The scrollTop property of the element will find the scroll position and add it with the clientHeight property.
Next, the if condition will check the addition of these two properties is greater or equal to the scroll-bar height or not. If the condition is true the loadMoreItems function will run.
class Layout extends React.Component {
  constructor(props) {
   super(props);
   this.state = {
      items: 10,
      loadingState: false
    };
  }

  componentDidMount() {
    this.refs.iScroll.addEventListener("scroll", () => {
      if (this.refs.iScroll.scrollTop + this.refs.iScroll.clientHeight >=this.refs.iScroll.scrollHeight){
        this.loadMoreItems();
      }
    });
  }

  displayItems() {
    var items = [];
    for (var i = 0; i < this.state.items; i++) {
      items.push(
Item {i}
);
    }
    return items;
  }

  loadMoreItems() {
    this.setState({ loadingState: true });
    setTimeout(() => {
      this.setState({ items: this.state.items + 10, loadingState: false });
    }, 3000);
  }

  render() {
    return (

          {this.displayItems()}

        {this.state.loadingState ?
 loading More Items..
 : ""}

    );
  }
}

This is example


cannot figure out how to get each answer in incremental loop

Question: I am coding a multiple choice quiz.
I have my questions as objects and each are contained in an array.
This is the code that I have.
Each object is names q1, q2 and so on.
for(int i = 0; i < questions.length; i++)
{
   System.out.println(questions[i]);
   choice = kb.nextLine();
   if(choice.equals(q1.getCorrectAns()))
   {
      correct++;
   }
}

The comparison works for the answer of question 1, but I don't know how to make the comparison change with each question.
Also I tried searching for how to ignore the case of user input, but the things I tried did not work. How can I achieve that?
Creation of the objects and the array
Question q1 = new Question("These are the rules that must be followed when writing a program.",
                                                                        "a. syntax", "b. punctuation", "c. key words", "d. operators", "a");
Question q2 = new Question("A group of statements are enclosed in __________.",
                                                                        "a. brackets []", "b. parenthesis ()", "c. braces {}", "d. any of these", "c");
Question q3 = new Question("This is an if statement that appears inside another if statement",
                                                                        "a. nested if statement", "b. structured if statement", "c. tiered if statement", "d. dislodged if statement", "a");

Question[] questions = new Question[3];

questions[0] = q1;
questions[1] = q2;
questions[2] = q3;

Here is the question object constructor
public Question(String question, String optionA, String optionB, String optionC, String optionD, String correctAns)
{
    this.question = question;
    this.optionA = optionA;
    this.optionB = optionB;
    this.optionC = optionC;
    this.optionD = optionD;
    this.correctAns = correctAns;
}

EDIT: My array only consists of the three questions. How can I print each one out, one time each, at random?
Comment: You've created an array of questions, so you can create an array of answers to match those questions.
Comment: When you find yourself creating variables named `q1`, `q2`, etc - you should really use an array instead
Comment: Share the code where you create `questions[]` and `q1,..`
Comment: Can you show the `getCorrectAns` method?
Comment: I want to be able to access the answer field of the object from within the array
Answer: You're already iterating correctly over the questions when you do this: System.out.println(questions[i]); - you just need to do that for your answer comparison as well.
Specifically, instead of checking if(choice.equals(q1.getCorrectAns())), check for if(choice.equals(questions[i].getCorrectAns()))
As a note, you may want to consider changing your question output to do something like System.out.println(questions[i].getQuestion());, so you don't need to override Question.toString() to only output the question.


Django Admin search query not hitting Postgres index

Question: I'm doing a full-text search with a GIN index in Postgres (all localhost), and when I write my own query and run it in psql, I am getting great response times and EXPLAIN ANALYZE reports an index hit (woohoo), however when querying via the Django Admin search box with the same search terms, the index is not scanned and the query takes upwards of forever to complete.
My index is created thusly via the fully-awesome pg_trgm Postgres extension:
CREATE INDEX name_gin ON entity USING gin (name gin_trgm_ops);

This query hits the index and takes a blazing 84ms to search through 900k full-text records:
SELECT COUNT(*)
FROM entity
WHERE name LIKE UPPER('%dubteeeff%')
 AND name LIKE UPPER('%django%');

The exact same query, as created by the Django Admin interface, takes 938ms:
SELECT COUNT(*)
FROM entity
WHERE UPPER("entity"."name"::text) LIKE UPPER('%dubteeeff%')
  and UPPER("entity"."name"::text) LIKE UPPER('%django%');`

The only difference appears to be the way the columns are referenced--I'm fairly new with Django and Postgres--is there some Postgres config setting or Django admin QuerySet-something, or a RawQuery that I could override or modify to speed this up?  I don't want my Admin page to at best be slow and at worst, drag the rest of the site down with it.
Thanks in advance.
Comment: The difference is that in your query the column is referenced. In the djange Query an expression `upper(name)` is used, which is not indexed. Araqnid is right that you probably need an index on `upper(name)` rather than "just" `name`. Or teach django to not apply the `upper` function (maybe tell it to *not* make the query case-insensitive)
Answer: Look like you need to add an index on entity(upper(name)) rather than entity(name) for the case-insensitive search that Django is generating.
Comment: Thanks--I can't believe I didn't notice that.  Generated the uppercase index and it works like a charm.
Answer: Is this perhaps an issue with COUNT(*) being slow in Postgres?  You might want to check into modifying your queries to return estimates instead of exact counts, as that is a known issue with Postgres.
Comment: Thanks but I've already done that-- the COUNT(*) by itself is quite fast.  Plus, if that were the issue, why would the query ever be fast?
Comment: Ah--yes.  Looks like the issue has to do with Postgres not interpreting `UPPER("entity"."name"::text)` the same way as `name`.  Not sure why that would be, or how to stop Django from doing that.  Good luck!
Comment: Django will use `UPPER()` in the SQL if you filter case insensitive by using the `i*` keywords: `.filter(name__istartswith=...)`, or `icontains`


Getting data from 2 tables in magento

Question: I created 2 textension in magento along with 2 different tables. First extension store data in table-1 while second second extension store data in table-2. Now i want to display data in first extension by LeftJoin. It show data without leftjoin from first table but not showing data with leftjoin from both the tables.
This code in block.php
public function methodblock()
 {
    $collection = Mage::getModel('test/test')->getCollection();

    $returnCollection = $collection->getSelect()
    ->joinLeft('magento_answer', 'id_pfay_test=question_id',
    array('*'), null , 'left');

     return $returnCollection;
 }

On Layout side. dislplaydata.phtml
<?php
$collection =  $this->testmethodblock();
foreach($collection as $rows {
    echo $rows ->getData('name');
}

Comment: What errors are you getting? See if this answer helps: http://stackoverflow.com/a/19401573/1076075
Comment: I is not displaying any error. when i echo $returnCollection. It gives this query.    SELECT `main_table`.*, `magento_answer`.* FROM `magento_pfay_test` AS `main_table` LEFT JOIN `magento_answer` ON id_pfay_test=question_id . This query is running properly on mysql db.
Comment: try to print query and check where is the problem.  before return function write echo $collection->getSelect();exit;
Answer: I Got the answer. I use the custom query which works for me.
$resource = Mage::getSingleton('core/resource');
        $readConnection = $resource->getConnection('core_read');
        $qTable   = $resource->getTableName('pfay_test');
        $aTable   = $resource->getTableName('answer/answer');
        $query = 'SELECT * FROM  '.$qTable.'  q  left join '.$aTable.' a ON  a.question_id=q.id_pfay_test';
        $results = $readConnection->fetchAll($query);
         return $results;

Getting data from 2 tables in magento


Wireless network adapter manufacturers with best Linux compatibility record?

Question: I need your help. I need i wireless adapter for my pc that runs Ubuntu. I tried the Trendnet TEW-423PI/A C1.2R, but it was a little wonky.
Comment: Aetheros nuff said.
Answer: Edimax and Tp-Link are probably the most linux compatible wireless network adapter manufacturers. They are also easy to purchase. For more information about specific models browse this page. When you find something that interests you note the chipset and go to WikiDevi. On the bottom of the main page there are links to specific chipset manufacturers like Ralink, find chipset and on the right there is a link to list of all adapters that use that specific chipset.
Few examples:

TP-LINK TL-WN821N v3 and TP-LINK TL-WN822N v2 on chipset Atheros AR9287+AR7010 2,4GHz supported by driver ath9k_htc
TP-LINK TL-WN721N and TP-LINK TL-WN722N on chipset Atheros AR9271 supported by driver ath9k_htc
TP-LINK TL-WN7200ND, Edimax EW-7711USn and Intellinet Wireless 150N USB Adapter on chipset RALINK RT3070 supported by driver rt2800usb

In case of mini pciE cards you should look for Atheros and Intel products (intellinuxwireless.org).
Answer: You can browse the certified hardware catalogue here:

Wireless (last updated 2015-04-20)

Network (last updated 2009-11-23)
Comment: the links are dead
Answer: From my personal experience with multiple wireless cards. The best card hands down for the ubuntu desktop is the intel centrino cards. All other cards had connection stability issues and significantly slower speeds. I eventually realized that my laptop never had these issues which prompted me to determine the driver and hardware being used for it's wireless internet. I found that the laptop was using an intel centrino chip which used the iwlwifi driver. A quick google search for intel centrino cards for desktops and $25 later, I had a  fast and stable internet connection using the iwlwifi driver. By fast and stable I mean, no disconnections ever, and wireless speeds up to 54 mbps at a distance of three rooms horizontally and a floor below the wireless router. No other card manufacturer that I have used has even come close to these speeds on an ubuntu desktop.


How can i set include_root_in_json to false for all my RoR models?

Question: How can i set include_root_in_json to false for all my RoR models?
I've tried to set ActiveModel::Base.include_root_in_json = false inside application.rb, but it has no effect.
Answer: Model.to_json method is used to returns a JSON string representing the model and i have used
self.include_root_in_json = false in a model itself.
But for the whole application you can try setting ActiveModel::Base.include_root_in_json = false in an initializer.[edit This does not work.]
[edit] ActiveRecord::Base.include_root_in_json = true try adding this line to config/environment.rb file.
Comment: I've got an initializer in config/initializers/active_record.rb that contains `ActiveRecord::Base.include_root_in_json = false` and it works fine for me (I'm using Rails 3.0.4). Something you have to remember (it used to catch me out) is if you change an initializer, you need to restart your server or reload your console for it to take effect.
Comment: this also works for me self.include_root_in_json = false, but ActiveModel::Base.include_root_in_json = false cause an error, like it is not defined. (I'm using Rails 3)
Comment: Can you try putting the following line in config/environment.rb

ActiveRecord::Base.include_root_in_json = false
Answer: I'm not sure if this is true for the later versions of rails but for me (running 2.3.5 atm) there was already a declaration for this setting in /config/initializers/new_rails_defaults.rb where it was set to:
ActiveRecord::Base.include_root_in_json = true

So if you try to set this setting in another place then it might be overridden.
Comment: +1 works for me by changing "true" to "false" in `config/initializers/new_rails_defaults.rb`.
Answer: On Rails 3.2.2, this is already set in the initializers:
---config/initializers/wrap_parameters.rb ---
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
  self.include_root_in_json = false
end

Answer: For default system wide config is alway good idea to set variable in initializers, like config/initializers/defaults.rb
Answer: I think you should set ActiveRecord::Base.include_root_in_json = false in config/application.rb
not ActiveModel::Base
Answer: At Rails 4 in "config/initializers/wrap_elements.rb" you can uncomment the following:
ActiveSupport.on_load(:active_record) do
 self.include_root_in_json = true
end


How may I make circular thumbnails using the paperclip gem?

Question: The new Basecamp is doing it, as it can be seen in this link. I wonder how can achieve this in my rails 3 application.
Answer: See this forum post on using masks with Imagemagick to get a circle effect.
However, realize that in the "new basecamp" with the "circular avatars," they use simple css, not image processing. Take a look at the properties border-radius, -moz-border-radius, -webkit-border-radius, and -khtml-border-radius.
To do this with CSS, take a look at this gist or this blog post.
Comment: And CSS is The Right Thing (TM) in that case, because it is the most flexible solution.
Answer: I have no experience using Rails, but from what I have read here, it looks like Paperclip is using Imagemagick as its backend. So you will need to use masking with Imagemagick.
Edit: You can follow this example and adjust the values for the circle radius:
http://loo.no/2009/08/09/rounded-corners-with-paperclip
Comment: Heads up, the link in your edit seems to be an empty page now :(


How do I test the data to fit to the Poisson distribution with goodfit?

Question: I have a data set with car arrivals per minute.
I drew a histogram and fit to the Poisson distribution with the following R codes.
#Aladdin Arrivals
Datast <- read.csv("Vehiclecount.csv", header = T, sep=";", dec=",")
hist(Datast$Arrival, xlab="Arrivals",
  probability = TRUE,col=16, ylim = c(0,0.2), xlim =c(0, 30),
  main = "Arrivals from Aladdin Street")
lines(dpois(x=0:25, lambda=13.20), col=2,lwd=3)
legend("topright", c("Probability of Vehicle Arrivals ",
    "Poisson Distribution Curve"),  fill=c(col=16, col=2))

The code above successfully ran and I got the fitted lines over the histogram.
But when I want to use the goodfit() function to know how the p-value is I got following error;

"Error in optimize(chi2, range(count)) : 'xmin' not less than 'xmax'"

dfs <- dpois(x=1:25, lambda=13.20)
summary(dfs)
goodfit(dfs, type="poisson", method="MinChisq")

How I can solve this issue ? Is there another function to use?
Comment: Please, could you share a sample of your data, in order to help you?
Comment: T.Period x Arrival Rate
7 1 4,87
8 2 12,54
9 3 10,89
10 4 11,46
11 5 12,18
12 6 12,85
13 7 13,72
14 8 17,49
15 9 18,34
16 10 20,83
17 11 13,09
18 12 13,23
19 13 10,07
Comment: I added the sample data as an image in answers..
Answer: You're applying goodfit (you should say it's from the vcd package, BTW) to the wrong thing.  The first argument should be your count data: try
vcd::goodfit(Datast$Arrival, type="poisson")

Comment: Yes it works in this way, thanks..
How should I follow when I want to measure the compatibility of this data set with the Chisquare test and get the p value?


Compiler error for classes and methods?

Question: I'm getting an error for items such as void / sender / class etc when attempting to paste in this example of a viewstate into Visual studio. I know that the methods need to be inside a class, but even that is still bringing up an error. The code needs to be inside a script in a web control and I'm wondering what's bringing up the errors. I've tried it in a different solution / project and changing the framework, no luck.
The code is
<code><%@ Control Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="Umbraco.cms.businesslogic" %>
<%@ Import Namespace="umbraco.cms.businesslogic.web" %>
<%@ Import Namespace="umbraco.cms.businesslogic.member" %>
<%@ Import Namespace="umbraco.cms.businesslogic.propertytype" %>
<%@ Import Namespace="umbraco.cms.businesslogic.relation" %>
<%@ Import Namespace="umbraco.nodefactory" %>
<%@ Import Namespace="System.ComponentModel" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="TemplateEngine.Docx" %>
<%@ Import Namespace="DocumentFormat.OpenXml.Packaging" %>
<%@ Import Namespace="DocumentFormat.OpenXml.Wordprocessing" %>

<script>

public class PageStateTemplate
{
   new umbraco.cms.businesslogic.web.Document(document location);

   protected void Page_Load(object sender, EventArgs e)
   {
        if(!IsPostBack)
         {
            string str = "Welcome to Aspdotnet-Suresh Site";
         if(ViewState["SampleText"]==null)
         {
             ViewState["SampleText"] = str;
         }

         }
   }

   protected void btnClick_Click(object sender, EventArgs e)
   {
    lblString.Text = ViewState["SampleText"].ToString();
   }
}
</script>
</code>
Comment: `new umbraco.cms.businesslogic.web.Document(document location);` this line is invalid because of `document location` - variables cannot contains spaces, arguments must be divided with comma. And you also don't assign your new Document to any variable, is it ok?
Comment: Post the exact error message, and the line.
Comment: That's not the issue since it's flagging up "class" as an error. All it says is "expected ;" and it's flaggingu p class, void, sender
Answer: You just have to create a new aspx page with the name PageStateTemplate and copy paste the whole code into the .aspx file.
That should do it
Comment: It has to be a web user control to integrate with Umbraco.

Compiler error for classes and methods?


What tech reduces the energy cost of roads?

Question: There is a technology that reduces the upkeep cost of roads and Magrail, but I can't remember what it is, nor can I find it by searching the civopedia.
Comment: There's an affinity that negates the cost.  I'm not sure if it's a tech.
Comment: I think that's what I was thinking of.
Answer: It's not a tech, it's an affinity, supremancy 3 actually

The level three affinity bonus for supremacy is one of the most
  useful: pay no maintenance on your roads and magrails.

More Inforamtion here
There is no Tech for it. You can check by going here
 and searching for "road".


How do I manage leveling up my party?

Question: My party consists of:

Level 7 Metapod
Level 7 Jigglypuff
Level 7 Spearow
Level 7 Zubat
Level 8 Kakuna
Level 18 Wartotle

I have a lot of level seven Pokémon. How can I better manage leveling up my Pokémon?
Answer: Generally speaking:

Swap Pokemon - Put a weaker Pokemon first in your party list. When you enter a battle, immediately swap to a higher level Pokemon.
Battle Trainers - While battling in the wild will be the greatest source of XP, it can also be slower. Other trainers generally have higher level Pokemon and therefore will give more XP per defeated Pokemon.

Have your battle mode set to 'Shift' and swap back to a weaker Pokemon every time a trainer sends another one out.

Know your team - Learn their strengths and weaknesses. Choose Pokemon that complement each other and can cover for each other.

In your specific case, judging by the type and level of Pokemon in your party, that likely puts you somewhere between Pewter City, Mt Moon, and Cerulean City. This is still quite early game and thus the options for catching Pokemon are a little limited.
Having said that, there are still other Pokemon you may have missed, or perhaps caught and stored in the PC. I mention this because I've noticed a glaring problem with your current party: it's extremely weak to Rock - Metapod, Spearow, Kakuna and Zubat all share this weakness thanks to Bug or Flying typing.
If possible, consider swapping some of them out. I'd suggest one or more of: Nidoran, Mankey, Geodude, Pikachu, Ekans/Sandshrew (version-specific), Oddish/Bellsprout (also version-specific).
If this is not an option, then focus on levelling one or two Pokemon in your party at a time. As they level up, they can start to take some of the load from Wartortle. I would start with:

Metapod -> Butterfree - If you can get Metapod to Level 10, it will evolve to Butterfree and learn Confusion. While it won't get the Same Type Attack Bonus (STAB) from Confusion, it will be super-effective against enemy Zubats and Oddish, which are prevalent in Mt Moon and the areas surrounding Cerulean City.
Zubat - Zubat is a bit weak early game but can be a good investment - level now and it starts to learn some more powerful Flying and Poison type moves. Note that it will be weak to Misty's Starmie thanks to the latter's Psychic-type moves
Spearow - Spearow is ok early game vs Grass and Bug, unfortunately it doesn't learn any good flying moves for a little while so you'll be stuck with Peck and Fury Attack for a little while.

That should get you through Mt Moon and the path to the Sea Cottage. Misty will be a challenge as you don't have any Grass/Electric coverage, but a high-enough Butterfree/Spearow/Wartortle should work ok. Be sure to use Butterfree's status moves as well.
Answer: As long as you don't have an Exp. Share, put the Pokemon you want to level at the first spot in your party, switch in your Wartortle, and finish of the opposing Pokemon with the strong Wartortle. In that way, the first Pokemon will get some experience and will level up slowly.
Comment: Seems like they're looking for a "What should I work on?" simplified guide, but this is a good tip towards that.

How do I manage leveling up my party?


What is the best way to show the Key/value pairs that has no data?

Question: When there is no data for some of the attributes (key/value pairs) in the info/properties card, what is the best way to represent it? IMO, those attributes with null values to be shown as well with "-" as values.
Or is it better to not show the attributes at all? Any recommendations?
Comment: I'd say a big dollop of "_it depends_". Sometimes, and/or for some data, I'd prefer to see all keys listed consistently, with data popping-in and -out of view as appropriate (especially if I were moving down a list and the properties were shown in a pane). Other times, or for other data, I'd only want to see keys that have a value. Your best bet would be to ask the users under which circumstances they would prefer one or the other.
Comment: Is NULL or Zero data? A general distinction would be are you filtering data, or returning data. If you're returning data, the need to show NULL results generally goes up with the technicality of data. Filtered results usually never show null. Technical research behooves showing NULL. I would ask in general, does showing showing NULL answer a question? Or, are your users asking that question?
Comment: Specific example of key/value pairs would be helpful. In some cases, it would be useful to show them so they can be filled out (contact info in an address book). In others, it might not be.
Comment: Will the user know the key exist if a null value is not present? Or will they completely forget such a key exists at all?
Answer: It looks like it's best to display nothing if that fits your case (solution 1).
Some default grayed out values like <no data> can be used as well if there is a need to distinguish between empty strings and null values (solution 2).
Gray dashes can be used as well (solution 3), however, it doesn't seem to be a better solution than not showing anything at all, but just adds unnecessary visual clutter.


Heat pump blower motor cycles on/off after running 140 seconds

Question: Standard Trane split heat pump, condenser outside blower inside.
Usually the system will run normally but after 2 min 20 seconds the blower motor will cycle on and off randomly for 20 seconds. Then run perfectly for the rest of the heating cycle.
One time the problem occurred at 3 min 20 seconds.
Expert checked system and said needed new motor.
Now has new motor but still same problem.
Anybody have any ideas.
Comment: What is the ambient temperature? And is this the indoor blower or the outdoor condenser fan that's cycling?
Comment: Hello, and welcome to Home Improvement. What do you mean by "cycle on and off randomly"?
Comment: Can you see the error LED's on the inside unit? There can be approx 75 different codes on some of the units and the error codes are the only way to figure out what is really happening. Cover switch not made, dirty air filter, high condensate all can cause strange problems.
Answer: Your system is trying to pull air it cannot supply. You have a dirty air filter; clean or replace it.


Number of Possible Ways to Distribute Apples

Question: I had this problem in a local math competition and was wondering how to solve it, even though I know the answer.
Bob has 24 apples. He want to give some apples to two of his friends Jill and Patty. He wants each of the three friends (counting himself) to end up with at least 2 apples each. How many possible ways could he distribute these apples (without breaking any)?
I tried permutations, combinations, and the multiplication rule but to no avail. Help would be greatly appreciated.
Thank you in advance!
Comment: Are we assuming the apples to be distinguishable in some fashion? i.e in shape, in color, in orchard?
Comment: No they're all identical.
Answer: If each person gets $2$ apples, then there remain $18$ apples to be distributed. Let $X_1, X_2, X_3$ be the number of additional apples that the first, second, and third friends get, respectively.
With these definitions, we wish to find the number of nonnegative integer valued vector solutions $(X_1,X_2,X_3)$ to $X_1 + X_2 + X_3 = 18$, $X_1, X_2, X_3 \geq 0$.
The result is well known and often referred to as the (nonnegative) solution to the "stars and bars" problem: ${18 + 3 - 1} \choose {3-1}$ $=$ $20 \choose 2$ $=190$ ways.
Comment: Thank you so much


ListView items source Binding without using mvvm

Question:  public MainWindow()
    {
        InitializeComponent();

        listView1.ItemsSource = myData; // myData is not ObservableCollection
    }

    private void AddData_ButtonClick(object sender, RoutedEventArgs e)
    {
        myData.Add(/*adding new item*/);
        listView1.Items.Refresh();
    }

and the xml code:
 <ListView x:Name="listView1" ItemsSource="{Binding}">
            <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Name}"  Header="File Name"/>
                    <GridViewColumn DisplayMemberBinding="{Binding NumOfPoints}" Header="Points"/>
                </GridView>
            </ListView.View>
  </ListView>

it works well, i just wanted to improve my code.for example removing Items.Refresh() method and improving the binding.
im newbie to wpf and looking for best practice advice and im not into mvvm right now.
any suggestion will be appreciated.
Comment: what type is `myData` if its of ObservableCollection then i believe you dont have to use `Refresh()`
Comment: No its not ObservableCollection
Comment: `List files = new List { new SDRfile("file1", "ok1", 11),
                                                      new SDRfile("file2","ok2",22)};`
Comment: ` class SDRfile
    {
        public string Name { get; set; }
        public string Status { get; set; }
        public int NumOfPoints { get; set; }

        public SDRfile(string name, string status, int numOfPoints)
        {
            Name = name;
            Status = status;
            NumOfPoints = numOfPoints;
        }
    }`
Answer: myData has to be an ObservableCollection<T> or any other type that implements the INotifyCollectionChanged interface for you to be able to see the added items in the ListView without having to reset or refresh its items collection explicitly. That's why the ObservableCollection<T> class exists.
So you have to the change the type of files from List<SDRFile> to ObservableCollection<SDRFile>.


How to get from python reply and display it on browser?

Question: I use a .post() to query for status of device in python function. When it is done, it should come back with the return value of the python function.
$.post('/request', {inputText: fbNum,key_pressed: fbType.toString()}).done(function (reply) {
      if (reply ^= "count") {
             $('#status_table tr #'+eachStatus).empty().append(the-reply-value-here);
      } });

part of my python file:
elif "C?" in response[0]:
         status="Count= %sH"%response[0].strip()[-2:]
return status

How can i get and display the status?
Do i use .get in jquery? But i'm not sure of the format. Is it
$.get("/request", reply).done(function(data){
    $('#status_table tr #'+eachStatus).empty().append(the-reply-value-here);});

??
But the reply i will is something like Count = FF. what i want to display is only the FF. How should i do it?
Answer: Try
$.post('/request', {inputText: fbNum,key_pressed: fbType.toString()}).done(function (reply) {
    if (/^Count\s*=/.test(reply)) {
        $('#status_table tr #'+eachStatus).empty().append(reply.replace(/Count\s*=\s*/, ''));
    }
});

Comment: thanks for the reply. +1 :) care to explain what `(/^Count\s*=/.test(reply))` means? and what about the `reply.replace()` part?
Comment: `/^Count\s*=/.test` is a regular expression which tests whether the reply starts with `Count =`, and then the [replace](https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/String/replace) function is used to replace the `Count = ` with an empty string you you could get the `FF` as the value
Comment: i see. where i can read more about that / \ ^ * . syntax? :s it's a bit confusing for me. so `/.test` is just a random name?
Comment: no [.test()](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test) is a function available in the regular expression object
Comment: You can read more about [RegExp](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions) in https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
Comment: oh!! thank you so much for this useful information! you saved my day again Arun :))


Get date given year, week number, day number within week with JavaScript

Question: as the topic suggest - I'm looking to get a date when all I have is year (ex. 2014), week number (ex. 47) and day number within that week (ex. 3 - which would be Wednesday).
I've seen some similar questions the other way around, but reverse-engineering answers didn't provide any successful results.
Any ideas?
Answer: I would highly recommend you to use the moment.js library. This is a complete date manipulation library.
Your problem would be solved by this moment().year(2014).week(47).day(3).toDate();
Comment: Thanks, I'll definitely take a look. Looks like it will solve all my problems though :)
Answer:

function getDatebyWeek(year, week, day) {

  var d = {
    year: year,
    month: 0,
    day: 1
  };

  var date = new Date(d.year, d.month, d.day);
  var weekCount = 0;
  var month = 1;

  var done = false;

  while (weekCount < week) {

    while (date.getMonth() < month) {

      if (d.day % 7 === 0) {
        weekCount++;
      }

      d.day++;
      date.setDate(d.day);

      if (weekCount === week) {
        done = true;
        break;
      }

    }

    if (done) {
      break;
    }

    month++;

    d.month = month - 1;
    d.day = 1;

    date.setMonth(d.month);
    date.setDate(d.day);

  }

  if (day <= d.day && day >= (d.day - 7)) {
    return new Date(d.year, d.month - 1, day);
  } else {
    throw new Error('The day you entered is not in week ' + week);
  }

}

var wk = getDatebyWeek(2014, 47, 22);

document.write(wk.toString());

I wrote this really ugly function in case you have something against moment.js :)
Answer: From : Getting first date in week given a year,weeknumber and day number in javascript
The answer to OP would be (if dayNumber starts from 1 (Monday) - to 7 (Sunday)):

function getWeekDate(year, weekNumber, dayNumber) {
  var date = new Date(year, 0, 10, 0, 0, 0),
      day = new Date(year, 0, 4, 0, 0, 0),
      month = day.getTime() - date.getDay() * 86400000;
  return new Date(month + ((weekNumber - 1) * 7 + (dayNumber - 1)) * 86400000);
};

alert(getWeekDate(2014, 47, 3));


Getting unquoted variable names from a vector using rlang

Question: I am building a function for which I'd like the user to be able to pass unquoted variables. Later on I'm going to need the names of those variables as strings as I prepare the output.
This is no problem if each argument carries only one variable. I can use deparse(substitute(x)) or rlang::as_name(rlang::enquo(x)) to get the name out (with the latter probably being the better approach). But how do I do this if I have them passing in multiple variables in one argument using c()?
The only way I've figured out how to do it so far, after reading a whole bunch about quosures, etc., is names(dplyr::select(data,{{x}})) but I can't imagine that's the proper way to do this.
nameprinter <- function(x, manynames, onename) {
  manynames <- names(dplyr::select(x, {{manynames}}))
  onename <- rlang::as_name(rlang::enquo(onename))

  c(manynames,onename)
}

df <- data.frame(a=1:10,b=1:10,c=1:10)

nameprinter(df,c(a,b),c)
# [1] "a" "b" "c"

What's a better approach to getting the names of the variables passed in manynames than I have here? Thank you.
Answer: There is actually already a function for it. We can use vars_select
tidyselect::vars_select(names(df), c(a,b), c)
# a   b   c
#"a" "b" "c"

tidyselect::vars_select(names(df), a, b)
#  a   b
# "a" "b"

Answer: You could use base R to accomplish this:
nameprinter <- function(x, manynames, onename) {
  manynames <- substitute(manynames)
  names_env <- setNames(as.list(names(x)), names(x))
  manynames_quo <- eval(manynames, names_env)

  onename <- deparse(substitute(onename))

  c(manynames_quo,onename)
}

df <- data.frame(a=1:10,b=1:10,c=1:10)

nameprinter(df,c(a,b),c)
#[1] "a" "b" "c"

This evaluates our manynames vector based on the names of the variables in our df. This should be a fair bit quicker than using select and then pulling out the names.
Answer: I don't think that you need to work with the rlang::enquo function directly for this problem:
library("dplyr")

nameprinter <- function(x, manynames, onename) {

  select(df, !!manynames) %>% print()
  select(df, !!onename) %>% print()

  c(manynames, onename)
}

df <- tibble(a = 1:10, b = 1:10, c = 1:10)
nameprinter(df, c("a", "b"), "c")

Is this what you wanted?
Comment: My concern was that pulling out the names using `select` seemed so kludgy, that there must be a cleaner way, such as how `as_name` works with the single variable. Is `select()` the best practice here?
Answer: I tought of an approach that is more generic and does not depend on a data frame. It uses as_name and applies it to the quosures using vapply...
foo <- function(.data, value_col, ...) {
  group_cols <- enquos(...)
  value_col <- enquo(value_col)
  # do stuff
  .data %>% group_by(!!!group_cols) %>% summarize_at(vars(!!value_col), mean) %>% print()
  # passed columns as a character vector
  vapply(c(group_cols, value_col), rlang::as_name, "")
}
foo(mtcars, mpg, cyl, vs)


Grub command line is the only thing that shows after starting my laptop

Question: I have a MSI ge60, with win8 pre installed. I installed Ubuntu 13.10 on a sperate partition than where win8 is. After restart grub doesn't show, the laptop goes straight to win8. I didn't know what t do so I formatted the partition with Ubuntu on it, after restarting the laptop I'm stuck at a GNU Grub version 2.00-19ubuntu2 screen
I searched how to load windows using it but it says I need to load kernel. It also says hd0,0 doesn't exist
Answer: On problems of marrying GRUB with the Win8 loader (not same thing as the Vista/7 loader) Windows 8 removes Grub as default boot manager
On the problem of loading Win8: burn a recovery CD on any Win8 machine, then use it to restore Win8 boot.
Answer: I have a similar problem, what I do for now is typing "exit" in that grub command line, it then shows me the boot list options.
Answer: i HOPE you did not accidentally delete any partition. To make sure everything is OK
you may run GParted preferably from a live Ubuntu USB. Then it would be only a matter of finding the boot partition, something like sda2/BOOT/...  Of course
you would have to mount the specific partition, first. But first things first, if
you really want to dual boot using ubuntu I would recommend Boot-repair which
would set things up and/or produce a detailed log of what's wrong!
[1] https://help.ubuntu.com/community/Boot-Info


Real Time File Transfer using python script

Question: I want to create an  application which needs from time to time do
file transfer (I want to write the server as well as the client).
What is the best way to do this file transfer?
Thanks in advance..
Nimmy...
Comment: FTP? It was invented for that.
Answer: Pyftpdlib as a server.
and any linux box as a client.
Answer: FTP Tunneled over SSH.
Use twisted and a good linux shell.


How do I access hidden quests and complete the optional objectives?

Question: Does anyone know how to get those darn hidden quests that have no clue in Dawn of Heroes? It seems like there are no FAQs for this yet.
Also, how is it possible to do some of the Optional Objectives. It seems impossible to kill all enemies in 2 turns when it takes 2 turns to kill at least one of them.
Answer: Try the ones of killing the enemies in two turns when you have bigger level than them.
Take care if you are on the 4th barony because the campaign may reset to the second battle of that map if you travel to other maps (once you have the town I suggest you first unlock the 2 heroes before trying to complete that barony).

2010/10/01:

Hidden Quests

The list below is completed. Some rewards may change (the ones that are not consumables)
If you post this list somewhere else, show the source and the author
Enjoy it :D

The Witch (1st Barony 1st quest) -> Giant Worm (Consumable)
Giant Worm -> Eagle quest (4th barony 1st quest) -> Dragon Egg (Consumable).
Dragon Egg -> Airborne (1st barony) -> Horned Amulet (Legendary Badge)

Red Key -> The Lesson (1st Barony) -> Iron Shackles (Consumable)
Iron Shackles -> Lair Raider (5th barony) -> Fire Rune (Consumable)
Fire Rune -> Ceremony (4th barony) -> Bony Amulet (Legendary Badge)

Brotherhood (2nd barony 1st quest) -> Coffee Machine (Consumable)
Coffee Machine -> Honey Honey (5th barony) -> No badge, no consumable

Safari (2nd barony) -> Prayer Book (Consumable)
Prayer Book -> Sage Miyagi (3rd barony) -> No badge, no consumable

Birthday Party (3rd barony 1st quest) -> Sword (main quest item)
Sword -> Unlocks a main quest

The Master (4th barony) -> Cuckoo Clock (Consumable)
Cuckoo Clock -> The Precious (2nd barony) -> No badge, no consumable

Gold Race (5th barony) -> Magical Barrel and Earth Ward (2 Consumables)
Magical Barrel -> Vegetarian (6th barony) -> Medal of Honor (Consumable)
Medal of Honor -> Treasure Hunt (3rd barony) -> Frosty Amulet (Legendary Badge)
Earth Ward -> Lies (3rd barony) -> No badge, no consumable

Dirty Job (5th barony) -> Silver Harp (Consumable)
Silver Harp -> The Siren (1st barony) -> Lorgnette (Consumable)
Lorgnette -> Tournament (4th barony) -> Fanged Amulet (Legendary Badge)

Water Skins (5th barony) -> Singing Fish (Consumable)
Singing Fish -> Giant Fish (1st barony) -> Ancestral Key (Consumable)
Ancestral Key -> The Chancellor (3rd barony) -> Snowy Amulet (Legendary Badge)

The Traitor (6th barony) -> Ancient Scroll (Consumable)
Ancient Scroll -> The Traitor (6th barony, battle for the treasure) -> Eyeless Skull (Consumable)
Eyeless Skull -> Diabolo 2 or Diabolo 3 (6th barony, both) -> One Eyed Skull (Consumable)
One Eyed Skull -> Diabolo 2 or 3 (The one still not done) -> Living Skull (Main Quest Item)

Catastrophe (6th barony) -> Rusty Spanner (Consumable)
Rusty Spanner -> Bomb Squad (4th barony) -> Robot Spider (Consumable)
Robot Spider -> Bug Infestation (2nd barony) -> Bloody Amulet (Legendary Badge)

The Door (6th barony) -> Big Cyan Key and Voodoo Doll (Consumable)
Voodoo Doll -> Ghost Town (2nd barony) -> Tin Foil Hat (Consumable)
Tin Foil Hat -> Impnapping (5th barony) -> Wicked Amulet (Legendary Badge)
Big Cyan Key -> Treasure (or Town if you unlock West spot) -> Ore Detector (Consumable)
Ore Detector -> Impbot (2nd barony) -> Shiny Ore (Consumable)
Shiny Ore -> Ashes To Ashes (1st barony) -> Fanged Amulet (Legendary Badge)

Tips:
I open the most of the treasures at level 25, but before killing the behemont. So I just get a tone of purple items and just 2 gold (non-badge) items. I think that the chance of gold items will rise if you open the chests after killing the behemont.
Once I discover how to kill it, I will make an update.
Comment: Is it a bug in the game?
Comment: Dont think so. They already tell you when you enter the realm, but ofc, not when you go out. So just make the 4th barony story-lane in a row, instead of trying to make hidden quests during it. Still Im not sure how it resets (roaming among maps), but its kinda anoying
Comment: Thanks for the effort! I'm just at the 5th barony and managed to get some of the secrets too.
Comment: It's hilarious how the first hint of how to do this is in the 6th barony. XD
Answer: Hidden objectives: use the proper orange "potion" on the stage to complete them. There is sort of a relation between the orange item description and the stage description. I suck with names, but as far as I can recall, the "big worm" for example is used on scenario number four, on the stage where you are in a giant eagle...
Comment: Orange potion? Where's this orange potion?
Answer: The orange potions are the specialty items like "Big Worm" that you get for completing the "Two Turn" special objectives. The "Big Worm" goes to the eagle. This is the first stage of the fourth Barony. There is also a Sage Book you get from the "Two Turn" turtle of the second barony. This goes to the Sage level in the Third Barony. I will post more as I figure them out.
Answer: The orange potions are the specialty items like the "Big Worm" that you get for completing the "Two Turn" special objectives. Now, I use "Banish" to easily complete the "Two Turn" special objective fights, by put one on each character and using them on the toughest opponents first and slaughtering any weaker units. This game seems to have very little information any where online. Oh, here's another hint about using "Banish", which purchasable in town, you can use it earn money fast by knocking out the stronger 2 units in the hard level mercenary battles.


signal() handler gets fired immediately

Question: Trying to implement process interruption handling using this function.
Following code running on OS X 10.10:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "sys/wait.h"

sig_t terminate(){
    printf("Thanks for the fish!\n");
    exit(EXIT_SUCCESS);
}

int main(int argc, const char * argv[]) {
    signal(SIGINT, terminate());
    while (1){
        printf("P");
    }
}

Problem is, that the terminate function is called immediately after running the program. Means, one does not see a single P, but only a line of Thanks for the fish!.  What am I doing wrong?
Answer: Pass a function name instead of calling the function
signal(SIGINT, terminate );

Also signal takes the function pointer of type
void handler_function (int parameter);

Comment: Changed the `sig_t terminate(){` to `void terminate(){` along with this solution. Works now. Thanks
Answer: Your signal handler does not match required prototype. You should redefine terminate() to take an int as parameter and return void.
That is,
void terminate(int sig) {
    printf("Thanks for the fish!\n");
    exit(EXIT_SUCCESS);
}

// ...
signal(SIGINT, terminate);

signal() handler gets fired immediately


Command Line Arguments in Imported Python Modules

Question: This is more a question of coding style, but I have a script that processes a particular file (or set of files). It would be nice to allow the user to provide those files as command-line arguments. Of course, it's possible that the user forgets to provide these or the filenames are invalid, so I have to introduce a try/except here.
Problem is, someone may want to import my module in the future. But, I don't know what command line arguments that program may require. Also, if an error is thrown when my module access the command-line argument, it seems like it would be better handled by the script that is importing my module. However, my script still needs to be able to cope as a stand-alone if an error is thrown.
Is there a smart way around this problem, or is the best solution just to abandon command-line arguments altogether?
Answer: The usual procedure:
import sys

def main(*files):
    # your program's logic goes here

if __name__ == "__main__": #i.e. run directly
    try:
        main(*sys.argv[1:])
    except IOError:
        handle_error()

If imported, __name__ will be != "__main__", thus nothing actually happens and the importer can call main(file1, file2). But if this script is the main script (i.e. not imported), it will just do what it does now, only in main.
Answer: Check if your file is being run or if it's imported thus:
def myFunction(file):
  #do stuff to file

if __name__ == '__main__':
  #I have not been imported!
  try:
    file = sys.argv[1]
  except:
    print "Usage: myFile.py file"
    sys.exit()
  myFunction(file)


Drill hole to mount metal junction box

Question: I am trying to install a metal junction box behind existing drywall. I cut a hole in the drywall next to the stud, and want to screw the left side of the box into the stud, but the holes that are pre-drilled into the box are too far forward and would go into the drywall, not the stud. Pardon the crude drawing.
Ideally, there would be screw holes further back in the box so I could install it into the stud, but I can't find any metal boxes that have that.  A few related Diy.SE posts suggest I can just drill my own holes (Can I side-mount metal box with holes in the back?, Why not use a plastic receptacle box for an outdoor outlet?) but doesn't making my own modifications violate the UL listing of the box and thus electric code? Am I allowed to drill my own holes (with some concrete information I can show my inspector to justify that), or if not, is there another solution to mount a metal box behind drywall?

Edit:The purpose of this box is to connect wires that run behind the drywall to conduit that will run on the surface. Thus, following a suggestion from the question in Best way to bring wire from flush-mount panel to surface-mount conduit I was going to use an extension box. If this is an X-Y problem, or if there is a better box or approach to doing this, I would appreciate suggestions.
Comment: Yes you can drill new holes to mount it so the front is flush with the drywall
Comment: do not understand your dilemma. There are virtually dozens of stud mount types
Comment: I am trying to mount this behind existing drywall, I guess what could be considered "old work". If I try to use a box with a mounting bracket on the side, I would have to cut a large section of drywall around the box. Ideally, I'm trying to mount the box without removing more drywall. If there is a stud mount type that can be inserted into a 4x4 hole, I would love to hear about it.
Comment: What's your surface solution here—what will be seen once your work is done?
Comment: You will see a box extender coming out of the wall with conduit running out of the side, and a cover plate (like the one you linked in your other comment) covering that. You can see the hole in the drywall behind the box which I don't like, but I can't figure out how to make that look better.
Answer: That box should have a mud ring of the correct thickness to account for the drywall and/or other wall finish mounted to the front to mount devices to. At which point the holes it has should land in the stud.

Image source - example not endorsement.
You could also use a box extension ring if you really just want the blank cover that fits the box type rather than a device or a finished cover plate that needs device mounting holes.
Comment: The purpose of this box is to take NM wire that was run behind the wall to conduit that will run on the front surface of the wall. Thus, following a suggestion from https://diy.stackexchange.com/questions/271276/best-way-to-bring-wire-from-flush-mount-panel-to-surface-mount-conduit, I was going to use an extension box. But if I install the box far back enough to use the screw holes in the studs, the extension box will not clear the drywall.
Comment: Also, I have a thick wire coming out the back of the box (NM 6-3). I can't push the box farther back into the wall because the wall is in the way.
Comment: @Daniel notice that your box has no provisions for mounting a cover plate, and you will need to use a diagonally-mounted cover plate in the style of the the mud ring Ecnerwal pictured to cover it anyway.  (Flat type linked from HD, but there are raised ones too: https://www.homedepot.com/p/Steel-City-4-in-Square-Metal-Electrical-Box-Flat-Cover-52C1-50R/205124442)
Answer: Get one like this one Raco box with bracket from Home Depot. It gives you the space and holes you need to mount it to the studs.
Comment: While this would be perfect for new construction, I already have drywall up. This would require me to cut a much larger hole to fit the bracket into (and larger still to have space to screw it in)

Drill hole to mount metal junction box


Returning to DialogFragment from another Activity reuses my enter animation

Question: I have an Activity (A) that creates a DialogFragment. In that DialogFragment, I have a button which creates a new Activity (B). When I finish Activity B, it displays the DialogFragment from Activity A and it reuses that custom animation I set. How do I prevent my DialogFragment from reusing that animation when returning to Activity A?
This answer works for some devices, however it freezes the entire window on some (hence the check version)
@Override
public void onStop() {
    super.onStop();
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
        getDialog().getWindow().setWindowAnimations(-1);
    }
}

https://stackoverflow.com/a/64454784/11110509
This is how I am creating my custom DialogFragment enter/exit animation:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.getWindow().getAttributes().windowAnimations = R.style.FragmentDialogAnim;
    return dialog;
}

loginactivity_left_to_right:
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate android:fromXDelta="-100%" android:toXDelta="0%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="700"/>
</set>

loginactivity_right_to_left:
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="-100%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="700" />
</set>

Here's the code for creating the DialogFragment:
https://pastebin.com/k1c6nz3p
Answer: You should disable the animation in onPause() method of your DialogFragment instead of onStop() method. Just remove all the lines of code you currently have in onStop() method and add onPause() with the below lines of code:
@Override
public void onPause() {
  super.onPause();
  if(getDialog()!=null)
    getDialog().getWindow().setWindowAnimations(-1);
 }

By doing it in onPause() method you are disable all window animations without also to freeze any touch events.
Comment: @NixSam I know this is old, but my solution to get round this was to reapply the animation - the trick being to put this into a runnable in the post method of one of your views, so that it doesn't get called until after the layout is drawn.
Comment: No way, there must be another solution to this! This will remove exit animation, as well.
Comment: @CharlieWalker good trick, I like it. It worked! Thanks! For other ones reading this, you can add
```
    override fun onResume() {
            super.onResume()
            view?.post {
                dialog?.window?.setWindowAnimations(R.style.BottomDialogSlideAnimation)
            }
         }
```
to have exit animation when user press back.
Comment: @NixSam I have facing same issue. Is there any other solution found apart from this? As I do not want to apply setWindowAnimation.
Comment: @MohitTrivedi No, Charlie's solution worked for me.
Answer: Recycling Views can always be problematic especially if you intend it to be slightly different in each scenario.
I would recommend that either you stop recycling this Dialog and instead create a specific Dialog for each of your different cases, or that you simply pass a flag into your Dialog defining what/when to use the animations.
Comment: what do you mean by recycling dialog? I have only created this dialog once in Activity A. I am returning to Activity A from Activity B.
Comment: You return to Activity A, and the Dialog is still there? Perhaps I didn't quite understand the problem.


Upper Bound for $|f^{n}(0)|$ given that $f$ is Analytic

Question: Let $f(x)$ be an analytic function in some neighborhood of $x=0$.
$f$ being analytic implies that its has a convergent Taylor series expansion about $x=0$. That is, there exists $R>0$ (radius of convergence) such that the Taylor series $$\sum_{n=0}^{\infty}\frac{f^{n}(0)}{n!}x^{n}$$ for all $|x|\leq R$.
The following is the part I do not understand. Any help will be appreciated.

This implies the existence of a constant $C$ such that $$|f^{n}(0)|\leq C\frac{n!}{R^n}.$$

Is it correct to say that for a convergent Taylor series, each term has an upper bound, say $C$, such that $\left|\frac{f^{n}(0)}{n!}x^{n}\right|\leq C$?
Added Later. The question is based on the following online notes (page 2, equations 10 and 11): Notes
Answer: There is one essential mistake in your question (your lecture notes, however, did it correctly): If $R$ is the radius of convergence of a power series
\begin{align*}
f(z):=\sum_{k=0}^\infty a_k(z-z_0)^k,
\end{align*}then it converges for all $|z-z_0|\color{red} < R$. Furthermore, for each $0<r\color{red}<R$ we have that
\begin{align*}
|a_k|\leq\frac{M_f(r)}{r^k},\qquad k\in\mathbb N_0,
\end{align*}
where
\begin{align*}
M_f(r):=\sup_{|z-z_0|=r}|f(z)|.
\end{align*}
In particular, since $a_k=\frac{f^{(k)}(z_0)}{k!}$ it follows that
\begin{align*}
|f^{(k)}(z_0)|\leq M_f(r)\cdot\frac{k!}{r^k},\qquad k\in\mathbb N_0.
\end{align*}
Now, in your notes you can assume that the radius of convergence is larger that $R$, hence the power series converges for all $|x|\color{red}\leq R$ and your statement is correct using $C=M_f(R)$.
Comment: Thank you. Can you please explain the meaning of \begin{align*}
M_f(r):=\sup_{|z-z_0|=r}|f(z)|.
\end{align*}
Comment: $M_f(r)=\sup\{|f(z)|\in\mathbb C\ |\ |z-z_0|=r\}$ is the maximal value which is attained by $|f|$ on the circle with center $z_0$ and radius $r$.
Answer: This is not true.
Let $f(x)=\sum_{n=0}^\infty  nx^n$. Then $f$ is analytic in $(-1,1)$, and the power series has radius of convergence, around zero, $R=1$. But
$$
f^{(n)}(0)=n\cdot n!,
$$
and hence ($R=1$)
$$
\lvert\,f^{(n)}(0)\rvert = n\cdot \frac{n!}{R^n}.
$$


How to determine if hardwoods are under cabinets?

Question: I'm house shopping and some homes have built-ins or kitchen cabinets that I'd like to remove.  I was wondering, first, is it possible to determine without taking the cabinets apart whether there are hardwood floors underneath?
Also, if there are not hardwoods underneath, how feasible/costly is it to patch a section of hardwood flooring to get a decent match to the existing?  Would the whole floor need refinishing?
Comment: First question would be, how old is the house? Secondly, do you have laminate floor in place? A close-up picture of the flooring, and a picture of the general room, highlighting the floor would help on both questions.
Comment: @Jack Not for a specific house necessarily.  We've seen many houses where we'd want to remove built-ins.  I'm looking for techniques to detect--or at least find evidence for or against  what's under the cabinetry.
Answer: If it is an older house with existing hardwood floors, there is a terrific chance of the floor going under the cabs, If there is laminate flooring, The chances are nil it goes under.
On older homes, with hardwood floors if the cabinets are removed, they may need to be refinished anyway since the floors usually are never sanded and stained under the cabinets, but it beats a tie in and refinish. On newer homes, I have seen cabinets placed on the subfloor or on plywood to raise them up, and the flooring run to the cabinets.
With laminate floors, if you can find the flooring still, you will need to pull a piece to match it up by. This will have to be done anyway to some degree to tie in the new with the old, if that is what you have. You could try to patch the immediate area, which I do not recommend. I would pull up the flooring to the affected area and relay the new to recover the cabinet's foot print.
Comment: To expand a little on this answer, if the home was built after 1950, the chances of having existing hardwood under the cabinets is very small. Typically homes built before the end of WWII were built with higher quality materials and would have hardwood floors throughout. After the war, there was a housing boom and to compensate, builders started to use cheaper materials and cut corners. Today, virtually no builder would put a finished product under a built in cabinet because of cost.
Answer: 3 choices

Measure toe kick height.  These are usually right at 4 or 4.5 inches.  I might assume that if toe kick was 3 3/4" then there was probably no hardwoods under.  This is not the best way though because toe kicks can be non-standard.
Remove a piece of trim and see if you see the bottom of the cabinets.  This might just be pulling back some quarter round.
This suggestion is pretty dubious.  You can always drill a hole in the cabinet to see.  If the hole is off to the side in the very front corner no one would ever see unless they were in the cabinet.
Comment: @Tester101 Hey now, quarter round looks great in a fire.
Comment: I'd say just the existence of quarter round, would point to the flooring not going under the cabinets.  The quarter round is likely there to hide the expansion gap, since almost nobody actually likes the appearance of quarter round.
Comment: @Tester101, not necessarily. We have shoe-molding (admittedly, not quarter round, but the same concept) all around our kitchen and bath cabinets, and kitchen island, all of which have been installed directly *on* vinyl floors. Shoe molding here is just a design element that breaks up sharp inside corners, period.
Comment: @alt Decorative moldings are design elements, quarter round is a cheap methods to cover expansion gaps.
Comment: @Tester101 - quarter round was trendy in the late 60s to early 80s.  Just because it frowned upon now doesn't mean it doesn't exist from decoration.  There is LOTS of quarter round that I pull from houses for really no reason at all.  Would people install it now?  Probably not.  Would they pull up something from their house unless doing a major renovation?  Probably not.
Answer: I think the easiest way to tell, look for a quarter round trim between the cabinet and the floor.  If it has a quarter round, then two options:  floor does not go under the cabinet, or the owner likes the look of the quarter round.  If it doesn't have a quarter round, floor goes under the cabinets, and if it doesn't it is pretty easy to see it doesn't (hence the need for the quarter round).  But if you see the quarter round, just assume it doesn't go under.
If the kitchen has tile, look at the grout lines.  If the tiles are cut to fit next to the cabinets with a grout line between, then the tile does not go under.
Comment: Another possibility is that the cabinets may have a kickplate that's 1/2" or so in front of the joint between the cabinet and the floor.
Answer: Sometimes you can tell by looking under the dishwasher.  Most have a plate that either moves or can be unscrewed.  Then, you can sometimes look at the edges.
Also, you can sometimes tell my walking on floors...if it's a floating floor, no it should only go up to cabinets (or if it's underneath it's done improperly and you may have other issues.
If you are going to replace cabinets and use same footprint, this is not a big deal at all. If you will change footprint and there is a section missing, you often can weave in new wood and refinish the room.  It' very easy to do if it's oak.
Comment: Self promotion is frowned on around here, see [What kind of behavior is expected of users?](http://diy.stackexchange.com/help/behavior).
Answer: Easiest way is to look under stove- bottom drawer typically pulls right out and the bottom panel is most often a skeleton type.  Also pull the trim panel at bottom of dishwasher and check there too.


POST request from Postman to Laravel

Question: I am trying to send a post request to a Laravel project using Postman, but I get a "419 unknown status" response
routes\web.php:
Route::post('/myaction', 'MymodelController@myaction');

app\Http\Controllers\MymodelController.php:
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Mymodel;

class MymodelController extends Controller
{
    function myaction()
    {
        return redirect('/');
   }
}

Why does this happen?
The same error appears independently of the content of myaction()
Comment: The `csrf`? No, how can I send it through Postman?
Comment: Thank you! The solution was to use api.php instead of web.php. (Please write it as a reply, for further help to other viewers)
Answer: As you are requesting api you should write your route in api.php instead web.php
web.php require _token the csrf field
Answer: By default, Laravel use the middleware VerifyCsrfToken.
See this
for more details.
You need to add your URL to the $excludes field inside VerifyCsrfToken class.
Answer: Do you have defined route for redirect('/'); in web.php ?
Comment: Yes `Route::get('/', function () {
     return view('welcome');
 });`
and GET request in / works properly. If I try to create a `Route::post('/'` the same 419 issue appears
Comment: in your form you must also send csrf token
{{ csrf_field() }}

POST request from Postman to Laravel


error: request for member size in ... which is of non-class type char

Question: I'm not very good at programming, nor experienced, and this is for a class where the teacher is of negligible aid.
The title is the error I'm getting.  This is the function:
void CapFormat (string Names, int NameCount)
 {
   int Comma;
   int c;
   int d;

    string::size_type len;

   for(c = 0; c < NameCount; c ++)
   {
     len = static_cast<unsigned> (Names[c].size);  //error starts here
     for(d = len; d > 0; d --)
     {
       tolower((Names[c].at(d)));  //supposed to lower cases every letter
     }
     touppper(Names[c].at(0));  //supposed to upper case first letter
     Comma = Names[c].find(",");  //supposed to find a comma between last and first names
     Comma = Comma + 1;
     toupper(Names[c].at(Comma));  //Error here as well.  supposed to then upper case letter after the comma.
   }
 }

Here is the expanded version of the errors:
In function âvoid CapFormat(std::string, int)â:
error: request for member âsizeâ in âNames.std::basic_string<_CharT, _Traits, _Alloc>::operator[] [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((long unsigned int)c))â, which is of non-class type âcharâ
error: request for member âatâ in âNames.std::basic_string<_CharT, _Traits, _Alloc>::operator[] [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((long unsigned int)c))â, which is of non-class type âcharâ
error: request for member âatâ in âNames.std::basic_string<_CharT, _Traits, _Alloc>::operator[] [with _CharT = char, _Traits = error: âtouppperâ was not declared in this scope
error: request for member âfindâ in âNames.std::basic_string<_CharT, _Traits, _Alloc>::operator[] [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((long unsigned int)c))â, which is of non-class type âcharâ
error: request for member âatâ in âNames.std::basic_string<_CharT, _Traits, _Alloc>::operator[] [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((long unsigned int)c))â, which is of non-class type âcharâ

Cstring, cctype, and string are all included.  I've copied the syntax directly from my book, everything should be in order, but the errors remain.
Assistance would be greatly appreciated.
Answer: Firstly, the way you use the Names parameter in your code suggest that it is supposed to be an array. But you declared it as a single object. Hence the errors.
The parameter was apparently supposed to be declared as either
void CapFormat (string Names[], int NameCount)

or
void CapFormat (string *Names, int NameCount)

(which is the same thing.) Compare this to your book. It is either your mistake or an error in the book.
Secondly, the size line is supposed to look as
len = static_cast<unsigned>(Names[c].size());

(note the extra ()). And there's absolutely no need for that static_cast to unsigned there. Just do
len = Names[c].size();

Was this static_cast your idea? If it is in the book, that would be a rather strange book.
The illogical mix of inappropriate int variables and proper string::size_type variables makes me doubt that this was actually taken from a book.
Comment: Another error `tolower((Names[c].at(d)))` should be `Names[c].at(d) = tolower(Names[c].at(d));`. tolower and toupper are functions which return the lower case or upper case version of a character. You then have to do something with that returned character, like assign it back to a string. Did your book get this wrong as well?
Comment: Yes it was taken straight from the book.  And yes it is rather strange.  Your advice fixed the errors I pointed out right away, in direct contradiction to what the book says should work.  thank you very much.
Comment: @LawrenceBenecke A book that is wrong, a teacher who's no help, you've got it tough. At least SO is here.
Comment: @LawrenceBenecke You should probably accept/upvote AndreyT's answer


How to put result of Promise.all at specific place?

Question: Is there any way to use Promise.all in my case ?
Should i use two different loop (one to push in an array of promise and another to push each result to the right place) ?
(This is just an example and my current code contains much more data, so using Promise.all seems very interesting since the requests are independent of each other)
const  myFunction = async ()=>{

    let someData=[{ID:55,name:'name1',firstname:'fname1',address:'address1'},
                  {ID:26,name:'name2',firstname:'fname2',address:'address2'},
                  {ID:88,name:'name3',firstname:'fname3',address:'address3'}]

    for (let i = 0; i < someData.length; i++) {
       someData[i].country = await getCountryFromDatabase(someData[i].ID)
      }

    }

Thank you
Answer: Map the array to an array of promises, using the reference to the object you have in the mapping callback to mutate it after the API call finishes.
let someData = [{ ID: 55, name: 'name1', firstname: 'fname1', address: 'address1' },
    { ID: 26, name: 'name2', firstname: 'fname2', address: 'address2' },
    { ID: 88, name: 'name3', firstname: 'fname3', address: 'address3' }]
await Promise.all(
    someData.map(obj => (
        getCountryFromDatabase(obj.ID).then((country) => {
            obj.country = country;
        })
    ))
);


Access - How to display data on a subform from multiple combobox

Question: I have a form that I have 3 different combobox's that I want to be able dynamically filter on. The ComboBox's are called cboVendor, cboRegion, cboPosition. When I filter on the ComboBox's individually it works fine, but when I try to filter on Vendor then Region then Position, the subform updates the data on only on the last combobox dropdown I select instead of limiting the data to only the previously selected combobox.
I was able to get each combobox to dynamically update depending on the the other boxes, I just cant get the subform to display the data this way.
Below are the individual subs i have for each combobox:
Private Sub cboVendor_AfterUpdate()
Dim myVendor As String
myVendor = "Select * from TblVendor where ([Vendor] = '" & Me.cboVendor & "')"
Me.tbl_Vendor_subform1.Form.RecordSource = myVendor
Me.tbl_Vendor_subform1.Form.Requery
Me.cboRegion = Null
Me.cboPosition = Null
Me.cboRegion.Requery

End Sub

Private Sub cboRegion_AfterUpdate()
Dim myRegion As String
myRegion = "Select * from TblVendor where ([Region] = '" & Me.cboRegion & "')"
Me.tbl_Vendor_subform1.Form.RecordSource = myRegion
Me.cboPosition = Null
Me.cboPosition.Requery

End Sub

Private Sub cboPosition_AfterUpdate()
Dim myPosition As String
myPosition = "Select * from TblVendor where ([Position] = '" & Me.cboPosition & "')"
Me.tbl_Vendor_subform1.Form.RecordSource = myPosition

End Sub

Answer: Try using this command.
strDataSource = "Select * from TblVendor where ([Vendor] = '" & Me.cboVendor & "' AND [Region] = '" & _
            Me.cboRegion & "' AND [Position] ='" & Me.cboPosition & "')"

Me.tbl_Vendor_subform1.Form.RecordSource = strDataSource
Me.tbl_Vendor_subform1.Form.Requery


Prevent a google sheets IF(TODAY()) function from editing after a certain date

Question: I'm trying to build a google sheets cell that updates after a certain date.
The function I'm using is =if(today()=oct 4, count(A:A)) which will just count rows. The only issue I'm encountering is that the A:A column updates regularly and I want it to just be static.
Ideally on october 4th the A:A column would be counted and it just get turned into a static value.
Not sure if a complete apps script would be the better option.
Comment: Use and time based trigger and a function.
Comment: Have you tried using apps script as mentioned on the previous comment and the answer?
Answer: Since you cannot automatically fix values using a formula, you need to use apps script. Ideally use an apps script which contains a trigger depending on your needs, as I assume that you do not only have a single instance where you want to fix the values from the formula. If you are clear about what you want to achieve then the community can help you. And we always appreciate if you've tried doing t yourself in order to see your effort.


Display Cyrillic and special characters in dp:serialize (DataPower)

Question: I want to display a whole SOAP message using XSL. I know that message is in var://context/INPUT variable and to display a whole message I use serialization <dp:serialize select="dp:variable('var://context/INPUT')"/> (dp is for IBM DataPower variables).
But this way, if message contains characters like ćčš or љњшђж they are displayed like #1084;&#1080 and so on. disable-output-escaping = "yes" doesn't work with serialization.
Any ideas how to resolve this problem?
Comment: Can you clarify where do you want to display the SOAP message? If you could throw some more lights into what do you want to achieve may be I can help? - Ajitabh
Comment: disable-output-escaping is not property of dp:serialize.
Answer: As long as the message is XML you can't really do anything about it as DataPower will escape those characters, else risking "destroying" the message if there is a character code conversion.
You would have to convert the message into a binaryNode to get round that issue I am afraid.


Firefox Crashes at launch on 17.10 (Lubuntu and Xubuntu)

Question: Very old Shuttle PC with an AMD Athlon XP 1800, 2GB RAM. I've installed Xubuntu 17.04, 17.10 and Lubuntu 17.10. On all when I launch Firefox I immediately get a crash report.
report includes:
<code>Build ID 20171227151402
releasechannel: release
safemode: 0
threadIdNameMapping: 5585:"Gecko_IOThread",5586:"Timer",5587:"Link Monitor", 5588:"Socket Thread",5589:"JS Watchdog",
Throttleable: 1
UptimeTS: 1.063488
Version: 57.0.3
</code>
I've removed and reinstalled Firefox. Any suggestions?
Comment: Does the crash report include anything else ? The info you posted does not seem very relevant - it should say _why_ it crashed.
Comment: See [here](https://support.mozilla.org/en-US/kb/firefox-crashes-asking-support) - does it start in safe mode ? You can start in safe mode by opening a terminal and typing  `firefox --safe-mode`. If not, you can get the techincal info by opening the newest file in `~/.mozilla/firefox/Crash Reports/submitted/` - it's a hidden directory - Ctrl + H should show it in the file manager.
Comment: just my info, install time, product ID, seconds since last crash. Since I have to type it out, I only picked the parts that I thought might be helpful at all. I expected a little more too. At the end it says, "This report also contains technical info about the state of the application when it crashed." However, I don't see any way to gather that info.
Comment: Safe mode has same issue: crash reporter pops up immediately.
Comment: The crash reports aren't helpful as far as I can tell. The entire contents of LastCrash is`1514998099`, in the Submitted folder there are a few crash files, complete content is `Crash ID: bp-e392caa3-e254-4289-9c55-b1ca30180103`
Comment: Turns out Chromium crashes and so far I can't get Opera to open at all. Chromium takes about 3 minutes, then a crash reporter pops up and disappears after about 1 second.
Comment: there's something bigger going on. opera crashes too. I try to launch it and about 4 minutes later I get a crash report. When i click "more Details" the crash reporter crashes.
Comment: If this used to work I recommend a [package sanity check](/a/57728/175814). If that doesn't turn up anything, try a different graphics driver.
Comment: Newly imaged machine and new machine to me. Trying to set this up for a client. Thank you for your help. I'll see about any driver updates and if that doesn't do it, it's not worth spending time and money on.
Answer: Athlon XP doesn't support the SSE2 instruction set.  Firefox made SSE2 mandatory after v48.0.2. You would think the install would detect the processor type and inform the user before aborting and the latest compatible browsers for these older processors would be offered in the repositories, but No. The only Firefox in the repository is a later version that won't run on Pentium III and Athlon XP. You have to download v48.0.2 from somewhere.  Chrome doesn't work, either. So your only clue is a crash during install or 1st run.


change tableview cell color to click

Question: I have a TableView that represents a calendar. Each cell is one day. and I want to add an event to the cells. When the cell is clicked, the background must be changed to red ... it should be possible to select more than one cell
Comment: Please show what you've tried so far, so we can understand how to help.
Comment: https://drive.google.com/open?id=1YhlIuQySsPeYn4O7aOmC2kU5kod7sSZm
This is the link of my project ... you must execute the MainRank class and select a very high rank (1 year is fine). Then you will see the calendar with the dates and if you click on a cell, the background color will change correctly. but if you lower and raise with the scrooll, the selection is distorted.
Answer: If it's just selection that you need you can use a selection model with multiple selection an cell selection mode.
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
table.getSelectionModel().setCellSelectionEnabled(true);

CSS stylesheet
.table-cell {
    -fx-selection-bar: red;
    -fx-selection-bar-non-focused: red;
}

If you don't want to use the selection model, you need to store the data in your items and use a custom TableCell
public class DayCell extends TableCell<Week, Boolean> {

    {
        setOnMouseClicked(evt -> {
            if (!isEmpty() && getItem() != null && evt.getButton() == MouseButton.PRIMARY) {
                WritableValue<Boolean> property = (WritableValue<Boolean>) getTableColumn().getCellObservableValue((Week) getTableRow().getItem());
                property.setValue(!getItem());
            }
        });
    }

    @Override
    protected void updateItem(Boolean item, boolean empty) {
        super.updateItem(item, empty);

        if (empty || item == null) {
            setStyle(null);
        } else {
            setStyle(item ? "-fx-background-color: red;" : null);
        }
    }
}

column.setCellFactory(c -> new DayCell());

This requires the ObservableValues returned by the cellValueFactory to implement WritableValue<Boolean> in a way that stores the data in table item class. Using a BooleanProperty stored in this class would do the trick.

I don't think it's a good idea to use TableView in this case though. It's not designed to display a fixed size non-resizable grid.
Comment: Hi, I have followed your advice. but I have an error when column.setCellFactory (c -> new DayCell ());
do you think you can check my project link and translate your idea
Comment: @MichaelSalinasRios You need to change `Week` to the item type of the `TableView`. I just used this name since it's a reasonable assumption that you're using the days of the week as columns.
Comment: Yes I do. in the column statement. with my WeekDates class, but when you load the calendar it paints the entire entire column

change tableview cell color to click