Why did a new drain pipe cause my septic tank to smell outside?

Question: We have (what I think) is a pretty standard setup: various drains converge in the basement and exit through a single pipe out to the septic tank. I have lived in this house for 13 months and never noticed a smell from the septic tank outside the house.
A family friend "helped" install a new 3" drain from the upstairs into the basement. The drain had nothing "on top" yet, just an open pipe. The drain line runs down through an HVAC duct, exits into the basement and ties into an existing drain line. The design is bad and flawed but that's for another discussion. Of course, we have a smell in the house due to the open drain.
However, the day that this work was done, I started to notice an intermittent raw sewage smell outside the house from the septic tank. Septic people told me it was normal to occasionally have a smell, but this was too much of a coincidence to me. As a hedge I had the tank pumped, the intermittent smell persisted.
A contractor has since removed the new drain line and put things back as they were. The smell outside straight away is gone.
On to my question: why can reconfiguring the drains in this fashion cause a septic smell outside the house?
Comment: Apparently you have the answer in your question ...which is YES!
Comment: Haha, yes I see that it _can_ be the cause but I was mainly curious as to the _why_ :)
Comment: The only reason I can think of as a non plumber, is that the pipe was adding extra air into the tank.  I do not think this is a good reason, since the pipe should have let the gases out in the house.
Comment: Were there open windows where the _eau de toilet_ was wafting out?
Comment: Because largely it makes no sense to me (as a total layman) that reconfiguring the drainage inside the house can cause the tank to start smelling... But there obviously is a reason, and the septic people I spoke with just said "oh it's normal for the tank to smell sometimes".
Comment: @FreeMan Good point but the smell was _pronounced_ outside the house around the tank. It was not very strong inside and only noticeable when the HVAC fan kicked off. I'm really sure it was two separate issues.
Answer: If your HVAC system has a fresh air intake -- for example a small duct to the outside to add 10% fresh air whenever the blower runs -- then you could have positive pressure in the house. If you feel air in your face when you open the front door slightly from outside when the HVAC is running, you have positive pressure.
You had a faulty drain setup, and if there was no P-trap between the open drain pipe in the house and the septic tank, you would have been forcing air into the septic tank through the new drain whenever the HVAC runs.
That air would have to go somewhere. It would seep out of the septic tank cover, which is not air-tight, and assuming it is buried by a couple inches of soil, the air and consequently odors would emanate from the area of the septic tank.
Comment: This sounds quite logical, @TheNextman, however it only applies if _you_ have a fresh air intake. Also, you might want to wait a bit before clicking that check mark, as it may discourage others from answering and you might miss out on some other good info.
Comment: Marking as answered in the face of any other suggestions. Thank you!
Comment: The HVAC indeed has a fresh air intake
Comment: @TheNextman FreeMan beat me to it! I was going to mention that it's customary here (for future reference) to wait 24 hours before accepting an answer because we have regular contributors all over the world. It's nice to know that you do indeed have a fresh air intake on your HVAC so the answer is plausible.


Azure ARM template dynamic variable binding

Question: How do I get the value of a key from a list by passing a dynamic variable?
My Code
<code>    "variables": {
                "locationCodeList": [
                  {
                    "southcentralus": "ussc",
                    "northcentralus": "usnc",
                    "westcentralus": "uswc",
                    "centralus": "usce",
                    "westus": "uswe",
                    "westus2": "usw2"
                  }
                ],
                "locCode": "[variables('locationCodeList')[0].(resourceGroup().location)]"
}
</code>
I want to get the value ussc when the resourceGroup().location is southcentralus. Is there a better way to achieve this?
Answer: Its json so you can just use []
I used this command to test the template below.
az deployment group create --resource-group rg-test --template-file .\blank.template
Update to make locationCodeList an object instead of an array.
<code>{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "22.214.171.124",
  "parameters": {
  },
  "variables": {
                "locationCodeList": {
                    "southcentralus": "ussc",
                    "northcentralus": "usnc",
                    "westcentralus": "uswc",
                    "centralus": "usce",
                    "westus": "uswe",
                    "westus2": "usw2"
                  },
                "locCode": "[variables('locationCodeList')[resourceGroup().location]]"
},
  "resources": [
  ],
  "outputs": {
    "locCodeOutput": {
      "type": "string",
      "value": "[variables('locCode')]"
    }
  }
}
</code>
In case there was a need for this I wanted to leave it.
<code>{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "220.127.116.11",
  "parameters": {
  },
  "variables": {
                "locationCodeList": [
                  {
                    "southcentralus": "ussc",
                    "northcentralus": "usnc",
                    "westcentralus": "uswc",
                    "centralus": "usce",
                    "westus": "uswe",
                    "westus2": "usw2"
                  }
                ],
                "locCode": "[variables('locationCodeList')[0][resourceGroup().location]]"
},
  "resources": [
  ],
  "outputs": {
    "locCodeOutput": {
      "type": "string",
      "value": "[variables('locCode')]"
    }
  }
}
</code>
Comment: Note that for simple object property reference you don't need the [0] - you can remove that and the [] in the var definition - here's a similar example: https://github.com/bmoore-msft/AzureRM-Samples/blob/master/paired-region/azuredeploy.json
Comment: True, could update the variable so instead of an array it was just a JSON object.  Thanks for that callout I have updated my answer to reflect that, and I should have done it.


HOC/Render-Call Back or Library function?

Question: I'm working on a project where a prospect needs to be sent an email about a property they are interested in. There is a top level component that fetches the property information and prospect's contact info from the database and passes to its children. There are two components that share the same process of formatting the information, and then call an email function that sends off an email. A sample of one component looks like this:
import sendEmail from 'actions/sendEmail'

class PropertyDetail extends React.Componet {
  state = {
    unit: undefined,
    prospect: undefined,
  };

  componentDidMount = () => {
    this.setState({
      unit: this.props.unit,
      prospect: this.props.prospect,
    });
  };

  sendEmail = ({ id, address, prospect }) => {
    // quite a bit more gets formatted and packaged up into this payload
    const payload = {
      id,
      address,
      prospectEmail: prospect.email,
    };

    emailFunction(payload);
  };

  handleEmail = () => {
    sendEmail(this.state);
  };

  render() {
    return (

{this.state.unit.address}

Send prospect an email about this property

        <button onClick={this.handleEmail}>Send Email</button>

    );
  }
}

and the other component looks like this
class UpdateShowing extends React.Component {
  state = {
    unit: undefined,
    prospect: undefined,
    showingTime: undefined,
  };

  componentDidMount = () => {
    this.setState({
      unit: this.props.unit,
      propsect: this.props.prospect,
      showingTime: this.props.showingTime,
    });
  };

  sendEmail = ({ id, address, prospectEmail }) => {
    // quite a bit more gets formatted and packaged up into this payload
    const payload = {
      id,
      address,
      prospectEmail,
    };

    emailFunction(payload);
  };

  handleUpdate = newTime => {
    // get the new date for the showing ...
    this.setState({
      showingTime: newTime,
    });

    // call a function to update the new showing in the DB
    updateShowingInDB(newTime);
    sendEmail(this.state);
  };

  render() {
    return (

Modify the showing time

        <DatePickerComponent />
        <button onClick={this.handleUpdate}>Update Showing</button>

    );
  }
}

So I see some shared functionality that I'd love to not have to repeat in each component. I'm still learning (working my first job), and why not use this as an opportunity to grow my skills? So I want to get better at the HOC/Render props pattern, but I'm not sure if this is the place to use one.
Should I create a component with a render prop (I'd rather use this pattern instead of a HOC)? I'm not even sure what that would look like, I've read the blogs and watched the talks, ala
<MouseMove render={(x, y) => <SomeComponent x={x} y={y} />} />

But would this pattern be applicable to my case, or would I be better off defining some lib function that handles formatting that payload for the email and then importing that function into the various components that need it?
Thanks!
Answer: I think a provider or a component using render props with branching is a better fit for you here
see this doc: https://lucasmreis.github.io/blog/simple-react-patterns/#render-props


Are multiple UIView animation callbacks a bad idea (i.e. cause mem issues)?

Question: I have multiple UIView animations running in my app.  They are very short, and then make callbacks to a method that then usually fires off another animation.  This leads to a lot of little animations running at the same time, each firing back callbacks.
This actually performs pretty well, and for the first few levels (the app is a game), no problems are observed.  However, as you continue to play deeper into the game, I'm starting to get memory warnings and ultimately crashes.  I've put NSLog in all of my dealloc methods, so I can see that everything is being properly released and dealloc'd.  I've also run static analysis on the app and fixed anything it found.
The weird part to me is this:  Shouldn't any performance problems caused by running multiple animations be processor bound (i.e. shouldn't I see a bunch of slowdown and such)?  It seems that everything performs just fine, it just runs up memory too fast and there's nothing more I can free.  Is there something in the framework on the UIView side of things that will need lots of memory to do these operations?  Is there perhaps a leak in the framework I need to avoid when doing these?
Additional note:  I'm animating a custom class that extends UIView and has a label and a UIImageView inside of them.
Answer: Multiple animation shouldn't cause memory warnings..
I suggest you should run Instruments for Leaks, ObjectAlloc & CPU Samplers..
That would give a much better view than NSLogs in dealloc
Comment: Looks like the multiple animations are performing fine.  You were right - I had a few things inside of the custom views I'm animating that were incorrectly alloc'd/released and were causing the leak.  I was confident my classes were being correctly dealloc'd (and they were) but I missed that I was leaking some core UI classes in the process.
Answer: You don't show any code so it's hard to give specific advice, however, have you considered using Core Animation layers instead of UIViews? If you need to animate text, you'll have to use a view since there is no CATextLayer on the phone, however, Core Animation provides the facilities to draw complex sprites in a 2d space making it a great candidate for many games.
Best Regards.


How to resolve "docker build" requires exactly 1 argument. error?

Question: I'm trying to do docker build with the following command and I get the following error:
C:\>docker build --no-cache -t myrabbit -f dockerfile_rabbitmq
"docker build" requires exactly 1 argument.
See 'docker build --help'.Usage:  docker build [OPTIONS] PATH | URL | -Build an image from a Dockerfile

My dockerfile: dockerfile_rabbitmq is defined and present in that directory. I'm not entirely sure why I'm getting this error. Any help would be appreciated!
Comment: You have not provided any arguments. You have only specified flags.
Comment: `docker build --no-cache -t myrabbit -f dockerfile_rabbitmq .` provide build context, it can be `dot .`
Comment: RESOLVED: I had to rename the dockerfile to `dockerfile` and change to the following cmd as follows: `docker build --no-cache -t myrabbit -f ./dockerfile.txt . `
Answer: You forgot the . at the end of the docker build command.
so your docker build command should be like this
docker build --no-cache -t myrabbit -f Dockerfile .

Comment: Thanks for the comment! That was the issue; it's working!


permission denied target 'xyz' is not a directory

Question: Please help with this question :
Create a new user called hos with password 123. In the home directory of this user, create a file called xyz, containing a list of all files and directories from /etc that start with a.
Make sure the newly created user owns the file.
I am using this but it says permission denied target '/home/hos/xyz' is not a directory
sudo adduser hos password 123
mkdir /home/hos/xyz
sudo cp -r /etc/a* /home/hos/xyz

Comment: sudo adduser hos password 123
mkdir /home/hos/xyz
sudo cp -r /etc/a* /home/hos/xyz
chown -R hos /home/hos/xyz
Comment: `mkdir` is for making directories. You should be trying to make a file that contains a list of all files and directories starting with `a` in `/etc`. You shouldn't be trying to make a directory called `xyz` with a copy of every folder and file starting with `a` inside.
Answer: To answer your question you need a few steps to solve that. As first you create a user and his username, add a group for him and add him to this group.
This you can do with one command or multiple commands, first the multiple approach where I add in comment lines for explanation:
# adding a user hos with password 123 which you have provide by hand
# you can add the password into the line with the -p flag but you have
# provide the password in encrypted format then.
sudo adduser hos

# adding a group with the same name as the user
sudo addgroup hos

# adding the newly created user to this newly created group
sudo usermod -aG hos hos

Same you can achieve with only the adduser command like in the following line. For options on the adduser command see its man page.
adduser --ingroup hos hos

Now to the second part of that question, creating a file containing the names of files in /etc which begin with a. This is simply achieved by listing the files with ls /etc/a*.
ls /etc/a* | sudo -u hos tee ~hos/xyz

This should be all.
Comment: You didn't create the group hos though?
Comment: [It is almost never a good idea to parse the output of `ls`](http://mywiki.wooledge.org/ParsingLs). In any case, it is not needed at all here, all you want is `ls /etc/a*`.
Comment: You don't need to create the deault homedir, adduser usually creates a homedir in /home/ automatically using `/etc/skel` as it's template. Unless you specify `--no-create-home`.
Comment: You should not need to take care of the primary group when you use `adduser` It automatically creates a group of the same name as the user and adds the user to it. You also don't need the `--ingroup`.


How do you stop the floor from squeaking?

Question: I have a home built in the 1940's. The main floor creaks a lot and more squeaking and creaks seem to spring up in new places all the time.
Is there an easy way to stop the squeaking and creaking? I don't necessarily need to prevent future annoyances, but I would like to stop the loudest creaking now.
The basement ceiling (bottom of main floor) is mostly exposed (if that helps).
Comment: See also http://diy.stackexchange.com/questions/392/how-do-i-fix-a-squeaky-floor-below-my-carpet
Comment: The solution depends on the type of flooring you have.  Carpet?  Hardwood?  Tile?
Answer: The main cause of wood floors squeaking is wood shrinkage around the nails. If you can localize the areas that are the worst, a common way to minimize squeaks is to drive screws up from the bottom through the subfloor into the hardwood. Be absolutely sure to use screws that are long enough to grab the hardwood, but short enough not to stick through.
If you do not have hardwood floors then you'll have to decide among a few different techniques appropriate for specific floor coverings, ie. carpet, tile, vinyl etc.
With carpet, for instance, there are special breakaway screws (such as these made by McFeely's) that can be installed from above. With tile or vinyl, the screw from under method is often the way to go.
Comment: Would cross bracing under the floor help?
Answer: I have used "Counter-Snap" through vinyl and carpet, and it worked great.

All it takes is to locate the squeak, insert the patented "snap off" screw into the fixture, drill it down and let it snap off.
Comment: also described here:  http://diy.stackexchange.com/questions/392/how-do-i-fix-a-squeaky-floor-below-my-carpet
Comment: I used these in a few parts of my house with mostly good results.  Overall, they're definitely worth a try.  But there may be some squeaks they can't fix.
Answer: I just finished fixing squeaks in hardwood floors my 1950's house. Most of the squeaks were caused by gaps between sub-floor and joists. I just inserted wood shims in between ( I bought them in Home depot for 5 bucks). Have somebody walk or jump on the area where the squeak is, and if you can see sub-floor movement, just stick shim in there. Do not overpush them, because it will cause floor to raise too much.
Hope this helps.
Answer: For a temporary fix, use some talcum powder. Work the powder into the joints between boards with a paintbrush and sweep away any excess.

ThisOldHouse.com
Comment: Please add a little more detail here, like where you use the talcum powder, how you apply it etc.


Why is co-op more popular than team-based multiplayer?

Question: I've noticed that the vast majority of servers are co-op rather than team-based multiplayer.  This seems to be skewed in comparison to most other first-person shooter online games, which would have the majority of the servers running a team-based multiplayer configuration (Assault, Capture the Flag, Team Deathmatch, etc.).
Is there a particular reason why ArmA II is the opposite?
Answer: Because you just don't play ArmA, ArmA 2 and Operation Flashpoint like CoD (just ONE example). It's an entirely different gameplay and, dare I say it, genre.
While CoD is an arcade/arcade-ish - shooter which focuses a lot more on Player vs. Player.
ArmA, ArmA 2, OFP are the closest what you get in terms of war-simulators on PC. Like the name suggests,    Bohemia Interactive Studio (the dev studio) want to simulate real war, it's hard to integrate Team Deathmath, CTF or Assault in a simulator game, although not impossible.
If I recall correct, Bohemia Interactive Studio said in some interview way back then, their focus is more along wanting players to play together rather than against.
Being a war simulation game is also its weakness because of that it's not so wide spread like CoD, Counter Strike or Battlefied, it's "too complicated" to play if you will.
Comment: Sure, but Project Reality, based off of the Battlefield 2 engine is 100% team-vs-team and I dare say much more coordinated than anything I've experienced so far in ArmA 2.  Now I understand that clan-based games would have a greater ratio of experienced players, but again, coop?  Just doesn't make sense to me when humans are going to be so much more of a realistic opponent than the AI.
Comment: I should add that they're working on a Project Reality mod for ArmA 2.
Answer: ArmA 2 is a game which will gleefully kill you in a dozen ways before the breakfast and in a typical scenario, there is no respawn. Most of the time you really need all the help you can get, not even more guys trying to drop an artillery strike on your position just because they can.


Is there any other number that has similar properties as $21$?

Question: It's my observation.
Let
$$n=p_1×p_2×p_3×\dots×p_r$$
where $p_i$ are prime factors and
$f$ and $g$ are the functions
$$f(n)=1+2+\dots+n$$
And
$$g(n)=p_1+p_2+\dots+p_r$$
If we put $n=21$ then
$$g(f(21))=g(231)=21.$$
I checked it upto $n=10000$, I did not find another number with this property $g(f(n))=n$.
Can we prove that other such numbers do not exist?
Comment: @PruthvirajHajari Did you come up with this problem by yourself? If so, please state that in your question and include the program code used to run it.
Comment: @PruthvirajHajari sure it is.
Comment: To clarify, is $g(12)=5$ or $=7$?
Comment: 12=3*2*2 then g(12)=2+2+3=7
Comment: I encourage you to accept my answer by clicking the tick you see beside it.
Comment: @ParclyTaxel now is it okay? And thank you so much for your answer
Answer: This is a very interesting question…
$\newcommand{sopfr}{\operatorname{sopfr}}$
$f(n)=\frac{n(n+1)}2$ and $g(n)=\sopfr(n)$, the sum of prime factors of $n$ with repeats (OEIS A001414). We want $n$ such that $g(f(n))=n$ or
$$\sopfr\left(\frac{n(n+1)}2\right)=n\tag1$$
which can be split into two cases due to the property $\sopfr(ab)=\sopfr(a)+\sopfr(b)$.

If $n$ is even, then $\sopfr\left(\frac n2\right)+\sopfr(n+1)=n$. We know that $\sopfr(n)\le n$, so $\sopfr\left(\frac n2\right)\le\frac n2$ and consequently $\sopfr(n+1)\ge\frac n2$. Either $n+1$ is a prime, in which case the LHS of $(1)$ is greater than $n$ and so the equality cannot hold, or $n+1$ is odd composite and so has a least prime factor at least 3*, yielding $\sopfr(n+1)\le3+\frac{n+1}3$ and thus
$$\frac n2\le3+\frac{n+1}3$$
which is only true for $n\le20$. Checking those $n$ reveals no solutions to $(1)$.
If $n$ is odd, the reasoning is similar: $\sopfr\left(\frac{n+1}2\right)+\sopfr(n)=n$, where $\sopfr\left(\frac{n+1}2\right)\le\frac{n+1}2$ and so $\sopfr(n)\ge\frac{n-1}2$. Since $n$ is odd, either it is prime and the LHS of $(1)$ is greater than $n$, or it has a least prime factor at least 3* and $\sopfr(n)\le3+\frac n3$, giving
$$\frac{n-1}2\le3+\frac n3$$
which only holds for $n\le21$. 21 is the solution to $(1)$ pointed out in the original question; we have just shown it is the only one.

*Technically we have to repeat the argument for other possible least prime factors $k$ of $n$ or $n+1$ – and the upper bound $N_k$ of the solution to the inequalities in $n$ increases accordingly, each 3 replaced with $k$. However, the least composite number with least prime factor $k$ is $k^2$, and this increases much faster than $N_k$ (which is $\sim\frac k2$). Indeed, $5^2$ already exceeds $N_5$ for both inequalities.
The method I use above has very strong similarities to the method I used in my most famous answer of all. It is sheer coincidence that 21 is a solution to both the problems I answered.
Comment: To elaborate on the footnote: If $n$ is composite and $p$ its minimal prime factor, then $\operatorname{sopfr}(n)=p+\operatorname{sopfr}(n/p)\le p+\frac np$ and $x\mapsto x+\frac nx$ is a decreasing function on $(0,\sqrt n)$, hence $n$ odd and composite implies $\operatorname{sopfr}(n)\le 3+\frac n3$.


How to break when a for loop reaches NSNotFound from a NSArray

Question: I have a nsmutablearray which I add object to it in a for loop from a nsarray. I want it to add object until it reaches NSNotFound in indexOfObject: from NSArray.
The array is inside a for loop to extract string from every index.
My code:
NSInteger untilNotFound = NSNotFound;
NSUInteger index = [array indexOfObject:string];

for (index; index < untilNotFound; index ++)
{
    [self.mutablearray addObject:[array objectAtIndex: index]];
}

Edit:
for (string in array)
{
NSComparisonResult *result = [string compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)
                              range:NSMakeRange(0, [searchText length])];

if (result == NSOrderedSame)
{
            NSInteger index;
            for (index =[array indexOfObject:string]; (index < [array count] && index < 100 && index!= NSNotFound); index ++)
            {
                [self.mutablearray addObject:[array objectAtIndex: index]];

            }

break;

}

}

EDIT.
My previous code that works, it is inside if (result == NSOrderedSame) I just wonder if there is any nicer and easier and performance-friendly solution to extract indexes just before it reaches NSNotFound:
        NSUInteger new = [array indexOfObject:string];

        NSString *last = [array lastObject];

        NSUInteger total = [array indexOfObject:last];

        NSUInteger newmax = new + 10;

        NSUInteger totalminus = total - 11;

        if (newmax <= totalminus )

        {

            [self.mutablearray addObject:string];

            [self.mutablearray addObject:[array objectAtIndex:new + 1]];

            [self.mutablearray addObject:[array objectAtIndex:new + 2]];
            [self.mutablearray addObject:[array objectAtIndex:new + 3]];
            [self.mutablearray addObject:[array objectAtIndex:new + 4]];
            [self.mutablearray addObject:[array objectAtIndex:new + 5]];
            [self.mutablearray addObject:[array objectAtIndex:new + 6]];
            [self.mutablearray addObject:[array objectAtIndex:new + 7]];
            [self.mutablearray addObject:[array objectAtIndex:new + 8]];
            [self.mutablearray addObject:[array objectAtIndex:new + 9]];
            [self.mutablearray addObject:[array objectAtIndex:new + 10]];
        }

        else
        {
            [self.mutablearray addObject:string];
        }

Answer: That's not how NSArray or NSNotFound work.  Attempting to access an object past the end of an NSArray will raise an exception.  Is there a specific reason why you want to do it this way?  It's much easier to use fast enumeration:
for (id object in array) {
    [self.mutablearray addObject:object];
}

Edit: I see from your other comments that you want to limit this to a maximum of 100 objects added to the mutable array.  That's easy enough:
NSUInteger count = 0;
for (id object in array) {
    [self.mutablearray addObject:object];
    count++;
    if (count >= 100) break;
}

Comment: But it raises an exception when it is within 100 indexes from nsarray.
Comment: it doesnt work. it shows only when i enter first alphabet in searchtext, more than that, nothing shows.
Comment: I thought it would raise an exception, but it didnt. it just display the result when I enter the first alphabet, and after that, nothing changes in the result list which is self.mutablearray. Please tell me where I should put this code? I tried this code inside if (result == NSOrderedSame).
Comment: It's impossible to debug your code without more information about what it is you are doing.  You talk about "after you enter the first alphabet", but there's no description of that in your question.  Try explaining exactly what it is you are trying to achieve, from a functional point of view.
Comment: please see my detailed code below my question. searchText is the text field which the user enters to search a word. It should display the result list immediately for each alphabet. Is it more clear now? I just want to break the main loop after 100 objects or less are extracted to save the performance.
Comment: You're keeping hold of `mutablearray` in a property.  Every time you search for something, the old results are going to appear because you aren't clearing it out.  Do you actually need this to be a property?  Will a local variable work instead?
Comment: I need it as a property, because it is required in UITableView and other methods too. Please see my new edit.
Comment: When a new search is performed, you need to call `removeAllObjects` on `self.mutablearray` and then after you've filled it in again, you need to call `reloadData` on the table view.
Comment: Both are already existant. removeAllObjects is in the last line before the main for loop.
Comment: Thanks for your effort, but I found a solution now.
Answer: Looks like you're trying to do a cumulative subset. Try this:
for(NSInteger index = [array indexOfObject: string]; ((index <  [array count]) &&
                                                      (index <= 100)           &&
                                                      (index != NSNotFound))   ;  index++)
{
    [self.mutablearray addObject: [array objectAtIndex: index]];
}

Or, if you're just doing a strict subset, try this:
NSInteger startIndex = [array indexOfObject: string];
NSInteger endIndex = MIN([array count], 100);
if(startIndex != NSNotFound)
{
    self.mutablearray = [array subarrayWithRange: NSMakeRange(startIndex, endIndex)] mutableCopy];
}

Comment: your answer is close to perfect, but I forgot to mention that I want to add 100 objects or less until the end of the array. How to do it?
Comment: So, you want to add no more than 100 elements, or the rest of the array if it's under 100 elements?
Comment: I havent tried it yet, but do you think it works with `for (index; index < index + 100 || index < index == NSNotFound; index ++)`
Comment: I added a 100 element cap, and a check to make sure than index doesn't start at NSNotFound.
Comment: Umm... it showed either 100 or nothing... I have a break; below this for a loop.
Comment: I tried also commenting out "break;", but it changes nothing.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4508/discussion-between-patrick-perini-and-wagashi)
Comment: Your second code works with 100, but the app crashes whenever it is under 100 objects.
Comment: I changed it to `for (index ; (index < [array count] && index <= index + 100 && index!= NSNotFound); index ++)` Finally, it works as I wish! Thank you!
Answer: NSNotFound is defined like this
enum {NSNotFound = NSIntegerMax};

so you're going to be accessing invalid indeces in your array.
Comment: Thanks for teaching me something new, but do you have a solution to my problem?
Answer: for (id obj in array){
 [self.mutableArray addObject:obj];
}

This will run until array has objects.


Can I configure the analog stick on my PS3 controller as "vehicle throttle" in GTA3 on Mac?

Question: I bought GTA3 on Mac App Store, and wanted to play it with my new PS3 controller on my MacBook. It works fine for playing on foot (left stick for running, right stick for view). But in car I can only use left stick for steering, and can't use analog stick for throttle.
I tried to redefine the controls on car, but when move the sticks they are not recognized in the "redefine controls" menu, only buttons are recognized.
How can I make so that I can control throttle with analog stick?
UPD. Actually I cant reassign analog sticks at all, not even change steering from left to right stick, they are simply not recognized, and I can play only on default settings for sticks.
UPD2. What about GTA SA, then? Will I be able to to control both throttle and steering with analog sticks in it?
Comment: I don't believe the situation is any different in the other GTA3-series games - they're all ports from the console versions of the games.  If you get to change the button layout at all, that's more than what we got on consoles :(
Comment: @agent86 "other GTA3-series games" you mean SA as well? It also didn't have analog throttle on consoles?
Answer: The original version of GTA3 used a button, and not a analog stick axis, for both throttle and brake.  On the other hand, the DualShock 2 had pressure sensitive button support, so on the PS2 they were more like analog controls than digital buttons.
However, most of the ports of GTA3 don't support analog throttle/brake for whatever reason.  It might be possible to use a controller remapping program (AutoHotKey is my go-to for this, but I think Controllermate might fill a similar niche in OSX) in order to change this behavior.  However, it's likely to break other things you'd want to do with the right analog stick - like looking around when you're on foot, for example.
I think in the end you might just have to chalk this up to a missing feature in the ports of GTA games.
Answer: Yes if you have the ps3 controller connected go to options in the game, then go to controls, then go to reconfigure controls and set it up how you want.


No proxy provider found for type only in dev mode, classic run is corect

Question: I'm writing an application in Erra and I got into trouble. RPC calls using the application. When I start in normal mode, Vee running well, but when it will bring the best in dev mode throws Well proxy provider for the type found.
And there is bug screen:
BUG FOUNDED IN WEB CONSOLE
I append some screen and source code...
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
  xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.jboss.errai.demo</groupId>
  <artifactId>errai-tutorial</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>elBooker-CRM</name>

  <properties>
    <errai.version>4.0.0.Beta1</errai.version>
    <gwt.version>2.8.0-beta1</gwt.version>
    <slf4j.version>1.5.11</slf4j.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <javaee.version>1.0.2.Final</javaee.version>
    <errai.dev.context>${project.artifactId}</errai.dev.context>
    <as.version>8.1.0.Final</as.version>

    <errai.jboss.home>${project.build.directory}/wildfly-${as.version}</errai.jboss.home>
  </properties>

  <repositories>
    <repository>
      <id>jboss</id>
      <name>JBoss Public Repo</name>
      <url>https://repository.jboss.org/nexus/content/groups/public</url>
    </repository>
    <repository>
      <id>sonatype-public</id>
      <name>Sonatype Public Snapshots Repo</name>
      <url>https://oss.sonatype.org/content/repositories/public</url>
    </repository>
  </repositories>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.jboss.errai</groupId>
        <artifactId>erra-bus</artifactId>
        <version>${errai.version}</version>
      </dependency>

      <dependency>
        <groupId>org.jboss.errai</groupId>
        <artifactId>erra-ioc-bus-support</artifactId>
        <version>${errai.version}</version>
      </dependency>

      <dependency>
        <groupId>org.jboss.errai.bom</groupId>
        <artifactId>errai-bom</artifactId>
        <version>${errai.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava-gwt</artifactId>
        <version>20.0-SNAPSHOT</version>
      </dependency>
      <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>20.0-SNAPSHOT</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-navigation</artifactId>
      <version>${errai.version}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.google.gwt</groupId>
      <artifactId>gwt-user</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-javaee-all</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-cordova</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.jboss.spec</groupId>
      <artifactId>jboss-javaee-7.0</artifactId>
      <version>${javaee.version}</version>
      <type>pom</type>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-cdi-jboss</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-cdi-server</artifactId>
    </dependency>
  </dependencies>

  <build>
    <finalName>${project.artifactId}</finalName>
    <outputDirectory>src/main/webapp/WEB-INF/classes</outputDirectory>

    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.eclipse.m2e</groupId>
          <artifactId>lifecycle-mapping</artifactId>
          <version>1.0.0</version>
          <configuration>
            <lifecycleMappingMetadata>
              <pluginExecutions>
                <pluginExecution>
                  <pluginExecutionFilter>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>gwt-maven-plugin</artifactId>
                    <versionRange>[2.4.0,)</versionRange>
                    <goals>
                      <goal>resources</goal>
                    </goals>
                  </pluginExecutionFilter>
                  <action>
                    <skip />
                  </action>
                </pluginExecution>
                <pluginExecution>
                  <pluginExecutionFilter>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <versionRange>[2.1,)</versionRange>
                    <goals>
                      <goal>unpack</goal>
                    </goals>
                  </pluginExecutionFilter>
                  <action>
                    <ignore></ignore>
                  </action>
                </pluginExecution>
              </pluginExecutions>
            </lifecycleMappingMetadata>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>

    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>gwt-maven-plugin</artifactId>
        <version>${gwt.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <logLevel>INFO</logLevel>
          <noServer>false</noServer>

          <extraJvmArgs>-Xmx2048m -XX:CompileThreshold=7000 -Derrai.jboss.home=${errai.jboss.home} -Derrai.dev.context=${errai.dev.context}</extraJvmArgs>
          <server>org.jboss.errai.cdi.server.gwt.EmbeddedWildFlyLauncher</server>
          <disableCastChecking>true</disableCastChecking>
          <runTarget>${errai.dev.context}/</runTarget>
          <soyc>false</soyc>
          <hostedWebapp>src/main/webapp</hostedWebapp>
          <strict>true</strict>
        </configuration>
        <dependencies>
          <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-user</artifactId>
            <version>${gwt.version}</version>
          </dependency>
          <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-dev</artifactId>
            <version>${gwt.version}</version>
          </dependency>
        </dependencies>
      </plugin>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>2.4.1</version>
        <configuration>
          <filesets>
            <fileset>
              <directory>${basedir}</directory>
              <includes>
                <include>src/main/webapp/app/</include>
                <include>src/main/webapp/WEB-INF/deploy/</include>
                <include>src/main/webapp/WEB-INF/lib/</include>
                <include>**/gwt-unitCache/**</include>
                <include>.errai/</include>
              </includes>
            </fileset>
          </filesets>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <id>unpack</id>
            <phase>process-resources</phase>
            <goals>
              <goal>unpack</goal>
            </goals>
            <configuration>
              <artifactItems>
                <artifactItem>
                  <groupId>org.wildfly</groupId>
                  <artifactId>wildfly-dist</artifactId>
                  <version>${as.version}</version>
                  <type>zip</type>
                  <overWrite>false</overWrite>
                  <outputDirectory>${project.build.directory}</outputDirectory>
                </artifactItem>
              </artifactItems>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>jboss7</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.2</version>
            <configuration>
              <packagingExcludes>**/javax/**/*.*,**/client/local/**/*.class</packagingExcludes>
              <outputFileNameMapping>@{artifactId}@-@{baseVersion}@@{dashClassifier?}@.@{extension}@</outputFileNameMapping>
            </configuration>
          </plugin>
          <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-maven-plugin</artifactId>
            <version>1.0.2.Final</version>
            <extensions>false</extensions>
          </plugin>
        </plugins>
      </build>
      <dependencies>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-jboss-as-support</artifactId>
        </dependency>

        <dependency>
          <groupId>com.google.guava</groupId>
          <artifactId>guava-gwt</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>hsqldb</groupId>
          <artifactId>hsqldb</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>javax.enterprise</groupId>
          <artifactId>cdi-api</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>javax.inject</groupId>
          <artifactId>javax.inject</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>javax.validation</groupId>
          <artifactId>validation-api</artifactId>
          <classifier>sources</classifier>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>javax.validation</groupId>
          <artifactId>validation-api</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.hibernate.common</groupId>
          <artifactId>hibernate-commons-annotations</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.hibernate.javax.persistence</groupId>
          <artifactId>hibernate-jpa-2.0-api</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-core</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-entitymanager</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-validator</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-validator</artifactId>
          <classifier>sources</classifier>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-cdi-jboss</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-codegen-gwt</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-data-binding</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-javax-enterprise</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-jaxrs-client</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-jpa-client</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-navigation</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-tools</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-ui</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.errai</groupId>
          <artifactId>errai-html5</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.logging</groupId>
          <artifactId>jboss-logging</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.resteasy</groupId>
          <artifactId>jaxrs-api</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.spec.javax.interceptor</groupId>
          <artifactId>jboss-interceptors-api_1.2_spec</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.spec.javax.transaction</groupId>
          <artifactId>jboss-transaction-api_1.2_spec</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.weld.servlet</groupId>
          <artifactId>weld-servlet-core</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>org.jboss.weld</groupId>
          <artifactId>weld-core</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>xml-apis</groupId>
          <artifactId>xml-apis</artifactId>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>io.netty</groupId>
          <artifactId>netty-codec-http</artifactId>
          <scope>provided</scope>
        </dependency>
      </dependencies>
    </profile>

    <profile>
      <id>mobile</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.jboss.errai</groupId>
            <artifactId>cordova-maven-plugin</artifactId>
            <version>${errai.version}</version>
            <executions>
              <execution>
                <id>build</id>
                <phase>package</phase>
                <goals>
                  <goal>build-project</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
      <pluginRepositories>
        <pluginRepository>
          <id>snapshots.jboss.org</id>
          <name>JBoss Snapshot Repository</name>
          <url>http://snapshots.jboss.org/maven2</url>
          <layout>default</layout>
          <snapshots>
            <enabled>true</enabled>
          </snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
</project>

App.gwt.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.5.0//EN"
            "http://google-web-toolkit.googlecode.com/svn/tags/2.5.0/distro-source/core/src/gwt-module.dtd">

<module rename-to="app">
  <inherits name="org.jboss.errai.enterprise.All" />
  <inherits name="org.jboss.errai.ui.nav.Navigation"/>
  <inherits name="org.jboss.errai.bus.ErraiBus"/>
  <inherits name="org.jboss.errai.ioc.Container"/>
  <set-property name="gwt.logging.enabled" value="TRUE"/>

</module>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet-mapping>
    <servlet-name>javax.ws.rs.core.Application</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>ErraiServlet</servlet-name>
    <servlet-class>org.jboss.errai.bus.server.servlet.DefaultBlockingServlet</servlet-class>
    <init-param>
      <param-name>auto-discover-services</param-name>
      <param-value>true</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>ErraiServlet</servlet-name>
    <url-pattern>*.erraiBus</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>ErraiServlet</servlet-name>
    <servlet-class>org.jboss.errai.bus.server.servlet.StandardAsyncServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>

</web-app>

LoginForm.java -> client side
package org.jboss.errai.demo.client.local;

import com.google.gwt.dom.client.FormElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextBox;
import javax.inject.Inject;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.jboss.errai.demo.client.local.share.UserAccount;
import org.jboss.errai.demo.client.local.share.LoginResponse;
import org.jboss.errai.ioc.client.api.EntryPoint;
import org.jboss.errai.ui.nav.client.local.DefaultPage;
import org.jboss.errai.ui.nav.client.local.Page;
import org.jboss.errai.ui.shared.api.annotations.Bound;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.EventHandler;
import org.jboss.errai.ui.shared.api.annotations.Model;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import org.jboss.errai.demo.client.local.share.LoginVerifyService;

/**
*
* @author ondra
*/
@EntryPoint
@Page(role = DefaultPage.class)
@Templated("LoginForm.html#container")
public class LoginForm extends Composite{

  @Inject
  @Model
  private UserAccount loginRequest;

  @Inject
  @Bound
  @DataField
  private TextBox password;

  @Inject
  @Bound
  @DataField
  private TextBox username;

  @Inject
  @DataField
  private Button login;

  @Inject
  private Caller<LoginVerifyService> loginVerify;

  @EventHandler("login")
  private void onLoginClick(ClickEvent ce){
    this.login.setFocus(false);
    this.loginVerify.call(new RemoteCallback<LoginResponse>() {
      @Override
      public void callback(LoginResponse response){
        Window.alert(response.toString());
      }
    }).authentication(loginRequest);
  }

}

LoginVerifyService -> rpc interface
package org.jboss.errai.demo.client.local.share;

import org.jboss.errai.bus.server.annotations.Remote;

/**
*
* @author ondra
*/

@Remote
public interface LoginVerifyService{
  public LoginResponse authentication(UserAccount recieveUserAccount);
}

package org.jboss.errai.demo.client.local.share;

import org.jboss.errai.bus.server.annotations.Remote;

/**
*
* @author ondra
*/

@Remote
public interface LoginVerifyService{
  public LoginResponse authentication(UserAccount recieveUserAccount);
}

LoginVerifyImpl -> rpc service
package org.jboss.errai.demo.server;

import javax.enterprise.context.ApplicationScoped;
import org.jboss.errai.bus.server.annotations.Service;
import org.jboss.errai.demo.client.local.share.UserAccount;
import org.jboss.errai.demo.client.local.share.LoginResponse;
import org.jboss.errai.demo.client.local.share.LoginVerifyService;

/**
*
* @author ondra
*/
@ApplicationScoped
@Service
public class LoginVerifyImpl implements LoginVerifyService{

  private DataSource dataSource = new DataSource();

  @Override
  public LoginResponse authentication(UserAccount recieveUserAccount){
    System.err.println("JSEM V METODE");
    VerifyResponse response = this.dataSource.getUserByName(recieveUserAccount.getUsername());
    UserAccount foundAccount = response.getUserAccount();

    if(response.getQueryStatus() == VerifyResponse.Status.ACCOUNT_FOUND){
      if(recieveUserAccount.getPassword().equals(foundAccount.getPassword())){
        return new LoginResponse(LoginResponse.Response.ALL_OK, "vitejte na webu");
      }else{
        return new LoginResponse(LoginResponse.Response.PASS_BAD, "spatne heslo");
      }
    }else{
      return new LoginResponse(LoginResponse.Response.USER_BAD, "spatny uzivtelsky ucet");
    }
  }

}

Comment: Hey. Did You sovle this issue. I have exacly same problem. Any help apreciated
Comment: yeah i solved like charm....I changed my work. I don't like Errai...I founded Angular2 is much better for fronted and you don't need bee friendly with JavaScript becouse it using TypeScript. It is frendly for Java developers
Comment: I've restart pc and now it works back again :-)
Answer: I saw this error when running Super Dev Mode through my IDE (IntelliJ).  When I ran Super Dev Mode through the GWT Maven Plugin (mvn gwt:run -Dgwt.noserver), this error went away.
I'm not sure what is causing the problem.  My first thought is that there was a version difference, but both the IDE and Maven Plugin are using the same version of GWT (2.8.0-beta1).
Hope this helps!


Scala warning a type was inferred to be 'AnyVal'

Question: I have this actor with the following recieve code:
override def receive: Receive = {

case RefreshAccessTokenRequest(accountId, Some(refreshToken), _, _) =>
  concurApi.refreshAccessToken(accountId, refreshToken) onComplete {
    case Success(refreshTokenResult) =>
      context.parent ! ConcurResultCallbackInformation(accountId, Right(refreshTokenResult))
      accountService.updateAccountOAuth2Credentials(accountId, refreshTokenResult.toOAuth2Credentials) recover {
        case ex => logger.error("Error updating account Id: " + accountId + " with new refresh token. message: " + ex.getMessage)
      }
      context.stop(self)
    case Failure(t) =>
      context.parent ! ConcurResultCallbackInformation(accountId, Left(t))
      context.stop(self)
  }

case Cancel => context.stop(self)

case x => logger.error(s"ConcurAccessTokenActor: Got an unknown message $x")

}

I am getting a warning on the bolded part which says:
Warning:(18, 42) a type was inferred to be AnyVal; this may indicate a programming error.
        case Success(refreshTokenResult) =>
this is the refreshAccessToken function:
def refreshAccessToken(accountId: String, refreshToken: String)(implicit context: ExecutionContext) : Future[ConcurRefreshTokenResult] = {
val body = s"client_id=${sandboxClientId}"

val futureRes = ws.url(sandboxRefreshTokenFullUrl).withHeaders("Content-Type" -> "application/x-www-form-urlencoded").post(body)
futureRes.flatMap { res =>
  res.status match {
    case 200 =>
      val extract = Try {
        res.body.fromJson[ConcurRefreshTokenResult]
      }.recover { case ex =>
        throw ex
      }
      Promise.fromTry(extract).future
    case 400 =>
      Future.failed(new RuntimeException(s"refresh Access Token failed with status 400, and body: ${res.body}"))
    case x =>
      Future.failed(new RuntimeException(s"refresh Access Token failed with status $x, and body: ${res.body}"))
  }
}
}

Any ideas?
Comment: Which is your line 18 ?
Comment: What are the return types of `.info` and `.stop`?
Comment: Line 18: case Success(refreshTokenResult) => . notice the arrow points on the '=>' arrow
Comment: .info (you meant .error) and .stop are all of UNIT type.
I think i found the reason though... the 'updateAccountOAuth2Credentials' function returns Future[Boolean] so the return type of the entire block is of AnyVal.
Answer: Ok I got it..
The warning came from this code part:
case Success(refreshTokenResult) =>
  context.parent ! ConcurResultCallbackInformation(accountId, Right(refreshTokenResult))
  accountService.updateAccountOAuth2Credentials(accountId, refreshTokenResult.toOAuth2Credentials) recover {
    case ex => logger.error("Error updating account Id: " + accountId + " with new refresh token. message: " + ex.getMessage)
  }
  context.stop(self)

the 'updateAccountOAuth2Credentials' function returns Future[Boolean] yet the recover part returns Unit so it interperts it to AnyVal
I think the only thing that is confusing is the location of the warning arrow since this function appears in the middle between 2 other functions, and has no effects on the return type of the entire case block


getting started C# websocket application

Question: I need to launch websocket server for javascript-based crm application. I study this example: Create "Hello World" WebSocket example
but I can't established connection. Program throws an exception in
<code>var key = headerResponse.Replace("ey:", "`")
                              .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                              .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                              .Trim();
</code>
Frame sending from client looks as follows:

GET / HTTP/1.1
  Host:   localhost:9801
  Connection:  keep-alive
  Cache-Control: max-age=0
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
  User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22
  (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22
  Accept-Encoding: gzip,deflate,sdch
  Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
  Accept-Charset: ISO-8859-2 ,utf-8;q=0.7,*;q=0.3

The key part of frame is missing on any browser. How to resolve that?
Comment: **What does the exception say**?
Comment: Please include newlines in the headers.
Comment: Error message: "Index was outside the bounds of the array". The 'key' part of frame doesn't exists so the key cant be parsed from string. This key is neccessary?
Answer: The way you are doing it seems a little bit unsave in regards to exceptions.
Try to prevent this by validating the value you received.
I can't say where your problem exactly is but this should fix your

Index was outside the bounds of the array

<code>    string key = "";
    if (string.IsNullOrEmpty(headerResponse))
    {
        //No header response... handle it ;)
    }
    var replacedString = headerResponse.Replace("ey:", "`");
    string[] splitted = replacedString.Split('`');
    if (splitted.Length > 1)
    {
        string replaced2 = splitted[1].Replace("\r", "");
        string[] splitted2 = replaced2.Split('\n');
        if (splitted2.Length > 0)
        {
            key = splitted2[0].Trim();
        }
        else
        {
            // '\n' not found
        }
    }
    else
    {
        // '`' not found
    }

    if (string.IsNullOrEmpty(key))
    {
        //do error correction
    }
    else
    {
        //everything is fine
    }
</code>


A positive measurable and improper integrable function is integrable

Question: Let $f: \mathbb{R} \rightarrow [0,+\infty)$ a positive measurable function. Suppose $f$ is improper integrable. Show that $f$ is integrable.

Take a row $x_{n} \rightarrow \infty$ and a row $y_{n}\rightarrow -\infty$ We know that:
  $\lim_{n\rightarrow \infty}\int_{x_{n}}^{y_{n}} {f} {d\lambda}$ exists. We can write this as: $\lim_{n\rightarrow \infty}\int_{\mathbb{R}} \mathbb{1}_{[x_{n},y_{n}]}f $. We can use now the monotone convergence theorem. Is this OK? Thanks.
Answer: The proof is correct if you assume that both $x_n$ and $y_n$ are monotone. You could actually fix them: $x_n = -n$, $y_n = n$.
Comment: But we know that $f$ is improper integrable. So we have to go to $+\infty $ and$  -\infty$ at a indepent way. Or am I wrong?
Comment: We *can* but not *have to*.
Comment: OK, so we know that it works for every row to $+\infty$ and every row to $-\infty$ (monotone rows) because $f$ is improper integrable. So we can take that row , to apply the monotone convergence theorem. Is this OK?
Comment: yes, it is correct.


GitHub Private Repository not taking Xcode pushes

Question: Currently I'm working on a Xcode project and committing/pushing to my local/remote GitHub repo. Everything was set up smoothly and ran smoothly, that is until I decided to change my GitHub repo from public to private. My local commits still work smoothly, but when I try to push to GitHub, everything will seem as if it ran smoothly, but when I go on my GitHub to see if the push has been updated, there's nothing. The last commit I see is from before I turned the repo to private.
I've also tried to delete the original repo and start fresh by committing to a private repo on the initial commit. But no luck.
Has anyone else also experienced this?
Does anyone know of a solution to this other than to revert the repo back to public?
Comment: Hey, GitHub private repos are now free! Cool!!! Thanks for the heads-up! — Okay, so as to your actual question, I've no idea. But I do know that Xcode git support sucks. So my question would be, what happens if, instead of using Xcode, you use git _itself_? Do your push from the command line instead of from Xcode. Does that fix it?
Comment: Another idea; what if you delete your github account from Xcode's preferences and then add it again. Does _that_ fix it?
Answer: I have faced this issue "The remote repository could not be accessed" but now it works properly. The solution is to go to the Xcode Setting delete the GitHub Account and then generate the token, then paste the token in Xcode where you are doing account sign in


Prove T is a linear operator

Question: Let $\mathcal{H}$ be a Hilbert space. Given that $T: \mathcal{H} \to \mathcal{H}$ $(Tx,Ty) = (x,y)$, how should we prove that T is an linear operator?
It is not hard to show that
$$(T(x+y), Tz) = (Tx + Ty, Tz),(T(ax), Tz) = (aTx, Tz)$$
But, how may I show that $Tz$ can be any element of $\mathcal{H}$?
It seems that all theorems relies on linear operator...
Answer: Use the inner product relation to calculate $\|T(x+y)-(Tx+Ty)\|^2$ and likewise $\|aTx-T(ax)\|^2$. You'll find that they are both zero. I'll do the second one and leave the first for you to check:
\begin{align*}
\|aTx-T(ax)\|^2 & = (aTx-T(ax), aTx-T(ax)) \\
& = (aTx,aTx)-2(aTx,T(ax)+(T(ax),T(ax)) \\
& = a^2(Tx,Tx)-2a(Tx,T(ax))+(T(ax),T(ax))\\
& = a^2(x,x)-2a(x,ax)+(ax,ax) \\
& = a^2\|x\|^2-2a^2\|x\|^2+a^2\|x\|^2 = 0.
\end{align*}
Note that I've implicitly assumed the Hilbert space is real. The calculation works basically the same way in the complex case though.
After you check for yourself that $\|T(x+y)-(Tx+Ty)\|^2=0$, just appeal to the fact that $\|v\|=0$ if and only if $v=0$. Thus $T(x+y) = Tx+Ty$ and $T(ax)=aTx$.
Comment: Thank you so much for your help!

Prove T is a linear operator


Add tranparency to huge image C#

Question: I have A0 format (600dpi) png (19860px x 28080px) that contains only black and white pixels (one bit per pixel file is about only 3MB). All I want is to save this file as png where white color pixels will be replaced by transparent color.
bitmap.MakeTransparent(color) doesn't work because file is too big. Same issue with using ColorMap
Any ideas how to replace all those white pixels in reasonable time?
Comment: I'm sorry, you didn't say that it needed to be speedy in your question...
Comment: Have you tried using `SetPixel(...)` to achieve this?
Comment: Not yet. But SetPixel() is a bit slow. For 19860x28080 it will be last about 15min
Comment: Right, my bad. I will have to process about 3000 images like that. :/
Comment: You need to play with the colormap instead. ColorMap you technically change the table saying color ID "x" is now the RGB "y". On such large file it should be 4-5 seconds tops to change the whole thing. You may want to check my answer [here](https://stackoverflow.com/questions/40284721/coloring-on-bitmap-not-accurate-i-already-looked-at-how-to-change-pixel-color/40286647#40286647)
Comment: There is only one bit per pixel. If I make it RGB file will be about 2GB instead of 3MB.
Comment: @Franck: Your link leads to an answer that starts with _i doubt this line compile but you get the idea_ The rest doesn't address the size issues one runs into with GDI+.
Comment: @Bar: What format does the original image have? Can you even load the image into a Bitmap? If yes: For speed use LockBits.  If no: I guess you'll have to look for a library to do the job. We can't help with the search, though.
Comment: @TaW My answer show both options. Either by `Graphics` or using `Bitmap`, second is with bitmap. I does work with extremely large image in excess of 45,000 pixel wide. I used that method to recolor all counties of the USA for Rep territory marking
Comment: In section 4.4 do you know what type file you have? See : https://www.w3.org/TR/PNG/#11IDAT
Comment: Could you post an example of such an image? After the discussion with jdweng I'm really curious about the internals.
Answer: You don't need System.Drawing for this operation at all.
See, one-bit-per-pixel black-and-white images in PNG format will be either in grayscale format, or paletted.
PNG is made up of chunks which have the following format:

Four bytes of internal chunk length (big-endian)
Four ASCII characters of chunk identifier
The chunk contents (with the length specified in the first part)
A four-byte CRC hash as consistency check.

Now here's the interesting part: PNG has the rather obscure feature that it supports a tRNS chunk to be added that sets the alpha for grayscale and paletted format. For grayscale this chunk contains a two-byte value that indicates which grayscale value should be made transparent (which I assume for one bit per pixel should be '1', since that's white), and for paletted format this contains the alpha for each of its palette colours (though it doesn't have to be as long as the palette; any indices not included default to opaque). And since PNG has no overall indexing of its chunks, you can literally just add that in and be done with it.
The code for reading and writing PNG chunks was posted in earlier answers here:
Reading chunks
Writing chunks
You will need to read the IHDR chunk and check the colour type in the header to see which type of transparency chunk you need to add. An overview of the header format and all colour type possibilities can be found here. Basically, colour type 0 is grayscale, and colour type 3 is paletted, so your image should be one of these two.
For palette transparency, the tRNS chunk should be added right behind the PLTE chunk. For grayscale transparency, I believe it should be just before the first IDAT chunk.
If it's paletted, you do need to check if white is the first or second colour in the palette, so you can set the correct one to transparent.
So once you got that, make a new byte array that's as large as your image plus the added chunk (12 bytes of chunk header and footer and probably 2 bytes of data inside it), and then copy the first part of the file up to the point where the segment should be added into it, then your new segment, and then the rest of the file. Save the bytes array to a file, and you're done.
Comment: the link you posted is working from bitmaps and not a png file.  Also you have to be careful of the chunk order.  The posted code is randomly checking for a chunk type and not sequentially going through the chunks.
Comment: No, the link I posted _returns_ a .Net `Bitmap` _object_ (since its purpose is to load the palette transparency correctly in .Net), but it takes _bytes_ as input. As for the order of the chunks, it does in fact _not_ matter at all for the _search_ procedure. It matters in that the tRNS chunk needs to be right behind the PLTE one, but I specifically mentioned that.
Answer: I'm not an expert on PNG files, but I read the documentation.  I believe if  you have a GRAEY SCALE file with only one byte data then all you have to do is add a transparency header before the first IDATA chunk.  The transparency header contains two bytes which is a color scale between 0 and (2^bitdepth - 1)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PNG_Tool
{
    class Program
    {
        const string READ_FILENAME = @"c:\temp\untitled.png";
        const string WRITE_FILENAME = @"c:\temp\untitled1.png";
        static void Main(string[] args)
        {
            PNG png = new PNG(READ_FILENAME, WRITE_FILENAME);

        }
    }
    class PNG
    {
        byte[] header;
        byte[] ident = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
        byte[] TNS = { 0x74, 0x52, 0x4E, 0x53 }; //"tRNS"

        public PNG(string inFilename, string outFilename)
        {
            Stream inStream = File.OpenRead(inFilename);
            BinaryReader reader = new BinaryReader(inStream);
            Stream outStream = File.Open(outFilename, FileMode.Create);
            BinaryWriter writer = new BinaryWriter(outStream);

            Boolean foundIDAT = false;

            header = reader.ReadBytes(8);

            if ((header.Length != ident.Length) || !(header.Select((x,i) => (x == ident[i])).All(x => x)))
            {
                Console.WriteLine("File is not PNG");
                return;
            }
            writer.Write(header);

            while (inStream.Position < inStream.Length)
            {
                byte[] byteLength = reader.ReadBytes(4);
                if (byteLength.Length < 4)
                {
                    Console.WriteLine("Unexpected End Of File");
                    return;
                }
                UInt32 length = (UInt32)((byteLength[0] << 24) | (byteLength[1] << 16) | (byteLength[2] << 8) | byteLength[3]);

                byte[] chunkType = reader.ReadBytes(4);
                if (chunkType.Length < 4)
                {
                    Console.WriteLine("Unexpected End Of File");
                    return;
                }
                string chunkName = Encoding.ASCII.GetString(chunkType);
                byte[] data = reader.ReadBytes((int)length);

                if (data.Length < length)
                {
                    Console.WriteLine("Unexpected End Of File");
                    return;
                }

                byte[] CRC = reader.ReadBytes(4);

                if (CRC.Length < 4)
                {
                    Console.WriteLine("Unexpected End Of File");
                    return;
                }
                uint crc = GetCRC(chunkType, data);

                UInt32 ExpectedCRC = (UInt32)((CRC[0] << 24) | (CRC[1] << 16) | (CRC[2] << 8) | CRC[3]);
                if (crc != ExpectedCRC)
                {
                    Console.WriteLine("Bad CRC");
                }

                switch (chunkName)
                {
                    case "IHDR" :
                        writer.Write(byteLength);
                        writer.Write(chunkType);
                        writer.Write(data);

                        Header chunkHeader = new Header(data);
                        chunkHeader.PrintImageHeader();
                        break;

                    case "IDAT" :
                        if (!foundIDAT)
                        {
                            //add transparency header before first IDAT header
                            byte[] tnsHeader = CreateTransparencyHeader();
                            writer.Write(tnsHeader);
                            foundIDAT = true;

                        }
                        writer.Write(byteLength);
                        writer.Write(chunkType);
                        writer.Write(data);

                        break;

                    default :
                        writer.Write(byteLength);
                        writer.Write(chunkType);
                        writer.Write(data);

                        break;
                }

                writer.Write(CRC);

            }
            reader.Close();
            writer.Flush();
            writer.Close();

        }
        public byte[] CreateTransparencyHeader()
        {
            byte[] white = { 0, 0 };

            List<byte> header = new List<byte>();
            byte[] length = { 0, 0, 0, 2 };  //length is just two bytes
            header.AddRange(length);
            header.AddRange(TNS);
            header.AddRange(white);

            UInt32 crc = GetCRC(TNS, white);
            byte[] crcBytes = { (byte)((crc >> 24) & 0xFF), (byte)((crc >> 16) & 0xFF), (byte)((crc >> 8) & 0xFF), (byte)(crc & 0xFF) };
            header.AddRange(crcBytes);

            return header.ToArray();
        }

        public uint GetCRC(byte[] type, byte[] bytes)
        {
            uint crc = 0xffffffff; /* CRC value is 32bit */
            //crc = CRC32(byteLength, crc);
            crc = CRC32(type, crc);
            crc = CRC32(bytes, crc);

            crc = Reflect(crc, 32);
            crc ^= 0xFFFFFFFF;

            return crc;

        }
        public uint CRC32(byte[] bytes, uint crc)
        {
            const uint polynomial = 0x04C11DB7; /* divisor is 32bit */

            foreach (byte b in bytes)
            {
                crc ^= (uint)(Reflect(b, 8) << 24); /* move byte into MSB of 32bit CRC */

                for (int i = 0; i < 8; i++)
                {
                    if ((crc & 0x80000000) != 0) /* test for MSB = bit 31 */
                    {
                        crc = (uint)((crc << 1) ^ polynomial);
                    }
                    else
                    {
                        crc <<= 1;
                    }
                }
            }
            return crc;
        }
        static public UInt32 Reflect(UInt32 data, int size)
        {
            UInt32 output = 0;
            for (int i = 0; i < size; i++)
            {
                UInt32 lsb = data & 0x01;
                output = (UInt32)((output << 1) | lsb);
                data >>= 1;
            }
            return output;
        }
    }
    public class Header
    {
        public UInt32 width { get; set; }
        public UInt32 height { get; set; }

        byte[] widthBytes { get; set; }
        byte[] heightBytes { get; set; }

        public byte depth { get; set; }
        public byte colourType { get; set; }
        public byte compressionMethod { get; set; }
        public byte filterMethod { get; set; }
        public byte interlaceMethod { get; set; }

        public Header(byte[] bytes)
        {

            UInt32 width = (UInt32)((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]);
            UInt32 height = (UInt32)((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7]);

            widthBytes = new byte[4];
            Array.Copy(bytes, widthBytes, 4);

            heightBytes = new byte[4];
            Array.Copy(bytes, 4, heightBytes, 0, 4);

            depth = bytes[8];
            colourType = bytes[9];
            compressionMethod = bytes[10];
            filterMethod = bytes[11];
            interlaceMethod = bytes[12];
        }
        public void PrintImageHeader()
        {

           Console.WriteLine("Width = '{0}', Height = '{1}', Bit Depth = '{2}', Colour Type = '{3}', Compression Method = '{4}', Filter Medthod = '{5}', Interlace Method = '{6}'",
               width.ToString(),
               height.ToString(),
               depth.ToString(),
               ((COLOUR_TYPE)colourType).ToString(),
               compressionMethod.ToString(),
               filterMethod.ToString(),
               interlaceMethod.ToString()
                   );

         }
        public byte[] GetHeader()
        {
            List<byte> header = new List<byte>();
            header.AddRange(widthBytes);
            header.AddRange(heightBytes);

            header.Add(depth);
            header.Add(colourType);
            header.Add(compressionMethod);
            header.Add(filterMethod);
            header.Add(interlaceMethod);

            return header.ToArray();
        }
    }
    public enum COLOUR_TYPE
    {
        GRAY_SCALE = 0,
        TRUE_COLOUR = 2,
        INDEXED_COLOUR = 3,
        GREY_SCALE_ALPHA = 4,
        TRUE_COLOUR_ALPHA = 6
    }

}

Comment: Sounds like a good question. Doesn't sound like an answer, though.
Comment: I wasn't sure what the colour mode was so I couldn't complete the code initially.  Reading the comments it appears the OP says it file is one byte Grey Scale so I assumed it was colour mode 0.  Reading the PNG documentation is looks like adding a  transparency chunk before 1st data chunk will solve issue.
Comment: Valid answer, but overcomplicated. You can just extract the palette and surgically insert the tRNS chunk, and be done with it. No need for full parsing of the png file at all.
Comment: Note that technically the tRNS chunk doesn't have to be the full palette size; any unspecified alpha values default to opaque.
Comment: Does a GreyScale image contain a palette chunk?  I only have full color images so I do not know the chunks in a GreyScale image.  I only made the tRNS palette two bytes and made the color value 0.  Nothing says in the documentation says the Transparent chunk should be the same size as the palette.  There is nothing complicated with my code.  It is the simplest I could make it and do everything necessary to add the transparency chunk.  The only thing extra I added was to display the Header so we can tell the colorour mode.
Comment: Hmm. I wasn't aware of the grayscale format. In theory though, that format can probably be converted to paletted simply by generating a black to white palette for it and changing the type in the header from 0 to 3. The actual image data shouldn't care if it refers to a gray gradient or a palette index.
Comment: Both Palette (suggested and Main), and Transparency chunks are optional.  I think it is easier to add the transparency chunk than the palette chunk.  You can only have one Palette chunk.  So without knowing the existing chunks any answer may or may not work. Or handling every case would make the code more complicated.
Comment: Palette chunk starts with a capital letter. According to standard chunk naming rules, that means it's _not_ optional (for indexed formats). I see now there's indeed a specific tRNS chunk for pure grayscale, that just contains "the gray value to use as transparent colour" though, yes. Your code never checks the colour type when writing the transparency chunk, though, and white would be value 1, not 0...
Comment: See figure 5.2 (With Plate) and 5.3 (Without Plate) : https://www.w3.org/TR/PNG/#11IDAT.  I wasn't sure of the color for white and though it would be 0 since full opaque is 2^8-1
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/184021/discussion-between-nyerguds-and-jdweng).

Add tranparency to huge image C#


How to use char data type as a number rather than a character?

Question: When I use the char datatype to add two numbers, I get the sum of the ASCII code of the characters and not the numbers itself. When I researched on the internet, various sites say that the char type can indeed be used to handle one byte numbers. But in reality, I get the sum of ASCII values. Why is this happening? Below is just a sample code which illustrates the problem:
uint8_t rows,cols; //uint8_t is just a typedef for char
cin >> rows;
cout << rows + 1 << endl;

Comment: "not the numbers itself". What exactly do you mean by this? Do you mean where A would equal 1 and B would equal 2? Could you please elaborate a bit more
Answer: When people talk about "one-byte numbers", they're talking about 8-bit values, ranging from -128 to 127 for a char, or 0 to 255 for an unsigned char, also known as octets. These can be converted directly to larger integer types and to floats:
char eight_bit = 122;
float floating_point = eight_bit; // = 122.0

If you're trying to convert a digit value such as '1' into the numeric value it represents, there's stoi:
#include <string>

int ctoi(char c) {
    std::string temp;
    temp.push_back(c);
    return std::stoi(temp);
}

Answer: Chars store the ASCII equivalent of a character as an integer.
For example
char value = 'A' // == int 65

It's best you use a short integer to store numbers, but if you really want to, you can do something like this;
char value1 = '2';
char value2 = '5';
char sum = (value1 + value2) - '0'; // int value of sum would be 7

Answer: When you use char, you use signed 8 bit data type (mostly).
And you get "sum of ASCII" only because std::cout is programmed to display char as ASCII character.
Try
cout << stratic_cast<int16_t>(rows) + 1 << endl;

And you will see that you get the 'number' rather than an 'ASCII character'.
NOTE
uint8_t is not (or probably should not be) char since char is defined as signed data type while uint* stands for unsigned.


Solve $\frac{A}{x^2}=\exp{(-\frac{x}{B})}$ for $x$

Question: Is it possible to solve $\frac{A}{x^2}=\exp{(-\frac{x}{B})}$ for $x$?
A and B are constants.
Answer: Yes,
using the Lambert W-function.
Given $z$,
$W(z)$ solves
$z = W(z)^{W(z)}$.
Putting you equation
into this form
is a matter of algebra.
Here is a start:
taking the square root
of each side,
$\sqrt{A}
=x e^{-x/2B}
$.


How to wire 3way combo switches to light/fan combo?

Question: Can someone please correct me if I'm wrong? I'm most worried about the 3way combo switches to the light/fan fixture. With the wires shown and routes run, will there be any issues once I start wiring switches to switches and switches to fixtures? Is there an issue with travelers and such? Please see pictures attached.
Comment: @ThreePhaseEel correct, this is new wiring
Comment: @Stephen -- a switch "pole" is an individual, isolated set of contacts on a given handle.  ordinary and 3-way switches are single pole.  double pole wall switches are a thing but somewhat uncommon.  you can get 3 pole wall switches but they're really manual motor controllers :P
Comment: @ThreePhaseEel that's right. This is all on a single 15A lighting circuit and the power in from breaker is in bottom-most switch box for fan/light combo and exterior light.
Comment: I take it this is new wiring, no?
Comment: "3 _pole_"? You have 3-pole switches?
Comment: @FreeMan I thought the term "3-pole" switches was the same as "3-way" switches. If not, then can you explain to me the difference between the two? The switches I'm using for the light/fan combo are pictured above.
Comment: I take it that this is all on a single lighting circuit that enters the picture at the bottom-most switch box, right?
Comment: @ThreePhaseEel also, thanks for the breakdown on the whole "pole" ordeal
Answer: Your cable combinations won't work
Your first problem is that your idea of using 2 14/3s for the blue and green runs would put the always-hot and neutral going to the left-hand switch box in different cables, which violates the NEC 300.3(B)/310.10(H) provisions about current being required to return via the cable it left on and generates nail-heating stray magnetic fields in your walls.
Instead, I would run a ½" ENT (smurf tube) between those two boxes, as well as for the yellow/red run between the left and right boxes, and then use individual 14AWG THHN wires to run the circuits inside them.  This fixes the aforementioned Code issue with the blue/green run, and lets both runs use sane colors, such as black, blue/blue, and orange/orange (as green is reserved for grounding) for the blue/green run and yellow/yellow and red/red for the yellow/red run instead of being limited to what NM cable provides.
The downside, though, is that plastic old work boxes don't supply factory KOs by and large, so you'll need to make your own ½" trade size (⅞" actual diameter) KOs in them, with appropriate ENT (or PVC) fittings installed.
Beyond that: multiway fan/light control is non-trivial
With that said, we move onto the controls themselves.  While the approach you suggest will work, it does create issues down the road.  You see, single-gang fan speed control/dimmer combos generally don't support 3-way applications (the Lutron MA-LFQM is the only one that did, but it's not easy to find nowadays), nor do dual dimmer switches.  So, I'd suggest using a 3-gang for the bottom box and a 4-gang for the left box, giving each switch its own gang and thus making sophisticated control possible without the need for unusual gyrations or "smart" switches.
Comment: I greatly appreciate your feedback and helping me sort out the suspected issue I had. I have decided to simplify the plans and added a new drawing of what I plan on achieving under the light switch picture attached above. If you don't mind, let me know if anything seems wrong with what I plan to do.
Comment: I do have an additional question/concern though. The yellow power strip lights in the kitchen island require 12v dc. Is there a way to wire them to work off a 15a 120v ac toggle switch?
Comment: @Stephen -- wire the switch on the input (AC) side of the driver


Wireless Network is not Recognized

Question: First of all, I am very new to Linux (as will be obvious).
I just purchased a new Tosiba Satellite laptop with Window 8 installed. I have downloaded Ubuntu 12.04.2 to a CD and when I boot to the CD, I have the choice to run Ubuntu or install it. I have tried to install it but it needs an internet connection. If I run it, it seems to work except that it does not detect the existence of a wireless network, which works just fine in Windows 8. I would like to install Ubuntu and replace Windows 8 entirely but I'm afraid that I'll still not be able to connect to the network and I will have lost Windows 8 (my only connection the the internet on this computer).
I saw a suggestion to use the lspci command so I tried it. I don't know how to copy the output to a file so I re-typed the result, as follows:
lspci -nn | grep 0280
02:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. RTL8188CE 802.11b/g/n WiFi Adapter [10ec:8176] (rev 01)
Then, I saw the suggestion:
Please get a temporary ethernet connection and open a terminal Ctrl+Alt+t and do:

sudo apt-get install firmware-b43-lpphy-installer
sudo modprobe -r b43 && sudo modprobe b43

Detach the ethernet and your wireless should now be working.

but this looks like it is specific to the network controller.
I followed the advice I found in other answers to internet connection issues and downloaded the new Realtec driver for Linux (linux_mac80211_0012.0207.2013.tar.bz2) but I don't know what to do with it. If I somehow run this file, will I have access to the internet? If I do, I think I can install Ubuntu and replace Windows 8.
My second question is: How do I get output from the terminal into a file so I can add it to a question? Thanks so much for your help.
My second question is: How do I get output from the terminal into a file so I can add it to a question? Thanks so much for your help.

I have executed the command:
tar xvjf linux_mac80211_0012.0207.2013.tar.bz2

Now I have several folders and lots of files. I have read the 'Readme' file but I still don't know what to do. Any help will be appreciated.

Yes, I have an Ethernet connection through which I could connect to the internet, I think. Should I try that and do a complete replace and install?
Comment: Just a simple question, does your laptop lacks of Ethernet JR45 ports? I mean, the one that you can connect with internet using cable.
Comment: Yes, I have an Ethernet connection through which I could connect to the internet, I think. Should I try that and do a complete replace and install?
Comment: Did you do what the suggestion *suggest*? Connect an ethernet cable and run those commands on the terminal. Do this after the installation for better results. Also check http://askubuntu.com/q/205575/169736 http://askubuntu.com/q/298303/169736 and http://askubuntu.com/q/298303/169736
Comment: I did not run those commands because they seem to be specific for the network controller described in the original question. My controller is a different make and model. Would the EXACT same commands work for my controller? @Braiam
Comment: Actually they are general for a whole bunch of Realtek cards.
Answer: Please hook up the ethernet and do:
sudo apt-get install linux-headers-generic build-essential
cd rtl_92ce_92se_92de_8723ae_88ee_linux_mac80211_0012.0207.2013/
make
sudo make install
sudo modprobe rtl8192ce

Your wireless should now be working.

Wireless Network is not Recognized


control consume speed of celery worker

Question: I am trying to set up Celery with my Django app. This app will let user call some API and get the response. However this API has limitation that only allow user to call it not more than once per second.
So I am planning to use celery to control the calling frequency. Multiple users might use this app at the same time, so I think I should set up the calling part as worker. Everybody can submit requests to call the API into queue, worker will consume them.
Here is the question: how can I limit the work to consume the task(i.e. send the api request) as 1 per second?
Thanks!
Answer: celery tasks have a rate_limit option that should do what you want. This is per-worker so you'll need to use a dedicated queue to ensure that all requests for this task got the the one worker.
Comment: even if you specify a  queue for this rate limited task i am assuming only one worker can work on it

control consume speed of celery worker


What should be my objectives when going to war with another civ?

Question: In Civ4, going to war with a more powerful army than your neighbors' was quite profitable. If a neighboring civ started to expand into your territory, you could go to war and raze their cities to free up some land and claim it later with a settler; or you could take over the city. In both cases, claiming more land counted towards global domination victory (the one where you own more than 80% of land, IIRC).
In Civ5, war does not seem so much profitable. There's a heavy penalty for annexing cities; and large empires are much harder to manage than in the previous game.
When I have a larger and more powerful army than the other civs, I can see that going to war can have the following uses:

Bully the other civ by hitting its cities long enough that they will ask for peace giving you lots of resources.
Kill enemy units in order to get culture
Buy the friendship of city-states by helping them fight off a warring civ.
Of course, there's the world domination victory and all your base are belong to us.

But then again, all of these do not seem profitable reason and do not seem to make for the cost of building a powerful military to begin with.
I feel like there's a purposed use to military in Civ5 other than simply crushing the other civs. Civ5 is not StarCraft... Right ?
Questions:

What should be my objective when going to war with another civ ?
When to accept a peace treaty ? When is it time to stop the war ?
What's the outcome of a war that you call profitable ? Culture, Gold, Land, Resources, Friendship with City-States ?
Comment: This is kind of a vague question; I've done my best to answer generally, but if you can provide more detail about what you're looking for, I may be able to provide a better answer.
Comment: I intended to make a nice question, but pressed Enter too soon. Here's the complete question.
Comment: Indeed!  I have done that enough times myself, my apologies. :)
Comment: It's worth noting that if you don't want people to hate you, then you need for them to declare war on *you*. Don't capture the city, but merely weaken it and defeat many of their units. Come treaty time, they will generally offer the city diplomatically. Of course, you can just capture everything in sight if you don't mind others getting mad at you.
Answer: There are many reasons to go to war with another Civ:

Take their territory and resources - although the game is more balanced towards making small Civs profitable than ever before, in most cases having more territory/cities/resources can still give you a big advantage.
Halt the progress of another Civ who is doing better than you in some other area - if you have the military, you can stop a Civ who is doing better in technology or culture but who is weak militarily.
Defending allies or forging new alliances - war is a powerful way to increase your reputation with allied civilizations.  Allies can make war against you more difficult, and they'll be more receptive to trade agreements that are beneficial towards you.
Nip a potential adversary in the bud - the AI in particular is terrible about unit tactics, so you may be able to provoke them to attack you and devote resources to war before they're completely ready.

Depending on why you're going to war, your goals/result will differ.  You may wish to simply weaken their army, force them to give you money or other resources, or take a strategic city, but if you're going for a Domination victory, you're going to want to capture or destroy all of their cities, despite their (likely) pleas for peace.
Be wary of growing too large too quickly, as happiness is critical to growth, and extended war and capturing cities leads to rampant unhappiness.  If you devote too much of your Civ's resources towards building and maintaining an army, you may fall behind in other areas, giving others room to outpace you.
I tend to prefer to puppet captured cities (instead of razing or annexing them) as this tends to provide a pretty good balance between the benefits of having more territory, resources, and population and the detriment of unhappiness due to size.  There may be cities that are just worthless (ie, population 1 or 2 cities in poor positions) and need to be razed, or cities that are extra valuable (ie, high population cities with wonders or other beneficial buildings) that you'll want to keep tighter control over.
Unit tactics have also changed significantly since Civ4 - in that game, you wanted to build large stacks of units to march across enemy territory with at least moderate losses.  In Civ5, if you focus on a few powerful front-line defensive units coupled with ranged attacks from siege units, you'll find that your investment in units is small compared to enemy losses.  Siege units in border cities can make mincemeat of overzealous enemy armies once war is declared.