text:
Q: Load file from external storage using chooser So, I'm trying to load a simple .txt file like this:
    private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("text/plain");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }
}

And of course, catching the result like this:
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
            if (resultCode == RESULT_OK) {

                // Get the Uri of the selected file
                Uri uri = data.getData();

It works great on genymotion and on my device if I use a file explorer that I have installed (File explorer, see image abovew), now, If use the chooser directly like this:

It says it cannot find the specified file. (FileNotFoundException)
Now, I've realized that the URIs I get from these two file choosers are different

content://com.android.externalstorage.documents/document/primary%3ADownload%2Ffile.txt <- THIS DOESNT WORK (android built in explorer)
content://media/external/file/44751 <- THIS WORKS (custom explorer)

Does anyone have any idea why I'm getting different URIs for the SAME file.
EDIT:
I tried to use a content resolver to get the file path from the URI like this:
public class Utils {

public static String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Files.FileColumns.DATA};
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(proj[0]);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

}
Still no luck :(

A: @CommonsWare's asnwer must be the right way of solving this, but I'm not sure how to implement his solution.
I've ended up doing what @Paul Burke recomends on this link:
Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT
EDIT
For my particular case, this is how my code ended up. I leave this here for future reference. (I'm using @CommonsWare's explanation) see his answer above.
               try {
                    InputStream inputStream = getContentResolver().openInputStream(uri);
                    BufferedReader br = null;
                    if (inputStream != null) {
                        br = new BufferedReader(new InputStreamReader(inputStream));

                        String line;
                        while ((line = br.readLine()) != null) {
                            text.append(line);
                            text.append("\n");
                        }
                    } else {
                        subscriber.onError(new InputException("There's something seriously wrong with this file"));
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    subscriber.onError(e);
                }

A:
I tried to use a content resolver to get the file path from the URI like this

There is no file path. A Uri does not necessarily point to a file that you can access on your local filesystem, just as the URL to this Web page does not necessarily point to a file that you can access on your local filesystem. The Uri might:

*

*represent a file held in internal storage of the other app

*represent a BLOB column value in a database

*represent a file held in "the cloud", to be downloaded when requested

*etc.

Use a ContentResolver and methods like openInputStream() to read in the content represented by the Uri, just like you would use HttpUrlConnection to read in the content represented by the URL for this Web page. openInputStream() takes the Uri as a parameter and returns an InputStream. You would use that InputStream the same way you would any other InputStream (e.g., FileInputStream, InputStream from HttpUrlConnection). The exact mechanics of that will depend a lot on the underlying data (e.g., read in a string, pass to BitmapFactory to decode a Bitmap).


text:
Q: how to compare two xml files and point out its difference in another file using perl file1.xml
<Car>
<Name> Taurus </Name>
<Color> White </Color>
</Car>
file2.xml
<Car>
<Color> grey </Color>
<Name> Taurus </Name>
</Car>
I am unable to distinguish and output the differences between both.plz help me out.

A: you can use XML::SemanticDiff - Perl extension for comparing XML documents.
XML::SematicDiff provides a way to compare the contents and structure of two XML documents. By default, it returns a list of hashrefs where each hashref describes a single difference between the two docs.
read in detail here
http://metacpan.org/pod/XML::SemanticDiff

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSRF verification failed. Request aborted. {% csrf_token %} in django python3 html I am trying to do a log in in django/python.
I have this in my views.py:
@csrf_exempt
def Principal(request):
    context = {}
    if request.method != 'GET':
        context = {
            'title': '405 Method Not Allowed',
        }

    if request.user.is_authenticated():
        logged_q = 'Logged in as '+ request.user.username
        logged = True
    else:
        logged_q = 'Not logged in.'
        logged = False

    print (logged_q)

    top_aparcamientos = Aparcamiento.objects.all()
    #top_aparcamientos = Comentario.objects.all().order_by('-aparcamiento__id').unique()[:5]
    pagina_list = Pagina.objects.all()

    context['top_aparcamientos'] = top_aparcamientos
    context['pagina_list'] = pagina_list
    usuario = request.user.username
    context = {
      'usuario' : usuario,
      'logged' : logged
    }

    return render_to_response('index.html', context

So, for do my template, I take the variable logged in my base.html like that:
{% if logged %}

            Bienvenido,&nbsp{{usuario}}
            <button id="logged"type="submit">Salir</button>

 {% else %}
    <form id="login_form" action="login/" method ="POST">
        {% csrf_token %}
        Nick:  <input id="id_username" maxlength="254" name="username" type="text" />
        Contraseña:  <input id="id_password" name="password" type="password" />
        <button type="submit">Login</button>
    </form> {% endif %}

But it gives me this error when I try to log in:
Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect.

Do I need anymore {% csrf_token %}? Where?
Thank you!

A: Instead of  {% csrf_token %}, you can probably use
<input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' />

Or you can also use {{ csrf_input }}.
<form action="login/" method="post">{{ csrf_input }}


text:
Q: Is it possible to order multiple columns by using the `ORDER BY FIELD` statement? I am using Ruby on Rails 3.2.2 and I would like to know if it is possible to order multiple columns/fields by using the ORDER BY FIELD statement (for example, as made in the Model.order("orders_count, created_at, name, ...") but for ORDER BY FIELD).
If so, how can I "ORDER BY FIELDS"?
P.S.: As written in a previous answer, in order to order my records relating to one column I am using the Model.order("field(status, 'blocked', 'unpublished', 'published')") statement.


text:
Q: Are there materials that would mimic cellular membranes at temperatures as high as 460°C? A typical mammal cell has a double lipid layer membrane that is hydrophobic on the inside. This is the way cells separate their internal milieu from the external milieu, allowing differences in ion and other solutes concentrations. So even in non-aquatic animals, cells have water inside and outside most of their cells, including neurons for example.
Water having to be liquid to act as a solvent for biological processes, this limits the temperatures allowed for a normal cell to survive especially in the upper range.
Living cells on Earth typically withstand a range of temperatures that is rather narrow in comparison with the variety of temperatures found in the solar system, let alone the entire universe.
Venus surface has a mean (in every sense of the word) surface temperature of about 460°C. This higher temperature and other things prevent Earth organic life from surviving in this environment without special protection, and even machines sent there like the Russian Venera missions, could not survive longer than an hour or two on the surface.
So I am wondering what would it take to create a biology made of other materials yet working on similar principles.
Since the cellular wall is undeniably a critical feature of all life on our planet, I am starting with it instead of, say, DNA.
Basically, water should be substituted with another solvent since it vaporizes at 100°C. I guess this is not impossible to have a solvent liquid at 460°C. At least some materials are liquid at this temperature, but would they have solvent properties is less certain.
Then comes the membrane. Given a solvent withstanding Venus surface temperature, are there materials that would produce something similar to hydrophobia with it? Does the solvent need to be polar?
I look for similar results, not necessarily the same physics.
For those not familiar with biology, a cell membrane is not a static object. Lipids are mostly free to move around the membrane. So this is like a liquid layer sandwiched between two other liquid layers. However,  the thickness of the membrane can be made constant because molecules that form each layer have some sort of legs attracting the legs of the opposite layer, so those molecules move laterally but not in other directions and this way there are always two layers only.
Sidenotes: having found a solvent and a way to make a cell membrane does not even start to build life, obviously. So this question is limited to the feasibility of artificial vesicles (little biological bubble filled with stuff), not entire cells, withstanding 460°C. Also, this is not about judging if life could have emerged on Venus, because I do not ask for a solvent or materials that are naturally found on Venus.


text:
Q: How to extend CountDown Timer With Pause? This seems to be a common question, "how do I pause a countdowntimer"?
I found this code which looks promising:
http://www.java2s.com/Open-Source/Android/Timer/multitimer-android/com/cycleindex/multitimer/CountDownTimerWithPause.java.htm
I'm just not sure how to implement it in code.  I need to override the abstracted methods and extend the class.  Can someone give me an idea how to do this?

A: Here is your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >
    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="0"
            android:gravity="center_horizontal"
            android:layout_marginBottom="40dp"
            android:layout_marginTop="20dp"
            android:textSize="27dp"
            android:id="@+id/txtView"/>
    <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_gravity="center">
        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Start"
                android:id="@+id/startButton"/>
        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Stop"
                android:id="@+id/stopButton"
                android:layout_toRightOf="@id/startButton"/>
    </RelativeLayout>
</LinearLayout>

Here is your activity class
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MyActivity extends Activity implements View.OnClickListener {

    TextView txt = null;
    Button startButton = null;
    Button stopButton = null;
    CountDownTimerWithPause timer = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        txt = (TextView) findViewById(R.id.txtView);
        startButton = (Button) findViewById(R.id.startButton);
        stopButton = (Button) findViewById(R.id.stopButton);

        startButton.setOnClickListener(this);
        stopButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view == startButton) {
            if (timer == null) {
                initTimer();
            }

            timer.resume();
        }

        if (view == stopButton) {
            timer.pause();
        }
    }

    private void initTimer() {
        timer = new CountDownTimerWithPause(10000, 1000, false) {
            @Override
            public void onTick(long millisUntilFinished) {
                Integer currentValue = Integer.valueOf((String) MyActivity.this.txt.getText());
                MyActivity.this.txt.setText(String.valueOf(currentValue + 1));
            }

            @Override
            public void onFinish() {
                Toast.makeText(MyActivity.this, "finish", Toast.LENGTH_SHORT).show();
            }
        };

        timer.create();
    }
}

Do not forget to copy CountDownTimerWithPause into your package.
Works for me, BUT...
I mention some bugs but it depends on your application. Maybe it's OK for you. Bug is - when starting timer, it fires immediatelly. 'So what?' you might ask. Imagine you click Stop button when 3 and half seconds passed. So when you click Start button you expect half second pass before you see 4, but not in that class implementation.
And there is some strange delay at the end of counting. I'd recommend to search for better implementation.

A: I have used CountDownTimerWithPause in my projects and it is pretty simple.
Take a look on this sample code I just wrote to explain the implementation of this counter.
Step 1
I have created sample XML layout just for better explanation later. This layout contains 3 buttons:

*

*Start

*Pause

*Resume

The layout:
<Button
    android:id="@+id/button_start"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start" />

<Button
    android:id="@+id/button_pause"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Pause" />

<Button
    android:id="@+id/button_resume"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Resume" />

Step 2
Just for this example I worked within an Activity.
So this is the code:
public class MainActivity extends Activity
{

    private CountDownTimerWithPause _countDownTimerWithPause = null;

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

        /*
         * Definition of the counter
         */
        _countDownTimerWithPause = new CountDownTimerWithPause(10000, 1000, true)
        {

            @Override
            public void onTick(long millisUntilFinished)
            {
                Toast.makeText(getApplicationContext(), "Tick", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish()
            {
                Toast.makeText(getApplicationContext(), "Finished", Toast.LENGTH_SHORT).show();
            }
        };

        /*
         * Click to start the counter
         */
        Button buttonStart = (Button) findViewById(R.id.button_start);
        buttonStart.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                _countDownTimerWithPause.create();
            }
        });

        /*
         * Click to pause the counter
         */
        Button buttonPause = (Button) findViewById(R.id.button_pause);
        buttonPause.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                _countDownTimerWithPause.pause();
            }
        });

        /*
         * Click to resume the counter
         */
        Button buttonResume = (Button) findViewById(R.id.button_resume);
        buttonResume.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                _countDownTimerWithPause.resume();
            }
        });
    }

}

It is easy to see how I have extended the CountDownTimerWithPause and which methods should be called to start,pause and resume the counter.
Hope I could explain the usage of this counter.


text:
Q: Gridview Cell Value I have a Gridview that displays some data. What im trying to do is if the Command name is edit etc to take the appropriate action.
I managed to get the command name by doing an If statement under the RowCommand event for the datagridview which allowed me to take the appropriate action on each command.
The problem i have come across is im trying to get the SELECTED Rows value from a certain column depending on which command has been selected. So if a user clicked edit on row 15 then i would like to get row 15's col 5 value. If the user clicked row 10 then it would be row 10, col 5 etc.
How could i do this under the RowCommand event OR any other way to achieve the above?
Thanks

A: I just read this question, but if you still havent figured it out then what you can do it go to your aspx file and define "OnRowEditing" under gridview. Then go back to code behind file and do something like this:
 protected void gvEvents_Edit(object sender, GridViewEditEventArgs e)
    {

        //Set the edit index.
        gvEvents.EditIndex = e.NewEditIndex;
        DataTable dt = Session["dtEvents"] as DataTable;
        //Bind data to the GridView control.

        gvEvents.DataSource = Session["dtEvents"];
        gvEvents.DataBind();
    }

You also need to define OnRowUpdating and OnRowCancelingEdit and put code for them in your code behind.
This is whats gonna be under OnRowCancelingEdit
    protected void gvEvents_cancEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //Reset the edit index.
        gvEvents.EditIndex = -1;
        //Bind data to the GridView control.
        DataTable dt = Session["dtEvents"] as DataTable;

        gvEvents.DataSource = Session["dtEvents"];
        gvEvents.DataBind();

    }


text:
Q: Minimizing roots of a transcendental equations I'm trying to use the solution of FindRoot with parameters for further calculations. Annoyingly enough it always gives me trouble with replacing the parameters. As an example I'm attaching a simple example I've cooked, since the solution is obvious. First I've defined the function "root", which is the solution for the equation, and is obviously (x-1)^2
root[x_] := y /. FindRoot[y - (x - 1)^2, {y, 1}]

Next I've tried to minimize this function, which should obviously return x=1, but I get a string of errors:
FindMinimum[root[x], {x, 2}]

FindRoot::nlnum: The function value {1. -1. (-1.+x)^2} is not a list of numbers with dimensions {1} at {y} = {1.}. >>

ReplaceAll::reps: {FindRoot[y-(x-1)^2,{y,1}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>

FindRoot::nlnum: The function value {1. -1. (-1.+x)^2} is not a list of numbers with dimensions {1} at {y} = {1.}. >>

ReplaceAll::reps: {FindRoot[y-(x-1)^2,{y,1}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>

FindRoot::nlnum: The function value {1. -1. (-1.+x)^2} is not a list of numbers with dimensions {1} at {y} = {1.}. >>

General::stop: Further output of FindRoot::nlnum will be suppressed during this calculation. >>

ReplaceAll::reps: {FindRoot[y-1. (-1.+x)^2,{y,1.}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>

General::stop: Further output of ReplaceAll::reps will be suppressed during this calculation. >>

FindMinimum::lstol: The line search decreased the step size to within the tolerance specified by AccuracyGoal and PrecisionGoal but was unable to find a sufficient decrease in the function. You may need more than MachinePrecision digits of working precision to meet these tolerances. >>

Out[87]= {0., {x -> 1.}}

The result comes out right in the end, but obviously something isn't right.
Any ideas?


text:
Q: Applying CSS Class on Individual Items vs Parent Children I am making a simple menu using HTML and CSS. It looks like this:
.menu {
  display:table;
  height:39px;
  font-size:0.8em;
  color:white;
  width:100%;
  text-align: center;
  font-weight: inherit;
  background-color:rgba(213, 220, 228, 0.1);
}

.menu-item {
  display:table-cell;
  padding:12px;
}

Item 1

Item 2

Item 3

Although I do have a class for menu items called "menu-item" I was thinking what if I do this instead.
.menu div {
      display:table-cell;
      padding:12px;
}

When I apply class ".menu-item" to child divs they appear correctly horizontally spaced but when I use the ".menu div" approach they stack on each other. Why is that?

A: The approaches
Both approaches work. You might have mixed up something.
See .menu div approach:

.menu {
  display:table;
  height:39px;
  font-size:0.8em;
  width:100%;
  text-align: center;
  font-weight: inherit;
  background-color:rgba(213, 220, 228, 0.1);
}

.menu div {
  display:table-cell;
  padding:12px;
}

Item 1

Item 2

Item 3

See .menu-item approach:

.menu {
  display:table;
  height:39px;
  font-size:0.8em;
  width:100%;
  text-align: center;
  font-weight: inherit;
  background-color:rgba(213, 220, 228, 0.1);
}

.menu-item {
  display:table-cell;
  padding:12px;
}

Item 1

Item 2

Item 3

The problem
Make sure you are implementing it correclty: for .menu div it doesn't need the class="menu-item", while for the .menu-item it does need the class="menu-item" for its menu items.
It will only reproduce the way you described if you have used the .menu-item css approach but haven't placed the class="menu-item" to the menu items divs, hence the .menu-item styles won't be affected:

.menu {
  display:table;
  height:39px;
  font-size:0.8em;
  width:100%;
  text-align: center;
  font-weight: inherit;
  background-color:rgba(213, 220, 228, 0.1);
}

.menu-item {
  display:table-cell;
  padding:12px;
}

Item 1

Item 2

Item 3

Another possible problem
Maybe you're implementing the .menu-item correctly, but there are other css overwritting it, possibly due to a higher selector weight. Different browsers implement the weights differently, so you may notice that in this case the issue occurs just for a few browsers.
Example of competing styles:

.menu div {
  display:block;
  padding:12px;
}

.menu {
  display:table;
  height:39px;
  font-size:0.8em;
  width:100%;
  text-align: center;
  font-weight: inherit;
  background-color:rgba(213, 220, 228, 0.1);
}

.menu-item {
  display:table-cell;
  padding:12px;
}

Item 1

Item 2

Item 3

To resolve that type of issue you will have to (a.) remove the overwritting style, or, if it's not possible: (b.) put a higher weight to your controlled style, for example, by using .menu .menu-item selector instead of just .menu-item:

.menu div {
  display:block;
  padding:12px;
}

.menu {
  display:table;
  height:39px;
  font-size:0.8em;
  width:100%;
  text-align: center;
  font-weight: inherit;
  background-color:rgba(213, 220, 228, 0.1);
}

.menu .menu-item {
  display:table-cell;
  padding:12px;
}

Item 1

Item 2

Item 3

If that still really doesn't help, maybe you'll need to add extra weight to overwrite a competing style, by, for example, using an auxiliar id to help:

function addExtraWeight() {
  $("#extra-weight-removed").attr("id", "extra-weight");
}

function removeExtraWeight() {
  $("#extra-weight").attr("id", "extra-weight-removed");
}
body div.menu.menu.menu div {
  display:block;
  padding:12px;
}

.menu {
  display:table;
  height:39px;
  font-size:0.8em;
  width:100%;
  text-align: center;
  font-weight: inherit;
  background-color:rgba(213, 220, 228, 0.1);
}

.menu .menu-item {
  display:table-cell;
  padding:12px;
}

#extra-weight .menu-item {
  display:table-cell;
  padding:12px;
}

Item 1

Item 2

Item 3

<button onclick="addExtraWeight()">Add extra weight</button>
<button onclick="removeExtraWeight()">Remove extra weight</button>


text:
Q: ArrayBuffer to blob conversion I have a project where I need to display djvu schemas in browser.
I found this old library on Github which, as far as I understood, converts djvu files to bmp and then puts them into canvas element.
As I said, library is old(last commit was 5 years ago), so I need to make some corrections. Main problem is that lib uses obsolete BlobBuilder.
Steps I made to solve this problem:

*

*Decompress this library via Chrome DevTools

*Initial error is at line 3774 var c = "undefined" != typeof MozBlobBuilder ? MozBlobBuilder : "undefined" != typeof WebKitBlobBuilder ? WebKitBlobBuilder : console.log("warning: cannot build blobs")

*I commented out this line

*Next, I commented out line c = new c; and some of following lines too.

So, now it looks this way(variable I is array buffer, and ololo1 and ololo2 are some kind of offset and limit)
var c = new Blob(new Uint8Array(new Uint8Array(I,ololo1,ololo2)))
              , b = b.createObjectURL(c)
              , c = document.getElementById(kb)
              , f = c.getContext("2d")
              , h = new Image
              , g = a[Ea >> 2]
              , i = a[Fa >> 2]
              , j = c.width
              , k = Math.round(i * j / g);

            h.onload = function()
            {
                var a = g / j;
                4 < a && (a = 4);
                1 > a && (a = 1);
                f.globalAlpha = 1;

                for (N = 0; N < a; N++)
                    f.drawImage(h, N, N, g - a + N, i - a + N, 0, 0, j, k),
                    f.globalAlpha *= 1 - 1 / a;
                R(h.complete, "Image /bmp.bmp could not be decoded")
            }
            ;
            h.onerror = function(errorMsg, url, lineNumber, column, errorObj) {
                console.log(errorMsg, url, lineNumber, column, errorObj);
                console.log("Image /bmp.bmp could not be decoded!")
            }
            ;

And now I stuck at error "Image /bmp.bmp could not be decoded!"(throwed in h.onerror handler).
So, my question is: what I am doing wrong?

A: var buffer = new ArrayBuffer(32);

new Blob([buffer]);

so the Uint8Array should be
new Blob([new Uint8Array([1, 2, 3, 4]).buffer]);

A: I don't know why the author did wrap his Uint8Array in an new one... note that I don't really know either the deprecated BlobBuilder API, but one typo I can see in your code is that you need to wrap your TypedArray in a normal Array:
new Blob([new Uint8Array(buffer, byteOffset, length)]);

The Blob constructor takes a blobParts sequence as first parameter, and then searches for BufferSource, USVStrings and Blob elements in this sequence. So when you pass a TypedArray, it will actually iterate over all the entries of this TypedArray and treat these as USVString (and thus convert their numerical value to UTF-8 strings in the Blob). That's rarely what you want, so better always pass an Array in this constructor.


text:
Q: dvgrab error: driver recieved an incomplete frame I am unable to use my DV webcam:
 # dvgrab -input /dev/video1

 Waiting for DV...
    End of pipe

    "": frame dropped: timecode 00:00:00.00 date 1999.11.30 00:00:00
    This error means that the ieee1394 driver received an incomplete frame.

What is the origin of this error?
It seems like a module within a package is missing. I cannot start ieee1394:
  modprobe ieee1392
   moddprobe: FATAL: Module aa not found in directory /lib/modules/4.6.0-amd64


text:
Q: Pandoc Error: ! missing $ inserted I was trying to convert a markdown file to pdf using Pandoc. The markdown is written in Atom editor. For simplicity I am just including the equation only.
The markdown file content is
\[
\frac{\partial \theta}{\partial t}= \mathrm{K}(\theta)\left( \frac{\partial h}{\partial z}\right) +1
\]

I run the following command from PowerShell
pandoc testfile1.md -s -o testfile1.pdf

and the following error was produced:
! Missing $ inserted.
<inserted text>
                $
l.53 {[} \frac{\partial \theta}{\partial t}

pandoc.exe: Error producing PDF

The preview is able to display formula but produces an error while conversion. If I replace \[ and \] by $$ i receive required output.
My question is: Can I not use \[ and \]?
I am also attaching snapshorts

A:
My question is: Can I not use \[ and \]?

No, you can't. In pandoc markdown:

Anything between two $ characters will be treated as TeX math.


text: Q: VB.NET OleDbDataAdapter Fill Function is creating duplicate "Columns" I am working with two DataTables. I am using the Clone() function on the first DataTable which is returned from SQL. The Clone() function is used to create an identical schema for my second DataTable. I am using the OleDbDataAdapter Fill() function to populate the second DataTable with data from a CSV file. After calling the Clone() function, I do see that it created the correct number of columns (88). After calling the Fill() function on the second DataTable, I inspected the column count which has now doubled to 176. Inspecting the 1st row, the first 88 items in the ItemArray are "" and items 89-176 are populated correctly from the CSV. There should only be 88 columns, period. Any ideas what may be causing the duplication columns after calling the Fill() function? Thanks!


text:
Q: Allocating an object for C / FFI library calls I have a C library, which has gpio implementation. There's gpio_type which is target specific, each MCU has different definition for gpio_type. One of the functions in the library:
void gpio_init(gpio_type *object, int32_t pin);

I want to write abstraction of Gpio object in Rust, using C library functions. Therefore need something like opaque pointer type (in C++ I would just create a member variable with type: gpio_type). I figured I would create an empty enum (or struct), allocate a space needed for the object and transmute it to match the type in C layer.
pub enum gpio_type {}

#[link(name = "gpio_lib", kind = "static")]
extern {
    pub fn gpio_init(obj: *mut gpio_type, value: i32);
}

pub struct Gpio {
    gpio : *mut gpio_type,
}

impl Gpio {
    pub fn new(pin: u32) -> Gpio {
        unsafe {
            let mut gpio_ptr : &'static [u8; 4] = init(); // size of gpio in C is 4 bytes for one target, will be changed later to obtain it dynamically
            let gpio_out = Gpio { gpio: transmute(gpio_ptr)};
            gpio_init(gpio_out.gpio, pin);
            gpio_out
        }
    }
}

This targets embedded devices, therefore no std, no libc. I don't want to redefine gpio_type for each target in rust (copy the C declaration for each target), looking for something to just allocate memory for the object which C will handle.
The following snippet below produces pointer to address 0 according to disassembly. Disassembly for Gpio new method:
 45c:   b580        push    {r7, lr}
 45e:   466f        mov r7, sp
 460:   4601        mov r1, r0
 462:   2000        movs    r0, #0
 464:   f000 fae6   bl  a34 <gpio_init>
 468:   2000        movs    r0, #0
 46a:   bd80        pop {r7, pc}

Any ideas why 462 is 0 ?

A:
looking for something to just allocate memory for the object which C will handle

What about something like this? Give the struct an actual size (in this case by giving it a fixed-size array of byte-sized items), allocate that space on the heap, then treat that as a raw pointer.
use std::mem;

#[allow(missing_copy_implementations)]
pub struct Gpio([u8; 4]);

impl Gpio {
    fn new() -> Gpio { Gpio([0,0,0,0]) }
}

fn main() {
    // Allocate some bytes and get a raw pointer
    let a: *mut u8 = unsafe { mem::transmute(Box::new(Gpio::new())) };

    // Use it here!

    // When done... back to a box
    let b: Box<Gpio> = unsafe { mem::transmute(a) };

    // Now it will be dropped automatically (and free the allocated memory)

    // Or you can be explicit
    drop(b);
}

However, I'd suggest doing something like this; it's a lot more obvious and doesn't need a heap allocation:
#[allow(missing_copy_implementations)]
pub struct Gpio([u8; 4]);

impl Gpio {
    fn new() -> Gpio { Gpio([0,0,0,0]) }

    fn as_mut_ptr(&mut self) -> *mut u8 {
        self.0.as_mut_ptr()
    }
}

fn main() {
    let mut g = Gpio::new();
    let b = g.as_mut_ptr();
}

As a bonus, you get a nice place to hang some methods on. Potentially as_mut_ptr wouldn't need to be public, and could be hidden behind public methods on the Gpio struct.
(might also be able to use uninitialized instead of [0,0,0,0])
An expanded example of the second suggestion
// This depends on your library, check the FFI guide for details
extern {
    fn gpio_init(gpio: *mut u8, pin: u8);
    fn gpio_pin_on(gpio: *mut u8);
    fn gpio_pin_off(gpio: *mut u8);
}

#[allow(missing_copy_implementations)]
pub struct Gpio([u8; 4]);

impl Gpio {
    fn new(pin: u8) -> Gpio {
        let mut g = Gpio([0,0,0,0]);
        g.init(pin);
        g
    }

    fn as_mut_ptr(&mut self) -> *mut u8 {
        self.0.as_mut_ptr()
    }

    fn init(&mut self, pin: u8) { unsafe { gpio_init(self.as_mut_ptr(), pin) } }
    pub fn on(&mut self) { unsafe { gpio_pin_on(self.as_mut_ptr()) } }
    pub fn off(&mut self) { unsafe { gpio_pin_off(self.as_mut_ptr()) } }
}

static BLUE_LED_PIN: u8 = 0x4;

fn main() {
    let mut g = Gpio::new(BLUE_LED_PIN);
    g.on();
    g.off();
}


text:
Q: Amazon S3 - Where we need to store Access and Secret Keys? I am new to Amazon S3 and would like to know where we need to store the Access and Secret Keys. Actually I am using ASP.Net app so can I store these Keys in Web.config or which is the better practice to store these keys.

A: web.config is probably the most common place to store them, as appKeys.   If you want to protect them a bit better, encrypt the configuration section where they're stored.


text:
Q: Trigger, preventing user from deleting campaign unless criteria met Would love some guidance.
Criteria : Only the Campaign Owner can delete a campaign. If any contact member has a campaign member statuses passed 'Sent' then the campaign can not be deleted. I would need this to apply for all campaign Record types.
However, I would want anyone with a System Administrator profile to be able to perform Deletes.
I was thinking of creating the the following trigger
    trigger CampaignDeletePrevent on Campaign (before delete) {
if(Trigger.isBefore){
    if(Trigger.isDelete){
        PreventCampaignDelete.campaignDelete(trigger.oldMap);
    }}}

The trigger would then call the class "PreventCampaignDelete". Within the class i would have the appropriate logic.
public class PreventCampaignDelete{
public static void campaignDelete(Map<Id,Contact> contacts){}

Question is do you recommend this approach ? or have it all within the trigger?

A: There are a few gaps in the requirements but based on your initial idea:

*

*Only campaign Owner can delete Campaigns. (This is granted pretty much as standard SFDC rights on Force.com sharing) You could reinforce it on the trigger if you want.

*If any Campaign Member passed 'Send' campaign can't be deleted. I assume that you are saying that the Campaign Member status is anything except 'Send'.

*If the running user has 'System Administrators' profile can delete any campaign.
This code has not been tested and it is a guideline you can use.
The trigger can be something like this:
trigger OnCampaingBeforeDelete on Campaign (before delete) {

List<Campaign> CampaignList = [SELECT Id, OwnerId, (SELECT Id, Status FROM CampaignMembers WHERE Status!='Send')
                               FROM Campaign WHERE Id IN: Trigger.new];

if(!CampaignList.isEmpty() && CampaignList.size()>0)
{
    OnCampaignBeforeDeleteHelperClass.OnCampaignBeforeDeleteMethod(CampaignList);
}

}

The idea here is to only run the 'before delete' trigger on campaigns that have a different value on the Campaign Member status than 'Send'.
If there are campaigns on that criteria, invoke the this helper class:
public class OnCampaignBeforeDeleteHelperClass {

public static void OnCampaignBeforeDeleteMethod(List<Campaign> campaignList)
{
    //We find the running user Id.
    Id currentUserId = UserInfo.getUserId();

    //We find the Profile Name and Profile Id from the current User
    User currentLoggedInUser = [SELECT Id, Profile.Name, Profile.Id FROM User WHERE Id =: currentUserId];
    String userProfileId = currentLoggedInUser.ProfileId;
    String userProfileName = currentLoggedInUser.Profile.Name;

    if(currentLoggedInUser.Profile.Name =='System Administrator')
    {
        delete campaignList;
    }else{
        for(Campaign ca: campaignList)
        {
            ca.addError('This campaign can\'t be delete');
        }
    }
  }

}

There we get the current user's profile and make sure that it is an admin, if not, fire an error.
Like I said before, I haven't tested this code and it is a kind of guideline for you to experiment.I hope it helps.

A: Don't put your logic in the trigger body. The best practice is to use Logic-less triggers

Logic-less Triggers
Another widely-recognized best practice is to make your Triggers logic-less. That means, the role of the Trigger is just to delegate the logic responsibilities to some other handler class. There are many reasons to do this. For one, testing a Trigger is difficult if all of the application logic is in the trigger itself. If you write methods in your Triggers, those can't be exposed for test purposes. You also can't expose logic to be re-used anywhere else in your org. Good old OO principles tell us that this is a bad practice. And to top it all off, cramming all of your logic into a Trigger is going to make for a mess one day. To remedy this scenario, just create a handler class and let your Trigger delegate to it.
  Here is an example:
trigger OpportunityTrigger on Opportunity (after insert) {
    OpportunityTriggerHandler.handleAfterInsert(Trigger.new);
}

And the handler class:
public class OpportunityTriggerHandler {
    public static void handleAfterInsert(List opps) {
        // handler logic
    }
}

I prefer a slightly different pattern than what's in the article, but the point is that you should try to minimize the logic you have in your trigger. But the handler shouldn't really answer how questions, so much as just what questions. The how should be laid out in a Service Layer. You basically need two methods, one to filter out records whose deletion is prevented, and another to actually perform the validation. It's not as necessary to separate out the filter concern with validation, but it's a good practice to get into and certainly makes things easier to test. Here's a rough outline of what an ideal service would look like:
public with sharing class CampaignService
{
    public static List<Campaign> getUndeleteableCampaigns(List<Campaign> records)
    {
        List<Campaign> undeleteableCampaigns = new List<Campaign>();
        if (/*check for admin profile*/) return undeleteableCampaigns;

        Map<Id, Campaign> requeriedCampaigns = new Map<Id, Campaign>([
            SELECT (SELECT Id FROM CampaignMembers WHERE Status = 'Sent' LIMIT 1)
            FROM Campaign WHERE Id IN :campaigns AND OwnerId = :UserInfo.getUserId()
        ]);
        for (Campaign record : records)
        {
            if (record.OwnerId != UserInfo.getUserId())
                undeleteableCampaigns.add(record);
            else if (!requeriedCampaigns.get(record.Id).CampaignMembers.isEmpty())
                undeleteableCampaigns.add(record);
        }
        return undeleteableCampaigns;
    }
    public static void validate(List<Campaign> records, String message)
    {
        for (Campaign record : records) record.addError(message);
    }
}


text:
Q: What is this mysterious macro plus sign in stdint.h? Please see my code:
#include <stdint.h>

int main(int argc, char *argv[])
{
unsigned char s = 0xffU;
char ch = 0xff;
int val = 78;
((int8_t) + (78)); /*what does this mean*/

INT8_C(val);    /*equivalent to above*/

signed char + 78; /*not allowed*/

return 0;
}

I find that the macro definition in <stdint.h> is:
#define INT8_C(val) ((int8_t) + (val))

What is the meaning or significance of this plus sign?

A: The snippet:
((int8_t) + (78));

is an expression, one that takes the value 78, applies the unary +, then casts that to an int8_t type, before throwing it away. It is no real different to the legal expressions:
42;
a + 1;

which also evaluate the expressions then throw away the result (though these will possibly be optimised out of existence if the compiler can tell that there are no side effects).
These "naked" expressions are perfectly valid in C and generally useful only when they have side effects, such as with i++, which calculates i and throws it away with the side effect being that it increments the value.
The way you should be using that macro is more along the lines of:
int8_t varname = INT8_C (somevalue);

The reason for the seemingly redundant unary + operator can be found in the standard. Quoting C99 6.5.3.3 Unary arithmetic operators /1:

The operand of the unary + or - operator shall have arithmetic type;

And, in 6.2.5 Types, /18:

Integer and floating types are collectively called arithmetic types.

In other words, the unary + prevents you from using all the other data types in the macro, such as pointers, complex numbers or structures.
And, finally, the reason your:
signed char + 78;

snippet doesn't work is because it's not the same thing. This one is starting to declare a variable of type signed char but chokes when it gets to the + since that's not a legal variable name. To make it equivalent to your working snippet, you would use:
(signed char) + 78;

which is the casting of the value +78 to type signed char.
And, as per C99 7.8.14 Macros for integer constants /2, you should also be careful with using non-constants in those macros, they're not guaranteed to work:

The argument in any instance of these macros shall be an unsuffixed integer constant (as
   defined in 6.4.4.1) with a value that does not exceed the limits for the corresponding type.

6.4.4.1 simply specifies the various integer formats (decimal/octal/hex) with the various suffixes (U, UL, ULL, L, LL and the lower-case equivalents, depending on the type). The bottom line is that they have to be constants rather than variables.
For example, glibc has:
# define INT8_C(c)      c
# define INT16_C(c)     c
# define INT32_C(c)     c
# if __WORDSIZE == 64
#  define INT64_C(c)    c ## L
# else
#  define INT64_C(c)    c ## LL
# endif

which will allow your INT8_C macro to work fine but the text INT64_C(val) would be pre-processed into either valL or valLL, neither of which you would want.

A: Seems everyone has missed the point of the unary plus operator here, which is to make the result valid in #if preprocessor directives. Given:
#define INT8_C(val) ((int8_t) + (val))

the directives:
#define FOO 1
#if FOO == INT8_C(1)

expand as:
#if 1 == ((0) + (1))

and thus work as expected. This is due to the fact that any un#defined symbol in an #if directive expands to 0.
Without the unary plus (which becomes a binary plus in #if directives), the expression would not be valid in #if directives.

A: It's a unary + operator.  It yields the value of its operand, but it can be applied only to arithmetic types.  The purpose here is to prevent the use of INT8_C on an expression of pointer type.
But your statement expression
INT8_C(val);

has undefined behavior.  The argument to INT8_C() is required to be "an unsuffixed integer constant ... with a value that does not exceed the limits for the corresponding type" (N1256 7.18.4).  The intent of these macros is to let you write something like INT64_C(42) and have it expand to 42L if int64_t is long, or to 42LL if int64_t is `long long, and so forth.
But writing either
((int8_t) + (78));

or
((int8_t) + (val));

in your own code is perfectly legal.
EDIT:
The definition for INT8_C() in the question:
#define INT8_C(val) ((int8_t) + (val))

is valid in C99, but is non-conforming according to the later N1256 draft, as a result of a change in one of the Technical Corrigenda.
The original C99 standard, section 7.18.4.1p2, says:

The macro INT***N*_C**(value) shall expand to a signed integer constant with
  the specified value and type int_least***N*_t**.

N1256 changed this to (paragraph 3):

Each invocation of one of these macros shall expand to an integer
  constant expression suitable for use in #if preprocessing directives.
  The type of the expression shall have the same type as would an
  expression of the corresponding type converted according to the
  integer promotions. The value of the expression shall be that of the
  argument.

The change was made in response to Defect Report #209.
EDIT2: But see R..'s answer; it's actually valid in N1256, for quite obscure reasons.

A: That's a unary plus.
There are only two things it could be doing.

*

*It applies what are know as the usual arithmetic conversions to the operand. This establishes a common real type for a result. I can't think of any reason to force this if the result is about to be cast into something specific.

*It restricts the operand to types for which arithmetic operators are defined. This seems like the more likely reason.


text:
Q: Can a SQS consumer receives duplicated message during visibility timeout of message? I am building an application using SQS standard queue, which will trigger Lambda function when a new message is available in the queue. I am aware that my Lambda function might receive a duplicated message which it has processed before:

On rare occasions, one of the servers that stores a copy of a message might be unavailable when you receive or delete a message. If this occurs, the copy of the message isn't deleted on that unavailable server, and you might get that message copy again when you receive messages.

Based on my understanding, the Lambda service will launch multiple instances of my Lambda function, and that different instances of my Lambda function might process the same message. But according to the developer guide,

Immediately after a message is received, it remains in the queue. To prevent other consumers from processing the message again, Amazon SQS sets a visibility timeout, a period of time during which Amazon SQS prevents other consumers from receiving and processing the message.

I would like to know whether one instance of my Lambda function might received a duplicated message while another instance of my Lambda function is still processing the message. That is, I want to know whether it is possible for one Lambda instance to receive a message while the message is in visibility timeout.
Thank you in advance.

A: After reading these docs
No if its still processing the message then it can't but if the processing is failed then it might.
In my view it depends on the number of messages and batch.

Lambda reads messages in batches and invokes your function once for each batch. When your function successfully processes a batch, Lambda deletes its messages from the queue.

*

*This establishes the fact the concurrency of lambda depends on batch.

When Lambda reads a batch, the messages stay in the queue but are hidden for the length of the queue's visibility timeout. If your function successfully processes the batch, Lambda deletes the messages from the queue. By default, if your function encounters an error while processing a batch, all messages in that batch become visible in the queue again

*This established the fact the all messages in the batch should be processed otherwise they will be visible in the queue.

For standard queues, Lambda uses long polling to poll a queue until it becomes active. When messages are available, Lambda reads up to five batches and sends them to your function. If messages are still available, Lambda increases the number of processes that are reading batches by up to 60 more instances per minute. The maximum number of batches that an event source mapping can process simultaneously is 1,000.

*This establishes that a single lambda can read up to 5 batches.

Combining all the 3.
If it is upto 5 batch a single lambda can process 5 batches, if it is more than 5 batch multiple lambda will be invoked and in this time if the previous lambda couldn't process the message and it reappears in the queue and the new invoked lambda will be able to read the previous messages which was not be ables to processed.
This blog also explains the same better than docs https://data.solita.fi/lessons-learned-from-combining-sqs-and-lambda-in-a-data-project/


text:
Q: Issues reconnecting PS4 controller to console after using iPad Any suggestions on how to reconnect my ps4 controller to console?
I recently connected it to the iPad to play and now I can't seem to reconnect to console. I have reset the small button in back and connected it to console with usb cable but it's not connecting


text:
Q: Retorno de imagem Banco de Dados Json Inicialmente para esclarecimento, estou tentando cria um app hibrido html, javascript e css.
objetivamente, meu obstáculo é exibir na tela do usuário seu avatar, que esta em um diretório do banco de dados Mysql no meu computador.
Eu consigo enviar a imagem por Json com o metodo FormData sem problemas. Na hora de retornar o login com os dados do usuário ele exibe as informações que armezeno com localStorage.setItem. Mas a imagem ele exibe somente o nome com o caminho do arquivo.
Ja pesquisei muito, quebrei a cabeça e não consegui. Se poderem me ajudar agradeço.
Vou enviar meus códigos
Faz login
$(document).ready(function(){
$.ajax({
    type:'post',                                        //Definimos o método HTTP usado
    dataType: 'json',                                   //Definimos o tipo de retorno
    url: 'http://xxxxx/classes/vlogin.php', //Definindo o arquivo onde serão buscados os dados
    data:{
        nemail: email,
        nsenha: senha,
    },
    success: function(dados){

        if (dados == false){
            $("#btn").show();
            $("#menssagem_login").html("Login ou senha Invalidos");
        }

        else{
            localStorage.setItem('id', dados[0]);
            localStorage.setItem('nome', dados[1]);
            localStorage.setItem('email', dados[2]);
            localStorage.setItem('estado', dados[3]);
            localStorage.setItem('senha', dados[4]);
            localStorage.setItem('tipo', dados[5]);
            localStorage.setItem('data', dados[6]);
            localStorage.setItem('imagem', dados[7]);

            // var obj = JSON.parse(dados);
            // var obj = jQuery.parseJSON(dados);   //tratar os dados
            // var obj = $.parseJSON(dados);    //tratar os dados
            window.location = "estrutura/perfil.html";
            console.log(dados);
        }
        }
    });
});

    $email =  $_POST['nemail'];
$senha =    $_POST['nsenha'];

$pasta = 'fotos/';

 include "conexao.php";
 $link = conexao();

$sql = "SELECT * FROM usuario WHERE email = '$email' AND senha = '$senha' AND ativo = 0";

$resultado = mysqli_query($link, $sql) or die (mysqli_error($link));
$vazio = mysqli_num_rows($resultado);

if($vazio == ''){
echo json_encode(false);
}

else{
$registro = mysqli_fetch_array($resultado);
// $registro = mysqli_fetch_object($resultado);

// $imagem1 = scandir($pasta,$imagem);
// $lista_dir = scandir($pasta);
// $img;
// foreach ($lista_dir as $registro['imagem']) {
//  $img;
// }

$id         = $registro['id'];
$nome       = $registro['nome'];
$email      = $registro['email'];
$estado     = $registro['estado'];
$senha      = $registro['senha'];
$tipo       = $registro['tipo'];
$data       = $registro['data'];
$imagem     = $pasta.$registro['imagem'];

// $imagem= $_FILE[$pasta][ $registro['imagem']];
// $imagem= base64_encode($imagem);

$retorno= array($id,$nome,$email,$estado,$senha,$tipo,$data,$imagem);

echo json_encode($retorno);
// echo json_encode($registro);
}
function carrega_perfil(){

var nome = localStorage.getItem('nome');
var email = localStorage.getItem('email');
var estado = localStorage.getItem('estado');
var tipo = localStorage.getItem('tipo');
var data = localStorage.getItem('data');
var imagem = localStorage.getItem('imagem');

// document.getElementById('status').innerHTML=nome+"
"+email;
document.getElementById('status').innerHTML=nome;

document.getElementById('avatar').innerHTML= "";
console.log(nome);


text:
Q: Mask UIView (UICollectionView) correctly Ok, I need to mask a horizontal UICollectionViewso it looks like a ribbon. My web dev counterpart got it done with an SVG that he used as a masking layer.
Here is my current situation:
And here is what I need (Photo from our web app):
Small detail in image spacing aside, I have an SVG like this:

Which I can successfully convert into UIBezierPath code (Paintcode):
let pathPath = UIBezierPath()
pathPath.move(to: CGPoint(x: 0.05, y: 0))
pathPath.addCurve(to: CGPoint(x: 162.02, y: 3.8), controlPoint1: CGPoint(x: 0.05, y: 2.1), controlPoint2: CGPoint(x: 72.57, y: 3.8))
pathPath.addCurve(to: CGPoint(x: 324, y: 0), controlPoint1: CGPoint(x: 251.48, y: 3.8), controlPoint2: CGPoint(x: 324, y: 2.1))
pathPath.addLine(to: CGPoint(x: 324, y: 150.2))
pathPath.addCurve(to: CGPoint(x: 162.02, y: 154), controlPoint1: CGPoint(x: 324, y: 152.3), controlPoint2: CGPoint(x: 251.48, y: 154))
pathPath.addCurve(to: CGPoint(x: 0.05, y: 150.2), controlPoint1: CGPoint(x: 72.57, y: 154), controlPoint2: CGPoint(x: 0.05, y: 152.3))
pathPath.addCurve(to: CGPoint(x: 0, y: 0.17), controlPoint1: CGPoint(x: 0.05, y: 148.1), controlPoint2: CGPoint(x: 0, y: 0.17))
pathPath.usesEvenOddFillRule = true
UIColor.lightGray.setFill()
pathPath.fill()

Now what do I do?

A: You should use the mask property of your UICollectionView by setting it to a view whose alpha channel indicates what part of the UICollectionView you want to mask out.  In outline it will probably be something like:
// If you don't have a custom subclass of UICollectionView... you can handle the resize in the
// UICollectionViewController or whatever view contoller is handling your view.
//
// If you do have a custom subclass of UICollectionView... you could do something similar
// in layoutSubviews.

class MyViewController : UICollectionViewController {

    // recreate the mask after the view lays out it's subviews
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        if let maskImage = createMaskingImage(size: self.view.bounds.size) {
            let maskView = UIView(frame: self.view.bounds)
            maskView.layer.contents = maskImage

            self.view.mask = maskView
        }
    }
}

// create a masking image for a view of the given size
func createMaskingImage(size: CGSize) -> UIImage? {

    let drawingBounds = CGRect(origin: CGPoint.zero, size: size)

    UIGraphicsBeginImageContext(size)

    // We're going to jump down to the level of cgContext for scaling
    // You might be able to do this from the level of UIGraphics, but I don't know how so...
    // Implicitly unwrapped optional, but if we can't get a CGContext we're in trouble

    let cgContext = UIGraphicsGetCurrentContext()!
    let maskingPath = createMaskingPath()
    let pathBounds = maskingPath.bounds;

    cgContext.saveGState()

    // Clearing the image may not strictly be necessary
    cgContext.clear(drawingBounds)

    // Scale the context so that when we draw the path it fits in the drawing bounds
    // Could just use "size" here instead of drawingBounds.size, but I think this makes it a
    // little more explicit that we're matching up two rects
    cgContext.scaleBy(x: drawingBounds.size.width / pathBounds.size.width,
                      y: drawingBounds.size.height / pathBounds.size.height)
    cgContext.setFillColor(UIColor.lightGray.cgColor)
    cgContext.addPath(maskingPath.cgPath)
    cgContext.fillPath(using: .evenOdd)

    cgContext.restoreGState()

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
}

func createMaskingPath() -> UIBezierPath {
    let path = UIBezierPath()

    path.move(to: CGPoint(x: 0.05, y: 0))
    path.addCurve(to: CGPoint(x: 162.02, y: 3.8), controlPoint1: CGPoint(x: 0.05, y: 2.1), controlPoint2: CGPoint(x: 72.57, y: 3.8))
    path.addCurve(to: CGPoint(x: 324, y: 0), controlPoint1: CGPoint(x: 251.48, y: 3.8), controlPoint2: CGPoint(x: 324, y: 2.1))
    path.addLine(to: CGPoint(x: 324, y: 150.2))
    path.addCurve(to: CGPoint(x: 162.02, y: 154), controlPoint1: CGPoint(x: 324, y: 152.3), controlPoint2: CGPoint(x: 251.48, y: 154))
    path.addCurve(to: CGPoint(x: 0.05, y: 150.2), controlPoint1: CGPoint(x: 72.57, y: 154), controlPoint2: CGPoint(x: 0.05, y: 152.3))
    path.addCurve(to: CGPoint(x: 0, y: 0.17), controlPoint1: CGPoint(x: 0.05, y: 148.1), controlPoint2: CGPoint(x: 0, y: 0.17))

    return path
}

A: /*
This is a UICollectionView, which clips normally on the left and right,
but allows some extra space horizontally.
A typical example is you need to clip the scrolling items but you
still need to allow shadows.
*/

import Foundation
import UIKit

class CustomClipCollectionView: UICollectionView {

    private lazy var extraSpaceOnBaseButStillClipSidesNormally: CALayer = {
        let l = CALayer()
        l.backgroundColor = UIColor.black.cgColor
        return l
    }()

    override func layoutSubviews() {
        extraSpaceOnBaseButStillClipSidesNormally.frame = bounds.insetBy(
                          dx: 0, dy: -10)
        layer.mask = extraSpaceOnBaseButStillClipSidesNormally
        super.layoutSubviews()
    }
}


text:
Q: Can I use my power bank usb output to charge my laptop? so I have this power bank that has 3 outputs and one in which is a USB output that delivers 5v =~ 2 A!
The charging cord that came with the laptop has an USB end that connects to an adapter that delivers 20V =~ 3.25 A
I want to know if I take the USB end of the factory charging cord and if I plug it in my power bank will it decrease/burn the battery.
If you are curious of the specification
The laptop: Lenovo Yoga 900, it has the USB input.

A: No - as you've stated the power bank falls far short of the power cable you have at 20V for charging, and can't provide close to the maximum amperage draw it may require of 3.25A (This is a maximum output of 65W, compared to the 10W maximum of your power bank.)
There is a very useful post here which covers these points:

How does it work?
The special "fool proof" charging cord has two extra pins on the AC
  adapter end and two extra pins on the Yoga 3 Pro end. The extra pins
  only make a connection when the fool proof cord is plugged in to the
  Lenovo charger and the Yoga 3 Pro. When a regular USB cord is plugged
  into either the charger or the Yoga 3 Pro, it makes a regular USB
  connection.
Can I charge the Yoga 3 Pro with any USB charger?
No. The Yoga 3 Pro requires 2A at 20V, which is what the provided 40W
  Lenovo AC adapter supplies.
Can I charge a USB device with the Yoga 3 Pro AC adapter?
Absolutely. In addition to 2A at 20, the Yoga 3 Pro AC adapter
  supplies 2A at 5.2V (10.4W), enough to charge a phone or tablet. Works
  for iPad.

It looks like the charger port on your machine also doubles up as a USB port for power output (likely not data but it's possible), so you could charge other devices from the Yoga, but not the other way around.
Bring on USB-C... :)

A: Not a chance. Your laptop needs something like 45W to 60W to charge. Your USB output supplies 10W maximum.


text:
Q: degraded accuracy performance with overfitting when downgrading from tensorflow 2.3.1 to tensorflow 1.14 or 1.15 on multiclass categorization I made a script in tensorflow 2.x but I had to downconvert it to tensorflow 1.x (tested in 1.14 and 1.15). However, the tf1 version performs very differently (10% accuracy lower on the test set). See also the plot for train and validation performance (diagram is attached below).
Looking at the operations needed for the migration from tf1 to tf2 it seems that only the Adam learning rate may be a problem but I'm defining it explicitly tensorflow migration
I've reproduced the same behavior both locally on GPU and CPU and on colab. The keras used was the one built-in in tensorflow (tf.keras). I've used the following functions (both for train,validation and test), using a sparse categorization (integers):
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
                        horizontal_flip=horizontal_flip,
                        #rescale=None, #not needed for resnet50
                        preprocessing_function=None,
                        validation_split=None)

train_dataset = train_datagen.flow_from_directory(
                        directory=train_dir,
                        target_size=image_size,
                        class_mode='sparse',
                        batch_size=batch_size,
                        shuffle=True)

And the model is a simple resnet50 with a new layer on top:
IMG_SHAPE = img_size+(3,)
inputs = Input(shape=IMG_SHAPE, name='image_input',dtype = tf.uint8)
x = tf.cast(inputs, tf.float32)

# not working in this version of keras. inserted in imageGenerator
x = preprocess_input_resnet50(x)

base_model = tf.keras.applications.ResNet50(
                                include_top=False,
                                input_shape = IMG_SHAPE,
                                pooling=None,
                                weights='imagenet')
# Freeze the pretrained weights
base_model.trainable = False
x=base_model(x)

# Rebuild top
x = GlobalAveragePooling2D(data_format='channels_last',name="avg_pool")(x)

top_dropout_rate = 0.2
x = Dropout(top_dropout_rate, name="top_dropout")(x)
outputs = Dense(num_classes,activation="softmax", name="pred_out")(x)
model = Model(inputs=inputs, outputs=outputs,name="ResNet50_comp")

optimizer = tf.keras.optimizers.Adam(lr=learning_rate)
model.compile(optimizer=optimizer,
        loss="sparse_categorical_crossentropy",
        metrics=['accuracy'])

And then I'm calling the fit function:
history = model.fit_generator(train_dataset,
                    steps_per_epoch=n_train_batches,
                    validation_data=validation_dataset,
                    validation_steps=n_val_batches,
                    epochs=initial_epochs,
                    verbose=1,
                    callbacks=[stopping])

I've reproduced the same behavior for example with the following full script (applied to my dataset and changed to adam and removed intermediate final dense layer):
deep learning sandbox
The easiest way to replicate this behavior was to enable or disable the following line on a tf2 environment with the same script and add the following line to it. However, I've tested also on tf1 environments (1.14 and 1.15):
tf.compat.v1.disable_v2_behavior()

Sadly I cannot provide the dataset.
Update 26/11/2020
For full reproducibility I've obtained a similar behaviour by means of the food101 (101 categories) dataset enabling tf1 behaviour with 'tf.compat.v1.disable_v2_behavior()'. The following is the script executed with tensorflow-gpu 2.2.0:
#%% ref https://medium.com/deeplearningsandbox/how-to-use-transfer-learning-and-fine-tuning-in-keras-and-tensorflow-to-build-an-image-recognition-94b0b02444f2
import os
import sys
import glob
import argparse
import matplotlib.pyplot as plt
import tensorflow as tf
# enable and disable this to obtain tf1 behaviour
tf.compat.v1.disable_v2_behavior()
from tensorflow.keras import __version__
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.optimizers import Adam

# since i'm using resnet50 weights from imagenet, i'm using food101 for
# similar but different categorization tasks
# pip install tensorflow-datasets if tensorflow_dataset not found
import tensorflow_datasets as tfds
(train_ds,validation_ds),info= tfds.load('food101', split=['train','validation'], shuffle_files=True, with_info=True)

assert isinstance(train_ds, tf.data.Dataset)
print(train_ds)
#%%
IM_WIDTH, IM_HEIGHT = 224, 224
NB_EPOCHS = 10
BAT_SIZE = 32

def get_nb_files(directory):
  """Get number of files by searching directory recursively"""
  if not os.path.exists(directory):
    return 0
  cnt = 0
  for r, dirs, files in os.walk(directory):
    for dr in dirs:
      cnt += len(glob.glob(os.path.join(r, dr + "/*")))
  return cnt

def setup_to_transfer_learn(model, base_model):
  """Freeze all layers and compile the model"""
  for layer in base_model.layers:
    layer.trainable = False
  model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

def add_new_last_layer(base_model, nb_classes):
  """Add last layer to the convnet
  Args:
    base_model: keras model excluding top
    nb_classes: # of classes
  Returns:
    new keras model with last layer
  """
  x = base_model.output
  x = GlobalAveragePooling2D()(x)
  #x = Dense(FC_SIZE, activation='relu')(x) #new FC layer, random init
  predictions = Dense(nb_classes, activation='softmax')(x) #new softmax layer
  model = Model(inputs=base_model.input, outputs=predictions)
  return model

def train(nb_epoch, batch_size):
  """Use transfer learning and fine-tuning to train a network on a new dataset"""

  #nb_train_samples = train_ds.cardinality().numpy()
  nb_train_samples=info.splits['train'].num_examples
  nb_classes = info.features['label'].num_classes
  classes_names = info.features['label'].names
  #nb_val_samples = validation_ds.cardinality().numpy()
  nb_val_samples = info.splits['validation'].num_examples
  #nb_epoch = int(args.nb_epoch)
  #batch_size = int(args.batch_size)

  def preprocess(features):
      #print(features['image'], features['label'])
      image = tf.image.resize(features['image'], [224,224])
      #image = tf.divide(image, 255)
      #print(image)
      # data augmentation
      image=tf.image.random_flip_left_right(image)

      image = preprocess_input(image)
      label = features['label']
      # for categorical crossentropy
      #label = tf.one_hot(label,101,axis=-1)
      #return image, tf.cast(label, tf.float32)
      return image, label
  #pre-processing the dataset to fit a specific image size and 2D labelling
  train_generator = train_ds.map(preprocess).batch(batch_size).repeat()
  validation_generator = validation_ds.map(preprocess).batch(batch_size).repeat()

  #train_generator=train_ds
  #validation_generator=validation_ds
  #fig = tfds.show_examples(validation_generator, info)
  # setup model
  base_model = ResNet50(weights='imagenet', include_top=False) #include_top=False excludes final FC layer
  model = add_new_last_layer(base_model, nb_classes)

  # transfer learning
  setup_to_transfer_learn(model, base_model)

  history = model.fit(
    train_generator,
    epochs=nb_epoch,
    steps_per_epoch=nb_train_samples//BAT_SIZE,
    validation_data=validation_generator,
    validation_steps=nb_val_samples//BAT_SIZE)
    #class_weight='auto')
#execute
history = train(nb_epoch=NB_EPOCHS, batch_size=BAT_SIZE)

And the performance on food101 dataset:

update 27/11/2020
It's possible to see the discrepancy also in the way smaller oxford_flowers102 dataset:
(train_ds,validation_ds,test_ds),info= tfds.load('oxford_flowers102', split=['train','validation','test'], shuffle_files=True, with_info=True)

Nb: the above plot shows confidences given by running the same training multiple times and evaluatind mean and std to check for the effects on random weights initialization and data augmentation.
Moreover I've tried some hyperparameter tuning on tf2 resulting in the following picture:

*

*changing optimizer (adam and rmsprop)

*not applying horizontal flipping aumgentation

*deactivating keras resnet50 preprocess_input

Thanks in advance for every suggestion. Here are the accuracy and validation performance on tf1 and tf2 on my dataset:

Update 14/12/2020
I'm sharing the colab for reproducibility on oxford_flowers at the clic of a button:
colab script

A: I came across something similar, when doing the opposite migration (from TF1+Keras to TF2).
Running this code below:
# using TF2
import numpy as np
from tensorflow.keras.applications.resnet50 import ResNet50
fe = ResNet50(include_top=False, pooling="avg")
out = fe.predict(np.ones((1,224,224,3))).flatten()
sum(out)
>>> 212.3205274187726

# using TF1+Keras
import numpy as np
from keras.applications.resnet50 import ResNet50
fe = ResNet50(include_top=False, pooling="avg")
out = fe.predict(np.ones((1,224,224,3))).flatten()
sum(out)
>>> 187.23898954353717

you can see the same model from the same library on different versions does not return the same value (using sum as a quick check-up). I found the answer to this mysterious behavior in this other SO answer: ResNet model in keras and tf.keras give different output for the same image
Another recommendation I'd give you is, try using pooling from inside applications.resnet50.ResNet50 class, instead of the additional layer in your function, for simplicity, and to remove possible problem-generators :)


text:
Q: Calculating number of edges from a degree sequence Problem: Suppose a graph $G$ has degree sequence $25, 18, 18, 5, 2, 2$.
How many edges are there in $G$?
I am assuming since the definition of degrees of a vertex that each one of the 6 vertex's (since there are $6$ nums in the degree sequence) has $n$ edges(paths) ($n$ being one of the six numbers in the degree sequence). So would the total number of edges in this case be $25+18+18+5+2+2$?
I don't think this graph exists as a simple graph, but would have to be drawn with the three vertices having degrees of $18$, $18$, and $25$ have loops or multiple edges between them. Do those count in the total number of edges?

A: Hint: For a vertex $v$, the degree of $v$ is the number of edges incident to $v$.
Counting the total degree, you will actually count each edge $\{u,v\}$ twice -- once when you count the degree of $u$, and once when you count the degree of $v$.
So, how should the total degree and the total number of edges be related?
If each edge $\{u,v\}$ gets counted for both $u$ and for $v$, then it has been counted twice -- and so the total degree is just twice the number of edges!
(This works if we allow multiple edges... it works with loops as well, with the convention that a loop on vertex $v$ contributes two to its total degree.)
So, if you notice that your total degree is 70, it must be the case that there are 35 edges.

A: it would be sum of degrees divided by two.

A: I believe the answer is the sum of the sequence divided by two. Each edge is incident on two vertices. I have this same problem due tomorrow too. This link supports my idea http://mathworld.wolfram.com/DegreeSequence.html

A: We can find the number of edges from the following observations:

*

*The degree of a vertex $v$ counts the number of times $v$ appears as the endpoint of an edge.

*If we sum the degrees, we get the total number of times any vertex appears as the endpoint of an edge.

*Each edge has two endpoints.
These observations will lead you to the result known as the Handshaking Lemma.
This particular degree sequence obviously cannot be realized by a simple graph: the vertex of degree $25$ would have $25$ distinct neighbours, but there are only $6$ vertices.
It can be realized as a multigraph, however, as the following picture indicates:

In this figure, numbers on edges indicate their multiplicity.


text:
Q: Having trouble with deck of cards I am having trouble with this part of the code. I keep getting a null pointer exception when calling the method. Im not sure whats wrong with it.
class Deck{

public Card[] myCards = new Card[52];

void refreshDeck(){
    int cardValue = 1;
    char cardSuit = 'c';

    for (int i = 0; i < 52; i++){
        myCards[i].setValue(cardValue);
        myCards[i].setSuit(cardSuit);

        if (cardValue == 13){
            cardValue = 0;
            switch(cardSuit){
                case 'c':
                    cardSuit = 's';
                    break;
                case 's':
                    cardSuit = 'd';
                    break;
                case 'd':
                    cardSuit = 'h';
                    break;
            }
        }
        cardValue++;
    }
}

I really cant find the error. and this works on c++.

A: You have to initialize each card in the array. Try that:
for (int i = 0; i < 52; i++){
    myCards[i] = new Card();//a constructor
    myCards[i].setValue(cardValue);
    myCards[i].setSuit(cardSuit);
    //...

A: You haven't initialised each card in your array, add
myCards[i] = new Card();

To the start of your for loop

A: You've build an array of 52 references to Card objects, but the objects haven't been created yet. The array is then an array of 52 null references. You need to build each one:
for (int i = 0; i < 52; i++) {
    myCards[i] = new Card();
    ...

It would be much better to add an adequate constructor to Card to be able to write :
    myCards[i] = new Card(cardValue,cardSuit);


text:
Q: how to implement viewpager and circleindicator I want to display images on launch screen using Viewpager & use Circle indicator to show position in the slideshow and would also like to add a button at the end image of the slideshow!

A: Try this Lib. (ViewPagerIndicator by JakeWharton)
Should do all what you need. Also it is very well coded, so its a nice guide if you want to do this by yourself.


text:
Q: Package iOS iPad application for company with 10 employees I would like to distribute the application I have created to a company who have 10 employees only and wont extend past 20.  The application will be in-house and will not be sold on the app store or anywhere else.
Is there a way to be able to distribute the application without having to add each individual's UDID in the Testing provisioning section in the developers portal as from what I understand is only used for testing purposes.
If anyone could give me a clear guide on how I am able to distribute the application with ease so that I can just install the app on the 10 iPad devices. The goals are:
1) to be able to send application updates every other week and make it easy for them to download.
2) to be able to add a new device when a new employee joins the company.
So far I have been using testflight to allow my beta tester to have a go at my application and i was about to add the 10 employees in a similar fasion but I dont think this would be the right way, although the advantage using testflight is the ability to send applications with ease to users.
Thanks

A: If your client can afford the big $300 per year, you can have them get into Apple's "Enterprise" program (described here) where they have some handy utilities and techniques you can use.

A: I was able to distribute my apo wirelessly. The application would check for the current version by analysing a plist file stored on the server, and if the ipad's software version was lower than that of the plist file version key then the application would swivel to the download page of the new ios application. it works nicely.


text:
Q: How to read line by line a CR-only file with Perl? I'm trying to read a file which has only CR as line delimiter. I'm using Mac OS X and Perl v.5.8.8. This script should run on every platform, for every kind of line delimiter (CR, LF, CRLF).
My current code is the following :
open(FILE, "test.txt");

while($record = <FILE>){
    print $record;
}

close(TEST);

This currently print only the last line (or worst). What is going on?
Obvisously, I would like to not convert the file. Is it possible?

A: You can set the delimiter using the special variable $/:
local $/ = "\r" # CR, use "\r\n" for CRLF or "\n" for LF
my $line = <FILE>;

See perldoc perlvar for further information.
Another solution that works with all kinds of linebreaks would be to slurp the whole file at once and then split it into lines using a regex:
local $/ = undef;
my $content = <FILE>;
my @lines = split /\r\n|\n|\r/, $content;

You shouldn't do that with very large files though, as the file is read into memory completely. Note that setting $/ to the undefined value disables the line delimiter, meaning that everything is read until the end of the file.

A: I solved a more general problem that could be useful here:
How to parse big file line-by-line with any line delimiter (CR/CRLF/LF), but unknown beforehand.
'Big' file means that it is not ok to read the whole file into one variable. Here function 'detectEndOfLine' gets name of file and returns either '\r' or '\n', whatever is used for line ending (it searched for '\r' or '\n' symbol char-by-char starting from the end of the file).
my $file = "test.txt";
local $/ = detectEndOfLine($file);
open(IN, $file) or die "Can't open file \"$file\" for reading: $!\n";
while(<IN>) {
    s/\r\n|\n|\r$//;
    print "$_\n";
}

sub detectEndOfLine {
    my $file = $_[0];
    my $size = -s $file;
    print "\"$size\"\n";

    open(IN, $file) or die "Can't open file \"$file\" for reading: $!\n";
    for(my $i = $size; $i >= 0; --$i) {
        seek(IN, $i, 0);
        $_ = <IN>;
        my $sym = substr($_, 0, 1);
        return $sym if( $sym eq "\n" or $sym eq "\r" );
    }
    return undef;
}


text:
Q: ContentPresenter DataTemplate I have a DataTemplate:
<DataTemplate x:Key="myTemplate">
    ...
</DataTemplate>

I want to use it as the ContentTemplate of a ContentPresenter:
<ContentPresenter Content="{Binding X}">
    <ContentPresenter.ContentTemplate >
        <!-- ????? what goes here ????-->
    </ContentPresenter.ContentTemplate>
</ContentPresenter>

How can I use the predefined DataTemplate in my ContentPresenter?

A: Should be something like:
<ContentPresenter Content="{Binding X}" ContentTemplate="{StaticResource myTemplate}"/>

Although I wouldn't define a Template on a contentpresenter, I will select the correct template based on the type anyway.

A: You just need to reference the defined resource:
<ContentPresenter Content="{Binding X}" ContentTemplate="{StaticResource myTemplate}"/>


text:
Q: How to set SelectedItem to ListViewItem from its child Is there an easy way to set the SelectedItem of my ListView when the TextBox gets the focus by Tab navigation?
AdditionalInformation.xaml:
<ListView Grid.Row="2" ItemsSource="{Binding PropertieList}" Style="{DynamicResource AdditionalInfo_ListViewStyle}" >
    <ListView.View>
        <GridView ColumnHeaderContainerStyle="{DynamicResource AdditionalInfo_GridView_HeaderStyle}">
            <GridViewColumn Header=" Name" KeyboardNavigation.TabNavigation="None" >
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Name}" Style="{DynamicResource AdditionalInfo_Body_TextBlockStyle}" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Header=" Value"  >
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding Value}" IsEnabled="{Binding AllowValueChanging}" MinWidth="300" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

ResourceDictionary
<Style x:Key="AdditionalInfo_ListViewStyle"  TargetType="{x:Type ListView}">
    <Setter Property="HorizontalAlignment" Value="Stretch" />
    <Setter Property="VerticalAlignment" Value="Stretch" />
    <Setter Property="Background" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush}}" />
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Margin" Value="14,0,14,0" />
    <Setter Property="SelectionMode" Value="Single" />
    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
    <Setter Property="KeyboardNavigation.TabNavigation" Value="Continue" />

    <!--Row style-->
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="{x:Type ListViewItem}">
                <Setter Property="VerticalContentAlignment" Value="Top" />
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                <Setter Property="Focusable" Value="false"/>
                <Setter Property="Background" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush}}" />
                <Style.Triggers>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsMouseOver" Value="true"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush_Hover}}"/>
                        <Setter Property="BorderBrush" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush_Hover}}"/>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsSelected" Value="true"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush_IsSelected}}"/>
                        <Setter Property="BorderBrush" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush_IsSelected}}"/>
                    </MultiTrigger>
                </Style.Triggers>
            </Style>
        </Setter.Value>
    </Setter>
</Style>

<!--Header-->
<Style x:Key="AdditionalInfo_GridView_HeaderStyle" TargetType="{x:Type GridViewColumnHeader}">
    <Setter Property="Visibility" Value="Visible" />
    <Setter Property="HorizontalContentAlignment" Value="Left" />
    <Setter Property="Foreground" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Header_ForegrounddBrush_enabled}}" />
    <Setter Property="Background" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Header_BackgroundBrush}}" />
</Style>

<Style x:Key="AdditionalInfo_Body_TextBlockStyle" TargetType="{x:Type TextBlock}">
    <Setter Property="OverridesDefaultStyle" Value="True"/>
    <Style.Triggers>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsEnabled" Value="true"/>
            </MultiTrigger.Conditions>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_ForegrounddBrush_enabled}}" />
        </MultiTrigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsEnabled" Value="false"/>
            </MultiTrigger.Conditions>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_ForegrounddBrush_disabled}}" />
        </MultiTrigger>
    </Style.Triggers>
</Style>

As shown here How can I get access to ListViewItem from its child control? it would be possible to set the SelectedItem by using the code-behind but I do not like to use the code-behind for this simple task.
AdditionalInformation.xaml:
<ListView x:Name="AdditionalInfoListView" Grid.Row="2" ItemsSource="{Binding PropertieList}" Style="{DynamicResource AdditionalInfo_ListViewStyle}" >
    <ListView.View>
        <GridView ColumnHeaderContainerStyle="{DynamicResource AdditionalInfo_GridView_HeaderStyle}">
            <GridViewColumn Header=" Name" KeyboardNavigation.TabNavigation="None" >
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Name}" Style="{DynamicResource AdditionalInfo_Body_TextBlockStyle}" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Header=" Value"  >
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding Value}" IsEnabled="{Binding AllowValueChanging}" GotFocus="TextBox_GotFocus" MinWidth="300" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

AdditionalInformation.xaml.cs
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    var item = (sender as TextBox).DataContext;
    int index = AdditionalInfoListView.Items.IndexOf(item);
    AdditionalInfoListView.SelectedItem = AdditionalInfoListView.Items[index];
}

A: You can use a Trigger to set the IsSelected state depending on IsKeyboardFocusWithin in your item container style. Whenever you focus a TextBox, it will focus the row, too.
<Trigger Property="IsKeyboardFocusWithin" Value="True">
   <Setter Property="IsSelected" Value="True"/>
</Trigger>

Here is the trigger merged with your items container style. Please note that the SelectedItem will only be set as long as your TextBox is focused, since you set the Focusable to False in your style. When the focus is moved, e.g. clicking a button, the SelectedItem will be reset to null. If you remove the focusable setter, the trigger will still work, the row stays focused and the SelectedItem will be kept even when clicking a button.
<Setter Property="ItemContainerStyle">
    <Setter.Value>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="VerticalContentAlignment" Value="Top" />
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            <Setter Property="Focusable" Value="false"/>
            <Setter Property="Background" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush}}" />
            <Style.Triggers>
                <Trigger Property="IsKeyboardFocusWithin" Value="True">
                    <Setter Property="IsSelected" Value="True"/>
                </Trigger>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsMouseOver" Value="true"/>
                    </MultiTrigger.Conditions>
                    <Setter Property="Background" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush_Hover}}"/>
                    <Setter Property="BorderBrush" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush_Hover}}"/>
                </MultiTrigger>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsSelected" Value="true"/>
                    </MultiTrigger.Conditions>
                    <Setter Property="Background" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush_IsSelected}}"/>
                    <Setter Property="BorderBrush" Value="{DynamicResource {x:Static local:ResourceKeys.ListView_L2_Background_Body_BackgroundBrush_IsSelected}}"/>
                </MultiTrigger>
            </Style.Triggers>
        </Style>
    </Setter.Value>
</Setter>


text:
Q: Search multiple columns for text contained within another column, return a value I apologize if this is a silly question, or if it's been asked before, but I have searched all over and haven't found a similar question/solution. I need to look within two possible columns (A and B) for text contained in another column (E). If text contained in column A or B is found within column E, I need the value in column C to appear in column F.
The text in column A and B will not be identical to that in column E (if it were I wouldn't be asking this question). And there may or may not be data in column B (not sure if that adds any complexity, but just for clarity).
I've tried all sorts of combinations of INDEX(MATCH and ISNUMBER(SEARCH, etc. but to no avail. I'm pretty sure there is a simple solution for this. Any help would be greatly appreciated!

A: You can use following array formula:
{=INDEX(F$2:$F$6,MATCH(1,--(MMULT(--ISNUMBER(SEARCH(IF(ISBLANK(B2),A2,A2:B2),$E$2:$E$6)),TRANSPOSE(COLUMN(IF(ISBLANK(B2),A2,A2:B2))^0))>0),0))}

Array formula after editing is confirmed by pressing ctrl + shift + enter

EDIT:
Reverse search - from column C to column F. Also an array formula.
{=INDEX($C$2:$C$9,MATCH(1,--(MMULT(--ISNUMBER(SEARCH(IF(ISBLANK($A$2:$B$9), $A$2:$B$9 & "#",$A$2:$B$9),E2)),TRANSPOSE(COLUMN($A$1:$B$1)^0))>0),0))}

In the expression $A$2:$B$9 & "#" instead of # you can specify any character that is not used in the search text

A: Not sure if there is an easier way, but with some validation you can easily come up with something like
=IF(OR(IF(A3<>"",ISNUMBER(SEARCH(A3,E3)),FALSE),IF(B3<>"",ISNUMBER(SEARCH(B3,E3)),FALSE)),C3,F3)

It verify that both A3 and B3 are not empty (<>"",...,FALSE) and return false if so.
It than make twice the same validation for A3 and B3; Search if the cell is contained within the cell E3.
If any of the two above is TRUE, than the whole IF is true, and it will return C3 as you need.
You didn't mention what you required in the case that the string was not found, so in my exemple, it return the value in F3 (but you could replace it with whatever).
Hope this help!


text:
Q: Loading multiple layers into QGIS Batch processing I'm trying to process multiple layers with QGIS batch processing, but I'm unable to get all the layers loaded into the batch processing input layer(s) without clicking every layer by hand.
How do I do this automatically?

A: There are different options. Use the one that fits your needs:
Add values by expression
Use Autofill... > Add values by expression and define an expression that generates an array of strings that match the layer names you want to add. If you use e.g. the variable @layers, all layers of the project will be added.
From context help:

Expected format: An array of values corresponding to each new row to
add

Calculate by expression
Using the Add values by expression option, a new line will be created for each layer. This is the difference to Calculate by expression..., where only rows that already exist are filled up with a name generated by an expression. If you have e.g. 10 rows with no layer name (new, empty rows can be generated by hitting the green + icon), you could use Calculate by expression... with an expression like 'layer_'  ||  @row_number and the row's input layer names will be filled like layer_0, layer_1, layer_2 etc.
This is best if you have a fixed number of layers that have names following a regular pattern.
Select from Open Layers
Another option is to use Autofill... > Select from Open Layers - then you can check the layers you want to add from those you have open in your project.


text:
Q: What are the different types of documents needed for software development? I am aware of Functional Requirement Document and Technical Specification Document.
However, I would like to know, what are the different documents needed for an overall Project Development.
Let's say I have a small company, and I want to build a project for another company. What are the different documents I need to submit from the start to the finish?
And where do the FRD and TSD fit in?

A: Go for the SRS in the first place. A legal written documentation is very necessary which will involve all the kinds of things that would be included in a software. It shows your professionalism.

A: Maybe these will be a good start:
http://en.wikipedia.org/wiki/Software_documentation
But I would say it all depends on the context. Different deliverables will be required for Agile projects as well as let's say RUP projects. This list should be agreed upon the target company/client..

A: For developing a perfect software following documents are mandatory in series:

*

*URS ( User Requirements Specification): The URS point wise describes all the requirements of the software.

*UI: Depending on the URS certain pages of the software are designed. This also includes error messages, pop up messages etc.

*SRS (System Requirements Specification): The SRS point wise defines system requirements depending on the URS.

*STC (System Test Cases): After the software is developed system testing is done with and recorded in STC

*UAT (User Acceptance Testing): After all system test cases are successful user acceptance testing in conducted to check if the software covers all points as mentioned in the URS and is prepared as expected

*DTL (Defect Track Log): All bugs/defects recorded during UAT/STC are mentioned in DTL so that they can be fixed

After all bugs are fixed second cycle of STC and UAT is conducted to check if everything is fine now and fulfill user expectation. And finally the software is ready to use.


text:
Q: DB Lookup in Mule - Not accepting Integrated Authentication We are trying to use DB lookup in Mule data mapper in our project, We are able to validate successful connection without integrated authentication even though when we have added sqljdbc_auth.dll in classpath as well as in the referenced library we are not able to have integrated authentication.
Any pointers to resolve this issue will be helpful. Thanks!

A: Adding if this will be helpful to any of those who came across this issue -  I finally made it working by adding JTDS drivers in the library and the below JTDS  file for integrated authentication jtds-1.2.7-dist\x64\SSO


text:
Q: Is it ok to submit the iPhone app binary with NSLog statements? I am just about to  submit my first iPhone app.
I have put lots of NSLog statements to test and debug the application .
So my question is " Is it ok to keep the NSLog statements in the source code "
and I have a doubt that whether the nslog statements slows down the total execution time or not .
thanks.

A: I used this all the time (found it somewhere):
// DLog is almost a drop-in replacement for NSLog to turn off logging for release build
//
// add -DDEBUG to OTHER_CFLAGS in the build user defined settings
//
// Usage:
//
// DLog();
// DLog(@"here");
// DLog(@"value: %d", x);
// Unfortunately this doesn't work DLog(aStringVariable); you have to do this instead DLog(@"%@", aStringVariable);
//

#ifdef DEBUG
#   define DLog(__FORMAT__, ...) NSLog((@"%s [Line %d] " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#   define DLog(...) do {} while (0)
#endif
// ALog always displays output regardless of the DEBUG setting
#define ALog(__FORMAT__, ...) NSLog((@"%s [Line %d] " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

The three20 project from Facebook has more complex way to debug or logging.

A: An app I was working on perviously had many NSLogs dumping debug to the console. We found that they hindered performance drastically on the iPhone 3G. The performance hit was noticeable on a 3GS, but not as much.
My advice would be to use a preprocessor macro and a debug preprocessor definition to conditionally use NSLogs in debug builds but not in release builds.

A: The three apps I have on the AppStore are loaded with NSLogs so I guess it's okay...

A: I've never got rid of mine :)
Some people recommend conditional compiling / compiler macros so you can make a build without any NSLog at all but I think that's too much effort for very little reward.
However, NSLogs do slow the app down (slightly) so I'd remove any ones that are directly affecting performance. Also, you might want to remove some debugging logging information to hide how you have implemented your app etc.
Hope that's helpful,
Sam

A: XCode4 offers a pretty neat solution to this - use breakpoints.
select action 'log a message' and set val = @val@ as the message,
then tick the 'automatically continue after evaluating actions' box.
Won't fit every use case, but it gives you the benefit of easy 'inspecting'
of values and guarantees they won't make it into a release.

A: I simply use a "useDebugMode" singleton int set to 0 or 1 that is stored in userPrefs (plist).  And, depending on the UUID of the iphone, I add a "Use Debug Mode: on/off" toggle to the settings screen so i can debug problems in the future with production versions.  This allows me to debug data problems (with downloaded XML) if people complain about issues with the program in the future.  I then wrap all "NSLog"s and "printf"s in
if (useDebugLog == 1)
{
     NSLog(@"debug statement");
}

This works for me...Of course, the:
 if (useDebugLog == 1)

causes some overhead that I am willing to deal with.

A: Its not a problem of using NSLog in Release. But if you put any valuable data in log other user(developer) can see that data. Like some download link etc..