Login cognito using with scope openId using id_token or access_token don't working

Question: I'm using cognito to authenticate to node-js using amazon-cognito-identity-js I logged in and it returns me an access_token, id_token and refresh_token but none of them work when I'm using the open id scope with authorization code grant.

I don't know if I need to call another service or do another process to get access at the gateway
but when I generate a token using client_credentials flow the api gateway works
Comment: The header should look like "Authorization: Bearer ". From the screenshot, it looks like the "Bearer " prefix is missing.
Comment: so, even with or without a bearer it somehow works
Answer: If I understood correctly, the scopes you are setting are OAuth 2.0 scopes and require using the OAuth 2.0 endpoints (e.g. the hosted UI, or an external IdP federation). Your code seems to be using the non OAuth 2.0 flow (e.g. I assume InitiateAuth with SRP). If you decode the JWT I believe you will see it has only the aws.cognito.signin.user.admin scope.
For using custom scopes you will need to

send the access token (not the id token)
use token you got from the token endpoint (e.g. using the hosted UI or federation) - they will contain the scopes you set in the screenshot

For using the open_id scope, same as above but send the id token, not the access token, and remove the custom OAuth scopes in API Gateway (if you put them it will expect an access token)
p.s. custom scopes work great with the client credentials flow, but less with the authorization code flow if it doesn't have a client secret.
Lastly I recommend you take a look at AWS Amplify as it will handle a lot of that for you behind the scenes as well as include security features such as PKCE out of the box.
Relevant github issue: https://github.com/aws-amplify/amplify-js/issues/3732
Comment: I understand, I could get the access token with custom scopes using amazon-cognito-identity-js because I'm using the server-side cognito with node.js according to the print. I disabled oauth scopes from the api gateway and using id_token it works. but, it is not the most recommended to be doing


Nuxt and i18n: Google showing mixed language results

Question: I've made a site using Nuxt.
The site has 2 languages: Italian (default) and English for everyone else.
I installed nuxt-i18n and configured it, and everything seems to work fine (especially when looking at the code with the devtools, html lang, rel=alternate and so on..).
But here's the problem: when i search for the site with google (in italian), the snippet for the site in the SERP is in english.
Here's my code:
    ['nuxt-i18n', {
      seo: false,
      baseUrl: 'https://www.leconturbanti.it',
      locales: [
        {
          name: 'Italiano',
          code: 'it',
          iso: 'it-IT',
          file: 'it-IT.js'
        },
        {
          name: 'English',
          code: 'en',
          iso: 'en-US',
          file: 'en-US.js'
        },
      ],
      pages: {
        'contatti/index': {
          it: '/contatti',
          en: '/contact-us'
        },
        'illustrazioni-collezione/index': {
          it: '/illustrazioni-collezione',
          en: '/illustrations-capsule'
        }
      },
      langDir: 'lang/',
      parsePages: false,
      defaultLocale: 'it',
      lazy: true
    }]

I set seo: false for better performance as explained in the docs, and merge the data in the default layout:
    head(){
      return{
        script:[
          {type: `text/javascript`, innerHTML: this.$t('policy.cookieId')},
          {src: `//cdn.iubenda.com/cs/iubenda_cs.js`, charset: `UTF-8`, type: `text/javascript`}
        ],
        __dangerouslyDisableSanitizers: ['script'],
        ...this.$nuxtI18nSeo()
      }
    },

I also set the meta tags for every page with $t in the head(). For example, in home:
    head(){
      return{
        title: this.$t('seo.home.title'),
        meta: [
          { hid: 'description', name: 'description', content: this.$t('seo.home.description')},
          { hid: 'og:title', property: 'og:title', content: this.$t('seo.home.title') },
          { hid: 'og:url', property: 'og:url', content: this.$t('seo.home.url') },
          { hid: 'twitter:title', property: 'twitter:title', content: this.$t('seo.home.title') },
          { hid: 'og:description', property: 'og:description', content: this.$t('seo.home.description') },
          { hid: 'twitter:description', property: 'twitter:description', content: this.$t('seo.home.description') },
        ]
      }
    },

I can't understand what i did wrong. I already added the site in Search Console. If you need to visit it for inspection, the url is: www.leconturbanti.it
If you need more of my code in order to answer just ask.
Thank you.
Comment: Yes, i posted an answer. Give a look.
Comment: Any luck with this? Running into the same issue..
Answer: Found out that this issue is from nuxt-i18n itself.
The problem is that the Google Crawler will fallback to the english version of a page, and this not good if you have another locale as default.
More here.
For now, until the problem is solved, the workaround I used is to disable the auto detect language to avoid the redirect with detectBrowserLanguage: false.
Comment: You know, I kinda figured this was the issue but I didn't want to mess with SEO rankings trying to fix it. Thanks for confirming!
Answer: My nuxt page head:
head(){
    return {
      ...this.$nuxtI18nHead({ addDirAttribute: true, addSeoAttributes: true }),
      title: this.page.title,
      meta: [
        {
          property: 'og:description',
          name: 'description',
          content: this.page.description
        },
        {
          property: 'og:title',
          name: 'title',
          content: this.page.title
        }
      ],
    }
  },

My nuxt.config.js
i18n: {
    locales ,
    strategy: 'prefix',//no_prefix , prefix , prefix_and_default ,prefix_except_default
    vueI18nLoader: true,
    defaultLocale: process.env.LOCALE_DEFAULT||'en',
    langDir: '~/locales/',
    vueI18n: {
      silentTranslationWarn: true
    },
    detectBrowserLanguage: false
  },


How do I scrape the starting pitchers and import to excel?

Question: How do I scrape the starting pitchers and import to excel?
Here is my code so far.
from urllib.request import urlopen
from lxml import html

response = urlopen("https://www.baseball-reference.com/previews/index.shtml")
content = response.read()
tree = html.fromstring(content)

Answer: I'll get you started. First you want to use cssselect unless you like xpath:
import cssselect

Then you just figure out the css for the things you want to iterate:
for div in tree.cssselect('.game_summaries'):
  for a in div.cssselect('table:nth-child(2) a'):
    print(a.text)

You can find the css from the elements inspector of your browser (chrome is best).
Comment: @JakeWest If the answer helped, you can mark the answer as "accepted" by clicking the checkmark under the vote buttons.
Comment: No, you're going to need all of them.
Comment: @pguardiario... Can I remove any of my lines of code?


How to access the user object in the form configure method

Question: I'm currently doing this kind fo thing with symfony forms
<code>$this->myForm = new MyForm();
$this->myForm->customConfigureMethod($this->getUser()->getGuardUser());
</code>
because I need to configure a DoctriineChoice widget on the basis of the user.
I would rather do this kind of thing
<code>$this->myForm =new myCustomConfiguredForm($this->getUser()->getGuardUser());
</code>
With the customisation being part of the form instantiation.
Anyone know how I could achieve this? I think I might be a bit unclear about the difference between the configure() and setup() functions for the forms so can't think clearly about it.
Answer: You shpuld pass the user object as an option. Here is an exapmle:
<code>class ProductForm extends BaseProductForm
{
  public function configure()
  {
    // or use an instance variable if you need the user in an another method too
    $user = $this->getOption('user');

    if (!$user instanceof sfBasicSecurityUser)
    {
      throw new InvalidArgumentException('A user object is required as "user" option in ' . __METHOD__);
    }

    // do something with the user...
  }

}

$form = new ProductForm(array(), array('user' => $this->getUser()));
</code>


Do fused weapons count for Shadow soldiers' pristine pool?

Question: Shadow soldiers in the Depths spawn with a random weapon in pristine version.
It's pretty well known that you have to find and destroy a decayed version of a weapon in the overworld in order to make it respawn in the Depths as a pristine one.
But I'm wondering:
If I fuse a weapon (that I never broke before) to something else and break it while it's attached to another weapon, does it still count for the Shadow soldiers' pool?
Answer: Apparently yes, days ago I broke a Royal Guard's Claymore which was attached to another weapon.
Recently I found a pristine Royal Guard's Claymore in the Depths.


Sharing calculation result between shader programs in OpenGL

Question: Question
Is there a way to compute something in a first shader program (eg. screen-space coordinates from word-space ones) and access those results in an another shader program?
Possible solutions

Give up multiple-shader-programs architecture and create one combined shader program
Save somehow results to a buffer objects (I couldn't find out if this is possible except computation shaders)
Render to texture and read the texture

Is there a nicer solution?
Answer: Yes you can, this is how deferred rendering for example would work. For that you would render to a texture in one pass, in openGL this would be via an FBO, then feed that texture as the input to the next pass/shader.
Comment: A texture is just a normal buffer, although in the fragment shader we use fancy sampler2D to read it with filtering/etc. You can use a compute shader to read it more in its raw form and skip the texture sampler stage.
Comment: Isn't it a bit restrictive? I mean, IMO, the texture is not the best-suited data storage for passing data in general (but I am new to computer graphics and maybe I have to get used to it).
Comment: There's a few options. Render-to-texture is probably the most straightforward but also kind of wasteful unless you need the results of your calculations in screen-space (like in deferred rendering), since you're rasterizing geometry before you can do any calculation. There's transform feedback, where you pull the output of a vertex or geometry shader before it hits the rasterizer and write it back to a buffer instead, might be good for the use case you mentioned but I haven't tried it myself. Otherwise compute shaders are the way to go, they're not that scary once you get used to them ;-)
Answer: While the other answers are giving possible techniques to achieve what you're looking for, rendering your stuff into a texture is not always the best way if you need it as VBOs (i.e. vertex attributes) in the next render step (requiring either a read into a PBO and some index/coordinate/sizing magic or a vertex texture fetch).
An approach that would more accurately represent your 2nd point and be better when you need a transformation from a buffer into a buffer would be what's called Transform Feedback (or Stream Output in the DirectX world). However, this requires OpenGL 3/DirectX 10 hardware (however, not necessarily the GL4/DX11 needed for compute shaders). It's also a little less of a synchronization mess than compute shaders with arbitrary shader storage buffers when your use case is really just to transform a bunch of vertices/primitives into a nother bunch of vertices/primitives.
It basically lets you hook into the render pipeline after the vertex (or rather primitive) processing step and before the rasterization and write out whatever per-vertex values you computed directly into a buffer object (that you can then use as vertex attributes in the next step). It therefore doesn't draw anything into the framebuffer either. You just specify a bunch of varying/out variables and how to format them into the buffer and bind a buffer to the corresponding binding point. You can also use a query to gather information of how many primtives were written (since a geometry shader could change that dynamically) or, in later versions, just render the results directly without any need for synchronization. For more details, see the above Wiki article.
Together with the geometry shader (which TF hardware should have, too) and its abilities for changing the primtive type or removing/adding vertices, this makes a useful tool for transforming your geometry however you deem fit in preparation of further rendering stages. Of course, it has to be evaluated if that really buys you anything in the particular use-case, especially if you're really just doing a simple vertex transformation.


Why is the effect of layout_weight in View behaves differently from TextView?

Question: I tried to set 3 colored areas in 1:2:3 ratio using TextView:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<TextView
    android:layout_weight="1"
    android:background="#FF0000"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    />
<TextView
    android:layout_weight="2"
    android:background="#00FF00"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    />
<TextView
    android:layout_weight="3"
    android:background="#0000FF"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    />
</LinearLayout>

which has my desired result (screen shot by android studio preview):

but when I change TextView into View:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<View
    android:layout_weight="1"
    android:background="#FF0000"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    />
<View
    android:layout_weight="2"
    android:background="#00FF00"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    />
<View
    android:layout_weight="3"
    android:background="#0000FF"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    />
</LinearLayout>

the layout changes (screen shot by android studio preview):

what is the reason?
Comment: Issue is resolved ?
Answer: You have to try like this
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<View
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:background="#FF0000"/>
<View
    android:layout_weight="2"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:background="#00FF00"  />
<View
    android:layout_weight="3"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:background="#0000FF"/>
</LinearLayout>

Answer: It has got to do with the width. Given that its a horizontal LinearLayout with match parent as the LinearLayout's width, and each of your views(View/TextView) is been given weights, the individual widths of the views are causing the misbehaviour.
If you gave each of the views width to be 0dp, both will behave in the same way
Answer: Replace width with 0dp.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <View
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#FF0000" />

    <View
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:background="#00FF00" />

    <View
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:background="#0000FF" />
</LinearLayout>

Answer: Your parent layout orientation is horizontal, so you can not use layout_width either match_parent, wrap_content or any value other than 0. So why it is giving unwanted result.
For more information, please read Layout Weight section.
<View
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="#FF0000" />

<View
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="2"
    android:background="#00FF00" />

<View
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="3"
    android:background="#0000FF" />


Sorting lua tables by arbitrary values

Question: I have a table with the following structure:
table = {
    [1] = {"something", "high"}
    [2] = {"something else", "low"}
    [3] = {"something further", "medium"},
    [4] = {"yet more something", "medium"},
}

What I want to do, is to use a delegate function to sort that table with table.sort() so that the priority variable (high, low, medium, etc) orders the list with high being followed in the list, followed by medium and then low. How would I go about doing this?
Answer: You seem to know how table.sort works, so where are you stuck?
Simply create a lookup table that translates priority names into integers and compare those:
priorities = {high = 2, medium = 1, low = 0}
table.sort(t, function(e1, e2)
    return priorities[e1[2]] > priorities[e2[2]]
end)

Answer: table.sort(t,
  function(e1, e2)
    return e1[2]:sub(-1) < e2[2]:sub(-1)
  end
)

Comment: @Ephemeralis - Please don't embed my solution into production code :-)
Comment: Funny idea, but quite obscure and inflexible, don't you think?
Comment: I just wanted to add a note of caution, as this is a very compact solution but one that I don't think should go into production code ;)

Sorting lua tables by arbitrary values


Call ASP.NET page method from class file method

Question: I am working on a project(ASP.NET website) where i need to call method in webpage from a class.
///Default Page Method is
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       BLMethods objBLMethods = new BLMethods();
       objBLMethods.BindingDataToControls();
    }

    public void BindGridView(List<clsPerson> objPersonList)
    {
      GridView1.DataSource = objPersonList.ToList();
      GridView1.DataBind();
    }
}

`
class file structure is
    public class BLMethods
    {
        public BLMethods()
        {
          List<clsPerson> objPersonList = new List<clsPerson>();
          clsPerson objPerson = new clsPerson();
          objPerson.personID = i;
          objPerson.personName = "Person" + i;
          objPersonList.Add(objPerson);
          BindGridView(objPersonList);
        }
    }

clsPerson Class:
public class clsPerson
{
    public int personID;
    public string personName;
}

As shown in the above program, I need to call BindGridView method of page from constructor of BLMethods class
Comment: Hi. Wouldn't the last line in the BLMethods ctor throw a compilation error?
Answer: I would do it the other way around. Add the method to the class (with a GridView as an argument):
public class BLMethods
{
    public BLMethods(GridView gv)
    {
      List<clsPerson> objPersonList = new List<clsPerson>();
      clsPerson objPerson = new clsPerson();
      objPerson.personID = i;
      objPerson.personName = "Person" + i;
      objPersonList.Add(objPerson);
      BindGridView(gv,objPersonList);
    }
    private void BindGridView(GridView gv, List<clsPerson> objPersonList)
    {
      gv.DataSource = objPersonList.ToList();
      gv.DataBind();
    }
}

Default Page Method is
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       BLMethods objBLMethods = new BLMethods(GridView1);
       objBLMethods.BindingDataToControls();
    }

}

Try giving getters and setters to your clsPerson class properties:
public class clsPerson
{
    public int personID {get;set;}
    public string personName {get;set;}
}

Comment: When i followed your approach, i'm getting error as, [The data source for GridView with id 'GridView1' did not have any properties or attributes from which to generate columns.  Ensure that your data source has content.]
Comment: @PavanKumar Can we see the clsPerson class?
Comment: public class clsPerson
        {
           public int personID;
           public string personName;
        }
Answer: You should be returning only data from business rule class and bind  grid view in the code behind class.
you can make method in the class which will return the List<clsPerson> and on page load bind it with your girdview:
public class BLMethods
    {
        public BLMethods()
        {

        }

        public List<clsPerson> GetPersons()
        {
          List<clsPerson> objPersonList = new List<clsPerson>();
          clsPerson objPerson = new clsPerson();
          objPerson.personID = i;
          objPerson.personName = "Person" + i;
          objPersonList.Add(objPerson);

          return objPersonList ;
        }
    }

and in code behind of page:
protected void Page_Load(object sender, EventArgs e)
    {
       BindGridView();
    }

    public void BindGridView()
    {
      BLMethods objBLMethods = new BLMethods();
      GridView1.DataSource = objBLMethods.GetPersons();
      GridView1.DataBind();
    }

Comment: Here in BLMethods i need to check for authorization of user and if he is valid, I need to call BindGridView or navigate to Error page
Comment: for checking autorization why not use forms authentication
Comment: We are using DataBase for authorization, by sending username, password, pagename to the procedure, we get a response object
Comment: @PavanKumar - Your class is doing too many things.  Have a separate class that deals with authentication and perform that check and redirect based on the result from there.  Then have your person class just return the data based on the user.  Don't try to pull your front end code into your back end.
Comment: @Paddy. The concept you explained is unclear to me. Can you explain me with the above code that i mentioned.
Comment: you can call that on page load to check if user is authorized then continue else redirect
Answer: You should look to separate your concerns correctly.  Based on comments and queries from Ehsan Sajjad's answer:
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       if (!new AuthenticationHelper().IsUserAuthorisedForPeople(Request.User.Identity))
       {
           Response.Redirect("NaughtyNaughty.aspx");
       }

       BindGridView();
    }

    public void BindGridView()
    {
      PersonHelper helper = new PersonHelper();
      GridView1.DataSource = helper.GetPeople();
      GridView1.DataBind();
    }
}

public class AuthenticationHelper()
{
     public bool IsUserAuthorisedForPeople(string userName) {
        return true; //Do your auth here.
     }
}

public class PersonHelper
{

    private void GetPeople()
    {
      List<clsPerson> objPersonList = new List<clsPerson>();

      //Populate your list of people.

      return objPersonList;
      //BTW - hungarian notation for your naming is just going to make your
      //code look cluttered...
    }
}

Answer: You have to work other way around. You write the method in BL that returns the objPersonList call it from your page to bind.
Comment: When i followed your approach, i'm getting error as, [The data source for GridView with id 'GridView1' did not have any properties or attributes from which to generate columns. Ensure that your data source has content.]


Decrease/increase for loop

Question: I have a component like so:
...
const STARTING_OPACITY = 0.3;
const STARTING_HEIGHT = ageVariable === 5 ? 70 : 20;
const opacityInterval = (1 - STARTING_OPACITY) / yearlyContr;
const heightInterval = (100 - STARTING_HEIGHT) / yearlyContr;
...

...
return (
    columns.map(
        (column, i) => {
            return(
                <Column height={STARTING_HEIGHT + (heightInterval * getBarsHeight(columns))}  key={`id-${i}`}>
                    <MonthlyContribution>£{column}</MonthlyContribution>
                    <ProgressionBar
                        opacity={((STARTING_OPACITY + (opacityInterval * i)))}
                    />
                    <AgeContainer>{age + (i * ageVariable)}</AgeContainer>
                </Column>
            );
        }
    )
);
...

and the key function is:
const isDecreasing = (firstPayment, secondPayment) => firstPayment > secondPayment;

let heightVariable;

const getBarsHeight = arr => {
    const getIsDecreasing = isDecreasing(arr[0], arr[1]);
    const arrLength = arr.length;

    if (getIsDecreasing) {
        for (let i = arrLength; i >= 0; i--) {
            heightVariable = i;
        }
    }
    else {
        for (let i = 0; i < arrLength; i++) {
            heightVariable = i;
        }
    }

    return heightVariable;
}

What I am trying to achieve is that if I have an array like so:
[1,2,3]

the height prop on the column component will increase gradually or viceversa if the array is like so:
[3,2,1]

at the moment I am always getting the same height prop value.
Comment: You are passing the variable `columns` to `getBarsHeight` every time, so of course it always returns the same value because `columns` doesn't change between the different loops.
Comment: Also, you are essentially just returning the last value of `i` so your height will always be either the array's length-1 or 0 depending on whether it is incresing or not. So the loop is not nescesary
Answer: getBarsHeight needs to be aware of the index to provide different value for different indexes => getBarsHeight(columns, i):
const getBarsHeight = (arr, i) => {
  const isDecreasing = arr[0] > arr[1]
  return isDecreasing ? arr.length - i : i + 1
}

Decrease/increase for loop


Why do my rooms heat to different temperatures?

Question: Any advise would be appreciated.
We moved into a 30-year-old home and this is our first winter and we've noticed that some of the rooms are colder than the others but none of the rooms are actually at our set temperature.
We set our thermostat to 72 and I've attached a picture of the layout and temperatures in each room.
The room that has the thermostat in it faces east, but I've never seen direct sunlight hit the thermostat. And that room its self never seems to make it to the set point.

We're worried that this could be an issue with our HVAC since no rooms in the house actually make it to 72, 68/70 is actually our preferred setting. Our realtor said that the HVAC was old and that we would likely need to replace it in a few years. But we're wondering if there could be another issue.
I've attempted to play around with the dampers and in doing so I can make all of the rooms upstairs warmer but the problem rooms still don't hit 68/70 and I had to set the thermostat at 74 to get most of the house around 68/70 and by doing that the master upstairs becomes horribly cold.
Could this be a damper issue and I'm just not setting them right? Or is it something else because there aren't actually any rooms that are hotter than I want them to be.
I was reading about boosters for specific rooms but I'm worried that adding them will make other rooms colder.
I was also wondering how complicated and expensive it is to move the thermostat to another colder room upstairs and if that would help.
Thank you for your time.
Comment: Are you saying that the thermostat deactivates the furnace at a temperature lower than it's set to? Does the thermostat read the set temp when it shuts off the furnace? What are you using to measure the air temps? Are you sure that it's more accurate than the thermostat?
Comment: The thermostat thinks its deactivating at 72, at least it says its a 72. I've used both a heat gun (not pointed at the walls that face the outside) and I've used mercury thermometers placed in water that was allowed to sit in in the center of rooms for 24hrs to take on that rooms temperature. Both the heat gun and mercury thermometers agree. The colder rooms also feel a whole lot colder.
Comment: Also, when measuring the temps, where in the room are you temping. Air or surface? High or low? If you have a way to confirm that the thermostat is correct, then make sure that it and you probe you are using are calibrated the same. If you have a thermostat that you can remove from the wall, and still show current temp, do so and place it and your probe together in the coldest room side by side, let them settle and check the temps on both from time to time. After an hour or so they should have settled enough to determine accuracy or a difference between the 2.
Comment: Hi Jeff - I've been pointing the heat run as center as I can and at the air. The thermometers in the water cup was placed as center as it could be in the room both in height and distance.
Comment: My main concern isn't that I can't get the thermostat to match actual temperature in the house, if I have to set the thing at 76 and all of the rooms are then actually 68, I'm fine with that. I just need the bedrooms upstairs to be at a nice temperature without making the rest of the house cold.
Comment: I would try to see if you can remove the thermostat, if not, place a glass of water above, below and beside the thermostat if possible. Heat rises and cold sinks!! What you want is to determine the actual temp around the thermostat. If it is several degrees off, then its the problem. Is it a digital thermostat or old mercury switch? If mercury, then it is possible that it could have accumulated enough dust on the  to weigh it down.
Comment: Hi Jeff - its a digital nest thermostat that we installed when we got the house but we didn't upgrade anything else. I will see if I can remove it tonight. Thank you for your help!
Comment: If it is a matter of balancing the temps in all the rooms, then you need to adjust the dampers in each room. Open all of them completely. Run the thermostat to 80. Once it shuts off, temp your rooms then adjust the dampers in each room accordingly. Its a balancing act. In my house I have 1 room we don't use except when we have guests, so it is closed all year round unless we have guests. 1 bathroom is closed mostly off because they are smaller rooms, get hot faster, and it has supplemental heat available. Our kitchen is closed about 3/4 and our living room has 2 fully open vents.
Comment: Hi Jeff - we did something like that when we started playing around with the dampers. We were never told which damper belonged to which room (they're located in a crawl space) so we shut and turned them on one at a time to see what rooms they controlled with our thermostat set around 85.
Comment: The problem was there didn't seem to a be a 1:1 correlation. There are 8 total dampers one controls half of the downstairs and upstairs and the others seem to control blocks of rooms that don't fit together on my hot and cold chart. For example one of the dampers controls bedroom #2 the coldest and the one of the kitchen vents the hottest room.
Comment: Related: https://nest.com/support/article/Why-does-the-temperature-Nest-detects-seem-different-than-my-old-thermostat
Comment: Get an instant read thermometer, like a meat thermometer for use in the kitchen, and turn it on with the probe in the air for a few minutes. That'll be much more accurate than a thermometer in a glass of water, as water tends to hold / release heat slowly. I suspect you'll find that, at the thermostat at least, the dining room *does* get to 72F.
Answer: I think two things will resolve 95% of your problem. Get a new thermostat (I like my Nest), and adjust your vent dampers seasonally and to suit your space usage.
Your thermostat apparently has issues with temperature, and a modern "smart" thermostat offers many benefits. One is the ability to run a fan outside of the normal heating/cooling cycles to equalize temperature in your rooms.
The variance between rooms isn't particularly concerning. Solar gain, airflow differences, human activity, and other factors can explain that. The highest temps are seen where cooking and bathing tend to introduce heat. Tweak your vents and see where that gets you. Be sure to look at the returns, too. They're critical to proper air movement.
Replacing your furnace won't do much unless you spring for multiple zones or automatic vent controls. That's probably not a practical approach for cost reasons.
Comment: Hi isherwood - we have a Nest, we installed it when we got the house but didn't upgrade anything else. But we have not tried to run a fan outside of when the heater is on. I can try to turn that on now. How do I check the air returns?
Comment: Look to see that they're not obstructed by furniture. Feel to be sure they're flowing as expected.
Comment: They're not obstructed by furniture and I know that some of them feel more powerful than others but air is moving out of all of them. Is this is a cause where a booster could help some of the rooms?
Comment: Boosters are rarely needed. Pseudo-boosting occurs when you restrict other outlets.
Answer: The thermostat placement really won't help in this case because if you put it in a cold room all the rest will be warm. With a 2 story home there should be at least 2 dampers for a central forced air system. One damper for the up stairs and one for down stairs, if everything was perfect all you would need to do is adjust the 2 dampers 2x4 per year for the heating season the lower floor is opened further than the upper floor and for the cooling season the upper floor will me opened more, now since everything is not perfect each room may require some small adjustments to the vents in each room. This may take quite a few adjustment cycles to figure it out for the first season you do this but once all the rooms are balanced both upstairs and down mark the damper and vent position. If you think your thermostat is off 2 degrees calibrate it or just know it is different than other measurement methods but once all rooms are balanced they should stay that way until the change from heating to cooling, wilt my last home I was able to reverse the summer winter damper settings for example if winter the downstairs was 80% open and the upstairs 60% open for winter I adjusted downstairs at 60% open and upstairs at 80, after that I had 2 upstairs rooms that got hammered by sunshine so those vents needed to be opened , that's all I did and all the rooms in that house were balanced or at the same tempature when measured with a fine wire thermocouple probe & meter. Did I ever compare the reading on my probe and thermostat no it is not import and if the rooms are balanced and you are cold turn the temp up it really dosent matter what the display shows. With 2 possible main dampers and 6 smaller ones a hand held an annometer may be needed to see the pressure change effect of opening and closing a duct.
Comment: We found 8 dampers in our crawl space. Two of them have the handles and   the rest are the screw type with the wings. We have no idea what damper controls which room(s). Last weekend we closed all of the dampers and opened them one at a time with the temp set at 85 and we tried to figure out which damper went where but it wasn't super clear. They seem to control blocks of rooms but one of the vents was on the entire time. Some barely seemed to have air flowing out of them. Is there a better way to figure out which damper controls what? Thank you for taking the time to help me
Comment: I would just turn 1 off at a time , some dampers. In ducts are to adjust the flow not totally block it as totally blocking all of them could blow the ducts apart. I would have someone at the damper and open and close while a second person is checking the rooms to feel the difference in flow. I use cheap walkie talkie when we are troubleshooting out of site. I would expect half to go upstairs and half downstairs. There should be at least 1 large or several small return ducts on each floor these are not normally dampered but I have seen them. Check flow With fan running heat is not needed.


How does elasticsearch find escaped character or reserved character correctly?

Question: Given that I have a string such as 'message-ID: 1394.00 This is Henry.Lin',
I want to use elasticsearch to find all the phrase or word contains '.'. In this case, 1394.00 and Henry.Lin are the words I am looking for. However, when I index my document with standard analyzer is not working. I understand that standard analyzer will escape such character. Therefore, I change the analyzer to ngram. Unfortunately, it is still not working. It would be great if someone can help me out.
Answer: You can add a custom character filter for dot. Replace "." with "dot". Just use the custom mapping like this:
<code>"char_filter": {
"&_to_and": {
    "type":       "mapping",
    "mappings": [ ".=>dot"]
}}
</code>
Please check this documentation for more details.
Now about, why ngram is not working ?
The question is how are you using ngram - as a tokenizer or token filter with some other analyzer? What's the min_gram, max_gram size? Checkout this example to clear the difference between two.
Also to understand more about how your data is getting indexes in elasticsearch and why not matching your query - try using termvectors api.
Finally I would not suggest you to use ngrams for solving this issue for following reasons - 1) n-grams are going to make your index larger , 2) They have totally different use case.
Comment: in that case I have to create filters for all the escaped characters?
Comment: I have tried your approach. However when it encounters document only contains one word such as `n/a` it fails.


How big is (Breath of the Wild's iteration of) Hyrule?

Question: The Legend of Zelda: Breath of the Wild has a huge world. I want to impress people by comparing Hyrule's size to that of a real-world location. Has anyone estimated the size of Hyrule?
Answer: The BOTW map is  ~602 km or ~372 miles.
This gif/video makes a size comparison between other LoZ maps (and even Skyrim).
Again, this isn't exact, but using measurements in the game (even using Link's height of ~1.7m/5'7"*) we can approximate.

* Again, this is an approximation - Source
Comment: Hrm, saying "Hyrule is as big as Manhattan" isn't as satisfying as I'd hoped. Well, thank you!


How to read a large json from a text file in android app?

Question: I have a text file in my android app which consist a json. I need to read and parse that json. File size is 21 mb. I am using following code to read file:
<code> StringBuilder stringBuilder = new StringBuilder();
 InputStream input = getAssets().open(filename);
 int size = input.available();
 byte[] buffer = new byte[size];
 byte[] tempBuffer = new byte[1024];
 int tempBufferIndex = 0;
 for(int i=0; i<size; i++){
    if(i == 0){
        tempBuffer[tempBufferIndex] = buffer[i];
    }else{
        int mod = 1024 % i;
        if(mod == 0){
            input.read(tempBuffer);
            stringBuilder.append(new String(tempBuffer));
            tempBufferIndex = 0;
        }
        tempBuffer[tempBufferIndex] = buffer[i];
    }
}
input.close();
</code>
Size int is 20949874 in real case. After loop is done stringBuilder length is always 11264 even if i change range of for loop. I tried to make one String from InputStream without using loop but it always gives me OutOfMemoryError Exception. I also get "Grow heap (frag case) to 26.668MB for 20949890-byte allocation" in my logs. I searched here and tried different solutions but did not make it work. Any idea how should i solve this issue. Thanks in advance.
Comment: I can recommend using gson
Comment: i think you have exceeded the heap size dedicated for the app, check Suvitruf answer below.
Comment: Is there any sample for that
Answer: For big json files you should use SAX parser and not DOM. For example JsonReader.
DOM ("Document Object Model") loads the entire content into memory and permits the developer to query the data as they wish.  SAX presents the data as a stream: the developer waits for their desired pieces of data to appear and saves only the parts they need.  DOM is considered easier to use but SAX uses much less memory.
Answer: You can try to split the file into several parts.
So during processing the app hopefully doesn't get out of memory.
You should also consider using "largeHeap" flag in your manifest
(See http://developer.android.com/guide/topics/manifest/application-element.html)
I don't know your file, but maybe if you use smaller JSON tags, you can reduce storage as well.


How to sort list in RecyclerView which is been populated through ViewPager

Question: I have a fragment(say X) which contain ViewPager and TabLayout and i am passing a fragment((say Y)with a list) three times to adapter of this viewpager but every time list is sorted by some parameter.
Y fragment contain RecyclerView. And i am passing that list to the adapter of this RecyclerView.
I am able to populate all the 3 tabs with fragment.But list inside recyclerview is not sorted.Only last tab with recyclerview was comming sorted
Please help me to find shortcoming of the code.
X Fragment
<code>@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.available_bus_fragment, null);
    tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
    viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
    ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
    List<Bus> departureTimeList = mBusList;
    Collections.sort(departureTimeList, new Comparator<Bus>() {
        @Override
        public int compare(Bus lhs, Bus rhs) {
            return lhs.getDepartureTime().compareTo(rhs.getDepartureTime());
        }
    });
    Fragment departureFragment = new AvailableRecyclerViewFragment(departureTimeList);
    if (getArguments()!= null) {
        departureFragment.setArguments(getArguments());
    }
    adapter.addFragment(departureFragment, "Departure");

    List<Bus> durationTimeList = mBusList;
    Collections.sort(durationTimeList, new Comparator<Bus>() {
        @Override
        public int compare(Bus lhs, Bus rhs) {
            return lhs.getDurationForSorting() - rhs.getDurationForSorting();
        }
    });
    Fragment durationFragment = new AvailableRecyclerViewFragment(durationTimeList);
    if (getArguments() != null) {
        durationFragment.setArguments(getArguments());
    }
    adapter.addFragment(durationFragment, "Duration");
    List<Bus> priceList = mBusList;
    Collections.sort(priceList, new Comparator<Bus>() {
        @Override
        public int compare(Bus lhs, Bus rhs) {
            return lhs.getFares() - rhs.getFares();
        }
    });
    Fragment priceFragment = new AvailableRecyclerViewFragment(priceList);
    if (getArguments()!= null) {
        priceFragment.setArguments(getArguments());
    }
    adapter.addFragment(priceFragment, "Fare");
    viewPager.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    tabLayout.setupWithViewPager(viewPager);

    return rootView;
}
</code>
This is my adapter of viewpager.
<code> public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragments = new ArrayList();
private final List<String> mFragmentTitles = new ArrayList();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

public void addFragment(Fragment fragment, String title) {
    mFragments.add(fragment);
    mFragmentTitles.add(title);
}

@Override
public Fragment getItem(int position) {
    return mFragments.get(position);
}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}

@Override
public int getCount() {
    return mFragments.size();
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitles.get(position);
}
}
</code>
Y fragment (AvailableRecyclerViewFragment.java)
<code>@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.available_list_fragment, null);

    recycler_view = (RecyclerView) rootView.findViewById(R.id.recycler_view);

    adapter = new CustomRecyclerViewAdapter(getActivity(), mBusList);
    adapter.notifyDataSetChanged();
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
    recycler_view.setLayoutManager(mLayoutManager);
    recycler_view.setItemAnimator(new DefaultItemAnimator());
    recycler_view.setHasFixedSize(true);
    recycler_view.setAdapter(adapter);
    return rootView;
}
</code>
Adapter for Recyclerview
<code>public class CustomRecyclerViewAdapter extends RecyclerView.Adapter<CustomRecyclerViewAdapter.CustomViewHolder> {
private List<Bus> dataList;
Context mContext;

public CustomRecyclerViewAdapter(Context context, List<Bus> list) {
    dataList = list;
    mContext = context;
}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    public TextView tv_departureTime;
    public TextView tv_arrivalTime;
    public TextView tv_duration;
    public TextView tv_price;
    public TextView tv_availableSeats;
    public TextView tv_travels;
    public TextView tv_busType;

    public CustomViewHolder(View view) {
        super(view);
        tv_departureTime = (TextView) view.findViewById(R.id.tv_departureTime);
        tv_arrivalTime = (TextView) view.findViewById(R.id.tv_arrivalTime);
        tv_duration = (TextView) view.findViewById(R.id.tv_duration);
        tv_price = (TextView) view.findViewById(R.id.tv_price);
        tv_availableSeats = (TextView) view.findViewById(R.id.tv_availableSeats);
        tv_travels = (TextView) view.findViewById(R.id.tv_travels);
        tv_busType = (TextView) view.findViewById(R.id.tv_busType);
    }
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.custom_list_row, parent, false);
    final Animation anim = AnimationUtils.loadAnimation(mContext, android.R.anim.slide_in_left);
    itemView.setAnimation(anim);
    return new CustomViewHolder(itemView);
}

@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {

    Bus bus = dataList.get(position);
    holder.tv_arrivalTime.setText("" + bus.getArrivalTime());

    String[] data = bus.getDuration().split(":");

    holder.tv_departureTime.setText("" + bus.getDepartureTime());
    holder.tv_duration.setText("" + data[0] + "hr " + data[1] + "min");
    if (bus.getFareList() != null) {
        String fare = "";
        for (FareDetails tempFare : bus.getFareList()) {
            fare = fare + tempFare.getTotalFare() + ("/");
        }
        holder.tv_price.setText("" + fare.substring(0, fare.length() - 1).toString());
    } else {
        holder.tv_price.setText("" + bus.getFares());
    }
    holder.tv_availableSeats.setText("" + bus.getAvailableSeats() + " seats");
    holder.tv_travels.setText(bus.getTravels());
    holder.tv_busType.setText(bus.getBusType());
}

@Override
public int getItemCount() {
    return dataList.size();
}
}
</code>
Answer: inside of Fragment X(where your ViewPager is) call method setOnPageChangeListener:
<code>   viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            viewPagerAdapter.notifyDataSetChanged();

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
</code>
As you see inside of onPageSelected() call notifyDataSetChanged for your viewpager adapter. Then it should sort fragment that you're on.
Comment: was this answer helpful?


Is there a way to run a script every time I insert a usb modem?

Question: I would like a shell script to execute each time I insert a USB modem.
How would I do this?
Comment: see http://askubuntu.com/questions/25071/how-to-run-a-script-when-a-specific-flash-drive-is-mounted for an example and delve into "udev rules"
Answer: You can accomplish this with some udev rules, as @Rinzwind suggested.
First, save your script to somewhere accessible by other users. For example, you could save it as /usr/local/bin/script.sh.
Now, make the script accessible by others.
sudo chmod 555 /usr/local/bin/script.sh

Now, plug in your USB modem and then run lsusb. Below is an example output:
$ lsusb
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 008 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 007 Device 002: ID 0fcf:1008 Dynastream Innovations, Inc. Mini stick Suunto
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

Find the line with your modem's name at the end. Now, find the portion near the middle in the format ID XXXX:####. The XXXX and #### portions will be, the Vendor ID and Device ID respectively.
For this example for the third line, which reads … ID 0fcf:1008 Dynastream …, the vendor ID is 0fcf and the Device ID is 1008. Your device will have different values for these IDs.
Now, we will use these IDs to create a rule for udev.
Now, create a rule for this device with udev.
Make a rules file with
sudo nano /etc/udev/rules.d/90-local.rules

Add the following line:
ACTION=="add", SUBSYSTEM=="usb", ATTRS{vendor}=="0xXXXX", ATTRS{device}=="0x####", RUN+="/usr/local/bin/script.sh"

Replace XXXX with the vendor id from earlier, and replace #### with the product id from earlier.
Now, force udev to reload it's rules (alternatively you could skip this step and reboot)
udevadm control --reload-rules
sudo service udev restart

And you're done!
Sources: Similar question on SU concerning udev rules, Creating udev Rules


JSON + PHP + Java - Android login to mysql

Question: i got a problem...
I am trying to store the udid of the device into my database when a user register...
I got this error in the logcat:
10-18 17:17:08.141: E/JSON(1712):

10-18 17:17:08.141: E/JSON(1712): Warning:  Missing argument 4 for DB_Functions::storeUser(), called in /home/matbest1/public_html/android_login_api/index.php on line 64 and defined in /home/matbest1/public_html/android_login_api/include/DB_Functions.php on line 25

10-18 17:17:08.141: E/JSON(1712): {"tag":"register","success":0,"error":1,"error_msg":"Error occured in Registartion"}
10-18 17:17:08.151: E/JSON Parser(1712): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
10-18 17:17:08.381: D/dalvikvm(1712): GC_CONCURRENT freed 296K, 5% free 9394K/9799K, paused 2ms+4ms

I am trying to store the udid in database...
Heres the registeractivity:
public JSONObject registerUser(String name, String email, String password, String uid){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("name", name));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    params.add(new BasicNameValuePair("uid", uid));

    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
    // return json
    return json;
}

Register:
UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.registerUser(name, email, password, uid);

The php code:
 public function storeUser($name, $email, $password, $uid) {
    $uuid = $uid;
    $hash = $this->hashSSHA($password);
    $encrypted_password = $hash["encrypted"]; // encrypted password
    $salt = $hash["salt"]; // salt
    $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
    // check for successful store
    if ($result) {
        // get user details
        $uid = mysql_insert_id(); // last inserted id
        $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
        // return user details
        return mysql_fetch_array($result);
    } else {
        return false;
    }
}

&
  if ($tag == 'register') {
        // Request type is Register new user
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $uid = $_POST['uid'];

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } else {
            // store user
            $user = $db->storeUser($name, $email, $password);
            if ($user) {
                // user stored successfully
                $response["success"] = 1;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error occured in Registartion";
                echo json_encode($response);
            }
        }
    } else {
        echo "Invalid Request";
    }
} else {
    echo "Access Denied";
}

Can someone help me? i am new to this... Thanks a lot.
Comment: I don't know how I can help you, other than to tell you that you're JSON is malformed.  You need to figure out why it is malformed.  Stack Overflow is not a debugger.
Comment: `Value <br of type java.lang.String cannot be converted to JSONObject` -- Seems as if the JSON you're passing to the jsonParser is malformed.
Comment: So there's some wrong when i parse the udid?
Comment: Read the error message.  It's throwing up on the string `` tag.  `` tags aren't even legal in JSON, so something's definitely wrong.  Look at the JSON.
Comment: can't i see what's wrong, i am new here, can you help me?
Answer: The server response contains a PHP error displayed in HTML..
So it's normal that you android app can't parse any JSON..
First thing, you need to be sure that your android app sends all the needed informations (the 4 parameters PHP awaits) because the PHP error clealry tells you that it lacks the parameters #4 : $uid
Try a
print_r($_REQUEST);
at the beginning of your php files to see if PHP receive all the parameters.. If not : the problem is in your android application (uid is a String ? an Integer ? DO you need to convert it ?)


How to translate /en/file.php to file.php?lang=en in htaccess Apache

Question: I'm writing multilingual website. I have several files on server like:
/index.php
/files.php
/funny.php

And would like to add language support by placing language code into URL like this:
http://mywebsite/en/index.php

would redirect to:
http://mywebsite/index.php?lang=en

And
http://mywebsite/en/files.php

would redirect to:
http://mywebsite/files.php?lang=en

I would like to put more languages for example:
http://mywebsite/ch-ZH/index.php

And I would like this to work only for files with php and php5 extension. Rest of files should be the same as they are.
So for example when i will go to address
http://mywebsite/ch-ZH/index.php

I would like my PHP to recognize that current path is
http://mywebsite

and NOT
http://mywebsite/ch-ZH

It's necessary for me because in my PHP code I relate on current path and would like them to work as they are working now.
Could you please write how to prepare htaccess file on Apache to meet this criteria?
Answer: Try this:
RewriteEngine on
RewriteRule ^([a-z]{2}(-[A-Z]{2})?)/(.*) $3?lang=$1 [L,QSA]

And for the current path problem, you have to know how relative URIs are resolved: Relative URIs are resolved by the client from a base URI that is the URI (not filesystem path!) of the current resource if not declared otherwise.
So if a document has the URI /en/foo/bar and the relative path ./baz in it, the client resolves this to /en/foo/baz (as obviously the client doesn't know about the actual filesystem path).
For having ./baz resolved to /baz, you have to change the base URI which can be done with the HTML element BASE.
Answer: Something like this should do the trick,
RewriteEngine on
RewriteRule ^(.[^/]+)/(.*).php([5])?$ $2.php$3?lang=$1 [L]

This will only match .php and .php5 files, so the rest of your files will be unaffected.
Answer: If you don't want to use ModRewrite, you can put symbolic links in the web folder (ln -s . en) and check the URL in PHP.


How to access a dynamic object property not using getter method?

Question: #include <iostream>

class SomeClass
{
 public: int *SomeNumber;

 SomeClass() { SomeNumber = new int; *SomeNumber = 5; }

 ~SomeClass() { delete SomeNumber; }
 int getSomeNumber(void) { return *SomeNumber; }

};

int main()
{

SomeClass A;
std:: cout << A.getSomeNumber() << std::endl; // outputs 5
std:: cout << A.SomeNumber << std::endl; // outputs SomeNumber address

return 0;
}

How can I get *SomeNumber, not its address, by not using the method getSomeNumber()? If SomeNumber were not a pointer to a int, I could get it with A.SomeNumber
Sorry If I were not clear enough.
Thanks in advance.
Comment: @pmr: And a copy constructor. See [The Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three).
Comment: You are missing an assignment operator and copy constructor.
Comment: @pmr: Darn! Did I really post this within your 5mins edit period? I fell for a stupid beginner's prank... `:)`
Answer: Simple:
*A.SomeNumber

It works because . has higher precedence than *, so it's the same as
*(A.SomeNumber)

Answer: Can't you just do:
std:: cout << (*A.SomeNumber) << std::endl;

Answer: Avoid making your properties public!!!!
You could use visitor design pattern instead of this code like:
class SomeClass
{
 public: int *SomeNumber;

 SomeClass() { SomeNumber = new int; *SomeNumber = 5; }

 void visit( IVisitor* visitor ){ visitor->doSomething(*SomeNumber);}

 ~SomeClass() { delete SomeNumber; }
 int getSomeNumber(void) { return *SomeNumber; }

};

IVisitor is an interface you can implement it and anything you want.
Comment: Maybe this toy example needs a SomeNumberFactory too, and a Decorator, and a dependency injection framework!
Comment: I am pretty sure that public member is a bad chose in any case.
Comment: @Thomas: You're forgetting an abstract wrapper and multiple dispatch. Call yourself a software developer...
Comment: getter setters are bad chose too.


Installing Ubuntu on Toshiba Satellite with Windows 8

Question: All I want to do is install Linux Ubuntu 12.04 LTS as another OS on my laptop (which already has Windows 8). I realize this thread might be deemed as a duplicate of this but I don't care about back-up or Lubuntu, nor can I disable UEFI because I can't get into BIOS no matter how hard I try.
I found out about this option in Windows 8, which for some reason has something to do with recovery: "Change advanced start-up settings"/"Advanced startup". Seems like at this point I do not have to deal with BIOS, UEFI, and Secure Boot, nor do I want to; this installation process is already complicated enough. (I'm writing this because I don't know if this is relevant to the problem I'm about to address.) I boot from the DVD with Ubuntu .iso image properly burnt on it. At the start-up I saw a suspicious line:
<code>Could not open "\EFI\BOOT\fallback.efi": 14
</code>
Then it moves on to the boot partitions menu without Windows 8 on it. Now I'm booting into the trial mode of Ubuntu. Even during the installation process it does not recognize Windows 8:

On this blog the author says that she "had to manually partition the hard drive, because the Ubuntu installer didn't recognize that Windows 8 was already on the computer." I don't know if this is safe for an amateur like myself to carry it out, considering that partitioning cannot be undone and I don't know how to do it right:

Problem/question: How do I get it to recognize Windows 8 so that I can partition the memory correctly?
Hope I didn't put up too many findings. Any help would be appreciated.
Comment: I'm going to try [this](https://www.youtube.com/watch?v=18F3CZveMwg) if I plan it well.
Comment: I think this question/answer will give you all the necessary information: http://askubuntu.com/questions/221835/installing-ubuntu-on-a-pre-installed-windows-8-64-bit-system-uefi-supported
Comment: That's the link that the duplicate thread I've mentioned points to. Your answer isn't helpful at all. Please read my post again. I'm looking for very few steps to install Linux on a laptop with Windows 8 on it without ever having to deal with UEFI. Besides, the answer on that other thread is really long, and I'm dealing with only one problem. Also, the answer discourages me from pursuing the dual-boot dream, which is not good because of how Microsoft has revamped things.
Comment: Sorry too much tabs open at the same time. Anyway this is the guide for you and if you read it carefully you can also avoid reading all the section and take just what you need. There is no way to do this in less step then the ones explained there. The first answer only is too long? This one should be enough.
Comment: Looks like I'll just have to make do with this as an option. Thanks.
Answer: I also have Toshiba. It's annoying that they lock almost all the things in there BIOS. But you can just create a partition with your windows OS. Later come back to ubuntu installation and use this partition for installing ubuntu (Don't forget to partition this partition into two. 2GB for swap (u can assign more if you want)and rest as ext4 or ext3 whatever you like). This should solve your problem.


Access class object by its parameters?

Question: Is there any way to find an object saved in a list, knowing only its parameters and without traversing the said list?
For example, there's a class, objects of which have an (x;y) coordinate, and none of the objects share the same coordinate (all x/y pairs are distinct and do not repeat). These objects are all saved in a list:
class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y

points = [Point(...), Point(...), Point(...), Point(...), ...]

Whenever I need the specific instance, is there any way to find it (here: its index in the list) by using just its coordinates without traversing the whole list like here:
def find_objects_index(x, y):
    for i in range(len(points)):
        if points[i].x == x and points[i].y == y:
            return i

EDIT: these Point()s are to be accessed for writing, not reading, and so object.x and object.y will be changing, you can't just create a dictionary with (object.x, object.y) as keys - you'd need to add a new entry and delete the old one each time.
Comment: I like dicts, so, if you define it as a dict with they key being a tuple(x,y) you can instantly get that point...... BUT in your use case, creating a class called Point wouldnt have metadata that would be beneficial unless you were just checking for the existence of that point.  You might not want the overhead of this implementation though as it is taking up a bunch of space.
Comment: "you'd need to add a new entry and delete the old one each time" - then do that?
Answer: You can use list aggregation with a condition to get the item(s) you are looking for:
matching = [p for p in points if p.x = VALX and p.y == VALX]

However, in this case having a dictionary with (x, y) as key is most likely the correct (and well performing) way to go.
Answer: Just put the Points in a dict():
class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y

points_list = [Point(...), Point(...), Point(...), Point(...), ...]
points_dict = {(p.x,p.y):p for p in points_list}

def find_object(x, y):
    if (x,y) in points_dict:
        return points_dict[(x,y)]

def replace_object(x, y, new_point):
    points_dict.pop((x, y), None)
    points_dict[(new_point.x, new_point.y)] = new_point

Comment: This is an excellent answer. Much more concise than the one I cooked up.
Comment: You could replace `find_object` with just `points_dict.get((x,y))` , though.
Answer:
Is there any way to find an object saved in a list, knowing only its
  parameters and without traversing the said list?

Short answer: No.
If you want or need to traverse such a collection of data points rapidly, perhaps you should consider using an type other than a list--a binary tree based off x or y data, for example (or if you need to track them separately, perhaps one tree for each)?
Comment: The reason everyone keeps suggesting a dict (dictionary) type for dealing with this is because usually works really well, and you didn't describe anything that would contradict this yet.

See @quamrana 's answer. For the limited information you provided, it's a really good solution.

Access class object by its parameters?


What is the Rails way to account the statuses?

Question: When I have only two statuses for an object, like 'active' and 'retired' for employee, I'd have a boolean field in the table users to account the user's status.
But what should I do if I have an object with three or more statuses? A task may be 'new', 'in progress', 'finished' and 'closed', and a computer may be 'ordered', 'in store', 'in use', 'in repair' and finally 'disposed'.
I can see several options:
1) Additional table 'statuses'. Status belongs to task, task have one status. It looks ok for me, but it takes additional table.
2) Somehow have a list of statuses in the 'users' table. Don't know if it's possible. I'm using PostgreSQL.
3) Decide that 1 means 'new', 2 - 'in progress', 3 - 'finished' and use these numbers as stauses.
4) Use name of status as a status. Make the field 'status' a string.
What is the best Rails way?
Answer: I personally prefer the gems like state_machine or aasm where I have to create the string column for current state. So I think thats the right way because It gives me the information about the status right away.
Comment: Wow! They look powerful. Thank you!


Extract floats from string to create multiple/multidimensional arrays to manipulate data

Question: First off, I am very weak programmer, and new to python and this site. Sorry for my mistakes. So here goes, my data file looks like this:
http://pastebin.com/60E84azv
there are 6221 lines in total in the paste bin file. For testing, I limited the line numbers to a maximum of 1000.
I am trying to read in the float values in the number lines, with the main columns being 1 and 2.
So far i have written this code to extract the lines i want from the file:
f = open('Sample Data.txt',"r")

num=0
line = f.readlines()

for n in range (107, 1000, 1):  #6621

    if (n>108):
    print line[n]

which works pretty well, printing the numbers in each line as a string. (Each number has 4 spaces by which it is separated from the next, except the first number in each column which has 2 spaces.)
I now wish to convert the string into an array or list so that I can work with the individual numbers and eventually plot a graph with column 2 on the y axis. I've written the following to split and convert the string into floats:
for i in range(108,1000,1):
line[i].split('    ')
float(line[i]) = X[i]
print(X[i])

When I run this, it comes back with the following error:
Traceback (most recent call last):
  File "<pyshell#25>", line 2, in <module>
print(X[i])
NameError: name 'X' is not defined

I've broken it down, and the line[i].split('    ') seems to kind of work, because when I test printed the line it gave 3 separate strings which look like:
['  5070.74537037   -0.003382', '0.009507\n']

I have no idea why there is this error. I thought X[i] was the new array that i was supposed to be creating with the floats but for some reason it doesn't seem to want to work. I've read somewhere that when using large data sets it's good to use multidimensional arrays... If I cannot even understand one dimensional, I have no chance at the other ones!
Is there any way I can create an array or maybe two one dimensional arrays which will allow me to manipulate the x or y column of the potential graph independently?
Thank you for your time!
Answer: This can be handled much more elegantly using split without any arguments for each line:
f = open('Sample Data.txt',"r")
num = 0
for line_number, line in enumerate(f):
    if (line_number < 109):
        #jump over lines at the beginning
        continue
    # now split the line everywhere there are one or more whitespaces:
    numbers_as_strings = line.split()
    # and convert the numbers to floats
    numbers = list(map(float, numbers_as_strings))

Comment: What does using `re` get you here over simply doing `line.split()`?  There's also no need to call `.readlines()`; `enumerate(f)` works just as well.
Comment: Ah, you're right, thanks for the heads up. I didn't know that `split()` with no arguments would do all this for me. I've updated my answer to include your suggestions.
Answer: The reason you are getting that error is because you need to declared X as a list before the for loop:
X = list()
for i in range(108,1000,1):
   line[i].split('    ')
   float(line[i]) = X[i]
   print(X[i])

I think this will give the output you want:
f = open('Sample Data.txt',"r")
num=0
line = f.readlines()

    X = []
    for n, lines in enumerate(line, 0):  #6621
        # make it 109 to remove the first line "['# Column 3: Magnitude error\n']"
        if (n > 109):
            linSplit = lines.split('    ')
            joined = ' '.join(linSplit)
            # apply the float function to every item in joined.split
            # create a new list of floats in tmp variable
            tmp = map((lambda x: float(x)), joined.split())
            X.append(tmp)

    print X[0] # print first element in the list

Output:
[5061.58148148, 0.079304, 0.011018]
Comment: Thank you so much, this works perfectly! Am I right in saying that the output is now a list containing string values? so if I wanted to convert say the 5061.58148148 value, I would just have to extract it from the string, convert it to a float and create a loop where this extraction is assigned to a new list such as hjd = []

Thank you once again!

Edit: it wont let me up vote, says I need 15 reputation :( if I could, I would.
Comment: No worries you will get your reputation up soon. You are right the output is a list of string values. I edited the answer to include a easy way of creating a list of floats instead, by using the `map` function. Or you could do what you said.
Comment: Thank you :). So to follow up, I have the list, and extracted the periods from the sample data. I have now written this block of code which should perform the following function.

    Period_1 = 0.870329
    Epoch_1 = 5062.4719
    phase = []
    j=0

    for j in range(0, len(X),1):
        phase_var = ((X[j][0] - Epoch_1)/Period_1)
        phase[j] = phase_var

    print phase[0]

Essentially producing a new list which should contain the phased X values (phase []) so I can plot them against the magnitude column.
Comment: Just realized I can add the function to the original post. Sorry. In addition to the last comment, when I try to run the script it comes up the error listed above. Not sure what I'm doing wrong. I have declared the list, and there is no need for me to initalize the list size either I don't think
Comment: you forgot to declare `X = list()` at the top. Look at my answer.
Answer: You are not declaring x before calling it in your for loop, if you declare it within your for loop, it will reinitiate with the initial value each loop passing. Try this.

x = []
for i in range(108,1000,1):
    line[i].split('    ')
    x.append(float(line[i]))
    print(x[i])

Comment: Thank you, I went back and declared the variable, but when I tried to print the list, it would print anything. No error message or anything, it would simply move on to a new ">>>" line. Sorry for my bad terminology.


AS3: How can I construct this Array problem?

Question: I want to do something like this with AS3, but I'm new to AS3 and I'm not sure how to go about the coding.
What I want to do is there are 4 MCs in an array, and I need them to move one MC over every time I click on one. And I need them to loop.
So I'll need something like:
if on click #1 - 4, 1, 2, 3
if on click #2 - 1, 2, 3, 4
if on click #3 - 2, 3, 4, 1
if on click #4 - 3, 4, 1, 2
How would I be able to do this in an array? I can't seem to get my head wrapped around it.
Answer: If you want to rotate an array you can use a combination of shift()/push() or pop()/unshift(), depending on which direction you want to rotate. In your case shift/push will do.
This basic code illustrate how you can do that:
var mc1:MovieClip,mc2:MovieClip,mc3:MovieClip,mc4:MovieClip;

var mcs:Array = [mc1, mc2, mc3, mc4];

function rotateArray(els:Array):MovieClip
{
    var el:MovieClip = els.shift();

    els.push(el);

    return el;

}

var nextEl:MovieClip = rotateArray(mcs);

Obviously, you also need to initialise and attach a click handler to your movie clips, here mc1, mc2 etc are just for illustration.
Check the AS3 Array docs for info on shift, push, pop, etc
To rotate left-wise:
shift() will pull the first element of an array and return it (while removing it from the array)
push() will put it back at the end of the array
To rotate right-wise:
pop() will pull the last element of an array and return it (also removing it from the array)
unshift() will put it back at the beginning of the array.
Answer: Below is the code to do what you asked.
The key piece is movieclips.push(movieclips.shift());
movieclips.shift() removes the first element from the array.
movieclips.push() adds the element to the end of the array.
Also check out the pop and unshift functions of the array.
package
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public var mc1:MovieClip = new MovieClip();
    public var mc2:MovieClip = new MovieClip();
    public var mc3:MovieClip = new MovieClip();
    public var mc4:MovieClip = new MovieClip();

    public var movieclips:Array = new Array(mc4,mc1,mc2,mc3);

    public class Demo extends MovieClip
    {
        public function Demo()
        {
            addEventListener(Event.ADDED_TO_STAGE, init);
        }

        public function init():void
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            addChild(mc1);
            addChild(mc2);
            addChild(mc3);
            addChild(mc4);
            mc1.addEventListener(MouseEvent.CLICK, click);
            mc2.addEventListener(MouseEvent.CLICK, click);
            mc3.addEventListener(MouseEvent.CLICK, click);
            mc4.addEventListener(MouseEvent.CLICK, click);
            // Left as exercise: Place and position mc shape, image or bitmap
        }

        public function click(e:MouseEvent):void
        {
            movieclips.push(movieclips.shift());
        }
    }
}


Can a Docker remote host keep its files synced with your local machine? Django project that needs auto-reloading

Question: I'm considering the purchase of one of the new Macbook M1's. Docker Desktop is apparently unworkable with their Rosetta 2 engine, and all of my development efforts rely on Docker desktop, and a local development environment that auto-reloads when files are changed.
I haven't done much with Docker remote hosts, but I see that this could be a stop-gap solution until Docker rewrites its engine.  Google is failing me... can you keep files on your local machine synced up with your Docker remote host?
Answer: No, Docker doesn't do this.  Instead, Docker packages your application code into an image; that image can be transferred to a repository (with Docker Hub being the most prominent option), and then run on the remote system, without necessarily needing to have the application code or the interpreter directly installed there.  Beyond the image system, Docker has no direct ability to transfer or mount files from one system to another (you could do something like create an NFS-backed named volume, but you would need to run the NFS server yourself).
For day-to-day development, using your language's native isolation system often will work better than trying to simulate a local development environment using Docker.  For Python, consider using a tool like Pipfile to create a virtual environment.  Python is reasonably platform-independent, so you shouldn't notice any trouble using Apple silicon vs. Intel's.
Don't even consider using the Docker remote API.  If you don't configure it perfectly, it's trivial to use it to root the host (and there are many instances of this in the wild).  Even if it is configured, you can't use it to mount files from your local system (a docker run -v bind-mount option is always interpreted relative to the Docker host it runs on).  If you need to work directly on the remote host for whatever reason, use an ordinary ssh connection.
Comment: Funny, I'm so biased toward Docker that I had forgotten about the standard Python virtualenv setup.

This is a good point. I'll have to just do dev on a virtualenv and prod can still be Docker.


Reading large XML file using xmerl crashes the node

Question: I have the following code that reads a wikipedia dump file (~50 GB) and delivers pages on request:
defmodule Pages do
  def start_link(filename) do
    pid = spawn_link(__MODULE__, :loop, [filename])
    Process.register(pid, :pages)
    pid
  end

  def next(xml_parser) do
    send(xml_parser, {:get_next, self()})
    receive do
      {:next_page, page} -> page
    end
  end

  def loop(filename) do
    :xmerl_sax_parser.file(filename,
      event_fun: &event_fun/3,
      event_state: :top)
    loop_done
  end

  defp loop_done do
    receive do
      {:get_next, from} -> send(from, {:next_page, nil})
    end
    loop_done
  end

  defp event_fun({:startElement, _, 'page', _, _}, _, :top) do
    :page
  end

  defp event_fun({:startElement, _, 'text', _, _}, _, :page) do
    :text
  end

  defp event_fun({:characters, chars}, _, :text) do
    s = List.to_string(chars)
    receive do
      {:get_next, from} -> send(from, {:next_page, s})
    end
    :text
  end

  defp event_fun({:endElement, _, 'text', _}, _, :text) do
    :page
  end

  defp event_fun({:endElement, _, 'page', _}, _, :page) do
    :top
  end

  defp event_fun({:endDocument}, _, state) do
    receive do
      {:get_next, from} -> send(from, {:done})
    end
    state
  end

  defp event_fun(_, _, state) do
    state
  end
end

Since the code uses SAX parser I would expect constant memory footprint. When I try to read first 2000 pages using
Enum.each(1..2000, fn(x) -> Pages.next(Process.whereis(:pages)); end)

the :pages process uses 1,1 GB of memory according to :observer.start(). When I try to read 10000 pages, the whole thing crashes:
Crash dump is being written to: erl_crash.dump...done
eheap_alloc: Cannot allocate 5668310376 bytes of memory (of type "heap").

When I open erl_crash.dump using dump viewer I see the following:

Is something wrong with the code above? Is GC not quick enough? Although I can see the memory per process it doesn't tell me a lot. How can I see where this memory actually goes?
P.S. Here is a link to a crash dump from today: https://ufile.io/becba.
The number of atoms is 14490, the MsgQ is 2 for :pages and 0 for all other processes.
Comment: I added the error message
Comment: Maybe it's filling the atom table? See [this thread](http://erlang.org/pipermail/erlang-questions/2007-March/025592.html) on xmerl. "What I find is a problem is that xmerl **produces new atoms** for every element name or **namespace URI** it parses from the input.".

The answer there suggests using the erlsom sax parser instead of xmerl.
Comment: What error message do you get when it crashes?
Comment: thanks, I don't think that it's atom table. Atoms are process independent, right? But the dump tells that `:pages` process is to blame, so it's something else.
Comment: Even though the code runs in another _erlang_ process, the atom table global in the running _VM_ process. I'll elaborate more in an answer below.
Comment: Sorry, I didn't realize it was another node running. But the atom table may still be filling up in the :pages node. It is the one actually running the xmerl parser, right?
Comment: @LauroMoura the Atom table's memory usage is not counted in a process's memory usage for me in either Observer or `erlang:process_info`.
Comment: @damluar can you check how many atoms were used by the VM when it crashed? It should be present in the crash dump, near the top, in a line like `Atoms: 123456`.
Comment: @damluar does the crash viewer not have a "MsgQ" column for you? or did you miss including it in the screenshot? Can you please add that?
Comment: @Dogbert, I updated the question, there are 14490 atoms and MsgQ is 2 for `:pages`. Instead of posting more screenshots I decided to attach crash file.
Comment: @damluar Hey. I would love to investigate this in detail if you've still not solved it. Can you reproduce this with a smaller file? Maybe upto a couple hundred MB? Can you link me to such a file?
Answer: The default max number of atoms is slightly over 1 million atoms. Given the English Wikipedia has over 5 million articles and  xmerl seems to create an atom for each namespace URI, I think it may be the culprit.
Also, trying the code below on Elixir fails with just a "stack smashing error".
Enum.each(1..2000000, fn (x) ->
  x
  |> Integer.to_string
  |> String.to_atom
end)

But if I raise the atom limit to something like 5 million with the environment variable ELIXIR_ERL_OPTIONS="+t 5000000", the problem vanishes.
Comment: this seems like a massive oversight in xmerl. considering it's like the easiest way to DOS an erlang service, you would think they'd have used binaries or strings.


Best foundation option for a garden workshop shed

Question: I am soon to be moving into a new house with a blank canvas of a garden. I enjoy woodworking and have been looking at buying a workshop shed, approximately 12ft x 10ft, to go in the garden so I don't make as much of a mess in the garden.
I know that the best option for a shed foundation would be to have a sturdy patio laid and put the shed on top of that. However, I haven't yet been able to see the garden fully in order to create a ground plan for how I may want a patio to be shaped in order to hold a shed and any other garden furniture.
Would it be possible/advisable to place a large workshop shed atop of a plastic shed base that is filled in with gravel, and then building a patio around this in future? See below for example diagram.
I have seen that many sheds on the internet that are built atop a patio require ramps to get wheeled tools in and out. Would going the plastic base route allow me to sink the shed the ramp height down such that it's level with the ground/patio around? This is where the gravel would act as a 'French drain'?
Any advice would be greatly appreciated.
Comment: **Best** is a matter of opinion and thus not a good question for this site. Concrete or mortared stone full basement 6 -7 feet into the ground and 1-2 feet above ground strikes me as far better than your choices if looking for "best" foundation, ignoring cost, for instance. Nice root cellar potential for garden produce storage, too.
Comment: And the two totally different answers we've got so far show exactly _why_ there is no "best" answer to a "best" question.
Answer: A concrete foundation is the "best". But short of that, I would consider deck blocks:

The basic concept is you prepare the ground (which may include gravel to keep down weeds/grass, etc.) and just put the deck blocks on the ground and build a deck on top. You level it by putting 4x4s cut to size into some/all blocks as needed. There are height limits when used for a real deck, but that doesn't apply here as you want to keep the height down anyway to avoid (or minimize) a ramp. The result is surprisingly sturdy and done right should have no problem supporting a shed on top.
While there is some cost, it will likely be quite a bit less than pouring a concrete foundation, and while permanent enough in use, allows you to dismantle, move, etc. without having to break up concrete.
I would make the deck with very little excess around 3 sides but in the front have a few feet of space for safe entry/exit/staging area, and if a step or two is a problem then build a ramp from the ground to the deck.
Answer: I likely have a "cheapest" option, best for me. I have a very sandy soil, very little freeze thaw ( guess no more than 2 in.), but 50 in. of rain. I raked weeds out of the soil, leveled it and set down a "foundation" perimeter of cinder blocks, no concrete. Laid treated 2 X 4 on the cinder block and built an 8' X 14' shed; (one foot of overhang at each end so the roof is 16' long). I laid a dry floor of house brick and filled the cinder block holes with urethane foam.  No problems for over 20 years. No anchors but built-in shelves hold two aquariums so there is 600# of weight in addition to the shed itself. I must admit, I never even considered if I needed a permit until recently; It has electric and water so permit could be a problem.


Remove metal clothesline

Question: I would like to remove two metal clothesline poles in my backyard. I was thinking of doing it by digging around the poles and cutting using a reciprocating saw.
Is this a decent method? It may be important to note that I would be using a Ryobi battery powered saw, which may not have the same oomph that electric saws have. The pole is shown in the back by the fence.
Should I be buying a particular blade for metal? I am a bit of a noob.
Comment: How are the poles secured in the ground? Are they cemented?
Comment: I have not yet dug around to check, but I believe they are. They are very stiff when I try to shake them forcefully.
Comment: There is probably a good chunk of concrete around the pole , I like to remove the entire thing some times a 4x4 strapped to the pole can be used with a chunk of wood for a fulcrum to pop it out of the ground .
Comment: I cut mine off 2 feet below ground level using an angle grinder and an abrasive disk. A recip saw is liable to vibrate your arm off before the poll comes down. I left the concrete plug, 2 feet+ deep, in place. That deep, it does not interfere with my garden tiller.
Answer: IMO the best option is to dig The whole thing out.
A sabre saw with the right blade  will cut it but you'll be left with 5cm+ of jagged pipe sticking out of the ground.
A grinder will cut it down further and tidy the edges, but will still be ugly.
Get digging.
Answer: If you have a Circular Saw - attach a nice CUT OFF WHEEL to it - that clothes line pipe will be cut off in a split 30 seconds or less.
I used a cut off wheel to repair the gates on a metal fence - had thought about the saw thing but man the Cut Off wheel route you will love it, or you can return my answer back.
I bought my cut off wheel at Harbor Freight  - it was cheap - about $10.
Comment: Given that cutoff wheels can fail explosively and PPE is really required when using them and they can still injure you, I would not buy any such thing at Harbor Freight, a store reknowned for selling the cheapest possible Cheese junk, with little regard for the tools' durability or safety.
Comment: @Harper - yes PPE should be worn whether he uses a saw or other wise. Harbor also known as China Freight does sell some poor quality tools - some you can find in other box stores - I have also found some pretty decent tools there ; they are better than they used to be.
Answer: Yes, a recipro-saw is a common approach. Use a fine-toothed metal-cutting blade and don't force it. They'll zip off in under a minute.
If you find that you can't get your cut low enough, go as low as you can, then make two opposing vertical cuts down the center from the top. Whack the quarters outward with a heavy hammer so they're below grade.
Answer: Here is a method that requires no digging or hammering, but it does require a farm jack and chain.   Once I tried it, I have never gone back to anything else to remove posts.   They come up easily and quickly.  When I first tried it I had doubts about the chain slipping, but once it is under tension it grips the metal post (or wood) does not slip.
Obviously you will need to proceed slowly at first to make sure the concrete footing isn't under the fence, but the jack allows you to go slow enough to determine that.

Remove metal clothesline


Correct typos in place names using Google Maps API

Question: I have a web form which asks for the user's address, but I would like to correct possible typos using the database underlying Google Maps. For example, when I search 'Amsterda' in Google Maps, it immediately jumps to Amsterdam.
Can I use Google Maps API for this?
Comment: Nice idea, will be interested to see if anything can be done with this.
Answer: Yes I use the Google Geocoding API to search for user's input. It corrects typos and returns one or more valid locations for the user's search. If it returns more than one, then I ask the user to clarify by choosing one.
Edit: It also breaks a user's input into lines of address, town/city, postcode, country which is great for storing neatly in a database if required
Hope that helps