How can I extract filesystem from vdi

Question: I am trying to build linux from scratch. I ll install it into virtualbox. Later I want to extract ext2 filesystem in it. Is it possible?
EDIT: I want to extract root.ext2 filesystem in vdi, to mount it in Ubuntu desktop environment and chroot into it.
EDIT2: moderators marked my topic as duplicate but it's not duplicate of above mentioned topic at all.
I found complete answer of my question. I post the link as a reference to people who seek the same answer:
http://www.turnkeylinux.org/blog/convert-vm-iso
Comment: Yes but this is not related to a problem with Ubuntu.
Comment: @Rinzwind
I used vdi tag. It's not Ubuntu specific question.
Comment: @SylvainPineau
I checked out that link and similar links, they don't mention how to extract root.ext2 filesystem, they only mention how to view filesystems
Answer: I have not tried it, but these could be the steps:

map a host folder as shared folder in virtual box machine.
use dd command from within the vm to raw copy the vm disk to a file in the
shared folder.
use the raw file and dd to write it to a real hardisk.
use something like gparted to strech the partition to the harddisk length, if not same size.
boot for that partition and see it if works.
Comment: Thank you for answer. It might work but I want to know how to  extract ext2 root filesystem into desktop as in lfs live iso image.
Answer: If your VDI is of type static then you can use a loop mount to mount the VDI in your host using ntfs-3g and just accesses it like any other file system.
If it is a dynamic VDI then you can create a temporary VM using a liveCD. Then temporarily release your VDI from your XP VM and assign it to this VM. When you boot the live CD you can then open a command shell and do
<code>    sudo -i
mkidir /xp
mount -t ntfs3g /dev/hda1 /xp
cd /xp
#You can now access and edit the XP VDI
</code>
If you want to move files to and from the host, there are various ways: e.g. a second static VDI which you can then loop mount on your host; good old ftp ...
Comment: Thank you for answer. I ll try your approach but I think you got me wrong, it's not a XP virtual machine. I am on Ubuntu 13.10 platform, and I ll create a VM and create ext2 filesystem to install LFS (linux from scratch) in it then I ll extract root.ext2 filesystem into desktop (if posssible) and mount it in Ubuntu and chroot into it.

How can I extract filesystem from vdi


Scanning 35mm film with Epson 4490 in Ubuntu

Question: I have read the guides on downloading drivers for the Epson 4490 from Epson and Vuescan from Hamrick.com, but am unclear on whether Ubuntu will let me use the film scan utility?
Can anyone confirm I can use all the scan modes in Ubuntu with this scanner before I obliterate my Windows OS?
Thanks
Answer: You can confirm this yourself in about 20 minutes. I assume you already have a CD or USB from which to install from so just boot to it, select "Try Ubuntu", install the drivers and VueScan (yes, in the Live environment), and test it all out.
It'll be slower than a real install but you'll know and you won't touch a real hard disk. Everything will be done in RAM and when you reboot, nothing will persist.
Comment: Perfect, didn't know I could test this with the "try ubuntu" option. Thanks Oli.
Comment: I tried this, Vuescan seemed to install correctly and sees the scanner, but after trying to install the Epson software, I get errors in the software installation: dependency is not satisfiable: iscan-data. Vuescan tells me there is an Epson 4490 there, but then tells me I need to download from Epson. I'm new so apologies for my stupidity. I have tried searching the forums and google but can't get an answer.
Comment: Run sudo apt-get update and try again.
Comment: Thanks Oli, managed to get the software to install without errors but the vuescan app still will not recognize the drivers: ' VueScan found an Epson Perfection 4490, but no Epson software for this scanner was found on your system. Try downloading a driver for this scanner from www.epson.com '
Comment: I installed the three deb downloads: iscan-plugin-gt-x750_2.1.2-1_i386.deb ., iscan-data_1.26.0-1_all.deb ., and iscan_2.29.3-1~usb0.1.ltdl7_i386.deb and ran sudo apt-get update - ubuntu seems to know the scanner is there, but vuescan and imagescan tell me there is no scanner connected. I am running this from the dvd - could this be my problem?
Answer: I decided to take a chance and install Ubuntu despite not getting the scanner up and running from the DVD.  It seems that was the problem.
After installation, I added the 3 .deb files above and it works a treat.


HTML Multiple option Dropdown box + manual input

Question: I need to have an HTML select with multiple selection capabilities. No problem until that, can use  and multiple. But additionally I want the user to manually input another option, think of the options like this:

Please choose at least 2 or Manually input:

Option A
Option B
Option C
Option D
Option E
Other (Please input)

Can this be done? or should I think of other methods like checkboxes and a text input?
Comment: http://stackoverflow.com/a/5629435/1299995
Answer: in case you want the user to input the other option him/herself, then you can use checkboxes and rather activate a textbox in case the user checks the "other" textbox. That is probably the way I would attempt do it.


Is there a way to release (free) captured prisoners?

Question: Is there any way to manually release captured prisoners at your own will? (let them go free)
My specific situation is this:
I have captured lords of a given faction, and that faction has since been defeated. I suspect that I will not receive a ransom for these captured lords anymore, and wish to let them go to free. This will free up a few prisoner slots.

I know that one option is to just let them escape on their own while I hold them in captivity with my army or in a town.
A second option being to put them in one of my town prisons, freeing up my prisoner slots.
A third option that does not apply to lords is to sell prisoners to a Ransom Broker.
A fourth option that does not apply to lords is to release prisoners after winning a battle.

I want to let them go free. Is it possible?
I defeated Kingdom of Vaegirs.

I held some of their lords prisoner before they were defeated. I wish to let them go free. However, I see no way of doing this.

These are the only remaining lords for this faction because I still have them!

Thanks for reading.
Comment: Nope, you can't just place them in your prison... they can escape from there aswell.
Comment: Yes, however I am not asking how to hold onto them, I am asking how to get rid of them. Them escaping is not a problem, it is a solution. Plus, I can leave an infinite number of them in a prison (as far as I know), so it also frees up my prisoner slots.
Comment: Whoops I mistyped there, what I meant was you can just place them in your prison... there is no other way of getting rid of them other then letting them escape.
Comment: You can talk to your faction's Marshall or king, they will often offer to buy prisoners from you.  Not sure if they do so for a defeated faction though.
Comment: @spartacus I made it to my marshal (I am the King) but saw no option to get rid of any prisoners (of a faction that is still in tact). Available options: http://i.imgur.com/sBPXtQb.jpg
Comment: @Lemmings19 There's no option that's always there.  When you sometimes start a conversation with a lord they'll ask to buy a prisoner from you.
Answer: If you own any castles or towns I think you can put all your items in a chest in the lord's hall and all our troops in the garrison.  Go unarmed with no troops with only the lords of the dead faction with you.  Then you get in a battle and let yourself get defeated.  Since all your items are in a chest and all your troops are in a garrison, all you should lose is your prisoners (the lords you want to set free).
Comment: that's one way to do it I suppose...
Answer: After taking time to look for an answer, it would appear that aside from the options I suggested in my question, there isn't any way to manually free lords in order to open up prisoner slots at any given time. The best thing to do seems to be to let them escape on their own over time, or drop them off in a town's prison.
You can let non-lords go free when capturing new prisoners after a battle or hiring troops after a battle, but that's about as close as it gets!
Some additional help, if you drag them around with you (not in a garrison), in 72 hours, they have a 50% chance of escaping from you. Just take a bunch of them and drag them along with your party and do normal stuff until they "escape".
Answer: There is no way to release them in the native game (perhaps with mods, but i haven't researched those). Your best bet is to take them out of your cities garisson and keep them in your personal prisoner inventory. Escape chances for your lord are higher there then in a town, making it easier for the lord to escape. After that it all depends upon luck (i still have two counts as a prisoner in my personal stack, even though both Rhodocks and Swadia were defeated more then 100 days ago. Most of them, including their kings have since escaped and left the realm or joined a new factions (me) since then.
Answer: The easy way to do this:
Step 1: garrison the prisoner in your own castle/ town prison and then Step 2: manually enter your own prison. Talk to your prisoner and there is an option that says "You are free to go".
Also if you use Diplomacy mod, there is an option to release prisoners by talking to the Constable.
It is true that defeat or waiting for escape are alternatives as well.
Answer: I don't have the lord of a faction in my party, but have you tried:
party menu> person you want to disband> clicking the "Talk" option> selecting option like:
Example 1
"We need to separate"
Then
Example 2
"That's right, we need to part ways"
Good luck, hope I helped!
Comment: This will not work, as talking to captured Lords only yields the "Don't you run off!" talk.
Comment: @FEichinger is correct. This doesn't work for prisoners.


Wolfram alpha doesn't allow me to plot and display a shaded area under Gaussian

Question: I quite simply for illustration and teaching purposes want to plot the area under a gaussian between two points and have this shaded. But Wolfram alpha seems to have other ideas. For example:
 integrate gaussian mu=0, sigma=0.1 from 0.3 to 0.6

How can I do this?
Comment: http://mathworld.wolfram.com/GaussianFunction.html Does this help anything?
Answer: I think you mean

To achieve this in WolframAlpha, first of all rewrite gaussian mu=0, sigma=0.1 as N(0,0.1).
Then just specify the limit of PDF: from 0.3 to 0.6. You don't need to specify integrate, WolframAlpha will understand you want P(0.3 < N(0,0.1) < 0.6)
The command will look like: N(0,0.1) from 0.3 to 0.6


Do not request https://fonts.gstatic.com

Question: I am trying to speed up my website and want to get rid off some https://fonts.gstatic.com requestes.
For instance, PageSpeed Insights gives me a warning about "Make sure all text remains visible while loading the web fonts" about https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2
While gtmetrix is displaying this request instead:
https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu4mxK.woff2
Do not know why they are different, but how can I omit this type of request?
I can not find these text strings when I search for them in my WordPress public_html directory using SSH.
PageSpeed Insights :

Gtmetrix:
Comment: I was also trying to do same but for a flutter project, i.e. getting rid of online fonts, and putting in local dir.
Answer: can you add this line.
<link rel="preload" as="font" type="font/woff2" href="https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2" crossorigin>

Answer:
want to get rid off some https://fonts.gstatic.com requests

If you are using Google Fonts, then you cannot. Gstatic.com is a domain that Google owns and uses to serve static content. See this answer on SuperUser.

PageSpeed Insights gives me a warning about "Make sure all text remains visible while loading the web fonts"

I hope you have read the documentation.
When using Google Fonts, add the &display=swap parameter to the end of the Google Fonts URL.
The good news is, following the instructions on Google Fonts will generally handle things for you.

Continue reading iff the above could not satisfy you
For further speedups and/or customization (e.g. reducing the number of preconnects), this is how I handle the issue.
Suppose I want to use the font Comfortaa.
 <link href="https://fonts.googleapis.com/css2?family=Comfortaa&display=swap" rel="stylesheet">

Instead of linking the remote CSS file at https://fonts.googleapis.com/css2?family=Comfortaa&display=swap, I visit the URL, download the CSS file to the server and link to that instead.
This gets rid of the delay caused while establishing connections to fonts.googleapis.com.
Warning:
The CSS files provided by Google Fonts may be changed in future.
It is your responsibility to update those files when modified by Google Fonts.


Why is Chrome Extension JavaScript does not get changed?

Question: I'm trying to build a chrome extension, based on this one
so I have two files: manifest.json and sample.js
I make some changes on sample.js, they sometimes apply when I reload the page, sometimes don't. I try clearing the cache. Again, it sometimes work. Now I'm completely stuck.
Let's say I try to alert something when clicked on a context menu,
function onClickHandler(info, tab) {
 alert("1");
}

then I change it to
function onClickHandler(info, tab) {
 alert("2");
}

but it keeps alerting 1.
I try clearing the cache, closing and re opening Chrome, even uninstalling and re-installing the extension. Nothing works.
I hope I made myself clear. How do I make sure that the extension is up to date with my sample.js file?
Do I need to disable javascript cache somewhere ?
Thanks for any help..
Comment: possible duplicate of [Faster way to modify chrome extension than Remove -> Load unpacked](http://stackoverflow.com/questions/8159273/faster-way-to-modify-chrome-extension-than-remove-load-unpacked)
Answer: You should go to chrome://extensions/ and click "Reload" for your extension. (or press Ctrl/Cmd+R but that will reload all your development extensions which might take longer if you have a bunch)
It's the best way to make sure all your extension files are reloaded.
Another way is to use something like Extensions Reloader. It's an extension that adds a button to your toolbar which will reload your extensions for you. (except for changes to manifest.json, which shouldn't be a problem since that's not the file you'll change the most)
Comment: Manually reloading is ok, I only have one. I just need a 100% sure way to have the latest code running. I will give that extension a try, if reload does not work. Thanks !
Comment: In that case, going to chrome://extensions/ is the way to go.
Comment: Yep, it worked. I will accept your answer in 2 minutes. Thanks again !
Comment: Note that the Reload button (circle arrow icon) is only visible, when there are no errors. (The Error Button appears next to the Remove Button.) Also, you need to press "clear errors" after reloading; they don't clear automatically.


CentOS 6.4 replace "CentOS 6.4" title during boot

Question: I would like to change the "CentOS 6.4" text which is displayed next to the boot status bar during boot with a custom text.

Is this possible, and if so, how?
Thanks,
Alex
Answer: The solution for above query is achieved by Plymouth theme plugin. Change the default "text" theme and program you own customized theme as mentioned here
Answer: A few years later... I ran into the same issue and unable to find doc's online. After reviewing source code in plymouth. The text that is displayed in this screen is extracted from the /etc/system-release file from BOTH the installed operating system and the initrd/initramfs file. If you make changes to both by editing the file and replacing and repackaging the initrd you will see the updated text.


C++, fastest STL container for recursively doing { delete[begin], insert[end], and summing entire array contents}

Question: I have some code and an array where each iteration I delete the first element, add an element at the end, and then sum the contents of the array. Naturally, the array stays the same size. I have tried using both vector and list, but both seem pretty slow.
int length = 400;

vector <int> v_int(length, z);
list <int>   l_int(length, z);

for(int q=0; q < x; q++)
{
    int sum =0;

    if(y)                       //if using vector
    {
        v_int.erase(v_int.begin());    //takes `length` amount of time to shift memory
        v_int.push_back(z);
        for(int w=0; w < v_int.size(); w++)
            sum += v_int[w];
    }
    else                        //if using list
    {
        l_int.pop_front();             //constant time
        l_int.push_back(z);
        list<int>::iterator it;
        for ( it=l_int.begin() ; it != l_int.end(); it++ ) //seems to take much
            sum += *it;                                    //longer than vector does
    }
}

The problem is that erasing the first element of the vector requires that each other element be shifted down, multiplying, by the size of the vector, the amount of time taken each iteration. Using a linked list avoids this (constant time removal of elements), and should not sacrifice any time summing the array (linear time traversal of the array), except that in my program it seems to be taking way longer to sum the contents than the vector does (at least 1 order of magnitude longer).
Is there a better container to use here? or a different way to approach the problem?
Answer: Why not keep a running sum with sum -= l_int.front(); sum += z?
Also the data structure you're looking for with that delete/insert performance is a queue
Comment: With a simple array you can access each element with pointer arithmetic. If you have elements of a certain size then you can just go to the `initial_offset + size * index` to find the element at the index. With a linked list you have to visit the first element, find the link to the next one, visit the next one, repeat until you get to the one you want.
Comment: hey good idea. Btw, is queue faster than list for delete/insert or ~the same speed? Also, out of curiosity, what's with list being so slow for array traversal?
Comment: @Graff yeah but if I already have to excess every element, as in summation, this shouldn't cost much extra time should it?
Comment: For a little more context, the [stl vector](http://www.cplusplus.com/reference/stl/vector/) is similar to a c array and the [stl list](http://www.cplusplus.com/reference/stl/list/) is similar to a linked list.
Comment: @Matt Generally it's much faster to do the pointer arithmetic for a lookup in a vector than to get an iterator to the next element in a list. Also, a queue should be similar in speed to a list for delete/insert - perhaps a tiny bit slower but usually not by much.
Comment: @Graff, Ah, ok. I guess that's about what I figured. I just didn't expect the iterator part to take so much extra time. Thanks.
Comment: The problem is not *really* the pointer indirection - the really painful part is that list elements are scattered throughout memory (each one is individually allocated on the heap, and there is usually at least a 2-pointer overhead between heap allocations), thus the CPU cache keeps getting flushed, and you are waiting for information to crawl its way in from memory.
Answer: Efficient additions and deletions of end elements in a container is what the deque was made for.
If you are just inserting at one end and deleting at the other then you can use a queue


HQL Expression equivalent for data types

Question: Background : I need to create a custom like extension method for linqtohiberante to do the below,
 result.Where(p => p.MyIntColumn.IsLike('%100%') );

so that would output a custom sql as follows.
select * from orders where  CONVERT(VARCHAR, MyIntColumn) LIKE '%100%'

And I'm trying to build the custom expression for that by extending the BaseHqlGeneratorForMethod as shown below.
    public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
            {
                return treeBuilder.Like(treeBuilder.MethodCall("convert",
new[] { "stuck here",  visitor.Visit(arguments[0]).AsExpression() }),
                                        visitor.Visit(arguments[1]).AsExpression());
            }

I need to be able to inject the VARCHAR as a expression to the parameter list of the MethodCall expression. See the text "stuck here" in the above code snippet. Any idea how can I do that.
Thanks in advance
Bumble
Answer: Didn't try it, but I think you have to call treeBuilder.Cast instead of treeBuilder.MethodCall
public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments,
        HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
    {
        return treeBuilder.Like(
            treeBuilder.Cast(visitor.Visit(arguments[0]).AsExpression(), typeof(string)),
            visitor.Visit(arguments[1]).AsExpression());
    }

Comment: i had to extend it a little bit to facilitate '%100%' , other than that this is perfect!
Comment: I got 'Don't currently support idents of type Byte[]' when trying this with a byte array :|


How to customize x-axis in GraphView in android

Question: I am trying to draw a line graph using GraphView in android.
I am able to print labels in the y axis, but the labels in the x-axis don't get displayed, also the points are not plotted correctly with respect to the x-axis. Can someone please help.
Please find my xml code below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.GraphActivity">

    <TextView
        android:id="@+id/linetext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bar Graph"
        android:textSize="16dp"
        android:layout_marginBottom="20dp"/>

    <com.jjoe64.graphview.GraphView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:title="Graph Title"
        android:id="@+id/graph"
        android:layout_below="@+id/linetext"/>

</RelativeLayout>

The activity code is as follows.
package com.example;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.helper.StaticLabelsFormatter;

public class GraphActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.graph_activity_layout);

        // Line Graph
        GraphView line_graph = (GraphView) findViewById(R.id.graph);
        LineGraphSeries<DataPoint> line_series =
                new LineGraphSeries<DataPoint>(new DataPoint[] {
                        new DataPoint(100, -20),
                        new DataPoint(1000, -15),
                        new DataPoint(10000, -10),
                        new DataPoint(12000, -5),
                        new DataPoint(14000, 0),
                        new DataPoint(16000, 5),
                        new DataPoint(18000, 10),
                        new DataPoint(19000, 15),
                        new DataPoint(21000, 20)
                });
        line_graph.addSeries(line_series);
        line_series.setDrawDataPoints(true);
        line_series.setDataPointsRadius(10);

        // set the bound

        // set manual X bounds
        StaticLabelsFormatter staticLabelsFormatter = new StaticLabelsFormatter(line_graph);
        staticLabelsFormatter.setVerticalLabels(new String[] {"-20", "-15", "-10","-5","0","5","10","15","20"});
        line_graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);

        // set manual Y bounds
        staticLabelsFormatter.setHorizontalLabels(new String[] {"0","100","1000","10000","24000"});
        line_graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);

        line_graph.getViewport().setScrollable(true);

    }
}

The graph I got is displayed below.

I get y-axis labels displayed that is -20,-15,-10 etc. But x axis gives trouble. I have 2 concerns

I tried everything but then x-axis labels don't get displayed.
Also I notice that the graph is not plotted correctly based on the x-axis labels that I have mentioned.(Yes i have labelled the x axis unevenly ("0","100","1000","10000","24000"), Is it disallowed in GraphView? hence the graph is plotted wrong?

If that is the case I can use a even distribution, but the display of labels at least is important to me
Can someone please help.
Thanks in advance.
Answer: Use this code:
graph1.getViewport().setYAxisBoundsManual(true);
graph1.getViewport().setXAxisBoundsManual(true);

Answer: click this my output:

use this code
graph1.getViewport().setYAxisBoundsManual(true);
graph1.getViewport().setXAxisBoundsManual(true);

Answer: Make sure to set hardwareAccelerated to true
Simply open the AndroidMainfest of the application then select application tag or select the activity tag if you want to enable hardwareAccelerated for a specific activity , and enter this line
android:hardwareAccelerated="true"


Cast an object back to a value type array

Question: I am using reflection to read properties from an object.
If the value I read is a reference type (for example String[]) I can cast this as Object[] array and loop through the strings in the array.
    String[] Workers = { "Steve", "Sally", "Jim" };
    Object SomeValue = Workers;
    // Prented that SomeValue is returned from reflection
    List<Object> SomeList = new List<Object>((Object[])SomeValue);

However when the object is an array of value types I can't recast it to an array. I've tried everything. C# for some reason won't recast it as an array of ValueType (thought that would probably work).
    Int32[] WorkingHours = { 1, 2, 65, 6 };
    Object SomeValue = WorkingHours;
    // Prented that SomeValue is returned from reflection
    List<Object> SomeList = new List<Object>((ValueType[])SomeValue);

Any suggestions?
Comment: have you try `(IEnumerable)SomeValue`?
Answer:
C# for some reason won't recast it as an array of ValueType (thought that would probably work).

No, it won't work because the representation is different.
The reason covariance works for reference type arrays is that the representation of a reference is the same regardless of the type of object it refers to. That's not the case if you compare value types and reference types.
For example, consider:
byte[] x = { 1, 2, 3, 4 };

Each element of x is just a byte. You can't view that array as an object[] - each element simply isn't a reference.
However, you can fairly easily convert each element via boxing and create a list that way:
List<Object> list = ((IEnumerable) WorkingHours).Cast<Object>().ToList();

Comment: Perfect - that's what I was looking for but couldn't quite get it, thanks!


EventBus: How to keep track?

Question: I am using an event bus (greenrobot) for communication between fragments and activities.
Works great.
But one thing I was wondering about: How do people keep track of where these are fired?
Example: When I see an onEvent() method somewhere, how can I find the places where this gets fired?
Answer: Granted you are using IntelliJ Idea/Android Studio, and the method is onEvent*(E ...):

Ctrl + click on E will move you to E class file
Ctrl + click again on E class (as in e.g. public classE) will show you all the usages of E class in general. You may want to filter out import statements in the show pop out dialog by clicking on the italized, blue i icon.

Bonus:
If the event class has only one constructor, it's better to ctrl + click it instead of class name. This will show you places where the event object is created.
Comment: Problem (for me) is that my `onEvent(E...)` methods do not always follow the principle that `E...` is the source for the `post`. I do have Fragments that fire an event and pass just a data object as the parameter... In these cases this does not work...

EventBus: How to keep track?


Getting the number of rows considering a time frame

Question: I want to get the number of rows of a certain table considering a time frame.
I'm using CakePHP 3.7.
Here you can see my code (from the controller class) :
public function nbOfDefense($dateIn, $dateOut){
        if($dateIn!=null && $dateFin!=null){
            $conditions = array('thesis.date_end BETWEEN ? and ?' => array($dateIn, $dateOut));
            $query = $this->Thesis->find('all',
                array('conditions'=>$conditions));

            die(strval($query->count()));
            return $query;
        }else{
            $query = $this->Thesis->find('all');
            die(strval($query->count()));
            return $query->count();
        }
    }

I'm testing my function through my browser using this URL :
http://localhost:8888/thesis/nbOfDefense/2003-02-01/2019-04-13
What I want my function to do, is to, get in parameters two dates :

If those two dates are not null, you get the number of rows that between the two dates considering a date stored in the table you're consulting.
If the dates are null, then you get the total number of rows of the table.

And return an int, which is the number of rows that are between those two dates.
I feel like the problem here is how I handle my condition, because counting the total number of rows works perfectly (the else part of the code).
The error I have right now with this code is the following :
Cannot convert value of type array to string
it's pointing to this line :
die(strval($query->count()));

I guess the count function returns an array (weird because it doesn't when I count all rows without conditions). I also tried this :
die(strval(sizeof($query->count())));

But I get the same error as before (cannot convert array to string)
I must be missing something but I don't know what...
Answer: Try:

use Cake\ORM\Query;
use Cake\Database\Expression\QueryExpression;

class MyController extend AppController
{

public function nbOfDefense($dateIn = null, $dateOut = null)
{
    $query = $this->Thesis->find();
    if ($dateIn && $dateOut) {
        $query->where(function (QueryExpression $exp, Query $q) use ($dateIn, $dateOut) {
            return $exp->between('date_end', $dateIn, $dateOut);
        });
    }
    $count = $query->count();

    $this->set(compact('query', 'count'));
}
// ..
}

and read:
https://book.cakephp.org/3.0/en/orm/query-builder.html
https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html
Comment: Oh my god! Yes that's it, thank you so much for your help!
Comment: Thank you for your answer! When I try your code, if the dates are null, it works perfectly. But when I try to set the dates (either by using the URL or by writing $dateIn="2003-02-01"; at the beginning of my function), I get the error : Argument 1 passed to App\Controller\ThesisController\::App\Controller\{closure}()   must be an instance of App\Controller\QueryExpression, instance of Cake\Database\Expression\QueryExpression given, called in .../cake3_7/vendor/cakephp/cakephp/src/Database/Query.php. So I am not sure how I can test that
Comment: @createurx add: ```use Cake\ORM\Query;```and
```use Cake\Database\Expression\QueryExpression;```


What is the function of a check valve on the inlet of a household macerator pump?

Question: Macerators sometimes require check valves on the inlet for shower waste. I'm thinking the low rate of flow from a shower might not be enough to trigger macerators activated by air switches, so the valve creates lets water from the shower through without letting air out, triggering the pump.
Would that be correct?
Comment: Brand specific/product specific instructions are O/T per the [faq].
Comment: Edited question to eliminate any semblance of product specificity.
Answer: The check-valve prevents waste from flowing backwards after the macerator pump stops.
Macerator pumps usually can't stop backflow by themselves. The pump has to let some solids through so the pump mechanism isn't water-tight. If it was, the solids would wear the those water-tight edges down quickly and the pump would no longer be water-right.
Answer: This isn't really something we can answer specifically as it's brand specific.  Contact the manufacturer or use the manual.
Why would you think we know better than the manufacturer?
Comment: Air switches and check valves are common concepts in fluid dynamics. Manufacturer unresponsive. Last manual I had for a ceiling fan was blatantly incorrect. Many SE sites I visit have engineers on board who understand the underlying principles and how such machines work, regardless of brand.


parsing a xml response fatal error

Question: Formatted XML:
<code><?xml version="1.0" encoding="UTF-8"?>
<ns2:HotelListResponse xmlns:ns2="http://v3.hotel.wsapi.ean.com/">
   <customerSessionId>0ABAAA86-43C0-8659-1492-40BA6A6C9ED0</customerSessionId>
   <numberOfRoomsRequested>1</numberOfRoomsRequested>
   <moreResultsAvailable>true</moreResultsAvailable>
   <cacheKey>-643c0865:14940ba6a6c:ed1</cacheKey>
   <cacheLocation>10.186.170.134:7300</cacheLocation>
   <cachedSupplierResponse supplierCacheTolerance="NOT_SUPPORTED" cachedTime="0" supplierRequestNum="226" supplierResponseNum="25" supplierResponseTime="808" candidatePreptime="9" otherOverheadTime="17" tpidUsed="5001" matchedCurrency="true" matchedLocale="true" />
   <HotelList size="25" activePropertyCount="246">
      <HotelSummary order="0" ubsScore="1077510">
         <hotelId>164116</hotelId>
         <name>Sheraton Seattle Hotel</name>
         <address1>1400 6th Ave</address1>
         <city>Seattle</city>
         <stateProvinceCode>WA</stateProvinceCode>
         <postalCode>98101</postalCode>
         <countryCode>US</countryCode>
         <airportCode>SEA</airportCode>
         <supplierType>E</supplierType>
         <propertyCategory>1</propertyCategory>
         <hotelRating>4.0</hotelRating>
         <confidenceRating>30</confidenceRating>
         <amenityMask>262147</amenityMask>
         <tripAdvisorRating>4.0</tripAdvisorRating>
         <tripAdvisorReviewCount>2074</tripAdvisorReviewCount>
         <tripAdvisorRatingUrl>http://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/4.0-12345-4.gif</tripAdvisorRatingUrl>
         <locationDescription>Near Pike Place Market</locationDescription>
         <shortDescription>&lt;p&gt;&lt;b&gt;Property Location&lt;/b&gt; &lt;br /&gt;With a stay at Sheraton Seattle Hotel, you&apos;ll be centrally located in Seattle, steps from 5th Avenue Theater and Washington State Convention Center. This 4-star</shortDescription>
         <highRate>145.8</highRate>
         <lowRate>145.8</lowRate>
         <rateCurrencyCode>USD</rateCurrencyCode>
         <latitude>47.61017</latitude>
         <longitude>-122.33357</longitude>
         <proximityDistance>11.115907</proximityDistance>
         <proximityUnit>MI</proximityUnit>
         <hotelInDestination>true</hotelInDestination>
         <thumbNailUrl>/hotels/1000000/30000/25300/25290/25290_88_t.jpg</thumbNailUrl>

         <RoomRateDetailsList>
            <RoomRateDetails>
               <roomTypeCode>200419433</roomTypeCode>
               <rateCode>202558544</rateCode>
               <maxRoomOccupancy>4</maxRoomOccupancy>
               <quotedRoomOccupancy>2</quotedRoomOccupancy>
               <minGuestAge>1</minGuestAge>
               <roomDescription>Traditional Room</roomDescription>
               <propertyAvailable>true</propertyAvailable>
               <propertyRestricted>false</propertyRestricted>
               <expediaPropertyId>25290</expediaPropertyId>
               <RateInfos size="1">
                  <RateInfo priceBreakdown="true" promo="true" rateChange="false">
                     <RoomGroup>
                        <Room>
                           <numberOfAdults>2</numberOfAdults>
                           <numberOfChildren>0</numberOfChildren>
                        </Room>
                     </RoomGroup>
                   <ChargeableRateInfo averageBaseRate="145.8" averageRate="145.8" commissionableUsdTotal="291.6" currencyCode="USD" maxNightlyRate="145.8"        nightlyRateTotal="291.6" grossProfitOffline="35.27" grossProfitOnline="58.82" surchargeTotal="57.34" total="348.94">
                        <NightlyRatesPerRoom size="2">
                           <NightlyRate baseRate="145.8" rate="145.8" promo="false" />
                           <NightlyRate baseRate="145.8" rate="145.8" promo="false" />
                        </NightlyRatesPerRoom>
                        <Surcharges size="1">
                           <Surcharge type="TaxAndServiceFee" amount="57.34" />
                        </Surcharges>
                     </ChargeableRateInfo>
                     <nonRefundable>true</nonRefundable>
                     <rateType>MerchantStandard</rateType>
                     <promoId>205881880</promoId>
                     <promoDescription>Sale! Save 10% on this Stay.</promoDescription>
                     <promoType>Standard</promoType>
                     <currentAllotment>678</currentAllotment>
                  </RateInfo>
               </RateInfos>
            </RoomRateDetails>
         </RoomRateDetailsList>
      </HotelSummary>
</code>
The error gives me an [Fatal Error] :1:1:1 content not allowed in prolog at the beginning of the line .
Say i only want to get the name of the hotel and the price rate , could someone help me to get through the error at the beginning ?
Thank you .
Comment: Are you absolutely sure there is NOTHING before  ? Not even some whitespace?
Comment: Just remove first line of your xml ` ?` and try again
Comment: As well this problem occurs, if you are getting null value of xml, I mean to say your xml file is blank.
Answer: "Content not allowed in prolog" can have a wide variety of causes, including:

there's something before the XML declaration, e.g. a newline character
the file starts with a BOM (byte order mark) and you're using an XML parser that doesn't recognize a BOM
the file you are parsing is not the file you think you are parsing: check the API you are using

parsing a xml response fatal error


How to evaluate this double integral $\int_0^1 \int_0^1 \cos (n\pi (x+y))\text{d}x\text{d}y$?

Question: Evaluate :
$$\int_0^1 \int_0^1 \cos (n\pi (x+y))\text{d}x\text{d}y$$
Can someone please point me in the correct direction? Thanks
Comment: What have you tried? Where are you stuck? Also you have three differential symbols but only two integral symbols. Perhaps you meant

$$
\int_0^1\mathrm dx\int_0^1\mathrm dy\cos (n\pi (x+y))\;?
$$
Answer: $$\begin{align}\int_0^1\mathrm dx\int_0^1\mathrm dy \:\cos (n\pi (x+y)) &= \int_0^1\mathrm dx\int_0^1\mathrm dy \: [\cos{n \pi x} \cos{n \pi y} - \sin{n \pi x}\sin{n \pi y}] \\ &= \int_0^1\mathrm dx \:\cos{n \pi x} \int_0^1\mathrm dy \cos{n \pi y} - \int_0^1\mathrm dx \:\sin{n \pi x} \int_0^1\mathrm dy \sin{n \pi y} \\ &= \frac{\sin^2{n \pi} - (1-\cos{n \pi})^2}{n^2 \pi^2}\\ &= -\frac{1 -2 \cos{n \pi} + \cos{2 n \pi}}{n^2 \pi^2}\end{align}$$
Comment: How are they 0?  You are assuming that $n$ is an integer, when there is no such assumption.  Anyway, $\cos{2 \pi n} = \cos^2{n \pi} - \sin^2{n \pi}$.
Comment: Oh, I see. So you did not assume that $n$ was an integer. Now it makes sense.
Answer: $$ \int_0^1 \cos(n \pi (x + y)) dx = \frac{1}{n\pi} [\sin(n\pi(y+1)) - \sin(n\pi y)]$$
$$\int_0^1 \int_0^1 \cos(n\pi(x+y))dx dy = \int_0^1 \frac{1}{n\pi} [\sin(n\pi(y+1)) - \sin(n\pi y)] dy = \frac{1}{n^2\pi^2}(2\cos(n\pi) - 1)$$
Comment: Have you checked your result at $n=0$?


How to set android notification so that the text is visible on all devices

Question: How can I specify android Notification so that the text is visible on all devices?
Some devices has black background in the notification area, and if the text is black, it is not visible.
And other devices has white background in the notification area.
Thank you.
Comment: possible duplicate of [Custom notification layouts and text colors](http://stackoverflow.com/questions/4867338/custom-notification-layouts-and-text-colors)
Answer: You can access the systems color attributes and use it in your layout.
Use for example
android:textColor="?android:textColorPrimary"

to set the text color of a TextView to the primary text color of the current theme. There are tons of other attributes, have a look at Referencing Style Attributes and the attributes list.
Answer: You should create your own view with a set background, and display your text using that. :)
Check out the documentation to get some sample code.
Answer: Use
android:textColor="?android:textColorPrimary"

and/or
android:textColor="?android:textColorSecondary"

in combination with
android:background="?android:colorBackground"

This refers to native attributes in the current style, so that your notification will always be legible.


Conditionally sample from texture in shader

Question: I'm building a little 2D graphics library in Rust/WGPU as a means to learn graphics programming. I want to draw an outline around a shape and specify the outline's color. All of my shapes have a texture, either explicitly set or a 1x1 white pixel otherwise. When I draw a shape with the default white texture, the outline is as expected but when I do the same with another texture set, it samples the color and sets the outline to it.
Here's  an example of the problem: the central rectangle has a white outline as desired, but the top left square has a red outline but it should be white.

The outline calculation is based on this answer and I'm calculating a triangle list so that I can use the same pipeline as the main shape which is also using a triangle list. Relevant aspects of my shaders and data structures are as follows:
struct Vertex {
    @location(0) coords: vec2<f32>,
    @location(1) color: vec4<f32>,
    @location(2) tex_coords: vec2<f32>,
}

struct VsOut {
    @builtin(position) position: vec4<f32>,
    @location(0) color: vec4<f32>,
    @location(1) tex_coords: vec2<f32>,
}

@vertex
fn vs_main(vertex: Vertex) -> VsOut {
    ...

    return VsOut(
        vertex.coords,
        vertex.color,
        vertex.tex_coords,
    );
}

@group(1)
@binding(0)
var r_sampler: sampler;
@group(1)
@binding(1)
var r_texture: texture_2d<f32>;

@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
    let sample = textureSample(r_texture, r_sampler, in.tex_coords);
    return sample * in.color;
}

I don't want to change pipelines to draw the border and I'd like to avoid changing bind groups (because of instancing). How can I conditionally decide in the shader whether to sample from the texture or not?
Comment: It would be helpful if there were more information on how the outlines are being drawn,  the shader code would be helpful as well.
Answer:
How can I conditionally decide in the shader whether to sample from the texture or not?

Abstractly, this is simple:

Add a vertex attribute that specifies whether to use the texture or not. Set that attribute appropriately for your outline and your fill (which I understand to be made of separate triangles).

Pass the attribute on to the fragment shader.

In the fragment shader,
let sample = textureSample(r_texture, r_sampler, in.tex_coords);
if in.use_texture {
    return sample * in.color;
} else {
    return in.color;
}

(The textureSample() call is outside of the if because it needs to be in "uniform control flow"; this can be avoided but that's another entire topic.)
However, you don't necessarily need to introduce a separate attribute; you can use one that already exists. For example, you could give all the border triangles texture coordinates of [-1, -1], which are clearly not meaningful to the texture (…unless you're using repeating textures). Or, if you never actually want to color-tint a texture, you could designate a particular color value to mean "use texture".

Or, instead, you can make sure your textures always have at least one white texel. This is a more appropriate solution if your application uses a texture atlas (unrelated textures arranged inside only one actual texture object) already.

Or if you only ever want to draw rectangles, then you can stretch the texture coordinates a bit in your mesh construction and draw a border that way, instead of using extra triangles:
if any(in.tex_coords < 0.0) || any(in.tex_coords > 0.0) {
    return sample * in.color;
} else {
    return in.color;
}

(Since you're using wgpu specifically, I'll mention that you can also use clamp to border to implement this directly in the sampler rather than in shader code. However, that's an extension and is not supported in WebGPU proper.)
Comment: I thought about both the flag field in the vertex and the tex coords options. I hadn't considered the latter would have implications with repeating. I like the texture atlas option but think I'll go with the vertex attribute for simplicity.
Comment: I'd be interested to know how to avoid declaring the sampler outside of the if statement - https://computergraphics.stackexchange.com/questions/13729/how-to-avoid-declaring-sampler-outside-of-statement


Continuous grep, output at same spot on console

Question: I use
tail -f file | grep pattern

all the time for continuous grep.
However, is there a way I can make grep output its pattern at the same spot, say at the top of the screen? so that the screen doesn't scroll all the time?
My case is something like this: tail -f log_file | grep Status -A 2 will show the current status and what changed it to that status. The problem is the screen scrolls and it becomes annoying. I'd rather have the output stuck on the first 3 lines in the screen.
Thank you!
Comment: Not exactly the same, but [watch](http://linux.die.net/man/1/watch) comes to mind as a tool that keeps output at the top of the screen.
Comment: Try running it through `sed` and appending a `\r` to the end of each line.
Comment: @MarkSetchell You'd need to clear the screen/lines too or you'll get the standard sort-of overwriting artifacts. But that's an interesting idea.
Comment: @EtanReisner I'll leave it to you to develop - I'm busy for the moment :-)
Comment: Something like this `tail ...| sed "s/^/$(tput clear)/"`
Comment: Look at multitail, which has many features that might help.  http://www.vanheusden.com/multitail/
Answer: you could use the watch command; which will always execute the same command, but the position on the screen will stay the same. The process might eat some more CPU or memory though:
watch "tail file | grep pattern"

by default watch executes that command every 2 seconds. You can adjust up to 0.1 seconds using:
watch -n 0.1

NOTE
As noted by @etanReisner: this is not exactly the same as tail -f: tail -f will change immediately if something is added to your logfile, the watch command will only notice that when it executes, ie every 2 (or 0.1 seconds).
Comment: You'd need to quote that `watch 'tail file | grep pattern'` to make it work I think. Otherwise you'd be grepping the watch output which likely isn't what is wanted.
Comment: Also this isn't quite the same as `tail -f` even at `0.1` if the log is filling really fast.
Comment: thanks for the two very constructive comments! I know it isn't quite the same, so I added this remark.
Comment: Another difference between `tail -f` is that this will continually grep the last 10 lines of the file. Assuming this runs every 2 seconds, it could have repeats.
Comment: there will not be repeats; since it will always remove its previous output
Answer: Assuming you are using a vt100 compatible emulator...
This command will tail a file, pipe it into grep, read it a line at a time and then display it in reverse on the top line of the screen:
TOSL=$(tput sc;tput cup 0 0;tput rev;tput el)
FROMSL=$(tput sgr0; tput rc)
tail -f file | grep --line-buffered pattern | while read line
do
    echo -n "$TOSL${line}$FROMSL"
done

It assumes your output appears a line at a time. If you want more than one line, you can read more than a line, but you have to decide how you want to buffer the output. You could also use the csr terminfo command to set up an entire separate scrolling region instead of just having one line.
Here is the scrolling region version with a ten line status area at the top:
TOSL=$(tput sc; tput csr 0 10; tput cup 10 0;tput rev;tput el)
FROMSL=$(tput sgr0; tput rc;tput csr 10 50;tput rc)
tail -f file | grep --line-buffered pattern | while read line
do
        echo -n "$TOSL${line}
$FROMSL"
done

Note that it is not impossible that your display will be corrupted from time-to-time as it could be that the output from your main shell and your background task get mixed up.
Answer: Simply replace the newlines with carriage returns.
tail -f file | grep --line-buffered whatever | tr '\012' '\015'

The line buffering is to avoid jumpy output; see http://mywiki.wooledge.org/BashFAQ/009
This is quick and dirty.  As noted in comments, this will leave the previous contents of the line underneath, so a shorter line will not completely overlay a longer line.  You could add some control codes to address that, but then you might as well use Curses for the formatting too, like in rghome's answer.


On iOS, left flex-Item collapses when many inline elems on the right. Workaround?

Question: I noticed that when there are many inline elements in the right flex-item, the left flex-item is somehow collapsed, on iOS (or iPad. I don't have an iPhone):

    Wanna Stay Center n Don't Push Me.

    Push!!
    Push!!
    Push!!
    Push!!
    Push!!
    ...

https://jsfiddle.net/jpLo0ava/2/
I realized that this happens on both of Chrome and Safari. Is this a brower bug or is there any wrong css usage? How should I handle this if I want to make the left text stay vertically in the middle?
Comment: Tested in iPad Safari, and layout working fine. Left item not collapsing; stays vertically centered.
Comment: @Michael_B Really? After a day, I'm still struggling with this issue...
Answer: All right, setting flex-shrink: 0; on the left worked for me...


No Internet Connection Even Connected Iphone App

Question: I have made some apps with xcode7 (2.3) (Swift) for iphone and ipad, all works fine but there is one major problem in my Reachability, it says "No Internet Connection" Even i am connected to internet via cellular data but when on wifi it works fine..
The Webview still load in background but there is error "No Internet Connection Found" In front, so users will close my app as they will see the error..
please help me out guyz..
this is my code:
override func viewDidAppear(animated: Bool) {
    if Reachability.isConnectedToNetwork() == true {

        print("Internet connection OK")

    } else {

        print("Internet connection FAILED")

        let ViewController = UIAlertController(title: "Error!", message: "No Internet Connection Found", preferredStyle: .Alert)

        let alertAction = UIAlertAction(title: "Dismiss", style: .Destructive) { (action) in

            print("Dismiss button tapped!")

        }

        ViewController.addAction(alertAction)

        presentViewController(ViewController, animated: true, completion: nil)

    }

}

and this is my Reachability File
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
    if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
        return false
    }

    let isReachable = flags == .Reachable
    let needsConnection = flags == .ConnectionRequired

    return isReachable && !needsConnection

}

}
Answer: Try this
class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
            SCNetworkReachabilityCreateWithAddress(nil, $0)
        }
    }) else {
        return false
    }

    var flags: SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)

    return (isReachable && !needsConnection)
}


Facebook API 2.2 - me/accounts - returns array(0)

Question: I'm actually having troubles with the graph API :
https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts&version=v2.2&
I've been generating an access token with the extended permission 'manage_pages' and i'm trying a request on the edge 'me/accounts'.
The result is always :
{
  "data": [
  ]
}

But I wished to get a page access token instead.
Is this a normal behavior, or did I miss something?

I also tried with the php SDK 4.0 with a short-lived and a long-lived token and got the same result...
My code is here:
$app_id             = '-hidden-';  //Facebook App ID
$app_secret         = '-hidden-';  //Facebook App Secret
$long_lived_token   = '-hidden-';  // tested at https://developers.facebook.com/tools/debug/
                                   //and giving  - Expires :1429438313 (in about 2 months)

FacebookSession::setDefaultApplication($app_id , $app_secret);
$session = new FacebookSession($long_lived_token);

if ($session) {
    try {
        $user_permissions = (new FacebookRequest($session, 'GET', '/me/permissions'))
            ->execute()->getGraphObject(GraphUser::className())->asArray();

        $found_permission = false;
        foreach($user_permissions as $key => $val){
            if($val->permission == 'manage_pages'){
                $found_permission = true;
            }
        }

        // if we got manage_pages
        if($found_permission){
            $user_token = (new FacebookRequest($session, 'GET', '/me/accounts'))
                ->execute()->getGraphObject(GraphUser::className())->asArray();
            var_dump($user_token); //array(0) { }  -  Why?? Is this normal??
        } else {
            echo "Manage pages not granted!";
        }

    } catch(FacebookRequestException $e) {
        echo "Exception occured, code: " . $e->getCode();
        echo " with message: " . $e->getMessage();
    }
}

Thanks for your help!
Comment: No. Page access token are only used for pages. Not for user profiles.
Comment: Are you sure manage_pages was approved? the call to `//accounts` will return an empty array unless you have that permission, or if the user doesn't admin any pages
Comment: I'm sure manage_pages was approved (this is what I tested in my php script) - but for the second part of your comment there is something I don't get: how come an user doesn't admin any pages? I mean, any user should at least admin his fb-Wall, doesn't he?
Comment: Thanks a lot, this is what I didn't get. My question is useless, so...
Answer: My user didn't have any pages to admin, this is why the array is empty.
I guessed page access token could be use to manage profile but I was wrong.
Answer: For anyone who had this problem and still couldn't solve, my problem is that I had generated a access_token before I was granted the admin privilege in the page I was looking for and because of that, I don't know why, I couldn't retrieve the page. I then deleted the access from my facebook page and when I generate a new token, it worked.


Can't find desktop shortcuts

Question: I updated Ubuntu to 14.04 about two weeks ago. In this last week or so I have noticed I can't find any of my desktop shortcuts. None of them are there. I can go to Desktop in Files and they will all be there, they just don't appear on my desktop until I go to the Desktop file in Files. Does anyone know how to fix my problem?
Answer: What exactly do you mean? If you mean that nothing shows up on your desktop,  no icons or anything, just the background,  then you should try my fix: install gnome-tweak-tool and click around until you find a toggle for icons on the desktop. It fixed my problem immediately (even though it took me hours to figure out this solution).
Answer: Maybe i didn't understand your question.
Anyway, did you see the standard shortcuts tab on Settings ?
They are on

System Settings > Keyboard > Shortcuts

Can't find desktop shortcuts


problem to create pattern like minesweeper with C#

Question: first at all, i'm new at C#, so, I apologize if I ask something somewhat "so newbie". Well, here the thing:
I'm trying to create a pattern, just like the game: Minesweeper 'cause i'm making a simple game, a chess game, so my big problem right now is that i can't create the columns efficiently, so, here's my code:
class chessGame
{
    static void Main(string[] args)
    {
        const string EX = "X";
        const string OU = "O";
        const int VALUE_X = 8;

        int numRows = 0;
        int numCol = 0;

        while (numRows < VALUE_X)
        {
            for (numCol = 0; numCol < VALUE_X; numCol++)
            {
                Console.WriteLine(OU);
            }
            for (numRows = 0; numRows < numCol; numRows++)
            {
                Console.WriteLine(EX);
            }
            Console.WriteLine();
        }
        Console.ReadLine();
    }
}

also, i don't know at all if that's the way create the columns and rows with that nested loop, so, if someone can help me with this, or just someone can help me to do it right with my actual code, thank you so much!
and for the record, here's what i see in the console right now:

beforehand, thank you for your advices to all of you guys!
Comment: It might be easier to track the state of objects on your board in a 2D array. For instance `var grid = new int[8, 8];` And then you can iterate over the contents in nested for loops, one for each row, and an inner loop for each cell in each row: `for (int i=0; i<8; i++) { for (int j=0; j<8; j++) { Console.Write(grid[i, j]); } Console.Write('\n'); }`
Answer: WriteLine, as the name implies, writes an entire line (and puts a newline at the end). Not so great for doing more than one column in your setup!
A typical solution is to just use Console.Write, sometimes with Console.SetCursorPosition so you can write individual "cells" at a time.
Another fairly simple approach is to pre-compute each row as a single string, then WriteLine that.
Either way, you'll need to rework your loops fairly significantly to get the effect right.
Comment: @Diego He meant the way you used the `Console.WriteLine()` it is not great for what you are trying to achieve. The way your logic is done could be fix using the solution he gave but if you are willing to change the way your loop works you can manage to use `Console.WriteLine()` properly
Comment: when you say that is not great to do more than one column, i mean.. i have to do an 8 x 8 pattern, so, it's better the typical solution that you said? , but, i also gonna try to do each row as single string! :)
Comment: @Franck thanks, now I understand, gonna practice more, thanks for the advice. :)
Answer: To get started, you want to change the two inner WriteLine() calls to Write().
But really, you want to start thinking in terms of a the whole board, where you have a 2D array to represent the status of the board. Then write a function to output the whole array.
Answer:         const string EX = "X";
        const string OU = "O";
        const int VALUE_X = 8;
        bool writeToggle = true;
        int numRows = 0;
        int numCol = 0;

        for (numRows = 0; numRows < VALUE_X; numRows++)
        {
            for (numCol = 0; numCol < VALUE_X; numCol++)
            {
                if (writeToggle)
                {
                    Console.Write(EX);
                }
                else
                {
                    Console.Write(OU);
                }
                writeToggle = !writeToggle;
            }
            Console.WriteLine();
        }
        Console.ReadLine();

Here is some code which should generate your pattern. Note the use of Console.Write instead of Console.WriteLine so it does not skip a line everytime a character is printed. Also, the bool writeToggle is used to alternate between X and O.
Comment: bro, thank you so much for taking the time to do that, really apreciate it, works perfectly! so, gonna practice more with this, also, that `writeToggle` kinda confused me, but thanks anyway, with time i'll be able to understand this completly!


"mplayer -vo caca fma.avi" lags, how can i skip frames so it doesn't lag

Question: "mplayer -vo caca" looks funny and enjoyably fun to watch in breaks, especially as a screen saver!
Unfortunately it lags, and (since video/asci is synced to sound,) sound is fragmented ( "s", pause, "o", pause, pause, "u", "n", pause, "d").
What command can i add to
mplayer -vo caca fma.avi

so that it plays in real time, I don't care (and am hoping actually) if frames are skipped, I just want to see funny frames of some funny avis (of course ideally i would just like to watch an episode without frame skips or lags between frames, and my card is not actually low end, especially for asci decoding, but it is an experimental feature, so cant actually complain)
How to edit the above command so movie is viewed(and heard) at 1x speed?
Answer: The MPlayer docs will usually suggest some combination of the following:
Try some of the lavdopts,
    e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.
- Broken file
  - Try various combinations of -nobps -ni -forceidx -mc 0.
- Slow media (NFS/SMB mounts, DVD, VCD etc)
  - Try -cache 8192.
- Are you using -cache to play a non-interleaved AVI file?
  - Try -nocache.

And perhaps this will be enough for you? BTW for the ultimate coolness you shoud try -vo matrixview  :).


Update AdMob SDK from v6.12.2 to v7.8.1

Question: I got a old project with admob sdk version 6.12.2 and I need to update the sdk.
from where to start ?
1) I try to delete the old folder of version 6.12.2 and after that install    admob cocapods and I got 18 linker errors.
2) I try to download the new sdk framework and replace it with the old and still have a errors.

Warning: Multiple build commands for output file
Undefined symbols for architecture arm64
linker command failed with exit code 1 (use -v to see invocation)

what I do wrong ?
Comment: This is at least one of your issues: [Admob SDK - iOS -File not found](http://stackoverflow.com/a/28586662/2108547)
Comment: Also, 7.9.0 is the newest version of AdMob at the moment: [Google Mobile Ads SDK](https://firebase.google.com/docs/admob/ios/download)
Answer: I solved this by change this from no to yes !
Comment: awesome, i have no idea about this options,
Thanks

Update AdMob SDK from v6.12.2 to v7.8.1


Lost linebreaks in Chrome console

Question: In Chrome's console (Tools » Developer Tools) the script I'm debugging is showing up without linebreaks even though the actual file has them. This has happened to me before, but I can figure out if it's something with the spaces in the file or a setting in Chrome. But it's pretty impossible to debug something when every error comes up as being on line 1. I tried restarting Chrome but no dice. Any idea how to get it back to normal?
Comment: have you tried it with firebug?
Comment: @AndréAlçadaPadez It's fine in Firebug in Firefox. But I want Chromeness ;)
Answer: It sounds like the file has been minified. Do you know if it's run through any kind of build process before you're looking at it?
If not, I'm not sure exactly why that might be happening. There is a halfway decent workaround:
Open the script in the Scripts tab, and click the <code>{}</code> prettyprint button at the bottom to restore the formatting. It's kind of annoying to have to do that all the time, though.
Is there a public link we could see? I can imagine that there might be some line-ending issues if the file was created on one platform (Mac/Linux/Windows) and is being viewed on another. Haven't run into this one myself yet.
Comment: Thx, nah it's not minified. That button didn't do it, but it'good to know about. :]
Comment: Copying it to to a new file fixed it.
Comment: I'm not sure what caused it but I had done a find and replace from tabs to spaces. But I do that all the time so I don't know if that was it or not.
Comment: I doubt it was the find and replace. Weird. Glad you got it worked out, though. :)
Comment: I think the line-endings did it even though I would expect Chrome to handle the UNIX newlines correctly.
Answer: Open your file with Notepad or some other editor and save it again. It seems like you ran into the same problem as the one mentioned here.
http://184.108.40.206/support/forum/p/Chrome/thread?tid=0936a4d8f8b915b5&hl=en
If that doesn't work, use the pretty print button :-)
Comment: Just fyi, it looks like that URL is too old now and doesn't show the forum message anymore.
Answer: I had this problem and it was the EOL line endings. I changed them from Mac Classic (\n) to Windows Dos (\n\r).

Lost linebreaks in Chrome console


Why does my thermostat require 240volts?

Question: Purchased smart thermostat from China still in transit, my old thermostat has two wires only from ducted gas heating unit was powered by 2-1.5 volt batteries.
The new thermostat requires a hard wire power source ,no batteries.
The connection at back of thermostat states 95-240 ac volts L and N , I gather line and neutral . See image.
My question is why do you need so many volts to power the display ?
Is it simply the fact that most households already have 110 or 240 volts (I live in Australia) supply so that's how they design them.
I just want to make sure that I don't damaged the unit by hooking up 240 volt power.
Comment: I had vague idea this might be the case, thanks for clarifying in detail, much appreciated.
Answer: You kind of answered your own question: "hard wire power source, no batteries".  If the thermostat requires its own power source and doesn't use batteries, then normal line and neutral household power is needed, that would be 120/204 volts. The line and neutral more than likely feed a transformer inside the unit that steps down the voltage to what the display requires.
Comment: Not sure if you concluded that my thermostat is a 'misfit' from what I implied from reading my post or you concluded because I mentioned the word ' china'.
Comment: I never concluded it was a misfit. I do know that much of the stuff from China lacks certification.
Comment: Sorry jack, your post answered my question for someone else posted it was a misfit, sent my reply to you by mistake, new to this forum, again sorry.
Comment: @Tonedown  Not to worry, we're all friends here trying to help people and learning along the way.
Answer: Why is your thermostat a misfit?  Because you bought random stuff from China, instead of safety-certified domestic stock designed for AU homes from reliable vendors.   Send it back and get something appropriate.
Well, I'm not exactly sure how your old thermostat worked.  I mean, obviously, your thermostat is set up as a "shunt, or don't" -- just like every thermostat on earth prior to smart 'stats.  The question is, which voltage does your system operate at?
For instance, US systems use a low voltage 24VAC pilot signal to operate thermostats on a  ducted gas system.  UK systems hotshot 240V straight to the thermostat.  Australia tends to pick and choose whose conventions they follow, so I'm not sure which system you need.  You can ascertain this by measuring voltage across the existing thermostat terminals when the thermostat is NOT calling for heat.  (when it's on, the difference will be 0-1 volt).
If your controls are low-voltage, then this thermostat is a misfit for your application.
Otherwise, you have the classic problem of any smart-switch or smart-stat installation: no "neutral" or "C-wire".  (different scopes but the same problem).  You will need to replace your thermostat wiring with 3-core wire + earth.
Comment: Do the UK thermostats that operate at line voltage (240 VAC) connect with the same small diameter wires we use for US residential 24 VAC thermostat control wires? I guess in the UK there are low current fuses protecting the wire?
Comment: @JimStewart No, UK 'stats use normal power wires, they don't have a small thermostat cable.
Answer: The way "universal power" devices or devices with a 90-240v input range work is with a power supply called a switching power supply.
These supplies take the available AC power and using electronics convert whatever is there to a lower voltage in most all cases , rectify it into dc (3-15v is the nominal range).
These particular switching supplies are called "buck supplies" as the voltage is reduced so any AC input in the range will be used to power the electronics.
You can usually tap the hot lead to power the electronics but a neutral may be needed.
In the past there were specific voltage devices because there was a transformer that is a fixed device to create the low voltage for the electronics, solid state electronics now make the power supply's much smaller and lighter and the voltage is created from whatever is available thus the term universal. The mfg only has to make 1 model and and it can work anywhere.  And you won't damage it because it is designed to work in that range.
Comment: I had vague idea this might be the case, thanks for clarifying in detail, much appreciated.


When do you choose quantitative research over qualitative research?

Question: I want to know some of the discerning factors of a product that makes you choose quantitative over qualitative research and vise versa at any given time during a project.?
Please elaborate when and why you choose one over the other.
When does one give more pertinent information than the other?
What makes it take priority?
Answer: Qualitative research is good to use at the beginning stages of product development (Interviews i.e.) because you want to gain insights in pain points from the user, that your product can ideally solve. Its also often used after prototyping or design part and prior to development, when you want to test overall design of the product. Quantiative on the other hand you can use to test specific elements of a product and to get exact data. It can be used as follow up to Interviews to get exact numbers and confirm on what to focus on in product development. It can be also used after product is designed / developed, to test and improve performance of specific features.
Comment: Thanks @xul. Do you have any specific examples?
Comment: You want to build an sport events app. First questions for you are why and how users will use your app. You want to know what functionalities you need, and what to place on screen in your designs. In this very begining Qualitative methods with open ended questions, in form of Interviews are good for you.  You get insight into peoples habbits, and they give you ideas on what to develop.
Comment: You have finished first version of website design, you have clickable protoype. It makes no sense for you to test it against measurments Quantitative, than you want to check general design. You want to check do people find menu, search and all important elements on your site, as also how they feel about your site. You go again with Qualitative, open ended questions. You gain insights in what they think about your site, and are they able to find eveything that is important.
Comment: You have finished you sport mobile app, you want to test if people really can find events that they want, and join them. You do Quantitative measurment for task sucess or time needed. You test how much time people need in your app to join one event. You have exact number, and you iterate your design to be better to reduce that time needed number. You can also test are they able to use filter, and you get number for task sucess rate. You iterate your design to increase that number.
Comment: Qualitative is all about gaining general insight, with open ended questions. Input you receive is often in written form, without exact number. Qualitative you receive exact numbers, you test on scales from 1 to 5 or 10. Therefore Quantitative is better to use in specific context, in smaller scopes. I.e. after development, to test performance of your search field, filter or other element.
Comment: This is based on personal experience and there is no right or wrong here. You can use combination of both, or you can use it differently in different context. It really depends upon your specific scenario what you need.
Answer: The qualitative

When you would like to discover new things and understand user behaviour because in this method the user is free to talk anything about the subject;
You just manage the time and point some subjects to be discussed not influence the user's answer.
You need more time to analyse the result because is not standardized;
You probably will not create charts with the answers;
You will need more time of the users to make the research because this is similar to an interview and you could do it in group fac-to-face.

The quantitative

When you would like to confirm some theory because in this method you will lead the users to limited answer options.
The result can be graphics and not so deep in user behaviour.
Take less time by the users and you can conclude it in a few minutes.
You have a lot of online tools that you can use to help you to have a lot of answers.

I could write hundreds of reasons to use each one and spend a lot of time explaining all the conditionals that you have in each situation but you can easily search on Google or Youtube by "Quantitative vs Qualitative Research" and invest some hours reading and watching videos. I just bring a brief about it.
I found this image with a basic and fair comparison:
Answer:
I want to know some of the discerning factors of a product that makes
  you choose quantitative over qualitative research and vise versa at
  any given time during a project.?

This is tricky because at different times during a project for a product you might have a preference for a certain type of information/data. I general I wouldn't choose one over the other (as I try to use a bit of both, no matter how
Please elaborate when and why you choose one over the other.
When does one give more pertinent information than the other? What makes it take priority?


Storage shelves under stairs

Question: I would like to build some shelves for the cupboard under the stairs. I quite like the layout in the following picture:

My cupboard is roughly per diagram below, were I would like to put a 3-layer shoe rack next to the shelves (the walls to the left and rear of the show rack are dot-and-dab, everything else is stud walls with metal studs.

I would like some recommendation on out to build something like this which results in level shelves. In particular:

Do I build everything in-situ, starting from the battens on the wall? Or
Do I pre-build each shelf, including frame and top and secure to wall afterwards?
Any other combination of the above?

I am quite happy to suggestions on how to build something functionally similar to the picture that is not structurally built like in the picture.
Answer: Exactly how you go about this is entirely up to you and either of the ideas you have presented will have advantages and drawbacks.

Building in place.

You can ensure that everything is square and level as you build it, accounting for small variations in the floor or wall as you go.

ProTip™: When I built similar shelves in my shed, I cut 2x4 spacers to put each shelf on as I assembled to hold the next one up level and identically spaced from the lower one.

Depending on your design, you might be able to use less material or lighter material on the back side because you're attaching it directly to the wall and are using the wall for some of the support.
It might be difficult holding pieces in place in cramped quarters while you get everything arranged just right and screw it all together.
There will be loads of trips back and forth between the assembly area and the prep/cutting area.

Pre-build

You can make a jig to ensure all your units are nice and square.
You can work where you have lots of room and near your large cutting tools so you're not making dozens of trips back and forth.
You'll probably want to put adjustable feet on the bottom of each leg to ensure that you can get the unit square and level once located in its final resting place.
You may have a hard time carrying fully assembled, wooden shelving through the house and wrangling it into the cupboard.
Answer: This is the order I would do this in:

If you are not certain of the weight bearing capacity of the wall, you should consider installing a sheet of plywood on the wall that touches the floor. If you have molding at the floor, remove it so the plywood sits on the floor.

Mark the wall/plywood for your shelves. Then draw in the thickness of the shelves and the battens. Use this drawing to make sure the items you want to store will actually fit. For example, hold a cereal box up to make sure it fits between the batten and next shelf.

Install the battens, making sure they are level left-to-right.

Cut one upright (I suggest the middle one, and leave it long), one shelf (I suggest the bottom one) and the front stringer. Install those, making sure the shelf is level front-to-back.

You now have one supported shelf that you can use to double-check your plan.

Depending on which is more convenient, either install the rest of the uprights and then the shelves, or install the shelves and then the uprights.

Don't forget to install the stringers on the sides!

Trim the uprights to the correct height.
Comment: This is good advice if you're storing gold bullion or osmium, but I can't imagine a normal storage situation where a couple of screws into studs for the battens wouldn't be totally adequate.

Storage shelves under stairs


When is temporary lifetime extension useful in modern C++?

Question: In C++ you can bind return value of a function (which return value, not reference) to const reference and code will still be valid because lifetime of this temporary will be prolonged till the end of scope. For example
std::string get_string() {
    return "abc";
}

void f() {
    const std::string& str = get_string();
    std::cout << str; // valid, str is not dangling reference.
}

My question is, when is it useful, e.g. when is code like
A get_a();
const A& a = get_a();

better than the code
A get_a();
A a = get_a();

and in what way (e.g. faster, smaller binary size, etc)? What should be the implementations of A, get_a and code after calling get_a?
I've tested several cases by hand and in each case it seems to have the same number of copies and moves.
Let's restrict this question to current C++ standard, modern versions of compilers and builds with optimisation enabled (O2, O3 or equivalents for other compilers)
Answer: Deliberate lifetime extension of prvalues into named stack variables like this is not useful if you know exactly what's going on. Which means it is useful if you don't know exactly what's going on.
Say, you're in a template function. And the user is supposed to give you some object that has a get member function that returns some type that fits some expected behavior. Question: does get return a reference or a prvalue?
Answer: you don't care. It doesn't matter if it returns a prvalue or a reference; what matters is that what it returns can be manipulated in the fashion you expect. So you might expect obj.get() = 10; to work, for example.
Maybe get returns a reference to an object. Or maybe it returns a prvalue that is a proxy object that acts like a reference. In the above case, maybe it has an operator= overload, so that you can assign to it. You the user don't care.
So, what happens if you want to store what get returns for a (short) period of time? Well, you don't want to do auto x = obj.get();; if it returned an actual reference, you would get a copy of the reference, which is probably not what you wanted. So you do auto &&x = obj.get();. Lifetime extension allows this to work just as well with proxy prvalue objects as with actual references.
Comment: @PaulSanders: If you expect to be able to do `obj.get() = 5;` to assign a value to `obj`, will `auto x = obj.get(); x = 5;` do the same? If the return of `get` is a proxy, then yes. If the return of `get` is a language reference, then no. You use `auto&&` to indicate that you want to store exactly what `get` returns.
Comment: Nice post.  Excuse my ignorance, but why would getting a copy of a reference be a bad thing?  In what way does it not behave in the same way as the original?  I realise that `auto &&` can bind to anything and so is more adaptable but that's not the same thing.  But perhaps I misunderstand or perhaps I'm just picking nits.  Learnt some interesting stuff about `auto &&` [here](https://stackoverflow.com/questions/13230480/what-does-auto-tell-us).
Comment: OK, I still didn't understand this so I knocked up a [demo](https://wandbox.org/permlink/trQqirCpnzBglr7w), and given (say) `int& get() { ... } ... auto x = obj.get();` you can indeed not assign to `obj` via `x`.  _But why not?_  Found my answer [here](https://stackoverflow.com/a/37394183/5743288): `When auto is deduced, it is not deduced to the reference. It always deduces to the value`.  That is the key phrase here.  My, you have to be so careful with this language.


How to access a method on a parent from a grandchild

Question: I am not sure what else to call this. I have a file, lets call it parent.vue. it has the following
PARENT.vue
<template>
  <input-box
    :room="currentRoom"
    v-on:messagesent="getMessages"
    class="dark:bg-gray-800 px-6 pb-6 pt-4 dark:border-t-2 dark:border-gray-600 bottom-0 sticky" />
</template>

method:
  getMessages() {
    axios.get('/chat/room/' + this.currentRoom.id + '/messages')
    .then(response => {
      this.messages = response.data;
    })
    .catch(error => {
      console.log(error);
    })
  },

Then I have a child which calls the v-on anytime something happens. The issue is, I need to call that from a child inside the child. "aka the grandchild" Inside the CHILD I have inside a method
this.$emit('messagesent');

How can I accomplish the same thing inside the grandchild.
Answer: Well that was a blank moment on my part.
Using
this.$parent.$emit()

Gave me the ability to send it up the chain. This is exactly what I wanted.
Answer: Not if you want to maintain encapsulation. Grandparent is not supposed to know about grandchild. It knows about parent, but not that there are sub-components or how many. In principle, you can swap one implementation of grandparent out for another that doesn't have multiple layers. Or has even more layers to get to child. And you could put child into a top-level component.
You already know about the notion of a global event bus. A bus doesn't have to be global, though. You can pass it down the props chain. (You could use grandparent itself as the bus, but that would expose it to its children; better hygiene to make a real bus.)
This distinguishes top-level components from sub-components: a sub-component will receive a bus prop to perform the functions of the top-level component that it helps to implement. A top-level component will originate the bus.
For more details check out the below link
https://andrejsabrickis.medium.com/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860
Comment: That was jus for your info, all I wanted to highlight is when the hierarchy goes beyond one level it's better to go with event bus
Comment: In this specific case, I am using a modal that pops up to add data to the child. so I am less concerned about encapsulation. When I complete my MVP and refactor some components ill revisit this but for now this accomplishes my goal


Bookmark Sync, Sync's then removes bookmarks!

Question: I got bookmark sync to work (sort of), now it'll sync, then remove all bookmarks it had just synced?
Comment: Problem resolved it self, but I'm still curious as to why it was doing that?
Comment: Rob, could you post an answer saying that it's resolved itself and then accept it to that this question is marked as resolved? Thanks :)
Answer: probably a bug in the extension
nice to have it solved yourself


How to remove all css classes and js in material design, to get default select box

Question: I want to remove all css classes and js in material design, and make a select box look like basic html.
I want this:

To be this:

Any help is appreciated.
Answer: Given that you have tagged your question materializecss, per the documentation at http://materializecss.com/forms.html, you need to add the class browser-default to your <select> thus
 Browser Select
  <select class="browser-default">
    <option value="" disabled selected>Choose your option</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
  </select>

Comment: Interesting, thanks, so I'm **not** offering my hack https://jsfiddle.net/Gunnar/mw3c38co/ :-) I really should start learning materializecss.


How to generate 40-bit unique values randomly?

Question: I'd like to generate 40-bit values, which are unique and non [so easily] guessable.
How can I do it? Any suggestions?
-edit-
I'm interested in an algorithm, C# or Java would be the cherry in the top of the cake!
-edit2-
I'm able to store previous values but I wouldn't like to have to check the whole list everytime I generate a new number
Comment: what is your preference programming language?
Comment: C# or Java, but an algorithm in any language would be fine!
Answer: What platform are you on? On unix-ish systems, just read 40bits from /dev/random (blocks if insufficient entropy is available) or /dev/urandom (doesn't block, but also produces lower-quality random numbers if entropy is limited).
Comment: Yes, they would be. Windows has its own random number generators built in, though the only method I can think of to access them in PHP is via the session name subsystem: http://www.php.net/manual/en/session.configuration.php#ini.session.entropy-file. Maybe there's a COM call or something you could do.
Answer: get first 12 bit(upto max 4095) as day from first release of ur program(will be unique part), other 38 bit use from random system call/function.
so u have recheck last day only values for unique.
sorry, no way GRANT unique from non-predictable(random) value.
u  can use more part from date, upto seconds for example. u can shafle predictable(date) bits, but it will nto add security.
anyway u have to balance between unique check time/random quality. to increase speed of check, can use binary tree or other technics.
also  u can use timer value upto miliseconds.. for busy system it will be unique(if do thread lock+ 50ms sleep) and not so predictable in multithreaded environment.
Answer: usign what? in general random =unqiue,so use random. or
date|md5sum|cut -b 4-9
something like that
Comment: That's not random. That's actually highly predictable. Also, random does NOT mean unique. It's entirely possible to randomly generate 5 million "heads" in a row via coin toss. Random? Yes. Likely? No.
Comment: Agree with Marc B, also it wouldn't work if I tried to generate the numbers in less than a second (I would get repeated numbers)
Comment: that was only posible answer for question in original state ;)


A monotone sequence of sets is convergent

Question: I'm having trouble understanding the following part of a proof from Leadbetter's measure and probability book:
THEOREM 1.4.2: A monotone increasing (decreasing) sequence {$E_n$} is convergent and lim$E_n=\bigcup_{n=1}^∞ E_n (\bigcap_{n=1}^∞ E_n)$.
Proof:
$$\bar{lim}E_n=\bigcap_{n=1}^∞ (\bigcup_{m=n}^∞ E_m )=\bigcap_{n=1}^∞ (\bigcup_{m=1}^∞ E_m )$$
But $\bigcup_{m=1}^∞ E_m$ does not depend on n and thus, $$\bar{lim}E_n=\bigcup_{m=1}^∞ E_m $$
In particular, I don't understand the logic behind moving from $\bar{lim}E_n=\bigcap_{n=1}^∞ (\bigcup_{m=1}^∞ E_m )$ to $\bar{lim}E_n=\bigcup_{m=1}^∞ E_m $. I understand that $\bigcap_{n=1}^∞ (\bigcup_{m=1}^∞ E_m )$ does not depend on n, but I don't see how removing the intersection wouldn't also change the union of all members of {$E_n$}. Since a monotone increasing sequence of sequences contains more elements per $E_n$ as n increases, wouldn't the union of all subsequences of {$E_n$} also be increasing, whereas the intersection wouldn't?
Answer: To see what's going on, let $A=\bigcup\limits_{m=1}^\infty E_m$; this is simply some fixed set. Then
$$\bigcap_{n=1}^\infty\left(\bigcup_{m=1}^\infty E_m\right)=\bigcap_{n=1}^\infty A\,,$$
and no matter how many copies of the set $A$ you intersect, you're just going to get $A$. Thus,
$$\bigcap_{n=1}^\infty\left(\bigcup_{m=1}^\infty E_m\right)=A=\bigcup_{m=1}^\infty E_m\,.$$
Comment: Thanks Brian! I appreciate the re-wording and I think I understand now. From my understanding: since each set in an increasing sequence of sets is a subset of the next set, no matter the value of "n" chosen, the infinite union of the sequence will be the same, making the intersection the same.
Comment: @tomhod14: You're welcome! Yes, that's correct.


Do these leaves signify anything?

Question: Occasionally, you can see little tufts of leaves blowing in spots on the map

Do these mean anything?
Comment: @P1raten Same answers, but different questions.
Comment: Possible duplicate of [How do I find Pokémon?](http://gaming.stackexchange.com/questions/272561/how-do-i-find-pok%c3%a9mon)
Answer: Yes, the rustling leaves usually indicate that there are pokemon near that area. Going and walking around near that area gives you a higher chance to encounter Pokémon.

Keep an eye out for rustling leaves, hinting at where critters may be
lurking and simply hang out in a suspected region for the increased
chance of an encounter. - Source

Edit:
I've been running and testing the leaves thing for a bit, and even though there have been reports that it increases the odds of finding Pokémon, I personally find using the step indicator to be far more reliable. An additional benefit is that you can actually use the steps to select a Pokémon you want to catch, and specifically go after that one. Here's how:

Step 1: Open up the nearby list and decide which pokemon you want to
find.
Step 2: Keep walking in a direction until you see that pokemon
move a spot in the list. If it moves closer to the upper left corner,
you're walking towards that pokemon, so continue walking that way. If
it moves down the list, backtrack and choose another direction to
walk in.
Step 3: Continue to triangulate until you find your pokemon
(also pay attention to the 'footsteps' underneath the pokemon, these
should go down from 3>2>1>none).
Step 4: Benefit.
Source

I believe these mechanics (steps + leaves) could possibly be meant to be used together to track down Pokémon the most efficient way. Use the steps to get a general bearing of the target location, then look around for leaves to home in.
I've had a Wartortle spawn inside the leaves before, and I believe the leaves are an indicator of a possible Pokémon spawn point. This does not mean that Pokémon are currently at that location, just that Pokémon spawn (and despawn) there - based on my findings and players I've spoken to.
Comment: -1 I'm fairly sure the leaves signify nothing (and neither of the sources given are official or even convincing imo), and the edited in bit about the footsteps is an answer to a different question, not this one.
Comment: Is there a source for this?
Comment: That last source on the nearby bar blinking is doubtful - several other users have said it does nothing, so it's hearsay at this point.
Comment: @Nelson added sources and additional info.
Comment: @jackwise Correct, updated.
Comment: From my observation, the position in the "near by" list is just historical -- newly approached pokemons are just added to the top, and they don't swap with each other.
Comment: @Nakilon Please keep in mind that currently the step indicator is bugged. This answer was posted pre-bug.

As an additional note, I've talked to dozens of players who can confirm this is the way the near by list worked pre-bug. I've also had hours upon hours of testing myself - and I'm quite convinced this is the way it works and have answered according to this belief. If you disagree, feel free to post your own answer based on your own personal findings. That is what stack is for.
Comment: This answer is wrong. The leaves mean nothing - they are a remnant from Ingress (exotic matter) and signify nothing in Pokemon Go.
Comment: @Matthew please supply a source for your information so I can update this answer.
Comment: There's no official source on it. If you look around, no one seems to agree on what the leaves mean, but anything that says they mean something are from the first days/week of the game when people also thought the blinking tracker meant you were getting closer. There's tons of misinformation going around and the leaves meaning something is one of them. So far I can only find people saying that it's a likely spawn point but doesn't indicate it means there's anything currently there. From personal experience the leaves mean literally nothing.
Comment: You can test it yourself by using pokevision and/or visiting rustled leaves areas. Leaves in an area are consistently in the same spot and don't seem to spawn pokemon any more than any other random area.
Answer: A flurry of leaves (although I don't think you see them anymore) signifies a CERTAIN spawn point, or in other words, a nest. Unfortunately, I haven't seen one recently, meaning I cannot test it out for you.
Comment: Thanks for your answer. As a matter of fact, this feature was actually removed a long time ago, in the early versions of the game. If there is a new version of this, you should state it, as it would be very helpful to regular players!
Comment: I am so sorry @Ben . I didn't notice that it had been removed. I liked the graphics
Comment: It's all good :) so there is no new version of this?
Comment: Don't think so, you could use third party software/sites , such as Silph Road
Answer: I've seen no significant difference when im around leaves. Ive stood on top of them for 20 minutes with an incense and nothing happened.
Comment: If no pokemon spawned with incense, your server connection probably failed.

Do these leaves signify anything?


watchOS app's icon is blank on the Watch app on iPhone

Question: I recently created a WatchKit extension of my iOS app. Xcode created 2 new targets:
WatchOS Target
WatchOS Extension
Each of these target has its own Assets.xcassets file. I've included the proper icons with the correct dimensions to both of these files, but the app icon is still showing blank on the Watch app on iPhone like so:

The icon is showing properly on my Watch. Any idea?
Answer: "Each of these target has its own Assets.xcassets file. I've included the proper icons with the correct dimensions to both of these files, but the app icon is still showing blank on the Watch app on iPhone like so: "
Do you have the Apple Watch app icons in your iPhone asset catalog?  There are several included on the iPhone side.
Comment: It will help the question if you list which ones you added on the phone side.  I suspect you have missed an important one.  Also, removing the app from the phone and re-installing may cause them to show up.  Sometimes it seems the caches are not properly updated.