问:
How to find S3 bucket created user?
I am using a different AWS user "B" to create an S3 bucket which is different from AWS account owner "A". But when I create an S3 bucket using user "B", I always see my S3 bucket owner as "A". How can I fetch details about the user who actually created the bucket ?

I have tried following S3 APIs, but I get the owner name as "A", not the actual
user "B" who created the bucket:

a. getS3AccountOwner

b. getOwner method in Bucket object returned by listBuckets API

c. getBucketAcl API

Thank You In Advance.

答:
Resources in AWS do not typically belong to a User. Rather, users have permissions that allow them to make API calls against the Account, and resources are owned by the Account.

If you particularly wish to track additional information against a bucket, you could add a Tag against the bucket to track this sort of information. However, this will not happen automatically -- you would be responsible for populating the Tag.

As @BMW pointed out, if your goal is merely to have some form of audit trail to determine who created a particular resource, then you should activate Amazon CloudTrail (which is always recommended as a best practice). It collects information about every API call including the user, IP adderess, timestamp and parameters passed.

Title: How to find S3 bucket created user?


来源: stackexchange

问:
Eclipse could not delete error
I'm working on a project with Eclipse and by now everything was fine, but last time I've tried building it, it returned the error,

"The project was not built due to "Could not delete '/Torpedo/bin/bin'.". Fix the problem, then try refreshing this project and building it since it may be inconsistent   Torpedo     Unknown Java Problem"

And it deleted my bin folder which stores all the images and stuff needed for the program. (Fortunately I had a backup). I've tried googling it and tried every solution I found, but nothing helped, and also most of them suggests to delete the folder by hand, which I can't.
What should I do?

答:
This issue came to me when permission of the project directory are changed. Make sure user has write permission to the Project directory. If there are no permission to write to Project directory then eclipse will fail to delete/create Bin folder.

To Resolve it, I gave write permission to Project directory.

Ex: sudo chmod -R 777 /MyProject/code (In my case I used Ubuntu, according to OS make sure you give write permission)

ContentLicense: CC BY-SA 3.0

Title: Eclipse could not delete error


问:
Get values from a pair RDD in Python
How to get value1 and value2 from a pair RDD of the form : [('key', (value1, value2))].

答:
You could use mapValues function to solve this. Consider that the productRDD has the structure:

```<code>[('someKey', (10, 20))]
</code>```

Then in order to find a new RDD(resultRDD) which hold the product of values in the productRDD we use:

```<code>resultRDD = productRDD.mapValues(lambda value: value[0] * (value[1]))
</code>```

The resultRDD will have the following data:

```<code>[('someKey', 200)]
</code>```

Title: Get values from a pair RDD in Python

Body:
You could use mapValues function to solve this. Consider that the productRDD has the structure:

[('someKey', (10, 20))]

Then in order to find a new RDD(resultRDD) which hold the product of values in the productRDD we use:

resultRDD = productRDD.mapValues(lambda value: value[0] * (value[1]))

The resultRDD will have the following data:

[('someKey', 200)]


问:
Chrome doesn't cache images/js/css
When Chrome loads my website, it checks the server for updated versions of files before it shows them. (Images/Javascript/CSS) It gets a 304 from the server because I never edit external javascript, css or images.

What I want it to do, is display the images without even checking the server.

Here are the headers:

```<code>Connection:keep-alive
Date:Tue, 03 Aug 2010 21:39:32 GMT
ETag:"2792c73-b1-48cd0909d96ed"
Expires:Thu, 02 Sep 2010 21:39:32 GMT
Server:Apache/Nginx/Varnish
</code>```

How do I make it not check the server?

答:
I believe you are looking for

Cache-Control: immutable

ContentLicense: CC BY-SA 2.5

Title: Chrome doesn't cache images/js/css

Body:
When Chrome loads my website, it checks the server for updated versions of files before it shows them. (Images/Javascript/CSS) It gets a 304 from the server because I never edit external javascript, css or images.

What I want it to do, is display the images without even checking the server.

Here are the headers:

Connection:keep-alive
Date:Tue, 03 Aug 2010 21:39:32 GMT
ETag:"2792c73-b1-48cd0909d96ed"
Expires:Thu, 02 Sep 2010 21:39:32 GMT
Server:Apache/Nginx/Varnish

How do I make it not check the server?


问:
How to read multiple pdf file from folder in asp.net.?
I am working on a project and i need to read multiple pdf file from a folder and show its content when click on button.
I am facing problem to read multiples files at a time. how could i read multiple pdf files.? Is anyone help me.?

```<code>protected void btnShowContent_Click(object sender, EventArgs e)
            {
                //if (fileUpload.HasFile)
                //{

                    foreach (string file in Directory.GetFiles(@"E:\\Rida\","*.pdf"))
                    {
                    string str = "";
                    str = str + ", " + file.ToString();
                    PdfReader reader = new PdfReader(file);
                        string strPDFFile = file.ToString().Trim();
                        StringBuilder strPdfContent = new StringBuilder();
                    string pdfText = strPdfContent.ToString();
                        string contents = File.ReadAllText(strPDFFile);

                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            ITextExtractionStrategy objExtractStrategy = new SimpleTextExtractionStrategy();
                            string strLineText = PdfTextExtractor.GetTextFromPage(reader, i, objExtractStrategy);
                            strLineText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(strLineText)));
                            strPdfContent.Append(strLineText);
                            strPdfContent.Append(contents);

                            strPdfContent.Append("<br/>");
                        }
                    reader.Close();
                    lblPdfContent.Text = strPdfContent.ToString();
                    }
            }
</code>```

This line convert my pdf file content into special characters. What should i Do to avoid this conversion.?

```<code>string contents = File.ReadAllText(strPDFFile);
</code>```

答:
As far as i know about the PDF parsing and manipulations in .NET environment, you can use iTextSharp, it is a PDF library that allows you to CREATE, ADAPT, INSPECT and MAINTAIN documents in PDF.
Use libraries, It can help you solve your problem !

https://sourceforge.net/projects/itextsharp/

http://jadn.co.uk/w/ReadPdfUsingCsharp.htm

Body:
I am working on a project and i need to read multiple pdf file from a folder and show its content when click on button.
I am facing problem to read multiples files at a time. how could i read multiple pdf files.? Is anyone help me.?

protected void btnShowContent_Click(object sender, EventArgs e)
            {
                //if (fileUpload.HasFile)
                //{

                    foreach (string file in Directory.GetFiles(@"E:\\Rida\","*.pdf"))
                    {
                    string str = "";
                    str = str + ", " + file.ToString();
                    PdfReader reader = new PdfReader(file);
                        string strPDFFile = file.ToString().Trim();
                        StringBuilder strPdfContent = new StringBuilder();
                    string pdfText = strPdfContent.ToString();
                        string contents = File.ReadAllText(strPDFFile);

                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            ITextExtractionStrategy objExtractStrategy = new SimpleTextExtractionStrategy();
                            string strLineText = PdfTextExtractor.GetTextFromPage(reader, i, objExtractStrategy);
                            strLineText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(strLineText)));
                            strPdfContent.Append(strLineText);
                            strPdfContent.Append(contents);

                            strPdfContent.Append("
");
                        }
                    reader.Close();
                    lblPdfContent.Text = strPdfContent.ToString();
                    }
            }

This line convert my pdf file content into special characters. What should i Do to avoid this conversion.?

string contents = File.ReadAllText(strPDFFile);


问:
Are line breaks in XML attribute values allowed?
I realise that it's not elegant or desired, but is it allowed (in well-formed XML) for an attribute value in an XML element to span multiple lines?

e.g.

```<code><some-xml-element value="this value goes over....
multiple lines!" />
</code>```

Yeah I realise there's better ways of writing that. I would personally write it like:

```<code><some-xml-element>
<value>this value goes over...
multiple lines!</value>
</some-xml-element>
</code>```

or:

```<code><some-xml-element value="this value goes over....
" />
</code>```

But we have our own XML parser and I'd like to know whether the first example is allowed in well-formed XML.

答: Yes the first example is a valid one.</p>

OwnerDisplayName: Ben Daniel

Body:
I realise that it's not elegant or desired, but is it allowed (in well-formed XML) for an attribute value in an XML element to span multiple lines?

e.g.

<some-xml-element value="this value goes over....
multiple lines!" />

Yeah I realise there's better ways of writing that. I would personally write it like:

<some-xml-element>
<value>this value goes over...
multiple lines!</value>
</some-xml-element>

or:

<some-xml-element value="this value goes over....
" />

But we have our own XML parser and I'd like to know whether the first example is allowed in well-formed XML.

Body: Yes the first example is a valid one.

OwnerDisplayName: GreenShadow


问:
Excel importing date inconsistently from Csv
I have a .csv file delimited with ; (semicolon) generated from PHP code. It has three columns that contain date in d m y format(eg. 23 Apr 2013).

But when imported it in Excel,these date value become inconsistent.

It shows two different formats:

```<code>12 Oct 2006
15. Feb 06
</code>```

In the .CSV, the format is same as that of 12 Oct 2006.

I have tried making them consistent by selecting the whole column and changing a single format. But it doesn't work.

答:
It's because of different language of your Excel.

for example:

In deutsche

```<code> 23 Oct 2017
</code>```

In English

```<code> 23 Okt 2017
</code>```

So it will not understand Oct if you are using deutsche language with your excel.

same for English language it will not understand Okt.

For Example Deutsche

```<code>1. Jan 07
1. Feb 07
1. Mrz 07
1. Apr 07
1. Mai 07
1. Jun 07
1. Jul 07
1. Aug 07
1. Sep 06
1. Okt 06
1. Nov 06
1. Dez 06
</code>```

For Example English

```<code>1. Jan 07
1. Feb 07
1. Mar 07
1. Apr 07
1. May 07
1. Jun 07
1. Jul 07
1. Aug 07
1. Sep 06
1. Oct 06
1. Nov 06
1. Dec 06
</code>```

Body:
I have a .csv file delimited with ; (semicolon) generated from PHP code. It has three columns that contain date in d m y format(eg. 23 Apr 2013).

But when imported it in Excel,these date value become inconsistent.

It shows two different formats:

12 Oct 2006
15. Feb 06

In the .CSV, the format is same as that of 12 Oct 2006.

I have tried making them consistent by selecting the whole column and changing a single format. But it doesn't work.

Body:
It's because of different language of your Excel.

for example:

In deutsche

 23 Oct 2017

In English

 23 Okt 2017

So it will not understand Oct if you are using deutsche language with your excel.

same for English language it will not understand Okt.

For Example Deutsche

1. Jan 07
1. Feb 07
1. Mrz 07
1. Apr 07
1. Mai 07
1. Jun 07
1. Jul 07
1. Aug 07
1. Sep 06
1. Okt 06
1. Nov 06
1. Dez 06

For Example English

1. Jan 07
1. Feb 07
1. Mar 07
1. Apr 07
1. May 07
1. Jun 07
1. Jul 07
1. Aug 07
1. Sep 06
1. Oct 06
1. Nov 06
1. Dec 06


问:
how to add move image on touch event android?
This class has three Buttons Add table, Add chair and reset add table will add tablein second layout add chair will add chair image in second layout.Both button works but I want to move chair and table (imageView) in screen.

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    private ArrayList<String> mSelecetdItems = new ArrayList<>();
    public static final String SELECETD_ITEMS = "SELECETD_ITEMS";

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

    public  void addtable(View v){
        this.mSelecetdItems.add("table");
        showSecondActivity();
    }
    public  void addchair(View v){
        this.mSelecetdItems.add("chair");
        showSecondActivity();
    }

    private void showSecondActivity() {
        Intent i = new Intent(this,Second.class);
        i.putStringArrayListExtra(SELECETD_ITEMS,this.mSelecetdItems);
        startActivity(i);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putStringArrayList(SELECETD_ITEMS , mSelecetdItems);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        this.mSelecetdItems = savedInstanceState.getStringArrayList(SELECETD_ITEMS);
    }
}
</code>```

This class has three Buttons Add table, Add chair and reset add table will add tablein second layout add chair will add chair image in second layout. I want to move table and chair in layout image.

Second.java

```<code>public class Second extends AppCompatActivity {

    ImageView iv;
    ImageView iv2;
    private int xDelta;
    private int yDelta;
    LinearLayoutCompat hall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Toolbar toolbar = (Toolbar) findViewById(R.id.second_toolbar);
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);

        hall = (LinearLayoutCompat) findViewById(R.id.hall_layout);
        Intent i = getIntent();

        ArrayList<String> selecetdItems = i.getStringArrayListExtra(MainActivity.SELECETD_ITEMS);
        for (String selecetdItem : selecetdItems) {
            if (selecetdItem.equals("table")) {
                addImageView(R.drawable.table, hall);
            } else if (selecetdItem.equals("chair")) {
                addImageView2(R.drawable.chair2, hall);
            }
        }
    }

    private void addImageView(int imageRes, LinearLayoutCompat hall) {
       iv = new ImageView(this);
        iv.setImageResource(imageRes);
        iv.setLayoutParams(new android.view.ViewGroup.LayoutParams(250, 250));
        iv.setMaxHeight(180);
        iv.setMaxWidth(120);
        iv.setPadding(15,15,0,0);
        hall.addView(iv);
    }

    private void addImageView2(int imageRes, LinearLayoutCompat hall) {
         iv2 = new ImageView(this);
        iv2.setImageResource(imageRes);
        iv2.setLayoutParams(new android.view.ViewGroup.LayoutParams(150, 150));
        iv2.setMaxHeight(30);
        iv2.setMaxWidth(30);

        iv2.setPadding(25,0,0,0);
        hall.addView(iv2);
    }
}
</code>```

activity_main.xml This layout file has ConstraintLayout in Root.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andiroot.restaurantbook.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:background="#ff1e8622"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
      >
    </android.support.v7.widget.Toolbar>

    <RelativeLayout
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="64dp">

        <Button
            android:id="@+id/btn_addtbl"
            style="@style/Widget.AppCompat.Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="76dp"
            android:text="Add Table"
            android:onClick="addtable"/>

        <Button
            android:id="@+id/btn_addchairs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="addchair"
            android:layout_marginTop="27dp"
            android:text="Add Chair"
            android:layout_below="@+id/btn_addtbl"
            android:layout_alignEnd="@+id/btn_addtbl" />

        <Button
            android:id="@+id/btn_reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/btn_addchairs"
            android:layout_below="@+id/btn_addchairs"
            android:layout_marginTop="51dp"
            android:text="Reset" />
    </RelativeLayout>

</android.support.constraint.ConstraintLayout>
</code>```

activity_second.xml This layout file has LinearLayoutCompat  in Root

```<code><?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/hall_layout"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andiroot.restaurantbook.Second">

    <android.support.v7.widget.Toolbar
        android:id="@+id/second_toolbar"
        android:minHeight="?attr/actionBarSize"
        android:background="#ff1e8622"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.widget.Toolbar>
<!--
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/hall_layout2">
    </RelativeLayout>
-->
</android.support.v7.widget.LinearLayoutCompat>

```
```

答:
try this</p>

```<code>    ImageView dishaIMG;
    RelativeLayout cropperLayout;
    float dX, dY;
    float windowWidth, windowHeight;

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    windowHeight = displayMetrics.heightPixels;
    windowWidth = displayMetrics.widthPixels;

    cropperLayout = (RelativeLayout) findViewById(R.id.activity_main2);

    dishaIMG = (ImageView) findViewById(R.id.img_disha);

        dishaIMG.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent motionEvent) {

            int width = dishaIMG.getLayoutParams().width;
            int height = dishaIMG.getLayoutParams().height;

            switch (motionEvent.getAction()) {

                case MotionEvent.ACTION_DOWN:

                    dX = v.getX() - motionEvent.getRawX();
                    dY = v.getY() - motionEvent.getRawY();

                    case MotionEvent.ACTION_MOVE:

                    if (width == windowWidth && height == windowHeight) {

                    } else {
                        v.animate()
                                .x(motionEvent.getRawX() + dX)
                                .y(motionEvent.getRawY() + dY)
                                .setDuration(0)
                                .start();

                        if (motionEvent.getRawX() + dX + width > windowWidth) {
                            v.animate()
                                    .x(windowWidth - width)
                                    .setDuration(0)
                                    .start();
                        }
                        if (motionEvent.getRawX() + dX < 0) {
                            v.animate()
                                    .x(0)
                                    .setDuration(0)
                                    .start();
                        }
                        if (motionEvent.getRawY() + dY + height > windowHeight) {
                            v.animate()
                                    .y(windowHeight - height)
                                    .setDuration(0)
                                    .start();
                        }
                        if (motionEvent.getRawY() + dY < 0) {
                            v.animate()
                                    .y(0)
                                    .setDuration(0)
                                    .start();
                        }

                    }
            }
            return true;
        }
    });
</code>```

Body:
This class has three Buttons Add table, Add chair and reset add table will add tablein second layout add chair will add chair image in second layout.Both button works but I want to move chair and table (imageView) in screen.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private ArrayList<String> mSelecetdItems = new ArrayList<>();
    public static final String SELECETD_ITEMS = "SELECETD_ITEMS";

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

    public  void addtable(View v){
        this.mSelecetdItems.add("table");
        showSecondActivity();
    }
    public  void addchair(View v){
        this.mSelecetdItems.add("chair");
        showSecondActivity();
    }

    private void showSecondActivity() {
        Intent i = new Intent(this,Second.class);
        i.putStringArrayListExtra(SELECETD_ITEMS,this.mSelecetdItems);
        startActivity(i);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putStringArrayList(SELECETD_ITEMS , mSelecetdItems);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        this.mSelecetdItems = savedInstanceState.getStringArrayList(SELECETD_ITEMS);
    }
}

This class has three Buttons Add table, Add chair and reset add table will add tablein second layout add chair will add chair image in second layout. I want to move table and chair in layout image.

Second.java

public class Second extends AppCompatActivity {

    ImageView iv;
    ImageView iv2;
    private int xDelta;
    private int yDelta;
    LinearLayoutCompat hall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Toolbar toolbar = (Toolbar) findViewById(R.id.second_toolbar);
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);

        hall = (LinearLayoutCompat) findViewById(R.id.hall_layout);
        Intent i = getIntent();

        ArrayList<String> selecetdItems = i.getStringArrayListExtra(MainActivity.SELECETD_ITEMS);
        for (String selecetdItem : selecetdItems) {
            if (selecetdItem.equals("table")) {
                addImageView(R.drawable.table, hall);
            } else if (selecetdItem.equals("chair")) {
                addImageView2(R.drawable.chair2, hall);
            }
        }
    }

    private void addImageView(int imageRes, LinearLayoutCompat hall) {
       iv = new ImageView(this);
        iv.setImageResource(imageRes);
        iv.setLayoutParams(new android.view.ViewGroup.LayoutParams(250, 250));
        iv.setMaxHeight(180);
        iv.setMaxWidth(120);
        iv.setPadding(15,15,0,0);
        hall.addView(iv);
    }

    private void addImageView2(int imageRes, LinearLayoutCompat hall) {
         iv2 = new ImageView(this);
        iv2.setImageResource(imageRes);
        iv2.setLayoutParams(new android.view.ViewGroup.LayoutParams(150, 150));
        iv2.setMaxHeight(30);
        iv2.setMaxWidth(30);

        iv2.setPadding(25,0,0,0);
        hall.addView(iv2);
    }
}

activity_main.xml This layout file has ConstraintLayout in Root.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andiroot.restaurantbook.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:minHeight="?attr/actionBarSize"
        android:background="#ff1e8622"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
      >
    </android.support.v7.widget.Toolbar>

    <RelativeLayout
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="64dp">

        <Button
            android:id="@+id/btn_addtbl"
            style="@style/Widget.AppCompat.Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="76dp"
            android:text="Add Table"
            android:onClick="addtable"/>

        <Button
            android:id="@+id/btn_addchairs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="addchair"
            android:layout_marginTop="27dp"
            android:text="Add Chair"
            android:layout_below="@+id/btn_addtbl"
            android:layout_alignEnd="@+id/btn_addtbl" />

        <Button
            android:id="@+id/btn_reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/btn_addchairs"
            android:layout_below="@+id/btn_addchairs"
            android:layout_marginTop="51dp"
            android:text="Reset" />
    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

activity_second.xml This layout file has LinearLayoutCompat  in Root

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/hall_layout"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andiroot.restaurantbook.Second">

    <android.support.v7.widget.Toolbar
        android:id="@+id/second_toolbar"
        android:minHeight="?attr/actionBarSize"
        android:background="#ff1e8622"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.widget.Toolbar>

</android.support.v7.widget.LinearLayoutCompat>

Body:
try this

    ImageView dishaIMG;
    RelativeLayout cropperLayout;
    float dX, dY;
    float windowWidth, windowHeight;

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    windowHeight = displayMetrics.heightPixels;
    windowWidth = displayMetrics.widthPixels;

    cropperLayout = (RelativeLayout) findViewById(R.id.activity_main2);

    dishaIMG = (ImageView) findViewById(R.id.img_disha);

        dishaIMG.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent motionEvent) {

            int width = dishaIMG.getLayoutParams().width;
            int height = dishaIMG.getLayoutParams().height;

            switch (motionEvent.getAction()) {

                case MotionEvent.ACTION_DOWN:

                    dX = v.getX() - motionEvent.getRawX();
                    dY = v.getY() - motionEvent.getRawY();

                    case MotionEvent.ACTION_MOVE:

                    if (width == windowWidth && height == windowHeight) {

                    } else {
                        v.animate()
                                .x(motionEvent.getRawX() + dX)
                                .y(motionEvent.getRawY() + dY)
                                .setDuration(0)
                                .start();

                        if (motionEvent.getRawX() + dX + width > windowWidth) {
                            v.animate()
                                    .x(windowWidth - width)
                                    .setDuration(0)
                                    .start();
                        }
                        if (motionEvent.getRawX() + dX < 0) {
                            v.animate()
                                    .x(0)
                                    .setDuration(0)
                                    .start();
                        }
                        if (motionEvent.getRawY() + dY + height > windowHeight) {
                            v.animate()
                                    .y(windowHeight - height)
                                    .setDuration(0)
                                    .start();
                        }
                        if (motionEvent.getRawY() + dY < 0) {
                            v.animate()
                                    .y(0)
                                    .setDuration(0)
                                    .start();
                        }

                    }
            }
            return true;
        }
    });


问:
i can see search icon on my actionbar even though i have not implemented searchquery listener in my fragment android
i can see search icon on my actionbar even though i have not implemented searchquery listener in my fragment android,

Prior to this i have a fragment that holds viewpager in which there are two fragments(FragA and FragB) with list...i have implemented SearchQueryListener and implement OCreateOptionMenu in both FragA and FragB,, on item click of FragA and FragB i want to add another fragment that keeps the detail of item but when i add that new fragment i am able to see the same search icon on topbar..when click on that search icon my app crash because search icon dowsnt belong to this current fragment..
Please help me to resolve how to get this fix.. i want to have Search icon only where i have implemented onCreateOptionMenu method..

Thanks in advance

答:
You can use either of the below options,

```<code>@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.removeItem(id)
}
</code>```

or

```<code>@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
</code>```

Body:
You can use either of the below options,

@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.removeItem(id)
}

or

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}


问:
Anomaly in output from enumerators in typescript
Can anyone explain the output i am getting from the below code?

enum days { sun = 1, mon = 0, tues };

console.log(days[1]); // returns tues // expected output --  mon

console.log(days[0]); // returns mon // expected output -- sun

Also, please explain how can i get sun printed in this case? This scenario is baffling me. Request you guys to provide valid explanations only after you have executed the code and observed the output.

答:
This typescript:

```<code>enum days { sun = 1, mon = 0, tues };
</code>```

compiles to this javascript:

```<code>var days;
(function (days) {
    days[days["sun"] = 1] = "sun";
    days[days["mon"] = 0] = "mon";
    days[days["tues"] = 1] = "tues";
})(days || (days = {}));
;
</code>```

This first part: days[days["sun"] = 1] = "sun";

first evaluates days["sun"] = 1 which:

makes sure that you're able to call days.sun and get value 1

returns the value set at key "sun" => 1. This means that initially days[1] will be set to "sun".

The second part: days[days["mon"] = 0] = "mon";

makes sure that you're able to call days.mon and get value 0

returns the value set at key "mon" => 0. So days[0] will be set to "mon".

This third part however: days[days["tues"] = 1] = "tues";

evaluates days["tues"] = 1 which

makes sure that you're able to call days.tues and get value 1

also returns the value set at key "tues" => 1

This means that at this point days[1] will be overwritten with value "tues"

Body:
This typescript:

enum days { sun = 1, mon = 0, tues };

compiles to this javascript:

var days;
(function (days) {
    days[days["sun"] = 1] = "sun";
    days[days["mon"] = 0] = "mon";
    days[days["tues"] = 1] = "tues";
})(days || (days = {}));
;

This first part: days[days["sun"] = 1] = "sun";

first evaluates days["sun"] = 1 which:

makes sure that you're able to call days.sun and get value 1

returns the value set at key "sun" => 1. This means that initially days[1] will be set to "sun".

The second part: days[days["mon"] = 0] = "mon";

makes sure that you're able to call days.mon and get value 0

returns the value set at key "mon" => 0. So days[0] will be set to "mon".

This third part however: days[days["tues"] = 1] = "tues";

evaluates days["tues"] = 1 which

makes sure that you're able to call days.tues and get value 1

also returns the value set at key "tues" => 1

This means that at this point days[1] will be overwritten with value "tues"


问:
Placeholder not working mozilla latest with bootstrap
Bootstrap v2.3.1 - less  placeholder styles working on chrome but not working on Mozilla latest version

Please help
Less code here

```<code>.placeholder(red);
</code>```

答:
```<code> <style>
 ::-webkit-input-placeholder { /* Chrome/Opera/Safari */
  color: pink;
 }
 ::-moz-placeholder { /* Firefox 19+ */
  color: pink;
 }
 :-ms-input-placeholder { /* IE 10+ */
  color: pink;
 }
 :-moz-placeholder { /* Firefox 18- */
  color: pink;
 }
 <style>
<input type="email" placeholder="anytext">
</code>```

Body:
Bootstrap v2.3.1 - less  placeholder styles working on chrome but not working on Mozilla latest version

Please help
Less code here

.placeholder(red);


问:
Using Visual Studio Code with non-Core Asp.Net MVC
How I do to work with non-Core Asp.Net MVC projects on Visual Studio Code?

I'm tired of slowness of Visual Studio Community, so I was thinking about if I can setup an VS Code environment for that.

答:
I've successfully setup my Visual Studio 2015+ ASP.NET project on VSCode.

I've created an gulpfile that handle the build for me:

It starts an IISExpress instance.

Refresh my browser on razor code change.

And automatically rebuild my application when I change C# code.

You can find the gulpfile on my project's Github


问:
Slick carousel in Center Mode causes SlidesToscroll does not work as it should be
In slick carousel(Slick.js), I would like to use centerPadding so I have to set centerMode to true. After I turn CenterMode on, I swipe the slides but it moves just only one slide per swipe no matter how much I drag/swipe the carousel from side to side. If I change centerMode to false, the carousel works properly but centerPadding does not work.

In summary

centerMode: true //Turn this false then the slideToScoll works but centerPadding doesn't work

centerPadding: "30px" //Work only if centerMode is true

slideToScroll: 3 //This doesn't works, only 1 slide scroll per swipe

I want those options of slicks carousel works together, centerMode with CenterPadding and number of slideToScroll works as indicated.

Is that possible?

答:
if I understand your issue correctly, this can be resolved by using:

swipeToSlide: true

in your settings.

That will cause swipe/drag to stop on the slide you actually swiped to, rather than the next slide.

But there is no way to make certerMode and slideToScroll, both to work at the same time.


问:
Avoid re-entering password for each submodule
I have a repo with 3 submodules. The repo and submodules are all on the same server, which I have ssh access to. The remote URLs are:

```<code>ssh://mm@theserver.com/path/to/sub1.git
ssh://mm@theserver.com/path/to/sub2.git
ssh://mm@theserver.com/path/to/sub3.git
</code>```

If I do an operation such as git submodule update --remote then it prompts for my password 3 times.

Is there any way to update the submodules but only require password once?  Same goes for committing changes etc.

答:
Solution that requires much less headache

Another approach is to use built-in git cache (v. 1.7.10 or newer required) so git will remember your login and password after you provide it first time.

To enable git cache with default timeout (15 min) you type

```<code>git config --global credential.helper cache
</code>```

To change default timeout type

```<code>git config --global credential.helper 'cache --timeout=3600'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a repo with 3 submodules. The repo and submodules are all on the same server, which I have ssh access to. The remote URLs are:

ssh://mm@theserver.com/path/to/sub1.git
ssh://mm@theserver.com/path/to/sub2.git
ssh://mm@theserver.com/path/to/sub3.git

If I do an operation such as git submodule update --remote then it prompts for my password 3 times.

Is there any way to update the submodules but only require password once?  Same goes for committing changes etc.

Body:
Solution that requires much less headache

Another approach is to use built-in git cache (v. 1.7.10 or newer required) so git will remember your login and password after you provide it first time.

To enable git cache with default timeout (15 min) you type

git config --global credential.helper cache

To change default timeout type

git config --global credential.helper 'cache --timeout=3600'


问:
Indexing a MYSQL table with many columns
I have a table posts with the following columns:

start_at, sun, mon, tue, wen, thu, fri, sat

start_at is of date type, the others - tinyint.

I make a query the following way:

```<code>SELECT * FROM posts WHERE start_at >= '2017-02-01' AND mon = 1
</code>```

That is after second AND I set proper day of week dynamically.

What is the best way to index this table? Do I need to make a composite index for each day of a week, for example:

```<code>CREATE INDEX mon_index ON posts(start_at,mon);
CREATE INDEX sun_index ON posts(start_at,sun);
</code>```

If I create 7 indexes for each day of the week, I think INSERT and UPDATE will be really slow.

UPDATED: I do need column for each day of week, because a user sets on which days post will be published. There can be a few days at the same time.

答:
Your schema has been oddly designed. Your current setup may make for easy reporting, but you're correct, indexing like you've suggested will create terrible insert and update performance.

My suggestion would be to refactor this table. Instead of your current setup, I would suggest that you change the posts table to have the columns (start_at, day). In this design, day can be Sun through Sat, and you only need one index (start_at, day).

If you really need the current format for reading/reporting reasons (I wouldn't blame you), you could always setup a view that pivots the data in that manner.

All of that being said, not every field you qualify on needs to be in an index. My estimation is that the vast majority of your table's rows will be filterable simply by the date. The few that are left probably don't need to be indexed for decent read performance.

In a different vein, why even store the day? That can be calculated based off the date.

Body:
I have a table posts with the following columns:

start_at, sun, mon, tue, wen, thu, fri, sat

start_at is of date type, the others - tinyint.

I make a query the following way:

SELECT * FROM posts WHERE start_at >= '2017-02-01' AND mon = 1

That is after second AND I set proper day of week dynamically.

What is the best way to index this table? Do I need to make a composite index for each day of a week, for example:

CREATE INDEX mon_index ON posts(start_at,mon);
CREATE INDEX sun_index ON posts(start_at,sun);

If I create 7 indexes for each day of the week, I think INSERT and UPDATE will be really slow.

UPDATED: I do need column for each day of week, because a user sets on which days post will be published. There can be a few days at the same time.


问:
Difference between SR and AES
I want to compare two "Evolution Startegies" using SR (Sucess Rate) and AES (average number of evaluations to a solution). I am not sure of how "AES" works...

Let's say, I have 10 runs of the algorithm and the optimum is at value 0.0:

```<code>Run 1: 0.1
Run 2: 0.8
Run 3: NAN
Run 4: 1.5
Run 5: 0.4
Run 6: 0.3
Run 7: NAN
Run 8: 1.9
Run 9: 1.1
Run 10: 0.5
</code>```

I understand that if I choose the limit of 1.0, the succes rate is: 5/10.

Questions:

1- Is the SR value right?

2- What is the value of the AES?

3- Do I have to use the same limit value (1.0 in thus example) for the SR and the AES?

4- To calculate the AES, do I need to know in which iteration of each run the value was lower than 1.0 (for example)? Could you provide an example?

Thanks in advance

答:
Success rate is the ratio of number of runs that an specific algorithm could reach to an expected accuracy to the total number of runs. It means that:
SR = (number of successful runs/total number of runs). To do this, you first need to determine a threshold for errors. This threshold depends on how hard the problem is. An example can be found in Kordestani, J. K., A. Ahmadi, and M. R. Meybodi. 2014. “An Improved Differential Evolution Algorithm using Learning
Automata and Population Topologies.” Applied Intelligence 41 (4): 1150–1169., where 1e-10 has been considered as an expected accuracy for some easy to optimize functions and 1e-6 and 1e-2 have been considered for some harder functions.
Average number of evaluations to a solution is the number of evaluations spended to reach the considered accuracy which are averaged over various runs. Following is an example to further examin SR and AES.
Assume that we run an algorithm for optimizing a mathematical function 5 times (atleast 30 times should be performed to reach a conclusion about the performance of different algorithms as suggested in different papers however for the sake of an example we consider 5 runs). Moreover, the termination condition is reaching 10000 function evaluation. The followings are the error of the best solution found(err), successful run(ea), and the evaluation number where the algorithm reaches to the expected accuracy(FE).

```<code>run     err     ea     FE     Successful run
1     1.35e-3  1e-2    8800      YES
2     1.05e-1  1e-2    -          NO
3     2.95e-4  1e-2    6000      YES
4     5.55e-8  1e-2    4200      YES
5     9.98e-0  1e-2    -         NO
</code>```

Considering the above table, SR = (3/5) = 0.6 or 60%.
The AES for successful runs is also calculated as (8800+6000+4200)/3

Title: Difference between SR and AES

Body:
I want to compare two "Evolution Startegies" using SR (Sucess Rate) and AES (average number of evaluations to a solution). I am not sure of how "AES" works...

Let's say, I have 10 runs of the algorithm and the optimum is at value 0.0:

Run 1: 0.1
Run 2: 0.8
Run 3: NAN
Run 4: 1.5
Run 5: 0.4
Run 6: 0.3
Run 7: NAN
Run 8: 1.9
Run 9: 1.1
Run 10: 0.5

I understand that if I choose the limit of 1.0, the succes rate is: 5/10.

Questions:

1- Is the SR value right?

2- What is the value of the AES?

3- Do I have to use the same limit value (1.0 in thus example) for the SR and the AES?

4- To calculate the AES, do I need to know in which iteration of each run the value was lower than 1.0 (for example)? Could you provide an example?

Thanks in advance

Body:
Success rate is the ratio of number of runs that an specific algorithm could reach to an expected accuracy to the total number of runs. It means that:
SR = (number of successful runs/total number of runs). To do this, you first need to determine a threshold for errors. This threshold depends on how hard the problem is. An example can be found in Kordestani, J. K., A. Ahmadi, and M. R. Meybodi. 2014. “An Improved Differential Evolution Algorithm using Learning
Automata and Population Topologies.” Applied Intelligence 41 (4): 1150–1169., where 1e-10 has been considered as an expected accuracy for some easy to optimize functions and 1e-6 and 1e-2 have been considered for some harder functions.
Average number of evaluations to a solution is the number of evaluations spended to reach the considered accuracy which are averaged over various runs. Following is an example to further examin SR and AES.
Assume that we run an algorithm for optimizing a mathematical function 5 times (atleast 30 times should be performed to reach a conclusion about the performance of different algorithms as suggested in different papers however for the sake of an example we consider 5 runs). Moreover, the termination condition is reaching 10000 function evaluation. The followings are the error of the best solution found(err), successful run(ea), and the evaluation number where the algorithm reaches to the expected accuracy(FE).

run     err     ea     FE     Successful run
1     1.35e-3  1e-2    8800      YES
2     1.05e-1  1e-2    -          NO
3     2.95e-4  1e-2    6000      YES
4     5.55e-8  1e-2    4200      YES
5     9.98e-0  1e-2    -         NO

Considering the above table, SR = (3/5) = 0.6 or 60%.
The AES for successful runs is also calculated as (8800+6000+4200)/3


问:
What are the benefits of using emacs auto-fill-mode?
I am wondering whether I should disable emacs auto-fill-mode it or keep it.

Why would I want to disable it?

Why would I want to keep it?

Are there any factors other than personal preference, or anything that may influence my personal preference?

答:
I guess a good rule of thumb is whether anyone else will be looking at the file, and whether they have a reasonable expectation the text will be filled. If it's going to be filled text, you might as well use auto-fill.

I'm not sure there is a single answer, but I use auto-fill in some modes and not in others. On for things that are commonly understood to have a column limit: code [comments], commit logs. Off for free form text notes, org-mode, etc. There's no reason it has to be used globally.


问:
Synchronized block will lock the whole object or the method alone?
I have multiple methods in a class and most of the methods are having critical sections(shared data). So I made those methods as synchronized. Say thread t1 is running one of the synchronized block . At the same time thread t2 can access the other methods critical section ? </p>

```<code>class Sample{

synchronized public void method1(){

}

synchronized public void method2(){

}

synchronized public void method3(){

}

public void method4(){

}

}
</code>```

答:
In the case

```<code>Sample sample1 = new Sample();
</code>```

Multiple threads can't access

```<code>sample1.method1(),sample1.method2(),sample1.method3()
</code>```

But Multiple threads can access concurrently

```<code>sample1.method4()
</code>```

if we have 2 objects

```<code>Sample sample1 = new Sample();
Sample sample2 = new Sample();
</code>```

Multiple threads can access cocurrently

```<code>sample1.method1(),sample2.method1() etc.
</code>```

so the lock is at object level

Body:
I have multiple methods in a class and most of the methods are having critical sections(shared data). So I made those methods as synchronized. Say thread t1 is running one of the synchronized block . At the same time thread t2 can access the other methods critical section ?

class Sample{

synchronized public void method1(){

}

synchronized public void method2(){

}

synchronized public void method3(){

}

public void method4(){

}

}

Body:
In the case

Sample sample1 = new Sample();

Multiple threads can't access

sample1.method1(),sample1.method2(),sample1.method3()

But Multiple threads can access concurrently

sample1.method4()

if we have 2 objects

Sample sample1 = new Sample();
Sample sample2 = new Sample();

Multiple threads can access cocurrently

sample1.method1(),sample2.method1() etc.

so the lock is at object level


问:
Illegal string offset on heroku deployment
I am configuring my postgresql driver in Laravel 5.4 for deployment to Heroku. Here is my config/database.php, the default is already set to pgsql

```<code>'pgsql' => [
        'driver' => 'pgsql',
        'host' => parse_url(getenv("DATABASE_URL"))['host'],
        'database' => substr(parse_url(getenv("DATABASE_URL"))['path'], 1),
        'username' => parse_url(getenv("DATABASE_URL")['username']),
        'password' => parse_url(getenv("DATABASE_URL")['password']),
        'charset' => 'utf8',
        'prefix' => '',
        'schema' => 'public',
    ],
</code>```

When I commit I see this warning

```<code>PHP Warning: Illegal string offset 'username' in app/config/database.php on line 62
</code>```

When run heroku run php artisan serveI am getting an error

```<code>[Symfony\Component\Debug\Exception\FatalThrowableError]
Type error: PDO::__construct() expects parameter 2 to be string, array given
</code>```

Here is my .env

```<code>DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=forge
DB_USERNAME=postgres
DB_PASSWORD=
</code>```

答:
I found the answer in this site. It caters also mysql, and sqlite, please read
https://mattstauffer.co/blog/installing-a-laravel-app-on-heroku</p>

Body:
I am configuring my postgresql driver in Laravel 5.4 for deployment to Heroku. Here is my config/database.php, the default is already set to pgsql

'pgsql' => [
        'driver' => 'pgsql',
        'host' => parse_url(getenv("DATABASE_URL"))['host'],
        'database' => substr(parse_url(getenv("DATABASE_URL"))['path'], 1),
        'username' => parse_url(getenv("DATABASE_URL")['username']),
        'password' => parse_url(getenv("DATABASE_URL")['password']),
        'charset' => 'utf8',
        'prefix' => '',
        'schema' => 'public',
    ],

When I commit I see this warning

PHP Warning: Illegal string offset 'username' in app/config/database.php on line 62

When run heroku run php artisan serveI am getting an error

[Symfony\Component\Debug\Exception\FatalThrowableError]
Type error: PDO::__construct() expects parameter 2 to be string, array given

Here is my .env

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=forge
DB_USERNAME=postgres
DB_PASSWORD=


问:
Open Camera Instantly when view appears
I have a requirement in my app in which I need to open a camera instantly.
But when I come to that ViewController opening camera is taking time for few seconds. Can any one help me.
I have tried with queues blocks but this doesn't work.
This is the code i have tried so far :==</p>

```<code>    - (void)viewDidLoad {

            [super viewDidLoad];
            [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
                [self onClickCamera:nil];

                //Your code goes in here
                NSLog(@"Main Thread Code");

            }];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self onClickCamera:nil];
//    });

//    dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
//    dispatch_async(queue, ^{
//        [self onClickCamera:nil];
//
//        // Do some computation here.
//
//        // Update UI after computation.
//        dispatch_async(dispatch_get_main_queue(), ^{
//            // Update the UI on the main thread.
//        });
//    });

    }

        - (IBAction)onClickCamera:(id)sender
        {
            NSLog(@"CALeed");
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = NO;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:NULL];
        }
</code>```

答:
Two issues :

Issue 1:

In viewDidLoad view has not yet finished rendering its layout yet. So trying to present something over a view which is still rendering, will obviously add the delay. Presenting camera will be triggered only after view finishes laying out its layout.

So move the code from viewDidLoad to viewDidAppear

```<code> - (void) viewDidAppear {
     [super viewDidAppear];
     [self onClickCamera:nil];
 }
</code>```

Issue 2:

More of a warning then error.

why even [NSOperationQueue mainQueue] addOperationWithBlock: ?? ViewDidLoad always gets called on main thread only which is associated with serialized main queue itself. The un-necessary context switching makes no much sense

Title: Open Camera Instantly when view appears

Body:
I have a requirement in my app in which I need to open a camera instantly.
But when I come to that ViewController opening camera is taking time for few seconds. Can any one help me.
I have tried with queues blocks but this doesn't work.
This is the code i have tried so far :==

    - (void)viewDidLoad {

            [super viewDidLoad];
            [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
                [self onClickCamera:nil];

                //Your code goes in here
                NSLog(@"Main Thread Code");

            }];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self onClickCamera:nil];
//    });

//    dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
//    dispatch_async(queue, ^{
//        [self onClickCamera:nil];
//
//        // Do some computation here.
//
//        // Update UI after computation.
//        dispatch_async(dispatch_get_main_queue(), ^{
//            // Update the UI on the main thread.
//        });
//    });

    }

        - (IBAction)onClickCamera:(id)sender
        {
            NSLog(@"CALeed");
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = NO;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:NULL];
        }

Body:
Two issues :

Issue 1:

In viewDidLoad view has not yet finished rendering its layout yet. So trying to present something over a view which is still rendering, will obviously add the delay. Presenting camera will be triggered only after view finishes laying out its layout.

So move the code from viewDidLoad to viewDidAppear

 - (void) viewDidAppear {
     [super viewDidAppear];
     [self onClickCamera:nil];
 }

Issue 2:

More of a warning then error.

why even [NSOperationQueue mainQueue] addOperationWithBlock: ?? ViewDidLoad always gets called on main thread only which is associated with serialized main queue itself. The un-necessary context switching makes no much sense


问:
How to trim whitespace in formula that is looks at data from a column
I have this formula

=B46+C46-D46-SUMIFS($G$2:$G$42, $A$2:$A$42, A46, $D$2:$D$42,"?uction*", $F$2:$F$42,"n")-SUMIFS($G$2:$G$42, $A$2:$A$42, A46, $D$2:$D$42,"Attorney")

I would like to be sure that any white space is removed from column D before it is compared to the string "Attorney". Could someone show me how to update this formula?

Body:
Not tested but see if this works

=B46+C46-D46-SUMIFS($G$2:$G$42, $A$2:$A$42, A46, $D$2:$D$42,"?uction*", $F$2:$F$42,"n")-SUMIFS($G$2:$G$42, $A$2:$A$42, A46, Arrayformula(trim($D$2:$D$42)),"Attorney")


问:
How to read Plist file from server and directly use it without creating local file?
I'm working on a project and I have some setting on the server which I got through the Plist file and I want to read this Plist file without creating any local copy.

Need to store this setting in the dictionary, not in the local Plist file.

any idea how can we do this?

Sample Plist like below:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>New item</key>
    <array>
        <dict>
            <key>value</key>
            <string>Data1</string>
            <key>key</key>
            <string>Tab1</string>
        </dict>
        <dict>
            <key>value</key>
            <string>Data2</string>
            <key>key</key>
            <string>Tab2</string>
        </dict>
    </array>
</dict>
</plist>
</code>```

Let me know if required more detail on this.

Thanks in advance!

答:
You need to use NSPropertyListSerialization class to parse your Data from response to Dictionary.

```<code>let url:URL = URL(string: "")! // URL to fetch plist

let urlSession:URLSession = URLSession(configuration: URLSessionConfiguration.default)

urlSession.dataTask(with: url) { (data:Data?, response:URLResponse?, error:Error?) in

guard let data = data else {
    return
}

let plistDict = try? PropertyListSerialization.propertyList(from: data, options:.mutableContainers, format: nil)

guard let dict = plistDict else {
    print("Error in parsing")
    return
}

print(dict)

}.resume()
</code>```

Body:
I'm working on a project and I have some setting on the server which I got through the Plist file and I want to read this Plist file without creating any local copy.

Need to store this setting in the dictionary, not in the local Plist file.

any idea how can we do this?

Sample Plist like below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>New item</key>
    <array>
        <dict>
            <key>value</key>
            <string>Data1</string>
            <key>key</key>
            <string>Tab1</string>
        </dict>
        <dict>
            <key>value</key>
            <string>Data2</string>
            <key>key</key>
            <string>Tab2</string>
        </dict>
    </array>
</dict>
</plist>

Let me know if required more detail on this.

Thanks in advance!

Body:
You need to use NSPropertyListSerialization class to parse your Data from response to Dictionary.

let url:URL = URL(string: "")! // URL to fetch plist

let urlSession:URLSession = URLSession(configuration: URLSessionConfiguration.default)

urlSession.dataTask(with: url) { (data:Data?, response:URLResponse?, error:Error?) in

guard let data = data else {
    return
}

let plistDict = try? PropertyListSerialization.propertyList(from: data, options:.mutableContainers, format: nil)

guard let dict = plistDict else {
    print("Error in parsing")
    return
}

print(dict)

}.resume()


问:
Unable to send AWS email using my sender id
I am sending AWS email using SNS. It's working fine but the only thing i am unable to find anywhere is how to replace the no-reply@sns.amazonaws.com via amazonses.com  id with my own email id..

I had used:

```<code>$result = $client->publish(array(
    'TopicArn' => $topicArn,
    'Message' => 'testing...',
    'Subject' => 'Test Msg',
    'DisplayName'=>'abc@gmail.com'
));
</code>```

I have used many other options also but every time it sends email through no-reply@sns.amazonaws.com

答:
Set attribute DisplayName in setTopicAttributes.

```<code>$result = $client->setTopicAttributes(array(
    // TopicArn is required
    'TopicArn' => 'string',
    // AttributeName is required
    'AttributeName' => 'DisplayName',
    'AttributeValue' => 'abc@gmail.com',
));
</code>```

Parameters explanation

```<code>AttributeName => (string)
The name of the attribute you want to set. Only a subset of the topic's attributes are mutable.
Valid values: Policy | DisplayName | DeliveryPolicy

AttributeValue => (string)
The new value for the attribute.
</code>```

Body:
I am sending AWS email using SNS. It's working fine but the only thing i am unable to find anywhere is how to replace the no-reply@sns.amazonaws.com via amazonses.com  id with my own email id..

I had used:

$result = $client->publish(array(
    'TopicArn' => $topicArn,
    'Message' => 'testing...',
    'Subject' => 'Test Msg',
    'DisplayName'=>'abc@gmail.com'
));

I have used many other options also but every time it sends email through no-reply@sns.amazonaws.com

Body:
Set attribute DisplayName in setTopicAttributes.

$result = $client->setTopicAttributes(array(
    // TopicArn is required
    'TopicArn' => 'string',
    // AttributeName is required
    'AttributeName' => 'DisplayName',
    'AttributeValue' => 'abc@gmail.com',
));

Parameters explanation

AttributeName => (string)
The name of the attribute you want to set. Only a subset of the topic's attributes are mutable.
Valid values: Policy | DisplayName | DeliveryPolicy

AttributeValue => (string)
The new value for the attribute.


问:
Is there any iOS app size inspection tool?
I am working with an iOS app which uses both objective-c and swift code. Currently app IPA size became large. Some resources are included but may not be used in Release IPA. I want to find out which resource should be removed and which resource are making my app size increased unnecessarily. I wonder if there is any such tool or xcode profiler to analyze.</p>

答:
So far the best tool I found is https://github.com/tinymind/LSUnusedResources

LSUnusedResources

A Mac App to find unused images and resources in an XCode project. It is heavily influenced by jeffhodnett‘s Unused, but Unused is very slow, and the results are not entirely correct. So It made some performance optimization, the search speed is more faster than Unused.

Export unused resource list

Use this tool and export unused/unreferenced resource list into unused.txt

Remove references from Xcode .pbxproj file

Use the below python script to delete references from project.pbxproj file:

    file = open("unused.txt","r")
    data = [line.rstrip('\n') for line in open("project.pbxproj", 'r')]
    newFile = open("project2.pbxproj","w")

    def removeLine(imageName):
            temp = data
            for line_s in temp:
                    if line_s.find(imageName) != -1:
                            data.remove(line_s)
                    else:
                            continue

    for line in file:
            if (len(line) > 5):
                    tokens = line.split("/")
                    len_a = len(tokens)
                    imageName =  tokens[len_a-1]
                    removeLine(imageName.rstrip('\n'))

    for line in data:
            newFile.write(line)
            newFile.write('\n')
```
<p>And an alternative script, in bash:</p>
<pre class="lang-sh prettyprint-override"><code>    #!/bin/bash

    UNUSED_ASSETS_FILENAME="unused-images.txt"
    XCODEPROJ_PATH="zilly.xcodeproj/project.pbxproj"

    while read LINE; do
      FILENAME="$(basename "$LINE")"
      if [[ $FILENAME =~ (png|jpeg|jpg|gif)$ ]]; then
        echo "Removing '$FILENAME' references from $XCODEPROJ_PATH"
        sed -i '' "/$FILENAME/d" $XCODEPROJ_PATH
      fi
    done < $UNUSED_ASSETS_FILENAME
</code>```

Body:
So far the best tool I found is https://github.com/tinymind/LSUnusedResources

LSUnusedResources

A Mac App to find unused images and resources in an XCode project. It is heavily influenced by jeffhodnett‘s Unused, but Unused is very slow, and the results are not entirely correct. So It made some performance optimization, the search speed is more faster than Unused.

Export unused resource list

Use this tool and export unused/unreferenced resource list into unused.txt

Remove references from Xcode .pbxproj file

Use the below python script to delete references from project.pbxproj file:

    file = open("unused.txt","r")
    data = [line.rstrip('\n') for line in open("project.pbxproj", 'r')]
    newFile = open("project2.pbxproj","w")

    def removeLine(imageName):
            temp = data
            for line_s in temp:
                    if line_s.find(imageName) != -1:
                            data.remove(line_s)
                    else:
                            continue

    for line in file:
            if (len(line) > 5):
                    tokens = line.split("/")
                    len_a = len(tokens)
                    imageName =  tokens[len_a-1]
                    removeLine(imageName.rstrip('\n'))

    for line in data:
            newFile.write(line)
            newFile.write('\n')

And an alternative script, in bash:

    #!/bin/bash

    UNUSED_ASSETS_FILENAME="unused-images.txt"
    XCODEPROJ_PATH="zilly.xcodeproj/project.pbxproj"

    while read LINE; do
      FILENAME="$(basename "$LINE")"
      if [[ $FILENAME =~ (png|jpeg|jpg|gif)$ ]]; then
        echo "Removing '$FILENAME' references from $XCODEPROJ_PATH"
        sed -i '' "/$FILENAME/d" $XCODEPROJ_PATH
      fi
    done < $UNUSED_ASSETS_FILENAME


问:
Php in cmd unable to load ALL dinamic libraries
When i use php in cmd Windows console i got the following error:

C:\wamp64\bin\php\php5.6.25>php
      PHP Warning:  PHP Startup: Unable to load dynamic library 'c:/wamp/bin/php/php5.6.25/ext/php_bz2.dll' - No se puede encontrar el m¾dulo especificado.
       in Unknown on line 0
     [...]

And continues whit ALL the dll libraries. I Chek the rute and its ok. And when my wamp start a page whit php i dont get this error

For example i got the error when i type:

```<code>cd C:\wamp64\www\ServicioApp\scripts
php script_notificaciones.php
</code>```

I run php --ini and search in the file, and i got:

```<code>extension_dir ="c:/wamp/bin/php/php5.6.25/ext/"
</code>```

答:
I found the problem my rute was:

```<code>c:/wamp/bin/php/php5.6.25/ext/
</code>```

And must be:

```<code>c:/wamp64/bin/php/php5.6.25/ext/
</code>```

I miss the 64*

Body:
When i use php in cmd Windows console i got the following error:

C:\wamp64\bin\php\php5.6.25>php
      PHP Warning:  PHP Startup: Unable to load dynamic library 'c:/wamp/bin/php/php5.6.25/ext/php_bz2.dll' - No se puede encontrar el m¾dulo especificado.
       in Unknown on line 0
     [...]

And continues whit ALL the dll libraries. I Chek the rute and its ok. And when my wamp start a page whit php i dont get this error

For example i got the error when i type:

cd C:\wamp64\www\ServicioApp\scripts
php script_notificaciones.php

I run php --ini and search in the file, and i got:

extension_dir ="c:/wamp/bin/php/php5.6.25/ext/"

Body:
I found the problem my rute was:

c:/wamp/bin/php/php5.6.25/ext/

And must be:

c:/wamp64/bin/php/php5.6.25/ext/

I miss the 64*


问:
Resolve conflicting package name in Flash Builder
I am using Flash Builder 4 and need a VideoDisplay component that works with Cue Points.  The newer version of theOSMF classes that Flex's VideoDisplay are based on handles this already.  The idea is to roll my own VideoDisplay component rather than monkey patch the existing one.  To do this, I have created a project with the newer version of the OSMF classes, and another project with which I would build the new VideoDisplay, in a separate package name.

The issue is that since the Flex 4.1 SDK contains the majority of the OSMF classes with their original package names, a statement such as import org.osmf.media.MediaPlayer; references the class located at

C:\Program Files\Adobe\Adobe Flash
  Builder
  4\sdks\4.1.0\frameworks\projects

and not the MediaPlayer class in the newer version of OSMF.

I've tried to rename the packages in the OSMF project so that it is distinctly named, but I get an exception from the IDE (an unexpected exception occurred during precondition checking.  See the error log for more details).

Does the SDK always (rightfully?) win in a fight?  Is there some (dirty?) way to force a project to prefer a reference to an swc/project over an identically named SDK class?

Any suggestions welcome.

Edit: Given the comments, I've apparently done a poor job of explaining my problem.  So here it goes again.

Flex uses an older, less capable version of the OSMF platform for its VideoPlayer. I need to use the new version that includes support for cue points.  I have downloaded the newer OSMF source and it is in its own project.  I would prefer to NOT have to rename the packages in this project for the sake of future maintainability.

The VideoPlayer I will implement is in a second project that DOES NOT duplicate the package names of either the Flex SDK or OSMF.  The conflict is between the Flex SDK and OSMF, not between the classes I would build and either OSFM or the SDK.  My project needs  to access classes in the OSMF project, not those from the Flex SDK that have the name package/class names.  Because the Flex SDK is based on OSMF, Flex has left the package and namespace identifies intact, thus the naming ambiguity.

答: Remove OSMF from the Flex 4.1 SDK in "Flex Build Path".</p>


问:
What is the best way to get content of a div as an image without loosing the quality
I have a DIV who's size may vary depending on the size of the window.
What I'm trying to get is the image version of div (as if the user took a screenshot of that div) but always in 1280x720 resolution.

One option I'm trying is to dump DIV content in canvas using html2canvas library but when I scale it up, I lose the image quality. Is there any alternative for that?

Body:
<img src="path/filename.extension" style="min-width:100%;" />

this will fit image in parent div (whatever size it gets).


问:
CocoaPods test target Library not loaded exit code 82
This appears to be an issue with CocoaPods, asking here first as per the guidelines.

Using Xcode 7.3.1, CocoaPods 1.0.1, 1.0.0-beta6 and 1.1.0-beta1

Create a new pod project using pod lib create SwiftTest

Language? Swift

Demo? Yes

Test frameworks? None

View based testing? No

Add a single class function to the auto-generated ReplaceMe.swift file to test the projects integration.

Calling the function from the example project works as expected.

Calling the function from the test project fails with the following error:

```<code>The bundle “SwiftTest_Tests” couldn’t be loaded because it is damaged or missing necessary resources. Try reinstalling the bundle.
(dlopen_preflight(/...): Library not loaded: @rpath/SwiftTest.framework/SwiftTest ... Reason: image not found)
Program ended with exit code: 82
</code>```

Example project: https://github.com/NextFaze/SwiftTest

答:
I was developing a CocoaPod and had to change its name in Xcode 8 (rumours say, that there is going to be a better renaming refactor functionality in Xcode 9).
(This caused so many troubles BTW!!)

After I fixed all the renaming issues, I wanted my tests to run as well, but that error occurred. All I had to do is to set up the Host Application:

In Targets > Select the test target > General > you will find the Host Application under Testing. Mine was empty/grayed-out due to this renaming issue. I selected my host application and that's it!

Body:
This appears to be an issue with CocoaPods, asking here first as per the guidelines.

Using Xcode 7.3.1, CocoaPods 1.0.1, 1.0.0-beta6 and 1.1.0-beta1

Create a new pod project using pod lib create SwiftTest

Language? Swift

Demo? Yes

Test frameworks? None

View based testing? No

Add a single class function to the auto-generated ReplaceMe.swift file to test the projects integration.

Calling the function from the example project works as expected.

Calling the function from the test project fails with the following error:

The bundle “SwiftTest_Tests” couldn’t be loaded because it is damaged or missing necessary resources. Try reinstalling the bundle.
(dlopen_preflight(/...): Library not loaded: @rpath/SwiftTest.framework/SwiftTest ... Reason: image not found)
Program ended with exit code: 82

Example project: https://github.com/NextFaze/SwiftTest


问:
Run python interpreter using python code, with local variables
Many a times we get an error in some user defined function and want to debug it. If the error had happened in the main program, we can use the -i flag to preserve variables after the error. But if the error happens in a user defined function, there is no way we can access the local variables of the function. Is there a way where we can open python interpreter through python code, accept code from stdin and print output to stdout. Something like this:-

```<code>def foo():
  x = 'Inside foo()'
  run_interpreter() # Pauses for input

foo()
</code>```

We should be able to give following input through stdin:-

```<code>print(x) # prints 'Inside foo()'
exit()   # exits interpreter and resumes other code
</code>```

答:
I found an easy way to do this. I don't know if there is a better way:-

```<code>import sys
def interpreter(vars):
    s = sys.stdin.readline().strip('\n')
    while s!= 'exit()':
        exec(s, globals(), vars)
        s = sys.stdin.readline().strip('\n')
</code>```

I am using sys.stdin to read, for statements with space to be parsed properly. However, this does not provide all functionalities of interpreter. We cannot browse history using arrow keys.

This is very useful in debugging. Whenever I get an error, I call interpreter(locals()) before that line to investigate the cause. I saved it as a sublime snippet so that it can be easily added to any python code.

Body:
Many a times we get an error in some user defined function and want to debug it. If the error had happened in the main program, we can use the -i flag to preserve variables after the error. But if the error happens in a user defined function, there is no way we can access the local variables of the function. Is there a way where we can open python interpreter through python code, accept code from stdin and print output to stdout. Something like this:-

def foo():
  x = 'Inside foo()'
  run_interpreter() # Pauses for input

foo()

We should be able to give following input through stdin:-

print(x) # prints 'Inside foo()'
exit()   # exits interpreter and resumes other code

Body:
I found an easy way to do this. I don't know if there is a better way:-

import sys
def interpreter(vars):
    s = sys.stdin.readline().strip('\n')
    while s!= 'exit()':
        exec(s, globals(), vars)
        s = sys.stdin.readline().strip('\n')

I am using sys.stdin to read, for statements with space to be parsed properly. However, this does not provide all functionalities of interpreter. We cannot browse history using arrow keys.

This is very useful in debugging. Whenever I get an error, I call interpreter(locals()) before that line to investigate the cause. I saved it as a sublime snippet so that it can be easily added to any python code.


问:
batch file to copy share drive folder to local windows D drive
Hi I am trying to copy folder from network drive to local window D drive using bath job but its not copying the files

```<code>echo off
cls

echo Would you like to do a backup?

pause

copy "S:\2017\*" "D:\TEST_BACKUP_FOLDER"

pause
</code>```

i have mapped my network drive as S drive i am getting below message.

```<code>Would you like to do a backup?
Press any key to continue . . .
S:\2017\*
The system cannot find the file specified.
        0 file(s) copied.
Press any key to continue . . .
</code>```

答:
I would recommend you to use xcopy instead, and include sub directories by adding '/s' option. You can always get help by 'copy /?' or 'xcopy /?'.

```<code>    echo off
    cls

    echo Would you like to do a backup?

    pause

    xcopy "S:\2017\*" "D:\TEST_BACKUP_FOLDER\" /s

    pause
</code>```

Body:
Hi I am trying to copy folder from network drive to local window D drive using bath job but its not copying the files

echo off
cls

echo Would you like to do a backup?

pause

copy "S:\2017\*" "D:\TEST_BACKUP_FOLDER"

pause

i have mapped my network drive as S drive i am getting below message.

Would you like to do a backup?
Press any key to continue . . .
S:\2017\*
The system cannot find the file specified.
        0 file(s) copied.
Press any key to continue . . .

Body:
I would recommend you to use xcopy instead, and include sub directories by adding '/s' option. You can always get help by 'copy /?' or 'xcopy /?'.

    echo off
    cls

    echo Would you like to do a backup?

    pause

    xcopy "S:\2017\*" "D:\TEST_BACKUP_FOLDER\" /s

    pause


问:
React Bootstrap button looking faded
I used the

```<code><Button bsStyle="primary" bsSize="large">Primary</Button>
</code>```

Unlike the question here React-bootstrap button bsStyle , I have included the bootstrap css in the root html page.

I am unable to figure the issue.

Here is my code

Index.ejs
Css file :

Component.jsx:

```<code>import {Button, Col, Glyphicon, Label, OverlayTrigger, Row, Table, Tooltip} from "react-bootstrap";

<Button href={version.downloadUri} bsStyle="primary" bsSize="large">
</code>```

Primary button

Main issue:
I do see the button and I also think that the css is being applied cause when I hover over the button, it looks normal. The button on the other hand in its natural state looks faded.

答:
Herewith attaching screenshot of button. It is behaving as normal as it gets. Probably you are messing something in css. However I used react-bootstrap and here what I got:

Could you post your button's screenshot ?

Title: React Bootstrap button looking faded

Body:
I used the

<Button bsStyle="primary" bsSize="large">Primary</Button>

Unlike the question here React-bootstrap button bsStyle , I have included the bootstrap css in the root html page.

I am unable to figure the issue.

Here is my code

Index.ejs
Css file :

Component.jsx:

import {Button, Col, Glyphicon, Label, OverlayTrigger, Row, Table, Tooltip} from "react-bootstrap";

<Button href={version.downloadUri} bsStyle="primary" bsSize="large">

Primary button

Main issue:
I do see the button and I also think that the css is being applied cause when I hover over the button, it looks normal. The button on the other hand in its natural state looks faded.


问:
Why does this code return a list index error?
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:

```<code>if result[i][0] < 0 or result[i][0] >= board.dimensions:
    result.pop(i)
</code>```

when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?

```<code>def neighborGen(row,col,board):
    """
    returns lists of coords of neighbors, in order of up, down, left, right
    """

    result = []
    result.append([row-1 , col])
    result.append([row+1 , col])
    result.append([row , col-1])
    result.append([row , col+1])

     #prune off invalid neighbors (such as (0,-1), etc etc)
     for i in range(len(result)):
        if result[i][0] < 0 or result[i][0] >= board.dimensions:
            result.pop(i)
        if result[i][1] < 0 or result[i][1] >= board.dimensions:
            result.pop(i)

    return result
</code>```

答:
You get the indexes to iterate over from the list, and then you proceed to remove elements from the list. Eventually you're going to hit an index that no longer exists. Use a list comprehension to filter instead.</p>

```<code>result = [entry for entry in result if entry[0] >= 0 and
  entry[0] < board.dimensions and entry[1] >= 0 and
  entry[1] < board.dimensions]
</code>```

Body:
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:

if result[i][0] < 0 or result[i][0] >= board.dimensions:
    result.pop(i)

when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?

def neighborGen(row,col,board):
    """
    returns lists of coords of neighbors, in order of up, down, left, right
    """

    result = []
    result.append([row-1 , col])
    result.append([row+1 , col])
    result.append([row , col-1])
    result.append([row , col+1])

     #prune off invalid neighbors (such as (0,-1), etc etc)
     for i in range(len(result)):
        if result[i][0] < 0 or result[i][0] >= board.dimensions:
            result.pop(i)
        if result[i][1] < 0 or result[i][1] >= board.dimensions:
            result.pop(i)

    return result

Body:
You get the indexes to iterate over from the list, and then you proceed to remove elements from the list. Eventually you're going to hit an index that no longer exists. Use a list comprehension to filter instead.

result = [entry for entry in result if entry[0] >= 0 and
  entry[0] < board.dimensions and entry[1] >= 0 and
  entry[1] < board.dimensions]