text:
Q: smart card: State of non-volatile memory has changed - 0x6581 I'm using HID smart card reader 3121 to read/write smart card using APDU commands. I successfully performed the basic operations (pin verification/ read / write) on some smart cards. However, some of my cards doesn't write data successfully and return the response as following: 0x6581 Memory failure (unsuccessful writing). I check the error detail on internet and it said: 0x6581: State of non-volatile memory changed.. if anybody knows the solution to this, please let me know. Thanks

A: Unfortunately there is no generic smart card behaviour and I did not find a specific card reference in your question.
Most probable solution: The cards you tried were already used for some time and might be subjected to (possibly excessive) rewrite of the same few memory cells. The error counter of the PIN is a likely candidate, since it needs to be updated at least twice on every VERIFY command. Note, that a typical limit guaranteed by the hardware manufacturer is in the magnitude of 100k write accesses, for exact numbers ask your hardware vendor.
"State of volatile memory changed" simply means that the state of the card is no longer the same as at the start of the last command (so something might already have been updated successfully before the error occurred). SInce the memeory is starting to wear out, there is not much benefit in atttempts to clean up.


text:
Q: SVN copy only certain directories and subdirectories to a branch I have the following directory structure in trunk:
trunk
      - dir1
      - dir2
          -subdir1
          -subdir2

I want to copy dir2/subdir2 to my https://mynewbranchurl
If I do svn cp ./dir2/subdir2 https://mynewbranchurl I see subdir2 directly under mynewbranch. What should I do to get dir2/subdir2/contents in mynewbranch?
I do not want to manually create dir2 in mynewbranch.

A: You should use the --parents option for the copy command:
svn cp --parents ./dir2/subdir2 http://repourl/branches/my_new_branch/dir2/subdir2

In this way Subversion creates all intermediate directories (I am not sure if you need subdir2, please test it)

A: So let's say that http://mysvn.com/repos/branches already exists, and after the copy you want trunk/dir2/subdir2 to be located at http://mysvn.com/repos/branches/my_new_branch, such that trunk/dir2/subdir2/file.txt is located at http://mysvn.com/repos/branches/my_new_branch/file.txt.  Just do this:
svn cp ./dir2/subdir2 http://mysvn.com/repos/branches/my_new_branch
Make sure that my_new_branch does not exist before the copy operation.  If it does exist, it will place dir2 inside of the existing folder.  I think that might be what's giving you grief.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does a filtered A_N algebra give rise to a multiplicative spectral sequence? The question is pretty much in the title. It is a classical fact that a filtered dga gives rise to a multiplicative spectral sequence. It is claimed in Remark 4.1 of https://arxiv.org/pdf/1410.6728.pdf that this generalizes to filtered $A_\infty$- algebras(see the page 27 of the same for this definition). One can define a notion of filtered $A_N$-algebras for $N \in \mathbb{N}^{\geq 0}$, $N \geq 3$ where $m_i$ are only defined for $i \leq N$ and the $A_{\infty}$ equations hold for $i \leq N$ (so the multiplication is still associative on the level of homology).
Question: Is the natural spectral sequence associated to a filtered $A_N$ algebra multiplicative?
I would guess the answer is yes, but could not find a reference for this fact and there seems to be some subtleties in the literature according to this earlier post:
Multiplicative structure on spectral sequence
Motivation: It seems like this might be an efficient way to prove that some spectral sequences that arise "in nature" are multiplicative, say by equipping the relevant (co) chain complex with an $A_3$ structure.

A: For the $d_r$-differentials to be derivations, i.e., to satisfy the Leibniz rule $d_r(x \cdot y) = d_r(x) \cdot y \pm x \cdot d_r(y)$ with $x \cdot y = m_2(x \otimes y)$, it is enough to have a filtered differential graded $A_2$-algebra.  This follows from Sections 7 and 8 of Massey's 1954 paper "Products in Exact Couples", since the pairing $m_2 \colon A \otimes A \to A$ is a filtration-preserving chain map.
Assuming the Leibniz rule, if the pairing of $E_1$-terms (or $E_2$-terms) is associative and unital, then so are the induced pairings of $E_r$-terms for all greater $r$.
Aside: The "subtleties in the literature" concern exact couples that do not come from filtered chain complexes, e.g., those that arise from the homotopy groups of sequences of spectra.  If a pairing of sequences is only defined in the stable homotopy category, then it is not generally clear that there will be a corresponding product in the spectral sequence.


text:
Q: Getting the type error while selecting Values from Result of Query I was writing the logic of selecting Values from a Result of the Query and I faced an error.
I tried to tackle it by myself, but end up with no success.
What I did:
I got from the query an array of objects.
There is the array of what was got:
[
 {
 chosenDoughType: "Thin"
 chosenSize: 26
 doughTypes: (2) [{…}, {…}]
 id: "yHYRVvZlnAZ6jXG9kzI4B"
 pizzaId: "fMtMxzIkRTsHEwHsSvGvi"
 sizes: (3) [{…}, {…}, {…}]
 },
// and a couple more similar
]

And there is my code where I wanted to get the only one object with a specific id:
interface SpecType {
    id: string
    doughTypes: object[]
    sizes: object[]
    chosenDoughType: string
    chosenSize: number
    pizzaId: string
}
  const { oneSpecData, isLoading, isSuccess, isError } = useGetSpecsQuery(undefined, {
        selectFromResult: result => ({
            ...result,
            oneSpecData: result.filter((item: SpecType): boolean => {
                return item.id !== specId
            }),
        }),
    })

but I received this message error:
TS2339: Property 'filter' does not exist on type 'UseQueryStateDefaultResult<QueryDefinition<void, BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryErr
or, {}, FetchBaseQueryMeta>, never, SpecType[], "api">>'.
  Property 'filter' does not exist on type '{ error?: undefined; data?: undefined; fulfilledTimeStamp?: undefined; originalArgs?: undefined; requestId?: unde
fined; endpointName?: string | undefined; startedTimeStamp?: undefined; status: QueryStatus.uninitialized; ... 5 more ...; isUninitialized: true; } & { ...;
}'.
    55 |         selectFromResult: result => ({
    56 |             ...result,
  > 57 |             oneSpecData: result.filter((item: SpecType): boolean => {
       |                                 ^^^^^^
    58 |                 return item.id !== specId
    59 |             }),
    60 |         }),

I guess the problem is in typification, but I do not know how to tackle it to make my code work.

A: result here is the full result. With data, isSuccess and all the other properties.
You probably want to do something like
selectFromResult: result => ({
    ...result,
    data: { ...data, oneSpecData: result.data.something.filter((item: SpecType): boolean => {
        return item.id !== specId
    }),
    }

}),

but keep in mind that this will return a new object in data on every render and not a stable reference - that might lead to your application rerendering a lot more often than you'd like.
You could do better with a selector like
const selector = useCallback(data => ({
  ...data,
  oneSpecData: data.something.filter((item: SpecType) item.id !== specId)
  }), [specId])

selectFromResult: result => ({
    ...result,
    data: selector(data)
}),


text:
Q: how to get the first tweet from my twitter and display it on my webpage? Please can somebody help to get the first tweet from my twitter and display it on my website.
I am using asp.net 2.0.
Thanks

A: There are many ways to do this depending on your requirements. Personally, I have accomplished this using the Twitterizer library.
var feed = TwitterTimeline.UserTimeline(new UserTimelineOptions() {
                            CacheOutput = true,
                            CacheTimespan = TimeSpan.FromMinutes(1),
                            ScreenName = "twitter_username",
                            Count = 1
                        });
var firstPost = feed.FirstOrDefault();

The advantage of this approach is that you are not required to have a Twitter API key in order to pull the data. It doesn't get much simpler than this!
Update
After you clarified .NET 2.0 I found this .NET 2.0 Twitter API wrapper. Haven't used it myself, but it may be worth a look. Yedda Twitter C# Library
If that that library/wrapper won't do, JSON.NET also has a .NET 2.0 compatible binary.
Just a caveat, JSON.NET would be the most involved simply because the various wrappers that exist will be specialized to Twitter, whereas JSON.NET is just a general JSON parser (Twitterizer even uses it).
In my own opinion, possibly the easiest solution of all is to use jQuery to pull up the API for you. Obviously, that would be done as a client event so it would not be as "ideal" as the alternative. Still it's a the most "no-fuss" solution. Here's a blog post on calling the Twitter API with jQuery.

A: Take a look at TweetSharp (works on .NET 2.0)
This example doesn't show your tweet, but you get the idea of how easy it is.
using TweetSharp;

TwitterService service = new TwitterService();
IEnumerable<TwitterStatus> tweets = service.ListTweetsOnPublicTimeline();
foreach (var tweet in tweets)
{
    Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}


text:
Q: put same ID different rows in one line How could I put those multiple rows into one line, and the contents are in different columns:
From:
ID          |   Subject1/Catalog/Session
10868952    |   NUR/3110/D507
10868952    |   NUR/3110/D512
10868952    |   NUR/4010/D523
10868952    |   NUR/4010/HD20

To
ID       |Subject1/Catalog/Session |Subject2/Catalog/Session | Subject3/Catalog/Session   |Subject4/Catalog/Session | Subject5/Catalog/Session

10868952 |NUR/3110/D507            | NUR/3110/D512           | NUR/4010/D523              | NUR/4010/HD20           |

A: Would be best if in the future you can provide ddl and sample data. I did this for you this time.
Here is how you could do this if you know the number of elements per row. I put links in the comments of the original post to both the static and dynamic versions of this type of approach.
if OBJECT_ID('tempdb..#Something') is not null
    drop table #Something

create table #Something
(
    ID int,
    Subject1 varchar(50)
)

insert #Something
select 10868952, 'NUR/3110/D507' union all
select 10868952, 'NUR/3110/D512' union all
select 10868952, 'NUR/4010/D523' union all
select 10868952, 'NUR/4010/HD20';

with OrderedResults as
(
    select *, ROW_NUMBER() over(partition by ID order by Subject1) as RowNum
    from #Something
)

select ID
 , MAX(Case when RowNum = 1 then Subject1 end) as Subject1
 , MAX(Case when RowNum = 2 then Subject1 end) as Subject2
 , MAX(Case when RowNum = 3 then Subject1 end) as Subject3
 , MAX(Case when RowNum = 4 then Subject1 end) as Subject4
from OrderedResults
group by ID

A: Here is how you can do this as a dynamic pivot. There are a number of concepts going on here. One is a tally table. In this code it is implemented as a cte. In my actual system I have this as a view. It generates 10,000 rows with zero reads. The tally table and most of the other concepts here were learned by the immortal Jeff Moden. If you do not know what a tally table is or how they work, check out Jeff's article here. http://www.sqlservercentral.com/articles/T-SQL/62867/
I will post some code for how to do this for this example but anybody who is unfamiliar with this technique should read his article. http://www.sqlservercentral.com/articles/Crosstab/65048/
Here is a full working example of doing this as a dynamic cross tab. When you are satisfied that the sql this generates is safe feel free to uncomment the last two lines.
LAST but certainly not least. Make sure that you fully understand what this code and how it works. It is not going to be my phone that rings at 3am when something goes wrong. You are the one who will have to be there to support this code.
if OBJECT_ID('Something') is not null
    drop table Something

create table Something
(
    ID int,
    Subject1 varchar(50)
)

insert Something
select 10868952, 'NUR/3110/D507' union all
select 10868952, 'NUR/3110/D512' union all
select 10868952, 'NUR/4010/D523' union all
select 10868952, 'NUR/4010/HD20' union all
select 12345, 'asdfasdf'
declare @MaxCols int

declare @StaticPortion nvarchar(2000) =
    'with OrderedResults as
    (
        select *, ROW_NUMBER() over(partition by ID order by Subject1) as RowNum
        from Something
    )
    select ID';

declare @DynamicPortion nvarchar(max) = '';
declare @FinalStaticPortion nvarchar(2000) = ' from OrderedResults Group by ID order by ID';

with E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS
(
    SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
)

select @DynamicPortion = @DynamicPortion +
    ', MAX(Case when RowNum = ' + CAST(N as varchar(6)) + ' then Subject1 end) as Subject' + CAST(N as varchar(6)) + CHAR(10)
from cteTally t
where t.N <=
(
    select top 1 Count(*)
    from Something
    group by ID
    order by COUNT(*) desc
)

select @StaticPortion + @DynamicPortion + @FinalStaticPortion

--declare @SqlToExecute nvarchar(max) = @StaticPortion + @DynamicPortion + @FinalStaticPortion;
--exec sp_executesql @SqlToExecute


text:
Q: JavaScript: Enter value and submit text input I am trying to write a JavaScript code to enter in a bunch of grades into an online grade book. The grade book is a table with inputs:
<input type="text" maxlength="12"
class="grade-entry input--flush" tabindex="1"
data-bind="visible:!$parent.assignment.useLetterGradingScheme,
value:gradeString, disable:showDetail ||
!$parent.permissions.AssignGrades || (isGradeApproved &&
!$parent.permissions.ChangeApprovedGrades), event:
{change:$parent.onChangeGrade,focus:$parent.onFocus},
attr:{'aria-label':'Grade for ' + sortableName},
css:{'animate-saving':saving, 'success':isGradeApproved}"
aria-label="Grade for [last name], [first name] [middle initial]">

I have written a code that finds the correct input to put a students name in by accessing the aria-label attribute and comparing the first and last names. The code successfully goes through and enters the grades by:
input.value = 10.5;

However, the grade does not submit. When entering the grades manually, I have to first type the grade, and then press "Enter". After pressing "Enter", the color of the input box changes and the grade saves so that if I refresh the grade stays.
My code does not do this. After running the code, the input fields contain the grades, but when I refresh they all go away. So at the moment I have to go through, one by one, and click on the input and then press "Enter".
I have an array with all the inputs. I then find the correct index for the student. I have tried to simulate an Enter key press by:
var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$(inputs[i]).trigger(e);

where inputs is an array of all the input elements and i is the index of the correct input for the student.
Is there any way to do what I am trying to do?
EDIT
I forgot to mention; the input is not embedded inside a form or anything. It's just standalone inside a table row.
EDIT
It looks like it is an AJAX form. I'm not really familiar with AJAX, but I have added a small section of a function called $.fn.ajaxSubmit below that I found (only a small section because the whole function is really long). What is the parameter options? And if I have the options parameter correct, could I just called this function to submit it?
/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    /*jshint scripturl:true */

    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    var method, action, url, $form = this;

    if (typeof options == 'function') {
        options = { success: options };
    }

    method = this.attr('method');
    action = this.attr('action');
    url = (typeof action === 'string') ? $.trim(action) : '';
    url = url || window.location.href || '';
    if (url) {
        // clean url (don't include hash vaue)
        url = (url.match(/^([^#]+)/)||[])[1];
    }

    options = $.extend(true, {
        url:  url,
        success: $.ajaxSettings.success,
        type: method || 'GET',
        iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
    }, options);

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
    }
    ....
    ....

Recall that with my current code, I find the actual <Input> object for each student and update the value. So could I call the above function with the specified <Input> and submit whatever value I just put in the <Input>?
EDIT
I have been trying to read up on AJAX. If I have the specified <Input> object (I'll call it input1, can I just say something like:
$(input1).ajaxSubmit();

A: Pressing Enter in the input control triggers the change event, which is then processed by $parent.onChangeGrade. Instead of sending a keypress event programmatically, you can trigger the change event directly:
$(inputs[i]).trigger("change");


text:
Q: How to use an array to hold controls in form and hide/show them I'm still new at coding. I'm making a calculator but I also want a lot of other things in it. like a conversion calculator, cook book, and kanji radical dictionary in c# WindowsFormsApplication I want to change from one to the next using a comboBox so I was going to make a array with all the control I wish to hide/show
string[] numList = {"button0","button1","button2", "button3"};//this will have all number and .
for (int i = 0; i < numList.Length; i++)
{
    numList[i].Hide();
}

But it tell me there no definition for 'Hide' but when I switch numList[i] to button0 it work but I don't wish to wright the same 11 control for every time i add something to the comboBox anyway to fixes this or any other method

A: If you want to hide all Buttons then try this:
foreach (Button control in Controls.OfType<Button>())
{
    (control).Hide();
}

This iterate through all Buttons of the form and hide them. But if you want to just hide a specific buttons then you can set the Tag property of that buttons to something like OP then to hide only that Buttons:
foreach (Button control in Controls.OfType<Button>())
{
     if (control.Tag.ToString() == "OP")
     {
          (control).Hide();
     }
}

Or with linq:
foreach (Button control in Controls.OfType<Button>().Where(control => control.Tag.ToString() == "OP"))
{
     (control).Hide();
}

A: try below code
private void btnHide_Click(object sender, EventArgs e)
{
    string[] buttonList = { "button1", "button2", "button3" };
    for (int i = 0; i < buttonList.Length; i++)
    {
        Control[] ctrl = this.Controls.Find(buttonList[i], true);
        ((Button)ctrl[0]).Visible = false;
    }
}

A: You are keeping a list of strings, you should actually add the buttons in to the list in order to have the Hide method visible
Control[] numList = {button0, button1, button2, button3 };


text:
Q: How to easily render partial HTML from a string in angular js? This fiddle tries to render two partials in string form. Of course, this solution won't work (the partials are rendered as-is and not interpreted as angular templates).
From what I understand, I somehow have to use the $compile service, but I don't quite get it. For performance reasons, I would like to have each partial only compiled once and then only updated locally. Can $compile do that, and if so, how? In my case there are not many partials, not many changes to the set of partials and each partial can be very large (entire sub-page).
And no, I do not want them to be in separate files. Also, the views are lazy-loaded.
Is it maybe even possible to achieve this by inserting a new module for each such partial?
UPDATE:
Thanks to @threed, I was able to fix it all up. This is an improved version with lazy-loaded content and controller.

A: You can use the ng-include directive (see this jsfiddle)...
HTML:

JavaScript:
var app = angular.module('app', []);
var data = [
    'data1-apple',
    'data2-banana'
];
var partials = [
    {
        name: 'template1',
        content: '
{{data[0]}}
'
    },
    {
        name: 'template2',
        content: '
{{data[1]}}
'
    }
];
function MyCtrl($scope, $templateCache) {
    for(var i in partials){
        $templateCache.put(partials[i].name, partials[i].content);
    }
    $scope.partials = partials;
    $scope.data = data;
}


text:
Q: how to delete data in SQLite and listview This is my main activity call mycontact.java:
package com.example.user.ice_myemergencycontact;

import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TableRow;
import android.widget.TextView;

import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.List;

/**
 * Created by User on 20/7/2016.
 */
public class mycontacts extends AppCompatActivity {
    private GoogleApiClient client;
    //TextView viewName, viewPhone;
    //ListView viewList;
    ImageView addbtn;
    dbcontact DBcontact;
    SQLiteDatabase sqLiteDatabase;
    Cursor cursor;
    ListDataAdapter listDataAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ListView listView;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_contacts);
        addbtn =(ImageView)findViewById(R.id.addbutton);
        listView = (ListView)findViewById(R.id.listContactView);
        listDataAdapter = new ListDataAdapter(getApplicationContext(), R.layout.activity_contact_list_view);
        listView.setAdapter(listDataAdapter);
        DBcontact = new dbcontact(getApplicationContext());
        sqLiteDatabase = DBcontact.getReadableDatabase();
        cursor = DBcontact.getAllContacts(sqLiteDatabase);
        registerForContextMenu(listView);

        if (cursor.moveToFirst()){

            do {

                String name, phone;
                name = cursor.getString(0);
                phone = cursor.getString(1);
                contactdata contact = new contactdata(name, phone);
                listDataAdapter.add(contact);

            }while(cursor.moveToNext());
        }

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

        addbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mycontacts.this, mycontacts_add.class));
                finish();
            }
        });
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_pop_up, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        switch (item.getItemId())
        {
            case R.id.call:
                break;
            case R.id.edit:
                break;
            case R.id.delete:
                DBcontact.deleteItem(listDataAdapter.getItem(info.position));
                listDataAdapter.deleteItem(listDataAdapter.getItem(info.position));

                return true;
            default:
                return super.onContextItemSelected(item);
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_options, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_home:
                startActivity(new Intent(mycontacts.this, homemenu.class));
                finish();
                break;
            case R.id.menu_about:
                startActivity(new Intent(mycontacts.this, about.class));
                finish();
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }
}

This is my ListDataAdapter.java:
    package com.example.user.ice_myemergencycontact;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by User on 26/8/2016.
 */
public class ListDataAdapter extends ArrayAdapter {
    List list = new ArrayList();
    public ListDataAdapter(Context context, int resource) {
        super(context, resource);
    }

    static class LayoutHandler{
        TextView Name, Phone;
    }

    @Override
    public void add(Object object) {
        super.add(object);
        list.add(object);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        LayoutHandler layoutHandler;
        if (row == null){

            LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.activity_contact_list_view, parent, false);
            layoutHandler = new LayoutHandler();
            layoutHandler.Name = (TextView) row.findViewById(R.id.item_name);
            layoutHandler.Phone = (TextView) row.findViewById(R.id.item_phoneNo);
            row.setTag(layoutHandler);
        }
        else{
            layoutHandler = (LayoutHandler) row.getTag();
        }

        contactdata contact = (contactdata) this.getItem(position);
        layoutHandler.Name.setText(contact.getNAME());
        layoutHandler.Phone.setText(contact.getPHONE_NO());

        return row;
    }

    public void deleteItem(Object item) {
        list.remove(item);
        notifyDataSetChanged();
    }
}

This is my db handler call dbcontact.java:
package com.example.user.ice_myemergencycontact;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by User on 9/8/2016.
 */
public class dbcontact extends SQLiteOpenHelper{

    private static final String DATABASE_NAME = "CONTACT.db";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_QUERY =
            "CREATE TABLE " + contactdata.NewContact.TABLE_NAME + " (" +
                    contactdata.NewContact.NAME + " TEXT, " +
                    contactdata.NewContact.PHONE_NO + " TEXT);";

    public dbcontact(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        Log.e("DATABASE OPERATION","Database created / opened...");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_QUERY);
        Log.e("DATABASE OPERATION", "Table created...");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int aldVersion, int newVersion) {

    }

    public void addcontact(String name, String phone, SQLiteDatabase db){

        ContentValues contentValues = new ContentValues();
        contentValues.put(contactdata.NewContact.NAME, name);
        contentValues.put(contactdata.NewContact.PHONE_NO, phone);

        db.insert(contactdata.NewContact.TABLE_NAME, null, contentValues);
        Log.e("DATABASE OPERATION", "One row inserted...");
    }

    public Cursor getAllContacts(SQLiteDatabase db){

        Cursor cursor;
        String[] projections = {contactdata.NewContact.NAME, contactdata.NewContact.PHONE_NO};
        cursor = db.query(contactdata.NewContact.TABLE_NAME, projections, null, null, null, null, null);

        return cursor;
    }

    public List<contactdata> getAllRecords() {
        List<contactdata> recordList = new ArrayList<contactdata>();
        // Select All Query
        String selectQuery = "SELECT * FROM " + contactdata.NewContact.TABLE_NAME;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                contactdata retrieveContact = new contactdata();
                retrieveContact.setNAME(cursor.getString(0));
                retrieveContact.setPHONE_NO(cursor.getString(1));

                // Adding record to list
                recordList.add(retrieveContact);
            } while (cursor.moveToNext());
        }

        // return record list
        return recordList;
    }

    public void deleteItem(Object item){
        SQLiteDatabase db = this.getWritableDatabase();

        db.delete(contactdata.NewContact.TABLE_NAME, contactdata.NewContact.NAME + " = ?", new String[]{String.valueOf(item)});
        db.close();
    }
}

This is my constant call contactdata.java:
package com.example.user.ice_myemergencycontact;

/**
 * Created by User on 13/8/2016.
 */
public class contactdata {

    private String NAME;
    private String PHONE_NO;

    public contactdata(){}

    public contactdata(String NAME, String PHONE_NO){
        this.NAME = NAME;
        this.PHONE_NO = PHONE_NO;
    }

    public String getNAME() {
        return NAME;
    }

    public void setNAME(String NAME) {
        this.NAME = NAME;
    }

    public String getPHONE_NO() {
        return PHONE_NO;
    }

    public void setPHONE_NO(String PHONE_NO) {
        this.PHONE_NO = PHONE_NO;
    }

    public static abstract class NewContact
    {
        public static final String NAME = "name";
        public static final String PHONE_NO = "phone_no";
        public static final String TABLE_NAME = "user_contact";
    }
}

The problem is, I can remove the data from the listview but it is still not deleted in the database. I have found that the main problem why the data is not deleted in the database is because of this coding:
public void deleteItem(Object item){
            SQLiteDatabase db = this.getWritableDatabase();

            db.delete(contactdata.NewContact.TABLE_NAME,
                 contactdata.NewContact.NAME + " = ?",
                 new String[]{String.valueOf(item)});
            db.close();
        }

Please help me solve this problem. tq

A: try to delete db row with following thing:
String whereClause = contactdata.NewContact.NAME + "='Put Name here'";
db.delete(contactdata.NewContact.TABLE_NAME, whereClause, null);


text:
Q: How to implement import/export an sqlite data from/to excel in android I am working on an app which needs to give all architect's profile. The app is almost finished. But the final task is about having backup/restore option.
I want to Backup the data in such a file that can be viewd in excel or some simple view. And then that bakup could also be used for Restore option.

A: You could create functions for backing up. Python has a great csv library which is easy to use.
As well as easy sqlite integration.
Just create a function that Select * from tableToBackUp and each row in that select statement should be a new row in the csv
 import csv
 with open('myCSV.csv', 'wb') as csvfile:
    writer= csv.writer(csvfile, delimiter=' ',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(rowInSQLITEQuery['columnName']  + rowInSQLITEQuery['columnName2'])

A: My app is also involves exporting data. I have saved the data in a SQLite database. Then stored it to the SD Card and mailed using JavaMail API. The exported .db can be easily read using software like SQLiteBrowser which is free to download. I assume that you have exported a database as you mentioned Excel in your question.
Reply if you need help/links on exporting db files to the SD card.

A: The exact solution may depend on how you expect to offload the data from the device.
You might be looking for this: http://developer.android.com/training/basics/data-storage/files.html
In which case you would write rows from your SQLite table as though they were rows in a '.csv' file that Excel can read. The below just writes a string to a file, but you can use a loop to write rows from your database line by line instead.
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;

try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(string.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}

A FileProvider looks like a more complicated solution but might be what you want if you're trying to read the file on the device from another app.
http://developer.android.com/training/secure-file-sharing/setup-sharing.html

A: The short answer, there is no straight way. What I did for my app is use 3rd party library  to create excel document and I actually created a sheet for every table and wrote them table by table.
There is no "convert method"  out there that will do that
The other option is to copy the  .db file from internal storage to backup folder and copy it back.. But  no excel involved


text:
Q: Linq groupby return unique group I have list of records, each record has Name and Rounds.
Rounds is a concatenated numbers seperated by "-"

How can i group by name and display only unique rounds, also count the number of rounds and display the first round and last round

Here is what i tried,
 data.GroupBy(d => d.Name)
.Select(
    g => new
    {
        Name = g.Key,
        Rounds = g.Concat(s => s.Rounds),
        NumberOfRounds =  g.Concat(s => s.Rounds).Split('-').Count,
        FirstRound = //??,
        LastRound = //??,
    });

A: I would start by projecting your entity to a name and collection-of-rounds pair. That will then be easier to work with. For example:
var query = results
    .Select(d => new { d.Name, Results = d.Rounds.Split('-').Select(int.Parse).ToList() })
    .GroupBy(
        d => d.Name, (key, values) => new {
            Name = key,
            Rounds = values.SelectMany(v => v.Rounds)
                           .Distinct()
                           .OrderBy(x => x)
                           .ToList()
       });

With the rounds available as a list, I don't see that there's much point in having NumberOfRounds, FirstRound and LastRound as properties, as you can just use Rounds.Count, Rounds.First(), Rounds.Last(). The important part is transforming the data into a more useful format as early as possible.
If you really need that in properties, it's easy enough to project:
// query as before, but with
.Select(x => new {
    x.Name,
    x.Rounds,
    NumberOfRounds = x.Rounds.Count,
    FirstRound = x.Rounds.First(),
    LastRound = x.Rounds.Last()
});

A: First you need to extract the rounds to numeric values. After that, it is easy.
var data = ...;
var groupedData = data
    .GroupBy(x => x.Name)
    .Select(x => new {
        Name = x.Key,
        Rounds = string.Join("-", x.Select(z => z.Rounds))
            .Split('-')
            .Distinct()
            .Select(z => int.Parse(z))
            .OrderBy(z => z)
            .ToArray()
    })
    .Select(x => new {
        x.Name,
        Rounds = string.Join("-", x.Rounds),
        NumberOfRounds = x.Length,
        FirstRound = x.Min(),
        LastRound = x.Max()
    })
    .ToArray();


text:
Q: PHP strtr does not work at all Even when i type
echo strtr("-äåö-", "äåö", "xxx");

it does not work properly it outputs this >xxx¥x¶<, however when i use example below it does not translate nothing at all it keeps original mambo jumbo.
If i type in form ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑŐŰÜÒÓÔÕÖØÝߟàáâãäåçèéêëìíîïñòóôõőöøšűùúûüýÿž and click translate it outpputs the same string and æ œ does not translate at all.
<form method="POST">
    <input style="width:500px;" type="text" name="first_name" />
    <input style="width:500px;" type="text" name="last_name" />
    <input type="submit" name="submit" value="translate" />
</form>

<?php

    $dict = array(
                    "Æ" => "AE",
                    "æ" => "ae",
                    "Œ" => "OE",
                    "œ" => "oe"
                 );

    $first = strtr($_POST['first_name'], $dict);
    $last  = strtr($_POST['last_name'], $dict);

    $first = strtr($first,
                          "ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑŐŰÜÒÓÔÕÖØÝߟàáâãäåçèéêëìíîïñòóôõőöøšűùúûüýÿž",
                          "AAAAAACEEEEIIIINOUUOOOOOOYSYaaaaaaceeeeiiiinooooooosuuuuuyyz");

    $last  = strtr($last,
                          "ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑŐŰÜÒÓÔÕÖØÝߟàáâãäåçèéêëìíîïñòóôõőöøšűùúûüýÿž",
                          "AAAAAACEEEEIIIINOUUOOOOOOYSYaaaaaaceeeeiiiinooooooosuuuuuyyz");

    echo $first." --- ";
    echo $last;
?>

even when i added on top of code
foreach ($_POST as $key => $value) {
    $POST[$key] = iconv(mb_detect_encoding($_POST["first_name"]), "ASCII//TRANSLIT", $POST[$value]);
}

and paste AAAAAACEEEEIIIINOUUOOOOOOYSYaaaaaaceeeeiiiinooooooosuuuuuyyz it comes out like this yAyAyAyEyEyIyIyNyUyOyOyOyYyYyayauaueyeyiyiynyoyoyoysyuuuyyyzy�y�y�y�y�y�y�y�y�y�y�y�y�y�y�y�y�y�uay�yuuzu�y�y�y�y�y�y�u�
Never mind since no one knows why it does not work i just used str_replace and str_ireplace very successfully without need for any concerns about encoding.
EDIT: my bad encoding does matter for str_replace  too. i used on html page
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

A: strtr with the function prototype
string strtr ( string $str , string $from , string $to )

does only work reliable with single-byte encodings (e.g. ISO-8859-1).
header("Content-Type: text/plain; charset=ISO-8859-1");
$str = "\x2d\xe4\xe5\xf6\x2d"; // ISO-8859-1: -äåö-
$from = "\xe4\xe5\xf6";        // ISO-8859-1: äåö
$to = "\x78\x78\x78";          // ISO-8859-1: xxx
dump($str, "ISO-8859-1");  // length in octets: 5
dump($from, "ISO-8859-1"); // length in octets: 3
dump($to, "ISO-8859-1");   // length in octets: 3

print strtr($str, $from, $to); // -xxx-

Output:
-: 2d
ä: e4
å: e5
ö: f6
-: 2d
length (encoding: ISO-8859-1): 5
length in octets (8-bit-byte): 5

ä: e4
å: e5
ö: f6
length (encoding: ISO-8859-1): 3
length in octets (8-bit-byte): 3

x: 78
x: 78
x: 78
length (encoding: ISO-8859-1): 3
length in octets (8-bit-byte): 3

-xxx-

If you use a multi-byte chars e.g. from UTF-8 you'll likely get a messed up string:
header("Content-Type: text/plain; charset=UTF-8");
$str = "\x2d\xc3\xa4\xc3\xa5\xc3\xb6\x2d"; // UTF-8: -äåö-
$from = "\xc3\xa4\xc3\xa5\xc3\xb6";        // UTF-8: äåö
$to = "\x78\x78\x78";                      // UTF-8: xxx
dump($str, "UTF-8");  // length in octets: 8
dump($from, "UTF-8"); // length in octets: 6
dump($to, "UTF-8");   // length in octets: 3

// > If from and to have different lengths, the extra characters in the longer
// > of the two are ignored. The length of str will be the same as the return
// > value's.
// http://de.php.net/manual/en/function.strtr.php

// This means that the $from-string gets cropped to "\xc3\xa4\xc3" (16 bit of
// the first char [ä] and the first 8 bit of the second char [å]):
strtr($str, $from, $to) === strtr($str, "\xc3\xa4\xc3", $to); // true
print strtr($str, $from, $to); // -xxx�x�-

Output:
-: 2d
ä: c3a4
å: c3a5
ö: c3b6
-: 2d
length (encoding: UTF-8): 5
length in octets (8-bit-byte): 8

ä: c3a4
å: c3a5
ö: c3b6
length (encoding: UTF-8): 3
length in octets (8-bit-byte): 6

x: 78
x: 78
x: 78
length (encoding: UTF-8): 3
length in octets (8-bit-byte): 3

-xxx�x�-

For multibyte encodings like UTF-8 you have to use the second function prototype:
string strtr ( string $str , array $replace_pairs )

header("Content-Type: text/plain");
$str = "-äåö-"; // UTF-8 \x2d\xc3\xa4\xc3\xa5\xc3\xb6\x2d
$replace_pairs = array(
    "ä" /* UTF-8 \xc3\xa4 */ => "x",
    "å" /* UTF-8 \xc3\xa5 */ => "x",
    "ö" /* UTF-8 \xc3\xb6 */ => "x"
);
print strtr($str, $replace_pairs); // -xxx-

If the encodings do not match you have to convert them with iconv:
header("Content-Type: text/plain");
$str = "\x2d\xe4\xe5\xf6\x2d"; // ISO-8859-1 -äåö-
$str = iconv("ISO-8859-1", "UTF-8", $str);
$replace_pairs = array(
    "ä" /* UTF-8 \xc3\xa4 */ => "x",
    "å" /* UTF-8 \xc3\xa5 */ => "x",
    "ö" /* UTF-8 \xc3\xb6 */ => "x"
);
print strtr($str, $replace_pairs); // -xxx-

function dump:
// outputs the hexvalue for each char for the given encoding
function dump($data, $encoding) {
    for($i = 0, $len = iconv_strlen($data, $encoding); $i < $len; ++$i) {
        $char = iconv_substr($data, $i, 1, $encoding);
        printf("%s: %s\n", $char, bin2hex($char));
    }
    printf("length (encoding: %s): %d\n", $encoding, $len);
    printf("length in octets (8-bit-byte): %d\n\n", strlen($data));
}

A: Did you try mb_strstr: http://php.net/manual/en/function.mb-strstr.php
This function supports Multibyte character encoding.

A: It sounds like you may have competing encodings. If your browser is submitting UTF8 but your file is saved in (e.g.) 8859-1, your characters will not match and the translate will fail. In addition, looking at the doc page, several comments suggest using utf8_decode() on your input string first. It is possible that utf8_decode() by itself will do what you want.
UTF8 is a multi-byte encoding (actually, it's a variable-byte encoding). Characters such as ÷ or ï have a Unicode code point beyond 256 which needs to be encoded into two or more bytes, both above 128, that identify the character. I suspect you are going to have to learn more about Unicode. There is another explanation at utf8_encode.
Edit: It's been a while since I've wrestled with encodings. You should look at iconv() for more general purpose re-encoding.


text:
Q: Error: AttributeError: 'powerOfTwo' object has no attribute 'x' I'm trying to write a python program to check if the positive integer divisable by 2 and return false or true with using classes and functions. I'm getting this error: AttributeError: 'powerOfTwo' object has no attribute 'x'. Can you help me with fixing this?
class powerOfTwo():

    def __init__(self, x):

        self.x = x

    def user(self):

        x = int(input("Enter a number: "))

    def check(self):

        if self.x == 1:

            return False

        elif (x > 0) and (x % 2 == 0):

            return True

        else:

            return False

a = powerOfTwo(5)

powerOfTwo().user()

powerOfTwo().check()

A: Your logic of checking power of two is not correct.
Try to think about what will be the output for value 6?
Also your code returns False for value 1, but 1 is a power of 2.

You can do something like this:
class powerOfTwo():
    def __init__(self, x = 1):    # Provide a defaul value otherwise powerOfTwo().user() and powerOfTwo().check() will not work.
        self.x = x

    def user(self):               # Use self.x instead of x
        self.x = int(input("Enter a number: "))

    def check(self):              # Use self.x instead of x
        if self.x == 0:
            return False

        while self.x != 1:        # Updated the logic.
            if self.x % 2 != 0:
                return False

            self.x = self.x // 2

        return True


text:
Q: How to find element in a component? I am wondering how can I find element inside a component using Renderer?
In angular1 I would just go:
link = (scope, element, attributes) => {
            var outsideBox = element.find('.outside-box');
}

Which returns me a

Any pointers are more than welcome!

A: I would use Plunker - BrowserDomAdapter
import {Component,ElementRef} from 'angular2/core';
import {BrowserDomAdapter} from 'angular2/platform/browser';
//import { DOM } from 'angular2/src/platform/dom/dom_adapter';
@Component({
    selector: 'my-app',
    template: `

    <button (click)="add()" class="btnClass">Add New Element</button>
    `
})

export class AppComponent {
 dom:BrowserDomAdapter;
  constructor(el:ElementRef) {
    this.dom = new BrowserDomAdapter();
    console.log(el);
  }
  add(){

      console.log( this.dom.query(".btnClass"));
      this.dom.addClass(this.dom.query(".btnClass"),"test");
      console.log(this.el);

  }
}

*
*
https://angular.io/docs/ts/latest/api/platform/browser/BrowserDomAdapter-class.html

A: I would use its selectRootElement method:
import {Component,Renderer} from 'angular2/core';

@Component({
  selector: 'my-app',
  template: `

Click

  `
})
export class AppComponent {
  constructor(private renderer:Renderer) {
  }

  onClick() {
    var outsideBox = this.renderer.selectRootElement('.outside-box');
  }
}

See this plunkr: https://plnkr.co/edit/9OJ9kr?p=preview


text:
Q: Trying to make an Excel usage graph user-proof I'm a stationary engineer in a large commercial facility. Recently we had a spike in our utility billing, and my boss wanted me to improve our tracking of usage so that we don't get surprised again.
We've got nightly meter readings going back roughly fifty years (no, I haven't dug into the really old ones!) but no one ever put them into a spreadsheet or other format to make daily tracking easier. I sat down and entered the most recent month's data into a template I created with the hope of replicating it month by month and having an ongoing track of usage. So far, so good.
The problem comes when some readings are missed. It's a big facility and the midnight man has a host of other things to do. So, if a water reading is missed, I show negative consumption of four hundred million gallons one day and a positive spike of four hundred million ten thousand gallons the next day. I can deal with the former by using the MAX(0, C12-C11) function, but I haven't found a good way to deal with the latter.
I can manually edit things like this, yes, but the goal is to turn it over to be used by some guys who don't all have a great degree of computer literacy. What I'd like to do, if possible, is to find a way to straight-line average over missing data points and reflect that in the graph by not showing the point markers. I can still deal with things such as meter replacements or rollovers by manual editing, but missing data is a routine enough problem that I'd like to be able to handle it automatically.
I should also mention that I'm largely unfamiliar with Excel; I've got much more time using LibreOffice Calc and Quattro Pro. I couldn't seem to figure out the requesters to do exactly what I want with the line graph. In addition to the daily usage, I also want to display high and low outside temperatures along with building occupancy on the same graph. Advice as to where to turn for a tutorial would be appreciated.
I wanted to post the spreadsheet as it stands now but I can't find a way to attach a file to this question...so some preliminary advice is welcome as well.
Editing To Add image of current spreadsheet:
Selection of Spreadsheet showing data table and pivot table

A: Max test misses multiple error paths

MAX ignores the validity of values in each cell instead relying on a limited error path where the difference between the values is less than zero.
When you use 'MAX' to test if C12-C11 is > 0, the result is '0' ALWAYS, AND ONLY IF 'C12 NOT GREATER THAN C11' regardless of the values (positive, negative) of 'C12' and 'C11'.  Because of this narrow scope, it doesn't work for your second use case as well as others:
----------------------------
Tests using 'MAX(0,C12-C11)'
----------------------------
C11=160,C12=189
   • MAX(0,19)        # 19  (Succeeds)

C11=189,C12=0
   • MAX(0,-189)      #  0  (Succeeds)

C11=0,C12=0
   • MAX(0,0)         #  0  (Succeeds)

C11=0,C12=189
   • MAX(0,189)       #  189 (Fails, '0' wanted)

C11=(-189),C12=181
   • MAX(0,370)       #  370 (Fails, '0' wanted, see note 1)

C11=("oops"),C12=181
   • MAX(0,#VALUE!)   #  #VALUE! (Fails, '0' wanted, see note 2)

NOTES:

*

*Your test will fail to return '0' for real numbers that are <> 0 but outside of a reasonable range unless the difference is < 0.

*Your current test will error with #VALUE! on a non-numeric entry such an accidental text entry in your data set.  This could be a text entry, a number that is stored as text "1849", or seemingly empty cell with hidden formatting such as a single quote (').   instead of nothing, you will generate errors when using it in a subtraction or any other calculations.

Test validity of both values

If we assume from your use case that you only want to perform the calculation 'C12-C11' in cases where both values are numbers greater than zero, then the test would be 'AND(C11>0,C12>0)=true' prior to your formula:
-----------------------------
Tests using 'AND(C11>0,C12>0'
-----------------------------

C11=160,C12=189
   • AND(true,true)   # true

C11=189,C12=0
   • AND(true,false)  # false

C11=0,C12=0
   • AND(false,false) # false

C11=0,C12=189
   • AND(false,true)  # false

C11=(-189),C12=181
   • AND(false,true)  # false

Issue with text values.
Excel has idiosyncrasies when comparing different data types, they can vary depending on the formulae being used.  This allows text values to slip through and trigger the same error to which your MAX approach was exposed (note 2 above).
Specific to this use case:
    # In Excel, '[text] > [number]' is 'true'
      • oops > 1,000,000 is true
      • ' > 0 is also 'true'

    C11=("oops"),C12=181
       • AND(true*,true)   # true (*C11 should be false)

   #  I suggest 2 ways to resolve this below (IFERROR vs ISNUMBER).

Adapt formula to include test

Error Handling
Because:
[number (or text)] - [text] = #VALUE! error
and
[text] - [number (or text)] = #VALUE! error

We can resolve that by including an ISNUMBER test of each of C11 and C12 to confirm they are numbers:
AND(ISNUMBER(C11),ISNUMBER(C12))

or we can alternatively skip the additional two tests and handle the error if triggered using the IFERROR function:
IFERROR([formula],[value_if_error])

The choice you make (and other approaches that are available) will depend on how you adapt the formula to your needs and what other calculations you are using.
Also, if C12 and C11 themselves refer to data elsewhere in the workbook you may choose to perform number checking / error checking earlier in the process.
-----------------------------------------
Formulae based on test 'AND(C11>0,C12>0)'*
-----------------------------------------

* Includes IFERROR handling or ISNUMBER check

If both C11 and C12 must be positive numbers:
   • =IFERROR(IF(AND(C11>0,C12>0),C12-C11,0),0)
       or
   • =IF(AND(C11>0,ISNUMBER(C11),C12>0,ISNUMBER(C12)),C12-C11,0)
       or
   • =IF(AND(ISNUMBER(C11),ISNUMBER(C12)),
         IF(AND(C11>0,C12>0,
            C12-C11,
            0),
         "custom error msg")

added C12 must always be greater than C11:
   • =IFERROR(IF(AND(C11>0,C12>0,C12>C11),C12-C11,0),0)
       or
   • =IF(AND(C11>0,ISNUMBER(C11),C12>0,ISNUMBER(C12)),C12>C11),C12-C11,0)

added C12 must always be at least 10% bigger than C11:
   • =IFERROR(IF(AND(C11>0,C12>0,C12>C11/.9),C12-C11,0),0)
       or
   • =IF(AND(C11>0,ISNUMBER(C11),C12>0,ISNUMBER(C12),C12>C11/.9),C12-C11,0)

and so on...

Hope that helps :-)

.
.
.
.
This may also be of interest
Error handling is sometimes intentionally triggered by people when they want to pass a value that needs (or is expected) to be a real number.
Trigger Error if not Real Number
1/(1/[myValue])  (Excludes '0' from Real Numbers)
# value=(Number<>0)
   • 1/(1/[myValue]) = [myValue]

# value=0 (or equivalent)
   • 1/(1/[myValue]) = #DIV/0!   (error)

# value=Non-Number (e.g. text)
   • 1/(1/[myValue]) = #VALUE!    (error)

[myValue]*1  (Includes '0')
# value = (Number < > = 0)
   • [myValue] * 1 = [myValue]

# value=Non-Number (e.g. text)
   • [myValue] * 1 = #VALUE!        (error)

These tests can be combine with IFERROR to pass a [myValue] or [alternateValue] and can be nested in other formulae:
=IFERROR(1/(1/[myValue]),[alternateValue])
=IFERROR([myValue]*1,[alternateValue])


text:
Q: Counting data in ACCESS database? I have 3 records in my database (database type : microsoft access ) . they are personal information of 3 Customers.
Now in interface I have button in the name of "Count Customers" . when I push it I want it to count records and says How many record(s) I have in Database ! .  for exmple here I have 3 , it must say you have 3 records or 3 cutomers .
I use Visual Studio 2008 , language is C# . my database is Microsoft Access Database .

A:    using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Test.mdb"))
        using (OleDbCommand Command = new OleDbCommand(" SELECT count (CustomerId) from Customer as total", con))
        {
            con.Open();
            OleDbDataReader DB_Reader = Command.ExecuteReader();
            if (DB_Reader.HasRows)
            {
                DB_Reader.Read();
                int id = DB_Reader.GetInt32(0);
            }
        }

A: this simple query will return the total number of rows in a table
SELECT COUNT(*) FROM Table_name

A: using (OledbConnection cn = new OledbConnection())
            {
                cn.ConnectionString = OledbConnectionString;
                cn.Open();

                OledbCommand commandRowCount = new OledbCommand("SELECT COUNT(*) FROM [TABLENAME]", cn);
                countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
                MessageBox.Show("Starting row count: " + countStart.ToString());
            }


text:
Q: "UITextField isNaturallyRTL" My iphone app crashes with the following error message:

2010-07-26 16:27:30.402 Nav[814:207]
  * -[UITextField isNaturallyRTL]: unrecognized selector sent to instance
  0x3947fe0 2010-07-26 16:27:30.403
  Nav[814:207] * Terminating app due
  to uncaught exception
  'NSInvalidArgumentException', reason:
  '*** -[UITextField isNaturallyRTL]:
  unrecognized selector sent to instance
  0x3947fe0'

I can't find the text isNaturally RTL in my program. Any ideas on how to find the bug?

A: It seems that isNaturallyRTL is an (undocumented) NSString method. At least NSString responds to it.
This may mean that you assign a UITextField to some variable, where you should put in an NSString instead.
BTW: 0x3947fe0 is the pointer to the UITextField that should be an NSString, so if you're totally lost, try to find out which UITextField has that address (e.g. by a dumb NSLog("tf X: 0x%x",tfx);)

A: I found the problem. It was in this line of code:
[tempValues setObject:textFieldBeingEdited forKey:tagAsNum];

I changed it to the following:
[tempValues setObject:textFieldBeingEdited.text forKey:tagAsNum];

and that's what fixed it.

A: It's because your UITextField object is somehow assigned to a variable/property which is not supposed to be a UITextField.
It can happen in many different ways.

*

*You might have connected the IB outlet incorrectly. Check your nib in the Interface Builder to see your UITextField is not connected to something strange.

*You might have just assigned an UITextField to a variable of a different type. In that case, the compiler should have given you a warning. Correct your code and remove all the warnings.

*You might have not correctly done retain/release. Do "build and analyze", and remove all warnings.


text:
Q: Can this Fourier transformed function be transformed into partial fraction? Hi I'm self learning stochastic process, I've come across a problem and found
$$H=\frac{2+j(2w)}{(1-w^2)+j(2w)} \\
|H(iw)|^2=\frac{2^2+(2w)^2}{(1-w^2)^2+(2w)^2} \\$$
In attempt to find the power spectral density with partial fraction,
$$S_y(w)=|H(iw)|^2 S_x(w)=\frac{2^2+(2w)^2}{(1-w^2)^2+(2w)^2} \frac{3}{2^2+w^2} \\
= \frac{12(1+w^2)}{(w^2+1)^2(w^2+4)}
= \frac{A}{(w^2+1)^2}+\frac{B}{(w^2+4)} \\
A = \frac{12(1+w^2)}{w^2+4} = 0, w=\pm\sqrt{-1}= \pm j \\
B=\frac{12(1+w^2)}{(w^2+1)^2} = \frac{12(1-4)}{(-4+1)^2}=\frac{-36}{9}=-4, w^2+4=0, w=\pm2j$$
Is complex $w$ even making any sense? Because I thought w is part of $iw$, then it should be real if that makes sense.

A: $$\frac{12(1+w^2)}{(w^2+1)^2(w^2+4)}=\frac{12}{(w^2+1)(w^2+4)}=\frac{4}{w^2+1}-\frac{4}{w^2+4}$$


text:
Q: NSNumberFormatterCurrencyStyle Driving me insane I'm trying to get a currency calculator to work, and I've stumbled accross a problem I do not know how to solve.
The problem is that when I normally type into the textfield I can obviously type over the 100.20, the problem arises when I try to do this using buttons.
Whole numbers work fine but as soon as I click on the dot button it put's the dot after the 100.20 so I end up with 100.20. and whatever I click after it.
If I don't use NSNumberFormatter it works fine as well.
Here are the code snippets :
-(IBAction)buttonDigitPressed:(id)sender
{
    mainNumber = 100.20;
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
    mainField.stringValue = [numberFormatter stringFromNumber:[NSNumber numberWithFloat: mainNumber]];
}

if(!userInTheMiddleOfEnteringDecimal)
{
    userInTheMiddleOfEnteringDecimal = YES;
    mainField.stringValue= [mainField.stringValue stringByAppendingString:@"."];
}


text:
Q: Can I get a property from a collection using Linq in a more elegant way than this? I have a collection of items
List<Thing> MyListOfThings

I get this list from a db using PetaPoco like this
var MyListOfThings = db.Fetch<Thing>();

Then I want to get the value of a property like this:
otherObject.Value = MyListOfThings.SingleOrDefault(q => q.UniqueID == otherValue).SomeProperty;

I think this is a very elegant solution, the problem is if the collection does not contain an object with the UniqueID of otherValue. Then it goes BANG with a null reference exception.
The solution I have been using is
otherObject.Value = MyListOfThings.SingleOrDefault(q => q.UniqueID == otherValue) == null
  ? ""
  : MyListOfThings.SingleOrDefault(q => q.UniqueID == otherValue).SomeProperty;

This works, Resharper still complains that there is a possible NullReferenceException, but I guess that's just because it doesn't count the first line as a nullcheck.
However... this looks ugly and is so unDRY that it's dripping...
Is there a more elegant solution for this?

A: It looks like SomeProperty is a string, and you want string.Empty as a fallback value. If that's right, then you can do
otherObject.Value =
    (from thing in MyListOfThings
    where thing.UniqueID == otherValue
    select thing.SomeProperty)
        .SingleOrDefault() ?? string.Empty;

The LINQ expression is an IEnumerable<string> containing the SomeProperty value of all Things having the relevant UniqueID; this might be an empty enumerable.

A: Use a where statement first and use DefaultIfEmpty to set your fallback value
otherObject.Value = MyListOfThings
    .Where(q => q.UniqueID == otherValue)
    .Select(q => q.SomeProperty)
    .DefaultIfEmpty("")
    .SingleOrDefault();

A: Do it like this
MyListOfThings object = MyListOfThings.where(q => q.UniqueID == otherValue).FirstOrDefault();

This will either get an object of my thing or null
if(!object.IsNull) // null check so wont Bang
{
//assign value here
}


text:
Q: typescript - difficulty "extending" IAngularStatic I asked a question similar to this not long ago and got a great deal of help, but even with the answer there I'm struggling with this code.
I've written - in typescript - a small service to use with google api (gapi) and an interface to go with it, listed as this in my code;
gapiService.ts
class GoogleAuthenticationService implements IGoogleAuthenticationService {
   // ...
}

interface IGoogleAuthenticationService extends ng.IServiceProvider { }

Now, I can use them like this, but for OCD purposes, I want to attach them to the angular namespace/module to be part of the ng loading. So I could call them...
ng.GoogleAuthenticationService
ng.IGoogleAuthenticationService

I thought this would work, but I keep getting the error that it either can't find them or some other error. I've gone through the following list of errors...

*

*Property 'GoogleAuthenticationService' does not exist on type 'IAngularStatic'

*Module 'angular' has no exported member 'IGoogleAuthenticationService'

*An export assignment cannot be used in a module with other exported elements.
Any idea how to achieve what I'm aiming for? It's driving me batty.
gapiAuth.d.ts
declare module 'angular' {
    interface IGoogleAuthenticationService{}
    var GoogleAuthenticationService: GoogleAuthenticationService
}

A:
ng.GoogleAuthenticationService
  ng.IGoogleAuthenticationService

Just wrap them in angular namespace:
namespace angular {
  class GoogleAuthenticationService implements IGoogleAuthenticationService {
     // ...
  }

  interface IGoogleAuthenticationService extends ng.IServiceProvider { }
}


text:
Q: JPA how to sync unmanaged entity object with database (call by value) Following Problem:
Relation:  |Shop| --1--------n--> |Products|
So I have an Entity named shop that can have many products.
I developed a function called void addProductToShop(Shop shop, Product product);
It looks something like this:
public void addProductToShop(Shop shop, Product product)
{
    entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();

    shop = entityManager.merge(shop);
    shop.getProductList.add(product);

    entityManager.getTransaction().commit();
    entityManager.close();
}

Everything works fine and is written correctly to the database.
The Problem is, that the two Entities are not updated in my Application code.
So after calling addProductToShop(shop, product); you have to update the two variables shop and product because they don't have the latest changes (because of callByValue).
But as consumer of this function I assume that my parameters are changed after the call and not only the database.
How can I achieve this without requesting an update of shop and product after each function call.
Are there any best practices?
Thanks,
Alex

A: I think entityManager.refresh(Object) is what you need to call for both shop and product.

A: I got it.
My mistake was that I should first change the entities from the parameters and then do a merge...
So the parameters have the same state as the merged entities have.
Little error in reasoning...
Regards,
Alex


text:
Q: SQL if recordset does not match error condition, Access This code is working for modifying a textbox if there is variable IntVer has a  value in it. IntVer is the variable holding the textbox version. But if the user initiates the add command from an empty text box they get a type mismatch error. Which in fact is a SQL error because it can't match the string because the IntVer does not exist so it result in an error because it can't find the record.
How can I prevent this from happening? I thought adding the recordcount <>0 would do it but the SQL command executes before the recordcount.
So the error makes sense to me, I just don't know how to fix it.
Thank you for your help,
Maxine
Private Sub cmdMod_Click()
  Dim strSelSQL As String

  strSelSQL = "SELECT EmpSWDetails.AssetID, EmpSWDetails.[" & SOFT & "] FROM EmpSWDetails " _
                & "WHERE (((EmpSWDetails.AssetID)='" & Asset & "') AND ((EmpSWDetails.[" & SOFT & "])='" & IntVer & "'));"

  Dim con As ADODB.Connection
  Set con = Application.CurrentProject.Connection

  Dim rs As ADODB.Recordset
  Set rs = New ADODB.Recordset

  rs.Open strSelSQL, con, adOpenDynamic, adLockPessimistic

  If rs.RecordCount <> 0 Then
      rs.Fields(SOFT) = SELVER   'update version to new version
  Else
      rs!AssetID = Asset
      rs.Fields(SOFT) = SELVER
  End If

  rs.Update
  rs.Close
End Sub

A: Nz() is probably your best option if you want it to catch only this specific Error (using Nz will handle both "object=Null and object="" at the same time making the if statement shorter, more efficient, and more readable).
Private Sub cmdMod_Click()
  Dim strSelSQL As String

  If Nz(intVer,"")="" then
     msgbox "Please enter data.", vbOkOnly, "Required"
  Else
      strSelSQL = "SELECT EmpSWDetails.AssetID, EmpSWDetails.[" & SOFT & "] FROM EmpSWDetails " _
                & "WHERE (((EmpSWDetails.AssetID)='" & Asset & "') AND ((EmpSWDetails.[" & SOFT & "])='" & IntVer & "'));"

      <the rest of your code>
  End If
End Sub

If you want it to catch all errors you can implement an error handler. Something like the following
  Private Sub cmdMod_Click()
  Dim strSelSQL As String
  On Error GoTo Error_Handler

  <code>

  Exit_Error_Handler:
       Exit Sub

  Error_Handler:
       Msgbox "Error: " & Err.Number & vbCrLf & "Description: " & Err.Description
       'You can also put code to handle specific errors
       'For Example: If Err.Number = 13 Then Msgbox "Data required in Textbox", vbOkOnly, "Required" End If
           GoTo Exit_Error_Handler
  End Sub

Error handling in Access is the the only thing I can think of where I would ever endorse the use of a GoTo statement.


text:
Q: Sorting bars by count in ggplot This code makes a barplot in ggplot:
ggplot(res, aes(x=TOPIC,y=count), labs(x=NULL)) +
  scale_y_continuous(limits=c(0,130),expand=c(0,0)) +
  scale_x_discrete("",labels=c("ANA"="Anatomy","BEH"="Behavior","BOUND"="Pop boundaries",
                           "CC"="Climate change","DIS"="Disease","EVO"="Evolution",
                           "POPSTAT"="Pop status","POPABU"="Pop abundance",
                           "POPTR"="Pop trend","HARV"="Harvest","HAB"="Habitat",
                           "HABP"="Habitat protection","POLL"="Pollution",
                           "ZOO"="Captivity","SHIP"="Shipping","TOUR"="Tourism",
                           "REPEC"="Reprod ecology","PHYS"="Physiology","TEK"="TEK",
                           "HWC"="HWC","PRED"="Predator-prey","METH"="Methods",
                           "POPGEN"="Pop genetics","RESIMP"="Research impact",
                           "ISSUE"="Other","PROT"="Protection","PA"="Protected areas",
                           "PEFF"="Protection efficiency","MINOR"="Minor","REV"="Review")) +
  theme_bw(base_size = 14) +
  theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.3)) +
  geom_bar(stat='identity') +
  ggtitle("Peer-reviewed papers per topic")

Here's the data frame:
structure(list(TOPIC = structure(c(20L, 18L, 21L, 3L, 9L, 4L,
7L, 8L, 17L, 27L, 29L, 2L, 24L, 30L, 16L, 28L, 10L, 22L, 12L,
5L, 1L, 19L, 6L, 25L, 11L, 23L, 14L, 15L, 13L, 26L), .Label = c("ANA",
"BEH", "BOUND", "CC", "DIS", "EVO", "HAB", "HABP", "HARV", "HWC",
"ISSUE", "METH", "MINOR", "PA", "PEFF", "PHYS", "POLL", "POPABU",
"POPGEN", "POPSTAT", "POPTR", "PRED", "PROT", "REPEC", "RESIMP",
"REV", "SHIP", "TEK", "TOUR", "ZOO"), class = "factor"), count = c(9,
7, 13, 5, 23, 35, 27, 5, 118, 0, 9, 22, 29, 46, 27, 12, 9, 44,
70, 40, 24, 19, 26, 2, 4, 17, 4, 10, 86, 31)), .Names = c("TOPIC",
"count"), row.names = c(NA, -30L), class = "data.frame")

How do I get the bars sorted by count, decreasing or increasing?


text:
Q: GMSCameraUpdate zooming out to the max distance rather than around a path I'm working on an app for iOS and i'm running into some trouble with the google maps sdk.
My app gets a list of coordinates and draws a polyline between them as well as start and finish markers. At the moment, this all occurs successfully. What i'm trying to do now is update the camera to contain the entire path. Here is my code currently:
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[[sharedModel startNode] nodeLocation].latitude
                                                        longitude:[[sharedModel startNode] nodeLocation].longitude
                                                             zoom:18];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];

GMSMutablePath *path = [GMSMutablePath path];
for (int i = 0; i < [results count]; i++)
{
    [path addCoordinate:[[results objectAtIndex:i] nodeLocation]];
}
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeWidth = 10;
polyline.map = mapView_;

GMSMarker *marker1 = [[GMSMarker alloc] init];
marker1 = [GMSMarker markerWithPosition:[[results objectAtIndex:0] nodeLocation]];//[[sharedModel startNode] nodeLocation]];
marker1.title = @"Start";
marker1.map = mapView_;

GMSMarker *marker2 = [[GMSMarker alloc] init];
marker2 = [GMSMarker markerWithPosition:[[results lastObject] nodeLocation]];
marker2.title = @"Finish";
marker2.map = mapView_;

GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithPath:path];

GMSCameraUpdate *update = [GMSCameraUpdate fitBounds:bounds];

[mapView_ moveCamera:update];
self.view = mapView_;

When I run this, my markers and polyline all show up in the right locations but the map is zoomed out to the max distance it can go (although it is centered over the path). Any advice?

A: Is this code in loadView? Try maybe creating the map view in loadView, but updating the camera later, maybe in viewDidLoad or viewWillAppear.
Based on the answer to this question I'm thinking that maybe the camera update methods don't work properly from loadView:
Fit bounds not working as expected


text:
Q: Prevent subclassing an abstract class interface in C++ I provide a SDK to my users, allowing them to write DLLs in C++ for expanding the software.
The SDK headers mostly contain interface class definitions. These class are of two types:

*

*Some that the user must subclass and implement

*Some that are wrappers to core classes, passed by the app to the DLL functions as pointers, which can then be used as arguments by the DLL code for calling core functions. These interfaces should not be subclassed by the user and passed to the core functions, as they expect a specific core subclass.

I write in the manual the interfaces that should not be subclassed, and only used through pointers on objects provided by the app. But at some places, it's too tempting to subclass them in the SDK if you do not read the manual.
Would it be possible to prevent subclassing some interfaces in the SDK headers?

A: As long as the client doesn't need to use the pointer for anything but
passing it back into your DLL, you can just use a forward declaration;
you can't derive from an incomplete type.  (When faced with a similar
case recently, I went whole hog, and designed a special wrapper type
based on void*.  There's a lot of casting in the interface code, but
there's no way the client can do much other than pass the value back to
me.)
If the classes in question implement an interface which the client must
also use, there are two solutions.  The first is to change this,
replacing each of the member functions with a free function which takes
a pointer to the type, and just provide a forward declaration.  The
second is to use something like:
class InternallyVisibleInterface;

class ClientVisibleInterface
{
private:
    virtual void doSomething() = 0;
    ClientVisibleInterface() = default;
    friend class InternallyVisibleInterface;
protected:      //  Or public, depending on whether the client should
                //  be able to delete instances or not.
    virtual ~ClientVisibleInterface() = default;
public:
    void something();
};

and in your DLL:
class InternallyVisibleInterface : public ClientVisibleInterface
{
protected:
    InternallyVisibleInterface() {}

    //  And anything else you need.  If there is only one class in
    //  your application which should derive from the interface,
    //  this is it.  If there are several, they should derive from
    //  this class, rather than ClientVisibleInterface, since this
    //  is the only class which can construct the
    //  ClientVisibleInterface base class.
};

void ClientVisibleInterface::something()
{
    assert( dynamic_cast<InternallyVisibleInterface*>( this ) != nullptr );
    doSomething();
}

This offers two levels of protection: first, although derivation
directly from ClientVisibleInterface is possible, it's impossible for
the resulting class to have a constructor, and so it cannot be
instantiated.  And secondly, if the client code does cheat somehow,
there will be a runtime error if he does so.
You probably don't need both protections; one or the other should
suffice.  The private constructor will result in a compile time error,
rather than a runtime one.  On the other hand, without it, you don't
even have to mention the name of InternallyVisibleInterface in the
distributed headers.

A: As soon as a developper has a developpement environment, he can do almost anything, and you should not even try to control that.
IMHO the best you can do is to identify the limit between the core application and the extension DLLs and ensure that objects received from those DLLs are or correct class, and abort with a distinctive message if they are not.
Using RTTI and typeid is generally frowned upon because it is generally the sign of a bad OOP design : in normal use case, calling virtual method is enough to have proper code invoked. But I think it can safely be considered in your use case.


text:
Q: Flask-JWT responce error 500 on server turnoff
Whenever i turn off server, and on again and try to access route with
  previous token without login into app, it gives me 500 internal server
  error instead of 'Authentication failed'. Is there any solution for
  this.

@app.route('/secret_page', methods=['GET'])
@jwt_required
def secret_page():
    print "secret page"
    return jsonify({'Success': True})

error is

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>

Internal Server Error

The server encountered an internal error and was unable to complete your request.  Either the server is overloaded or there is an error in the application.

A: Just a guess, but try setting PROPAGATE_EXCEPTIONS = True in your flask app config. Or look at using flask_jwt_extended, which handles this for you, and is still actively maintained. Flask_jwt which has been abandoned for a while now (full disclosure, I'm the author or flask_jet_extended).

A: The likely culprit is another Python extension, namely flask_restful, which is impacting the default Flask error handling. This error will also happen with flask_jwt_extended which was offered as a solution in the original answer.
If indeed you are using flask_restful, then alter your initialization code as so:
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'my_secret'
app.config['PROPAGATE_EXCEPTIONS'] = True

# configure Flask App with Flask RESTFUL API
api = Api(app)

# configure Flask App with JWT support
jwt = JWTManager(app)

Now the 500 error will no longer occur.


text:
Q: Newlines are not correctly put into intent I am trying to send plaintext copied from email/web to my application vi ACTION_SEND intent for futher processing. What bothers me is the fact that new lines are not correctly sent with the text.
For example when I have a list of items with each item on a new line, mark them and send them to my app via share option then EXTRA_TEXT of the sent intent will have all items in one line separated by one whitespace.
Source:
item1
item2
EXTRA_TEXT:
item1 item2
How ever if I copy list of items which are separated by two lines (double br between items in emails source) then EXTRA_TEXT contains items seperated by newlines.
How can I get exactly what I see in the email application or browser? Is there any other way to pass the text to intent and keep all the formating? I tried to change mimeType of my intent filter to text/html but then my application is not even listed as option where to send selected data.
Piece of code (just testing):
    if (intentAction.equals(Intent.ACTION_SEND)) {
        Bundle bundle = intent.getExtras();
        Log.d("Intent_Extra:", bundle.getString(Intent.EXTRA_TEXT));
        BufferedReader reader = new BufferedReader(new StringReader(bundle.getString(Intent.EXTRA_TEXT)));
        try {
            String str;
            while((str = reader.readLine()) != null) {
                Log.d("Item:", str);
            }

Thanks for any suggestions.


text:
Q: Unit-test testing for class equality I'm adding some unit tests to a project and want to have a test that checks that the array returned from a method is immutable so I created the following unit test:
- (void)testReturnedObjectIsOfTypeImmutableArray
{
    XCTAssertEqualObjects([NSArray class],
                          [[NSArray reverseArray:self.array] class],
                          @"NSArray should be returned");
}

However this fails because the object being returned is of class "__NSArrayI" instead of "NSArray".
I can't work out how to adapt the above to have "_NSArrayI" be acceptable where as receiving "_NSArrayM" or "NSMutableArray" should be unacceptable.

A: As suggested in the answer to
How to get classname in objective c Like 'NSString', you could use classForCoder instead of class. Example:
NSArray *a = @[@"foo"];
NSMutableArray *b = [a mutableCopy];

NSLog(@"a class: %@", [a class]); // -> __NSArrayI
NSLog(@"b class: %@", [b class]); // -> __NSArrayM
NSLog(@"a classForCoder: %@", [a classForCoder]); // -> NSArray
NSLog(@"b classForCoder: %@", [b classForCoder]); // -> NSMutableArray

So this test should give the expected results:
- (void)testReturnedObjectIsOfTypeImmutableArray
{
    XCTAssertEqualObjects([NSArray class],
                          [[NSArray reverseArray:self.array] classForCoder],
                          @"NSArray should be returned");
}

A: Testing for class equality is a problem with class clusters.
Use isKindOfClass:[NSArray class] to check whether the object is a subclass of NSArray and then check if it responds to selector @selector(addObject:) to see if it's mutable.
BOOL isArray = [self.array isKindOfClass:[NSArray class]];
BOOL isMutable = [self.array respondsToSelector:@selector(addObject:)];
XCTAssertTrue(isArray && !isMutable, @"...");

A: _NSArrayI is an NSArray, so if your reverseArray is returning a NSArray, it should work.


text:
Q: javascript D8 engine version 3.14 I have an exam which mandates the use of 3.14 D8 javascript compiler.Can anyone point me out to where I can get Javascript d8 version 3.14.I searched a lot and I can't find it in the archives too???

A: You can download and build V8, see https://github.com/v8/v8/wiki/Building%20with%20Gyp; then you can find the V8 shell d8 in ./out/Release/d8
The 3.* tags are still available:
$ git co 3.14.
3.14.0      3.14.1.2    3.14.3      3.14.5.1    3.14.5.4    3.14.5.8
3.14.0.1    3.14.1.3    3.14.4      3.14.5.10   3.14.5.5    3.14.5.9
3.14.1      3.14.1.4    3.14.4.1    3.14.5.2    3.14.5.6
3.14.1.1    3.14.2      3.14.5      3.14.5.3    3.14.5.7

So if you check out one of those tags and build, you'll have a 3.14 d8. I don't know, if the build instructions are still the same though. Are you sure that you must use such an old version?


text:
Q: Is R a compiled language? I can't find it anywhere on the web (and I don't want to install it). Is the R language a compiled language? How fast does it run a pre-written script? Does it do any kind of compilation, or just execute instructions line by line?

A: I've often rewritten R code in C++ and made it run 100x faster.  Looping is especially inefficient in R.

A: R is generally an interpreted language. However, package compiler offers bytecode compilation that can improve performance. You can also call compiled code from R.
In terms of how fast, it depends on what you are trying to do and how you are trying to do it. Some looping operations can be very slow. However, in many cases, with well written code, the performance of R scripting is determined by the speed of the underlying internal C-based libraries and system memory read-write speeds, and so R is about as fast as anything else.

A: In most cases R is an interpreted language that runs in a read-evaluate-print loop.  There are numerous extensions to R that are written in other languages like C and Fortran where speed or interfacing with native libraries is helpful.


text:
Q: CKEditor is not rendered when running capybara tests with js enabled CKEditor is not rendered in browser when running capybara tests for some reason. In development and production modes - everything is OK. CKEditor is precompiled, init part with CKEDITOR_BASEPATH is also present. All other js stuff used on the page works properly.
I use this gem in my app - https://github.com/galetahub/ckeditor
CKEDITOR.replace('editor1'), when I run it from console, hides original textarea also, but editor is not shown (I get only empty space on the place of textarea). And there are no errors in browser's console.
UPDATE:
I use sinon (https://github.com/travisjeffery/sinon-rails) to set fake time:
window.clock = sinon.useFakeTimers(<%= Time.now.to_i * 1000 %>)

When I remove this code - CKEditor works properly, but this code is needed to make js and ruby time the same. How can I make CKEditor work properly without removing sinon?

A: It is happening because you probably have some timeout somewhere that is halting javascript execution and so editor is not being loaded
you are using sinon for some of your use, which uses delay so then you should use sinon before you start rendering ckeditor, or after ckeditor is rendered


text:
Q: How to print ASCII value of 2 characters? I'm trying to print ASCII value of "\t" i.e escape sequence.
But my program only prints the ASCII value of "\" i.e ASCII value will be 92.
Is there any way to print ASCII value of 2 characters ?
Help would be really appreciated.I have included my code below.
#include<stdio.h>

main()

{

    char b=0;

    printf("Enter any character to print it's ASCII value : ");

scanf("%c",&b);

printf("The ASCII value of '%c' is %d",b,b);

return 0;

}

A: Capture input of backslash and handle it as a separate input. A switch can be used to print the result for the escaped characters.
#include <stdio.h>

int main( void) {
    char b=0;

    printf("Enter any character to print it's ASCII value : ");

    if ( 1 == scanf(" %c",&b)) {
        if ( b == '\\') {//read a backslash
            if ( 1 == scanf(" %c",&b)) {
                switch ( b) {
                    case 't' :
                        printf("The ASCII value of '\\t' is %d\n", '\t');
                        break;
                    case '\\' :
                        printf("The ASCII value of '\\' is %d\n", '\\');
                        break;
                    default :
                        printf ( "not handled yet\n");
                }
            }
        }
        else {
            printf("The ASCII value of '%c' is %d\n",b,b);
        }
    }

    return 0;
}

Output
Enter any character to print it's ASCII value : \t
The ASCII value of '\t' is 9
Enter any character to print it's ASCII value : \\
The ASCII value of '\' is 92
To get the code for a backslash, two backslashes must be entered

A: This code might help you understand what is going on here:
#include <stdio.h>

const char* escaped(int ch) {
    switch (ch) {
    case '\t': return "tab";
    case '\n': return "newline";
    case '\r': return "carriage return";
        // continue with other escaped characters
    default: return "not escaped";
    }
}

int main()
{
    char b = 0;
    printf("Enter any character to print it's ASCII value : ");
    scanf("%c", &b);
    printf("The ASCII value of '%c' is %d and is also known as: %s\n", b, b, escaped(b));
}

Just to be really clear, for a tab, at the keyboard you just press the tab key.  You do not enter the string "\t".  The string "\t" will be interpreted as 2 characters: '\' and 't'.
The \ escape code is something you would use in writing strings in your C code.
For example, if you type the string "trying" into some C source code, then you are entering the stream of characters:  t r y i n g but if you type the string: "\trying" then the first character is indicating that this is an escaped character and is a convenient way to indicate that you really wanted a tab followed by the characters: r y i n g.
With the above code, if you enter "\t" scanf is only getting from stdin, one character at a time, so it just takes the first character, the backslash (start of an escape sequence), and will print out:
Enter any character to print it's ASCII value : \t
The ASCII value of '\' is 92 and is also known as: not escaped

the 't' character is still in the input stream and the program has not handled this character.
scanf does not interpret "\t" as a tab but as the character stream \ followed by t.  That is causing your confusion.
You will experience some problems in running this code.  For example, you want to try backspace, which is \b or decimal 8 value.  scanf will probably ignore it and assume you are attempting to backspace a previous character.  But for other escaped characters such as tab character and newline it will work.
Have a read of this: https://en.wikipedia.org/wiki/Escape_character

A:  #define INV       (EOF -1)

int z = 0, tmp = INV;
char buff[6] = "\\0";
while (1)
{
    if (tmp == INV)
        z = getchar();
    else
    {
        z = tmp;
        tmp = INV;
    }
    if (z == EOF || tmp == EOF) break;
    if (z == '\\')
    {
        tmp = getchar();
        switch (tmp)
        {
        case 't':
            z = '\t';
            tmp = INV;
            break;
        case 'b':
            z = '\b';
            tmp = INV;
            break;
        case 'r':
            z = '\r';
            tmp = INV;
            break;
        case 'n':
            z = '\n';
            tmp = INV;
            break;

            // add here anothere ones
        default:
            break;
        }
    }
    printf("Char \\0%03o - '%c'\t\t has the ascii code of %03d decimal 0x%02X hexadecimal\n",  z, z < 32 ? ' ' : z, z, z);
}


text:
Q: Run another script after reloading the page with jquery I have a requirement which needs to load after reloading the page with Jquery. Below is the code.
$("a[id='gobutton']").click(function(e)) {
  location.reload();
  somefunc();
});
function somefunc() {
  alert("run my script"); }

A: After you run location.reload() your code is gone. You cant run anything after it.
You would need to pass an argument to the page to run the function.
let param = new URLSearchParams(location.search);
$("a[id='gobutton']").click(function(e)) {
  location.href = '?somefunc=true'
});

if(param.get('somefunc'){
  somefunc()
}
function somefunc(){}


text:
Q: load contact photo into listview android I'm having problems setting my ImageView in my ListView to a contact image. I've tried every so-called "solution" from the developer website to here on SO, but none of them seem to work.
This is my CustomAdapter class that populates my ListView:
http://pastebin.com/ABeK9nmT
This is my activity holding the listview:
http://pastebin.com/FcBDprfG
Its important to know that the activity holds a listview with unmovable objects around it.
The problem when I run the code is that only the default photo registers and no contacts are shown.
When the activity is ran, LogCat shows this for each of the 6 contacts:
W/Resources(5997): Converting to string: TypedValue{t=0x12/d=0x0 a=3 r=0x7f080015}
I receive no errors whatsoever. does anyone understand what I may be doing wrong?
Please, No copy and paste coding from other SO "solutions." I've tried them all, and they were either for lower APIs, copied from another answer to get points, or missing too many pieces of data. I'm using 2.3.3 which uses Contacts.Contract.

A: I would like to recommend few things and also the solution which you may try and let me know if it still fails.
1) You are using SMS custom providers for your application which may fail if user updates his OS to 4.0 or above as when I tried they dint work in them.
2) It will be better if you try querying all the custom providers not in getView() as it will speed up the process and listview.
3) I feel the problem with your code is when you are trying to fetch contact image, which is little bit typical as I implemented earlier and doesnt turns out as mentioned in blog, dont know why.
4) Now the solution flow:

*

*You have the telephone number for which you want to query.

*Now we will take that number and query the Phone Book Content Providers for Name.

*If name is not null we may proceed in getting that particular ID of number(Check if you can directly fetch ID and do it without fetching name)

*If contactId is not null fetch the picture and put it on your ListView.

Do not forget to place null checks and follow the code as mentioned, if fails let me know.
5) The Codes:
Get contact name:
/**
 * Method used to fetch CONTACT NAME FOR CONTACT NUMBER
 *
 * @param number   :: Contact Number
 * @param context  :: Activity context
 * @return         :: returns CONTACT-NAME for CONTACT NUMBER
 */
private String getContactNameFromNumber(String number, Context context)
{
    String contactName = null;
    Uri contactUri = null;
    String[] projection = null;
    String selection = null;
    Cursor cursorContactId = null;

    /*
     * Defining URI, Projection and Selection elements
     */
    contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    projection = new String[]{Contacts._ID,Contacts.DISPLAY_NAME};
    selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " = " + number;

    /*
     * Cursor iterator to fetch
     * particular ID
     */
    try
    {
        cursorContactId = context.getContentResolver().query(contactUri, projection, selection, null, null);
        while (cursorContactId.moveToNext())
        {
            contactName = cursorContactId.getString(cursorContactId.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        cursorContactId.close();
    }

    if(contactName != null)
    {
        return contactName;
    }
    else
    {
        return null;
    }
}

Get Contact ID(If name not null):
/**
 * Fetching Contact from a Number
 * @param number    - For which specific Id is required
 * @param context   - current context
 * @return          - ID as String
 */
private String getContactIdFromNumber(String number, Context context)
{
    String contactId = null;
    Uri contactUri = null;
    String[] projection = null;
    String selection = null;
    Cursor cursorContactId = null;

    /*
     * Defining URI, Projection and Selection elements
     */
    contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    projection = new String[]{Contacts._ID};
    selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " = " + number;

    /*
     * Cursor iterator to fetch
     * particular ID
     */
    try
    {
        cursorContactId = context.getContentResolver().query(contactUri, projection, selection, null, null);
        while (cursorContactId.moveToNext())
        {
            contactId = cursorContactId.getString(cursorContactId.getColumnIndex(ContactsContract.Contacts._ID));
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        cursorContactId.close();
    }

    if(contactId != null)
    {
        return contactId;
    }
    else
    {
        return null;
    }
}

Finally load contact image(If ID not null. Pass id & photo_id same ID value. This code taken is from SO after searching various links):
/**
 * Fetching contact picture from PhoneBook if available
 * @param contentResolver   - Current Content Resolver context
 * @param id                - Specific Contact Id as retrieved
 * @param photo_id          - Same as Contact Id
 * @return                  - Contact Byte Array if present or null
 */
private byte[] loadContactPhoto(ContentResolver contentResolver, String id, String photo_id)
{
    byte[] result = null;
    byte[] photoBytes = null;

    /*
     * Step 1 : Directly fetching with contactId or execute Step 2
     */
    Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id));
    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
    /*
     * Execute only if stream is not null
     */
    if (input != null)
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try
        {
            int next = input.read();

            while (next > -1)
            {
                bos.write(next);
                next = input.read();
            }

            bos.flush();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        result = bos.toByteArray();

        return result;
        // return BitmapFactory.decodeStream(input); // Open if want to return as Bitmap
    }
    else
    {
        Log.d("PHOTO","first try failed to load photo");
    }

    /*
     * Step 2: Image not fetched directly, fetching through traversing
     */
    Uri photoUri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, Long.parseLong(photo_id));
    Cursor cursorImageFetch = contentResolver.query(photoUri, new String[] {ContactsContract.CommonDataKinds.Photo.PHOTO}, null, null, null);

    try
    {
        if (cursorImageFetch.moveToFirst())
            photoBytes = cursorImageFetch.getBlob(0);
    }
    catch (Exception e)
    {
        e.printStackTrace();

    } finally {

        cursorImageFetch.close();
    }

    if (photoBytes != null)
    {
        return photoBytes;
        //return BitmapFactory.decodeByteArray(photoBytes,0,photoBytes.length); // Open if want to return as Bitmap
    }
    else
    {
        Log.d("PHOTO","Picture of the contact not available");
        return getByteArray();
    }

}


text:
Q: Catch data from open.window blocked by chrome I need to open an authentication window..
On load, I'm calling window.open
(Pay attention that there is no user's click to trigger the window.open)
In Chrome, if window.open wasn't triggered by a user action, popup is blocked. there is an icon in the URL saying that popup has been blocked: .
If user clicks on this icon the popup will open but window.open returns null. So there is no way to link the window.open to the opener
I would like to send the token to the opener on close.
Is there a way to get the opened window for that use case?

A: Seems I did it wrong.
I simply add a listener to localStorage
window.addEventListener('storage', function (e) {
  if (e.key === "access_token" && e.newValue)
    store.dispatch('onLoggedIn', e.newValue)
  else if(!e.key)
    store.dispatch('onTokenInValid', e.newValue)
})

In The popup I'm setting the access_token into localStorage and the opener listening to it


text:
Q: dynamic column referencing- greenplum I am trying to dynamically reference multiple column names in a query, and I am confused on how to achieve the same. Below, I am stating the problem situation and any tips on how to achieve this is highly appreciated. Thanks in advance
Problem statement:
I have a column reference table which contains the following attributes: Colname, colvalue, description. for reference purposes lets name this table Tablename:colref
I have a standard table: Tablename: Tasks
Now using colref I want to exclude certain records from the Tasks table
for ex. if there is an entry in colref table such as below- all records in Tasks table having the same value for that column should be excluded.
Colname:TaskType
Colvalue:Open
description: Excludes open tasks

Any tips on how to achieve the same?
Table Tasks:
 TaskID TaskName    Tasktype    TaskStatus  TaskOwner   Description
    1   abc         SR          New         jim         desc1
    2   xyz         SR          WIP         john        desc2
    3   qwe         CR          New         dave        desc3
    4   rty         SR          Closed      mike        desc4
    5   yui         CR          Closed      paul        desc5

Table: Colref
ColName    ColValue include  description
TaskStatus  New     true     all new tasks are included
Tasktype    CR      true     all CR tasks are included

Result table:
TaskID  TaskName    Tasktype    TaskStatus  TaskOwner   Description
   1    abc         SR          New         jim         desc1
   3    qwe         CR          New         dave        desc3
   5    yui         CR          Closed      paul        desc5

Basically I want to include only those conditons that are mentioned in the ColRef table. in this case only those thats that are New or are of type CR.
Any suggestions?


text:
Q: Accessing Local Network with VLC Media Player Server - Windows 7 64 Home
Remote receiver - Lubuntu 19.04
I am able to stream media from the Windows 7 server to Android and iOS apps over the Local Network with excellent results. However, Lubuntu 19.04 seems to be posing difficulties. I installed samba but still had authentication problems. Not sure what to put down for "Domain." The online tips for samba look pretty complicated.
Any quick, simple tips on how to make this work? I am not asking about streaming individual files one at a time but rather, about how to access the server file system from the remote, choose a file remotely and then stream it.