$facebook->getUser() always return zero

Question: Hi I m integrating facebook connect functionality in my website. So I used facebook new graph api. I used following code..
<code>.............
.............
    $facebook = new Facebook(array(
  'appId'  => $fbconfig['appid'],
  'secret' => $fbconfig['secret'],
));

$uid = $facebook->getUser();
var_dump($uid);
if($uid)
{
   //do someting
 }
 else
......
</code>
but problem is that $uid always comes zero. Why this is happening. Please help..
Comment: I think this a possible duplicate. Please check [My Facebook object is empty][1].

  [1]: http://stackoverflow.com/questions/7309684/my-facebook-object-is-empty
Comment: Still I m getting same error. Is there any solution why this is happening.
Comment: possible duplicate of [Why is Facebook PHP SDK getUser always returning 0?](http://facebook.stackoverflow.com/questions/6790272/why-is-facebook-php-sdk-getuser-always-returning-0)
Answer: Try This
<code>$user = null;
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));

$user = $facebook->getUser();

if ($user) {
echo "user";

}
else
{

echo("<script language=\"javascript\">");
echo("top.location.href = \"http://apps.facebook.com/myapp\";");
echo("</script>");
exit;
}
</code>
Answer: this is code by which you can login with fb account..
<code><?php
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
if(isset($cookie))
{
    $first_name = json_decode(@file_get_contents('https://graph.facebook.com/me?access_token=' .$cookie['access_token']))->first_name;
    $last_name = json_decode(@file_get_contents('https://graph.facebook.com/me?access_token=' .$cookie['access_token']))->last_name;
}
?>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
          FB.init({appId: <?php echo FACEBOOK_APP_ID;?>, status: true, cookie: true, xfbml: true});
          FB.Event.subscribe('auth.logout', function(response) {});
          FB.Event.subscribe('auth.sessionChange', function(response) {
            if (response.session) {

              FB.api('/me', function(response) {
                 if(response.id!='undefined')
                 {
                    window.location='Fbaccess.php?first_name='+response.first_name+'&last_name='+response.last_name+'&email='+response.email;
                 }
                 else
                 {
                    window.location='login.php';
                 }
                });

            } else {

              // The user has logged out, and the cookie has been cleared
            }
          });

        </script>
</code>

$facebook->getUser() always return zero


Can you change your shoes in Animal Crossing GameCube version?

Question: Can you change your shoes in Animal Crossing Game Cube version?
Comment: i'm skeptical if this is a real question considering user past questions and answers
Comment: I'm willing to give it the benefit of a doubt.  Others that have played this can weigh in with whether or not this is a valid questions.
Comment: In some of the games you can change your shoes, so I think I will let this one stand.
Answer: In Animal Crossing (Gamecube), the only type of clothes the player could change was the ones worn on their torso. Male characters had a short-sleeved shirt shape while female characters' shirts were longer to give the appearance of a dress.
Source:  http://animalcrossing.wikia.com/wiki/Animal_Crossing
Answer: You can't change your shoes in Animal Crossing GameCube. Male players wore green socks and blue shoes while female players had blue/white striped socks and red shoes.
Comment: I've unlocked everything in Animal Crossing gamecube and there isn't any shop that sells shoes.


Sublime Text 3 unable to import python module although importing from command line is possible?

Question: when I tried to build with python in ST3, I get an import error as I tried to do
import caffe

but when I simply ran on the terminal, typing
$ python
>>> import caffe

it works. On my sublime text 3 I still can import other modules like numpy and matplotlib.
This is the sublime python build I found (is this the right location? Why is it not extracted out but instead in a package?):
The directory is: /opt/sublime_text/Packages/Python.sublime-package
and the file python.sublime-build in the Python.sublime-package is:
{
    "shell_cmd": "python -u \"$file\"",
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",

    "env": {"PYTHONIOENCODING": "utf-8"},

    "variants":
    [
        {
            "name": "Syntax Check",
            "shell_cmd": "python -m py_compile \"${file}\"",
        }
    ]
}

After I checked my python path:
$ python -c "import sys; print '\n'.join(sys.path)"

my output is:
/home/user/caffe/python
/home/user
/usr/lib/python2.7
/usr/lib/python2.7/plat-x86_64-linux-gnu
/usr/lib/python2.7/lib-tk
/usr/lib/python2.7/lib-old
/usr/lib/python2.7/lib-dynload
/usr/local/lib/python2.7/dist-packages
/usr/lib/python2.7/dist-packages
/usr/lib/python2.7/dist-packages/PILcompat
/usr/lib/python2.7/dist-packages/gtk-2.0
/usr/lib/python2.7/dist-packages/wx-3.0-gtk2

and my dist-packages doesn't have caffe as I installed it in home/user instead.
So I decided to run in the terminal:
export PYTHONPATH=/home/user/caffe/python:$PYTHONPATH

but checking my python path again, it doesn't seem to get added in. Is this the reason? However, why is it that I can import caffe directly from my terminal but not in ST3? PS: I did add caffe to my user and etc bashrc profile.
Thank you for your help.
Comment: Possible duplicate of [Sublime Text2 Import error: No module named Gnuplot](http://stackoverflow.com/questions/13239839/sublime-text2-import-error-no-module-named-gnuplot)
Answer: You can add this before import caffe
import sys
sys.path.insert(0, '/path_to_caffe_root/python')

Comment: After I added the command, I could not import the dependencies required in caffe, like libcudart.so.8.0. What is the fundamental cause of why ST3 couldn't import caffe, although my terminal could? Is there a way to target this problem directly?
Comment: what about putting 1 instead of 0 for the first argument?
Comment: hmm it gives the same problem as putting 0.
Comment: well, what about using `append`?
Comment: for append, I removed the number as it takes in only 1 argument. However, it gives the same error as before.
Comment: Can you show the error? What did you mean by importing dependencies?
Comment: Anyway, it might be caused by the order of paths to see first.
There are discussions about this, might be useful for you (http://stackoverflow.com/questions/10095037/why-use-sys-path-appendpath-instead-of-sys-path-insert1-path) and (http://stackoverflow.com/questions/1893598/pythonpath-vs-sys-path)
Answer: I had the same problem. It turned out that there were a few virtual environments on my computer, because of Anaconda. I deactivated the virtual environmet, command pip3 list didn't show the required package, so it was installed and ST stopped complaining.
I caused the mess, without knowing -- some packages were installed in the virtual environment, and some not.


I can't find the ethernet adapter at all using terminal commands

Question: I am using Ubuntu 22.04.
The ethernet port is blinking showing that it is working
I run ip addr, and the ethernet port does not show up
Comment: You likely don't have an IP assigned to the ethernet port.  Note that just 'connecting Ethernet' on its own usually isn't sufficient enough to get internet working.  Have you checked the output of `ip link` to see if the ethernet adapter is there and that it says "UP" in the output for that adapter to make sure the link is in fact up?  (This is the first step before we dig into why you don't have an IP or nto)
Answer: First of all:
Try to verify that your Ethernet card driver is up and running and shown as a network device, so the output of that command shows groups of devices which you must have at least a (eth0, ethxx, enp0s21u1u2, enp0xx, enp1xx) named device exists in the list:
Using iproute:
ip a

Using ifconfig:
ifconfig

So if its okay and shown healthy (but no ip assigned) continue the steps:
Install NetworkManager and (nmtui + nm-applet if you don't have a network-manager gui panel which in most cases you do):
sudo apt install network-manager

then try to connect Ethernet to your PC/Laptop and let DHCP to assign an ip address to your session, verify to see if you have ip address or not:
ip a

OR
ifconfig

otherwise at that point, you must go through installation of the driver of your Ethernet card which you can try to verify the card (product & name) by:
lspci command.


Is there a way to make the terminal show a background with compositing

Question: I like using window compositing because it makes all my windows look good and have shadows, however it makes the terminal show through when I have it on. Is there a way to disable window compositing for the terminal or something similar?
What I want:

What I get with compositing on:
Comment: I want to have the desktop background be my terminal background @SadeghGhasemi
Comment: Have you disabled transparency in XFCE Terminal? http://askubuntu.com/q/63179/158442
Comment: that just makes the terminal look bad
Comment: I didnt get it, do you want to set a background image for Terminal?
Comment: I have Xubuntu 14.04 with the Xfce 4.12 upgrade and I can have transparency enabled with a background image.
Comment: @jbrock does that make it so the terminal window sees through all your other windows to the background? You might just have your compositor off
Comment: @Azdrif Ydkkaba The background image is one that you choose from within Xfce Terminal. It is not the desktop background.
Answer: Open the terminal and right click somewhere in the window. From Profiles select Profile preference. Then go to Background tab and select Background image then choose a picture and click open.

You can also select if you want the picture to scroll or not.
Comment: I think OP is using XFCE4 Terminal and that screenshot is for GNOME Terminal.
Comment: Yeah but they are almost similar. He can notice the differences.
Comment: this won't give the effect where the background stays in the same place as the window moves (at least not in xfce erminal)


How to read a file json in Angular 7 by using http module?

Question: Read JSON file in Angular 7
I am writing a simple program to output an array of data from a json file to a browser.
When I try to read a json file, I get an error:
Cannot read property 'code' of undefined.
app.module.ts :
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    RouterModule.forRoot(appRoutes),
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts :
import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

   countries: any;

   constructor(private http : HttpClient) { }

   ngOnInit(){
       this.http.get("...path to json file...")
       .subscribe((data) => this.displaydata(data));
   }

   displaydata(data) {this.countries = data;}
}

app.component.html :

  ID
  code
  name
  population

  {{country.code}}
  {{country.name}}
  {{country.population}}

Comment: While considering answers make sure you choose the fastest response. I am not asking you to mark mine, but i see you as a new user here! Just a heads up
Answer: Here:

ng-repeat is AngularJS syntax. You want

Comment: Thank you so much! I thought about this problem for 2 days ))
Answer: You need to use ngFor with Angular instead of ng-repeat which is Angularjs syntax,

  {{country.code}}
  {{country.name}}
  {{country.population}}

Answer: In Angular 7 there is no ng-repeat, use *ngFor instead

  {{country.code}}
  {{country.name}}
  {{country.population}}


How do I make things go into a dropper using water?

Question: I have a stream of water and a dropper next to it. I drop an item into the water and it travels to the dropper but doesn't go into it. How do I do this? How do I make it so that the item travels along the stream of water and then goes into the dropper without me having to do it manually?
Answer: You need to make the water flow above a Hopper, pointing the Hopper to the Dropper.
You can then make a Redstone Clock, a redstone system that activates the Dopper when it has items, or a button/lever to make the Dropper drop the items.
Comment: Giving a hopper a redstone signal disables it, rather than enabling it.
Comment: @AngusAtkinson Typo, activates the dropper, not hopper. When i mean activate, it's the same as sending a signal and making the dropper drop 1 item.


Why Post request not working on server with codeigniter 4?

Question: I started using codeigniter 4. Everything working properly on localhost but after installing on a host only "post" request not working. I cant get any value after post request.
HTML:
<form  action="<?php echo base_url()."/slider/ekle" ?>" method="POST" enctype="multipart/form-data" >

          Başlık
          <input type="text" class="form-control"  placeholder="Slider başlığı" name="baslik" value=""/>

            <button type="submit" class="btn btn-primary waves-effect waves-light mr-1">Ekle</button>

</form>

Ekle.php (Controller )
public function ekle()
{
    $baslik=$this->request->getPost("baslik");
    $aciklama=$this->request->getPost("aciklama");
    print_r($baslik);
    die();
}

What I mean is every code is working well on "localhost" but "post" request not working on my remote hosting.
Comment: @DhavalChheda its at the end of the path. The dot concatenates the output from the base url function to the path string.
Comment: Is this a shred hosting? Maybe you have post request blocked. What does it look like on what print_r?
Comment: "<?php echo base_url()."/slider/ekle" how is this working? Where is your php tag ending?
Answer: use $this->request->getVar() instead of $this->request->getPost()


Issue while calling MS graph API

Question: I am working on an API that will download the videos from OneDrive by providing a URI.
I was able to get the access token but when I try to download the file I get an error stating:

/me request is only valid with delegated authentication flow.

Below is the code that I used.
I got the access token using this API-
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'

# Fetch the access token
token = oauth.fetch_token(
    token_url=token_url,
    client_id=client_id,
    client_secret=client_secret,
    scope=scope
)

# Print the access token
print(token['access_token'])`
This worked fine.

then I called this api to fetch file details-
`file_url = 'onedrive file url'

# Set the API endpoint and parameters
url = f'https://graph.microsoft.com/v1.0/me/drive/root:/Documents/{file_url}:/'
headers = {
    'Authorization': f'Bearer {access_token}'
}

# Make the API request to get the file metadata
response = requests.get(url, headers=headers)

# Check if the request was successful
if response.status_code == 200:
    # Get the file ID and name from the metadata
    file_id = response.json()['id']
    file_name = response.json()['name']
    print(f'File ID: {file_id}, File Name: {file_name}')

    # Download the file content
    download_url = f'https://graph.microsoft.com/v1.0/me/drive/items/{file_id}/content'
    response = requests.get(download_url, headers=headers)

    # Check if the download was successful
    if response.status_code == 200:
        # Write the file to disk
        with open(file_name, 'wb') as f:
            f.write(response.content)
        print(f'{file_name} has been downloaded.')
    else:
        print(f'Error downloading {file_name}: {response.text}')
else:
    print(f'Error getting metadata for {file_url}: {response.text}')`

This returns the error:
{
    "error": {
        "code": "BadRequest",
        "message": "/me request is only valid with delegated authentication flow.",
        "innerError": {
            "date": "2023-03-27T21:15:20",
            "request-id": "d2f3f66b-7bc8-4806-a082-f2d763482570",
            "client-request-id": "d2f3f66b-7bc8-4806-a082-f2d763482570"
        }
    }
}

any ideas?
Answer: You cannot use the /me path segment using an app-only token (i.e. the Client_Credentials OAuth flow).
The /me segment is an alias for /users/{current user id}. When you authenticate using Client Credentials, you are authenticating as an Application rather than on-behalf of a given User. Without a User, there is no way for Graph to determine which User in AAD /me should map to.
You will either need to explicitly reference the User (/users/{id}) or switch to using an Authorization Code flow. This OAuth flow will generate a token on behalf of the authenticated User and enable the /me segment.

Issue while calling MS graph API


How to target nth of class when other selectors/classes exists

Question: I'm finding it hard to target the nth of a class when another class or selector exists in the same grouping.
So for example, I'm trying to get every 5th selector of a specific class called "item". But there's other selectors in the grouping called "title", which throw off the nth count.

Title

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Title

Item

Title

Item

Item

Item

    ...

.item {
    background-color: red;
}

.item:nth-child(5n+5) {
    background-color: cyan;
}

I put up a fiddle here of the full example code: https://jsfiddle.net/pb12gjp1/1/
In the fiddle, the result shows the 4th instance of ".item" having cyan applied verus the 5th one having it applied. The ".title" li's throw off the count as they're included in the nth count.
Is there any way to tackle it with jQuery? I've found there's not many options to handle it with CSS only.
Any help would be greatly appreciated.
Answer: You can use a selector directly over the li
ul li:nth-child(5n+5) {
    background-color: cyan;
}

DEMO

Sorry I understood your problem wrongly, Use .filter() with a relevant logic to solve your problem.
var items = $(".item");
items.filter(function(i){
  return i % 5 == 4;
}).css("background-color","cyan");
//or you can add a class here.

DEMO

As per your new requirement you have to use .each() along with .nextUntil() and .filter() to achieve what you want.
var titles = $(".title");
titles.each(function(i){
  $(this).nextUntil(".title").filter(function(i){
   return i % 5 == 4;
  }).css("background-color","cyan");
});

DEMO
Comment: @RyanPalmer I hope, the new edit will suits your requirement.
Comment: The result there is the same as mine. The 4th ".item" has the cyan background applied vs the 5th one having it applied.
Comment: Filtering I think is a good idea. But the last ".title" class in there throws off that final count. You can see, it takes into affect the ".item" right before it. Changed the title here to make it stand out more: https://jsfiddle.net/pb12gjp1/6/
Comment: @RyanPalmer So you want to select the each 5th `.item` after `.title`? Right?
Comment: Right. But the ordering and amount of titles and items in the lists varies from page to page. It's all dumped into the pages based on user input, so it's never the same exact order or amount.
Answer: Most probably, your markup is semantically incorrect.
Instead, I would use nested lists with :nth-child or :nth-of-type

ul > li > ul > :nth-child(5n+5) {
    background-color: cyan;
}

Title

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Title

Item

Item

Title

Item

Item

Item

Item

Item


load data local infile ignore line if a value exists

Question: There is a table with some data in it, I'm inserting additional data from txt file with this function:
LOAD DATA LOCAL INFILE 'users.txt' IGNORE INTO TABLE users2
FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'
(@col1,@col2,@col3,@col4) set login=@col1,name=@col1,balance=@col2,email=@col3,reg_date=@col4;

It works, but if login already exists with a different balance, it creates a row with a duplicate login and a different balance.
I need the function to ignore the line if the login exists. Can anybody help me with that please?
Answer: Create a unique index on the login field.
ALTER TABLE USER2 add UNIQUE KEY(login);

thats all
Comment: Thanks! That did it.


Object.assign(...as) changes input parameter

Question: Object.assign(...as) appears to change the input parameter. Example:
const as = [{a:1}, {b:2}, {c:3}];
const aObj = Object.assign(...as);

I deconstruct an array of object literals as parameter of the assign function.
I omitted console.log statements. Here's the stdout from node 13.7:

as before assign:  [ { a: 1 }, { b: 2 }, { c: 3 } ]

aObj:  { a: 1, b: 2, c: 3 }

as after assign:  [ { a: 1, b: 2, c: 3 }, { b: 2 }, { c: 3 } ]

The reader may notice that as first element has been changed in an entire.
Changing a new array bs elements to an immutable object (using freeze)
const bs = [{a:1}, {b:2}, {c:3}];
[0, 1, 2].map(k => Object.freeze(bs[k]));
const bObj = Object.assign(...bs);

leads to an error:

TypeError: Cannot add property b, object is not extensible
at Function.assign (<anonymous>)

Which indicates the argument is indeed being changed.
What really confounds me is that even binding my array, cs, by currying it to a function (I think you call this a closure in JS)
const cs = [{a:1}, {b:2}, {c:3}];
const f = (xs) => Object.assign(...xs);
const g = () => f(cs);

const cObj = g();

returns:

cs before assign:  [ { a: 1 }, { b: 2 }, { c: 3 } ]
cObj:  { a: 1, b: 2, c: 3 }
cs after assign:  [ { a: 1, b: 2, c: 3 }, { b: 2 }, { c: 3 } ]

What went wrong here? And how may one safely use Object.assign without wrecking its first argument?
Comment: You should use `Object.assign({}, ...as)` since it modifies the first argument.
Comment: Does this answer your question? [Object.assign() - weird behaviour need explanation](https://stackoverflow.com/questions/41149560/object-assign-weird-behaviour-need-explanation)
Answer: Object.assign is not a pure function, it writes over its first argument target.
Here is its entry on MDN:

Object.assign(target, ...sources)
Parameters
target
The target object — what to apply the sources' properties to, which is returned after it is  modified.
sources
The source object(s) — objects containing the properties you want to apply.
Return value
The target object.

The key phrase is "[the target] is returned after it is modified". To avoid this, pass an empty object literal {} as first argument:
const aObj = Object.assign({}, ...as);

Comment: Another term that I more commonly associate with side effects is [procedure](https://en.wikipedia.org/wiki/Procedure_(computer_science)). But you really just should write "*…is not a pure function*".
Comment: Also there's no "curried function" here.
Comment: "Any function can make modifications to an object passed in as a parameter." Yes indeed. But that's a genuinely bad thing. Even back in Fortran 77 that was frowned upon. Functions (with side-effects) oughtn't touch their arguments, use `procedure` to do so. The fact that `Object.assign` also returned the modified first argument is extra misleading. Now, your comment pointed me to why one might to do it. Since writing `o = Object.assign(o, ...as);` binds `o` to a new object (changes reference), while in `const rubbishO = Object.assign(o, ...as)` changes it without changing the bind of o.
Comment: @Bergi I thought it were trivially clear that it is not a _pure_ function, ie without side effects. I was thinking in the terms of procedure vs function. Now, since it gaves rise for more controversy than it is worth, how to edit it out. Let's try... ps.: nice to see you here Bergi, I read quite a couple of your answers  here over the course of the last weeks. Good job at getting present answers to old questions that had only clumsy pre ES6 code as answers.
Comment: About your open question: try [immutable.js](https://immutable-js.github.io/immutable-js/)
Comment: @Pointy I concede that is a very muddy statement. It is pretty obvious that the assignment of variable to reference was not changed (const as...) However, when we peel off that level of abstraction we do have no functions in any stricter sense whatsoever. Since Object.assig is obviously not pure, I'm at a loss of finding a concise phrase for a method that meddles with its input _and_ returns it. When you help me to find a more suitable 'deragoratory term' ;-) for it, I shall happily edit it :-)
Comment: Well it's absolutely no different than any other function. Any function can make modifications to an object passed in as a parameter (unless the object is frozen of course).
Comment: @Pointy (2) However, there may be a curried function. And that's when it is relevant. For instance, look at the example in the Q. Let `f' = xs => y => f(xs)`, f' is thus a function that's constant in y but has two arguments `f : [a] -> b -> { a }`. Now curry with `g' =  f'(as)` and then `g' : b -> {a}` is a function with one argument it is constant in. Now I'm not certain with nomenclatura and defs, we may extend the same principle to functions f and g, with one and zero arguments, respectively. I think you tend to call them closures.
Comment: @gschenk Just press the [[edit]] button below the answer :-)


Clojure: two different definitions of update-in in GitHub

Question: I have been trying to reimplement update-in as a learning exercise, and have been using Clojure's core.clj GitHub to find a definitive answer. I have found two separate definitions of the function, one in the Master branch:
(defn update-in
  ;; metadata removed
  {:added "1.0"
   :static true}
  ([m ks f & args]
     (let [up (fn up [m ks f args]
                (let [[k & ks] ks]
                  (if ks
                    (assoc m k (up (get m k) ks f args))
                    (assoc m k (apply f (get m k) args)))))]
       (up m ks f args))))

And one in the 010864f8ed... tree:
(defn update-in
  ;; metadata removed
  {:added "1.0"
   :static true}
  ([m [k & ks] f & args]
   (if ks
     (assoc m k (apply update-in (get m k) ks f args))
     (assoc m k (apply f (get m k) args)))))

Presumably (though I'm not sure how to find out), the version in the non-Master tree is newer and not been brought into the Master. I've tried implementing the non-Master version in the REPL and it seem to work fine. I can see the arguments are slightly different, and calling (doc update-in) in REPL returns the same arguments as the tree's definition.
I'm also slightly confused as to why the definition in Master is more verbose than non-Master version, which seems to use established Clojure functions (i.e. nothing introduced in later versions).
Please can someone:

clarify what the two different versions are?
explain why the Master's more verbose definition exists when the tree's more succinct one works (albeit with slightly different args)? Has it just been refactored to work more efficiently?
Answer: The master is actually the most recent one, which can be see by looking at the result of Blame for both trees. In the case of the Master branch, you can see the commit that introduced the changes is called improve update-in perf. I don't see any more information in the commit, which is frankly not good.
The patch introduces a local function which changes what is done when there is a non-null ks argument (the general case, when descending into keys). The recursive call to update-in through apply is replaced by a direct call to up.


what should a method return from service layer

Question: I am just wondering about the way to validate my viewmodel.
A user can own only one team, so I have to check it somehow if he hasn't got one.
<code>    public ActionResult AddTeam(TeamCreatingViewModel teamToAdd)
    {
        if (ModelState.IsValid)
        {
            //check if the user has got a team
            if (!TeamService.checkIfUserHasCreatedTeam(User.Identity.GetUserId()))
            {
                //if not then allow him to create one
                if (!TeamService.addTeam(teamToAdd, User.Identity.GetUserId()))
                {
                    ViewBag.Info = "Success";
                    return View("Info");
                }
                else
                {
                    ViewBag.Info = "It was impossible to create a new team";
                    return View("Error");
                }
            }
            else
            {
                ViewBag.info = "You have a team!";
                return View("Error");
            }
        }
        else
        {
            return View("TeamCreatingForm", teamToAdd);
        }
    }
</code>
Or would the solution below be better ?
<code>    public ActionResult AddTeam(TeamCreatingViewModel teamToAdd)
    {
        if (ModelState.IsValid)
        {
            if (!TeamService.addTeam(teamToAdd, User.Identity.GetUserId())) //<--- now it is checking and adding (if allowed)
            {
                ViewBag.Info = "Success";
                return View("Info");
            }
            else
            {
                ViewBag.Info = "It was impossible to create a new team";
                return View("Error");
            }
        }
        else
        {
            return View("TeamCreatingForm", teamToAdd);
        }
    }
</code>
How can I report (from service layer) if an error has occured (and what kind of )? In the second case, users won't know anything about what was done wrong.
And in the first case I have to get an entity object 2 times, what seems to be useless.
Answer: You can report errors from business layer by throw out param, for example
<code>public bool AddItem(string name, out List<string> errors){...}// or just string with error
</code>
Comment: Yes, if your service code will be used from two or more places(web+api for example). I think it's more elegant then throw exceptions and catch them later.


Every set of size $2^n-1$ has a subset of size $2^{n-1}$ that sums to a multiple of $n$

Question: Is the following statement true? If so, how can it be proved?

Every set of $2^n-1$ positive integers, $n\in\{1,2,\dots\}$, has a subset of size $2^{n-1}$ that sums to a multiple of $n$.

An attempt at a proof
I was able to prove a similar, but weaker statement:

If $n\in\{1,2,\dots\}$ is a power of $2$, then every set of $2^n-1$ positive integers has a subset of size $2^{n-1}$ that sums to a multiple of $n$.

Indeed, noting that $k\leq2^{k-1}$ for every $k\in\{1,2,\dots\}$ (this can be shown by induction), we must have $n\leq 2^{n-1}$, and therefore $n=2^{k-1}$ for some $k\in\{1,2,\dots,n\}$, hence $2^{n-1}=mn$ for some $m\in\{1,2,\dots\}$ (namely, $m=2^{n-k}$), whence $2^n-1\geq m(2n-1)$. By the Erdős–Ginzburg–Ziv theorem, there are $m$ disjoint subsets each of size $n$, each of which sums to a multiple of $n$. Their union is a subset of size $mn=2^{n-1}$ that sums to a multiple of $n$. Q.E.D.
Comment: If the $2^n-1$ numbers are all congruent to $1\bmod{n}$ then any $2^{n-1}$ of them have a sum congruent to $2^{n-1}\bmod{n}$ hence we need $n\mid 2^{n-1}$, i.e. the problem is false when $n$ is not a power of two. When $n$ is a power of two, you correctly solve it.
Comment: @oVlad This solves my question. Thanks. If you post it as an answer, I will accept it.
Comment: Glad I helped :)
Answer: If the $2^n-1$ numbers are all congruent to $1\bmod{n}$, then any $2^{n−1}$ of them have a sum congruent to $2^{n−1}\bmod{n}$, hence we need $n\mid 2^{n−1}$, i.e. the problem is false when $n$ is not a power of two.
When $n$ is a power of two, you correctly solve it.


java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream

Question: When I'm reading Excel file(.xls format), I keep getting an Exception :
java.lang.IllegalArgumentException: Your Input Stream was neither an OLE 2 stream, nor an OOXML stream.

I Go-ogled and found that if the input stream is not supporting reset or mark, I should wrap it with pushbackStream. My input stream is not mark\reset supported.
So using pushbackStream is the only option? How to use it? And whats the use of it?
Thanks
Comment: Are you sure your file really is an Excel .xls file? And not, say, a .csv or .html file with the extension changed?
Comment: No, its a Excel .xls file.
Comment: Please provide your SSCCE.
Comment: The file may be empty as well, like reading from the InputStream failed or all data was already previously read
Answer: Your InputStream was neither an OLE2 stream, nor an OOXML stream
java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream

I guess you are using Workbook Factory OR a different format input file and different workbook type. This error usually pops up when its not able to not able to read the file type. Apache POI does not check the file extension. If you open it in a text editor, you'll see that instead it'll be in a different format. Or you might be initializing the workbook type to HSSF or XSSF, before using Workbook Factory.
Simpler solution is to open the file using Microsoft Excel and save it as another file(using File>Save As option from Microsoft Excel > Menu).
Workbook Factory does not check the file extension, Instead it checks the file MIME type. Basically excel works with different files(Eg: the files created using third party applications, excel 2003 version), but Apache POI is very specific.
PushbackInputStream adds "push back" or "unread" functionality to another input stream. It allows you to read ahead a few bytes to see what is coming, before you can determine how to interpret the current byte.
If you are not using Workbook Factory, PushbackInputStream is the only alternative I guess.
If you can share the code here I can test it and reconfirm it.
Comment: Your suggestion don't help me :(
Comment: I can help you if you can tell me about the error in detail.
Comment: Thank you, But I don't remember the problem. I have solved it! :)
Comment: CAN you provide solution @Andrey E
Comment: @Labeo sadly I don't remember that problem and how I solved it. Think You should create a separate question if this answer didn't help you.
Or just explain your problem in detail and share some code.
Comment: http://stackoverflow.com/questions/33175608/unable-to-read-excel-files-in-java-getting-2-below-error-in-java


Why is the following NOT a proof of The Chain Rule?

Question: In Leibniz notation of the chain rule,
$$\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}$$
Where $y\left ( u\left ( x \right ) \right )$ is a composite function of x.
I understand that the du's don't simply cancel out because $\frac{dy}{du}$ and $\frac{du}{dx}$ are defined as specific limits making the numerator and denominator infinitesimals and thus making the whole thing indeterminate and inoperable on.
But applying the definition of a derivative, we can express the above like so:
$$\lim_{\Delta x\to 0} \frac{\Delta y}{\Delta x} = \lim_{\Delta u\to 0} \frac{\Delta y}{\Delta u} \cdot \lim_{\Delta x\to 0} \frac{\Delta u}{\Delta x}$$
At this point we can't use the Product Law of Limits to combine the two limits on the right.
But if we consider a coordinate system u vs x, doesn't $\Delta u \rightarrow 0$ when $\Delta x \rightarrow 0$ ? And if so,  then whenever $\Delta u \rightarrow 0$ we necessarily have $\Delta x \rightarrow 0$.
Then can't we rewrite the above limit equation as:
$$\lim_{\Delta x\to 0} \frac{\Delta y}{\Delta x} = \lim_{\Delta x\to 0} \frac{\Delta y}{\Delta u} \cdot \lim_{\Delta x\to 0} \frac{\Delta u}{\Delta x}$$
And then can't we use the Product Law of Limits to say:
$$\lim_{\Delta x\to 0} \frac{\Delta y}{\Delta x} = \lim_{\Delta x\to 0} \left (  \frac{\Delta y}{\Delta u} \cdot \frac{\Delta u}{\Delta x} \right )$$
And since $\frac{\Delta y}{\Delta u}$ and $\frac{\Delta u}{\Delta x}$ within the quantity who's limit is being taken are no longer "quotients" infinitesimals,  Δu's can cancel, leaving us with:
$$\lim_{\Delta x\to 0} \frac{\Delta y}{\Delta x} = \lim_{\Delta x\to 0}   \frac{\Delta y}{\Delta x} $$
Which in Leibniz notations looks like:
$$\frac{dy}{dx} = \frac{dy}{dx}$$
Q.E.D (Since we manipulated the right hand side of the equation into looking the same as the left hand side).
Comment: I'll point out here that the bit about not treating $dy/dx$, etc. as ordinary fractions in deriving $dy/dx = (dy/du)(du/dx)$ is not just mathematicians being pedantic. It's false in, for example, higher dimensions: the corresponding chain rule for a function $f(t) = g(x(t), y(t))$ is $\frac{df}{dt} = \frac{\partial g}{\partial x}\frac{dx}{dt} + \frac{\partial g}{\partial y} \frac{dy}{dt}$.
Comment: Why do you make this assumption "if we consider a coordinate system ***u*** vs ***x***, doesn't $\Delta u \rightarrow 0$ when $\Delta x \rightarrow 0$"?. May need to consider a practical example where the relation between u and x is inversely proportional.
Comment: NoChance -
 The relationship between **u** and **x** may be governed by inverse proportionality but as far as I can tell the relationship between $\Delta u$ and $\Delta x$ is always proportional.
Answer: The main problem is that you could have $\Delta u = 0$ for some $x$, which makes $\dfrac{\Delta y}{\Delta u}$ undefined.
Comment: Yes! Thank you. Obviously that disqualifies this as a proof, but for all other cases this analogy holds? I'm trying to make a notebook of math based on solely intuitive explanations I come up with or gather along the way. Wondering if I can include this or if it is too non-technical.
Answer: The proof given in question is almost rigorous and correct but written in reverse (as pointed out by Wazul). Moreover this is a very standard proof of the chain rule. Contrary to what many students think this proof is not based on infinitesimals. But we do need to add some details.

Let $u = g(x)$ be differentiable and $y = f(u)$ be also differentiable. Then $y = f(g(x)) = (f \circ g)(x)$ and the Chain Rule says that $$\frac{dy}{dx} = \frac{dy}{du}\cdot\frac{du}{dx}$$ or $$(f\circ g)'(x) = f'(u)g'(x) = f'(g(x))g'(x)$$ The proof in the question needs to be supplemented with proper definitions of $\Delta u, \Delta y$.
We have $\Delta u = g(x + \Delta x) - g(x)$ and $$\frac{du}{dx} = g'(x) = \lim_{\Delta x \to 0}\frac{g(x + \Delta x) - g(x)}{\Delta x} = \lim_{\Delta x \to 0}\frac{\Delta u}{\Delta x}$$ And similarly with $\Delta y = f(u + \Delta u) - f(u)$ we have $$\frac{dy}{du} = f'(u) = \lim_{\Delta u \to 0}\frac{f(u + \Delta u) - f(u)}{\Delta u} = \lim_{\Delta u \to 0}\frac{\Delta y}{\Delta u}$$ We then have
\begin{align}
\frac{dy}{dx} &= (f\circ g)'(x) = \lim_{\Delta x \to 0}\frac{(f \circ g)(x + \Delta x) - (f \circ g)(x)}{\Delta x}\notag\\
&= \lim_{\Delta x \to 0}\frac{f(g(x + \Delta x)) - f(g(x))}{\Delta x}\notag\\
&= \lim_{\Delta x \to 0}\frac{f(g(x) + \Delta u) - f(g(x))}{\Delta x}\notag\\
&= \lim_{\Delta x \to 0}\frac{f(u + \Delta u) - f(u)}{\Delta x}\notag\\
&= \lim_{\Delta x \to 0}\frac{f(u + \Delta u) - f(u)}{\Delta u}\cdot\frac{\Delta u}{\Delta x}\text{ (assume }\Delta u \neq 0)\notag\\
&= \lim_{\Delta x \to 0}\frac{f(u + \Delta u) - f(u)}{\Delta u}\cdot\frac{g(x + \Delta x) - g(x)}{\Delta x}\notag\\
&= \lim_{\Delta u \to 0}\frac{f(u + \Delta u) - f(u)}{\Delta u}\cdot\lim_{\Delta x \to 0}\frac{g(x + \Delta x) - g(x)}{\Delta x}\notag\\
&= f'(u)g'(x)\notag\\
&= \frac{dy}{du}\cdot\frac{du}{dx}
\end{align}
We have assumed in the above that $\Delta u \neq 0$ when $\Delta x \to 0$. Also by continuity of $u = g(x)$ (note that differentiability implies continuity) we have $\Delta u \to 0$ as $\Delta x \to 0$.

The above argument fails when $\Delta u = g(x + \Delta x) - g(x)$ vanishes for infinitely many values of $\Delta x$ as $\Delta x \to 0$. In this case we we have $du/dx = g'(x) = 0$. Why? Because if $g'(x) \neq 0$ then the ratio $\Delta u / \Delta x \neq 0$ for all small values of $\Delta x$ and hence $\Delta u \neq 0$ for all small values of $\Delta x$.
Hence if $\Delta u = 0$ for infinitely many small values of $\Delta x$ then $du/dx = g'(x) = 0$. We show that in this case $dy/dx = 0$. Clearly for those values of $\Delta x$ for which $\Delta u = 0$ we also have $\Delta y = f(u + \Delta u) - f(u) = 0$ so that the ratio $\Delta y/\Delta x = 0$. For values of $\Delta x$ where $\Delta u \neq 0$ we know that $\Delta y/\Delta u$ is bounded (because the derivative $dy/du$ exists) and the ratio $\Delta u/\Delta x$ can be made arbitrarily small (because its limit is $du/dx = 0$). Hence the overall product $$\frac{\Delta y}{\Delta x} = \frac{\Delta y}{\Delta u}\cdot\frac{\Delta u}{\Delta x}$$ can be made arbitrarily small by choosing $\Delta x$ sufficiently small. It follows that $\Delta y / \Delta x$ can be made arbitrary small for all sufficiently small values of $\Delta x$. It follows that $$\frac{dy}{dx} = \lim_{\Delta x \to 0}\frac{\Delta y}{\Delta x} = 0$$ and therefore the chain rule holds true in this case also.
Note that most common textbooks of calculus omit the discussion of the case when $\Delta u = 0$. Also it is much better to type and understand if $\Delta x$ is replaced by $h$ and $\Delta u$ is replace by $k$. However I have tried to stick to the notation used by OP.
Answer: If $\Delta u=0$ then you have a $0$ in a denominator.
That's not a problem if it happens only when $|\Delta x|>0.000000000001$ since the limit depends only on what happens when $|\Delta x|$ is less than that.  And similarly with any other positive number in place of $0.000000000001$.
But now suppose it happens when $|\Delta x|=0.000000000001$ and again when $|\Delta x| =0.000000000001^2$ and again when $|\Delta x|=0.000000000001^3$ and so on, ad infinitum.  Then it's a difficulty to be addressed.  And what if $\Delta u=0$ for all $\Delta x$ between $\pm 0.001$?  Then your proof clearly won't work.
Hence one writes
$$
\frac{\Delta y}{\Delta x} = \left.\begin{cases} \Delta y/\Delta u & \text{if } \Delta u\ne0, \\[6pt]  dy/du & \text{if }\Delta u = 0, \end{cases} \right\} \cdot \frac{\Delta u}{\Delta x}
$$
and one goes on from there. The $\displaystyle \left\{ \begin{array}{c} \text{factor in} \\ \text{braces} \end{array} \right\}$ approaches $dy/du$ as $\Delta x\to 0$ and the second factor, $\dfrac{\Delta u}{\Delta x}$, approaches $du/dx$.
Comment: Yes.  $\vphantom{\dfrac{\displaystyle\int}{\displaystyle\int}}$ $\displaystyle \lim_{\Delta x\to0} \frac{\Delta y}{\Delta x} = \lim_{\Delta x\to0} \left( \left.\begin{cases} \Delta y/\Delta u & \text{if } \Delta u\ne0, \\[6pt]  dy/du & \text{if }\Delta u = 0, \end{cases} \right\} \cdot \frac{\Delta u}{\Delta x} \right)$ $\displaystyle= \left(\lim_{\Delta x\to0} \left.\begin{cases} \Delta y/\Delta u & \text{if } \Delta u\ne0, \\[6pt]  dy/du & \text{if }\Delta u = 0, \end{cases} \right\} \right) \cdot \left( \lim_{\Delta x\to0} \frac{\Delta u}{\Delta x} \right)$. ${} \qquad {}$
Comment: You're talking about making that adjustment here:

$$\lim_{\Delta x\to 0} \frac{\Delta y}{\Delta x} = \lim_{\Delta x\to 0} \left (  \frac{\Delta y}{\Delta u} \cdot \frac{\Delta u}{\Delta x} \right )$$

Right?
Comment: Thanks, Much clearer now. This will go in my notebook.
Comment: I find this strange... When $\Delta u = 0$ then obviously $\Delta y = 0$ and hence we can write $\Delta y/\Delta x = \text{ anything }\times \Delta u/\Delta x$. Why choose specifically $dy/du$? A proper justification of $\Delta u = 0$ case is given in my answer. In this case we have $du/dx = 0$ and $dy/dx = 0$ so that chain rule holds.
Comment: @ParamanandSingh : When $\Delta u=0$ then $\Delta y=0$ and we can write $\Delta y/\Delta x = \text{ anything }\times \Delta u/\Delta x$ because $\Delta u/\Delta x=0$, so this equality says $0=0$, which is true.  The reason why $dy/du$ is chosen as the value of the piecewise factor when $\Delta u=0$ is that that is what makes the piecewise factor continuous. ${}\qquad{}$
Answer: This is not a proof, because you start with the formula you want to prove and imply a true statement. But a true statement can by implied by a false statement. You would have to start with
$$ \frac{dy}{dx}=\frac{dy}{dx} $$
and then prove
$$ \frac{dy}{dx}= \frac{dy}{du}\cdot\frac{du}{dx} $$
and not the other way around.
Comment: Isn't that exactly how all proofs we do in a College Trig class work though? Assume an identity is true, manipulate one side into looking exactly like the other, and there you have your proof. What's different about this?
Comment: You're right of course that starting with what you want to prove and deducing something true is not a proof. But that's not the problem here - if that were the major problem then what he wrote could easily be made into a valid proof, just by rewriting it.
Comment: I disagree, because you cannot be sure that you can seperate the two limits.


CodeIgniter SQL Query to include apostrophes and search every column in a specific order

Question: First off, I'm not a programmer and attempting to learn from Google on a project I've been trying to complete for myself.
Technologies Used: CodeIgniter 2.1.2, PHP 5.3, MySQL
I have a search keyword box on my page, what I'd like this to do is search an entire table but show results in a specific order.
I currently have this SQL query which does not work with apostrophes and does not order the results by column.
function search($keyword)
 {
  $query="SELECT *
  FROM HWC
  WHERE ModelName LIKE '%{$keyword}%' OR Toy LIKE '%{$keyword}%'OR Year LIKE '%{$keyword}%'
  OR Col LIKE '%{$keyword}%'OR Series LIKE '%{$keyword}%'OR Color LIKE '%{$keyword}%'
  OR Tampo LIKE '%{$keyword}%'OR BaseColor LIKE '%{$keyword}%'OR BaseType LIKE '%{$keyword}%'
  OR WindowColor LIKE '%{$keyword}%'OR InteriorColor LIKE '%{$keyword}%'OR WheelType LIKE '%{$keyword}%'
  OR Country LIKE '%{$keyword}%'OR 'Series#' LIKE '%{$keyword}%'OR Notes LIKE '%{$keyword}%'";

  $result=$this->db->query($query);
  $result=$result->result_array();

  return $result;
}

I know this is wrong, it was temporary to get some things working.
Honestly I could break it into 3 catagories for sorting
ModelName
Toy
Other (All the rest)

I'd also like the SQL Query that I build to support pagination, but that shouldn't be hard with an offset and limit from what I read.
Answer: You might have not notice but there is an error in your query year is your column name and mysql also has a function year so it will generate the error you have put you column name with back ticks " ` "  if your are not sure that it will conflict with t any function name, Best practice to add the back ticks on all columns so there will be no chance of conflicting  so it will look like this
SELECT *
  FROM HWC
  WHERE `ModelName` LIKE '%{$keyword}%' OR `Toy` LIKE '%{$keyword}%' OR `Year` LIKE '%{$keyword}%'
  OR `Col` LIKE '%{$keyword}%'OR `Series` LIKE '%{$keyword}%' OR `Color` LIKE '%{$keyword}%'
  OR `Tampo` LIKE '%{$keyword}%' OR `BaseColor` LIKE '%{$keyword}%' OR `BaseType` LIKE '%{$keyword}%'
  OR `WindowColor` LIKE '%{$keyword}%' OR `InteriorColor` LIKE '%{$keyword}%' OR `WheelType` LIKE '%{$keyword}%'
  OR `Country` LIKE '%{$keyword}%' OR `Series#` LIKE '%{$keyword}%' OR `Notes` LIKE '%{$keyword}% '

For order by the result set you can order by with multiple columns like
ORDER BY col1,col2,col3
For pagination of the result you have use the LIMIT function of mysql with the starting index and the ending index like
LIMIT 0 , 10 or for first 10 results simply you can specify LIMIT 10 keep in mine that limit will be applied at the end of query by default it will order the result set in ascending order but you can specify the order if you want result set in  descending order DESC.
SELECT *
  FROM HWC
  WHERE `ModelName` LIKE '%{$keyword}%' OR `Toy` LIKE '%{$keyword}%' OR `Year` LIKE '%{$keyword}%'
  OR `Col` LIKE '%{$keyword}%'OR `Series` LIKE '%{$keyword}%' OR `Color` LIKE '%{$keyword}%'
  OR `Tampo` LIKE '%{$keyword}%' OR `BaseColor` LIKE '%{$keyword}%' OR `BaseType` LIKE '%{$keyword}%'
  OR `WindowColor` LIKE '%{$keyword}%' OR `InteriorColor` LIKE '%{$keyword}%' OR `WheelType` LIKE '%{$keyword}%'
  OR `Country` LIKE '%{$keyword}%' OR `Series#` LIKE '%{$keyword}%' OR `Notes` LIKE '%{$keyword}% '
ORDER BY `ModelName`, `Toy` LIMIT 0,10'

Note

If you are not adding the back ticks on the column names then make sure they are unique and also put a space between the operators, functions etc and the column names  like
  LIKE '%{$keyword}%'OR should be with space LIKE '%{$keyword}%' OR


Can I rest floor joists on a ledger lying under the beams?

Question: I'm building a 1.5 story cabin and have a full perimeter 8" block foundation that's 20' x 40' with 16" x 16" piers inside...2 rows of 5ea piers. Piers are the same elevation as the perimeter block.
My joists will run with the 20' width, 3 joists to create the 20' span (sill plate to pier...pier to pier...pier to sill plate). Basically 3 joist 6.6' long.
My questions are...
Can I run a sill plate from pier to pier the 40' way, for the girder (for lack of better definition) to sit on, and use that sill plate as a ledger for the joists? Didn't know if the ledger would have to be nailed to the sides of the girder.
Secondly, will I need to double or triple the girders.
I plan to use 2 x 8's for everything.
This is the way I had planned to frame it.
,
but the piers are actually 16" x 16" rather than 8" x 16".
Comment: Why do you have a beam/ledger running the 40' direction on the piers?  Do you have some load bearing wall riding above them?
Comment: Just figured that was the easiest way to frame it. Nothing load bearing inside. Going to try to add a plan view pic showing the foundation only.
Answer: No. Your joists must bear on the beam directly, using hangers or actually resting on it. Even if you'd bolt the ledger up to the bottom of the beam you'd be relying on cross-grain strength. Not a good situation.
As to your beam sizing question, that's for an engineer to answer (with drawings in hand). We don't have enough information about the structure as a whole to properly answer that. I can speculate, since 2x8 lumber isn't used for floor systems anymore, that even tripled you wouldn't meet most codes.
Comment: How do joist hangers compare in strength to running the joists over the girder? Larry Haun put the joists over the girders here https://i.ytimg.com/vi/pQbKmPWCOf4/hqdefault.jpg
Comment: Full video of Larry Haun framing a floor https://www.youtube.com/watch?v=b2KfsJoZCnM
Comment: Specifically-designed hangers, such as those from Simpson, are commonly used in modern construction. However, they do make hangers of various thicknesses for different uses. You'd want the heavier ones.
Answer: Ok, I see what you're getting at.
You would have to have an engineer spec the beam (probably microlam) that runs on top of the piers, but then yes, you would use joist hangers to hang the joist from those beams.
For a 20' span, I think two rows of piers is overkill.  You could easily go with a single row.  Or even a clear span with something like a 12" TJI 360 or 14" TJI 110 (TJI Span Table).  Till you figure the cost of those piers, beams, hangers, etc., I think you'll still come out ahead and have a better floor.
Note that the "sill plate" you show on top of the piers doesn't need to run between the pier - your joists will be supported by joist hangers from the beam.
Comment: Thanks, but the piers are already in place.


Relationship between the sum of the marginal percent change and cumulative percent change?

Question: Let's say I have a sequence denoted $a_n=a_0+kn$. The total percent increase from $n=0$ to $n$ is just $100\cdot\frac{kn}{a_0}$.
However, let's denote the sum of the marginal percent increase as $100\cdot \sum_{i=0}^{n-1} \frac{k}{a_0+ki}$.
I'm wondering if there's a connection between the total/overall percent increase and the sum of the marginal percent increases? I understand how percent increase is inherently multiplicative in nature, but I'm wondering if there's a simple way to go from the result of the sum above to the cumulative percent increase. I tried computing a closed form of the sum first but I'm getting results with the polygamma function and I can't figure out a conversion.
Edit: to clarify, I'm wondering if it is possible without knowing $a_0$ or $k$. So you would be given $n$ and you would be given the sum of the marginal percentage increases. Can you then find purely from this information the cumulative percent increase?
Comment: It seems clear that you cannot compute the total percent increase if you know the sum of the marginal percent increases but do not know $n$ and do not know both $a_0$ and $k.$ So, exactly what information do you suppose to be known when you want to make your calculation? Do you know $n$ and the sum? (I don't promise there will be a good answer if you explain this, but as it stands, you haven't asked the question yet.)
Comment: @DavidK I wanted to see if it was possible without knowing either. I thought maybe $a_0$ would cancel in both expressions and we'd be left with something involving $k$. I've edited my question accordingly.
Answer: If $a_0 \gg kn$ the marginal percent increase does not change much, so is just the total percent increase divided by $n$, which is $100\frac k{a_0}$.  Otherwise the sum of the marginal percent increases will be smaller because the absolute increase stays the same and the base is increasing.  The next level of approximation would be to take the average of the marginal percent increases as $x$ and say the total percent increase is $(1+\frac x{100})^n$.  This should be accurate for $kn$ much closer to $a_0$.  Make up a spreadsheet and give it a try.
Answer: Given the values of $t$ (a real number) and $n$ (a positive integer),
and given the fact that
$$ t = 100\sum_{i=0}^{n-1}\frac{k}{a_0+ki} $$
where $a_0$ and $k$ are unknown,
you wish to find the value of $100\frac{kn}{a_0}.$
If you let $r=\frac{k}{a_0},$ then
$$
\sum_{i=0}^{n-1}\frac{k}{a_0+ki}
=\sum_{i=0}^{n-1}\frac{r}{1+ir}
=r \sum_{i=0}^{n-1}\frac{1}{1+ir}.
$$
Define a function $f(r) = r\sum_{i=0}^{n-1}\frac{1}{1+ir}$; then

$f(0) = 0$, $f(r)$ is strictly increasing for $r \geq 0,$
and $\lim_{r\to+\infty} f(r) = +\infty,$
so if we restrict $a_0$ and $k$ so that $\frac{k}{a_0} \geq 0,$
then whenever $t \geq 0$
there is exactly one solution for the unknown $r$ in $100f(r) = t$
provided that $t \geq 0.$
You can then find the value of $100\frac{kn}{a_0}$
by using that value of $r$ in the formula
$$100\frac{kn}{a_0} = 100rn.$$
For all but a few possible values of $n,$ I do not believe there is a conventional closed-form solution of $100f(r) = t,$
so in general I would expect to have to solve for $r$ using numerical methods.
Also note that $f(r)$ is undefined at
$r=-1,-\frac12,-\frac13,\ldots,-\frac{1}{n-1},$
that $f(r)$ tends to $\pm\infty$ near those values of $r,$
that $\lim_{r\to-\infty} f(r) = -\infty,$
but $f'(r) > 0$ whenever $f(r)$ is defined.
Graphing $y=f(r)$ according to those facts, it is clear that
if we allow solutions such that $r < 0,$
there are $n$ possible solutions of $100 f(r) = t$ for any real number $t.$
But if you assume that $a_0 > 0$ and $k \geq 0,$ you avoid this complication.


Let $E$ be a TVS and $f:E \to \mathbb R^n$ linear. If $\ker f$ is closed, then $f$ is continuous at $0_E$

Question: Previously, I showed that

Theorem Let $E$ be a (not necessarily Hausdorff) real TVS and $f:E \to \mathbb R$ linear. If $\ker f$ is closed, then $f$ is continuous at $0_E$.

The proof is as follows:

Assume that $H := \ker f$ is closed and thus $H^c$ is open. WLOG, we assume $f$ is not constant. Then there exist $a \in H^c$ and an open neighborhood (nbh) $U$ of $0_E$ such that $U +a \subseteq H^c$.
Let $T:\mathbb R \times E \to E, (t, x) \mapsto tx$ be the scalar multiplication. Then $T$ is continuous. Then there are open nbh $V_1$ of $0_{\mathbb R}$ and open nbh $U_1$ of $0_E$ such that $T (V_1 \times U_1) \subseteq U$. There is $t_1 >0$ such that $I := (-t_1, t_1) \subseteq V_1$. Let $U_2 := \bigcup_{t \in I} t U_1 \subseteq U$.
We claim that $f(U_1)$ is bounded. If not, for each $m \in \mathbb N$, there is $x_m \in U_1$ such that $|f(x_m) |> m$. Then $m t_1(-1, 1) \subseteq f(Ix_m)$ for all $m \in \mathbb N$. Then $f(U_2) = \mathbb R$. So there is $b \in U$ such that $f(b + a) = 0_\mathbb R$, which is a contradiction. So $f(U_1)$ is bounded. Hence there is $t_2 >0$ such that $f(U_1) \subseteq (-t_2, t_2)$.
If $N = (-t_3, t_3)$ is a nbh of $0_\mathbb R$, then $f \left (\frac{t_3}{t_2}U_1 \right) \subseteq N$. It follows that $f$ is continuous at $0_E$.

I tried but could not adapt above proof to the case $f:E \to \mathbb R^n$. Could you elaborate on how to do so?
Answer: Not an adaption but a different proof. For $H=$ker$(f)$ let $q:E\to E/H$ be the quotient map. Since $H$ is closed the quotient topology on $E/H$ is Hausdorff, and since finite dimensional spaces have a unique Hausdorff TVS topology the induced linear map $\tilde f: E/H\to \mathbb R^n$ (mapping the equivalence class of $x$ to $f(x)$) is continuous. This implies the continuity of $f=\tilde f\circ q$.
Comment: Actually, I want to use my theorem to prove (S1): *finite dimensional spaces have a unique Hausdorff TVS topology*. Is there an approach that does not appeal to (S1)?


Ubuntu Server 16.04 Letsencrypt SSL Website Configuration File

Question: I am new to Linux. I have sucessfully set up a server with Linode, and have installed a LAMP stack and my website works now. What I wanted to do was install a SSL certificate using "Lets Encrypt". I followed the guide here https://www.linode.com/docs/security/ssl/install-lets-encrypt-to-create-ssl-certificates.
After that I got this message:
IMPORTANT NOTES:

Congratulations! Your certificate and chain have been saved at /etc/letsencrypt/live/msystim.com/fullchain.pem. Your cert will expire on 2017-02-05. To obtain a new or tweaked version of this certificate in the future, simply run letsencrypt-auto again. To non-interactively renew all of your certificates, run "letsencrypt-auto renew"
If you lose your account credentials, you can recover through e-mails sent to email@example.com.
Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal.

So that's all good.
Now what I was wondering is how to set up my site configuration file to use the certificate?
Current Set Config looks like this
Comment: Have a look here: [CertBot](https://certbot.eff.org/#ubuntuxenial-apache) - It's a much more efficient way of doing it, and it sets up your config for you.
Answer: You need to add a directive to your site config for ssl.  You'll need to modify the following to match your site settings.  Once you've made your changes, you'll need to sudo service apache2 reload for it to take affect.

<VirtualHost *:443>
    SSLEngine On
    SSLCertificateFile /etc/ssl/certs/example.com.crt
    SSLCertificateKeyFile /etc/ssl/private/example.com.key
    SSLCACertificateFile /etc/ssl/certs/ca-certificates.crt  #If using a self-signed certificate, omit this line

    ServerAdmin email@example.com
    ServerName www.example.com
    DocumentRoot /var/www/example.com/public_html/
    ErrorLog /var/www/example.com/log/error.log
    CustomLog /var/www/example.com/log/access.log combined
</VirtualHost>

Comment: I got this error code when I tried that ........Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details.     Does port 80 need to stay turned on? Do I need to change the apache config file? Is port 443 possibly not open?
Comment: The output from systemctl status will give more insight.  You don't need to keep port 80 on, though usually it's a good idea to redirect to 443.  I'm not sure if it actually checks if 443 is open, I'd imagine not.


How to display images in JS using loop?

Question: I have this function, and I'm trying to display photos using a loop.
in name1 I have the file location of the photos, every loop I change the photo so the location is obviously changed.
in console.log I do see the file, for example "cardImages/7_of_diamonds.png".
now the problem that I have is that I don't really understand how to display the photos and keep them there, so I have 2 ways that I found but they don't actually work.
and the end result should look like the photo I added to the post.
the first loop for the ph1 id.
and the second loop for the ph2 id.
what I'm missing here?
example
   //$("#ph1").append("");

    //result.innerHTML = "";

     function DisplayUsingLoop(pla1, numb1) {
                var name1;

                for (i = 0; i < numb1; i++) {

                    name1 = pla1[i].img
                    console.log(name1)
                   result.innerHTML = "";
                }

                for (i = 0; i < numb2; i++) {

                    name1 = pla2[i].img
                    console.log(name1)
                    $("#ph1").append("");
                }

    <input type="button" value="Start" onclick="start()" />

            Player 1:

            Player 2:

Answer: To display photos using a loop, use the for loop. First of all, you need to put your js inside of tags, like this:

Player1:
//this is js
let div = document.getElementById(`ph1`)
for (let i = 0; i < 5; i++) {
div.innerHTML += `<img src=`your_image_file_name`></img>`
}

if you want different images each time, then manually do it without a loop:
//this is js
let div = document.getElementById(`ph1`)

div.innerHTML += `<img src='img1.png'></img>`

div.innerHTML += `<img src='img2.png'></img>`

Also, try to learn js and html using w3schools before you start coding this stuff.
Also, you are using jQuery, which you need to import using html before you start your js.
Also, try using strict html formatting and put js at the end of your body.
Comment: thanks! this works, but for some reason instead of using `` in `your_image_file_name` i iused '', maybe becuase the file location is saved in changed var.
Comment: Do you have any idea why im getting this Identifier 'div' has already been declared? @JSst67?
Comment: Sorry, @user17712660, my keyboard is funky, so it does ', which is not the proper character and not accepted in most platforms. I need to fix that.
Comment: Do not put the two snippets of code together, since "div" can only be declared once. If you need to put them together, use another variable name. If you already have a variable "div" already use different variable names.
Answer: Try this
your start function should contain your players' card arrays.
function start(){
 var cards1 = ["cardImages/A_of_diamonds.png", "cardImages/2_of_diamonds.png", "cardImages/3_of_diamonds.png", "cardImages/4_of_diamonds.png"];

 var cards2 = ["cardImages/10_of_diamonds.png", "cardImages/J_of_diamonds.png", "cardImages/Q_of_diamonds.png", "cardImages/K_of_diamonds.png"];

 DisplayUsingLoop(cards1, 4, "ph1");
 DisplayUsingLoop(cards2, 4, "ph2");
}

To the DisplayUsingLoop function I added the idPlayer
function DisplayUsingLoop(pla1, numb1, idPlayer)

JSFiddle - example
Answer: Maybe use a class in your divs like 'ph' and then use something like this:
let x=document.getElementsByClassName('ph');
    Array.from(x).forEach((el)=> {
        el.innerHTML += `<img src=`image_src_name`></img>`
        };

How to display images in JS using loop?


From sql query to Pandas (pd.NamedAgg() )

Question: I would like to transform this query with a pandas function, but I have problems with variables constructed from other variables, e.g. var1. Can anyone help me with this?
This is the query:
select
AVG(VAR_1),
AVG(VAR2+ VAR3) AS X,
1 - (SUM(VAR1)/SUM(VAR2)) AS Y,
AVG((VAR1) / ((VAR2/ 1.22) - VAR3)) AS Z
FROM data
group by id

And this is my pandas function incomplete:
df = input.groupby(['ID'], as_index=False) \
                    .agg(VAR1 = pd.NamedAgg(column = 'VAR1', aggfunc='mean'),
                         X =  pd.NamedAgg(),
                         Y  = pd.NamedAgg(),
                         Z = pd.NamedAgg()
                    )

How do I complete this function?
Thanks
Answer: Use the pandasql:
import pandas as pd
import pandasql as ps

df = pd.DataFrame('Define your fataframe')

q1 = """ <PLACE YOUR SQL QUERY HERE> """

print(ps.sqldf(q1, locals())) # or globals

Comment: I try pandasql but there isn't standard deviation function.....
Comment: Place the sql query in "q1"


Shrink a partition without losing data

Question: I've got a Linux-based OS installed on a partition I want to shrink. Want to avoid reinstallation or losing/corrupting data, if possible.
Answer: As always:
D O   A   BACKUP. At least of the sensitive data on the partition, you want to shrink. Neither I, nor geparted can be held responsible if you screw up.
Now to the procedure using gparted:

The picture is a little messy but don't get scared (you'll be moving with your partition to your auntie and uncle in Bel Air. Wait wat? XD). Just stick with this for a moment and follow the instructions below. Start looking at the image in the top right corner. Then follow the numbers in ascending order.
Here is a text version of the steps numbered as in the picture:

Install gparted / sudo apt-get install gparted
Start gparted

Select the disk in the upper right dropbox
Select the partition in the main list in the middle

If mounted: Unmount that partition using the contex menu (right click)

Click the resize button
A dialog will pop up
Resize
Click "Apply" after double checking your changes. That's it.

This will not work with all partitions. It can be more complicated for Mac partitions or logical volumes.
Comment: +1 for the mounted part. If you're trying to shrink the / partition (or something that is essential to be mounted), just boot from a liveCD and then run gparted.
Comment: Er, do you mind dividing the steps into different screenshots? The image is as confusing as your name is.
Comment: Yes, gparted will move the data by itself as long as you don't shrink the partition to a size that's too small for it.
Concerning the 'confusing' bit: The numbers in the pictures correspond to those in the text.
As for the unbootable bit: What partition do you resize?
Comment: Wait, now that I read the whole thing, just doing the usual shrinking will be fine? It will move the data by itself?
Comment: It gave me a warning that it could rendered unbootable...
Comment: @Oxwivi Still having problems? If you enter the [general chat](http://chat.stackexchange.com/rooms/201/ask-ubuntu-general-room) someone might help you.
Comment: The overlapping lines is the what would confuse anyone. Anyway, I'll report back if I can't actually boot from it.
Comment: Since you didn't report back, I assume everything went well. Care to accept my answer then?
Comment: @conf-use your picture makes me to confuse.
Comment: +1 for Fresh Prince of Bel-Air too, that was amazing.
Answer: I was not able to shrink my partition only by using gparted. Instead, I had to first resize the filesystem with resize2fs:
resize2fs /dev/sdx# 50G

After that, I could shrink the partition with gparted without any problems or loss of data.
Note: resize a partition only, not your whole disk. So for example, instead of choosing sda, choose sda1.
Note: you might have to run e2fsck -f /dev/sdx# first.
Comment: Apparently parted lost the ability to do FS resizes in 3.0, partially regained it in 3.1 and then lost it for real in 3.2: https://unix.stackexchange.com/questions/169395/how-do-i-resize-partitions-and-filesystems-on-them

Shrink a partition without losing data


Refactor the if...else block to use a ternary operator

Question: My answer is not working according to the code challenge specifications.

let favoritePhrase = 'Love That!';

 if (favoritePhrase === 'Love That!') {
   console.log('I love that!');
 } else {
   console.log("I don't love that!");
 }

// My refactored code  below
favoritePhrase ? console.log('I love that!') : console.log("I don't love that!");

Answer: You need to check the value of favoritePhrase:
favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");

In your code, favoritePhrase ? was evaluating to true because it is a non-falsy value.
Answer: In your example you are just checking if favoritePhrase is not falsy. You want to check if it is equal to 'Love That!'.
favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");

Answer: In the ternary operator you are just checking if the variable evaluates to true, and not if it is equal to Love That!... so you need to switch from:
favoritePhrase ? console.log('I love that!') : console.log("I don't love that!");

to
favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");

Answer: you forgot to check if the value is equal to 'I Love that'
(favoritePhrase === 'Love That!') ? console.log('I love that!') : console.log("I don't love that!");

Answer: The real use for a conditional (ternary) operator ?: is to return an expression, like the wanted string.

let favoritePhrase = 'Love That!';

console.log(favoritePhrase === 'Love That!'
    ? 'I love that!'
    : "I don't love that!"
);


Weird Error message in Xcode

Question: I have a program that I am trying to make, and so far things seem to be going well. I've been busy debugging a certain chunk of code, and it works fine in the debugger. The problem, however, is that the program still crashes. When I go through the debugger window, it looks like it's something outside of my own code. The error message is:
<code>Unable to disassemble dyld_stub_writev
</code>
That's what I see when I look at the console. I've tried to do a search on this, but I seriously got no results. Does anyone have any idea what this error message means?
Answer: Nevermind, solved it. Turns out I wasn't releasing an NSArray right, so I just set it up as a property in the header file, and it works now.

Weird Error message in Xcode


Simplifying fractional exponents

Question: I am very confused about the following:

whenever I put in into wolfram alpha the answer it gives me is "indeterminate", is it not possible to simplify fractional exponents or something? if the exponent is 2/6 can i simplify it to 1/3 and get -1 as the answer? Provided I'm working with real numbers.
What I put in wolfram alpha was "(-1)^(1/3) real numbers" to which it answered "-1", then when I tried "(-1)^(2/6) real numbers" it answered "indeterminate".
Comment: If you square first you get all the $6^{th}$ roots of $1$ including $1$.
Comment: See http://math.stackexchange.com/questions/956541/what-is-8-frac23
Comment: @labbhattacharjee ok, so, then why does wolfram say "indeterminate" for (-1)^(2/6) and "-1" for (-1)^(1/3)? Keep in mind that I'm talking about real numbers!
Comment: @paulpaul1076, http://www.wolframalpha.com/input/?i=%28-1%29^{\frac26}  and http://www.wolframalpha.com/input/?i=%28-1%29^{\frac13}
Comment: @labbhattacharjee once again, I am talking about real numbers! add "real numbers" to what you wrote and you get "indeterminate" for "2/6" exponent and "-1" for "1/3" exponent, also I edited my question
Answer: I figured it out, apparently wolfram first takes the 6th root of -1 and since (-1)^(1/6) is indeterminate since we're dealing with real numbers and can't take an even root of a negative number, it says "indeterminate".
Also, Rory's first solution is absolutely wrong (unless he corrects if when you see this), because we can't take a root of a real negative number raised to a power greater than 1, if what he wrote were true I can then prove that -1 = 1 like so: -1 = (-1)^(1/3) = (-1)^(2/6) = (1)^(1/6) = 1.
Answer: The usual definition (used in high schools) of $x^{a/b}$ is $\sqrt[b]{x^a}$. Therefore, your expression $(-1)^{2/6}$ could mean either:
$$(-1)^{2/6}=\sqrt[6]{(-1)^2}=\sqrt[6]{1}=1$$ or
$$(-1)^{2/6}=(-1)^{1/3}=\sqrt[3]{(-1)^1}=\sqrt[3]{-1}=-1$$
That seems pretty indeterminate to me!
You could complain that it is obvious that the fraction $2/6$ should be simplified before applying the definition of a rational power, but it apparently is not obvious to Wolfram Alpha. Wolfram does not know you or your particular definition, it could be argued that Wolfram took the correct approach.
Comment: Then why does it not answer "1" instead of "indeterminate"?
Comment: Because there are two obvious ways of calculating the answer, and those give different answers. If you asked *me* which answer were correct, I would choose $-1$. So $1$ is not at all the obvious correct answer. I made a slight edit to my answer that might help.
Comment: Yeah, I got it and posted my own answer, thanks.
Comment: Also it's indeterminate not because it can take 2 approaches but because the answer to (-1)^(1/6) is unknown, as i said in my post
Comment: I have actually talked about this with someone, and he said that expression x^(a/b) = b roots from x^a is only valid when x is not negative, so your first solution is incorrect

Simplifying fractional exponents


Who's the right person to hire for exterior door repair?

Question: I have an old(ish) house with a door that no longer seals tight against the frame. This is the door between my house and my uninsulated garage, so it's effectively an external door. (Also, it's probably not up to code.)

I've decided that this is not something I'll be able to fix myself; I want to hire someone who knows what they're doing. But who's the right person to hire for this - a handyman? a general contractor? something else? (This is in the USA.)
Thanks!
edit: I should clarify - I'm not struggling to find someone to do the work. I'm struggling to know which job title to start Googling in order to find someone to do the work.
Comment: Your neighbours/friends will probably know a decent person who is handy or a local contractor.   If just wanting better sealing, can probably just buy weather stripping at a local store.  A better door frame and/or door is a bit bigger job.
Comment: Have a guess as to which became out of shape: door or frame … get a new door made / fitted.
Comment: In the US, these people are called carpenters.  They are very very VERY hard to find.  For some reason, the pay just isn't as good as being an electrician, plumber, or HVAC tech, so people give it up and move on.
Comment: Do the other door while you're at it, with one that doesn't have a glass pane next to the handle. I don't need the combo to that key box; I could open that door with my fist.
Answer: That door could be repaired by handyman, but for the cost of that, you could get new pre-hung door (frame and door) that is also an outside door.
Looking at your door it is in a sad state (Lots of repairs needed.). Also the door threshold needs to be replaced.
New door will fix all you current problems and resist weather elements.
I recommend Fiberglass door or even steel with self closing hinges.
Get a handyman estimate for the repairs the alignment, new weather strips and threshold replacement, and compare that to the new door.
New door install can also be accomplished by same handyman, and they come with new threshold.
I get my handyman from Angi.com or from Handy.com
Comment: A steel door will be more likely to meet the fire resistance code for a door between the garage and living space and can be nicely insulated. It might not come with a self-closing hinge, but that can be easily retrofit.
Answer: A carpenter, handyperson, or home repair specialist should all be able to handle that type of work. It's not something that requires any particular credentials or certifications. It's a matter of knowledge and good craftspersonship.
I see several repairs needing to be made:

The door is sagging (or the wall has shifted). See how the gaps aren't uniform? They should be uniform and appropriately sized. The door jamb may need to be re-hung or just adjusted with some strategically placed screws, hidden behind hinges.
Weatherstripping should be retrofitted. This doesn't look like it was intended to be an exterior door, but if it's sheltered from rain and some seals are applied it could do.
A proper exterior threshold should be installed. While this door has a threshold, there's no bottom seal. It can work to simply install a sweep seal, but that's not ideal.
Some aesthetic repairs could be made. It's difficult to repair veneer damaged to that extent, but a partial or full overlay could bring it back to beauty.


Predict network interfaces names in Wily/Xenial

Question: I usually install systems with debootstrap. As part of the script, I add the interface eth0 to /etc/network/interfaces.
But with Wily changing to persistent network interfaces, this doesn't work anymore, since, while it may be persistent, the name is also unpredictable (e.g. something like enp0s3).
How should I adjust? Is there any way to know what the interface name will be? To deactivate persistent names? Or is the only solution to defer that configuration to the first boot, for instance by using a systemd oneshot service?
Answer: Yes, in my opinion, this stuff is a little inconsistent.
I now use the following line in grub:
GRUB_CMDLINE_LINUX_DEFAULT="net.ifnames=1 biosdevname=0"

and things are the way they used to be (although I haven't tried it in Wily). See also.
Comment: Seems it does not work on Wily.


HTTP request via proxy on AWS server fails with 407

Question: I'm running this brief script locally as well on an AWS EC2 intance in an ECS cluster:
<code> import requests
 proxies = {'http':'http://user:pw@host:port','https':'http://user:pw@host:port'}
 r = requests.get('http://quotes.toscrape.com/', proxies=proxies)
 print r.status_code
</code>
When I run the script locally, I get a 200 status code, indicating that I successfully am able to connect to access the website via the proxy.
When I run the script on the AWS instance, I get a 407 proxy authentication error.
This is a common error that others have experienced (e.g. see here). I'm looking for a solution that allows me to authenticate the proxies WITHOUT having to whitelist the instance.
The reason being is that every time I run a new instance, I'd have to whitelist that instance too. I would rather just pass in the credentials to requests and authenticate the proxy directly.
Is this possible?
Answer: I would suggest you launch instances in the private subnet, and whitelist your NAT(s) EIP in this case you will only have to whitelist 1-4 IP addresses depending if you are using single NAT or a NAT per AZ (which is recommended).
Hopefully, it does make sense, feel free to ask additional questions


Sticky Navigation and mobile responsive

Question: I am trying to use Sticky Navigation like this:  https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_navbar_sticky
but also make it mobile response like this: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_topnav
Thank you in advance for your reply...

function myFunction() {
  var x = document.getElementById("myTopnav");
  if (x.className === "topnav") {
    x.className += " responsive";
  } else {
    x.className = "topnav";
  }
}

function myFunction2() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
body {
  margin: 0;
  font-size: 28px;
  font-family: Arial, Helvetica, sans-serif;
}

.header {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

#navbar {
  overflow: hidden;
  background-color: #333;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}

#navbar a.active {
  background-color: #4CAF50;
  color: white;
}

.content {
  padding: 16px;
}

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

.sticky + .content {
  padding-top: 60px;
}

.navbar {
  overflow: hidden;
  background-color: #333;
}

.navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.navbar a:hover {
  background-color: #ddd;
  color: black;
}

.active {
  background-color: #4CAF50;
  color: white;
}

.navbar .icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .navbar a:not(:first-child) {display: none;}
  .navbar a.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  .navbar.responsive {position: relative;}
  .navbar.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .navbar.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
}
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Scroll Down

Scroll down to see the sticky effect.

  Home
  News
  Contact

Sticky Navigation Example

The navbar will stick to the top when you reach its scroll position.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Comment: what is your question?
Answer: You can do this simply using jquery, see below code.
Took offset of the div till navbar need to be static, then it will be sticky.

var fixmeTop = $('div#mynavbar').offset().top;
$(window).scroll(function(){
  var currentScroll = $(window).scrollTop(); // get current position

    if (currentScroll >= fixmeTop) {       // apply position: fixed if you
        $('div#mynavbar').css({         // scroll to that element or below it
            position: 'fixed',
            top: '0',
            left: '0'
        });
    } else {                                   // apply position: static
        $('div#mynavbar').css({          // if you scroll above it
            position: 'static'
        });
    }
});
body {
  margin: 0;
  font-size: 28px;
  font-family: Arial, Helvetica, sans-serif;
}

.header {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

#navbar {
  overflow: hidden;
  background-color: #333;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}

#navbar a.active {
  background-color: #4CAF50;
  color: white;
}

.content {
  padding: 16px;
}

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

.sticky + .content {
  padding-top: 60px;
}

.navbar {
  overflow: hidden;
  background-color: #333;
}

.navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.navbar a:hover {
  background-color: #ddd;
  color: black;
}

.active {
  background-color: #4CAF50;
  color: white;
}

.navbar .icon {
  display: none;
}
div#mynavbar {
  width: 100%;
}
@media screen and (max-width: 600px) {
  .navbar a:not(:first-child):not(:last-child) {display: none;}
  .navbar a.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  .navbar.responsive {position: relative;}
  .navbar.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .navbar.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
}

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Scroll Down

Scroll down to see the sticky effect.

  Home
  News
  Contact

Sticky Navigation Example

The navbar will stick to the top when you reach its scroll position.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.

Comment: This does make it sticky, but the menu is not responsive responsive like https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_topnav
Comment: Added css for max-width:600px; bars icon display block, included font-awesome library that you used. Check now...
Comment: Thank you  ElusiveCoder
Comment: I got this error... {
  "message": "Uncaught ReferenceError: myFunction is not defined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 131,
  "colno": 71
}

Sticky Navigation and mobile responsive


Meaning of 1-digit base 100 number in RSA Cryptosystem

Question:

Explani the RSA cryptosystem by showing coding and decoding of the word Birthday if the public key is known to be $(101, 3)$. Consider each alphabet as 1-digit base 100-number.

I know how to code it. Only I want to ask what is the meaning of $\textbf{ Consider each alphabet as 1-digit base 100-number}$.
Answer: It's not a standard terminology. I suspect the author actually missed some words and meant "consider each letter of the alphabet ..." though that's still far from a standard way to phrase things.
My best guess is that they're encoding each letter as a number between 0 and 100, probably with the scheme
<code>A - 1
B - 2
C - 3
D - 4
....
</code>
and then encrypting each letter separately.
(This is a rather bad way of using RSA -- in addition to the brute-forcing opportunity inherent in only having 26 different messages, there's the fact that the number 1 always encrypts to itself. Check if your source material defines a concrete coding somewhere else).
Comment: Thanks for your prompt reply.If we replace 100 by 10, then what change we will see in these alphabets.
Comment: @Struggler: I'm not sure I understand that question. What do you imagine  happens to your public key if you "replace 100 by 10"? It wouldn't do to make it $(11,3)$, because $11$ is not a product of two primes.


Are new "low noise" whole house fans actually quieter?

Question: I've dealt with a number of older whole house fans (10 years and older) and the one thing they all had in common was a ton of noise.
Are the new "low noise" fans actually that much quieter than the old fans, and should one expect a premium price for a quiet whole house fan?
Are there installation tricks/techniques that will help reduce noise even further?
Answer: Noise should be a main concern when shopping for a whole house fan, because the hours while you are sleeping offer the coolest temperatures of the day. More important than simply exchanging the air, the cooling of the thermal mass of the structure down to the core simply takes time. Unfortunately, you can not wring all of the heat out of the thermal mass like a sponge - it just takes time - and a bit of stady, constant airflow. In this way, Running a fan overnight while you are sleeping will take advantage of these cooler temperatures, making your fan more effective on more days of the year, and reducing your need for A/C to a minimum.
Some manufacturers have incorporated ECM (electronically commutated motor) technology  into whole house fans. This not only delivers AMAZING efficiency numbers, but the brushless motor design also offers extremely low noise levels.
With older, brushed motors, turning them down to a lower speed using a rheostat can reduce the noise level slightly, but you will notice that the power consumption stays roughly the same. On the other hand, ECM technology allows you to not have to trade efficiency for noise level, and you can actually maximize efficiency while minimizing noise level.
Whole house fans + ECM motors = A perfect combination for quiet, effective, efficient natural cooling.
They may cost a bit more, but considering the outstanding efficiency numbers and low noise levels, a modern whole house fan (especially those using an ECM motor) is definitely a worthwhile investment.
Cheaper whole house fans are too noisy that they in many cases go unused, or they are turned off too early in the evening, before it has really cooled off outside.
Answer: I finally installed one, and following a tip on a review left on Amazon.com, I built a box larger than the fan, then put pipe insulation around the bottom edge of the fan.  Slipping the fan into the box I built causes the fan to rest on the pipe insulation, reducing the vibration transmitted from the fan to the rafters to a minimum.  It doesn't reduce the noise of the air flow, but I'm getting 80dB directly below the fan, and 50dB in the bedrooms, which is fantastic compared to other house fans I've known.
Still too loud to comfortably talk beneath for extended periods of time, but not a jet engine roar either.
If I wanted to reduce the sound further I'd probably use ductwork to move the fan further away in the attic, but I'm satisfied with this.  The house is normally 40-45dB during the day, so 50dB in the rest of the house is fine.
If you choose to follow this technique, make sure you leave room for your shutters to open when you build your box.  I didn't do a fit test before moving everything to the ceiling, and it's significantly harder to rework the box in the ceiling than it would have been on the ground.

Also, I highly recommend installing a timer switch for the fan.  It was easy to install, and now we don't have to think about turning the fan off, just press one of the buttons for the length of time desired and forget about it.
Answer: In the ~7 years since this was asked, an obvious-but-new concept emerged that has made whole-house-fans even quieter. The ECM motors from greenhead's answer are getting more common, but now companies are offering mounts that suspend the actual motor and fan a bit away from the intake like shown:

This not only moves the fan several feet away from the intake below, but also reduces much of the vibration to near zero because it's suspended.
So yes, new fans have gotten much more efficient and much quieter.
Answer: I can't speak to how much better the "low noise" fans are than the old ones, but I have an old one and really don't notice the noise much.
The location of the installation is key here.  In my case, the fan is on the second floor at the end of a hallway where all the bedrooms are.  While it is loud if you are in that hallway, you can really barely hear it through the rest of the house.  So as long as you tuck it into an out-of-the-way corner of the house, the noise isn't really that much of a concern.