How do I iterate over JSON objects?

Question: I have a JSON object of all 50 U.S. states and information about them. I want to iterate over each one and console.log their names using a for loop.
JSON stores all the state objects in one big object, and I don't know how to access the state objects since they are in an object of their own.

const jsonobject = {
  "AL": {
    "name": "Alabama",
    "capital": "Montgomery",
    "lat": "32.361538",
    "long": "-86.279118"
  },
  "AK": {
    "name": "Alaska",
    "capital": "Juneau",
    "lat": "58.301935",
    "long": "-134.419740"
  },
  "AZ": {
    "name": "Arizona",
    "capital": "Phoenix",
    "lat": "33.448457",
    "long": "-112.073844"
  },
  "AR": {
    "name": "Arkansas",
    "capital": "Little Rock",
    "lat": "34.736009",
    "long": "-92.331122"
  },
  "CA": {
    "name": "California",
    "capital": "Sacramento",
    "lat": "38.555605",
    "long": "-121.468926"
  },
  "CO": {
    "name": "Colorado",
    "capital": "Denver",
    "lat": "39.7391667",
    "long": "-104.984167"
  },
  "CT": {
    "name": "Connecticut",
    "capital": "Hartford",
    "lat": "41.767",
    "long": "-72.677"
  },
  "DE": {
    "name": "Delaware",
    "capital": "Dover",
    "lat": "39.161921",
    "long": "-75.526755"
  },
  "FL": {
    "name": "Florida",
    "capital": "Tallahassee",
    "lat": "30.4518",
    "long": "-84.27277"
  },
  "GA": {
    "name": "Georgia",
    "capital": "Atlanta",
    "lat": "33.76",
    "long": "-84.39"
  },
  "HI": {
    "name": "Hawaii",
    "capital": "Honolulu",
    "lat": "21.30895",
    "long": "-157.826182"
  },
  "ID": {
    "name": "Idaho",
    "capital": "Boise",
    "lat": "43.613739",
    "long": "-116.237651"
  },
  "IL": {
    "name": "Illinois",
    "capital": "Springfield",
    "lat": "39.783250",
    "long": "-89.650373"
  },
  "IN": {
    "name": "Indiana",
    "capital": "Indianapolis",
    "lat": "39.790942",
    "long": "-86.147685"
  },
  "IA": {
    "name": "Iowa",
    "capital": "Des Moines",
    "lat": "41.590939",
    "long": "-93.620866"
  },
  "KS": {
    "name": "Kansas",
    "capital": "Topeka",
    "lat": "39.04",
    "long": "-95.69"
  },
  "KY": {
    "name": "Kentucky",
    "capital": "Frankfort",
    "lat": "38.197274",
    "long": "-84.86311"
  },
  "LA": {
    "name": "Louisiana",
    "capital": "Baton Rouge",
    "lat": "30.45809",
    "long": "-91.140229"
  },
  "ME": {
    "name": "Maine",
    "capital": "Augusta",
    "lat": "44.323535",
    "long": "-69.765261"
  },
  "MD": {
    "name": "Maryland",
    "capital": "Annapolis",
    "lat": "38.972945",
    "long": "-76.501157"
  },
  "MA": {
    "name": "Massachusetts",
    "capital": "Boston",
    "lat": "42.2352",
    "long": "-71.0275"
  },
  "MI": {
    "name": "Michigan",
    "capital": "Lansing",
    "lat": "42.7335",
    "long": "-84.5467"
  },
  "MN": {
    "name": "Minnesota",
    "capital": "Saint Paul",
    "lat": "44.95",
    "long": "-93.094"
  },
  "MS": {
    "name": "Mississippi",
    "capital": "Jackson",
    "lat": "32.320",
    "long": "-90.207"
  },
  "MO": {
    "name": "Missouri",
    "capital": "Jefferson City",
    "lat": "38.572954",
    "long": "-92.189283"
  },
  "MT": {
    "name": "Montana",
    "capital": "Helana",
    "lat": "46.595805",
    "long": "-112.027031"
  },
  "NE": {
    "name": "Nebraska",
    "capital": "Lincoln",
    "lat": "40.809868",
    "long": "-96.675345"
  },
  "NV": {
    "name": "Nevada",
    "capital": "Carson City",
    "lat": "39.160949",
    "long": "-119.753877"
  },
  "NH": {
    "name": "New Hampshire",
    "capital": "Concord",
    "lat": "43.220093",
    "long": "-71.549127"
  },
  "NJ": {
    "name": "New Jersey",
    "capital": "Trenton",
    "lat": "40.221741",
    "long": "-74.756138"
  },
  "NM": {
    "name": "New Mexico",
    "capital": "Santa Fe",
    "lat": "35.667231",
    "long": "-105.964575"
  },
  "NY": {
    "name": "New York",
    "capital": "Albany",
    "lat": "42.659829",
    "long": "-73.781339"
  },
  "NC": {
    "name": "North Carolina",
    "capital": "Raleigh",
    "lat": "35.771",
    "long": "-78.638"
  },
  "ND": {
    "name": "North Dakota",
    "capital": "Bismarck",
    "lat": "48.813343",
    "long": "-100.779004"
  },
  "OH": {
    "name": "Ohio",
    "capital": "Columbus",
    "lat": "39.962245",
    "long": "-83.000647"
  },
  "OK": {
    "name": "Oklahoma",
    "capital": "Oklahoma City",
    "lat": "35.482309",
    "long": "-97.534994"
  },
  "OR": {
    "name": "Oregon",
    "capital": "Salem",
    "lat": "44.931109",
    "long": "-123.029159"
  },
  "PA": {
    "name": "Pennsylvania",
    "capital": "Harrisburg",
    "lat": "40.269789",
    "long": "-76.875613"
  },
  "RI": {
    "name": "Rhode Island",
    "capital": "Providence",
    "lat": "41.82355",
    "long": "-71.422132"
  },
  "SC": {
    "name": "South Carolina",
    "capital": "Columbia",
    "lat": "34.000",
    "long": "-81.035"
  },
  "SD": {
    "name": "South Dakota",
    "capital": "Pierre",
    "lat": "44.367966",
    "long": "-100.336378"
  },
  "TN": {
    "name": "Tennessee",
    "capital": "Nashville",
    "lat": "36.165",
    "long": "-86.784"
  },
  "TX": {
    "name": "Texas",
    "capital": "Austin",
    "lat": "30.266667",
    "long": "-97.75"
  },
  "UT": {
    "name": "Utah",
    "capital": "Salt Lake City",
    "lat": "40.7547",
    "long": "-111.892622"
  },
  "VT": {
    "name": "Vermont",
    "capital": "Montpelier",
    "lat": "44.26639",
    "long": "-72.57194"
  },
  "VA": {
    "name": "Virginia",
    "capital": "Richmond",
    "lat": "37.54",
    "long": "-77.46"
  },
  "WA": {
    "name": "Washington",
    "capital": "Olympia",
    "lat": "47.042418",
    "long": "-122.893077"
  },
  "WV": {
    "name": "West Virginia",
    "capital": "Charleston",
    "lat": "38.349497",
    "long": "-81.633294"
  },
  "WI": {
    "name": "Wisconsin",
    "capital": "Madison",
    "lat": "43.074722",
    "long": "-89.384444"
  },
  "WY": {
    "name": "Wyoming",
    "capital": "Cheyenne",
    "lat": "41.145548",
    "long": "-104.802042"
  }
}

const jsonarray = [];
jsonarray.push(jsonobject);

for (i=0; i < jsonarray.length; i++) {
  console.log(jsonarray[i].name);
}
Comment: Object.values(jsonobject).forEach(item => console.log(item.name))
Answer:

    const jsonobject = {
      "AL": {
        "name": "Alabama",
        "capital": "Montgomery",
        "lat": "32.361538",
        "long": "-86.279118"
      },
      "AK": {
        "name": "Alaska",
        "capital": "Juneau",
        "lat": "58.301935",
        "long": "-134.419740"
      },
      "AZ": {
        "name": "Arizona",
        "capital": "Phoenix",
        "lat": "33.448457",
        "long": "-112.073844"
      },
      "AR": {
        "name": "Arkansas",
        "capital": "Little Rock",
        "lat": "34.736009",
        "long": "-92.331122"
      },
      "CA": {
        "name": "California",
        "capital": "Sacramento",
        "lat": "38.555605",
        "long": "-121.468926"
      },
      "CO": {
        "name": "Colorado",
        "capital": "Denver",
        "lat": "39.7391667",
        "long": "-104.984167"
      },
      "CT": {
        "name": "Connecticut",
        "capital": "Hartford",
        "lat": "41.767",
        "long": "-72.677"
      },
      "DE": {
        "name": "Delaware",
        "capital": "Dover",
        "lat": "39.161921",
        "long": "-75.526755"
      },
      "FL": {
        "name": "Florida",
        "capital": "Tallahassee",
        "lat": "30.4518",
        "long": "-84.27277"
      },
      "GA": {
        "name": "Georgia",
        "capital": "Atlanta",
        "lat": "33.76",
        "long": "-84.39"
      },
      "HI": {
        "name": "Hawaii",
        "capital": "Honolulu",
        "lat": "21.30895",
        "long": "-157.826182"
      },
      "ID": {
        "name": "Idaho",
        "capital": "Boise",
        "lat": "43.613739",
        "long": "-116.237651"
      },
      "IL": {
        "name": "Illinois",
        "capital": "Springfield",
        "lat": "39.783250",
        "long": "-89.650373"
      },
      "IN": {
        "name": "Indiana",
        "capital": "Indianapolis",
        "lat": "39.790942",
        "long": "-86.147685"
      },
      "IA": {
        "name": "Iowa",
        "capital": "Des Moines",
        "lat": "41.590939",
        "long": "-93.620866"
      },
      "KS": {
        "name": "Kansas",
        "capital": "Topeka",
        "lat": "39.04",
        "long": "-95.69"
      },
      "KY": {
        "name": "Kentucky",
        "capital": "Frankfort",
        "lat": "38.197274",
        "long": "-84.86311"
      },
      "LA": {
        "name": "Louisiana",
        "capital": "Baton Rouge",
        "lat": "30.45809",
        "long": "-91.140229"
      },
      "ME": {
        "name": "Maine",
        "capital": "Augusta",
        "lat": "44.323535",
        "long": "-69.765261"
      },
      "MD": {
        "name": "Maryland",
        "capital": "Annapolis",
        "lat": "38.972945",
        "long": "-76.501157"
      },
      "MA": {
        "name": "Massachusetts",
        "capital": "Boston",
        "lat": "42.2352",
        "long": "-71.0275"
      },
      "MI": {
        "name": "Michigan",
        "capital": "Lansing",
        "lat": "42.7335",
        "long": "-84.5467"
      },
      "MN": {
        "name": "Minnesota",
        "capital": "Saint Paul",
        "lat": "44.95",
        "long": "-93.094"
      },
      "MS": {
        "name": "Mississippi",
        "capital": "Jackson",
        "lat": "32.320",
        "long": "-90.207"
      },
      "MO": {
        "name": "Missouri",
        "capital": "Jefferson City",
        "lat": "38.572954",
        "long": "-92.189283"
      },
      "MT": {
        "name": "Montana",
        "capital": "Helana",
        "lat": "46.595805",
        "long": "-112.027031"
      },
      "NE": {
        "name": "Nebraska",
        "capital": "Lincoln",
        "lat": "40.809868",
        "long": "-96.675345"
      },
      "NV": {
        "name": "Nevada",
        "capital": "Carson City",
        "lat": "39.160949",
        "long": "-119.753877"
      },
      "NH": {
        "name": "New Hampshire",
        "capital": "Concord",
        "lat": "43.220093",
        "long": "-71.549127"
      },
      "NJ": {
        "name": "New Jersey",
        "capital": "Trenton",
        "lat": "40.221741",
        "long": "-74.756138"
      },
      "NM": {
        "name": "New Mexico",
        "capital": "Santa Fe",
        "lat": "35.667231",
        "long": "-105.964575"
      },
      "NY": {
        "name": "New York",
        "capital": "Albany",
        "lat": "42.659829",
        "long": "-73.781339"
      },
      "NC": {
        "name": "North Carolina",
        "capital": "Raleigh",
        "lat": "35.771",
        "long": "-78.638"
      },
      "ND": {
        "name": "North Dakota",
        "capital": "Bismarck",
        "lat": "48.813343",
        "long": "-100.779004"
      },
      "OH": {
        "name": "Ohio",
        "capital": "Columbus",
        "lat": "39.962245",
        "long": "-83.000647"
      },
      "OK": {
        "name": "Oklahoma",
        "capital": "Oklahoma City",
        "lat": "35.482309",
        "long": "-97.534994"
      },
      "OR": {
        "name": "Oregon",
        "capital": "Salem",
        "lat": "44.931109",
        "long": "-123.029159"
      },
      "PA": {
        "name": "Pennsylvania",
        "capital": "Harrisburg",
        "lat": "40.269789",
        "long": "-76.875613"
      },
      "RI": {
        "name": "Rhode Island",
        "capital": "Providence",
        "lat": "41.82355",
        "long": "-71.422132"
      },
      "SC": {
        "name": "South Carolina",
        "capital": "Columbia",
        "lat": "34.000",
        "long": "-81.035"
      },
      "SD": {
        "name": "South Dakota",
        "capital": "Pierre",
        "lat": "44.367966",
        "long": "-100.336378"
      },
      "TN": {
        "name": "Tennessee",
        "capital": "Nashville",
        "lat": "36.165",
        "long": "-86.784"
      },
      "TX": {
        "name": "Texas",
        "capital": "Austin",
        "lat": "30.266667",
        "long": "-97.75"
      },
      "UT": {
        "name": "Utah",
        "capital": "Salt Lake City",
        "lat": "40.7547",
        "long": "-111.892622"
      },
      "VT": {
        "name": "Vermont",
        "capital": "Montpelier",
        "lat": "44.26639",
        "long": "-72.57194"
      },
      "VA": {
        "name": "Virginia",
        "capital": "Richmond",
        "lat": "37.54",
        "long": "-77.46"
      },
      "WA": {
        "name": "Washington",
        "capital": "Olympia",
        "lat": "47.042418",
        "long": "-122.893077"
      },
      "WV": {
        "name": "West Virginia",
        "capital": "Charleston",
        "lat": "38.349497",
        "long": "-81.633294"
      },
      "WI": {
        "name": "Wisconsin",
        "capital": "Madison",
        "lat": "43.074722",
        "long": "-89.384444"
      },
      "WY": {
        "name": "Wyoming",
        "capital": "Cheyenne",
        "lat": "41.145548",
        "long": "-104.802042"
      }
    }

    for(let item of Object.keys(jsonobject)){
      console.log(jsonobject[item].name)
    }

You can first using Object.keys to extract all of the states and  try using for..of loop to access the name

How do I iterate over JSON objects?


How to convert a ComposeView to Bitmap?

Question: I have a simple activity which I am using to convert a composeView to Bitmap.
However when I run the below myBitmap is blank and does not show the "Hello" text composable.
How can I make the below convert composeView to Bitmap?
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val widthPx = 200
        val heightPx = 120

        val composeView = ComposeView(applicationContext)
        composeView.setContent {
            Text(
                text = "Hello",
                color = Color.Black,
                fontSize = 14.sp,
                modifier = Modifier
                    .wrapContentSize()
                    .background(Color.Green)
            )
        }

        val myBitmap: Bitmap = Bitmap.createBitmap(widthPx,heightPx,Bitmap.Config.ARGB_8888)

        val myCanvas = Canvas(myBitmap)
        composeView.draw(myCanvas)
        val result = myBitmap /*<--- result is blank bitmap*/
    }
}

Answer: you have to wait until the view has been laid out
viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val bitmap = graphicUtils.createBitmapFromView(view = view, width = width, height = height)
                onBitmapCreated(bitmap)
                viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })

taken from
https://proandroiddev.com/create-bitmaps-from-jetpack-composables-bdb2c95db51
Answer: You are missing this code:setContentView(composeView)
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val widthPx = 200
        val heightPx = 120

        val composeView = ComposeView(applicationContext)
        composeView.setContent {
            Text(
                text = "Hello",
                color = Color.Black,
                fontSize = 14.sp,
                modifier = Modifier
                    .wrapContentSize()
                    .background(Color.Green)
            )
        }
        // Without this code, you need to render to the activity to take a screenshot
        setContentView(composeView)

        val myBitmap: Bitmap = Bitmap.createBitmap(widthPx,heightPx,Bitmap.Config.ARGB_8888)

        val myCanvas = Canvas(myBitmap)
        composeView.draw(myCanvas)
        val result = myBitmap /*<--- result is blank bitmap*/
    }
}

How to convert a ComposeView to Bitmap?


In Borderlands 1, how can I see the chat?

Question: I can't see the chat in Borderlands 1.
I press Y, then I type something in the msg prompt, I hit enter, nothing happens. My co-op partner can't see it either.
A Google doesn't yield any results that would suggest that this is an issue. What is going on here?
Comment: Is 'Y' the right key? I'm at work so I can't check, but I thought the talk key was usually 'T'. (Though I suppose the fact that you're seeing a message prompt rules that out.)
Answer: You have to remove the text ("msg") that is already in the prompt. Then, hit enter and the chat will appear on the right-hand center of the screen ...


Is the empty set a power set?

Question: I have some home work with problems such as...
Determine whether each of these sets is the power set of a set:
$ 1. \{\phi, \{a\}\}$
$ 2. \phi$
So yes $1$ is the power set of $\{a\}$.
But what about $2?$ Since power sets have to have $2^k$ members then no it can't be a power set. It would have to be $P(\phi) = \{\phi, \{\phi\}\}$ correct? Since it must contain $2$ members.  However, when I try to check myself with Wolfram Alpha, it says $P(\{\}) = \{\{\}\}...$ why? I thought it must have $2^k$ members!
Comment: $1 =2^0{}{}{}$.
Comment: If you have to ask if W|A is ever wrong, you haven't been using it enough!
Comment: WolframAlpha is correct. The power set of the empty set has one element, which is the empty set.
Comment: Is WolframAlpha ever wrong!?
Comment: The first option is the power set of $\{ a \}$, not $a$. If $a$ is a set it may have a much larger power set.
Comment: You are right Yuan, oops!
Answer: We want to make a power set, so start with the set bars:
$$
P(\emptyset) = \{\text{stuff goes here}\}.
$$
What do we fill this set with? As with any other power set, we fill it with all subsets of the big set in question. Here, the big set in question is $\emptyset$, which has exactly one subset (namely, $\emptyset$). So, we write that one subset into the power set to get
$$
P(\emptyset) = \{\emptyset\}.
$$
Notice the empty set contains $0$ elements, while its power set contains $2^0 = 1$ elements.
Comment: @Shashwat that's the point
Comment: Isn't $\{\emptyset\}$ different from $\emptyset$?
Comment: The original question asks if $\emptyset$ is a power set of some set. This "answer" shows that the power set of $\emptyset$ is $\{\emptyset\}$. How does this answer the question?
Comment: I thought that might be the reasoning! I was correct that 2 is not a power set but wrong about the reason. Thank you!
Answer: One way you can see that $\emptyset$ cannot be a power set is that by Cantor's theorem the power set of any set $A$ has strictly greater cardinality than $A$. Now which set $A$ could have strictly smaller cardinality than the empty set?
Comment: +1 for an actual proof, rather than answering a different question
Answer: Every powerset must contain at least one member, namely $\emptyset$.  The set $\emptyset$ itself contains no members, so it cannot be the powerset of any set.
The powerset of $\emptyset$ is $\{\emptyset\}$, which has exactly $1 = 2^0$ members.  It is the smallest powerset, in the strict sense that it is a proper subset of every other powerset, all of which contain at least two members.  (Specifically, the powerset of any set $S \ne \emptyset$ has at least $\emptyset$ and $S$ as members.)

Is the empty set a power set?


How to reverse this bit operand?

Question: Basically I have a number that is manipulated with bitwise operands as you can see here:
is[i_6_] = i_9_ - 256 | ~0x7fffffff;

I need to reverse/undo this bit operand..
| ~0x7fffffff

So that I would just have the value of:
i_9_ - 256r help!

How to reverse this bit operand?
Comment: Unless I'm misreading the "question", it can't be done. Imagine a single bit, and these cases: `0|1->1`, `1|1->1`, `0|0->0`, `1|0->1`. That is, we get: `x|1->1`, `0|0->0`, `1|1->1`. However, this is a problem because `1->x|1` means that we can either "go back" to `1->0|1` or `1->1|1` by a different `x`. Perhaps there is some missing context?
Answer: 1st of all im assumming the expression you wrote is actually (i_9_ - 256) | ~0x7fffffff
| ~0x7fffffff

is effectively the same as
| 0x80000000

meaning it will make the highest bit of the original number (i_9_ - 256 according to what you said) into a "1" regardless of its original value.
so i dont think you can reverse this
Answer: To just remove that bit would be, as you likely know:
& 0x7fffffff

But since you need to revert it to its previous state, you would need to--generally speaking--save the state of that most-significant bit prior to OR'ing to determine whether you should clear that bit or not.  The most direct way to obtain your result, then, would be to re-use the original value of i_9_, but without the OR operation this time:
= i_9_ - 256

Answer: Using this: And with the (~) inverse of the value
i_9_ - 256 & 0x7fffffff;

inverse of inverse ~(~)
Comment: you can also consider bitwise XOR (^) operator - havent tried it

How to reverse this bit operand?


Allow call (and maps, and mail) in cordova

Question: I've been struggling with this for a while. I'm trying to make a call after people press 'Call' from a popup. Funny thing is, that it goes straight to calling when they click the phone number. But when they hit 'Call', console returns:
ERROR Internal navigation rejected - <allow-navigation> not set for url='tel:06-83237516
Code:
Controller:
$scope.callPerson = function() {
    var link = "tel:" + $scope.person.phonenumber;
    var confirmTel = $ionicPopup.confirm({
        title: $scope.person.phonenumber,
        cancelText: 'Cancel',
        okText: 'Call'
    });
    confirmTel.then(function(res) {
        if (res) {
            window.open(link);
        } else {
            console.log('cancel call');
        }
    });
}

Config.xml:
<access origin="*"/>
<allow-intent href="tel:*"/>
<allow-intent href="mailto:*"/>
<access origin="tel:*" launch-external="yes"/>
<access origin="mailto:*" launch-external="yes"/>

html:

 {{person.phonenumber}}

With Mail, it doesn't work at all, and returns an identical error.
Same for opening maps. It does work in the PhoneGap test app, but not when deployed.
Maps code:
$scope.openmaps = function() {
    var address = $scope.person.adres + ", " + $scope.person.plaats;
    var url = '';
    if (ionic.Platform === 'iOS' || ionic.Platform === 'iPhone' || navigator.userAgent.match(/(iPhone|iPod|iPad)/)) {
        url = "http://maps.apple.com/maps?q=" + encodeURIComponent(address);
    } else if (navigator.userAgent.match(/(Android|BlackBerry|IEMobile)/)) {
        url = "geo:?q=" + encodeURIComponent(address);
    } else {
        url = "http://maps.google.com?q=" + encodeURIComponent(address);
    }
    window.open(url);
};

Comment: Try  document.location.href = 'tel:'+$scope.person.phonenumber;
Comment: That might work! However, I found something; adding  to the config.xml did the trick (instead of ). Don't know why that is.. Maybe because I try to call the url from a controller?
Comment: for me it is working fine in android but not working in iOS any help?
Answer: May be it is too late but I want to comment so that other users couldn't face this issue.
Because I didn't find any working solution anywhere.
You need to add
<allow-navigation href="tel:*" /> in config.xml
I was facing same issue for mailto intent. It was working when I tried it directly
Email

But I got an error when I tried to call it using javascript window.location.href = 'mailto:firstname.lastname@example.com

internal navigation rejected - <allow-navigation> not set for url='mailto:email@example.com'

All you need to is to add allow-navigation in your config.xml
So your config.xml will be:
<access origin="mailto:*" launch-external="yes"/>
<allow-intent href="mailto:*" />
<plugin name="cordova-plugin-whitelist" version="1" />
<allow-navigation href="mailto:*" />

Comment: @DavidPrieto you should be able to add it only under the ``, so that it does not break on Android.
Comment: Adding `` in config.xml makes it work on iOS but break its on Android, which works fine without that line. Quite a dilemma.
Answer: I use this config in config.xml
for ios
    <allow-navigation href="tel:*" />

for android
    <allow-intent href="tel:*"/>

Comment: This partially solved my problems, i've to add target="_system" to the links also
Answer: Altering Cordova's WhiteListPlugin in config.xml did not work for me -- <access >,`. I tried many combinations, including those above. Doesn't mean these won't work necessarily, just for my setup it doesn't.  (Building for Browser, Android, and iOS)
However, using the Cordova InAppBrowser Plugin worked:
Use the inAppBrowser plugin and set the target to _system.
cordova.InAppBrowser.open('tel:123456789', '_system');
This by passes the issues I was seeing in iOS with unsupported url, and launches the native system's web browser (i.e., Does not rely on WhiteListPlugin to allow the URL call).
Hope this helps.
Cordova version 6.3.1.


Is breaking long menu names into two lines bad design?

Question: I have a requirement in which I have to design a horizontal navigation with 6 menu items.The challenge here is some of these menu items are pretty long and if I tried putting all the menu items on one line, the menu will go beyond the screen width and one of the requirements was that the size of the container should not exceed 1024 pixels. So if I go with a design which is something like this:

Is it bad design or is it acceptable?
Unfortunately I can't change the names since they have been defined already.
Comment: Can you and your users easily read it? If so, yea, it's fine. It's also quite common. (whether you should use horizontal menus is a different debate altogether, though...)
Answer: The issues this can cause are breaking designs and breaking expectations.
Often I see this as an issue with table headers; dynamic tables might occasionally have an unusually long header for one color, which doubles the size of the header. In the worst cases the table looks silly with the extra large header or the design is broken; the extra large header might break out of it's containing element in some way, ect.
If the design visually accommodates for the extra line I would only see a problem if it just plain looked odd; say you had a list of 10 single line menu items then one that's two lines. That's where it starts to look sloppy.
Try to keep menu names within a certain standard of length, don't have any one menu item stand out for being extremely long*.
If it doesn't look inappropriate and your users don't care, you're good.
*There are exceptions when you want a menu item to stand out, but generally this isn't the case
Answer: With respect to UX, it's as simple as it is, try to get at least 2 or 3 target users and give them a task which needs some good navigation. If the users are happy with it and can finish the task easily - that is a good UX design as this all depends on the usecase. There is no rule that states you can't have 2 lines in navigation.
But when it comes to Aesthetics it might look little weird, but a little tricky design like making rectangular buttons which vertically stand will give room for 2 lines where ever needed.
Comment: In my opinion, the quality of experience a user has while using an application isn't just defined by whether it's possible to finish a task.
Comment: @codeinthehole: Yup you are correct , its too complicated to exactly define most of things in UX.
Answer: Brevity is good.  If a user can refer to a menu item using one or two words - they will be able to talk about your application's functionality more effectively.
In all likelihood, your more frequent users will choose to shorten your menu titles whether you do or not.  It might be worth considering how you can conceptually represent these items using a shorter description now; the longer (more verbose) titles can always be displayed using a tool-tip on hover.


Find the currently active Finder window/folder

Question: Is there any way to determine the currently active window, or a folder, in the Finder? I need this to determine, in some sense, an appropriate "default" location in which to do some particular things in my app.
Actually, does this question even make sense? Does this concept of a "currently active Finder window/folder" even exist in the first place? If it does not, I kindly ask how to get the currently selected Finder item.
Answer: Yes, the concept of the currently active Finder window does exist, as well as the currently selected item.
For example, the following AppleScript gets the selection which is the current selection in the frontmost window. Since this returns a list of files or folders even if there is a single item, the next line gets the first item out of that list (after making sure that the count of the list is greater than 0). You can then ask the Finder for the container window of the selected item, which will return a Finder window object.
tell application "Finder"
    set selectedItems to selection

    if ((count of selectedItems) > 0) then
        set selectedItem to (item 1 of selectedItems) as alias
        container window of selectedItem
    end if

end tell

I'm pretty sure the code sidyll posted will work okay in 10.5 and earlier, but it errors out in 10.6 due to the inevitable changes and quirkiness that AppleScript seems to have from one version of OS X to the next.
[EDIT] Actually, I just figured out what's going on.
I usually have the Finder's Inspector window open all the time (the dynamic Get Info window you get through Command-Option-i), the upper right panel in the image below:

That image shows 3 different classes of windows:
1) The upper left, a Get Info window, is an information window, which inherits from the generic window class.
2) The upper right, an Inspector window, is a plain window.
3) The lower image shows a Finder window, which inherits from the generic window class.
If I run the following script with the setup of windows shown above:
tell app "Finder"
    every window
end tell

it returns the following result:

{window "mdouma46 Info" of application
  "Finder", information window "mdouma46
  Info" of application "Finder", Finder
  window id 1141 of application
  "Finder"}

So, what was happening in my case is that, since the Inspector window is a floating utility panel, if it's currently being shown, asking the Finder for window 1 will always return the Inspector panel, since it's always floating in front of the other windows.
So the error I was getting when running the code was:

error "Can't make «class fvtg» of
  window 1 of application \"Finder\"
  into type alias." number -1700 from
  «class fvtg» of window 1 to alias

(In other words, the Inspector window, a plain window, doesn't have the FileViewer target (fvtg) property; only Finder windows do).
So, your code will work fine as long as the user doesn't have the Inspector window, the Preferences window, or a Get Info window that is frontmost. By changing window to Finder window, though, you can make sure that you only look at the file viewer windows that have the target property.
So, like this:
NSDictionary *errorMessage = nil;

NSAppleScript *script = [[[NSAppleScript alloc] initWithSource:
    @"tell application \"Finder\"\n"
        " if ((count of Finder windows) > 0) then\n"
           "  return (POSIX path of (target of Finder window 1 as alias))\n"
        "end if\n"
     "end tell"] autorelease];

if (script == nil) {
    NSLog(@"failed to create script!");
    return nil;
}
NSAppleEventDescriptor *result = [script executeAndReturnError:&errorMessage];
if (result) {
    // POSIX path returns trailing /'s, so standardize the path
    NSString *path = [[result stringValue] stringByStandardizingPath];
    return path;
}

Comment: Very comprehensive answer! Anyway, my app was targeting 10.6; and just to confirm the script runs correctly here (with `window` only). Well, I'm not an AppleScript master, but certainly it's something to investigate.
Comment: @sidyll: Ah hah! You're right about the code. I figured out what the problem was. I've updated my answer with what was causing my problem.
Comment: Oh man, a lot of valuable information going on here. Thanks for sharing this, by the way I think it's time to release an update to my app :-) no one ever complained about the problem, probably because ⌥⌘I isn't a very well known feature, but that was a lucky play. I'd upvote more times if possible.
Answer: I needed to do this in a project in the past and recurred to AppleScript:
// Get path
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:
                        @"tell application \"Finder\"\n"
                         "  return POSIX path of (target of window 1 as alias)\n"
                         "end tell"];
NSDictionary *errors = nil;
NSAppleEventDescriptor *descriptor = [script executeAndReturnError:&errors];

if ((errors != nil) || (descriptor == nil)) {
    // There is no opened window or an error occured
} else {
    // what was retrieved by the script
    path = [descriptor stringValue];
}
[script release];


async.Future async.Completer - how to "continue" if an error

Question: Some help with the following would be appreciated. I am writing some console test programs, and I want to be able to enter some parameters from the terminal (I don't want to use command line arguments - too many parameters). I have tried some variations, but I cannot find how to accomplish this. The following is the latest version of my test for terminal input. The problem with this program is that if an error is encountered, the Completer closes automatically, and I want to continue from either the Main() or from fGetNumber() function. While I can see why this program doesn't work, it illustrates what I need to achieve - re-enter the number, but I cannot find how to achieve that. If a valid number is entered, there is no problem. If an invalid number is entered, I cannot find out how to re-enter the number.
The code is as follows, and the problem I have is highlighted by "//////////" :
import "dart:async" as async;
import "dart:io";

void main() {
  fGetNumber("Enter Nr of Iterations : ", 0, 999999)
  .then((int iIters){
    print ("In Main : Iterations selected = ${iIters}");
    if (iIters == null) {
      print ("In Main: Invalid Number of iterations : ${iIters}.");
    } else {
      fProcessData(iIters);
    }
    print ("Main Completed");
  });
 }

async.Future<int> fGetNumber(String sPrompt, int iMin, int iMax) {
  print ("In fGetNumber");
  int iIters  = 0;
  async.Completer<int> oCompleter = new async.Completer();

  while (!oCompleter.isCompleted) { ///////////   This loop does not work ///////
    return fGetUserInput(sPrompt).then((String sIters) {
      iIters = int.parse(sIters);
      if (iIters < iMin || iIters > iMax) throw new Exception("Invalid");
      oCompleter.complete(iIters);
      return oCompleter.future;
    }).catchError((_) => print ("Invalid - number must be from ${iMin} to ${iMax}")
    ).whenComplete(() => print ("fGetNumber - whenComplete"));// always gets here
  }
  print ("In fGetNumber (at end of function)");     //// it never gets here
}

async.Future<String>  fGetUserInput(String sPrompt) {
  print ("In fGetUserInput");
  async.Completer<String> oCompleter = new async.Completer();

  stdout.write(sPrompt);
  async.Stream<String> oStream = stdin.transform(new StringDecoder());
  async.StreamSubscription oSub;
  oSub = oStream.listen((String sData) {
    oCompleter.complete("$sData");
    oSub.cancel();
  });

  return oCompleter.future;
}

void fProcessData(int iIters) {
  print ("In fProcessData");
  for (int iPos = 1; iPos <= iIters; iPos++ ) {
    if (iPos%100 == 0) print ("Processed = ${iPos}");
  }
  print ("In fProcessData - completed ${iIters}");
}

Answer:
// This loop does not work

Of course it does - you enter it exactly once, where you immediately return and therefore leave the loop and method.

// always gets here

That's because whenComplete() always gets called, on success or on error.

// it never gets here

Because you already returned out of the method.
So what can be done?
The easiest way would be to not rely on fGetUserInput(). Listen to stdin in fGetNumber and only complete the completer / cancel the subscription if the input is valid:
async.Future<int> fGetNumber(String sPrompt, int iMin, int iMax) {

  print ("In fGetNumber");
  async.Completer<String> oCompleter = new async.Completer();

  stdout.write(sPrompt);
  async.Stream<String> oStream = stdin.transform(new StringDecoder());
  async.StreamSubscription oSub;
  oSub = oStream.listen((String sData) {
    try {
      int iIters = int.parse(sData);
      if (iIters < iMin || iIters > iMax) throw new Exception("Invalid");
      oCompleter.complete(iIters);
      oSub.cancel();
    } catch(e) {
      print("Invalid - number must be from ${iMin} to ${iMax}");
      stdout.write(sPrompt);
    }
  });

  return oCompleter.future;
}

Are there alternatives?
Of course. There are likely many, many ways to do this. This one for example:
async.Future<int> fGetNumber(String sPrompt, int iMin, int iMax) {
  print ("In fGetNumber");
  async.Completer<int> oCompleter = new async.Completer();
  fGetUserInput(sPrompt, oCompleter, (String sIters) {
    try {
      int iIters = int.parse(sIters);
      if (iIters < iMin || iIters > iMax) throw new Exception("Invalid");
      return iIters;
    } catch(e) {
      print ("Invalid - number must be from ${iMin} to ${iMax}");
      stdout.write(sPrompt);
    }
    return null;
  });
  return oCompleter.future;
}

void fGetUserInput(String sPrompt, async.Completer oCompleter, dynamic inputValidator(String sData)) {
  print ("In fGetUserInput");
  stdout.write(sPrompt);
  async.Stream<String> oStream = stdin.transform(new StringDecoder());
  async.StreamSubscription oSub;
  oSub = oStream.listen((String sData) {
    var d = inputValidator(sData);
    if(d != null) {
      oCompleter.complete(d);
      oSub.cancel();
    }
  });
}

If you really feel there should be something addressed by the Dart team, you could write a feature request. But the Completer is designed to only be completed once. Whatever code you write, you can't just loop to complete it again and again.
Comment: Thanks for the response. I did already know that, however, I want a "standard" input function, and other functions that "call" that function - eg. string, integer, currency, etc. However, if what you have posted is the only way to achieve "it", I will accept the answer, however, I think that "this" needs to be addressed by "Dart". However, maybe I'm wrong. Async IMHO needs what has been posted as "await", or something else to address this scenario.
Comment: @BrianOh I said "the easiest", not "the only one". I'm editing the answer to show another approach. There are likely even more alternatives.
Comment: Perhaps the ability to disable autocomplete of a Completer would be a "solution". Then "my" loop would work (?). Why have "Complete" if there is autocomplete? I'm probably over-simplifying the "problem", or at least what I see as a problem.
Comment: Where is there any autocomplete? `Completer`s are completed when calling `complete()`. That's a conscious method call. Your loop still wouldn't work, because no async operation is performed while you endlessly loop.
Comment: @BrianOh Anyway, it's a fact there is no way to block processing until a `Future` completes, which would be a requirement for your loop. There are easy ways (code #1), and there are dynamic ways (code #2) to do what you want. If you think this isn't enough, file a feature request. I can't change that.
Comment: quote "Completers are completed when calling complete(). That's a conscious method call". I don't believe that is the case. When there is an error (non numeric or range), an exception is thrown, and the code for the completer is not executed. When control returns to MAIN, the value returned is null (if an error). There are other situations where I believe it is not possible to achieve what is needed because of what appears to me to be an "anomaly". I will post that separately.
Comment: @BrianOh That appears so because you don't return the `Future` of `fGetNumber`s `oCompleter`, but from `fGetUserInput`. Both handlers are called by the `oCompleter.complete()` in `fGetUserInput`. Return the right `Future` and you'll see that `fProcessData` is never called when your input is invalid.
Comment: or rather, `print ("In Main : Iterations selected = ${iIters}");` will never be printed (your code wouldn't call fProcessData anyway)
Comment: I'm not sure what point you are making there Mario. As I see it, I cannot achieve what I need to achieve. In this case, it can be "fixed" by changing the code and doing the test at the point of data entry. There are other situations where that cannot be done, and I will post that situation separately. But maybe there is an acceptable solution to that scenario - I'm just learning async and futures. I'll make the other post once I document it with a test program. There seems to me to be something missing with loops involving Futures (IMHO).
Comment: @BrianOh My point is that the "anomaly" is no anomaly at all. And the whole point of Futures is that there is no need for any loop. You can still achieve anything with Futures - again, see the code above. You are stuck thinking synchronously. While I agree that sync I/O would be very nice, there isn't any, so you need to adapt, even if this isn't your "style".


MobileServiceClient invokeApi timeout

Question: I'm using Android Azure Mobile Services SDK to connect to Azure Mobile Services.
When I use invokeApi of MobileServiceClient, everything is fine when the Api complete within 60 seconds.
However, when my method of this Api gets longer than 1 minute, the "exception" in the "onCompleted" method shows "Error while processing request".
And I search all the documents about the Android Azure Mobile Services SDK and the class MobileServiceClient, I can't find any setting regarding to this around 60 seconds timeout setting for me to configure.
Could anyone shed some light on it?
thanks alot.
Comment: Is the timeout in the client SDK or on the server execution? I'm sure it is surfacing on the client, but where is it originating? What is your custom API doing that would make it time out - making an outbound HTTP request?
Answer: Implement your custom OkHttpClientFactory. For example:
public class MyOkHttpClientFactory implements OkHttpClientFactory {
    @Override
    public OkHttpClient createOkHttpClient() {
        long timeout = 30_000;
        TimeUnit unit = TimeUnit.MILLISECONDS;
        OkHttpClient okClient = new OkHttpClient();

        okClient.setConnectTimeout(timeout, unit);
        okClient.setReadTimeout(timeout, unit);
        okClient.setWriteTimeout(timeout, unit);

        return okClient;
    }
}

and set instance of this class to MobileServiceClient
MobileServiceClient mobileServiceClient = new MobileServiceClient(SERVICE_URL, Context);
mobileServiceClient.setAndroidHttpClientFactory(new MyOkHttpClientFactory());

this works for me
Default timeout values for OkHttpClient is 10 seconds.
Answer: After a long research, it turns out that Azure Mobile Service for Android uses class MobileServiceClient, and it uses AndroidHttpClient to make the SSL communication with our Azure Mobile Services url.
AND the AndroidHttpClient, from this post android httpclient hangs on second request to the server (connection timed out)  , has a default "reasonable" settings which is 60 seconds timeout for SSL access! OMG.
Don't know if someone who is in the team of Azure Mobile Service for Android can see this post and figure out a way for us to make the timeout setting configurable directly in the class of Azure Mobile Service for Android.
Answer:     By default azure is using AndroidHttpClient. This has a default socket operation timeout 1 min(SOCKET_OPERATION_TIMEOUT = 60 * 1000)

we can simply edit this as
 HttpConnectionParams.setConnectionTimeout(client.getParams(), SOCKET_OPERATION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(client.getParams(), SOCKET_OPERATION_TIMEOUT);

    Inside azure sdk there is an interface ServiceFilterRequest and it holds a method
     public ServiceFilterResponse execute() throws Exception;

    We can edit this method and add our custom interval as follows.
    1. Open its implementation class ServiceFilterRequestImpl.
    2. set a connection interval time

        // I'm changing the default 1 min to 5 minutes..
        private static final int SOCKET_OPERATION_TIMEOUT = 5 * 60 * 1000;

    3. edit  public ServiceFilterResponse execute() throws Exception { } method

      public ServiceFilterResponse execute() throws Exception {
            // Execute request
            AndroidHttpClient client = mAndroidHttpClientFactory.createAndroidHttpClient();
            client.getParams().setParameter(HTTP.USER_AGENT, MobileServiceConnection.getUserAgent());

 //Overriding the default interval with the desired connection timeout value.
            HttpConnectionParams.setConnectionTimeout(client.getParams(), SOCKET_OPERATION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(client.getParams(), SOCKET_OPERATION_TIMEOUT);

            try {
                final HttpResponse response = client.execute(mRequest);
                ServiceFilterResponse serviceFilterResponse = new ServiceFilterResponseImpl(response);
                return serviceFilterResponse;
            } finally {
                client.close();
            }
        }

This will  resolve the issue.

MobileServiceClient invokeApi timeout


highcharts append to highcharts container div

Question: I would like to append to the highcharts div and render more elements when the view reaches to the bottom of the window scroll.
i have tried this:http://jsfiddle.net/kh5jY/8556/
        $('.chartheight').scroll('scroll', function(){
            if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight){
                data.push(5, 7, 3,4);
                chart.series[0].setData(data);
            }
        });

usecase: i have a bar chart with 3 elements when i scroll to bottom i want more 3 more elements to be added to the chart.without the height of high charts being reduced.
Answer: Unfortunately there is no vertical scroller in Highcharts. You could trigger series update and axis set extremes when page is scrolled - http://jsfiddle.net/re4d4q02/

$(function() {
  var lastScrollTop = 0;
  $(window).scroll(function(event) {
    if($(window).scrollTop() + $(window).height() == $(document).height()) {
      var data = [5, 7, 3, 5, 5, 5]
      chart.series[0].setData(data, false);
      chart.xAxis[0].setExtremes(3, 5);
    }
  });

  var chart = new Highcharts.Chart({
    chart: {
      renderTo: 'container',
      type: 'bar'
    },
    title: {
      text: 'Fruit Consumption'
    },
    xAxis: {
      categories: ['Apples', 'Bananas', 'Oranges'],
      minRange: 1
    },
    yAxis: {
      title: {
        text: 'Fruit eaten'
      }
    },
    series: [{
      name: 'John',
      data: [5, 7, 3]
    }],
  });
});
.chartheight {
  height: 800px
}


Disable Integrity Check On Ubuntu Server 20.04.1 ISO?

Question: Trying to install Ubuntu Server 20.04.1 from ISO virtually mounted at ILO4. I get this integrity check, which takes ages How to skip?
Integrity Check Issue
It's insane. Takes more than half an hour now and nothing...
Comment: Additional info belongs as an edit to the question not as a comment.
Comment: No. This is when booting from virtual media (imitating CD) on a server when trying to install the OS.
Comment: Are you installing onto bare metal? Or into a VM or container? Your output indicates that your system disabled caching, so yes the check is going to take a long time.
Comment: I went out shopping and it finished. Now I am installing. Yes - on bare metal. Would be good to know how to skip this. Also there appears to be 20.04.2 installer, which is being downloaded now. Strange. It is not available on the ubuntu site, yet.
Answer: I was plagued with this issue as well, would easily take 40+ minutes for the check to finish when using IPMI virtual media.
I believe I've found a workaround for now.

Spam press Ctrl+C as soon as you see the purple screen appear after booting from ISO. You should see the following screen after pressing Ctrl+C:

Select your language, press Enter. Then, once the screen is at Install Ubuntu Server, select F6 Other Options:

Press Esc to close the dialog box in the bottom left corner. At this point, you should be able to type on the line that starts with Boot Options.... Replace quiet with fsck.mode=skip, then press Enter:

At this point you should be able to boot without disk verification which is very fast over an IPMI-mounted disk.
Comment: At the grub prompt for install ubuntu server you need to hit 'e' then add "fsck.mode=skip" immediately before "quiet" (add a space before and after "fsck.mode=skip") then hit F10 or ctrl+x, I tried adding it to the very bottom and it didn't work, more info here : https://bugs.launchpad.net/ubuntu/+source/casper/+bug/1892369/comments/21
Answer: Worked for me without having to do it before the Grub menu.  I just hit F6 a couple more times after inputting the line of text at the bottom and it takes right off. One thing to note if you are using SuperMicro IPMI, is to change your Hot Key for F6 (other wise it will reboot).
Great fix!
Answer: If you get the grub menu (as opposed to the purple screen) :

then enter e to edit and replace quiet with fsck.mode=skip

then continue with the boot...


Can't update from Ubuntu 16.04 to Ubuntu 17.04

Question: I have been trying to update my PC to Ubuntu 17.04. Apparently I can't. I have issues with these two.
Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/f/fonts-takao/fonts-takao-pgothic_00303.01-2ubuntu1_all.deb Hash Sum mismatch
Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/g/gdb/gdb_8.0.1-0ubuntu1_amd64.deb Hash Sum mismatch.

I have tried answers from Trouble downloading packages list due to a "Hash sum mismatch" error
I tried downloading several times everytime the update comes to like 1930/1931 downloaded and fails here.
I don't know what is the issue. My PC previously stuck at a purple screen and I selected advanced options in GRUB and selected an old version of Ubuntu recovery from there.
Comment: I suggest that you wait until the first point release, 18.04.1 LTS, available in the end of July or beginning of August (unless you want to help debugging the new LTS release and the upgrade script). At that time you will find the option to upgrade from 16.04 LTS to 18.04 LTS. Before that time several bugs will be squashed (in 18.04 LTS itself and in the upgrading tool). See also this link, [Ubuntu Development version / How to participate](https://askubuntu.com/questions/1018033/ubuntu-development-version-how-to-participate)
Comment: ***Reviewers / Close Voters***: This is not an EOL Release-specific question, and therefore is not off-topic: OP has 16.04 and is trying to upgrade it ot a newer release (but can't because 17.04 is EOL and 18.04.1 is not yet available so the 16.04 -> 18.04 upgrade path is not yet available).
Comment: can i just know what to do if i get error like failed to fetch.I entered the url in browser and immediately downloaded a .deb so whats the matter with software manager
Comment: Upgrading to a another release is always risky, so you should **backup** everything, that you cannot afford to lose before trying. It is a good idea to make a full backup of the current system (in your case Ubuntu16.04 LTS). After that you can take risks and upgrade, even if the upgrade system is not quite mature yet.
Answer: Ubuntu 17.04 is EOL.
Normally it is only allowed to upgrade to next version (16.10 which is also EOL) or next LTS version, 18.04.
So, upgrade to Ubuntu 18.04 is the only supported option now.
Comment: When i check for updates in software packager i dont see 18.04 i.e when i selected lts then i dont see it there.When i selected for any version in the bottom area its showing me 17.04 as available.I think the software manager is broke.
Comment: @ThakurKarthik In update-manager's settings you can choose if you want to update to any new version or LTS only. Try to set it to LTS Only.
Answer: Upgrade to the latest LTS.  You can use the "-d" argument to upgrade to the latest supported release, which currently the latest development release.
$ sudo do-release-upgrade -d

You can avoid errors and conflicts by cleaning taking your repository library back to the defaults and running these commands:
$ sudo apt update
$ sudo apt upgrade
$ sudo apt full-upgrade

This is the default source.list for Ubuntu 16.04:
deb http://us.archive.ubuntu.com/ubuntu/ xenial main restricted
deb http://us.archive.ubuntu.com/ubuntu/ xenial-updates main restricted
deb http://us.archive.ubuntu.com/ubuntu/ xenial universe
deb http://us.archive.ubuntu.com/ubuntu/ xenial-updates universe
deb http://us.archive.ubuntu.com/ubuntu/ xenial multiverse
deb http://us.archive.ubuntu.com/ubuntu/ xenial-updates multiverse
deb http://us.archive.ubuntu.com/ubuntu/ xenial-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu xenial-security main restricted
deb http://security.ubuntu.com/ubuntu xenial-security universe
deb http://security.ubuntu.com/ubuntu xenial-security multiverse

To avoid conflicts when trying to upgrade, backup your current /etc/apt/sources.list and use the default one.  After you have completed your upgrade, you can then migrate your custom repository listings back.
The release upgrade process usually automatically disables possible conflicting entries.  But it doesn't always work.
Comment: don't you need the `sudo`?


Uploading video to Firebase uing ngCordova ($cordovaCapture) in ionic framework

Question: How to upload video that I record using my mobile.  I manage to upload the video  path to Firebase but when I want to use it in my view (html file), it does not work. Here is my code:
.controller("HomeCtrl", function($scope, $firebaseArray, $cordovaCamera, $location, $cordovaCapture){
  var fb = new Firebase("https://myURL.firebaseio.com/videos");
  $scope.videos;
  $scope.record = function(){
      fb = new Firebase("https://myURL.firebaseio.com/videos");
      $scope.videos = $firebaseArray(fb);
      var options = { limit: 1, duration: 15 };
      $cordovaCapture.captureVideo(options).then(
          function(videoData) {
              var i, path, len;
              var pathtogo;
              var pathtogostring;
              for (i = 0, len = videoData.length; i < len; i += 1) {
                  path = videoData[i].fullPath;
                  pathtogo = path.toString();
                  pathtogostring = pathtogo.substr(6);
                  alert("Path of the video is = " + path.toString());

                  obj = {
                      videoP: path,
                      videosrc: pathtogostring
                  }
                  $scope.videos.$add(obj);
                }
          },
          function(err) {
          }
      );
  }//end record
 })//end controller

My html file

        {{video.videoP}}

        {{video.videosrc}}

    <video controls>
        <source src="video.videosrc" type="video/mp4">
    </video>

Answer: It's hard to tell without running the app myself, but I do see an issue with your record function.
Don't initialize the $firebaseArray inside of the record function, do it when the controller initializes:
.controller("HomeCtrl", function($scope, $firebaseArray, $cordovaCamera, $location, $cordovaCapture){
  var fb = new Firebase("https://myURL.firebaseio.com/videos");
  $scope.videos = $firebaseArray(fb);
  $scope.record = function record() {
     // ... your record code here
  };
})

The $firebaseArray is in sync with the server, so it only needs to be created once.
As for your display issue...
You need to change the src attribute in <source> to ng-src, and use curlys {{ }} to interpolate:
<video controls>
    <source ng-src="{{video.videosrc}}" type="video/mp4">
</video>

For more information on HTML attrs vs directives, see this answer.
Answer: .controller("HomeCtrl", function($scope, $firebaseArray, $location, $cordovaCapture){
var fb = new Firebase("https://myURL.firebaseio.com/videos");
$scope.videos;
$scope.record = function(){
    fb = new Firebase("https://myURL.firebaseio.com/videos");
  $scope.videos = $firebaseArray(fb);
  var options = { limit: 1, duration: 15 };
  $cordovaCapture.captureVideo(options).then(
      function(videoData) {
          var i, path, len;
          var pathtogo;
          var pathtogostring;
          for (i = 0, len = videoData.length; i < len; i += 1) {
              path = videoData[i].fullPath;
              pathtogo = path.toString();

              obj = {
                    videosrc: pathtogo
              }
              $scope.videos.$add(obj);
            }
      },
      function(err) {
      }
  );
}//end record
 })//end controlle


Why does C print different values than what PHP prints?

Question: This is a complete noob question.
So here is my code in C,
#include<stdio.h>

int main()
{
    int I, X=4;
    double I0;
    double COEFF1[7];
    double COEFF2[9];
    /*Coefficient 1 I0*/
    COEFF1[0]=0.0045813;
    COEFF1[1]=0.0360768;
    COEFF1[2]=0.2659732;
    COEFF1[3]=1.2067492;
    COEFF1[4]=3.0899424;
    COEFF1[5]=3.5156229;
    COEFF1[6]=1.0000000;
    /*Coefficient 2 I0*/
    COEFF2[0]=0.00392377;
    COEFF2[1]=-0.01647633;
    COEFF2[2]=0.02635537;
    COEFF2[3]=-0.02057706;
    COEFF2[4]=0.00916281;
    COEFF2[5]=-0.00157565;
    COEFF2[6]=0.00225319;
    COEFF2[7]=0.01328592;
    COEFF2[8]=0.39894228;

    if(X>=3.75)
    {
        I0=COEFF2[0];
        for(I=1;I<9;I++)
        {
            I0=(3.75/X)*I0+COEFF2[I];
            printf("%i\n", I0);
        }
        //return I0/(sqrt(X)*exp(-X));
    }
    else
    {
        I0=COEFF1[0];
        for(I=1;I<7;I++)
        {
            I0=I0*(X/3.75)*(X/3.75)+COEFF1[I];
        }
        //return I0;
    }

    return 0;
}

And with little housekeeping, this is my translated code in PHP,
<?php
    $coeff1 =array();
    $coeff2 =array();
    /*Coefficient 1 $i0*/
    $coeff1[0]=0.0045813;
    $coeff1[1]=0.0360768;
    $coeff1[2]=0.2659732;
    $coeff1[3]=1.2067492;
    $coeff1[4]=3.0899424;
    $coeff1[5]=3.5156229;
    $coeff1[6]=1.0000000;
    /*Coefficient 2 $i0*/
    $coeff2[0]=0.00392377;
    $coeff2[1]=-0.01647633;
    $coeff2[2]=0.02635537;
    $coeff2[3]=-0.02057706;
    $coeff2[4]=0.00916281;
    $coeff2[5]=-0.00157565;
    $coeff2[6]=0.00225319;
    $coeff2[7]=0.01328592;
    $coeff2[8]=0.39894228;

    $x = 4;

    if($x>=3.75)
    {
        $i0=$coeff2[0];
        for($i=1;$i<9;$i++)
        {
            $i0=(3.75/$x)*$i0+$coeff2[$i];
            printf($i0."
");
        }
        //return $i0/(sqrt($x)*exp(-$x));
    }
    else
    {
        $i0=$coeff1[0];
        for($i=1;$i<7;$i++)
        {
            $i0=$i0*($x/3.75)*($x/3.75)+$coeff1[$i];
        }
        //return $i0;
    }
?>

But why won't they generate the same result?
http://imageshack.com/a/img59/3402/98ak.jpg
Please help. I'm stuck.
Comment: Clearly they are printing out the data using different types - one set are integers and one set are reals.  Which do you want?
Comment: If you're translating to PHP for comparison at very least use the equivalent format string in the PHP version something like `printf("%f\n", $i0);` and `printf("%f\n", I0);` in the C version
Comment: I'd like PHP to print the same results like what C prints
Answer: %i is the format specifier for int; I0 has type double but printf is being told to interpret it as int.  You should use %f for doubles instead:
printf("%f\n", I0);

Answer: Maybe this bit might be useful too.
The difference in the output of the two programs can be attributed indeed to the line
printf("%i\n", I0);

in your C program where I0 is interpreted as an integer but its bit pattern was stored as a double type which uses different logic for organizing the bits (and in the standard variation also uses a different number of bits). What the printf function does is that it just takes whatever that bit pattern was (in the length of an integer) and prints it out like it was an integer - because you told it so (%i), hence the output of the program.
PHP uses dynamic type definition so your variables are interpreted in the context in which they are used (unless sometimes forced to be a certain type by casting or using settype()).
I.e.: $a = 1; will be an integer but if you do another assignment like $a += 0.5; it will be casted into a float automatically.
Comment: I think everyone is trying to correct my C codes. I'm actually trying to get PHP to print the same data output just like C.
Comment: I'm still stuck figuring out what to do. Can I contact you via anything? I really need to get the PHP code worked out :(
Comment: @benjdewantara I would argue that the output of the C program as in your question is incorrect because of reasons stated in the answers. Why would you want to the PHP program to give (mathematically) incorrect result too?
Comment: Well.. It's true that the the C is wrong.. Actually, I asked the wrong question.. Can you help me with this? Why http://pastebin.com/rkdk92Cu won't generate the same output like http://pastebin.com/K8qHzexB


Gradle multiple compile dependencies syntax

Question: I am trying to declare a compile dependency in Gradle 1.12, with multiple items that shares the same exclude clauses (this is to avoid repeating the exclusion everywhere). I know I can do something like this:
configurations {
    compile.exclude group: 'com.google.gwt'
    all*.exclude group: 'com.google.guava'
}

but this will affect ALL configurations. What I want is something like this (which does not work in Gradle 1.12 as written below):
compile (
         ["org.jboss.errai:errai-data-binding:2.4.4.Final"]
        ,["org.jboss.errai:errai-data-ioc:2.4.4.Final"]
    ){
        exclude group: 'com.google.gwt'
        exclude group: 'com.google.guava'
    }

so I can gather together all dependencies for which I need exclusion in one place, and still be able to have elsewhere this:
compile 'com.google.guava:guava:17.0'

Update:
Just to clarify, my only goal is to replace this piece of code:
compile ('bla.bla.bla:1.0'){
  exclude 'same.component:1.0' //Ugly repeat
}
compile ('boo.boo.boo:1.0'){
  exclude 'same.component:1.0' //Ugly repeat
}
compile ('uh.uh.uh:1.0'){
  exclude 'same.component:1.0' //Ugly repeat
}
compile ('oh.oh.oh:1.0'){
  exclude 'same.component:1.0' //Ugly repeat
}

with something short and sweet like this (not working currently):
compile( 'bla.bla.bla:1.0'
        ,'boo.boo.boo:1.0'
        ,'uh.uh.uh:1.0'
        ,'oh.oh.oh:1.0'
)
{
    exclude 'same.component:1.0' //Only once! Sweet!
}

Answer: There is no way to have per-dependency excludes while still being able to use the compile 'com.google.guava:guava:17.0' syntax. configurations.compile.exclude ... will only affect the compile configuration (and configurations inheriting from it), and is almost always preferable over per-dependency excludes.
Another solution is to factor out dependency declarations with something like:
ext.libs = [
    error_data_ioc: dependencies.create("org.jboss.errai:errai-data-ioc:2.4.4.Final") {
        exclude group: 'com.google.gwt'
        exclude group: 'com.google.guava'
    }
]

Then you can reuse these declarations wherever you need them (e.g. dependencies { compile libs.error_data_io }; also works from a subproject). If you really wanted, you could also share the same { exclude ... } block among multiple declarations (by assigning it to a local variable).
Comment: It's rarely needed, and hence Gradle doesn't provide a special syntax for it. Of course you can always do `def excludes = { exclude ... }` and then `compile "foo:bar:1.0", excludes`.
Comment: Thanks Peter, but I wonder If I explained my issue well ... I updated and clarified the question, I just can not believe Gradle does not provide compact syntax for what I want.


error: invalid conversion from 'short unsigned int*' to 'short unsigned int'| (in c++)

Question: I am new to programming and I have been trying to create a program that would solve any Sudoku puzzle. However, I've been getting a lot of errors, and in this one I just can't figure out what's wrong.
This is the code where the error is:
for (short o = indice;o>=divergencias[n_diver];o--){
    N=historico[o];
    P=tabela[N];  //Line 205
    tabela[N]=0;  //Line 206
    }
    indice -= divergencias[n_diver];
    n_diver --;
    }

And the errors, which happened on the lines marked with comments, are:
C:\(...)\main.cpp|205|error: invalid conversion from 'short unsigned int*' to 'short unsigned int'|

and
C:\(...)\main.cpp|206|error: incompatible types in assignment of 'int' to 'short unsigned int [9]'|

I've been searching for this error, and didn't find any satisfying answer to it. Moreover, the website in which I learn what I know about programming specifies that writing something like b = billy [a+2]; is valid. So I just can't understand what's wrong with this...
Comment: Where do you declare `tablea`? Is it a 2D array? Also please include declarations for your other variables.
Comment: Perhaps you could explain what you think lines 205 and 206 do? It looks like tabela is a 2D array (this is sudoku right). But those lines would only be correct if tabela was a 1D array.
Comment: Show the declarations of `N`, `tabela` and `P`. Somewhere here is a type mismatch.
Comment: Geesh... Sorry for wasting your time. Yes, tabela was a 2D array. I have replaced tabela[N] with tabela[N%9][N/9]
Thank you for your answers
Answer: It looks like tabela is declared as short unsigned tabela[9][9]. In order to get an item of type unsigned short from it you have to provide two indexes, not one.
On the other hand, if you are looking to get an entire sub-array from tabela, the left side of the assignment needs to be compatible with a 1-D array of unsigned short, for example, an unsigned short* pointer.


Sudden FPS drop in Cemu BOTW caused by unknown monster only

Question: Using latest Cemu 1.26.2f with AMD Radeon HD 7800, I get a solid 27-30 FPS with the default settings. But whenever Link is facing in the direction of this monster (looking south from Riverside Stable on Hyrule Field), there is a sudden drop to an unbearable 5-10 FPS, which lasts until the camera is moved away from it.
Also, the monster seems bugged somehow, because it barely moves in a sluggish back-and-forth, senseless fashion. I'm attaching the Graphic Packs settings as well. Those OpenGL GPU workarounds don't have any effect. Forcing Vertical Sync and enabling Triple buffering as all youtubers suggest doesn't help either. Any ideas will be greatly appreciated and properly upvoted, thanks. If you know the monster's name, please let me know so I can perform a more specific search for this issue.
Ps. please avoid suggesting to buy an RTX 3080 card to deal with this glitch; I know my Radeon is quite old but it works perfectly fine except for that little guy in the screenshot.

This is the HW monitor when this monster appears:
Comment: That's [Farosh](https://zelda-archive.fandom.com/wiki/Farosh), the electric dragon spirit.
Comment: I solved this problem by changing from OpenGL to Vulkan. It turns out Vulkan mode is not provided by the driver to Windows 8.1, only Windows 10, which I have installed now with great success.
Comment: Great! And since you solved your own problem, consider posting an answer and accept it :)
Comment: That GPU is older than the Wii U itself. Don't expect to ever get good performance on it.
Answer: The solution was to switch to Vulkan API instead of OpenGL. The drivers for Windows 8.1 do not provide Vulkan support so I had to migrate to Windows 10, which I used to avoid like the plague due to its errors. Everything runs smooth and much faster than with OpenGL now.


Find stored grants on mysq tables

Question:
i'm looking for a way to find all privileges for a specific user.
Provided I have a User "John" who has read-only rights on some tables, is there any "select" or "show" to retrieve me the names of the tables "john" has the rights for? So far, i looked in information_schema but couldn't find any specific information on grants for tables.
Or if i set up a role via mysqlworkbench, where is the formation on this role stored in?
how can i manually assign a new user to this role?

Thank you!
Answer: SHOW GRANT FOR user will display multiple rows of data for the user.
SELECT * from mysql.user where User = 'user'

will get the grants for the whole server.
SELECT * from mysql.db where User = 'user'

will get the grants by database.
mysql.tables_priv mysql.columns_priv, and mysql.procs_priv show the fine-grained grants if any happen to exist.

Find stored grants on mysq tables


how can one calculate the minimum and maximum distance between two given circular arcs?

Question: how can one calculate the minimum and maximum distance between two given circular arcs?
I know everything of each arc: startangle, endangle, center, radius of arc.
The only thing I don't know how to calculate is the min and max distance.
Thanks in advance
Comment: you can set it up as a variational problem
Comment: I think it would be better if we knew the equations of the arcs. However if they have a point of intersection, the of course the minimum distance between them will be zero.
Comment: Are the arcs coplanar?
Comment: @MarkBennet yes.
Answer: There are four cases to consider:
1) Endpoints of both arcs
2) An endpoint of one and an interior point of the other, which is on the line through that endpoint and the centre of the other arc.
3) Interior points of both arcs, which are on the line through the centres of the two arcs.
4) Intersections of the two arcs (thanks for pointing that out, Lopsy)
Comment: "4) Intersections of the two arcs" too, surely?
Comment: @Lopsy - that looks right But other than that Robert gave the answer I was just about to post.
Answer: If you know the center of the circular arcs (not meaning its midpoint but a point from which the distance to all the points on the arc is the same, just to avoid confusion), then you can easily calculate the minimum distance. Just use the distance formula to find the distance between the centers and subtract (add alternatively) the radii. This will yield the min. distance. The only problem might be that in some cases the arcs will not face each other directly and if that is the case, you would have to proceed differently. You would have to set a distance function that would express distance between one arc and second arc. This can be done by finding the min. distance between arc and the other arc's center and its radius and plugging it into the cosine rule. Minimizing this will give you the angle at which is the point closest to the other arc.


Zero-copy texture reading from CPU memory

Question: The Intel 740 AGP graphics card read textures directly from system RAM, using VRAM exclusively for depth buffers and the framebuffer. This has the effect of saving video RAM, and it could be implemented with AGP transfer speeds far lower than PCIe transfer speeds of today.
Is such a method of zero-copy texture loading possible/optimal on modern discrete graphics hardware? Is there a specific hardware feature that was present on the i740 requisite for this technique that is not present on modern graphics cards? Furthermore, could zero-copy texture access functionality be exposed by using mapped buffers in OpenGL?
Answer:
Is such a method of zero-copy texture loading possible/optimal on modern discrete graphics hardware?

You say that as though it were optimal back then. The Intel 740 was not exactly warmly embraced by the market, as noted by the Wikipedia article in question:

The AGP Texture concept soon proved to be a tremendous error in design, because the card had to constantly access the textures over a channel that was upwards of eight times slower than RAM placed on the graphics card itself.

The disparity between available memory bandwidth/performance and available compute resources has only increased in the last 20 years. So, will it be "optimal" to have a discrete GPU read from main memory?
No.
Could it be "possible"? Not in terms of marketability. Even $50 and below discrete GPUs carry their own on-board RAM. Anything much slower/smaller than that isn't worthwhile, because pretty much everyone already has Intel or AMD's on-die GPUs for when performance isn't of importance. If you have a discrete board, it will always be better to put some RAM on the board with its own bus than to have the board try to read most of its data directly from main memory.

Furthermore, could zero-copy texture access functionality be exposed by using mapped buffers in OpenGL?

No. Mapped buffers would be buffers, not textures. They're different kinds of storage objects with (hypothetically) distinct allocations behind them. PBO is a means of asynchronously transferring data from a buffer to a texture. That is a transfer of data, not an adoption of a memory allocation.
Intel has an extension for mapping a texture's storage, but that requires that the texture be in a linear format. It's not widely supported, and likely never will be.
Vulkan provides for the possibility of something similar, but using linear texture as sources in sampler read operations from a shader is not required to be supported. You'd have to ask each implementation whether it allows it and in which formats, and for which usages are allowed.
Comment: Indeed, the decreased performance does certainly make sense. However, interestingly, these benchmarks seem to contradict it: http://vintage3d.org/i740.php


FtpWebRequest request is triggering a Invalid URI format

Question: From the command line I can successfully connect via FTP to my host using either
ftp.domain.com or domain.com

C:\Users\Aaron>ftp
ftp> open
To domain.com
Connected to domain.com.
220 FTP Server ready.
User (domain.com:(none)): Login failed.
ftp> close
221 Goodbye.
ftp> open
To ftp.domain.com
Connected to ftp.domain.com.
220 FTP Server ready.
User (ftp.domain.com:(none)): Login failed.
ftp> close
221 Goodbye.
ftp> quit

I escaped entering the password above and scrubbed the domain, but it still shows for each connection I was successful.  When I run this code in Visual studio, I get the invalid URI.
Here is my code I've tried in C#
Uri target = new Uri("ftp://ftp.domain.com/");
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(target);
requestDir.Credentials = new NetworkCredential("user", "pass");

Uri target = new Uri("ftp://ftp.domain.com/");
FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(target);
requestDir.Credentials = new NetworkCredential("user", "pass");

The requested URI is invalid for this FTP command
I've looked on here as there are many like this, but I've tried all of them (I think) and I just keep on getting this error.  Any ideas?
Thanks!
Answer: I was able to get it working with the help of some other posts here and a lot of troubleshooting.  I now have this working and have moved on to new errors.  Here is the code for the successful FTP upload:
reqCakes = (FtpWebRequest)WebRequest.Create("ftp://domain.com/images/" + "koala.jpg");
                reqCakes.UseBinary = true;
                reqCakes.Method = WebRequestMethods.Ftp.UploadFile;
                reqCakes.Credentials = new NetworkCredential("user", "pass");
                BinaryReader rdrCakes = new BinaryReader(File.Open(fileToOpen, FileMode.Open));
                rdrCakes.Close();
                byte[] cakeData = File.ReadAllBytes(fileToOpen);
                reqCakes.ContentLength = cakeData.Length;
                Stream reqStream = reqCakes.GetRequestStream();
                reqStream.Write(cakeData, 0, cakeData.Length);
                reqStream.Close();


FoxPro to WPF porting help?

Question: I am porting an application based on foxpro to WPF C# but i stuck in this window & i need your help.
here is a screen shot of window Click Here.
this is basically a wine shop billing part which allows to bill upto 99 items. Code col. allows to input item code and all description will come up. I am looking for something similar interface in WPF.
Please help.
Answer: There isn't anything out of the box, but create a tabular window, and to each row add a textbox that will load all descriptions after its text is changed. You'd have to calculate subtotal and total stuff by yourself, but clever use of databound controls and LINQ would allow you to create this kind of interface elegantly.
Comment: You can find a LINQ to VFP dll at http://linqtovfp.codeplex.com if you choose to go this route.
Answer: There are a couple of developers in Europe (Uwe Habermann and Venelina Jordanova) who are working on a Visual FoxPro to Silverlight product right now. They are presenting it in Europe during the summer of 2010 and at the Southwest Fox Conference held in Mesa, AZ, USA this October. It is a free pre-conference session if you subscribe to their framework, subscribe to FoxRockX, or attend the conference.
(full disclosure, I am one of the organizers of Southwest Fox Conference, but hopefully it does not make the information any less valuable).
Rick Schummer, VFP MVP

FoxPro to WPF porting help?


Redirect Piwik HTTP request to different server

Question: I have Piwik running on one server, Server A. All my websites run on a different server, Server B. I don't want my users to know Server A's address (including any cookies that would be set), but I want it to do all the statistics. I presume I will have to redirect all the requests to piwik.php from Server B to Server A but I don't know how.
Comment: Redirect let your users know Server A's address.
Comment: Well I know that if I use a 301 or 302 that my address will be revealed. That's why I''m asking.
Comment: Hmm, if you know that, then I see no reason to ask because you already know it does not work. also, how could you tell the user to do requests to piwik w/o telling where piwik is. This inherently makes no sense at all.
Comment: Well, I thought I might be able to get the raw HTTP request header, rewrite it and then send it to Server A -- or something similar.
Answer: <code>## Piwik Proxy Hide URL
This script allows to track statistics using Piwik, without revealing the
Piwik Server URL. This is useful for users who track multiple websites
on the same Piwik server, but don't want to show the Piwik server URL in
the source code of all tracked websites.
</code>
Located in the /path/to/piwik/misc/proxy-hide-piwik-url/ folder.
Should do what your looking for.


Can the primary attribute names be hidden in a custom hero layout?

Question: A friend told me about the "Customize Grid" feature in the hero picker of Dota 2, and about a great website (Dota2Layout.com) to edit those grids. However, that website became incompatible with latest updates to Dota, so for the time being I hacked together my own DotaGrid editor.
This works just fine, but I can't seem to get rid of the primary attribute names. Here's a screenshot of a custom layout I've created:

Question: Is there any way to remove the red-encircled texts ("Strength", "Agility", "Intelligence")?
What I've tried / considered:

Resetting and exporting the layout, scouring through the file to see if there's anything to tweak;
Applying some Google-fu;
I've checked if dota2layout.com does anything special (by checking exported files);
Searched the steamapps/dota2 folder for *.jpg or *.png (a long shot, I know).

All to no avail.
Is it currently (6.81b) possible at all to remove those attribute names?
Comment: Upvote, because somehow I never knew you could mess with the hero layout :O
Answer: I found something for you! You can change the texts in the dota_"YourLanguage".txt file in the resource folder. In case English is the language you use for Dota follow these Steps:

Go into the Steam\SteamApps\common\dota 2 beta\dota\resource Folder
Open dota_english.txt
Press Ctrl + f and search for "DOTA_Hero_Selection"
Now is the time to remember getting a backup copy of the file.
You can change all kinds of stuff here but to simply remove the texts scroll down to:
"DOTA_Hero_Selection_Team_Good" "THE RADIANT"
"DOTA_Hero_Selection_Team_Bad"  "THE DIRE"
"DOTA_Hero_Selection_STR"       "STRENGTH"
"DOTA_Hero_Selection_AGI"       "AGILITY"
"DOTA_Hero_Selection_INT"       "INTELLIGENCE"

and change it to:
"DOTA_Hero_Selection_Team_Good" "THE RADIANT"
"DOTA_Hero_Selection_Team_Bad"  "THE DIRE"
"DOTA_Hero_Selection_STR"       ""
"DOTA_Hero_Selection_AGI"       ""
"DOTA_Hero_Selection_INT"       ""

Awesome work until now! I hope that you can improve your website with this post.
Comment: Thanks a bunch, this works as expected. Afraid my little app can't do much with this though, other than provide it as a "quick tip".
Comment: As could be expected though, this file is overwritten usually when Dota updates. Probably not much we can do about that though.


filter method replacing one array with another array

Question: I'm trying to filter out the values of one array from another array.  When using Javascript's filter method, my script looks like this.
var notUsed = ["Advanced Tac. Training Area", "Dunbarton Railroad Yard"];

var areas = ["A Area", "Advanced Tac. Training Area", "B Area", "Dunbarton Railroad Yard", "C Area"];

areas.filter(function(){
    return areas = notUsed;
})
console.log(areas);

According to the documentation, when I console the areas array after I've run the filter function, the array should look like this
"A Area", "B Area", "C Area"

However, that's not what's happening.  Instead, I'm getting the values of the notUsed array, so it's essentially replacing the areas array with the notUsed array.  Can anyone explain why this is happening and how I go about getting the areas array without the values of the notUsed array?
If this question has already been asked, please let me know in the comments and link to the answered question.  that way I can delete this one and eliminate the duplication.
Answer: Two mistakes.

areas = notUsed will simply assign the value of notUsed to areas, it doesn't compare them.
filter returns a new array. It doesn't change the original array.

Probably you can write it like this
areas = areas.filter(function (area) {
  return notUsed.indexOf(area) === -1;
});

Now, the notUsed.indexOf(area) returns the index of the area in the notUsed array. If it couldn't find it, then it will return -1.
Also, see we assign the result of filter back to areas.
Comment: Awesome, thank you.  Do you know why this isn't something that's explained or demonstrated in the documentation?  I know that it explains that the original array is not changed, but it doesn't demonstrate how to do anything like this.  At least, not that I've seen.
Comment: @Robert There are [few examples in MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Examples).
Answer: You have not understood the use of filter correctly.
var notUsed = ["Advanced Tac. Training Area", "Dunbarton Railroad Yard"];

var areas = ["A Area", "Advanced Tac. Training Area", "B Area", "Dunbarton Railroad Yard", "C Area"];

var res = areas.filter(function(ele){
    return (notUsed.indexOf(ele) == -1)
})
console.log(res);

Answer: The Filter function should test the values in the array against a condition implemented by you. This is not the case in your example. Filter Function
This could be a possible solution for you.

var notUsed = ["Advanced Tac. Training Area", "Dunbarton Railroad Yard"];

var areas = ["A Area", "Advanced Tac. Training Area", "B Area", "Dunbarton Railroad Yard", "C Area"];

var filtered = areas.filter(value => { return notUsed.indexOf(value) === -1 })
console.log(filtered);
Answer: filter() method creates a new array with all elements that pass the test implemented by the provided function.

  var notUsed = ["Advanced Tac. Training Area", "Dunbarton Railroad Yard"];
    var areas = ["A Area", "Advanced Tac. Training Area", "B Area", "Dunbarton Railroad Yard", "C Area"];
    var out = areas.filter(function(index) {
     return notUsed.indexOf(index) == -1;
    });
    console.log(out);


Tomcat through Apache

Question: I'd like to know if is a good decision to configure tomcat through port 80 (in apache with virtual-hosts ).
I need to setup a tomcat service in the same server I have apache, plus I need to use Tomcat through port 80.
Is this right? or is best to use them in separated servers?
Answer: That's OK. But sometimes tomcat is deployed with Apache. The Apache is a front-end server to balance load. And many tomcats are as back-end servers.

Tomcat through Apache


Rails forms (checkboxes) - get a name attribute from an associated model without using f.label

Question: I've been following this tutorial to set up a simple tagging system: http://www.sitepoint.com/save-multiple-checkbox-values-database-rails/
The only problem is that the 'name' on my Expertise model is being used as keys in .yml files (the tags will be translated into various languages).
The relationship of the Expertise model with the form's model (in this case, Teacher model) is a mutual 'has_and_belongs_to_many'
The form for the check boxes looks like this.
<%= form_for(@teacher, :html => {multipart: true, :class => "sky-form"}) do |f| %>
...

  Areas of expertise:
  <%= f.collection_check_boxes :expertise_ids, Expertise.all, :id, :name do |b| %>

      <%= b.check_box %>  <%= b.label %>

  <% end %>
...

<% end %>

Instead of b.label I want to do b.name (name is an attribute on the Expertise model) but when I do this, it pulls an error.
Any suggestions? I'm just trying to get the 'name' text of each instance of the Expertise model rather than it served in an entire html  element.
Comment: Could you share the error itself?
Comment: undefined method `name' for #
Application
Comment: I see, can you please also share the HTML, which is being generated with the above code and point out what is wrong with it?
Comment: the issue is b.label generates a`Label Text` element. I just want to generate the text of the name itself (here, "Label Text") without an accompanying  element.
Answer: Quote from: http://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes

There are also three special methods available: object, text and value.

I guess b.text or b.value is what you are looking for.
Comment: Thank you so much! I swear I looked over that exact page, but not thoroughly enough, evidently, as I completely missed that section. Thanks for your help!


What is the difference between various space-filling curves?

Question: Space-filling curves are important in many graphics applications because they help expose spatial locality. We often hear about different algorithms using Z-curves, Morton codes, Hilbert curves, etc. What are the differences between some of these different curves and how do they apply to various applications?
Comment: Try the book [Space-Filling Curves - An Introduction with Applications in Scientific Computing](http://www.space-filling-curves.org/).
Comment: See also section 184.108.40.206 of Samet's *Foundations of Multidimensional and Metric Data Structures*.
Answer: The difference is how well a mapping preserves locality and how easy it is to encode/decode the keys. The paper "Linear Clustering of Objects with Multiple Attributes" by H V Jagadish says: "Through algebraic analysis, and through computer simulation, we showed that under most circumstances, the Hilbert mapping performed as well as or better than the best of alternative mappings suggested in the literature". On the other hand, z-order is a bit simpler to use, for example compare the various methods listed in Bit Twiddling Hacks for z-order and Wikipedia for Hilbert-order.
As for the applications, I think the main advantage in using space filling curves is that they map points from higher dimensional space to space of lower dimension. For example, they make it possible to window query for points using traditional B-tree database index. Again, on the other hand, the disadvantage is that one needs to know the bounds of the input in advance as it is difficult to "resize" the mapping later.
PS: "Z-curve" is the same as "Morton code".
PPS: Additional mappings include Peano curve and for applications see also Geohash.
Answer: Those space filling curves allow to keep locality in multiple dimensions when you "walk" linearly along the curve.
From what I have seen, Z-Order (also known as Morton code) is the most employed because of its computational cost which is constant (and cheap) to access any point of the curve directly. (And easy to implement in hardware with 0 cycle penalty, as it corresponds to "just switching" address wires).
A concrete example of Z-Order curve is texture swizzling : which is basically increasing the cache-hit rate for texture read on GPUs.
(See images in the article about Z-Curve https://en.wikipedia.org/wiki/Z-order_curve)
If the texture is simply stored linearly, you get the maximum cache hit if you render just the texture as 2D image, but if you rotated it by 90 degree on screen, you get into the worst case scenario (cache miss for every texture read).
As a result, it is better to trade off a little and lower your best case scenario and have better cache hit for most of the patterns.
As a personal note, from what I have seen, other curves may require recursive step for their computation and result in bigger cost than Z-Curve with a minimal gain in term of locality coherence. So, I have not heard about those curve used with a practical purpose, except as a research subject in mathematic or creative/funny rendering.


How can I deploy a new service in Juju GUI specifying the destination machine?

Question: I would like to deploy a new service in the juju GUI specifying on which machine it should run. I mean the equivalent of doing juju deploy --to 0 mysql.
Answer: The GUI does not support this yet.  We expect to be starting work on this (containerization and machine support) very soon.


Vertical centring with :after pseudo-element not working

Question: I'm trying to vertically centre my introWrap container using the :after pseudo-element method (as described at the end of this article). I've always applied this method without any problems, but I can't for my life seem to understand why it doesn't work in this case (http://jsfiddle.net/4yfru/2/).
Right now the introWrap div is at the top, whilst it should really be in the center on the vertical axis. I tried replacing the :after pseudo-element with a span, and it worked perfectly. Something's fishy is going on here and I don't know what.
Could any kind soul please help me out here?
Answer: You have the wrong element with the :after applied. You need to apply it to the "wrapping" element, so like this:
#intro:after{
    content: "";
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

Comment: Oh no! Please don't (even in jest) refer to me as "God," a title which only belongs to Jesus Christ my Savior. In answer to "why," I can only say "I don't know" (see, I'm not God). The technique listed on the site you reference clearly says, "a 'ghost' element inside the parent," which would indicate it does not work inside the child. You mention a span replacement working, but I do not see that [on the child](http://jsfiddle.net/4yfru/6/), only if [in the parent](http://jsfiddle.net/4yfru/7/). So if it did work for you previously, I don't know why.
Comment: You, my friend, are God. However, it still doesn't make sense to me. I've always done applied ``:after`` on the element being wrapped, so I'm wondering why it is not working in this case. :/
Comment: You are welcome. I was not offended, though maybe God was. Glad you have it working, however.


Compare an expression with zero

Question: I need to compare $1-\frac{2}{3}\cdot3^{-\frac{2}{3}}\cdot \log_e9$ and $0$ without any computer
Comment: You just need to see if it's positive or not. After some fiddling, you'll see that this is equivalent to seeing if $\displaystyle\log_e9 < \frac{3^\frac{5}{3}}{2}$.
Answer: It's easy to take conservative estimates $3^{-\frac{2}{3}}<\frac{1}{2}$, $\log_e9<\frac{5}{2}$ and conclude that the expression is positive.
Comment: And why is $\log_e 3$ less than $\frac{5}{2}$?
Comment: @МаркТюков: because $e\approx 2.7$, $e^2\approx 7.3$, $\sqrt{e} > 1.5$
Answer: With the use of $\;9<e^3$ we get
$$\frac{2}{3}\cdot3^{-\frac{2}{3}}\cdot \ln 9<\frac{2}{3}\cdot3^{-\frac{2}{3}}\cdot \ln e^3=\frac{2}{9^{1\over 3}}<\frac{2}{8^{1\over 3}}=1,$$ thus $$1-\frac{2}{3}\cdot3^{-\frac{2}{3}}\cdot \ln 9>0.$$

Compare an expression with zero


Changing colonies seems wasteful?

Question: I'm still new to the game, but I seem to get a lot of "so and so needs help over at X location" which seems to usually require me uprooting my colony to live elsewhere.
I've done this a few times and honestly it seems like a waste. Does it make more sense to stay put or what? Because the game seems like it's always pushing me to travel.
Answer: You don't need to uproot your entire colony for prisoner rescues. Just form a caravan with enough combatants to help them, enough food to survive the journey there and back (and a bit extra), and perhaps some medicine and bedrolls. The rest of your colonists can continue life as normal (or as normal as things get out on the Rim).
Moving your entire colony is usually a bad idea and a waste of resources. It's often only done as part of self-imposed challenges, getting to the spaceship, or as a last resort.

Changing colonies seems wasteful?


Wiring in a bath heater,vent, fan combo with power source coming from ceiling

Question: I have 3 cables coming in from the ceiling, with one being the supply. At the switch box I have 2 cables with neither being hot. In the switch box I have a black/white and another set being black/white/color.
How do I wire in the connection at the fixture in order to have my 3 switches work for each individual function? Which one do I need to wire to be my common? My switch has a common and 3 terminals on the other side.
Comment: What is "*black/white/color*" What is the *color*?
Answer: If you were using separate switches:
Use the two wire cable to switch device #1. Use the white as the hot and mark it with black tape or marker. Use the black as the switched feed back to the ceiling box.
Use the three wire cable to power the other two devices. Use the white as the hot and mark it with black tape or marker. Use the black as the return switched hot for device #2 and the red as the return for device #3.
At the ceiling box, attach the incoming hot to the two white wires going to the switch box. Mark both of those whites with black tape or marker. Attach black and red wires from the switches to their respective devices.
Also in the ceiling box, attach the white (neutral) from the feed cable to the white on each device.
Attach all ground wires (green or bare) to all other grounds in each box.
If you re using one switch with a common hot:
Mark both white wires in the switch box with black tape or marker. Attach them together with a pigtail (a short length of wire). Attach the pigtail to the common terminal on the switch. Use the black wire from the two wire cable to one of the three other terminals. This will switch device #1.
Use the black from three wire cable as the return switched hot for device #2 and the red as the return for device #3.
At the ceiling box, attach the incoming hot to the two white wires going to the switch box. Mark both of those whites with black tape or marker. Attach black and red wires from the switches to their respective devices.
Also in the ceiling box, attach the white (neutral) from the feed cable to the white on each device.
Attach all ground wires (green or bare) to all other grounds in each box.
[Note: This may seem a bit strange since you are running parallel hot wires and attaching them to each other at both ends of the run.  This is done to comply with the rule that a circuit must be complete within each cable, to avoid possible induction heating.]
Comment: Thanks for the **Note**!  Until I got there, I didn't understand why you were running hot in both cables, but that cleared it up.
Answer: When you say "black/white/color" you probably mean a 14/3 cable with black/white/red. The "common" you are referring to, will be a hot wire (supply wire) from the fan junction box to the switch.
Use the black/white cable for power (black) and neutral (white) from the power supply to the switch location. The neutral you can cap off and leave in the box for future use. (Or use it if your switch requires a neutral.)
Use the 3 conductor cable for return power back to your fan/heater/light combo. You choose which color to connect to which function. However, you should re-identify the white as blue in this case. It is a switched wire and is not a neutral and therefore should not be left white.
Connect the fan neutral (white) to the supply neutral at the fan box.
Good luck!