How to get Current Week details as well as Quarter Details in android?

Question: I am having current date from which I want to calculate current week as well as Quarter of the Current month in android.
How can I achieve this?
I am using Calendar to get current date.
Please help me for this.
Thanks in advance.
Comment: What do you have so far?
Comment: see the answer on this post,this is my post check this, hope u get him idea from it and if it is worked then let me know.. http://stackoverflow.com/questions/21473696/android-display-date-from-one-week-to-another-like-thursday-to-thursday/21676492#21676492
Answer: Here is an example of a DateSelection Class i put together. I created an Activity then i had this as a sub class in my Activity.
private class DateSelection{

    //---------------------------------------------------
    // Initial Date
    private Calendar currentDate    = null;

    // Two GregorianCalendar Objects to Return
    private GregorianCalendar beginDate         = null;
    private GregorianCalendar endDate           = null;

    private int buttonId = -1;
    private int month = -1;
    private int year = -1;

    //---------------------------------------------------
    // Constructor
    public DateSelection(int buttonId){

        // Initialize the buttonId to the passed in value
        this.buttonId = buttonId;

        // Initialize the new GregorianCalendar Objects
        currentDate = new GregorianCalendar();

        // Set the Current Month
        month   = currentDate.get(Calendar.MONTH);

        // Set the Current Year
        year    = currentDate.get(Calendar.YEAR);

        beginDate   = new GregorianCalendar();
        endDate     = new GregorianCalendar();

        // Set the Current Date Selection
        setCurrentDateSelection();
    }

    // Constructor : Creates a new Date Selection Object with Two Dates
    public DateSelection(GregorianCalendar beginDate, GregorianCalendar endDate){

        // Set the Being and End Dates for this object
        this.beginDate  = beginDate;
        this.endDate    = endDate;
    }

    // Sets the Current Date based on the Button Used
    public void setCurrentDateSelection(){
        // Switch on the buttons id
        switch(buttonId){
            // Current Month
            case 0:
                getCurrentMonth();
                break;

            // Current Quarter
            case 1:
                getCurrentQuarter();
                break;

            // Current Year
            case 2:
                getCurrentYear();
                break;
            case 3:
                getPriorMonth();
                break;

            case 4:
                getPriorQuarter();
                break;

            case 5:
                getPriorYear();
                break;
            case 6:
                getMonthToDate();
                break;
            case 7:
                getQuarterToDate();
                break;
            case 8:
                getYearToDate();
                break;

            // Default Case
            default:
                break;
        }
    }

    // Returns the Current Month Range as a Date Selection Object
    public DateSelection getCurrentMonth(){

        // Determine the First and Last Day of the Current Month
        int firstOfMonth    = currentDate.getActualMinimum(Calendar.DAY_OF_MONTH);
        int lastOfMonth     = currentDate.getActualMaximum(Calendar.DAY_OF_MONTH);

        // Set the Year, Month and Date for the beginDate
        beginDate.set(Calendar.YEAR, year);
        beginDate.set(Calendar.MONTH, month);
        beginDate.set(Calendar.DAY_OF_MONTH, firstOfMonth);

        // Set the Year, Month and Date for the endDate
        endDate.set(Calendar.YEAR, year);
        endDate.set(Calendar.MONTH, month);
        endDate.set(Calendar.DAY_OF_MONTH, lastOfMonth);

        // Return the new DateSelection Object
        return new DateSelection(beginDate, endDate);

    }

    // Returns the Current Quarter Range as a DateSelection Object
    public DateSelection getCurrentQuarter(){

        // Determine the Quarter Begin and Quarter End Months
        int quarterBeginMonth = (((month - 1) / 3) * 3);
        int quarterEndMonth = quarterBeginMonth + 2;

        // Set the Month and Year for the Current Quarter
        beginDate.set(Calendar.MONTH, quarterBeginMonth);
        beginDate.set(Calendar.YEAR, year);

        // Determine First Day of the Quarter Begin Month
        int firstDayOfBeginMonth = beginDate.getActualMinimum(Calendar.DAY_OF_MONTH);
        // Set the Day for the Begin Date of the Current Quarter
        beginDate.set(Calendar.DAY_OF_MONTH, firstDayOfBeginMonth);

        // Set the Current Quarter Ending Month and Year
        endDate.set(Calendar.MONTH, quarterEndMonth);
        endDate.set(Calendar.YEAR, year);

        // Determine the Last Day of the Quarter End Month
        int lastDayOfEndMonth = endDate.getActualMaximum(Calendar.DAY_OF_MONTH);
        // Set the endDate Date of Month
        endDate.set(Calendar.DAY_OF_MONTH, lastDayOfEndMonth);

        // Return the new DateSelection Object
        return new DateSelection(beginDate, endDate);

    }

    // Returns the Current Year Range as a DateSelection Object
    public DateSelection getCurrentYear(){

        // Determine the int values of the first and last months of the year
        int firstMonth = currentDate.getActualMinimum(Calendar.MONTH);
        int lastMonth = currentDate.getActualMaximum(Calendar.MONTH);

        // Set the Month for beginDate
        beginDate.set(Calendar.MONTH, firstMonth);

        // Determine the int value for the first Day of the Year
        int firstDayOfYear = beginDate.getActualMinimum(Calendar.DAY_OF_MONTH);
        // Set the Day for Begin Date to the first Day of the year
        beginDate.set(Calendar.DAY_OF_MONTH, firstDayOfYear);
        // Set the Month for the endDate to the Last month of the year
        endDate.set(Calendar.MONTH, lastMonth);

        // Determine the last day of the Year from the given month
        int lastDayOfYear = endDate.getActualMaximum(Calendar.DAY_OF_MONTH);

        // Set the Day of the endDate to the Last day of the year
        endDate.set(Calendar.DAY_OF_MONTH, lastDayOfYear);

        // Return the new DateSelection Object
        return new DateSelection(beginDate, endDate);
    }

    // Returns the Prior Month as a DateSelection Object
    public DateSelection getPriorMonth(){

        // Decrement the Month by 1 to get the prior month
        month -= 1;

        // Allow for underflow to the previous year
        if(month < 0)
        {
            month = 11;
            year--;
        }

        // Determine the int value for the first month of the year
        int firstOfMonth    = currentDate.getActualMinimum(Calendar.DAY_OF_MONTH);

        // Set the Year, Month, and Day
        beginDate.set(Calendar.YEAR, year);
        beginDate.set(Calendar.MONTH, month);
        beginDate.set(Calendar.DAY_OF_MONTH, firstOfMonth);

        // Determine the int value for the last month of the year
        int lastOfMonth     = currentDate.getActualMaximum(Calendar.DAY_OF_MONTH);

        // Set the Year, Month, and Day
        endDate.set(Calendar.YEAR, year);
        endDate.set(Calendar.MONTH, month);
        endDate.set(Calendar.DAY_OF_MONTH, lastOfMonth);

        // Return the new DateSelection Object
        return new DateSelection(beginDate, endDate);
    }

    // Returns the Prior Quarter as a DateSelection Object
    public DateSelection getPriorQuarter(){

        // Determine the int values for the Begin and End Quarter Months
        int quarterBeginMonth = (((month - 1) / 3) * 3);
        int quarterEndMonth = quarterBeginMonth + 2;

        // Subtract 3 from the
        quarterBeginMonth   -= 3;
        quarterEndMonth     -= 3;

        // Allow for underflow for the previous year
        if(quarterBeginMonth < 0)
        {
            quarterBeginMonth += 12;
            quarterEndMonth += 12;

            year --;
        }

        // Set the Begin Date's Month and Year
        beginDate.set(Calendar.MONTH, quarterBeginMonth);
        beginDate.set(Calendar.YEAR, year);

        // Get First Day of Quarter's Begin Month
        int firstDayOfBeginMonth = beginDate.getActualMinimum(Calendar.DAY_OF_MONTH);
        beginDate.set(Calendar.DAY_OF_MONTH, firstDayOfBeginMonth);

        // Set the End Date's Month and Year
        endDate.set(Calendar.MONTH, quarterEndMonth);
        endDate.set(Calendar.YEAR, year);

        // Determine the Last Day of the Quarter's End Month
        int lastDayOfEndMonth = endDate.getActualMaximum(Calendar.DAY_OF_MONTH);
        // Set the End Day for the End Month
        endDate.set(Calendar.DAY_OF_MONTH, lastDayOfEndMonth);

        // Return the new DateSelection Object
        return new DateSelection(beginDate, endDate);
    }

    // Returns the Prior Year Range as a DateSelection Object
    public DateSelection getPriorYear(){

        // Decrement the Year by 1 to get the Prior Year
        year -= 1;

        // Determine the int values for the Current years first and last months
        int firstMonth = currentDate.getActualMinimum(Calendar.MONTH);
        int lastMonth = currentDate.getActualMaximum(Calendar.MONTH);

        // Set the Begin date's Year and Month
        beginDate.set(Calendar.YEAR, year);
        beginDate.set(Calendar.MONTH, firstMonth);

        // Determine the first day of the first month of the previous year
        int firstDayOfYear = beginDate.getActualMinimum(Calendar.DAY_OF_MONTH);
        // Set the beginDate to the first day of the previous year
        beginDate.set(Calendar.DAY_OF_MONTH, firstDayOfYear);

        // Set the End date's Year and Month
        endDate.set(Calendar.YEAR, year);
        endDate.set(Calendar.MONTH, lastMonth);

        // Determine the last day of the last month of the previous year
        int lastDayOfYear = endDate.getActualMaximum(Calendar.DAY_OF_MONTH);
        // Set the endDate to the last day of the previous year
        endDate.set(Calendar.DAY_OF_MONTH, lastDayOfYear);

        // Return the new DateSelection Object
        return new DateSelection(beginDate, endDate);
    }

    // Returns the Month to Date as a DateSelection Object
    public DateSelection getMonthToDate(){

        // Determine the int value for the first day of the Month
        int firstOfMonth = currentDate.getActualMinimum(Calendar.DAY_OF_MONTH);

        // Set the Year, Month, and Day for the Begin Date
        beginDate.set(Calendar.YEAR, year);
        beginDate.set(Calendar.MONTH, month);
        beginDate.set(Calendar.DAY_OF_MONTH, firstOfMonth);

        // Set the endDate to the Current Date
        endDate = (GregorianCalendar) currentDate;

        // Return the new DateSelection Object
        return new DateSelection(beginDate, endDate);
    }

    // Returns the Quarter to Date as a DateSelection Object
    public DateSelection getQuarterToDate(){

        // Determine the int value for the current Quarter's beginning month
        int quarterBeginMonth = (((month - 1) / 3) * 3);

        // Set the Month and Year for the beginMonth
        beginDate.set(Calendar.MONTH, quarterBeginMonth);
        beginDate.set(Calendar.YEAR, year);

        // Determine the First Day of Quarter's Begin Month
        int firstDayOfBeginMonth = beginDate.getActualMinimum(Calendar.DAY_OF_MONTH);
        // Set the day of the beginDate to the first day of the Quarter's Month
        beginDate.set(Calendar.DAY_OF_MONTH, firstDayOfBeginMonth);

        // Set the end Date to the Current Date
        endDate = (GregorianCalendar) currentDate;

        // Return the new DateSelection Object
        return new DateSelection(beginDate, endDate);
    }

    // Returns the Year to Date as a DateSelection Object
    public DateSelection getYearToDate(){

        // Determine the first Month of the Year
        int firstMonth = currentDate.getActualMinimum(Calendar.MONTH);

        beginDate.set(Calendar.MONTH, firstMonth);

        int firstDayOfYear = beginDate.getActualMinimum(Calendar.DAY_OF_MONTH);
        beginDate.set(Calendar.DAY_OF_MONTH, firstDayOfYear);

        // Set the end Date to the Current Date
        endDate = (GregorianCalendar) currentDate;

        // Return the new DateSelection Object
        return new DateSelection(beginDate, endDate);
    }

}

Then to get the Dates I create a class Variable of a DateSelection Object and then used buttons and id's to control which date returns.
For example for the current year i created a button added a click listener like this:
Class variable: DateSelection m_dateSelection = null;
And an int id private static final int BUTTON_CURRENT_MONTH = 0;
OnClickListener CurrentMonthListener = new OnClickListener(){

    @Override
    public void onClick(View view) {
        m_dateSelection = new DateSelection(BUTTON_CURRENT_MONTH);
        Toast.makeText(getBaseContext(), "Current Month is from "+ calendarToNumberString( m_dateSelection.beginDate) + " to "+ calendarToNumberString(m_dateSelection.endDate), Toast.LENGTH_LONG).show();

    }

};

And then in my sub class you can see how i use a switch statement to control the ouput.
Good Luck
Comment: And you can copy the code from get CurrentMonth, use GregorianCalendar to find the current date, then add 7 or find current date, get first day of week, last day off week, etc.


CASE Function in mysql query

Question: I can't get the result I want from the following query. Can I get a little help, please? thank you.
$sql = "SELECT id,
                 CASE
                    when Rcon = '' then '0',
                    when Rcon = 'x' then '1',
                    when Rcon = '2x' then '2',
                    when Rcon = 'x3' then '2',
                    when Rcon = 'x,x3' then '3',
                    when Rcon = 'x4' then '3'
                    ELSE Rcon END AS Rcon
FROM mytable";

Comment: what do you want to do in else part?
Comment: In else part, I tried to give an option if there is any unexpected data.
Comment: if you just read the error message raised from mysql you can get what is the error.
Answer: You've got a problem with your CASE statement.
SELECT  id,
        CASE
          when Rcon = '' then '0'
          when Rcon = 'x' then '1'
          when Rcon = '2x' then '2'
          when Rcon = 'x3' then '2'
          when Rcon = 'x,x3' then '3'
          when Rcon = 'x4' then '3'
          ELSE Rcon
        END AS Rcon
  FROM mytable;

Note that I have removed the commas (,) from the end of each line of the CASE statement.  Commas are not valid in a case statement.
Comment: @Max Yes it's just the commas - you don't need them in a `CASE` statment
Comment: so just the comma does the trick? thank you, Martin. this works!

CASE Function in mysql query


How can I give Diamond Armour to Villagers in MCA?

Question: I'm using the Minecraft Comes Alive mod for Minecraft 1.7.10 and I want to equip the villagers in my world with diamond armour.
I cannot put it in their inventory or gift the armour to them, so how do I get them to equip it?
Comment: @TheUnicornMaster we still support questions about mods, but we don't do tech support (crash help) for nodded minecraft.
Comment: Yeah,it's a hard thing to equip in MCA. For example,if your wife is a guard,her sword will dissapear,but she will still patrol,and I don't know how to give her a sword.
Comment: Hi Brendan! I don't believe we support modded Minecraft here.
Comment: @TrentHawkins woops! I wasn't sure. sorry Brendan, please feel free to ask these sort of mod-related questions
Comment: Questions asking about mod contents are welcome here,so long it's not asking about mod support. @TheUnicornMaster
Answer: Try to set up dispensers so that the villagers will be forced to wear the armor.

Place dispensers in a row (facing the same direction).
Put your desired armour in them.
Pace one line of redstone in front of the dispenser's "mouth" an place a pressure plate in front of that.
Have the villagers walk on the pressure plates to activate the dispensers which should shoot the armour into the villagers and equip them with the armour.

If everything goes right, you should have armoured, warrior traders!
Answer: In normal Minecraft you can't give armor to villagers and the only solution is to use dispenser to hit them with armor. That is very easy to remember because it works on normal player too.
Answer: So if anyone in 1.12.2 see this, backup your file, and turn the main into a zip, after this unpack it and go into "MCA-1.12.2-6.1.0-universal\assets\mca\api\gui\Main.json" and open it as a text in notepad, after this find the gui.button.inventory, change the y to 105 and remove the everything in the constraints quote, repack the mod(make sure the repack is exactly as the main was) put it into your mods folder and launch, you now have access to all villager inventories and can equip them with any armor you want manually.


ifstream will not open

Question: The file exists in the directory, and I've tried running Visual Studios in Administrator Mode. However, ifstream can not find the file I give to it.
Here is the code I am using:
std::ifstream instream;
instream.open("appdata.txt");

if (!instream)
{
    std::cout << "Could not find appdata.txt!";
}

But I am always greeted with Could not find appdata.txt! when I run the program.
Here is a picture of my directory, for proof that I have it spelled correctly and it exists.
So, my question is, am I missing something so glaringly obvious that I am glazing over it each time I look? I can not figure out for the life of me why instream can not open appdata.txt.
Comment: Are you sure that the program is run from the directory the file is in and has permission to read the file?
Comment: You could use something like [ProcMon](https://technet.microsoft.com/en-us/sysinternals/processmonitor.aspx) to inspect which paths are being tried for the file
Comment: Are you sure the file isn't called `appdata.txt.txt`? Turn on file extension display in Windows Explorer  - your `BallBuster.exe` is being displayed as `BallBuster` so perhaps the same is happening to the other files
Answer: This is a problem with current directory being set to something else than a dir where your file is (usually your home folder if executing from explorer).
Try executing the program from command line from directory where your file is.
EDIT
If you want to set the working directory to some specific location, check this: https://msdn.microsoft.com/en-us/library/aa363806.aspx
Answer: Add the file by right clicking on project name on visual studio interface.
This will keep your file in the right directory.
If you want to add in the directory by yourself, first add a file using the method I said above and the find which is the folder you should keep so that you can use that file by mentioning just the file-name. And then you can add your files in that folder.

ifstream will not open


hashsum is not available- unable to get source of package

Question: I want to get the source of package wirehshark for year 2009. I am doing that by editing source.list according to Debian snapshot information. After doing sudo apt-get update. I tried:
sudo apt-get source wireshark
--skipped downloading of file wireshark....dsc as requested hashsum is not available for authentication

--skipped downloading of file wireshark....gz as requested hashsum is not available for authentication

--skipped downloading of file wireshark....diff.gz as requested hashsum is not available for authentication

Need to get 0B of source archive.

Basically if am trying to get the source of any packages using debian snapshot of year 2009.. i am getting this error. how to solve this? please give suggestions.
Answer: You can find the snapshot also on the snapshot webpage. Here you will
find tar.gz (source) files.
In the year 2009 it was the 1.2 version.
Comment: Ok.. this is a direct download. As debian maintains snapshots from march 2005. If i want to download version of 2005 then which folder is it? like i tried the last one and that is of year 2006-07 but not of 2005. How can i get source of 2005? and how can i get source of files older than 2005?


How can I add custom bullets to tinyMCE?

Question: I want to add a few extra option to the bullets dropdown on tinyMCE, is that possible?
I want to add ► type of bullet and different color options. (red, blue, etc...)
Comment: You can add bullets to a specific class with `:before` on whatever element you want
Comment: Thanks @Andres, but this was answered a year and a half ago. Before I could expand.
Comment: @ntgCleaner you should expand on your answer. Perhaps offer a small example or a more clear reference to the API/docs
Comment: @ntgCleaner For example, if you were referring to CSS selectors, it might help to be explicit about it. An example might look like this: `p::before {
    content: "► ";
}`
Answer: Yes. In your tinyMCE config, you need to specify:
<code>style_formats: [
    {
         title: 'Custom Bullet',
             selector: 'ul',
             classes: 'custom1'
         }
],
</code>
From there, you need to specify the styling in the CSS:
<code>.custom1 { list-style-image: url('custom1.png'); }
</code>
See this for more info: https://www.tinymce.com/docs/configure/content-formatting/#style_formats
Comment: I go that working... thanks... But it won't change in the editor, I have to save the content and it will display. Is it possible to do so after I select the style it would display on the editor screen?
Comment: TinyMCECustomConfig("custom2","style_formats", "{title: 'Custom Bullet', selector: 'ul', classes: 'custom1'}");


include not work (PHP)

Question: i have strange problem with include commnad
my files structure
/index.php
/files/init.php
/files/db.php

and sources of this files
index.php
<?
include ('files/init.php');
?>

init.php
<?
include ("db.php");
?>

Source from db.php is not executing..  NOW if i rename file db.php to db2.php and rename it in init.php NOW IT WORKS
there is some php cache or what ?  i dont understand it.
Comment: I'm pretty sure it's `include ("files/db.php");`. On a side note, you should **not** use short open tags ``, it will save you some pain when moving to other environments.
Comment: possible duplicate of [How to include PHP files that require an absolute path?](http://stackoverflow.com/questions/4369/how-to-include-php-files-that-require-an-absolute-path)
Comment: No it is different problem. read my answer conflict filename DB.php from PEAR.
Comment: The answer listed there is somewhat "universal" and way better than your methods.
Answer: conflict filename DB.php from PEAR.
DB.php from PEAR is included instead of your "db.php"..
So use filename other than "db.php".
EDIT or use include with DIR macro
Comment: Same issue on "config.php"
Answer: try this
<?php
include ("db.php");

?>

or using ./
<?php
include ("./db.php");

?>

Answer: The included files are resolved according to the entry point (here index.php).
Moreover, require is better is the file MUST exist.
index.php
<?php require 'files/init.php'; ?>

files/init.php
<?php require 'files/db.php'; ?>

Update 1: As suggested by @Darsstar, here is an example using __DIR__:
files/init.php
<?php require __DIR__.'/db.php'; ?>

Update 2: Maybe you should consider PSR-0 or PSR-4 to deal with file inclusion.
Comment: You might want to add an example using `__DIR__`
Comment: ok it works, but why if i only rename file db.php to db2.php  now work this
how can it be possible that it works with different file name. That's what I want to know. In other project i am using it and it works.
Comment: @PepíkSamků Are you sure that there is no other `db2.php` in the include path?
Comment: i make this simple example. There is only this 3 files. It is some bug or i dont know.
Comment: @PepíkSamků it's just impossible. A typical [user error](http://en.wikipedia.org/wiki/User_error). Make sure to show hidden files. It's just tiresome to help troubleshoot such trivial things.
Comment: http://us3.php.net/get_included_files can be used to see which db2.php was included. Like @HamZa said, this should be a user error.
Comment: OMG I know..

PEAR DB.php  something like shadowing variables so there shadowing included files

thanks for that get_included_files();

include not work (PHP)


"Invalid Table Rates File Format" when uploading a Table Rate for "Price vs Destination" for the UK only

Question: I'm trying to set up delivery charges for a Magento site I'm in charge for. I've been tasked with setting up the shipping charges along the following lines:
<code>Basket Cost       |  Delivery Cost
-----------------------------------
£0.00 to £9.99    |  £1
£10.01 to £29.99  |  £2
£30.00 and above  |  £3
</code>
I've followed this tutorial and I've got up to the point of uploading the CSV file. I've attached a screenshot of the CSV file.
Every time I upload this file though and save it, I get the following error:

"Invalid Table Rates File Format"

I've based my CSV file on the tutorial, and have tried everything from typing "United Kingdom", "GBR", and "GB", but it still doesn't work. I've also set it as "Price vs Destination" and it's set to just be applicable to the UK only. What am I doing wrong?
Answer: The problem is that Magento doesn't like CSV files that have been edited in a spreadsheet. I had tried both LibreOffice and Excel, both of which caused this issue.
However, when I edited the file in a text editor and uploaded it, it worked straight away. I did try messing about with the save settings in Excel to achieve what the text editor was doing, but it just doesn't seem to work.
Answer: The error suggest its not about table values but about file format.
Is your file comma separated or Tab separated.
Just open your file in edit plus or some simple editor.
http://www.magentocommerce.com/knowledge-base/entry/how-do-i-set-up-table-rate-shipping link has some explanation.
Here you will find an export button export file using this button and then populate this file and upload.
Answer: There is no delivery price for exactly £10. Also I think £0.00 isn't a price. Row 2 column d maybe should be 0.1 you know? 0 isn't a price.
Comment: In the tutorial it uses 0 as a Subtotal value, but I'll check this now.
Answer: I had this issue and it was driving me bonkers.I finally saved the file as Unicode(utf-8) and then it worked fine.
Answer: just export using open office but when saving select
1-

2-

3- here replace this " with this '
Answer: easy check this https://www.elgentos.nl/tablerates/
creator - easy to use and works perfect


Help with probability, expected values

Question: Question: Image

Consider  random variable $X$ over the positive integers, satisfying $P[X=i] = C/i^2$ for any integer $i>0$, where $C^{-1} = \sum_{i=1}^\infty 1/i^2$, what is $\mathsf E(X)$?

I am learning expected values, but I am not sure what this question is asking. They have given me the formula for $X$ which is $C/i^2$.
However why did they give me $C^{-1}$?
I know that $E(X) = X * Pr(X)$
But how do I apply it to this questions?
Thank you
Disclaimer: this is a weekly school tutorial and we are allowed to discuss but I do not know anyone to ask. Some guidance would be great!
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: You (usually) need to know C to compute $E[X]$. You could have computed it yourself using the requirement that $\sum_i C/i^2 =1$, if you knew how to compute $\sum_i 1/i^2 $ (which is more advanced), but they gave it to you. It is not true that $E[X]=X \cdot P(X)$, but rather $E[X]=\sum_i i \cdot P(i)$
Answer:
They have given me the formula for $X$ which is $C/i^2$.
However why did they give me $C^{-1}$?

As a distraction, or to assure you that the total probability equals $1$.   Well, rather, if the formula is to be a proper probability mass function over that domain, then that is what $C$ must equal. $$\begin{align}\sum_{i=1}^\infty\mathsf P(X=i)&=\sum_{i=1}^\infty (C/i^2)\\&=1\end{align}$$
Well, you could use this to find $C$, but you don't need to.
$\tiny 1/\sum\limits_{i=1}^\infty i^{-2} =6/\pi^2$

I know that $E(X) = X * Pr(X)$

It does not.
You should know that $$\begin{align}\mathsf E(X)&=\sum_{i=1}^\infty i\cdot\mathsf P(X=i)\\&=\end{align}$$
So it's trivial to find the series formula.
$\color{silver}{\tiny\text{Don't worry about trying to find a closed form, as this series fails the convergence test.}}$
Comment: It is obvious the series for $E(X)=C\sum\limits_{i=1}^\infty  \frac{1}{i}$ is divergent

Help with probability, expected values


Detecting the user input as an error for string input in java

Question: What can I do to detect string input as an error, where the user has to enter an int value?
What is the condition I can use to detect whether the user has entered a string value?
<code>Scanner input = new Scanner(System.in);
int characterNum = input.nextInt();

do{

 if ((characterNum < 0)&&(characterNum > 12)){
 System.out.println("Invalid Input, Try again");

  }

 characterNum = input.nextInt();

 }while((characterNum < 0)&&(characterNum > 12));
</code>
Comment: Look at this https://stackoverflow.com/questions/6456219/java-checking-if-parseint-throws-exception
Comment: What I understood is, you are trying to get user input but you want to make sure it is a numeric value?
Comment: can you put your code to see how are you trying to do ??
Comment: @ElSheikh yes exactly
Comment: @S.Liyanage check David's comment
Comment: @abby37 This is the part(loop) which i used to validate the range of the input number. How can I add the string validation condition in the same loop?
Comment: [nextInt](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()) from the docs, it won't accept the string and it will throw input mismatch exception. So why you want to put additional condition for string or I may be missing something in question ??
Answer: By Using instanceof :
Use "s instanceof String" , where s is variable entered by user to check wither it is String or not
Comment: If the OP takes a string as input, and they want to know if it is or is not parsable as an integer, `instanceof String` is obviously going to be true. If they try and take input as something other than a string, it will be false. Either way, it is not helpful.


google map api v2 it was appearing [Android]

Question: The map was appearing then now it is just gray blank screen with zoom buttons, i changed
the api key nothing changed re-install google play service in android sdk and also nothing changed.
Any Help !!
http://farm8.staticflickr.com/7347/8752555837_4bd5d0abee_m.jpg
Thanks
Comment: will you post your code ?
Comment: Check API key is correct and or not
Answer: You have incorrectly set the API up. It is most probably related to API key.
Comment: explain please i'm an android developer beginner
??
Comment: @NesreenMansour follow the instructions here: https://developers.google.com/maps/documentation/android/start#the_google_maps_api_key and make sure you did this: "In the list of services displayed in the center of the page, scroll down until you see Google Maps Android API v2. To the right of the entry, click the switch indicator so that it is on."


'NSDictionary' may not respond to '-objectAtIndex:'

Question: There are no bugs in the code but my Dictionary doesnt get loaded
CODE:
//
//  SectionsViewController.m
//  Sections
//
//  Created by Kunwar Handa on 25/05/11.
//  Copyright 2011 Fortune4  Technologies. All rights reserved.
//

#import "SectionsViewController.h"

@implementation SectionsViewController
@synthesize names;
@synthesize keys;

#pragma mark -
#pragma mark UIViewController Methods

-(void)viewDidLoad{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"sortednames" ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.names= dict;
    [dict release];

    NSArray *array = [[names allKeys] sortedArrayUsingSelector:@selector(compare:)];
    self.keys= array;

}

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [names release];
    [keys release];
    [super dealloc];
}

#pragma mark -
#pragma mark Table View Data Source Methods

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return [keys count];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    return [nameSection count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];

    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];

    static NSString *SectionTableIdentifier = @"SectionTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionTableIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SectionTableIdentifier] autorelease];
    }

                cell.text = [nameSection objectAtIndex:row];
                return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{

    NSString *key = [keys objectAtIndex:section];
    return key;

}
@end

**LOG:**

Build Sections of project Sections with configuration Debug

ProcessInfoPlistFile /Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/Sections.app/Info.plist Sections-Info.plist
cd /Users/kunwarhanda/Documents/Sections
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
builtin-infoPlistUtility Sections-Info.plist -genpkginfo /Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/Sections.app/PkgInfo -expandbuildsettings -format binary -platform iphonesimulator -o /Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/Sections.app/Info.plist

CompileXIB /Users/kunwarhanda/Documents/Sections/MainWindow.xib
cd /Users/kunwarhanda/Documents/Sections
setenv IBC_MINIMUM_COMPATIBILITY_VERSION 4.2
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/usr/bin/ibtool --errors --warnings --notices --output-format human-readable-text --compile /Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/Sections.app/MainWindow.nib /Users/kunwarhanda/Documents/Sections/MainWindow.xib --sdk /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk

CompileXIB /Users/kunwarhanda/Documents/Sections/SectionsViewController.xib
cd /Users/kunwarhanda/Documents/Sections
setenv IBC_MINIMUM_COMPATIBILITY_VERSION 4.2
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/usr/bin/ibtool --errors --warnings --notices --output-format human-readable-text --compile /Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/Sections.app/SectionsViewController.nib /Users/kunwarhanda/Documents/Sections/SectionsViewController.xib --sdk /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk

ProcessPCH /var/folders/6o/6oRlqcHSG3i+gabLJ+MCV++++TM/-Caches-/com.apple.Xcode.502/SharedPrecompiledHeaders/Sections_Prefix-gyjbjzxosthibsbszggxsbxqehxr/Sections_Prefix.pch.gch Sections_Prefix.pch normal i386 objective-c com.apple.compilers.gcc.4_2
cd /Users/kunwarhanda/Documents/Sections
setenv LANG en_US.US-ASCII
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -x objective-c-header -arch i386 -fmessage-length=0 -pipe -std=c99 -Wno-trigraphs -fpascal-strings -fasm-blocks -O0 -Wreturn-type -Wunused-variable -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk -fexceptions -fvisibility=hidden -mmacosx-version-min=10.6 -gdwarf-2 -fobjc-abi-version=2 -fobjc-legacy-dispatch -D__IPHONE_OS_VERSION_MIN_REQUIRED=40200 -iquote /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-generated-files.hmap -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-own-target-headers.hmap -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-all-target-headers.hmap -iquote /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-project-headers.hmap -F/Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator -I/Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/include -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/DerivedSources/i386 -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/DerivedSources -c /Users/kunwarhanda/Documents/Sections/Sections_Prefix.pch -o /var/folders/6o/6oRlqcHSG3i+gabLJ+MCV++++TM/-Caches-/com.apple.Xcode.502/SharedPrecompiledHeaders/Sections_Prefix-gyjbjzxosthibsbszggxsbxqehxr/Sections_Prefix.pch.gch

CompileC build/Sections.build/Debug-iphonesimulator/Sections.build/Objects-normal/i386/main.o /Users/kunwarhanda/Documents/Sections/main.m normal i386 objective-c com.apple.compilers.gcc.4_2
cd /Users/kunwarhanda/Documents/Sections
setenv LANG en_US.US-ASCII
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -x objective-c -arch i386 -fmessage-length=0 -pipe -std=c99 -Wno-trigraphs -fpascal-strings -fasm-blocks -O0 -Wreturn-type -Wunused-variable -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk -fexceptions -fvisibility=hidden -mmacosx-version-min=10.6 -gdwarf-2 -fobjc-abi-version=2 -fobjc-legacy-dispatch -D__IPHONE_OS_VERSION_MIN_REQUIRED=40200 -iquote /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-generated-files.hmap -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-own-target-headers.hmap -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-all-target-headers.hmap -iquote /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-project-headers.hmap -F/Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator -I/Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/include -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/DerivedSources/i386 -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/DerivedSources -include /var/folders/6o/6oRlqcHSG3i+gabLJ+MCV++++TM/-Caches-/com.apple.Xcode.502/SharedPrecompiledHeaders/Sections_Prefix-gyjbjzxosthibsbszggxsbxqehxr/Sections_Prefix.pch -c /Users/kunwarhanda/Documents/Sections/main.m -o /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Objects-normal/i386/main.o

CompileC build/Sections.build/Debug-iphonesimulator/Sections.build/Objects-normal/i386/SectionsAppDelegate.o /Users/kunwarhanda/Documents/Sections/Classes/SectionsAppDelegate.m normal i386 objective-c com.apple.compilers.gcc.4_2
cd /Users/kunwarhanda/Documents/Sections
setenv LANG en_US.US-ASCII
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -x objective-c -arch i386 -fmessage-length=0 -pipe -std=c99 -Wno-trigraphs -fpascal-strings -fasm-blocks -O0 -Wreturn-type -Wunused-variable -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk -fexceptions -fvisibility=hidden -mmacosx-version-min=10.6 -gdwarf-2 -fobjc-abi-version=2 -fobjc-legacy-dispatch -D__IPHONE_OS_VERSION_MIN_REQUIRED=40200 -iquote /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-generated-files.hmap -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-own-target-headers.hmap -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-all-target-headers.hmap -iquote /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-project-headers.hmap -F/Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator -I/Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/include -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/DerivedSources/i386 -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/DerivedSources -include /var/folders/6o/6oRlqcHSG3i+gabLJ+MCV++++TM/-Caches-/com.apple.Xcode.502/SharedPrecompiledHeaders/Sections_Prefix-gyjbjzxosthibsbszggxsbxqehxr/Sections_Prefix.pch -c /Users/kunwarhanda/Documents/Sections/Classes/SectionsAppDelegate.m -o /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Objects-normal/i386/SectionsAppDelegate.o

CompileC build/Sections.build/Debug-iphonesimulator/Sections.build/Objects-normal/i386/SectionsViewController.o Classes/SectionsViewController.m normal i386 objective-c com.apple.compilers.gcc.4_2
cd /Users/kunwarhanda/Documents/Sections
setenv LANG en_US.US-ASCII
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -x objective-c -arch i386 -fmessage-length=0 -pipe -std=c99 -Wno-trigraphs -fpascal-strings -fasm-blocks -O0 -Wreturn-type -Wunused-variable -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk -fexceptions -fvisibility=hidden -mmacosx-version-min=10.6 -gdwarf-2 -fobjc-abi-version=2 -fobjc-legacy-dispatch -D__IPHONE_OS_VERSION_MIN_REQUIRED=40200 -iquote /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-generated-files.hmap -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-own-target-headers.hmap -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-all-target-headers.hmap -iquote /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Sections-project-headers.hmap -F/Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator -I/Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/include -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/DerivedSources/i386 -I/Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/DerivedSources -include /var/folders/6o/6oRlqcHSG3i+gabLJ+MCV++++TM/-Caches-/com.apple.Xcode.502/SharedPrecompiledHeaders/Sections_Prefix-gyjbjzxosthibsbszggxsbxqehxr/Sections_Prefix.pch -c /Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m -o /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Objects-normal/i386/SectionsViewController.o

/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m: In function '-[SectionsViewController viewDidLoad]':
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m:27: warning: incompatible Objective-C types 'struct NSArray *', expected 'struct NSDictionary *' when passing argument 1 of 'setKeys:' from distinct Objective-C type
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m: In function '-[SectionsViewController tableView:numberOfRowsInSection:]':
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m:99: warning: 'NSDictionary' may not respond to '-objectAtIndex:'
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m:99: warning: (Messages without a matching method signature
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m:99: warning: will be assumed to return 'id' and accept
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m:99: warning: '...' as arguments.)
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m: In function '-[SectionsViewController tableView:cellForRowAtIndexPath:]':
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m:110: warning: 'NSDictionary' may not respond to '-objectAtIndex:'
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m:120: warning: 'setText:' is deprecated (declared at /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UITableViewCell.h:211)
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m: In function '-[SectionsViewController tableView:titleForHeaderInSection:]':
/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m:127: warning: 'NSDictionary' may not respond to '-objectAtIndex:'

Ld build/Debug-iphonesimulator/Sections.app/Sections normal i386
cd /Users/kunwarhanda/Documents/Sections
setenv MACOSX_DEPLOYMENT_TARGET 10.6
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk -L/Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator -F/Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator -filelist /Users/kunwarhanda/Documents/Sections/build/Sections.build/Debug-iphonesimulator/Sections.build/Objects-normal/i386/Sections.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework Foundation -framework UIKit -framework CoreGraphics -o /Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/Sections.app/Sections

GenerateDSYMFile build/Debug-iphonesimulator/Sections.app.dSYM build/Debug-iphonesimulator/Sections.app/Sections
cd /Users/kunwarhanda/Documents/Sections
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/usr/bin/dsymutil /Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/Sections.app/Sections -o /Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/Sections.app.dSYM

Touch build/Debug-iphonesimulator/Sections.app
cd /Users/kunwarhanda/Documents/Sections
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/usr/bin/touch -c /Users/kunwarhanda/Documents/Sections/build/Debug-iphonesimulator/Sections.app

Comment: "There are no bugs in the code" ?
Comment: I have fixed the formatting for you, in the future, please try and use proper formatting before you post.
Comment: Gah, codedump. Can you boil it down to what actually breaks, please?
Comment: How was your "keys" property declared in your header file ? It looks like you declared a NSDictionary instead of a NSArray.
Answer: NSDictionary, According to the documentation, Should NOT respond to objectAtIndex:, which is a method for an NSArray. The equivalent for an NSDictionary would be objectForKey:.
Answer: Given the almost complete lack of formatting in your post it's hard to see what the problem is. From the title of your question I would guess you are trying to call 'objectAtIndex' on a NSDictionary when you should be calling 'objectForKey'.
Answer: it's true - 'NSDictionary' does not respond to '-objectAtIndex:'
the compiler points out the source line of the problem, for example:
    SectionsViewController.m:99
and xcode will probably highlight it for you too.
Answer: objectAtIndex: is a method for arrays and it cannot be used for dictionary. You are trying to access an object in your dictionary somewhere in your class using objectAtIndex:. check if u are accessing it for NSDictionary
Answer: Following the errors, you have keys declared as an NSDictionary when you want it to be an NSArray. Hence the warnings that you're assigning the wrong type of object on line 27, then making a possibly incompatible call on line 99.
You should check how you declare keys, which will be in the associated header file rather than in the code you've given. Solving just the first warning:

/Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m:
  In function '-[SectionsViewController
  viewDidLoad]':
  /Users/kunwarhanda/Documents/Sections/Classes/SectionsViewController.m:27:
  warning: incompatible Objective-C
  types 'struct NSArray *', expected
  'struct NSDictionary *' when passing
  argument 1 of 'setKeys:' from distinct
  Objective-C type

Will solve all of them.


Not able to install from ubuntu software center

Question: Not able to install any software from ubuntu software center. There is no response after pressing install button.
The error which I get

Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/defer/init.py", line 475, in
  _inline_callbacks
     result = gen.send(result)
File "/usr/lib/python2.7/dist-packages/aptdaemon/client.py", line 1622, in
  _run_transaction_helper
daemon = get_aptdaemon(self.bus)
File "/usr/lib/python2.7/dist-packages/aptdaemon/client.py", line 1696, in
  get_aptdaemon
     False),
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 241, in get_object
     follow_name_owner_changes=follow_name_owner_changes)
File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 248, in init
     self._named_service = conn.activate_name_owner(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 180, in activate_name_owner
     self.start_service_by_name(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 278, in
  start_service_by_name
     'su', (bus_name, flags)))
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in call_blocking
     message, timeout)
  dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ChildExited: Launch
  helper exited with unknown return code 1
  Traceback (most recent call last):
   File "/usr/lib/python2.7/dist-packages/defer/init.py", line 475, in
  _inline_callbacks
     result = gen.send(result)
   File "/usr/lib/python2.7/dist-packages/aptdaemon/client.py", line 1622, in
  _run_transaction_helper
     daemon = get_aptdaemon(self.bus)
   File "/usr/lib/python2.7/dist-packages/aptdaemon/client.py", line 1696, in
  get_aptdaemon
     False),
   File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 241, in get_object
     follow_name_owner_changes=follow_name_owner_changes)
File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 248, in init
     self._named_service = conn.activate_name_owner(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 180, in activate_name_owner
     self.start_service_by_name(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 278, in
  start_service_by_name
     'su', (bus_name, flags)))
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in call_blocking
     message, timeout)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ChildExited: Launch
  helper exited with unknown return code 1
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ChildExited: Launch
  helper exited with unknown return code 1

Edit 1
New errors after running the command given in the answer.
I tried with sudo too.
A part of the error code
Removing /usr/local/lib/python2.7/dist-packages/setuptools-1.4.1-py2.7.egg
Copying setuptools-1.4.1-py2.7.egg to /usr/local/lib/python2.7/dist-packages
setuptools 1.4.1 is already the active version in easy-install.pth
Installing easy_install script to /usr/local/bin
error: /usr/local/bin/easy_install: Permission denied
Something went wrong during the installation.
See the error message above.
Comment: don't remove python,it was necessary to boot ubuntu.
Answer: permissions in your python packages are possibly not working , change its permission by using-
sudo chown -R $USER /usr/local/lib/python2.7/dist-packages/

-Replace USER with your login name, if this doesnt works check the output of -
/usr/lib/ubuntu-sso-client/ubuntu-sso-login

If it throw any error ImportError: No module named pkg_resources
then the reason behind this could be setup tools package has been deleted in my Python environment .to solve this use the following script-
curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | python

hope it will work.
Comment: I agree with @dobey. While it may fix the issue changing permissions in system folders is a bad idea. Plus "fixing" an issue like this does not really get to the root cause
Comment: it worked! thanks , i was able to install software but i was getting error as edited in question after running the curl command
Comment: you can now install trough Ubuntu Software Center ??
Comment: yes, but while running the curl ---- command it resulted in errors as added in the question
Comment: that was for if you failed in first line the one for chown. No issues your problem is solved.
Comment: While this "answer" may work, it is just bad advice. You shouldn't `chown -R $USER` system directories. And you shouldn't tell people to run arbitrary scripts off the Internet.
Comment: Sir , is there any safe method?? if yes let me know , then i will keep it in mind for next time.


Is this a GFCI tester on breaker panel? What does it do?

Question: I noticed that there is a GFCI tester on the breaker panel. But I'm not sure what it was for. The directory just says "Ground Fault".
so I interact with it a little. I pressed the test button and heard a click sound. However when I push the switch to "ON" position nothing happens, and I heard no clicking sound. Further, when I pressed the test button again there's no clicking sound.
My questions are: what is the tester usually for on a breaker panel?
And should I be worried that the breaker does not seem to turn ON after testing?
Thank you!
Answer: What you're looking at there is a GFCI circuit breaker. Just like the other thing is a combination of outlet + GFCI, this is a combination of circuit breaker + GFCI.
A GFCI breaker protects the entire circuit from a ground fault and would replace the need for a GFCI outlet on the first outlet from the panel for that circuit.
The breaker should reset but to do so you must turn it all the way to the off position first and then turn it on. A tripped breaker will trip to the middle (between On and Off).
Comment: In case it's not apparent to the OP, the test button is the test for **that breaker** which provides GFCI protection to the entire circuit.
Comment: Emphasized what you are talking about. Other than that this answer is perfect.
Comment: And yes, the GFCI breaker doesn't need a reset button because, cycling the breaker "off, then on" serves as the reset button.
Comment: OP here. I can't seem to cycle the GFCI breaker "off then on" to turn the power back on. It seems unlikely that the receptacles are broken due my experiment. Is it possible that the breaker is broken??


Opening project in new tab stopped working in Intellij

Question: My current settings in my system :
<code> Mac OS Big Sur :: System preference -> General -> prefer tabs : always
 Intellij :: Preferences -> System settings -> open project : new window
</code>
Is anyone facing the same issue?
<code>IntelliJ IDEA 2021.3.1 (Ultimate Edition)
Build #IU-213.6461.79, built on December 28, 2021
</code>
Answer: Looks like it is a known problem. Follow https://youtrack.jetbrains.com/issue/IDEA-284415 for updates.


SQL - How to get a user's favorite posts title from StackExchange Database

Question: I am working on a project analyzing Stackoverflow's user's behaviors and I need to get data from the stackoverflow, one of the data I need to get is to get a user's favorite posts title from stackexchange Database. Right now, I only figured out how to get the user's favorite information as following:
select VT.name, U.DisplayName
from VoteTypes VT, Votes V, Users U
where VT.Id = 5 and
           VT.Id = V.VoteTypeId and
           U.Id = V.UserId and
           U.Id = '85597'

I think the next step is to find the posts the User voted, then match the userId. But I don't know if it is a right step to do. And I could not find any connection between a User's vote and a question post
Comment: no-one should be joining using comma separated tables any longer, over 25 years have elapsed since explicit join syntax was formalized. time to change.
Comment: @Used_By_Already what do I change to? As I am taking a database course right now, and it taught me to use in this way.
Answer: SELECT
      vt.name
    , u.DisplayName
FROM VoteTypes vt
   , Votes v        <<<<<<<<< not good
   , Users u        <<<<<<<<< not good
WHERE vt.Id = 5
AND vt.Id = v.VoteTypeId  <<<<<<<<< join predicate (vt = v)
AND u.Id = v.UserId       <<<<<<<<< join predicate (u = v)
AND u.Id = '85597

Just STOP using commas between table names.'That simple step will force you to more carefully consider the joins.
Move the join predicates to the table they refer to AFTER an ON. (Join predicates refer to different tables either side of an operator such as equals.)
SELECT
      vt.name
    , u.DisplayName
FROM VoteTypes vt
   , Votes v ON vt.Id = v.VoteTypeId
   , Users u ON u.Id = v.UserId
WHERE vt.Id = 5
AND
AND
AND u.Id = '85597'

Replace those dreaded commas with appropriate join type, and tidy-up.
SELECT
      vt.name
    , u.DisplayName
FROM VoteTypes vt
INNER JOIN Votes v ON vt.Id = v.VoteTypeId
INNER JOIN Users u ON u.Id = v.UserId
WHERE vt.Id = 5
AND u.Id = '85597'

Done.
If your course is using old syntax; consider getting a better course.
Comment: Thank you for you correction! I am wondering if you could also help me with the content?


Matplotlib BoxPlot Labels and Title

Question: Thank you in advance for your help!
I am trying to create a boxplot in matplotlib and I get an error when trying to add the labels.
This is the code that pulls an error:
df_selected_station_D.boxplot(column='20 cm', by='Month',figsize=(15,5),grid=True, xlabel = 'x data');

This is the error it causes:
TypeError: boxplot() got an unexpected keyword argument 'xlabel'

What does this error mean and why am I getting it? (Complete code and images below)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')

raw_data = pd.read_csv('all-deep-soil-temperatures.csv', index_col=1, parse_dates=True)
df_all_stations = raw_data.copy()

df_selected_station = df_all_stations[df_all_stations['Station'] == 'Minot']
df_selected_station.fillna(method = 'ffill', inplace=True);
df_selected_station_D=df_selected_station.resample(rule='D').mean()
df_selected_station_D['Day'] = df_selected_station_D.index.dayofyear

mean=df_selected_station_D.groupby(by='Day').mean()
mean['Day']=mean.index

df_selected_station_D['Month'] = df_selected_station_D.index.month
df_selected_station_D.head()

df_selected_station_D.boxplot(column='20 cm', by='Month',figsize=(15,5),grid=True);

Answer: The data is not the same, but adding labels and modifying titles can be accomplished with the following code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()

np.random.seed(1234)
df = pd.DataFrame(np.random.randn(10, 4), columns=['Col1', 'Col2', 'Col3', 'Col4'])
ax1 = df.boxplot(column=['Col1', 'Col2', 'Col3'], figsize=(15,5), grid=True)
ax1.set_title('test title')
ax1.set_xlabel('x data')
ax1.set_ylabel('y data')

plt.show()

Comment: Thank you! I will make sure to accept your answer when the time limit expires!

Matplotlib BoxPlot Labels and Title


Cant use apt because of gnome-settings-daemon

Question: i am running ubuntu gnome. when i attempt to do ANYTHING (update, upgrade, purge, remove, install...) with apt, i get
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 gnome-control-center : Depends: gnome-settings-daemon (>= 3.25.90) but 3.24.0-0ubuntu2 is to be installed
                        Recommends: gnome-online-accounts (>= 3.25.3) but 3.24.0-0ubuntu1 is to be installed
                        Recommends: rygel but it is not going to be installed or
                                    rygel-tracker but it is not going to be installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

then when i use
sudo apt-get --fix-broken install

i get:
Preparing to unpack .../gnome-settings-daemon_3.26.2-1_amd64.deb ...
Unpacking gnome-settings-daemon (3.26.2-1) over (3.24.0-0ubuntu2) ...
dpkg: error processing archive /var/cache/apt/archives/gnome-settings-daemon_3.26.2-1_amd64.deb (--unpack):
 trying to overwrite '/lib/udev/rules.d/61-gnome-settings-daemon-rfkill.rules', which is also in package gnome-settings-daemon-schemas 3.24.0-0ubuntu2
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Reinstalling /etc/xdg/autostart/org.gnome.SettingsDaemon.XRANDR.desktop that was moved away
Reinstalling /etc/xdg/autostart/org.gnome.SettingsDaemon.Orientation.desktop that was moved away
Errors were encountered while processing:
 /var/cache/apt/archives/gnome-settings-daemon_3.26.2-1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

I cannot do anything unless i am using dpkg to install a local package. can anybody help?
Comment: You will have to file a bug report
Answer: i fixed it.
it was a problem with my repositories -- i had added the kali repository for the tools, and it was trying to install kali's gnome over ubuntu's gnome. it is all good!
Comment: Welcome to Ask Ubuntu! I recommend to [edit] this answer to expand it with specific details about what you did. (See also [How do I write a good answer?](/help/how-to-answer) for general advice about what sorts of answers are considered most valuable on Ask Ubuntu.)


simple view in backbone not working

Question: I try to make a simple view in backbone, on button press (with class .buy-products) it must trigger the 'buyProducts' method, but it doesn't , help plz
var CurrProducts = Backbone.View.extend({

        events: {
            "click .buy-products": 'buyProducts'
        },

        buyProducts: function() {
            console.log("working1");
        },

        render: function() {
            return this;
        }
    });
    var test = new CurrProducts();
    test.render()

Answer: You need to first bind the backbone view to element on the page that is containing the .buy-product button.
For simplicity sake you can bind it to the body:
var CurrProducts = Backbone.View.extend({
    el: "body",
    //rest of your code
});

http://backbonejs.org/#View-el

simple view in backbone not working


WCF Client config trouble

Question: I created a WCF service in VS2010 that returns Json. I also created an Nunit test project that calls the methods of the service. All was working well when using the built-in VS2010 web server. I then configured the service to run in my local IIS6.1. I can successfully bring up the service in a browser as in http://localhost/PVSCService/WebData.svc but I get the famous:

There was no endpoint listening at http://localhost/PVSCService/WebData.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.

My service web.config:
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="PVSCWeb.Service.WebData">
        <endpoint name="jsonEP"
                  address=""
                  binding="webHttpBinding"
                  behaviorConfiguration="json"
                  contract="PVSCWeb.Service.IWebData"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="json">
          <webHttp defaultOutgoingResponseFormat="Json"/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

and my Nunit test project app.config:
<configuration>
    <system.serviceModel>
      <bindings>
        <wsHttpBinding>
          <binding name="WSHttpBinding_IWebData" closeTimeout="00:01:00"
              openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
              bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
              maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
              messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
              allowCookies="false">
            <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                maxBytesPerRead="4096" maxNameTableCharCount="16384" />
            <reliableSession ordered="true" inactivityTimeout="00:10:00"
                enabled="false" />
            <security mode="Message">
              <transport clientCredentialType="Windows" proxyCredentialType="None"
                  realm="" />
              <message clientCredentialType="Windows" negotiateServiceCredential="true"
                  algorithmSuite="Default" establishSecurityContext="true" />
            </security>
          </binding>
        </wsHttpBinding>
      </bindings>
      <client>
        <endpoint address="http://localhost/PVSCService/WebData.svc"
            binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IWebData"
            contract="ServiceReference1.IWebData" name="WSHttpBinding_IWebData">
          </endpoint>
      </client>
    </system.serviceModel>
  <system.diagnostics>

    <sources>
      <source propagateActivity="true" name="System.ServiceModel" switchValue="Error, ActivityTracing">
        <listeners>
          <add name="AppFabricTracing" />
        </listeners>
      </source>
    </sources>
    <trace autoflush="true" />
    <sharedListeners>
      <add name="AppFabricTracing" initializeData="c:\PVSCService.svclog" type="System.Diagnostics.XmlWriterTraceListener" />
    </sharedListeners>
  </system.diagnostics>
</configuration>

I have noticed the suggestions regarding turning off Windows Firewall but network policy forbids that. I've tried adding in the correct endpoint address :
<endpoint name="jsonEP"
          address="http://localhost/PVSCService/WebData.svc"
          binding="webHttpBinding"
          behaviorConfiguration="json"
          contract="PVSCWeb.Service.IWebData"/>

But this creates another error regarding multiple site bindings. Seems like I'm missing something simple but critical. Thanks in advance, any help much appreciated.
Comment: Can you please show us the contents of the `WebData.svc` file?
Answer: Well, your WCF service uses the webHttpBinding which is the one to use for REST services.
However, your NUnit config uses wsHttpBinding which is wrong here - that's a SOAP binding and it's NOT compatible with webHttpBinding. You need to change the NUnit config to also use webHttpBinding

WCF Client config trouble


When C++ const methods synchronize mutable state, do non-const methods have to do so too?

Question: According to Herb Sutter (http://isocpp.org/blog/2012/12/you-dont-know-const-and-mutable-herb-sutter), in C++11 const methods must not alter the object bit-wise, or must perform internal synchronization (e.g. using a mutex) if they have mutable data members.
My question is, do non-const methods have to acquire the mutex too? Or can they rely on the external synchronization their user will have to perform if the user wants to mix const and non-const methods on the same object concurrently?
EDIT: Put another way,  is the following class thread-safe? does the following class provide Sutter's "basic thread safety guarantee" (from part 4b of GOTW #95)?
#include <thread>

class C {
  public:
  void const_method() const
  {
    std::lock_guard<std::mutex> g(m);
    i = 2;
  }

  void non_const_method()
  {
    // std::lock_guard<std::mutex> g(m); // <-- is this needed?
    i = 1;
  }

  private:
  mutable int i;
  mutable std::mutex m;
};

Answer: No, your class is not in and of itself thread safe.
void non_const_method()
{
    // std::lock_guard<std::mutex> g(m); // <-- is this needed?
    i = 1;
}

The above is not thread safe as multiple threads could call the function thus altering i at the same time.
So to answer:

does the following class provide Sutter's "basic thread safety guarantee"

Then yes, the class provides a "basic thread safety guarantee".  You cannot modify one instance from another instance and the const methods of the class are thread safe.
You will have to use some sort of external synchronization in order to use the mutable functions of the class on the same instance in multiple threads but your non-mutable function will not require external synchronization.
Comment: @DavidSchwartz: "*The only function that can be legally called concurrently is const_method,*" And that's why the class is not thread safe. The point Herb is making is that `const` methods should always be thread safe. Non-const methods may or may not be thread safe, depending on the whims of the class implementer. Making `const` methods thread-safe doesn't mean that the entire type is thread-safe (unless the only uses of it use `const` methods).
Comment: @DavidSchwartz: To me, something is "X-safe" if you can use it for X without having to read its interface contract. So a type would be thread safe if you can use it in your threading code and not have to read which functions can or cannot be concurrently called. A class that only provides "safety" if you are very careful with how you use it is not very safe. As an analogy, C4 is a safe explosive because it only blows up when you want it to. Nitro glycerine by contrast is not considered safe, even though it won't blow up if you are very careful about handling it.
Comment: @NicolBolas Every class will fail if you don't follow its interface contract. You can't use any class for anything safely without understanding its interface contract. Your proposed definition of thread safe is not good one. For example, consider a queue that provides an `isEmpty` function and a `get` function that crashes if you call it on an empty queue (and no other query/get type functions). If there are no restrictions on concurrent invocation, is that class thread safe? (Perhaps a more accurate definition is that a class is thread safe if it provides useful concurrency?)
Comment: @DavidSchwartz: "*Every class will fail if you don't follow its interface contract.*" And a safe class is one where the contract *cannot* be broken (without employing perfidy). Your example fails because `get` is not a safe function; it crashes for reasons that you cannot control or prevent. In a thread-safe class, it would throw or otherwise error on failure, not crash.
Comment: How could multiple threads alter `i` at the same time? The only function that can be legally called concurrently is `const_method`, and it acquires a lock. (Code that calls `non_const_method` concurrently wouldn't be thread safe, but there is no such code in the class.)
Comment: @NicolBolas It does mean the entire type is thread-safe, so long as no two non-const methods of the same instance of the class are called at the same time. But then it would be the code that called the two non-const methods at the same time that wasn't thread-safe, not the class. A class is thread safe if it provides predictable behavior when used in multi-threaded code that doesn't violate its interface contract. The usual interface contract is "no concurrent accesses to non-const methods on the same instance". Every class does bad stuff if you violate its interface contract.
Comment: @DavidSchwartz: "*A class is thread safe if it provides predictable behavior when used in multi-threaded code that doesn't violate its interface contract.*" I don't think I've ever heard that definition of "thread-safe" before. I'm not sure it's a particularly useful definition, since it basically includes any class which actually has a contract that specifies threading behavior.
Comment: @NicolBolas It's just different words to express the same concept -- adjusted to highlight a relevant point often unstated. Even if you prefer "code that only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time", it's still understood that that is only so long as its interface contract isn't violated. No class ever has to provide "safe execution" if its interface contract is violated, that's the point of interface contracts.
Comment: @DavidSchwartz IMHO a class that is thread safe needs no external synchronization on any of its mutable methods(`std::atomic` comes to mind).  This class is exactly like a `std::vector` where only the `const` member function is thread safe.  I think most people would agree that a `std::vector` is not thread safe in and of itself.
Comment: @NicolBolas Almost every class of any significance is not "safe" by this definition, and most such classes would be impractically clunky. Is a container thread-safe if modifications invalidate iterators? Would you argue that a thread-safe container that owns its objects cannot return a reference to an object in it?
Comment: I think my "put another way" didn't actually rephrase my question, it asked a different one, so I'm going to edit the question for clarity. I did find another Sutter article that was helpful: https://herbsutter.com/2014/01/13/gotw-95-solution-thread-safety-and-synchronization/. In different parts of it, he effectively defines "thread-safe type" to mean the same as a fully internally synchronized type, like a message queue. Elsewhere, he defines "basic thread safety guarantee" to mean "concurrent operations on different objects is safe; concurrent const operations on the same object is safe".
Comment: @SCFrench Yes I was not understanding exactly what you were asking.  I have updated my answer.
Answer: Ideally, a writer needs to obtain more strict lock than a reader would. You might have argued if reader need to obtain a lock or not (but you asked the other way). Writers are more of the cause to produce data inconsistency.
By strict lock, I mean in a locking-protocol where reader-lock and writer-lock are possible - then writer-lock would be more strict. In most implementations, a thread which obtained a writer-lock would stall all other threads from obtaining any kind of lock, but reader-locks can be taken simultaneously. So, a non-const function would ideally take a writer-lock, but const function may simply take a reader-lock - thus allowing parallel execution of same function (or similar const functions of same object).
Yes, it is possible that a locking-protocol won't give preference to writer threads waiting, over reader thread waiting. But, that's implementation detail.


JFrame doesn't get closed completely

Question: I am using VLCJ binding to create a video player.
My code:
public class MyVideoPlayer {

    private EmbeddedMediaPlayerComponent mediaPlayerComponent;
    static String VLCLIBPATH = "C:\\Program Files\\VideoLAN\\VLC";

    public MyVideoPlayer(String source) {
        NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), VLCLIBPATH);
        Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
        JFrame frame = new JFrame("VLC Player");
        mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
        frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        frame.setContentPane(mediaPlayerComponent);
        frame.setSize(1366, 768);
        frame.setVisible(true);
        mediaPlayerComponent.getMediaPlayer().playMedia(source);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
}

I call this video player from another frame by new VideoPlayer(source).
When I use JFrame.DISPOSE_ON_CLOSE, the frame gets closed but the sound still won't go..
How can I close the video player frame completely?
Answer:
Declare the close operation as JFrame.DO_NOTHING_ON_CLOSE.
Add a WindowListener as follows (adapt to your code as needed):
frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        mediaPlayerComponent.getMediaPlayer().stop(); // Very important!
        frame.dispose();
    }
});

It will likely be necessary to declare frame & mediaPlayerComponent as final in order to access them from within an inner class.
Answer: Use JFrame.EXIT_ON_CLOSE
i.e frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The exit application default window close operation. If a window has this set as the close operation and is closed in an applet, a SecurityException may be thrown. It is recommended you only use this in an application.

https://docs.oracle.com/javase/8/docs/api/javax/swing/JFrame.html#EXIT_ON_CLOSE
If you don't want to use Exit on close which will close your application then
Add a Listener on windowClosing, when the listener call the method stop the audio
frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        System.out.println("Closed");
        //Here stop the audio
        e.getWindow().dispose();
    }
});

Comment: If i use JFrame.EXIT_ON_CLOSE, all the frames would close,and I only want to close the video player frame
Comment: That just says to use DISPOSE_ON_CLOSE in place of EXIT_ON_CLOSE
Comment: @PrateekKalra answer updatred
Comment: Do you have any idea,how to stop the audio?

JFrame doesn't get closed completely


Come along (Hoist Puller) vs Ratchet Strap

Question: Does a Ratchet Strap rated at 10,000 pounds such as this one really have 5 times the pulling strenght of a "comealong" winch rated at 2 ton such as this one?
Ratchet straps are much cheaper, and a few feet of pulling is all I need.
Comment: That would be two and a half times, not five, and is either attributable to the rope composition or hardware design.
Comment: I've unloaded equipment with a ratchet strap.  It's not something you would want to do twice.  You yourself can't put nearly 10,000 pounds of force on a ratchet strap.  When you strap down a load and cinch it with a few hundred pounds of force tops... and the load shifts... the strap will suddenly have thousands of pounds of tensile load.  If it's under 10,000, it will hold.
Answer: You might be confusing rated working load with the actual ability to pull. The comealong has a much longer lever arm and is therefore better suited to manually pull loads. The ratchet strap, on the other hand, is intended for transport. It's designed to handle dynamic loading of cargo on trucks, etc.
The bottom line is that they serve different purposes and you should select the one that meets your functional needs the best.


Great UX blogs - any "ultimate" collection you should know of?

Question:
Possible Duplicate:
Which are the best UI related blogs/sites?

Where do you find inspiration for user interface design for web applications?
What are your preferred blogs and resources of inspiration?
I try to browse http://uxpad.com/ that aggregates blogs, but there's so much clutter.
Comment: I didn't know UXPad - thank you for the reference. However, I haven't yet found a news site like Engadget with a more narrow focus on (software) UI/UX news (about e.g. browsers, Mac OS X Lion, Win 8, etc.). Engadget doesn't seem to have filtering options that address such needs? I have tried to make a Yahoo Pipe with filtering of RSS feeds from e.g. Engadget, but that doesn't work well, either.
Comment: You're welcome :) I discovered UXPad just recently. Don't they have RSS feeds per tag? Maybe you could gather interesting tags, and aggregate their RSS feeds.
Answer: bellow are some bookmarks

Usibility Post
Yahoo Developer YPatterns
Anoriod practices
Designing Help
Color Theory
Google Books
welie.com/patterns/
patterntap collection
Slideshare search for visual design
Use IT

Visit The UX Bookmarks for more Bookmarks
and after all i would like to share some thing which is i think the most important aspect of inspiration
A song to inspire confidence
This question is already asked.  Which are the best UI related blogs/sites?
Answer: a while ago I wrote an article titled "24 inspirational blogs, books and articles on user interface patterns". You'll probably find everything you need right there.
Comment: +1 - If I could choose two answers, I would include yours. Great article.
Answer: This list is certainly incomplete without http://konigi.com/. Highly recommend Coopers blog as well: http://www.cooper.com/journal/
Answer: - littlebigdetails.com is a site I love for some quick inspiration. They showcase nice little features that have a big impact on the interface involved & that would normally be overlooked.
- Smashing Magazine has a great UX section with fresh & interesting content. Always worth a look.
Answer: uxmyths.com is a very useful website.
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


all checkboxes selected on selecting specific checkbox among multiple checkboxes which has [(ngModel)] in angular4

Question: Here 'n' is incremental and 0 by default when i click "NEXT" it increments by 1
, which retirives objects respectively
statement 1:
============

#let option of question[0].options

 here,lets assume "option" will have 1st question's option. and outputs the
 following using *ngFor

 **<input name="0"  value="{{q1_option_value}}" [(ngModel)]="option_value[0]"
type="checkbox"/>{{q1_option_value}}**

 **<input name="1"  value="{{q1_option_value}}" [(ngModel)]="option_value[1]"
type="checkbox"/>{{q1_option_value}}**

 =========================
'n' value incremented by 1
 =========================

 **<input name="0"  value="{{q2_option_value}}" [(ngModel)]="option_value[0]"
type="checkbox"/>{{q2_option_value}}**

 **<input name="1"  value="{{q2_option_value}}" [(ngModel)]="option_value[1]"
type="checkbox"/>{{q2_option_value}}**

now when i select a checkbox in question1's option, that selection presist
to next question also...
Here is my code sample !
<form>

   <input name="{{i}}"  value="{{option}}" [(ngModel)]="option_value[i]"
    type="checkbox"/>{{option}}

</form>

Comment: this might help you check it https://stackoverflow.com/questions/43423333/angular-2-how-to-get-the-multiple-checkbox-value
Answer: Is technologies_value an array? If so have you tried this?
[(ngModel)]="technologies_value[i]"

Comment: OK. Well you have multiple checkboxes so the ngModel needs to be able to bind each checkbox to its own value. At the moment you are binding them all to the same variable (technologies_value) so they all get the same value.
Comment: OK. I may not entirely understand the example but the ngModel will need to have one value for every separate checkbox. In your example you have: option_value[0] and then option_value[0] repeated again for the next 'N'. If N goes up to 1 (meaning it was zero and then a 1), then you would need option_value[0], option_value[1], option_value[2] and option_value[3]
Comment: thanks for your answer, but after implementing your solution i met with another problem so i re-edited my question please take a look
Comment:
{{option}}
    **here, n performs as index & i performs as key -- hence i solved this already**.. thank you guys...


why the partitioned table is empty?

Question: I tried to partition a table based on a TIMESTAMP column. I ran the following query
CREATE OR REPLACE TABLE `stackoverflow.questions_2018_partitioned` PARTITION BY DATE(creation_date) AS SELECT * FROM `bigquery-public-data.stackoverflow.posts_questions` WHERE creation_date BETWEEN '2018-01-01' AND '2018-07-01';
but the partition table is empty. I copied this query from HERE.
would you please help me find out my mistake?
Comment: The select statement you have returns valid data ~980k rows.  When you say the table is empty how are you determining that?  Are you running a query, examining the table through the UI?
Comment: yes after creating the table, I ran a simple query to check the records of the table. but it returned no results. the query I ran for examining is copied from the link I mentioned in my question too.
Answer: Maybe the default partition expiration time in your environment is 60 days. Expiration can be set to never with OPTION (partition_expiration_days = NULL). The full command is
CREATE OR REPLACE TABLE `stackoverflow.questions_2018_partitioned`
PARTITION BY DATE(creation_date)
OPTIONS (partition_expiration_days = NULL)
AS SELECT * FROM `bigquery-public-data.stackoverflow.posts_questions` WHERE creation_date BETWEEN '2018-01-01' AND '2018-07-01';

Your personal Google Cloud account with billing-enabled will let you have partitioned tables that don't expire. This will NOT work however, in qwiklab.
Answer: I encountered same problem while populating the partitioned table, and able to find it is due to default partition expiration set as 60 days, and removing the partition expiration helped!!!.
So, remove the partition expiration for your target table stackoverflow.questions_2018_partitioned.
Please try below steps for your SQL statement and update your feedback.

 1. Create empty partitioned table

      CREATE OR REPLACE TABLE `stackoverflow.questions_2018_partitioned`
      PARTITION BY DATE(creation_date);

 2. Remove partition expiration

      ALTER TABLE `stackoverflow.questions_2018_partitioned`
      SET OPTIONS (
          -- removes partition expiration
          partition_expiration_days = NULL);

 3. Populate the partitioned table

      INSERT INTO `stackoverflow.questions_2018_partitioned`
      SELECT * FROM `bigquery-public-data.stackoverflow.posts_questions`
      WHERE creation_date BETWEEN '2018-01-01' AND '2018-07-01';

why the partitioned table is empty?


How to implement class in TypeScript?

Question: Could you help me to create class 'MyClass'
class M should be Newable and implement IMyInterface
export interface IMyInterface
{
    SomeData : A;
}

export class MyClass<T,M inherits IMyInterface<T> and new() >
{
    list = new Array<M>();

    privete Creator()
    {
        const      obj = new M();
                   obj.SameData = 'Hello data';
        list.push( obj );
    }
 }

Answer: Think you're looking for something like this...
export interface IMyInterface {
  SomeData: A;
}

export class MyClass<T, M extends IMyInterface<T>> {
  private list: M[] = [];

  constructor(private constructorFunction: {new(): M; }) {
  }

  public add(item: T): void {
    const obj = new this.constructorFunction();
    obj.SomeData = item;
    this.list.push(obj);
  }
}

export class MyItem implements IMyInterface<string> {
  public SomeData: string = '';
}

const collection = new MyClass<string, MyItem>(MyItem);
collection.add('Hello data');

I've tweaked your psuedocode so that it actually compiles and does what I think you were aiming for in the question. The important thing to note is that the types in TypeScript have no representation at runtime so you can't do new T(). Instead you need to pass in the constructor function for your class which has a type of { new(): M; }. You can then do a new X() with this value to get an object which extends your interface.

How to implement class in TypeScript?


C# Json Deserialization

Question: I have been asked to work with json data in order to create a quiz game in windows phone. I knew that I had to use json.net to achive this which I have previously used in the past but the method I used in the past is no useful here.
My question is this. I have this json string
 [{"corr":"1","q":"text.","type":"0"},
    {"corr":"0","q":"text.","type":"0"},
    {"corr":"1","q":"text.","type":"0"},
    {"corr":"0","q":"text.","type":"0"},
    {"corr":"0","q":"text.","type":"0"},
    {"corr":"1","q":"text.","type":"0"},
    {"corr":"4","q":"text","a":["text","text","text","text"],"type":"1"},
    {"corr":"2","q":"text","a":["text","text","text","text"],"type":"1"},
    {"corr":"1","q":"text","a":["text","text","text","text"],"type":"1"},
    {"corr":"2","q":"text","a":["22,2%","45%","54%","67%"],"type":"1"}]

and as you can image I want to fill some List with the properties above.
I have created the following class in order to represent the json objects
public class QuizObj
{
    public string corr { get; set; }
    public string q { get; set; }
    public string type { get; set; }
    public List<string> a { get; set; }
}

but I don't really know how to use it and can't find something really relevant.
Answer: Something like this should do the trick:
var quizObjs = JsonConvert.DeserializeObject<List<QuizObj>>(serializedStringValue);
string corr = quizObjs.First().corr;
// or
foreach(var quizObj in quizObjs)
{
    string corr = quizObj.corr;
    // etc
}

You will need to add a reference to NewtonSoft.Json, which you can get via NuGet (if you haven't already).
Comment: Could you indicate how I would retrieve the values from the quizObj ;
Comment: @dotnetter It will be a strongly typed `QuizObj`. So you could, for example: `string corr = quizObj.corr;`
Comment: What Bennor said didn't work.
@Simon It's gonna be a strongly typed QuizObj but if use the code you typed which corr property I'll get ;
Comment: yeap, that worked for me too. Could someone explain to me why we used
Comment: Because you have a collection of items. We could also have deserialized into an array or even IEnumerable.
Comment: @BennorMcCarthy You don't need that reference. The `JavaScriptSerializer` in the `System.Web.Script` namespace can sufficiently deserialize a list.
Comment: You do if you're using json.net (which the question was tagged with and why I used `JsonConvert`), but you're right -- there's really no need to use json.net for something this simple (providing you're using .net 3.5 or greater). Also, if you're using a client profile of .NET, you won't be able to have a reference to System.Web.

C# Json Deserialization


n identical objects in k distinct bins with k-1 boxes having an odd number of objects, and one box having x number of objects such that x mod 3 = 2?

Question: How many ways are there to distribute 32 indistinguishable objects into five distinct bins such that four bins have an odd number of objects and one bin has x objects such that x mod 3 = 2.
Initially, I realized that 4 of the boxes must have at least 1 object, and that one box must have at least 2 objects. To maintain the first four objects as odd, we must add pairs of objects to them and to maintain the last bin as producing x mod 3 = 2, we must add triplets of objects to them. But I am unsure where to go from there.
Comment: Well, don't forget that there are odd numbers $\equiv 2\pmod 3$, so one bin might discharge two constraints.
Answer: First suppose the question means that bins 1,2,3,4 have an odd number and bin 5 has $x$ objects
Your idea regarding initially putting 1 object into each of bins 1 to 4 and 2 into bin 5 is very sensible. Notice also that 4 odd numbers plus $x$ makes 32 and so $x$ is even i.e. $x$ is 2 modulo 6.
You must now put 13 pairs of objects into the bins with either 0, 3, 6, 9 or 12 pairs into bin 5.
It will be easy for you to count the cases now. However, you need to decide precisely what the question is asking:-
@lulu raised the issue of whether one of the odd numbers can also be the $x$. Can it?
Also, remember that the bin with $x$ objects can be any of bins 1 to 5.
Continuing with the solution. You need to do 5 separate calculations:-
If $N$ pairs go into the $x$ -box, the number of solutions is the number of ways of distributing 13-$N$ identical pairs into 4 distinct bins.
You then multiply the sum of the five numbers by 5 to take account of the position of the $x$ box.
We have $\begin{pmatrix}16 \\ 3\end{pmatrix}+\begin{pmatrix}13 \\ 3\end{pmatrix}+\begin{pmatrix}10 \\ 3\end{pmatrix}+\begin{pmatrix}7 \\ 3\end{pmatrix}+\begin{pmatrix}4 \\ 3\end{pmatrix}$
which must then be multiplied by 5.
Comment: Any of the boxes is able to be the box full-filling the modulo constraint. The odd numbers can also be x
Comment: UPDATE: I reread the question, the only constraints is that four boxes are odd and the last box has the 2 mod 3 property. Any distribution of the objects which follows this is valid.
Comment: When you say "last box" do you mean one other than the odd boxes?
Comment: In that case the method given above works. Are you familiar with "stars and bars" type problems?
Comment: I am familiar. I am just alittle unclear about accounting for the number of pairs which are not 0,3,6,9,12 in box 5. Distributing pairs into each box without taking into the condition would just be (13 + 5 - 1)C(13), but I am still unclear as to how to take into account the # of pairs that cannot be added to the 5th box (of which there are 7)
Comment: I've added what I hope will be helpful to the answer above. I don't understand what you mean by the "7" pairs.
Comment: Ah! I understand. Thank you!