Event handler does not get called

Question: In the following code, the asp does not enter the action listener (Button1_Click).
Can anyone help?
protected void Project_Click(object sender, EventArgs e)
    {
        Courses.ActiveViewIndex = 0;

        String ConnStr = ConfigurationManager.ConnectionStrings["MyRuMoR"].ToString();
        SqlConnection conn = new SqlConnection(ConnStr);
        conn.Open();
        SqlCommand cmd = new SqlCommand("ViewProjects", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@course_code", "PHYS305");

        SqlDataReader rdr = cmd.ExecuteReader();

        int c = 1;

        while (rdr.Read())
        {
            String name = rdr.GetString(rdr.GetOrdinal("name"));
            int p_id = rdr.GetInt32(rdr.GetOrdinal("p_id"));

            LinkButton lb = new LinkButton();
            lb.ID = p_id.ToString();

            lb.Text = "Project " + c + " is: " + name;
            form1.Controls.Add(lb);

            lb.Click += new EventHandler(this.Button1_Click);

            c++;
        }
        conn.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("Hello");
    }

Comment: You better change your logic and use Repeater instead, binding its data source in the `Project_Click` method.
Comment: You mean event handler. Action listener is a Java concept.
Answer: You need to read up on the ASP.NET page lifecycle.
When it comes to dynamic controls, you need to recreate them on postback, or they will not exist and the attached event handler will not fire.
Dynamic contorls are best created on the PreInit event of the page.
As described here:
protected virtual void OnPreInit(EventArgs e)
{
   base.OnPreInit(e);
   //your code
}

Comment: not in the init but PreInit. http://msdn.microsoft.com/en-us/library/ms178472.aspx
Comment: thank you for your reply but could you please illustrate more? I don't really get what is the PreInit stage of the page.
Comment: I'm new to asp.net and this my first project, so i'm a little bit lost and don't understand how to add a dynamic control on the PreInit event of the page.
Answer: Yes not just understanding dynamic controls you need to TRULEY understnad them
This is one of the best article on them by a ASP.NET team memeber.
TRULY UNDERSTANDING DYNAMIC CONTROLS
Answer: You have to put all or the part of your code that creates dynamic controls inside the Pre_Init event of page life cycle, something like this
protected void Page_PreInit(object sender, EventArgs e)
{
   LinkButton lb = new LinkButton();
   lb.ID = p_id.ToString();

   lb.Text = "Project " + c + " is: " + name;
   form1.Controls.Add(lb);

   lb.Click += new EventHandler(this.Button1_Click);
}

Then only it will achieve what you want.

Event handler does not get called


Formatted text output to std::string object using std::ostream methods

Question: I've made a function dump_text(std::ostream &) that dumps some text in a standard output stream. The text goes to a file or to the user console. Now, I want that text to end up in a standard string object (see the next code sample).
void dump_text(std::ostream &p_ostream)
{
    p_ostream << "text that must endup in string object";
}

class my_class
{
    public:
    my_class(std::string &);
    operator std::ostream & ();
};

int main(int, char **)
{
    std::string l;
    my_class k(l);

    dump_text(k);
}

1) Is there a standard implementation of 'my_class' in the CRT-library?
2) Does anyone know a better solution to this problem of assigning text to a string using std::ostream - methods?
Comment: Have you tried stringstream? http://www.cplusplus.com/reference/iostream/stringstream/
Answer: You would use a std::ostringstream.
#include <sstream>
using namespace std;

...
ostringstream out;
dump_text(out);
string value = out.str();
...


Is using tabs for navigation a violation of the ARIA specification?

Question: The current title is as carefully reworded by somebody else. I could rephrase it as Do ARIA specs allow the use of tabs-based implementation of a navigation menu?, just in case it makes things clearer to other readers.

§3.22 Tabs from WAI-ARIA Authoring Practices 1.1 reads

Tabs are a set of layered sections of content, known as tab panels, that display one panel of content at a time. Each tab panel has an associated tab element, that when activated, displays the panel. The list of tab elements is arranged along one edge of the currently displayed panel, most commonly the top edge.

This doesn't seem to exclude that one could use tabs for navigation, i.e. for the elements in a . I think one example of a website that does so are GitHub profile pages (example).
On the other hand, the examples from WAI-ARIA Authoring Practices 1.1 use <button role="tab" ...> in a
, and the selected tab doesn't persist across page refreshes. From a later part of the document, I read:

When a tabbed interface is initialized, one tab panel is displayed and its associated tab is styled to indicate that it is active.

which makes me think it's the intention of WAI-ARIA to have a specific tab panel be selected when the page is refreshed, ignoring which one is selected right before refreshing.
And this does seem to exclude that one could use tabs for navigation, unless one is happy that the navigation state is wiped out every time the page is refreshed.
So my question is two-fold:

Does using tabs for navigation violate some ARIA principle (e.g.  accessibility)?
If that's the case, then what are those tab-like things I see on GitHub profiles, if not tabs? Or is it just that GitHub is designed in a way that is not ARIA-compliant?
Comment: Yes, it was a typo from copying/moving words around, thanks. And yes, that would be a good title
Comment: As currently written, this question is off-topic because what constitutes "good practice" or "bad practice" is a matter of opinion. If you edit this question to be about compliance with a specification (e.g. ARIA) then it would be on-topic because compliance with a published specification is an objective matter.
Comment: @TylerH what about it now?
Comment: Adding essentially "about ARIA" to the title is not a sufficient edit in that regard, no. I will take some time to revise your question so that it focuses on objective/on-topic matters.
Comment: @TylerH _WAI-ARIA_ is written 3 times in the body of my question. Doesn't that convey that I'm interested in an answer as regards that standpoint?
Comment: Yes, but  the question you were actually, explicitly asking was "is this bad design/undesirable/edgy". These are irrelevant to ARIA compliance. Someone could legitimately hold the view that ARIA's spec itself is bad design, undesirable, or edgy... but their answer wouldn't particularly help you if you want to comply with ARIA's spec. That is why questions on Stack Overflow must be objective; ask about complying with ARIA's spec specifically and you will only get answers that are guaranteed to help not only you, but also anyone else who has the same question in the future.
Comment: @TylerH, I guess _volution_ is a typo for _violation_? Btw, I was going to change the title to _Do ARIA specs allow the use of tabs-based implementation of a navigation menu?_ Would that be good?
Answer: The tab pattern is a nice way to save screen real estate without having to navigate to new pages.  It's essentially a container that lets you display different content depending on which tab is selected.  It's almost like an iframe.
Using it for navigation would be a little odd because what role would you use?  Navigation elements should be links but tab elements have a role of tab.  Selecting a link implies you can go back to where you previously were by selecting the browser's "back" button.  Selecting a tab does not have such implications.
The example on github, if you're talking about the "overview", "repositories", "projects", and "packages" elements, those actually take you to a new url so using links is correct.  The "back" button takes me back to the previous view.  Those elements are not implemented as tabs.
Comment: I'm not totally convinced. You say that _Those elements are not implemented as tabs_, yet which one is selected is encoded in the URL with a trailining `?tab=whatever`, so whoever wrote that code thought of them as tabs, don't you think?
Comment: They're implemented as links using the '?' as a parameter so they can visually stylize the page to make a tab look selected.  But since they're links, I can use the browser "back" button to go back to the previous view.  A true `tab` widget would not have the "back" behavior.


How should I connect the ground wire for my light fixture?

Question: I am replacing a light fixture in my bathroom and have the following setup:

The electrical box is plastic
The wire coming from supply has black (hot), white (neutral) and copper (ground).
The light fixture comes with a metal bracket for attaching to the electrical box that has a green screw
The light fixture has black, white and copper wires.

The instructions supplied with the fixture dont give me an example of how to wire it up if there is an existing ground wire coming from supply.  It only tells me to attach the copper wire of the light fixture to the green screw.  So I'm curious what I should do with the ground from the supply.  Looking online, my options appear to be this:

So I think since the electrical box is plastic, I should just connect the ground of the supply with the ground of the light fixture with the wire nut.  Do I need to connect both of them together with the green grounding screw on the light fixture as well, or would that only be if the electrical box was metal?
Answer: The instructions for the fixture are only correct for a metal box.  If a metal box was used, the box itself would (should) be grounded.  The bracket that holds the light would then be connected to the box, which would make the bracket grounded.  Finally the ground wire from the fixture would attach to the bracket, grounding the fixture.
In the case of a plastic box, the box is not grounded.  All ground connections must be made by connecting the ground wires together. So in your situation you are correct, you'll connect the ground from the supply to the ground from the fixture using a twist-on connector (or other approved connection).
Answer: Even plastic electrical boxes may have a metal strip for ground that connects to the metal screw receptors.  Check that first.
If not, connect the ground from the panel to the fixture ground with a marette (just like the power wires) and twist the fixture ground around the green screw.
While it isn't critical to connect the ground wire from the fixture to the grounding screw on the mount, it's a good idea.  I always make sure this ground wire is shorter than the power wires so that if the fixture falls it gets stopped by the ground wire attached to the mount rather than stressing the power wires from the panel.
Comment: I have never seen a plastic box with a grounding strip.
Comment: Interesting point about making the ground wire shorter.  The only negative I can see with this is that if all the stress is on the ground, the ground could become disconnected.  You now have a dangling fixture with no ground - lets hope it doesn't become energized!
Comment: Really?  At least some of the one's I've bought have them; it's about 1/2" wide and runs from one screw hole along the back to the other.  I never really thought much about it and just assumed it was something required.
Comment: That's a good point.  Prevention vs Protection.  Can anybody provide an official "code" statement on the better method?
Answer: I would connect both coppers wires together via the green screw. I would also ensure that the copper on supply side is longer than hot and neutral, that way if there is a breakage it is most likely the hot or neutral that snaps and if it shorts to any metal work on the lamp it will go to earth/ground.
Comment: In general it is ill-advisable and I believe against code to tie more than one wire to any screw down point not specifically made for multiple junctions. The accepted approach would be via pigtail as @Tester101 suggests


android how to get indicate when the internet connection is lost?

Question: I'm developing an android application and I want to get a notification when the internet (wifi or packet data connection) connection is lost. On my approach I can get the status of the connection as:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

while having this in the Manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How could I be notified automatically when the connection is lost?
Comment: The above code is the standard way to check whether there is internet or not, so what is your question?
Comment: see here http://stackoverflow.com/questions/3119607/how-to-be-notified-on-wifi-network-status-change
Comment: @user2310289 : its need to  call the `isNetworkAvailable();` method to get to know the connection status. its ok when app starting. but while app running its not much good way to handle the requirement
Answer: For WIFI you could register a broadcast receiver as:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);

You can also register the receiver in the Manifest.
Then in your receiver:
@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
        if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)){
            //do stuff
        } else {
            // wifi connection was lost
        }
    }
}

For any type of data connection listeners you could use the following receiver registered as:

<receiver android:name=".receiver.ConnectivityReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
</receiver>

and the in your ConnectivityReceiver:
public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
    }
}

In the onReceive method you could check if you have internet connectivity or not using this developer article.
Comment: could you please explain `registerReceiver(broadcastReceiver, intentFilter);`
Comment: You can use `registerReceiver` if you're interested to be notified on the life-time of an `Activity`/`Service`. Otherwise you're registering a `BroadcastReceiver` directly in the manifest and so you're getting the updates all the time, no matter if the application is running or not. [`registerReceiver`](http://developer.android.com/reference/android/content/Context.html#registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)) is available in the `Context` class. Just don't forget to call unregisterReceiver if you registered in a `Context` class.
Comment: does this also work when mobile data connection is lost?
Comment: This intent action/constant was deprecated in API level 28.
Answer: use following code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import classes.NetworkUtil;

public class NetworkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(final Context context, final Intent intent) {

            boolean IsConnected = NetworkUtil.getConnectivityStatusString(context);
           // Toast in here, you can retrieve other value like String from NetworkUtil
           // but you need some change in NetworkUtil Class
        }
    }

and NetworkUtil is:
package classes;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtil {

    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;

    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        }
        return TYPE_NOT_CONNECTED;
    }

    public static boolean getConnectivityStatusString(Context context) {
        int conn = NetworkUtil.getConnectivityStatus(context);
        boolean status = false ;
        if (conn == NetworkUtil.TYPE_WIFI) {
            status = true;
        } else if (conn == NetworkUtil.TYPE_MOBILE) {
            status = true;
        } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
            status = false;
        }
        return status;
    }
}

and in manifest file:
 <receiver
            android:name="receiver.NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

and this permission:
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Comment: Yes you right, you must use JobScheduler, WorkManager, or register broadcast programmatically  @c-an, I wrote this answer in 2014
Comment: This is deprecated for apps targeting N and higher. In general, apps should not rely on this broadcast and instead use JobScheduler.
Answer: You need to set up a broadcast receiver.
Add these as intent filters.
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>

Answer: You should use BroadcastReceivers for your requirement. Create a BroadcastReceiver which listen for network changes.
Incase of any change in the network it will automatically fire the event and you can perform your operations regarding it.


How to write many rows in text file?

Question: I write/read file text with C#.
My method is:
public static void Save(List<DTOSaveFromFile> Items)
{
    File.WriteAllLines(dataPath, (from i in Items select i.Serialize()).ToArray(), Encoding.Default);
}

This always overrides data and only insert 1 rows.
How to insert many rows and don't override before rows.
Comment: Can you show some sample input and output?
Comment: Possible duplicate of [How to add new line into txt file](http://stackoverflow.com/questions/8255533/how-to-add-new-line-into-txt-file)
Comment: Sample input: user1  firstname.lastname@example.com              16:43
Comment: @fds, I was read your link. I try but it show data in my text file:
`System.Linq.Enumerable+WhereSelectListIterator`2[STU.Email.DTOSaveFromFile,System.Char[]]
System.Collections.Generic.List`1[System.Char[]]`
It not add data. Here my code I was edited: http://pastebin.com/K6AYQdw5
Answer: Try the File.AppendAllLines method:
public static void Save(List<DTOSaveFromFile> Items)
{
    File.AppendAllLines(dataPath, (from i in Items select i.Serialize()).ToArray(), Encoding.Default);
}

From MSDN:

Appends lines to a file, and then closes the file.

So, this will prevent the file getting overwritten.
Comment: I find don't have any File.AppendAllLines, only have File.AppendAllText. If change to File.AppendAllText it's show error like that `Argument 2: cannot convert from 'string[]' to 'string'`
Comment: I'm using .NET 3.5. Thanks.
Answer: Try this
public static void Save(List<DTOSaveFromFile> Items)
{
    using (StreamWriter sw = File.AppendText(path))
    {
        foreach(DTOSaveFromFile d in Items)
            sw.WriteLine(d.Serialize(), Encoding.Default);
    }
}

Comment: So, File only contains AppendAllText. Do you use StreamWrite?
Comment: Sorry, I was test your update answer but it have error like:
`Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable>' to 'string'
`
Comment: 'Try this' answers are discouraged. Your first answer just replaced one word (and that is okay if it fixes the problem). Just explain what you did and where the error was, then future readers can understand what the problem is.

How to write many rows in text file?


Trying to get the difference between two arrays in php

Question: I have two arrays. $array_advise and $array_oab, respectively.

Array ( [0] => Array ([oab] => 226015 ) ... )
Array(  [0] => Array([oab]=> 289240 )... )

The first one is the bigger array with the complete data. The second one is smaller. What I want is what is in $array_oab and is not in the $array_advise.
I tried with array_diff(), but it returns an empty array. What I'm doing wrong ?
Edit

  foreach ($lista_advise as $value_advise) {
    $array_advise[] = array("oab"=>trim($value_advise["OABNumero"]));
    $array_advise_nome[] = array("vinculo"=>$value_advise["nomeVinculo"]);
   // print_r($array_advise_nome);
  }
    foreach ($corporativos->lista as $value){
      $input = $value["info_adicionais"];
      $input = utf8_decode($input);
      $input = trim($input);
      $data = json_decode($input,true);
      if ($data["andamentos"] != NULL) {
        $advogados = explode(";",$data["andamentos"]);
        foreach ($advogados as $advogado) {
          $dados = explode(",",$advogado);
          $oab = explode("/",$dados[1]);
          //  print_r(strtoupper(removerAcento($array_adv[0]["nome"])));
          $array_adv[] = array("cliente" => $value["nome"], "clienteid" => $value["clienteId"] ,"nome"=>$dados[0], "oab"=>$oab[0], "estados"=>$oab[1]);
          $array_oab[] = array("oab" => trim($oab[0]));
        }
      }
    }
    print_r(array_diff($array_oab, $array_advise));

I edited with my code, the output is a empty array.
Comment: Can you post your complete tried code ? And if possible eg of an expected output.
Comment: If I'm not wrong, you can't use array_diff() with multidimensional arrays.
Comment: What you are doing wrong? In order for us to answer that you should specify what you are actually doing.
Comment: There's no day in stackoverflow without the typical php question "How do I compare those two arrays?" or "How do I do that with 2D-Arrays in PHP?" (Like accessing values in it)
Comment: Why is it so hard to print data you're working with when asking questions, what's `$lista_advise`, `$corporativos->lista` ?
Answer: array_diff() works with single-dimension arrays only. You have to use array_udiff().
Something like this:
function cmp($a, $b) {
return $a['oab'] == $b['oab']? 0 : 1;
}

array_udiff($array_oab, $array_advise, 'cmp');

Answer: array_diff
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>


Bathtub impersonating waterbed?

Question: Just bought a new house - new to me, but it's from '52.  My bathtub looks like it's relatively new, and at first use was great.  When we recently used it for a bath, however, it felt like there was some water... underneath the floor of the tub?  It could be moved around, like a water bubble underneath a lawn.
Worried, I checked the basement - but there's no leak, nothing's even wet.  What in the world is going on, and how do I fix it?
Even when the bathtub is empty, the water underneath the floor seems to remain - and it's got worse again when we tried taking another bath (which, in both pro-and-retrospect, we probably shouldn't have done).
Comment: @jay613 I've got the video, might be a bit quiet.  My phone sorta sucks.  https://youtube.com/shorts/qQgxmQYHARg Also: I THINK the stack is in the wall by the sink, not by the tub unfortunately.
Comment: What is the tub made out of?  Is there a liner or refinished surface in the tub?  How does it feel like there's water underneath the bottom of the tub?  Is the ceiling in the basement beneath the tub finished?  Try filling it with cold water and seeing if the same thing happens.  The bottom might be getting heated up by the hot bath water, expanding, and getting bent up out of shape.  Then it acts like what you describe:  press down one side, the other side pops up.
Comment: Does the side of the tub have a panel that can be removed?  What is the basement ceiling beneath this made of?  Are you able/willing to cut it open?  Can you make a video, with sound, of this sloshing effect and post a link to it here?
Comment: It's literally actually filled with water underneath, I'm pretty sure: I can feel and hear it sloshing when the tub is empty and we press on the spots (which remain).  I don't know what the tub is made of but I'm guessing fiberglass, seems relatively new.  The ceiling isn't finished, but I don't have good access to the underside of the tub.
Comment: @aquaticapetheory Should have "@"d you, but neglected to do so.  Don't know if an edit will trigger it, so I'm just commenting again.
Comment: I can get a video, sure.  The floor underneath is its own problem - take a look at other questions I've posted in the last hour or two - but there's no panel on the tub that I see.  There MIGHT be an access panel in an adjacent closet, but I won't know until my household goods get here (used a company, didn't drive them myself) and I can get my screwdriver to open it.  @jay613
Comment: I don't know what's wrong with this tub, but if we assume there is some serious problem with it, and it needs to be replaced, and if one of the cast iron waste stacks from your other post is inside a wall adjacent to this tub, there may be an argument to now replace some or all of that stack.  It's always a crap shoot -- your stack may fail tomorrow or may last another 100 years.  But having open acccess to it on multiple floors simultaneously is a rare opportunity that changes the equation.
Answer: You probably have a bathtub liner with a hairline crack, and water between the liner and original tub.
If a renovation of this bathroom is on the horizon, you may opt for a short-term fix to temporarily get rid of the water. Since you have access from the basement you can remove the drain basket, then most of the water in the liner will flow into the drain.  Some water may end up on the basement floor.  Also look for the cracks or wherever the water is getting under the liner and seal that.  Don't re-use the basket or the drain shoe washer.  Watch youtube videos on how to replace a bathtub drain and use new parts as much as possible.
If a renovation is not on the horizon you may be able to replace the liner or remove it and reglaze the tub.
Comment: @user112697 If you do a freestanding tub with a shower curtain, you don't have to tile the walls or worry about the wall and ceiling to tub joints.  Sounds like you already have enough to do...
Comment: In my experience the money to *replace* a bathtub which is usually in an ageing bathroom is better put in a piggy bank towards a total renovation of the room.

Bathtub impersonating waterbed?


RSelenium: loop over all values in dropboxes

Question: I am trying to scrape for each country its table with all HIV/AIDS related NGOs using this link: https://www.unodc.org/ngo/showExtendedSearch.do
I am able to navigate towards the url and select the 'HIV/AIDS' radio button. But now I also need to extract for both the dropboxes 'region' and 'country' all the values so that I can use them inside a loop to sequentially webscrape the table for each country. How can I collect the values for both dropboxes? My code so far is below:
#load library
library(RSelenium)

#Specify remote driver
remDr <- remoteDriver(browserName='firefox')

#Initialise session
remDr$open()

#navigate to advanced search page

url <- "https://www.unodc.org/ngo/showExtendedSearch.do"
remDr$navigate(url)

#Click 'HIV/AIDS' filter
webElem <- remDr$findElement(using = 'css',
                         value = '#applicationArea > form > table > tbody > tr > td > table:nth-child(7) > tbody > tr:nth-child(2) > td > table > tbody > tr > td:nth-child(2) > table > tbody > tr:nth-child(3) > td:nth-child(4) > input[type="checkbox"]')

webElem$clickElement()

Answer: Use firebug or Developer Tools to determine the xpath of the dropdown menu elements then use getElementText to retrieve the values:
 region_element <- remDr$findElement('xpath', '//*[@id="applicationArea"]/form/table/tbody/tr/td/table[2]/tbody/tr[2]/td/table/tbody/tr[1]/td[2]/select')
regions <- strsplit(region_element$getElementText()[[1]], "\n")

country_element <- remDr$findElement('xpath', '//*[@id="applicationArea"]/form/table/tbody/tr/td/table[2]/tbody/tr[2]/td/table/tbody/tr[2]/td[2]/select')
countries <- strsplit(country_element$getElementText()[[1]], "\n")

R> print(regions[[1]])
 [1] "Middle East and Northern Africa"   "Eastern Africa"
 [3] "Western Africa"                    "Central and Southern Africa"
 [5] "Northern America"                  "Central America and the Caribbean"
 [7] "Latin America"                     "Central and Western Asia"
 [9] "Southern and Eastern Asia"         "Europe"
[11] "Oceania"
R> print(head(countries[[1]]))
[1] "Afghanistan"    "Albania"        "Algeria"        "American Samoa" "Andorra"
[6] "Angola"


NSUInteger written into NSData (Objective-c) cannot be converted as integer (Java)

Question: I'm trying to read a binary file written in Objective-C like this :
u_int32_t test = 71508;

NSMutableData * outputData = [ [ NSData dataWithBytes:&test length:sizeof( u_int32_t ) ] mutableCopy ];

// Saves the data
...

// Then reading the value works fine
u_int32_t test;
[ self getBytes:&test length:sizeof( u_int32_t ) ];

Then I'm trying to read the int in Java :
// Read the file
...
Bytes ObjCBytes = byteArrayOutputStream.toByteArray( );
...

// Try to convert my Objective-C byte array to an int :
ByteBuffer buffer = ByteBuffer.allocate( 4 );
buffer.put( ObjCBytes );
buffer.flip( );
int ObjCInt = buffer.getInt( );

But I don't have the same result!
So, I decided to do the same in Java :
ByteBuffer buffer = ByteBuffer.allocate( 4 );
buffer.putInt( 71508 );
bytes javaBytes = buffer.array( );

It seems that the two byte arrays are inverted :
ObjCBytes : {84, 23, 1, 0}
javaBytes : {0, 1, 23, 84}
The behavior is the same regardless of the integer value.
Sorry : I'm newbie ...
I believe that the reason is that Java has no unsigned int ?
I tried a lot of answers, but I have not found the solution.
How can I convert my byte array to an integer regardless of the language used to write it?
Many thanks for your help.
Comment: You could just reverse the byte array on one side or the other.
Comment: @Avi, yes if I consider that the byte array was written if Objective-C. I don't want to do that.
Comment: Reverse it on the ObjC side.  If you also need to read it back in ObjC, you'll know that it was reversed, so you reverse it again.
Comment: @Avi, Thank you but I think that your solution is "a band-aid on a wooden leg". My app will work on Android and Objective-C. So I want to read or write my int regardless of the language used.
Comment: You'll have to choose another method of serialization if you don't want to do the easy thing.  Byte ordering is an old problem, and every implementation needs to deal with it at some point.  Look at the C `hton*` functions, for example.
Comment: @Avi, thanks for your help. I decided to use the BIG_ENDIAN order in Objective-C (CFSwapInt32BigToHost / CFSwapInt32HostToBig) like Java does. That works!
Comment: That's basically what I recommended.  Good choice :)
Comment: Thank you you helped me to understand. So the solution is that I must respect the network byte order which is BIG ENDIAN. https://en.wikipedia.org/wiki/Endianness
Comment: Well, Java uses big endian, while ObjC uses the native ordering (which is little-endian for both x86 and ARM, though ARM can be switched, IIRC).  The only requirement for your code is to be consistent.
Answer: As I understand, NSData use the little_endian byte order by default while Java use big_endian byte order.
More information on Wikipedia
I decided to convert my NSData to big_endian so it can be read in Java:
NSUInteger    test = 71508;

// Java compatibility
u_int32_t bigEndianTest = CFSwapInt32BigToHost( test );

// Writes the value
NSMutableData * outputData = [ [ NSData dataWithBytes:&bigEndianTest length:saltSize ] mutableCopy ];

As needed, the reverse is possible (Java => Little Endian => Objective-C)


Local mail in Thunderbird in /var/mail/username

Question: I'm trying to configure Thunderbird to read local mail, as described in the answer in similar question:
How do I read local email in thunderbird?
However my mail is stored in /var/mail/username file. Thunberbird is looking for mail in /var/spool/mail/ and I get errors that this directory can not be read.
How to configure Thunberbird to read mail from /var/mail/username?
Answer: $ ls -l /var/spool/mail
lrwxrwxrwx 1 root root 7 Feb 14  2012 /var/spool/mail -> ../mail

As displayed, my /var/spool/mail is just a symlink back to /var/mail. I didn't create that but if you don't have it, and it's causing you significant grief in Thunderbird, I wouldn't hesitate to add a link:
sudo ln -s '../mail' /var/spool/mail

And now I read the original answer, it does suggest to use /var/mail/username and shows a screenshot of how to specify it (in the Server Settings tab).

If you're getting read errors and /var/spool/mail exists check:

file /var/spool/mail to make sure it's the right thing
stat /var/mail/$USER is it accessibly by your current user? Is it owned by the right person? Have you copied this from a filesystem with different UID/GIDs? If in doubt, reset the permissions back to the correct ones:
sudo chown $USER:mail /var/mail/$USER
chmod 0600 /var/mail/$USER

Comment: Changing the storage dir as in the original answer does not change anything, still the same error message. Also my `/var/spool/mail/` dir exists, and contains `/var/spool/mail/username` file.
Comment: I've added an if-all-else-fails section.


"Standard" or "best" UI element for "turn offline" and "turn online"?

Question: We have a series of buttons in our administrative interface, for turning systems online or offline (context-sensitive). Currently these buttons are simply either blue "Online" buttons to bring a system online or red "Offline" buttons to bring a system offline.
However, I find the buttons a bit ambiguous; does a blue "Online" button mean it's Online and the button will turn it off, or does it mean clicking the button will bring it online? The matter is made worse by the fact that there are a large number of systems, so the individual lines are small, and the text is difficult to read. Compounding this, one of my coworkers is colorblind, and the somewhat distinguishable (to me) red and blue is lost on him and he's left to squint at the small text.
There is also an online/offline status column (which helps somewhat) to clarify the button's meaning, but then there's the issue of "which is the button and which is the indicator again?". This indicator suffered a similar problem, just stating "Online" or "Offline", using a green/red color scheme (which is even worse for my colorblind coworker).
I used TamperMonkey to fix the indicator, which now presents a very obvious dark green checkmark on light background for "online", or a white "X" in a filled bright red circle for "offline" (so it's using shape, background reversal, color, and intensity to differentiate). However, I'd like to change the buttons so their meaning is just as unambiguous and easy to determine at a glance.
Is there any sort of "standard" means of indicating the action of turning something on or off, or can someone recommend something that's easily intuitive and immediately distinguishable? I'd like something that conveys a change of state, perhaps with an arrow or the like.
Here are the original indicators (pre-userscript):

Here's the current state of our indicators, as a reference (post-userscript, with the check and "X" being my modifications):

(Note that I screenshotted a different set of indicators, so they appear reversed between the two screenshots. In both shots, the line that has the blue "Online" button is currently offline, and the line that has the red "Offline" button is currently online)
Comment: Show both states and the toggle in the middle. -- http://ux.stackexchange.com/a/40954
Comment: Why not use the "in-Flight-Mode" sign like in Android?
Comment: @keuleJ well I've since moved on from this job (and thankfully, the UI has been improved since I asked this question), but an airplane icon (I think that's what you're suggesting?) would be confusing, as our service/interface has nothing to do with airplanes or wireless connections.
Answer: You guys have a major UX issue, since buttons are being used interchangeably for both as buttons and as "status messages".
You have already improved the situation for the better by replacing the button with icons (tick and X). Now just need to modify the text on the button clearer. You could use "Turn ON" and "Turn OFF" on the other action buttons accordingly. Because "online" and "offline" labels on the buttons are just a statement and it's not calling the user for action.
Here is my take: (you could replace my turn on and turn off text links with your buttons).

download bmml source – Wireframes created with Balsamiq Mockups
Comment: We use "Offline" and "Online" as verbs in day-to-day speech, so I'd like to use those as the action titles. I do think that perhaps doing away with the button backgrounds might be the right direction. As a sort of graphic indicator for the state, I was think perhaps the Unicode curved arrows, e.g. "Online ⤴" (U+2934) and "Offline ⤵" (U+2935)? Since onlining a system can be considered "bringing it up" and offlining "bringing it down", I think these arrows convey that action. Do you folks think this adds constructively, or just adds clutter?
Comment: @DoktorJ It's never too late to start enforcing "best practices". Another option would be to add a word to to the buttons/action links to make it verbs e.g; "Make Online", "Offline It" etc. I think arrows might not be the best icons for the statuses, since "down arrow" might also mean server is experiencing difficulty and going down rather than totally offline.
Comment: I like the idea of adding a verb... still trying to find a graphical indicator though, as space on the screen is limited. In case you couldn't tell from the screenshot, the admin interface was designed by engineers :P
Answer: Another option would be to use sliders like on a tablet computer interface. The text could simply say "Online" and if the switch is green and slid say to the left, the system is online. When the slider or text is clicked, the slider moves to the right and goes red (or maybe grey, as it doesn't imply danger so much), then the system is offline, and vice versa when clicked in the offline state. This wouldn't be too radical a change for the users, but would clarify it greatly.
Edit:
If you're looking for a quick fix, you could add clarifying verbs. Where you have "offline" in the post user-script, you could change the text to "take offline", and change "online" to "bring online", etc.


error using aif360 package for bias mitigation

Question: I am revising IBM AIF360 package to resolve bias in data. I installed the package correctly using the command !pip aif360 install in google colab, but after days I was working in my project I got the error described on the bottom, google colab doesn't recognize the dataset which I call to analyze the data, why the installer aif360 package doesn't work, please any idea??
<code># I am using AIF 360
dataset_orig = GermanDataset(protected_attribute_names=['age'],privileged_classes=[lambda x: x >= 25],features_to_drop=['personal_status', 'sex'] )
dataset_orig_train, dataset_orig_test = dataset_orig.split([0.7], shuffle=True)
privileged_groups = [{'age': 1}]
unprivileged_groups = [{'age': 0}]
# Error I got
IOError: [Errno 2] File /usr/local/lib/python3.6/dist-packages/aif360/datasets/../data/raw/german/german.data does not exist: '/usr/local/lib/python3.6/dist-packages/aif360/datasets/../data/raw/german/german.data'

To use this class, please download the following files:

    https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data
    https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.doc

and place them, as-is, in the folder:

    /usr/local/lib/python3.6/dist-packages/aif360/data/raw/german

An exception has occurred, use %tb to see the full traceback.

SystemExit: 1
/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py:2890: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
</code>
Comment: I am using google colab
Answer: This is easy. All you've to do is download these two files from the link :
https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data
https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.doc
and put them in the folder '/usr/local/lib/python3.6/dist-packages/aif360/data/raw/German' and re-run it. It'll work like a charm :).


Practical filter for rain barrel used for irrigation

Question: I bought a house with an 250+ gallon rain barrel that is exclusively used to pump water to the lawn and garden irrigation system. No human or other animal consumption, no swimming pool or hot tub, no water play, no car washing. Because the water coming from the gutters contains all sorts of impurities, there is a whole-house type water filter between the rain barrel and the pump, mostly to protect the pump and the sprinkler heads. Everything works very well.
The problem is that the previous owner used a 30-micron filter cartridge (pleated) that quickly clogged up, reducing water flow to the point that the sprinklers would no longer rise. A new filter brought everything back to normal.
But, it seems that 30 microns is overkill for this application. I can get a 100 micron filter, but even that seems to be overkill. I just want to remove anything that would clog the pump or sprinkler heads. Sanitation is irrelevant.
Any ideas for a substitute cartridge better suited to irrigation applications?
It's a common 10 x 4.5 filter with a 1-inch center hole.
UPDATE: I didn't say it explicitly, but all I have against continuing to use the 30 micron filters is the expense. But, I have a filter cleaning kit I bought for our spa filter, and I'm going to try that. Also, I've since learned that there are lots of contaminants in roof runoff that I don't want on my garden edibles, and, while even a simple 30 micron filter won't eliminate all of them, going to a coarser filter seems counterproductive. I'll post here whether filter cleaning was successful. (Successful means that the water flow is restored to what it is with a new filter, or nearly so.)
Comment: Find out what the pump can take.  The filter is to remove particles that can damage the pump.  Filters cheap, pumps expensive.
Answer: I'd want to see what could be done with something like a big sand filter (easily backwashed) on the way INTO the tank, without backing up too much and losing too much water. However....
For drip irrigation, a 200-mesh filter (74 micron) is generally considered adequate by most manufacturers. This one suggests 150 mesh as adequate for this product.
Sprinklers don't even need that much, a far as I recall. Check the documentation for your specific sprinker types. This site suggests 30 mesh (533 micron) for sprinkler heads, 60 mesh-100 mesh (254-152 micron) for irrigation valves and gear-drive sprinklers.
No affiliation with either site, just looking for irrigation filtration suggestions from suppliers.
I will say that the type of filter that swirls the water around a screen element and dumps the crud down where you can blow it out (and clean the screen) by opening a valve for a few seconds is far more convenient (and less expensive to maintain) than a cartridge filter where you have to take it apart and discard the element, when dealing with water with a lot of crud in it.
Given your update mentioning concerns with other roof runoff contaminants, you might want to insert e.g. a reed-bed filter or similar (plenty of info available from permaculture resources, for free, even) between the roof and the storage. That might require moving the storage downhill or underground (the other flavor of downhill, when a hill to go down isn't actually handy.)
Answer: Some filter setups, eg for swimming pools, let you easily "backwash" the filter, running water backward through it to flush the material it caught to a place where it won't clog things. You can do the same manually by dismounting the filter and running water through it the other way, or dismounting the filter medium and washing it in a sink.


React Custom Hook not triggering DOM updates

Question: Here's a sandbox reproducing my issue:
https://codesandbox.io/s/ymmyr3o70x?expanddevtools=1&fontsize=14&hidenavigation=1
For reasons I can't understand, when I add product via the form, the product list is only updated once, then never again.
I'm using a custom hook (useObservable) combined with RxJS to manage state. If you check the console logs, the ReplaySubject does emit the expected values. But the useObservable hook is not triggering an update of the DOM.
What am I missing?
Answer: The issue is that your addProduct function mutates the old state instead of creating a new one. Yes, you have the observable emit the state again, but since its the same object as before, calling setValue has no effect and so react does not rerender.
The solution to this is to make the state immutable. For example:
import { ReplaySubject } from "rxjs";

let products = {};

export const products$ = new ReplaySubject(1);

export const addProduct = product => {
  products = {...products, [product]: product};
  products$.next(products);
};

Comment: Of course! React state 101. For some reason it didn't occur to me when using hooks. I'm surprised they don't remind users about this in the docs, or throw up a warning in the console. Anyway, problem solved. Thanks


How to prove that $2+2 = 2*2 = 2^2 \cdots= 4$

Question: One day, I noticed that
$2+2 = 2*2 = 4$.
Later, I learned that
$2+2 = 2*2 = 2^2 = 4$
Multiplication is an abstraction of a lot of additions , exponential is an abstraction of a lot of multiplications...  I'm sure there is always an abstraction of the previous operation.
But my questions is : if I use any abstraction with the numbers $2$ and $2$ does it always result $4$ ?
Comment: $2/2=1$, case closed.
Comment: Look at http://en.wikipedia.org/wiki/Hyperoperation and at http://en.wikipedia.org/wiki/Ackermann_function.
Comment: I don't understand the downvotes. The question is asking whether $2$ tetrated to $2$ or $2$ pentated to $2$ and so forth always results in $4$ (and also a proof it seems). Seems like a valid question to me.
Comment: @Raskolnikov $3/3 = 1$ and $3+3 ≠ 3^3$  I don't understand what you mean.
Comment: See Corollary 2(iii) on p. 97 of: John Doner and Alfred Tarski, [*An extended arithmetic of ordinal numbers*](http://www.math.ucsb.edu/~doner/articles/Doner-Tarski.pdf), **Fundamenta Mathematica** 65 (1969), 95-127.
Answer: I think the "deep" reason for this is that these are all binary operations.
Given a binary operation $\ast$ on integers at least $2$, define $\ast'$ by $$m\ast' n = \overbrace{m\ast m\ast \cdots \ast m}^{n\text{ times}}.$$
Always associate to the right (for concreteness), so that $a\ast b\ast c = a\ast(b\ast c)$ and so on.
Now starting with any binary operation $\ast$, define $\ast_1=\ast$ and $\ast_{n+1} = \ast_n'$. Then for all $n$ we clearly have $2\ast_n 2 = 2\ast_{n-1} 2 = \cdots = 2\ast 2$.
The sequence you consider is given by taking $\ast$ to be $+$.
Comment: Exercise: Find $\ast$ such that $\ast'$ is $+$.
Comment: This is what we always do in a vector space.
Comment: @SeanEberhard I think the operation $*$ such that $*'$ is $+$, is **incrementation** and needs just one number. :)
Comment: @SeanEberhard: Well, as $a\ast'1=a$, that makes the exercise tricky...
Comment: @GeorgeLowther I only defined $\ast'$ on integers at least $2$.
Comment: @SeanEberhard: Ah, I missed that bit. In that case, the exercise does have a solution.


PHP- Regex to match words with more than two letters

Question: I'm trying to explode a string into a word array, the condition is that a word is considered as such only if it has two or more letters, what I have is the following, but words with a single letter are still being considered as match:
$input_string = "I have a cake inside my fridge";

$string_array = preg_split("/[^\w{2,}]*([\s]+([^\w{2,}])*|$)/", $input_string, -1, PREG_SPLIT_NO_EMPTY);

But I'm still getting the words "I" and "a", why it isn't working?
Comment: Alt without regex.. i.e less confusing, explode with array_filter: https://3v4l.org/kdPgh
Comment: @LawrenceCherone Yeah, thank you, but it has to be done with a regex pattern :/
Comment: What is the exact output you expect here?
Answer: If you just want to capture all "words" having 2 or more letters, then just use preg_match_all here:
$input_string = "I have a cake inside my fridge";
preg_match_all("/\b\w{2,}\b/", $input_string, $matches);
print_r($matches[0]);

This prints:
Array
(
    [0] => have
    [1] => cake
    [2] => inside
    [3] => my
    [4] => fridge
)

Answer: The reason it is not working is because the pattern [^\w{2,}]*([\s]+([^\w{2,}])*|$) matches only spaces, and then you split on those spaces resulting in an array with all the words. This is due to \s which matches a whitespace char, and using the negated character class [^\w{2,}] which also matches whitespace chars.
If you want to use split, you also have to match the single word characters so that they are not part of the result.

If you must use split, you can match either a single word character surrounded by optional horizontal whitespace characters to remove those as well, or match 1+ horizontal whitespace characters.
\h*\b\w\b\h*|\h+

Regex demo
For example
$input_string = "I have a cake inside my fridge";
$string_array = preg_split("/\h*\b\w\b\h*|\h+/", $input_string, -1, PREG_SPLIT_NO_EMPTY);
print_r($string_array);

Output
Array
(
    [0] => have
    [1] => cake
    [2] => inside
    [3] => my
    [4] => fridge
)

If you want to match all strings that consist of at least 2 characters, you could also use \S{2,} with preg_match_all.


I want to convert my HTML page into image and upload the same on server using JavaScript

Question: I'm using html2canvas ,able to generate the screenshot and open the same in another window. However, the response of my HTML page is dynamically created and I need to upload the same screenshot to server, Bluemix recursively and retrieve the same from any other application using the URI.

html2canvas(document.getElementById("mydiv")).then(function(canvas) {
     // Export the canvas to its data URI representation
      var base64image = canvas.toDataURL("image/png");
     // Open the image in a new window
    window.open(base64image , "_blank");
  });

I have tried saving the image using Blob, but that's not working.

html2canvas(document.getElementById("mydiv")).then(function(canvas) {
    // Export canvas as a blob
    canvas.toBlob(function(blob) {
        // Generate file download
        window.saveAs(blob, "yourwebsite_screenshot.png");
    });
});
Answer: You won't get real HTML rendering to  per se currently, because canvas context does not have functions to render HTML elements.
There are some emulations:
html2canvas project http://html2canvas.hertzen.com/index.html (basically a HTML renderer attempt built on Javascript + canvas)
HTML to SVG to  might be possible depending on your use case:
https://github.com/miohtama/Krusovice/blob/master/src/tools/html2svg2canvas.js
Also if you are using Firefox you can hack some extended permissions and then render a DOM window to
https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_Graphics_with_Canvas?redirectlocale=en-US&redirectslug=Drawing_Graphics_with_Canvas#Rendering_Web_Content_Into_A_Canvas


Killing all entities except players and armor stands

Question: Is there a way to kill every entity except players and armor stands? I've tried with
<code>/kill @e[type=!Player,!ArmorStand]
</code>
and
<code>/kill @e[type=!Player;!ArmorStand]
</code>
But it doesn't work. How can I do that?
Comment: I'm not familiar with the `/kill @e` command because I don't regularly play in 1.8, but try `/kill @e[type!= Player, ArmorStand]`
Comment: @ModDL - not a duplicate. Yeah that's close, but it's `@e[type!=Player,type!=ArmorStand]`, I believe
Comment: Same thing, just replace the item with armor stand
Answer: Run these commands first:
<code>/scoreboard objectives add blackList dummy
</code>
Run these on a clock:
<code>/scoreboard players set @e blackList 1
/scoreboard players set @e[type=Player] blackList 0
/scoreboard players set @e[type=ArmorStand] blackList 0
</code>
Lastly kill all entities that don't have a blackList score of 0:
<code>/kill @e[score_blackList_min=1]
</code>
(edited 5/26/19 for Minecraft 1.14.1)
Comment: oops, made a mistake there
Comment: Since `selectMe` scoreboard objective didn't exist, I replaced it with `blacklist` and it worked like a charm :D
Thank you very much ;)
Comment: There should be no spaces between score_blacklist_min[SPACE]=[SPACE]1, that gives the error: The entity UUID provided is in an invalid format
Comment: @Maximuym please add the content of your edit as a new answer.


Launch view from app delegate

Question: I need to launch a view from the delegate (and switch the selectedViewController).After the view switching I need to execute a view method from the delegate....How I can do that.
For mor precision this is the app delegate method.
<code>-(void)launchOtherView{
NavigationCtrl *navCtrl = [self.rootController.viewControllers objectAtIndex:3];

    PrimaryView *prmView;

    //Need to lauch the view(navCtrl) .. for that it's ok..

    //Now I need to get the first view of the navCtrl...

    //After I need to execute a view method (someMethod:)
</code>
}
Thanks
Answer: Drop the navigation controller from the tools--->Library-->objects.
connect the navigation controller to its instance created in appdelegate class.
open MainWindow.xib and connect the file's owner delegate to instance of UINavigationController.
Drop the navigation controller object and inside atttach the view contoller which view you want to launch first.
All inside the implementation file of the will get executed.

Launch view from app delegate


A question related to improper integrals

Question: Been stuck on it for quite a while now, any help would be appreciated:
Prove or provide counterexample:
Let $f$:[1,$\infty$)$ \rightarrow\Bbb R$ be a continuous function. if $f>0$ and integrable on [1,$\infty$), then there exists some sequence ${x_n}$ $\rightarrow$ $\infty$ such that $\lim_{n\to \infty}f(x_n)=0$

My attempted solution:
This statement seems true as I could not find a counterexample, so here is my solution (I got stuck in the process):
Define $g(x)=\int_{1}^x f(t)dt$,
then: $\lim_{x\to \infty}g(x)=\lim_{x\to \infty}\int_{1}^x f(t)dt=L>0$
By the fundamental theorem of calculus we get:
$g'(x)=f(x)>0$
Hence $g$ is strictly increasing, is bounded above by $L$ and positive.
If only I were able to show that $\lim_{x\to \infty}g'(x)=0$ then my proof would be done but I could not figure out how.
Thank you for your input!
Answer: The thing is that it need not be the case that $g' = f \to 0$. Consider, for instance, the case where in each interval $[n, n+1)$, the graph of $f$ looks like a triangle of height $n$ but width $1/n^3$, outside of which $f$ is $0$. Such an $f$ of course satisfies the claim, but it scuppers your stategy.
On the other hand, we know that $\liminf f = 0$. Otherwise there is some $\varepsilon > 0$ such that $f > \varepsilon$ for large $x$, which makes the integral of $f$ blow up. Since $\liminf$s are approached arbitrarily closely infinitely many times, this tells us that a sequence of $x_n$ such that $f(x_n) \to 0$ must exist.
One can be quite explicit in identifying such a sequence. For naturals $n$, let $m_n := \min_{x \in [n,n+1]} f(x),$ let $y_n$ be the corresponding minimiser (which exists because continuous function on a compact set), and consider the step function $h := \sum m_n \mathbf{1}\{x \in [n, n+1)\}.$
Then we know that $h > 0$ and $h \le f$ is integrable. So we know that $m_n \to 0$. This gives a sequence of values $y_n$ which diverge (since $y_n \ge n$), and for which $f(y_n) \to 0$.
The only problem with the $y_n$ is that some of the consecutive $y_n$ may coincide - for instance if the minima are at the even naturals. However, it is trivially true that $y_n \neq y_{n+2}$ for any $n$, since they live in disjoint sets. The simple fix then is to go in steps of two. So $x_n = y_{2n}$ serves as a sequence that satisfies the claim.
Answer: For any $n\in \mathbb N,$ we must have $\inf_{[n,\infty)} f=0.$ Otherwise for some $n_0,$ $\inf_{[n_0,\infty)} f =c>0.$ We would then have
$$\int_{n_0}^\infty f(x)\,dx \ge \int_{n_0}^\infty c\,dx =\infty,$$
contradiction.
It follows that for each $n,$ there exists $x_n\in [n,\infty)$ such that $f(x_n)<1/n.$ We then have $x_n\to \infty$ and $f(x_n)\to 0$ as desired.


Exporting world from 1.7.9 CraftBukkit to 1.6.5 or 1.7.2

Question: Is it possible for a world generated in 1.7.9 to be exported to an earlier version, such as 1.7.2 or 1.6.5?
I am aware that people can simply copy world files into respective directories, but I am not sure how far back this applies to.
The main reason I am doing this is to use modifications from the earlier Minecraft version.
Thank you for any comments or suggestions.
Answer: Worlds are generally backwards-compatible, but it has several drawbacks:

Generally, Blocks and Items that were introduced later in the game will simply vanish.
1.7.6 paved the way for name-changing by converting the player data to a new format. Downgrading will mean that everyone starts from scratch, though you can always dump your inventory into a chest, downgrade, an then grab it again.
1.7.2 "Changed the World" by introducing a completely new world generation. While the existing world will largely stay the same (apart from invalid blocks), any newly generated chunks will use the old world generator, which will make for ugly borders
Answer: it would be possible to play that world as far back as you want... but any existing blocks that dont exist in the update you're moving to would be destroyed, as would any Items that dont exist in that update


Force my code to use my extension method

Question: I'm using BitFactory logging, which exposes a bunch of methods like this:
public void LogWarning(object aCategory, object anObject)

I've got an extension method that makes this a bit nicer for our logging needs:
public static void LogWarning(this CompositeLogger logger,
      string message = "", params object[] parameters)

Which just wraps up some common logging operations, and means I can log like:
Logging.LogWarning("Something bad happened to the {0}. Id was {1}",foo,bar);
But when I only have one string in my params object[], then my extension method won't be called, instead the original method will be chosen.
Apart from naming my method something else, is there a way I can stop this from happening?
Comment: Class methods always take precedence over extension methods, so I'd say no. But maybe someone knows of some workaround.
Comment: Extension methods (with similarly-named non-extension method(s)), optional arguments, *and* `params` all in one method? You like confusing the compiler, don't you?
Answer: The rules about how overloaded methods are resolved to one (or an error) are complex (the C# specification is included with Visual Studio for all the gory details).
But there is one simple rule: extension methods are only considered if there is no possible member that can be called.
Because the signature of two objects will accept any two parameters, any call with two parameters will match that member. Thus no extension methods will considered as possibilities.
You could pass a third parameter (eg. String.Empty) and not use it in the format.
Or, and I suspect this is better, to avoid possible interactions with additions to the library (variable length argument list methods are prone to this) rename to LogWarningFormat (akin to the naming of StringBuffer.AppendFormat).
PS. there is no point having a default for the message parameter: it will never used unless you pass no arguments: but that would log nothing.
Comment: Thanks for the PS about the default on the message.
Answer: Declared methods are always preceding extension methods.
If you want to call the extension regardless of the declared method, you have to call it as a regular static method, of the class that declared it.
eg:
LoggerExtensions.LogWarning(Logging, "Something bad happened to the {0}. Id was {1}",foo,bar);

I assume that the extension is declared in a class named LoggerExtensions
Answer: Provided that I think a method with a different name is the way to go (easier to read and maintain), as a workaround you could specify parameters as a named parameter:
logger.LogWarning("Something bad happened to the {0}.", parameters: "foo");


Prove: $(\forall \epsilon > 0 )(\forall x \in K)(\exists U \in O(x))(\forall f \in Z)(\forall y \in U) | f(x) - f(y) | < \epsilon$ .

Question: Let $K$ be compact space and $Z \subseteq C(K, \mathbb{R})$ compact, in metric topology $T_{d_{\infty}}$ on $C(K, \mathbb{R})$ which is induced by metrics $d_{\infty}$. Prove:
$(\forall \epsilon > 0 )(\forall x \in K)(\exists U \in O(x))(\forall f \in Z)(\forall y \in U) | f(x) - f(y) | < \epsilon$ .
P.S.$C(K, \mathbb{R}) $ is set of all continuous functions from $ K$ to $ \mathbb{R}$.
I'm not sure what technique should I use for solivng this. Any hint helps!
Answer: Assuming $K$ is Hausdorff and $d_\infty$ is the metric induced by the uniform norm $C(X,\Bbb R)$, the claim required to prove is a corollary of Arzelà–Ascoli theorem for compact Hausdorff spaces.


Joomla Akeeba Fatal error

Question: My client set auto-upgrade for a component "Smart form golder' component.
After the auto upgrade, Akeeba components stop working.
It throws fatal error in administrator component page -

Fatal error: Access level to AkeebasubsToolbar::renderSubmenu() must be public (as in class FOFToolbar) in /public_html/administrator/components/com_akeebasubs/toolbar.php on line 358

But the front end working fine, when I checked with Akeeba support forum, they said that it requires upgrade. I customize the component so I am not willing to do also the upgrade can be done through Joomla admin panel and the page are not loading properly. So I am not sure how to fix this.
Please help me.
Comment: if you have customized the component and aren't willing to do an upgrade then you're pretty much stuck. This is why customizations should be done using plugins
Answer: Simply reinstall the modified version of the fof your version of Akeeba component came from. Your new component "smart form golder" may stop working.
fof - "framework on framework" is now integrated in Joomla since version 3.2.  It was developed by Akeeba and ships with all their components; alas it changed a lot between versions, you usually need the exact version the component shipped with.
Comment: Is the downgrade of Smart form golder will fix the issue? Please comment.
Comment: You'd be better off starting over from a backup, or uninstalling the Smart form golder and reinstalling the right version (careful: uninstalling may wipe your db configuration of smart form, make a backup)
Comment: Guys, fatal error in com_akeebasubs is a bug of com_akeebasubs. There is nothing to do with SmartFormer gold
Comment: @nico Apparently smartformer installed a version of fof which was not compatible with akeebasubs, so it seems the issue was with the smartformer installation, not with smartformer itself
Comment: There are a lot of similar errors in google. Just run search for "Fatal error: Access level to AkeebasubsToolbar::renderSubmenu() must be public (as in class FOFToolbar)". The people reporting the error do not have smartformer installed.
Comment: Of course: the issue is an incompatible version of fof, but not only akeeba and smartforms use it: its use is so widespread that it was introduced in the Joomla core

Joomla Akeeba Fatal error


Combinations for Screen lock For iPhone / Android

Question: I was wondering if there was a general for formula to calculate the combination of the password lock for the current smart phones

The following is the condition

We must use four nodes or more to make a pattern at least.
Once anode is visited, then the node can't be visited anymore.
You can start at any node.
A pattern has to be connected.
Cycle is not  allowed.

If using 4 as the minimum string for the password with 9 nodes , the result is 389112.
Is there anyway to estimate the number of combinations for 16 nodes, 25 nodes and so on?
Comment: The number 389112 shows up exactly once at the Online Encyclopedia of Integer Sequences, at http://oeis.org/A160743 where it's $8P_7(n)$, Legendre polynomial of order 7. I doubt it's related, just thought I'd save others the trouble of consulting OEIS.
Comment: [This question](http://math.stackexchange.com/questions/37167/combination-of-smartphones-pattern-password) is closely related. It's very nearly a duplicate, including the same image and wording, except it doesn't ask about the generalization to larger grids.
Comment: Note that the answer $389112$ is obtained if the rules specified in [this other duplicate](http://math.stackexchange.com/questions/128423/9-dots-possible-combinations-problem) are assumed. If these are the intended rules, the present problem description is incomplete.
Comment: @dii, did you see where I wrote, "I doubt it's related"?
Comment: @GerryMyerson I am just learning about Legendre Polynomials and I am glad of you mentioning it. I did not know that Legendre Polynomials will be useful for these types of problems.
Comment: @GerryMyerson way to spoil Legendre polynomials then.
Comment: how Legendre Polynomials  and Legendre's differential equation can solve this problem?
Comment: As @Gerry wrote, they most likely can't. It's most likely just a coincidence.
Answer: Since each dot can be the starting point for the pattern, the number of possibilities are as follows:

4 dots combination (since this is the minimum required): 9 dots (starting points) ^ (raise to the power) 4 = 6,561 patterns
5 dots combination: 9 dots ^ 5 = 59,049 patterns
6 dots combination: 9 dots ^ 6 = 531,441 patterns
7 dots combination: 9 dots ^ 7 = 4,782,969 patterns
8 dots combination: 9 dots ^ 8 = 43,046,721 patterns
9 dots combination: 9 dots ^ 9 = 387,420,489 patterns

Total possible number of patterns = 435,847,230 patterns
Comment: That's not right. The dot sequence must be *connected*.


Covering Trex Enhance Board Ends

Question: I am installing Trex Enhance decking and would like to know how to cover the scalloped profile ends.  I could picture frame the deck to cover the ends.  How much overhang should the board have before attaching the facia board underneath it?
An alternative to picture framing is to cover the scalloped profile ends with facia board.  I won't overhang the board ends with this option.  I don't see as many people doing this and am wondering if there is a reason other than aesthetics.
Answer: The 2 choices you suggested are pretty much the standard. The amount of overhang for the first choice can be varied, from a 1/2" to 1", perhaps as much as 1 1/4" AFTER the fascia is applied. This will require screws through the top to help keep it in place.
There is no reason the second choice will not work either, it give a more contemporary/modern look that may or may not fit your exterior of your home. The other is more traditional. The fascia board will need to be wider for the second choice, to cover the framing the same as the first choice.
If it was me in either case, I would router the cut ends and edges the same radius as the  uncut factory edges, so all the gaps take on the same look.

Covering Trex Enhance Board Ends


Give angles to images in circular slider

Question: I'm making a circular image slider. When a user clicks on any images it slides into center. On the left side images I want to to add in class to give some angle, and right side image I want to add in different class to give different angle.
Javascript:
$(document).on('click', 'img', function() {
    var t=$(this);
    t.prevAll().removeClass('t2').addClass('t1');
    t.nextAll().removeClass('t1').addClass('t2');
}

CSS:
.t1
{
    transform: skewX(5deg) skewY(175deg); /* W3C */
    -webkit-transform: skewX(5deg) skewY(175deg); /* Safari & Chrome */
    -moz-transform: skewX(5deg) skewY(160deg); /* Firefox */
    -ms-transform: skewX(5deg) skewY(175deg); /* Internet Explorer */
    -o-transform: skewX(5deg) skewY(175deg); /* Opera */
}

.t2
{
    transform: skewX(-5deg) skewY(15deg); /* W3C */
    -webkit-transform: skewX(-5deg) skewY(10deg); /* Safari & Chrome */
    -moz-transform: skewX(-5deg) skewY(5deg); /* Firefox */
    -ms-transform: skewX(-5deg) skewY(10deg); /* Internet Explorer */
    -o-tran
}

On click event of image I am giving angle, but on click of last '12th' images will not show correct alignement because previous all will go in same class, how to do it?

Comment: We'll need to see more code than this to help though..
Comment: please replicate your problem on jsbin.com.
Comment: in jsfiddle and bin its not working , cause it has so many files
Answer: Unfortunately, perspective seems not to be supported yet (at least in chrome where I tested it).
But you can use other transformations, just use the css attribute transform (or the prefixed ones):
img {
  -webkit-transform: skew(-10deg, 5deg);
  -moz-transform: skew(-10deg, 5deg);
  -o-transform: skew(-10deg, 5deg);
  -ms-transform: skew(-10deg, 5deg);
}

Check out this example (tested in chrome): http://jsfiddle.net/uynXh/5/


Removing sublimetext installation

Question: I followed this link
http://www.technoreply.com/how-to-install-sublime-text-2-on-ubuntu-12-04-unity/
To install sublime-text 2 and i followed the steps hoping it would work and it does. Except that now whenever i open sublime. It has a default.list, sublime.desktop file that always opens with it. Then when i try to register with my license it works, but when i re-open the text editor its once again unregistered.
I think installing it how i did must of broken sublime-text altogether and i have no idea how to reverse the effects. I was hoping someone here could help me out.
Also installed it through the sudo apt-get install sublime-text-installer but it turns out after doing what i did in the techno install tutorial it busted the whole thing.
i should also mention that i tried to remove these files myself using sudo rm or sudo rm -rf but they seem to be already deleted. Yet it still says they exist even though when i try to remove them now it says files could not be found.
Answer: If you did this:
sudo mv Sublime\ Text\ 2 /opt/

then
sudo rm -rf /opt/Sublime\ Text\

will remove the software. If you want to make sure go to /opt and do an ls and then remove the directory will all its contents.
There are some residual files that you can remove with:
sudo rm /usr/share/applications/sublime.desktop

And you need to redo the changes to defaults.list. So do a sudo sublime /usr/share/applications/defaults.list and replace all references to sublime.desktop to gedit.desktop. Or restore a backup you made.

Removing sublimetext installation


Show that a non-constant holomorphic function has zeroes in a compact set

Question: I am struggling with the following exercise:

Let $G \subseteq \mathbb{C}$ be a domain and let $K \subset G$ be compact with non-empty interior. Let further be $f: G \rightarrow \mathbb{C}$ a holomorphic and non-constant function with $\lvert f(z) \rvert = C$ for all $z \in \partial K$ and some constant $C \in \mathbb{R}$.
Show that $f$ must have zeroes in $K$.

My idea is this: I think it should be true that the the maximum value of $f$ on $K$ has to be on the boundary of $f(K)$ and is due to our assumption equal to $C$. So the disk centered at $0$ with radius $C$ should contain $K$. All the values of $f$ in the interior of this disk have to be smaller than $C$ , however. I guess that we may now conclude that $f$ has to be equal to $0$ for some point in $K$.
Could you tell me if I am on the right track?
Comment: Assuming $f$ has no zero, think about $1/f$...
Comment: You know $|1/f|\le1/C$, so $|f|\ge C$. You also know $|f|\le C$, and hence $|f|=C$...
Comment: Yes, you're misunderstanding a great deal. The fact that $|f|=C$ shows that $f$ is constant; of course it does not imply $f=C$. You should probably have learned the Open Mapping Theorem by now...
Comment: The question is how $|f|$ constant implies $f$ constant. Can you _state_ the OMT? Is $\{z:|z|=C\}$ an open set?
Comment: @DavidC.Ullrich: I can only see the following: If $f$ has no zeroes on $K$ then we can safely define $1/f$. On the boundary of $K$ $1/f$ takes on $1/C$ and insided $K$ the values of $f$ have to be smaller. But I do not see what comes now.
Comment: @DavidC.Ullrich: I fear I still do not get it. You are saying that $\lvert f \rvert \equiv C$ on $K$. I can follow you that far. If I understand you right you now want to argue that $f \equiv C$ on $G$. I guess that you want to use the Identity Theorem with the following argument: $K$ is compact, thus it has an accumulation point and since $f \equiv C$ on $K$ we have $f \equiv C$ on $G$ by the  Identity Theorem. But I have an objections to this: $f= \lvert C \rvert $ does not imply $f = C$. Do I misunderstand anything?
Comment: @DavidC.Ullrich: I think I got it now: We can use the Identity Theorem to see that $\lvert f \rvert \equiv C$ on $G$ as outlined above. And since $G$ is a domain and $f$ is holomorphic the fact that $\lvert f \rvert $ is constant implies that $f$ is also constant. I am rather sure that this should work. I would still be interested how you can use the Open Mapping Theorem here; could you explain?
Comment: @DavidC.Ullrich: I got it now, you use the OMT and the fact that $\{z \mid \lvert z \rvert = C \}$ is not open to prove that $\lvert f \rvert \text{ constant } \implies f  \text{ constant }$. Till now I have only seen this proved via the Cauchy-Riemann Differential Equations; hence my confusion. Thanks a lot for your help!
Comment: You can also get it from the C-R equations, yes. Using OMT seems simpler/cleaner; as we saw in the first version of the answer, getting it from the C-R equations involves $\log f$, which then leads to an argument that has to be stated carefully, since $\log f$ exists locally but not globally.
Answer: By maximum modulus principle, $|f|\le C$ on $K$.
Assume there are no zeroes in $K$, then by minimum modulus principle $|f|\ge C$ on $K$. Therefore, $|f|\equiv C$ on $K$.
Choose an arbitrary $z_0\in K$. By assumption $f(z_0)$ is non-zero, thus $g:=\operatorname{log} f$ defines a holomorphic function on a open neighbourhood $B$ of $z_0$ (composition of holomorphic functions is holomorphic).
We notice $\Re g=\operatorname{log}|f|=\ln C$ is constant on $B$, thus by Cauchy-Riemann's equations $\Im g$ is also constant on $B$. Hence, $g$ is constant on $B$, and so is $f$. By identity theorem, $f$ is constant on $K$, contradicting the given condition that $f$ is non-constant.
Comment: @DavidC.Ullrich Thank you for pointing out such serious mistake. I guess $f(z)=z$ defined on an origin-certered annulus is an example of your claim. I have modified the proof accordingly. Regarding your second point, I did not assume $|f|=C$ on $K$. I derived it under the assumption of absence of zeroes.


Let $A$ and $B$ be two invertible matrices. Prove or disprove that $A+B$ is invertible.

Question: I need help on this question. I know $A+B$ cannot be invertible, but I dont know how to prove it to my professor?
Comment: Let $A+B=0$ and done.
Answer: Let $A=I$, $B=-I$, is $A+B$ invertible?
Also, consider $A=I$, $B=I$, is $A+B$ invertible?
Answer: Like @SiongThyegoh said, there is no way to produce a general theorem. I would like to add some cases.

$A$ and $B$ could be invertible but not $A+B$ (take $A=I_n$, $B=-I_n$)
$A$ could be invertible,and $B$ not but $A+B$ is (take $A=I_n$, $B=0$)
$A$ and $B$ could both be not invertible but $A+B$ could be:

$$A:=\begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}$$
and
$$B:=\begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}.$$


Enable PHPUnit with Laravel / Homestead on PhpStorm 2016.1 to

Question: I am working on vagrant / homestead, and have a box configured.
I could enable Xdebug in PhpStorm!
Now, I want to enable PHPUnit, but I can't do it...
I followed several tutorials:
https://blog.mayflower.de/5274-Run-your-tests-with-PHPStorm-on-your-vagrant-box.html
https://confluence.jetbrains.com/display/PhpStorm/Running+PHPUnit+tests+over+SSH+on+a+remote+server+with+PhpStorm
Here are my settings:

Here is the message I receive when running PhpUnit with Code Coverage
<code>vagrant:///Users/julien/Homestead/usr/bin/php -dxdebug.coverage_enable=1 /home/vagrant/.phpstorm_helpers/phpunit.php --coverage-clover   /home/vagrant/.phpstorm_helpers/coverage/Laravel_PhpUnit.coverage -- configuration /home/vagrant/Code/vendor/autoload.php  /Users/julien/Documents/Proyectos/laravel/tests/functional
Testing started at 11:12 AM ...

bash: line 0: cd:  /Users/julien/Documents/Proyectos/laravel/tests/functional: No such file or  directory
PHP Fatal error:  Uncaught UnexpectedValueException: Cannot create phar  '/home/vagrant/Code/vendor/bin', file extension (or combination) not  recognised or the directory does not exist in  /home/vagrant/.phpstorm_helpers/phpunit.php:181
Stack trace:
Fatal error: Uncaught UnexpectedValueException: Cannot create phar   '/home/vagrant/Code/vendor/bin', file extension (or combination) not  recognised or the directory does not exist in  /home/vagrant/.phpstorm_helpers/phpunit.php on line 181#0  /home/vagrant/.phpstorm_helpers/phpunit.php(181): Phar- >__construct('/home/vagrant/C...')

#1 /home/vagrant/.phpstorm_helpers/phpunit.php(250):    IDE_PHPUnit_Loader::init()

#2 {main}
UnexpectedValueException: Cannot create phar '/home/vagrant/Code/vendor/bin', file extension (or combination) not recognised or the directory does not exist in /home/vagrant/.phpstorm_helpers/phpunit.php on line 181
thrown in /home/vagrant/.phpstorm_helpers/phpunit.php on line 181

Call Stack:
0.0006     442920   1. {main}() /home/vagrant/.phpstorm_helpers/phpunit.php:0
0.0006     442920   2. IDE_PHPUnit_Loader::init() /home/vagrant/.phpstorm_helpers/phpunit.php:250
0.0006     451168   3. Phar->__construct() /home/vagrant/.phpstorm_helpers/phpunit.php:181

Process finished with exit code 255
</code>
Answer: Setting up vagrant with PhpStorm and PHPUnit can be a little bit daunting as it is really not that straight forward... From your console output I'd say that your interpreter setting is not correct since it executes PHP on your local machine.
The way that always worked for me was setting up vagrant as SFTP Deployment Configuration and use that configuration as PHP interpreter. As you are already using Homesteasd, these tutorials might shed some more light onto the setup:

Setting up PhpStorm with Vagrant on a Laravel Homestead box
Setting up Laravel with PHPUnit on Vagrant in PhpStorm

Here are the essential parts:


How to filter Sanity posts by category title?

Question: Here what I've done in vision
*[_type == "post" && categories == SOCIAL ]{
  _id, title
}

It returned
No documents found in dataset production that match query:

*[_type == "post" && categories == SOCIAL ]{
  _id, title
}

Comment: So it's not an array of strings. You need to write it like this: `"SOCIAL" in categories[].title`. If `categories` is an array of refs, however, you need to write it like this: `"SOCIAL" in categories[]->title`.
Comment: Is `categories` an array that can contain the string `"SOCIAL"`? If so you have to use `in`: `*[_type == "post" && "SOCIAL" in categories]`.
Comment: @AlexanderStaubo
No documents found in dataset production that match query:

*[_type == "post" && "SOCIAL" in categories]
Comment: Is `categories` an array of strings?
Comment: @AlexanderStaubo

"result":[8 items
0:{6 items
"_createdAt":"2021-12-15T05:14:53Z"
"_id":"167d5d3e-ce1b-4f0c-a092-aa81213bed41"
"_rev":"wY9KfPeCwmcMrJtIpsqdOq"
"_type":"category"
"_updatedAt":"2021-12-15T05:14:53Z"
"title":"SOCIAL"
}
Comment: @AlexanderStaubo "No documents found in dataset production that match query: " for both
Comment: Flagging this question because the author should provide one of: content schema or at least the result of querying `post` documents without other filters. Otherwise, people have to guess the structure of documents so they can't provide a correct answer
Answer: *[_type == "post" &&  "social" in categories[]->title]{
title
}

Answer: You have to format it like so:
*[_type == "post" && categories == "SOCIAL" in categories[]->title]{
  title,
  slug,
  body
}

If nothing shows up then there are no posts associated with that category. Categories are also case sensitive, so make sure your capitalization is right.
Answer: *[_type == 'post' && category->name == 'Technology']
Can also try this in cases where your categories are not saved as arrays.
Answer: What worked for me is instead of searching by the name of the category i searched using the ._ref property of the category.
It would look something like this
    *[_type == "post" && categories == categories._ref]


convert video file to .ogg

Question: I've been having trouble with this because I'm new to Linux:
I would like to convert different video formats to ogv.  I found some terminal commands like this: ffmpeg -i input.avi -acodec libvorbis -ac 1 -b 768k output.ogg
The problem with these type of commands is that they are intended to change bit rate, fps, or even resolution.  I would like to just change the file format without changing anything else about the video.
I looked at the man pages for ffmpeg and found some useful info but I don't know how to space command-line options.
Are there any easy ways to do this?  In addition, is there a command to change the bit rate so that it doesn't go over a certain rate?
Answer: You can simply run this to do the conversion.
ffmpeg -i neha.avi -acodec libvorbis output.ogg

Dont bother to put any options for bitrate or aspect ratio. It will choose for itself.
You can set the max audio bitrate to 192000 (or whatever value you want, upto 320000 AFAIK) by adding -ab 192000 anywhere in the command. Also, you set the video bitrate at say, 1200kb (or any other value), by including -b 1200kb in the command.
So here is the command in the end, (the order of options dont matter, since you asked. nothing to worry)
ffmpeg -i neha.avi -acodec libvorbis -ab 192000 -b 1200kb output.ogg

Here is a good guide to all that you might want to do.
Comment: thank you for the reply
I will try but 192000kb is less then my source file has can I rise the value
Comment: You sure can. Also, reading the manual (`man ffmpeg`) is very easy. Just try out.
Comment: If it works, consider Accepting the answer so if anyone else sees, they'll know. Ffmpeg is ultra-powerful, good luck with it!
Comment: sadly non of this works same problem it just does it's own thing does not cars what I tell it to do
Comment: sorry my video has 25mb+ video bit rate and 1.2 mb is just not enough as a top value
Comment: The value can be anything, @Levan. You can change it to whatever you want.
Comment: ffmpeg -i '/media/levan/BEEA60D8EA608E89/w8/CIMG8599_1.avi' -acodec libvorbis -ab 192000 -b 226304k ~/test.ogg this is a commend i tried
yes it encoded but from a 221 Mbps I got  8 200 Kbps
Answer: I don't usually use the terminal for my audio/video conversions. I guess that's one area where I like to stick to the GUI.
There's a Windows application called Format Factory, and it runs well in WINE. Once you install it, the left side of the window has all the conversion options. I think it's pretty self-explanatory from there. I hope that works!
Comment: thank you for the answer but I want one to one conversion of files  and can it convert video files ??
Comment: yes, Format Factory does all sorts of conversions. Video, Audio, Picture, and you can even rip DVDs with it. As far as one to one conversion, I'm not entirely sure what you mean (probably just my noobiness) but I've always found it to work well for everything I need to do.
Comment: There is a very powerful tool to do this, and you can do it using a terminal. Why not when you can? Refer my answer.
Comment: person who edited my question chopped it up so bad that it is hard to understand what was my question. I want same fps, video/audio bit rate, resolution, aspect ratio
Comment: Saw your original question. You can just not specify all the options, and it'll pick them for itself.
Comment: My source file has 25 mb of video bit rate 30 fps and 384 kb of audio
 when i use ffmpeg it just lowers the video and audio bit rate and I do not want that I want my quality to be as good as the source
Answer: http://www.iasptk.com/ff-multi-converter-is-a-simple-graphical-application-which-enables-you-to-convert-audio-video-image-and-document-files-between-all-popular-formats
FF Multi Converter is a simple graphical application which enables you to convert audio, video, image and document files between all popular formats, using and combining other programs. It uses ffmpeg for audio/video files, unoconv for document files and PythonMagick library for image file conversions.
The goal of FF Multi Converter is to gather all multimedia types in one application and provide conversions for them easily through a user-friendly interface. Extra options will be gradually added.
The application is written in python and PyQt.
All code is licensed under the GNU General Public License.
FF Multi Converter is free software - software that respects your freedom.
Features
Conversions for several file formats.
Very easy to use interface.
Access to common conversion options.
Options for saving and naming files.
Recursive conversions.
Installing on Ubuntu and Debian
Stable release
To add the ppa to your system resources and install ffmulticonverter, open a terminal and enter:
sudo add-apt-repository ppa:ffmulticonverter/stable

sudo apt-get update

sudo apt-get install ffmulticonverter

Answer: I found pretty useful ffmpeg2theora, which kept original video's quality (full HD), launching the command
ffmpeg2theora in_file.mkv -o out_file.ogg

Answer: I figured it out here is the command
ffmpeg -y -i '/media/some/file.mkv' -s 1920x1080\
 -aspect 16:9 -r 25 -b 18550k -bt 22792k -vcodec libtheora \
 -acodec libvorbis -ac 2 -ar 48000 -ab 320k lol.ogg

-b is target bit rate
-bt is like max bit rate
-ac 2 -ar 48000  is stereo 48 kHz
-ab is audio bit rate

convert video file to .ogg


nib but didn't get a UITableView

Question: My application works for iOS 5.1 but for iOS 6 simulator I get the following error.

Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: '-[UITableViewController
  loadView] loaded the "MainListViewController" nib but didn't get a
  UITableView.'

I am subclassing UITableViewController and I don't want to change it.
The tableview is created programmatically, there is a dummy MainListViewController.xib to load from Mainwindow.xib Tab Bar Controller.
I also tried to delete MainListViewController.xib, remove it from the MainWindow.xib Tab Bar Controller, created the MainListViewController in AppDelegate and added it to Tab Bar Controller as UITabBarItem to get rid of this nib problem, but I still get the same error.
Comment: Where is your table being loaded?  And is it being set to the view outlet/property
Comment: It is loaded in viewDidLoad, in the second version(which adds a UITabBarItem programmatically) it is not set to a outlet/property.
Answer: If you have a NIB for the UITableViewController subclass then its view outlet must be hooked up to a UITableView.
You're right to delete MainListViewController.xib and do it all in code, but the reason it didn't work for you is because the old XIB will not be deleted when you build & run. So, delete the app from the simulator and try again. It should work then.
Comment: Thanks! I deleted the old application,cleaned the project and closed the iOS simulator now the version without the .xib file works.
Comment: @xuhuanze - But that's the point of this question - the NIB was being used to initialise a subclass of `UITableViewController`. If yours was something different, then it's not this question you should be looking at.
Comment: I don't understand, if the xib file is not used anywhere to initialize the subclass of UITableViewController, why would it be a problem at all? It sounds like a bug of Xcode or something... anyway, i deleted the xib file, cleaned the project and it didn't work, but after i deleted the old app then it worked.
Comment: @mattjgalloway you are right. my issue is different, i created the controller with a xib, but later i decided not to use it but same error...
Comment: How in the world you knew the ridiculous answer to this (particularly the 2nd part), is amazing.
Answer: I had a similar problem using storyboards. I'll post my solution for the benefit of others. The key is that if you have correctly set the file's owner to the subclass of UITableView you still have to make sure the view property is set to the Table View. I'm using storyboards, but the same sort of thing should apply to nibs as well. Expand the "document outline" so you can see the hierarchy of your storyboard. I will include some screen shots below. The quick way to solve this is that you want to look at your view in the document outline. Delete any tableview you have as a child of it. Drag the other tableview on top of the view property. Done. I'll show you in screen shots.

Notice the two tables. You want to remove table1 and its cell.

Good. Now drag table2 to the view and you're done. Should work now. Basically if you have a subclass of UITableViewController then it must have Table View in place of view or it will crash.
Comment: I didn't understand this answer at first, so to clarify for others: the `Table View` must be a child of the `ActivitiesTVC - Activities` node and NOT a child of the `View`
Comment: Ran into this when I wanted to get a statically sized view above the tableview, which seems impossible (no resizing of top view) when subclassing UITableViewController. Your answer convinced me I had to subclass UIViewController instead. Then I hooked up my own UITableView instance. Thanks!
Comment: @owenfi If you do need a tableViewController you can always use an embedded one. So, if you're doing a static tableview it must be a tableViewController. Here you can get around the issues by using an embedded tableViewController. I use them all the time.
Comment: @cocoanut sorry, I needed a "static sized" scrollview (horizontally scrolling) atop a dynamic prototype tableview. Not sure if I follow your example, are you able to extend UITableViewController and resize it's tableView to take, say the bottom 50% of the screen?
Comment: @owenfi I'm not sure exactly what you're trying to achieve. Perhaps check out http://www.raywenderlich.com/4680/how-to-make-an-interface-with-horizontal-tables-like-the-pulse-news-app-part-1 , but you might also consider using UICollectionView if tableView doesn't suite your needs. I think that tutorial is obsolete because collectionViews are used in place of this functionality in modern versions of the sdk.
Answer: The reason might be :
.h file check that it is a subclass of UIViewController. it will solve the problem.
Answer: In short, you are setting a custom UITableViewController subclass to a UIViewController !!
You cannot do this. You should give the UIViewController a UIViewController subclass.
Answer: If you use UITableView as your Top View.
Like this :

You need use UITableViewController in your Controller
class ItemsViewController: UITableViewController

If you use UITableView under a View in your Storyboatd.
Like this :

You need use UITableViewDelegate and UITableViewDataSource with UIViewController
class ItemsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

Answer: I find the solution when using Storyboards and 1 table View.
The key is when you create a custom class (newViewController) just check that is a subclass of UITableViewController. Once created Go to the table view controller (of our table) and in the Identity Inspector select the custom class that just created before (newViewController).
That works for me. Hope my comment help someone.
Answer: There is several reason why this may occur.

You may have not have added UITableViewDelegate & UITableViewDataSource to your .h
@interface TableController : UIViewController  {
You may have not connected your declared outlets to the components in the Storyboard/Nib
You maybe calling a UIViewController instead of a UITableView or vide verser in your .h

@interface TableController : UIViewController
or
 @interface TableController : UITableViewController

Answer: Please connect your table view as a View outlet.outlet must be hooked up to a UITableView.
Answer: I had this problem and solving it was just one simple thing.
Keep the nib if you already created ...
Go to (XIB file) and add a tableView component from objects library to the XIB file's iPhone screen, and it should work :)
Answer: @smileBot answer helped me realized the solution is very easy and the error raised by iOS makes sense

Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: '-[UITableViewController
  loadView] loaded the "MainListViewController" nib but didn't get a
  UITableView.'

Their basically saying that nib's view controller is not returning a UITableView because it isn't, for most - your nib is returning a View - which is created for you by default when you create a new ViewController in the Xcode IDE.
The solution is as simple as deleting that View - which might feel against the norm - but go ahead and select it and backspace - then drag and drop a UITableView inside your ViewController and this UITableView will now act as your root view inside your TableViewController.
Keep in mind this is only necessary for classes directly subclassing UITableViewController.
Good luck.
Answer: This worked for me.  Hope it helps you.
In AppDelegate-->
#import "TableViewController.h" // name of your TableViewController class

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//PUT
TableViewController *controller = [[TableViewController alloc]
                                  initWithStyle:UITableViewStylePlain];
    self.window = [[UIWindow alloc]
                   initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = controller;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    // Override point for customization after application launch.
    return YES;
}

Make sure in storyboard your view controller points to this class:
Answer: I also encountered this problem, but I used storyboard in xcode 6.2. I deleted the corresponding view from storyboard and re-dragged the table view controller from the object library to storyboard, then it works.
Answer: I have same problem and after waste 3 hours i find it out..."this is mistake" i use tableviewcontroller class and give uiviewcontroller reference of this class, instead of view controller class i take tableviewcontroller class as i take uiviewcontroller in storyboard. so delete tableviewcontroller class and paste your code of tableviewcontroller class to view controller class,"not paste whole code only paste logic" after this in storyboard in identity inspector give class reference of current view controller class.

nib but didn't get a UITableView


How can I show data using a div when clicking a table row

Question: I have a page with a table which contains tracks from a users.
When you click a row I want it to show the track details in a div. I have managed to display the details using on-click + java script function but it displays the last track details.
<code>$(document).ready(function () {
    $("a#tracks").click(function () {
        $("div#track-info").toggle();
    });
});
$(document).ready(function () {
    $("a#close-box").click(function () {
        $("div#track-info").hide();
    });
});
</code>
I want to display the track details by its track_id? How can I get that?
Comment: You need to show us the table and script you are using if you want us to help you with it.
Comment: It's also important for us to see a table example. And from where you get the data you want to show. Also note that IDs should be unique and note more with the same name per page.
Comment: Please edit your question with more content and not put them in the comments
Comment: <% @tracks.each_with_index do |track, a| %>

<%= track.title %>
<%= track.user ? track.user.Firstname.upcase : "" %>
<%= track.subgenere %>

<% end %>
Comment:
 <% @tracks.each_with_index do |track, a| %>

X
<%= image_tag("sheisdevilicon.png")%>

<%= track.title %>

  MR.<%= track.user ? track.user.Firstname.upcase : "" %>

<%= track.subgenere %>
<%= track.created_at.strftime "%Y/%m/%d" %>
<% end %>
Comment: Click on edit and put that in your question
Comment: Sorry spokey,, it's not edited right now, dont know the problem.. use commented data.. kindly help me through this..
Comment: Am new for this, Simply the question is I want to display Track details when i click on my Track index by onclick().how can i pass id="tracks_<% track.id %>"
Comment: I understand what you want to do, but it's hard to answer without seeing the table structure? Can you please show the generated table?
Answer: Change all IDs to classes and try the following
<code>$(document).ready(function () {
    $('.row.navtopbg').hide();

    $(".tracks").click(function () {
        $('.track-info').show().find('.row.navtopbg:eq(' + $(this).index() + ')').show();
    });

    $(".close-box").click(function () {
        $(".track-info, .row.navtopbg").hide();
    });

});
</code>
Comment: This code is works. But it shows last track_info only. how can i get the track_info of clicked track_id
Comment: @mohdazmath Please show the generate HTML and make a fiddle with it http://jsfiddle.net/