问:
Set minimum value or column randomly where minimum values are same
I have a problem with minimum value. Here in the below table, d1, d2, d3 values are minimum values. When SQL min() or least() functions are used, it will always result left side first (perhaps I am wrong) means d1 column here.

My question is : Is there any possibility to set least value or least column randomly among d1, d2 or d3. I want to say here, for every execution time, least_column will be changed where values are same.

Table formal

```<code>id  date                    name    d1  d2  d3  d4  least_value     least_column
1   2017-02-10T09:00:00Z    bimal   1   1   1   4   1               d1
</code>```

```<code>select f.*,
       (case ff.least_column
             when 'd1' then d1
             when 'd2' then d2
             when 'd3' then d3
             when 'd4' then d4
        end) as least_value,
        ff.least_column
from formal f cross join
     (select least(d1, d2, d3, d4) as least_value,
             (case least(d1, d2, d3, d4)
                   when d1 then 'd1'
                   when d2 then 'd2'
                   when d3 then 'd3'
                   when d4 then 'd4'
              end) as least_column
      from formal
     ) ff;
</code>```

SQL Fidle here

答:
You are relying on a small row structure which limits the ability to randomize. I suggest you "unpivot" the data to produce more rows and then you can get a more random result. Note order by rand() is fine for small result sets/tables but not for large sets.

You will need to visit this SQL Fiddle and click run to see any "randomness"

```<code>CREATE TABLE formal
    (`id` int, `date` datetime, `name` varchar(5), `d1` int, `d2` int, `d3` int, `d4` int)
;

INSERT INTO formal
    (`id`, `date`, `name`, `d1`, `d2`, `d3`, `d4`)
VALUES
    (1, '2017-02-10 09:00:00', 'bimal', 1, 1, 1, 1);
</code>```

Query 1:

```<code>select
*
from (
      select id, date, name, d1 colvalue, 'd1' colsource from formal union all
      select id, date, name, d2         , 'd2'           from formal union all
      select id, date, name, d3         , 'd3'           from formal union all
      select id, date, name, d4         , 'd4'           from formal
    ) p
inner join (
        select id, least(d1, d2, d3, d4) as least_value from formal
      ) lv on p.id = lv.id
where colvalue = least_value # correction here
order by rand()
limit 1
</code>```

Results:

```<code>| id |                 date |  name | colvalue | colsource | id | least_value |
|----|----------------------|-------|----------|-----------|----|-------------|
|  1 | 2017-02-10T09:00:00Z | bimal |        1 |        d2 |  1 |           1 |
</code>```

For a multi-row result, one per id:

```<code>select
    *
from (
      select
            p.*
          , lv.least_value
          , @row_num :=IF( @prev = p.id, @row_num + 1, 1)AS RowNumber
          , @prev := p.id
      from (
            select id, date, name, d1 colvalue, 'd1' colsource from formal union all
            select id, date, name, d2         , 'd2'           from formal union all
            select id, date, name, d3         , 'd3'           from formal union all
            select id, date, name, d4         , 'd4'           from formal
          ) p
      inner join (
              select id, least(d1, d2, d3, d4) as least_value from formal
            ) lv on p.id = lv.id
      cross join (
          select @row_num := 0, @prev := null
          ) vars
      where colvalue = colvalue
      order by p.id, rand()
    ) d
where rowNumber = 1
;
</code>```

result

```<code>| id |                 date |  name | colvalue | colsource | least_value | RowNumber | @prev := p.id |
|----|----------------------|-------|----------|-----------|-------------|-----------|---------------|
|  3 | 2017-02-10T09:00:00Z | suman |        1 |        d3 |           1 |         1 |             3 |
|  1 | 2017-02-10T09:00:00Z | bimal |        1 |        d1 |           1 |         1 |             1 |
|  2 | 2017-02-10T09:00:00Z |  amal |        1 |        d2 |           1 |         1 |             2 |
</code>```

see this revised sqlfiddle

Body:
I have a problem with minimum value. Here in the below table, d1, d2, d3 values are minimum values. When SQL min() or least() functions are used, it will always result left side first (perhaps I am wrong) means d1 column here.

My question is : Is there any possibility to set least value or least column randomly among d1, d2 or d3. I want to say here, for every execution time, least_column will be changed where values are same.

Table formal

id  date                    name    d1  d2  d3  d4  least_value     least_column
1   2017-02-10T09:00:00Z    bimal   1   1   1   4   1               d1

select f.*,
       (case ff.least_column
             when 'd1' then d1
             when 'd2' then d2
             when 'd3' then d3
             when 'd4' then d4
        end) as least_value,
        ff.least_column
from formal f cross join
     (select least(d1, d2, d3, d4) as least_value,
             (case least(d1, d2, d3, d4)
                   when d1 then 'd1'
                   when d2 then 'd2'
                   when d3 then 'd3'
                   when d4 then 'd4'
              end) as least_column
      from formal
     ) ff;

SQL Fidle here

Body:
You are relying on a small row structure which limits the ability to randomize. I suggest you "unpivot" the data to produce more rows and then you can get a more random result. Note order by rand() is fine for small result sets/tables but not for large sets.

You will need to visit this SQL Fiddle and click run to see any "randomness"

CREATE TABLE formal
    (`id` int, `date` datetime, `name` varchar(5), `d1` int, `d2` int, `d3` int, `d4` int)
;

INSERT INTO formal
    (`id`, `date`, `name`, `d1`, `d2`, `d3`, `d4`)
VALUES
    (1, '2017-02-10 09:00:00', 'bimal', 1, 1, 1, 1);

Query 1:

select
*
from (
      select id, date, name, d1 colvalue, 'd1' colsource from formal union all
      select id, date, name, d2         , 'd2'           from formal union all
      select id, date, name, d3         , 'd3'           from formal union all
      select id, date, name, d4         , 'd4'           from formal
    ) p
inner join (
        select id, least(d1, d2, d3, d4) as least_value from formal
      ) lv on p.id = lv.id
where colvalue = least_value # correction here
order by rand()
limit 1

Results:

| id |                 date |  name | colvalue | colsource | id | least_value |
|----|----------------------|-------|----------|-----------|----|-------------|
|  1 | 2017-02-10T09:00:00Z | bimal |        1 |        d2 |  1 |           1 |

For a multi-row result, one per id:

select
    *
from (
      select
            p.*
          , lv.least_value
          , @row_num :=IF( @prev = p.id, @row_num + 1, 1)AS RowNumber
          , @prev := p.id
      from (
            select id, date, name, d1 colvalue, 'd1' colsource from formal union all
            select id, date, name, d2         , 'd2'           from formal union all
            select id, date, name, d3         , 'd3'           from formal union all
            select id, date, name, d4         , 'd4'           from formal
          ) p
      inner join (
              select id, least(d1, d2, d3, d4) as least_value from formal
            ) lv on p.id = lv.id
      cross join (
          select @row_num := 0, @prev := null
          ) vars
      where colvalue = colvalue
      order by p.id, rand()
    ) d
where rowNumber = 1
;

result

| id |                 date |  name | colvalue | colsource | least_value | RowNumber | @prev := p.id |
|----|----------------------|-------|----------|-----------|-------------|-----------|---------------|
|  3 | 2017-02-10T09:00:00Z | suman |        1 |        d3 |           1 |         1 |             3 |
|  1 | 2017-02-10T09:00:00Z | bimal |        1 |        d1 |           1 |         1 |             1 |
|  2 | 2017-02-10T09:00:00Z |  amal |        1 |        d2 |           1 |         1 |             2 |

see this revised sqlfiddle


来源: stackexchange

问:
Scroll in recyclerview scrolls to bottom of view instead of top
I'm using a RecyclerView that displays pages from a book. I have an EditText  box that takes you to a page in the book. The only problem is that when it scrolls to the page of the book sometimes it will scroll to the top of the page and sometimes to the bottom. I think this has something to do with the RecyclerView and it not loading the view for the page before i scroll to it. I want it to always scroll to the top of a page but I'm not sure of the best way to go about it.

Here is the relevant code

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

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

        EditText editText = (EditText) findViewById(R.id.page);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_GO) {
                    int p = Integer.valueOf(v.getText().toString()) - 1;
                    scrollToPage(p);
                    handled = true;
                }
                return handled;
            }
        });

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        // specify an adapter (see also next example)
        mAdapter = new MyAdapter(pages);
        mRecyclerView.setAdapter(mAdapter);

    }

    //*******************RECYCLERVIE***************************************8//
    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
        private String[] mDataset;
        // Provide a reference to the views for each data item
        // Complex data items may need more than one view per item, and
        // you provide access to all the views for a data item in a view holder
        public class ViewHolder extends RecyclerView.ViewHolder {
            // each data item is just a string in this case
            public TextView mTextView;
            public TextView pageNumber;
            public ViewHolder(View v) {
                super(v);
                mTextView = (TextView) v.findViewById(R.id.info_text);
                pageNumber = (TextView) v.findViewById(R.id.page_number);
            }
        }

        // Provide a suitable constructor (depends on the kind of dataset)
        public MyAdapter(String[] myDataset) {
            //my Dataset is an array with 4 members making up the 4 pages//
            mDataset = myDataset;
        }

        // Create new views (invoked by the layout manager)
        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                       int viewType) {
            // create a new view
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.cards, parent, false);
            // set the view's size, margins, paddings and layout parameters
            ViewHolder vh = new ViewHolder(v);
            return vh;
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            // - get element from your dataset at this position
            // - replace the contents of the view with that element
            holder.mTextView.setText(mDataset[position]);
            int page = position + 1;
            holder.pageNumber.setText("" + page);

        }

        // Return the size of your dataset (invoked by the layout manager)
        @Override
        public int getItemCount() {
            return mDataset.length;
        }
    }

    //******SCROLL TO TOP BUTTON************//
    public void scrollToTop(View v){
        mLayoutManager.scrollToPosition(0);
    }

    //*******************SCROLL TO SELECTED PAGE***********//
    public void scrollToPage(int p){
        mLayoutManager.scrollToPosition(p);
    }

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- A RecyclerView with some commonly used attributes -->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="GO TO TOP"
            android:onClick="scrollToTop"
            android:layout_gravity="bottom|left"/>

        <EditText
            android:id="@+id/page"
            android:layout_width="50dp"
            android:layout_height="20dp"
            android:layout_gravity="bottom|center_horizontal"
            android:imeOptions="actionGo"
            android:inputType="number"
            android:background="@color/cardview_light_background"/>

    </LinearLayout>
</RelativeLayout>
</code>```

cards.xml

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

<!-- A CardView that contains a TextView -->
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="300dp"
    android:layout_height="500dp"
    android:layout_gravity="center"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:id="@+id/info_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/frayedpaper"
        android:text="@string/body" />

    <TextView
        android:id="@+id/page_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:text="page"/>

</android.support.v7.widget.CardView>
</code>```

答:
I've run into this problem myself before, and I found that calling LayoutManager.scrollToPositionWithOffset(position, 1) instead of simply LayoutManager.scrollToPosition(position) solved it for me.

Unfortunately, I don't really know why this works. It seems that the one-pixel offset changes the layout manager's calculations somehow; calling scrollToPositionWithOffset(position, 0) didn't work for me. Fortunately, over-scrolling by one pixel wasn't noticeable in my app.

ContentLicense: CC BY-SA 3.0

Body:
I'm using a RecyclerView that displays pages from a book. I have an EditText  box that takes you to a page in the book. The only problem is that when it scrolls to the page of the book sometimes it will scroll to the top of the page and sometimes to the bottom. I think this has something to do with the RecyclerView and it not loading the view for the page before i scroll to it. I want it to always scroll to the top of a page but I'm not sure of the best way to go about it.

Here is the relevant code

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

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

        EditText editText = (EditText) findViewById(R.id.page);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_GO) {
                    int p = Integer.valueOf(v.getText().toString()) - 1;
                    scrollToPage(p);
                    handled = true;
                }
                return handled;
            }
        });

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        // specify an adapter (see also next example)
        mAdapter = new MyAdapter(pages);
        mRecyclerView.setAdapter(mAdapter);

    }

    //*******************RECYCLERVIE***************************************8//
    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
        private String[] mDataset;
        // Provide a reference to the views for each data item
        // Complex data items may need more than one view per item, and
        // you provide access to all the views for a data item in a view holder
        public class ViewHolder extends RecyclerView.ViewHolder {
            // each data item is just a string in this case
            public TextView mTextView;
            public TextView pageNumber;
            public ViewHolder(View v) {
                super(v);
                mTextView = (TextView) v.findViewById(R.id.info_text);
                pageNumber = (TextView) v.findViewById(R.id.page_number);
            }
        }

        // Provide a suitable constructor (depends on the kind of dataset)
        public MyAdapter(String[] myDataset) {
            //my Dataset is an array with 4 members making up the 4 pages//
            mDataset = myDataset;
        }

        // Create new views (invoked by the layout manager)
        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                       int viewType) {
            // create a new view
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.cards, parent, false);
            // set the view's size, margins, paddings and layout parameters
            ViewHolder vh = new ViewHolder(v);
            return vh;
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            // - get element from your dataset at this position
            // - replace the contents of the view with that element
            holder.mTextView.setText(mDataset[position]);
            int page = position + 1;
            holder.pageNumber.setText("" + page);

        }

        // Return the size of your dataset (invoked by the layout manager)
        @Override
        public int getItemCount() {
            return mDataset.length;
        }
    }

    //******SCROLL TO TOP BUTTON************//
    public void scrollToTop(View v){
        mLayoutManager.scrollToPosition(0);
    }

    //*******************SCROLL TO SELECTED PAGE***********//
    public void scrollToPage(int p){
        mLayoutManager.scrollToPosition(p);
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="GO TO TOP"
            android:onClick="scrollToTop"
            android:layout_gravity="bottom|left"/>

        <EditText
            android:id="@+id/page"
            android:layout_width="50dp"
            android:layout_height="20dp"
            android:layout_gravity="bottom|center_horizontal"
            android:imeOptions="actionGo"
            android:inputType="number"
            android:background="@color/cardview_light_background"/>

    </LinearLayout>
</RelativeLayout>

cards.xml

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

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="300dp"
    android:layout_height="500dp"
    android:layout_gravity="center"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:id="@+id/info_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/frayedpaper"
        android:text="@string/body" />

    <TextView
        android:id="@+id/page_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:text="page"/>

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


问:
Find out the recently selected rows from a Oracle table and can I update a LAST_ACCESSED column whenever the table is accessed
I have a database table which have more than 1 million records uniquely identified by a GUID column. I want to find out which of these record or rows was selected or retrieved in the last 5 years. The select query can happen from multiple places. Sometimes the row will be returned as a single row. Sometimes it will be part of a set of rows. there is select query that does the fetching from a jdbc connection from a java code. Also a SQL procedure also fetches data from the table.

My intention is to clean up a database table.I want to delete all rows which was never used( retrieved via select query) in last 5 years.

Does oracle DB have any inbuild meta data which can give me this information.

My alternative solution was to add a column LAST_ACCESSED and update this column whenever I select a row from this table. But this operation is a costly operation for me based on time taken for the whole process. Atleast 1000 - 10000 records will be selected from the table for a single operation. Is there any efficient way to do this rather than updating table after reading it. Mine is a multi threaded application. so update such large data set may result in deadlocks or large waiting period for the next read query.

Any elegant solution to this problem?

答:
Oracle Database 12c introduced a new feature called Automatic Data Optimization that brings you Heat Maps to track table access (modifications as well as read operations). Careful, the feature is currently to be licensed under the Advanced Compression Option or In-Memory Option.

Heat Maps track whenever a database block has been modified or whenever a segment, i.e. a table or table partition, has been accessed. It does not track select operations per individual row, neither per individual block level because the overhead would be too heavy (data is generally often and concurrently read, having to keep a counter for each row would quickly become a very costly operation). However, if you have you data partitioned by date, e.g. create a new partition for every day, you can over time easily determine which days are still read and which ones can be archived or purged. Also Partitioning is an option that needs to be licensed.

Once you have reached that conclusion you can then either use In-Database Archiving to mark rows as archived or just go ahead and purge the rows. If you happen to have the data partitioned you can do easy DROP PARTITION operations to purge one or many partitions rather than having to do conventional DELETE statements.


问:
Flask with Python error when MySQL Select statement
So the difference between working and not working is the insertion of the SELECT statement below the SELECT address execute() statement from MySQLdb.

My function:

```<code>@app.route('/ask/', methods=['GET','POST'])
def ask():
    #clients come here first
    error = ''
    try:
    c, conn = connection()
    #grab all the clients info
    email = session['email']
    c.execute("SELECT cid FROM clients WHERE email = (%s)", (thwart(email),))
    clientcid = c.fetchone()[0]
    c.execute("SELECT phone FROM clients WHERE email = (%s)", (thwart(email),))
    phone = c.fetchone()[0]
    c.execute("SELECT rating FROM clients WHERE email = (%s)", (thwart(email),))
    rating = c.fetchone()[0]
    c.execute("SELECT first_name FROM cpersonals WHERE cid = (%s)", (clientcid,))
    first_name = c.fetchone()[0]
    c.execute("SELECT last_name FROM cpersonals WHERE cid = (%s)", (clientcid,))
    last_name = c.fetchone()[0]
    c.execute("SELECT address FROM cpersonals WHERE cid = (%s)", (clientcid,))
    address = c.fetchone()[0]
    c.execute("SELECT zip FROM cpersonals WHERE cid = (%s)", (clientcid,))
    czip = c.fetchone()[0]
    c.execute("SELECT reg_date FROM cpersonals WHERE cid = (%s)", (clientcid,))
    reg_date = c.fetchone()[0]
    conn.commit()
    c.close()
    conn.close()

    session['logged_in'] = 'client'
    session['clientcid'] = clientcid
    session['phone'] = phone
    session['rating'] = rating
    session['first_name'] = first_name
    session['last_name'] = last_name
    session['address'] = address
    session['czip'] = czip
    session['reg_date'] = reg_date

    #if user posts a question to the pool
        if request.method == 'POST':
            #grab question info from form
            difficulty = request.form['difficulty']
            title = request.form['title']
            body = request.form['body']
            clientcid = session['clientcid']
            c, conn = connection()

            c.execute("INSERT INTO tickets (cid, difficulty, title, body) VALUES (%s, %s, %s, %s)", (clientcid, difficulty, thwart(title), thwart(body)))
            conn.commit()
            c.close()
            conn.close()

            flash("Submission successful.")
            return redirect(url_for('ask'))

        else:
            error = "We couldn't post your question, please reload the page and try again!"

        return render_template("ask.html")

    except Exception as e:
        return(str(e))
</code>```

Inserting this just below the SELECT address FROM cpersonals:

```<code>c.execute("SELECT city FROM cpersonals WHERE cid = (%s)", (clientcid,))
city = c.fetchone()[0]
</code>```

Super confused because this is the same as the SELECT statement above them for getting the address, yet it causes a 500 error. Anyone have a clue on what areas I can look at to solve this? Why would it be behaving as such?

EDIT:
Apache error log:

```<code>[Tue Nov 14 03:20:26.932754 2017] [mpm_event:notice] [pid 10241:tid 140272413560320] AH00491: caught SIGTERM, shutting down
[Tue Nov 14 03:20:27.002887 2017] [mpm_event:notice] [pid 10347:tid 140399854022144] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.11 Python/2.7 configured -- resuming normal operations
[Tue Nov 14 03:20:27.003054 2017] [core:notice] [pid 10347:tid 140399854022144] AH00094: Command line: '/usr/sbin/apache2'
[Tue Nov 14 03:20:28.212299 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860] mod_wsgi (pid=10351): Target WSGI script '/var/www/FlaskApp/flaskapp.wsgi' cannot be loaded as Python module., referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212379 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860] mod_wsgi (pid=10351): Exception occurred processing WSGI script '/var/www/FlaskApp/flaskapp.wsgi'., referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212415 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860] Traceback (most recent call last):, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212451 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860]   File "/var/www/FlaskApp/flaskapp.wsgi", line 7, in <module>, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212558 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860]     from FlaskApp import app as application, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212622 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860]   File "/var/www/FlaskApp/FlaskApp/__init__.py", line 41, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212635 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860]     c.execute("SELECT state FROM cpersonals WHERE cid = (%s)", (clientcid,)), referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212641 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860]     ^, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212647 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860] SyntaxError: invalid syntax, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.269478 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861] mod_wsgi (pid=10350): Target WSGI script '/var/www/FlaskApp/flaskapp.wsgi' cannot be loaded as Python module., referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269538 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861] mod_wsgi (pid=10350): Exception occurred processing WSGI script '/var/www/FlaskApp/flaskapp.wsgi'., referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269566 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861] Traceback (most recent call last):, referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269594 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861]   File "/var/www/FlaskApp/flaskapp.wsgi", line 7, in <module>, referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269679 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861]     from FlaskApp import app as application, referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269730 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861]   File "/var/www/FlaskApp/FlaskApp/__init__.py", line 41, referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269740 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861]     c.execute("SELECT state FROM cpersonals WHERE cid = (%s)", (clientcid,)), referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269747 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861]     ^, referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269753 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861] SyntaxError: invalid syntax, referer: http://138.197.210.172/ask/
</code>```

答:
Figured it out: all I needed to do was tab out the statements below the try statement. I suppose this is because Python is very finicky about tabbing!

As such:

```<code>try:
        c, conn = connection()
        #grab all the clients info
        email = session['email']
        c.execute("SELECT cid FROM clients WHERE email = (%s)", (thwart(email),))
        clientcid = c.fetchone()[0]
        c.execute("SELECT phone FROM clients WHERE email = (%s)", (thwart(email),))
        phone = c.fetchone()[0]
        c.execute("SELECT rating FROM clients WHERE email = (%s)", (thwart(email),))
        rating = c.fetchone()[0]
        c.execute("SELECT first_name FROM cpersonals WHERE cid = (%s)", (clientcid,))
        first_name = c.fetchone()[0]
        c.execute("SELECT last_name FROM cpersonals WHERE cid = (%s)", (clientcid,))
        last_name = c.fetchone()[0]
        c.execute("SELECT address FROM cpersonals WHERE cid = (%s)", (clientcid,))
        address = c.fetchone()[0]
        c.execute("SELECT city FROM cpersonals WHERE cid = (%s)", (clientcid,))
        city = c.fetchone()[0]
        c.execute("SELECT state FROM cpersonals WHERE cid = (%s)", (clientcid,))
        state = c.fetchone()[0]
        c.execute("SELECT zip FROM cpersonals WHERE cid = (%s)", (clientcid,))
        czip = c.fetchone()[0]
        c.execute("SELECT reg_date FROM cpersonals WHERE cid = (%s)", (clientcid,))
        reg_date = c.fetchone()[0]
        conn.commit()
        c.close()
        conn.close()

        session['logged_in'] = 'client'
        session['clientcid'] = clientcid
        session['phone'] = phone
        session['rating'] = rating
        session['first_name'] = first_name
        session['last_name'] = last_name
        session['address'] = address
        session['city'] = city
        session['state'] = state
        session['czip'] = czip
        session['reg_date'] = reg_date

       #if user posts a question to the pool
        if request.method == 'POST':
            #grab question info from form
            difficulty = request.form['difficulty']
            title = request.form['title']
            body = request.form['body']
            clientcid = session['clientcid']
            c, conn = connection()
</code>```

Body:
So the difference between working and not working is the insertion of the SELECT statement below the SELECT address execute() statement from MySQLdb.

My function:

@app.route('/ask/', methods=['GET','POST'])
def ask():
    #clients come here first
    error = ''
    try:
    c, conn = connection()
    #grab all the clients info
    email = session['email']
    c.execute("SELECT cid FROM clients WHERE email = (%s)", (thwart(email),))
    clientcid = c.fetchone()[0]
    c.execute("SELECT phone FROM clients WHERE email = (%s)", (thwart(email),))
    phone = c.fetchone()[0]
    c.execute("SELECT rating FROM clients WHERE email = (%s)", (thwart(email),))
    rating = c.fetchone()[0]
    c.execute("SELECT first_name FROM cpersonals WHERE cid = (%s)", (clientcid,))
    first_name = c.fetchone()[0]
    c.execute("SELECT last_name FROM cpersonals WHERE cid = (%s)", (clientcid,))
    last_name = c.fetchone()[0]
    c.execute("SELECT address FROM cpersonals WHERE cid = (%s)", (clientcid,))
    address = c.fetchone()[0]
    c.execute("SELECT zip FROM cpersonals WHERE cid = (%s)", (clientcid,))
    czip = c.fetchone()[0]
    c.execute("SELECT reg_date FROM cpersonals WHERE cid = (%s)", (clientcid,))
    reg_date = c.fetchone()[0]
    conn.commit()
    c.close()
    conn.close()

    session['logged_in'] = 'client'
    session['clientcid'] = clientcid
    session['phone'] = phone
    session['rating'] = rating
    session['first_name'] = first_name
    session['last_name'] = last_name
    session['address'] = address
    session['czip'] = czip
    session['reg_date'] = reg_date

    #if user posts a question to the pool
        if request.method == 'POST':
            #grab question info from form
            difficulty = request.form['difficulty']
            title = request.form['title']
            body = request.form['body']
            clientcid = session['clientcid']
            c, conn = connection()

            c.execute("INSERT INTO tickets (cid, difficulty, title, body) VALUES (%s, %s, %s, %s)", (clientcid, difficulty, thwart(title), thwart(body)))
            conn.commit()
            c.close()
            conn.close()

            flash("Submission successful.")
            return redirect(url_for('ask'))

        else:
            error = "We couldn't post your question, please reload the page and try again!"

        return render_template("ask.html")

    except Exception as e:
        return(str(e))

Inserting this just below the SELECT address FROM cpersonals:

c.execute("SELECT city FROM cpersonals WHERE cid = (%s)", (clientcid,))
city = c.fetchone()[0]

Super confused because this is the same as the SELECT statement above them for getting the address, yet it causes a 500 error. Anyone have a clue on what areas I can look at to solve this? Why would it be behaving as such?

EDIT:
Apache error log:

[Tue Nov 14 03:20:26.932754 2017] [mpm_event:notice] [pid 10241:tid 140272413560320] AH00491: caught SIGTERM, shutting down
[Tue Nov 14 03:20:27.002887 2017] [mpm_event:notice] [pid 10347:tid 140399854022144] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.11 Python/2.7 configured -- resuming normal operations
[Tue Nov 14 03:20:27.003054 2017] [core:notice] [pid 10347:tid 140399854022144] AH00094: Command line: '/usr/sbin/apache2'
[Tue Nov 14 03:20:28.212299 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860] mod_wsgi (pid=10351): Target WSGI script '/var/www/FlaskApp/flaskapp.wsgi' cannot be loaded as Python module., referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212379 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860] mod_wsgi (pid=10351): Exception occurred processing WSGI script '/var/www/FlaskApp/flaskapp.wsgi'., referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212415 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860] Traceback (most recent call last):, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212451 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860]   File "/var/www/FlaskApp/flaskapp.wsgi", line 7, in <module>, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212558 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860]     from FlaskApp import app as application, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212622 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860]   File "/var/www/FlaskApp/FlaskApp/__init__.py", line 41, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212635 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860]     c.execute("SELECT state FROM cpersonals WHERE cid = (%s)", (clientcid,)), referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212641 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860]     ^, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.212647 2017] [wsgi:error] [pid 10351:tid 140399645546240] [client 108.196.200.128:64860] SyntaxError: invalid syntax, referer: http://138.197.210.172/login/
[Tue Nov 14 03:20:28.269478 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861] mod_wsgi (pid=10350): Target WSGI script '/var/www/FlaskApp/flaskapp.wsgi' cannot be loaded as Python module., referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269538 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861] mod_wsgi (pid=10350): Exception occurred processing WSGI script '/var/www/FlaskApp/flaskapp.wsgi'., referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269566 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861] Traceback (most recent call last):, referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269594 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861]   File "/var/www/FlaskApp/flaskapp.wsgi", line 7, in <module>, referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269679 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861]     from FlaskApp import app as application, referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269730 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861]   File "/var/www/FlaskApp/FlaskApp/__init__.py", line 41, referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269740 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861]     c.execute("SELECT state FROM cpersonals WHERE cid = (%s)", (clientcid,)), referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269747 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861]     ^, referer: http://138.197.210.172/ask/
[Tue Nov 14 03:20:28.269753 2017] [wsgi:error] [pid 10350:tid 140399578404608] [client 108.196.200.128:64861] SyntaxError: invalid syntax, referer: http://138.197.210.172/ask/

Body:
Figured it out: all I needed to do was tab out the statements below the try statement. I suppose this is because Python is very finicky about tabbing!

As such:

try:
        c, conn = connection()
        #grab all the clients info
        email = session['email']
        c.execute("SELECT cid FROM clients WHERE email = (%s)", (thwart(email),))
        clientcid = c.fetchone()[0]
        c.execute("SELECT phone FROM clients WHERE email = (%s)", (thwart(email),))
        phone = c.fetchone()[0]
        c.execute("SELECT rating FROM clients WHERE email = (%s)", (thwart(email),))
        rating = c.fetchone()[0]
        c.execute("SELECT first_name FROM cpersonals WHERE cid = (%s)", (clientcid,))
        first_name = c.fetchone()[0]
        c.execute("SELECT last_name FROM cpersonals WHERE cid = (%s)", (clientcid,))
        last_name = c.fetchone()[0]
        c.execute("SELECT address FROM cpersonals WHERE cid = (%s)", (clientcid,))
        address = c.fetchone()[0]
        c.execute("SELECT city FROM cpersonals WHERE cid = (%s)", (clientcid,))
        city = c.fetchone()[0]
        c.execute("SELECT state FROM cpersonals WHERE cid = (%s)", (clientcid,))
        state = c.fetchone()[0]
        c.execute("SELECT zip FROM cpersonals WHERE cid = (%s)", (clientcid,))
        czip = c.fetchone()[0]
        c.execute("SELECT reg_date FROM cpersonals WHERE cid = (%s)", (clientcid,))
        reg_date = c.fetchone()[0]
        conn.commit()
        c.close()
        conn.close()

        session['logged_in'] = 'client'
        session['clientcid'] = clientcid
        session['phone'] = phone
        session['rating'] = rating
        session['first_name'] = first_name
        session['last_name'] = last_name
        session['address'] = address
        session['city'] = city
        session['state'] = state
        session['czip'] = czip
        session['reg_date'] = reg_date

       #if user posts a question to the pool
        if request.method == 'POST':
            #grab question info from form
            difficulty = request.form['difficulty']
            title = request.form['title']
            body = request.form['body']
            clientcid = session['clientcid']
            c, conn = connection()


问:
Unexpected Token in React/Redux export
Working on my first React Native app (and new to Redux as well). I keep getting the error: "Unexpected token auth" that points to the last line of my auth.js reducer. I'm using Nuclide on Atom for editing with ESLinter to help out. Any thoughts on either (1) what my problem is? Or (2) how do I get Nuclide Diagnostics to provide more information on my error?</p>

```<code>const defaultState = {
  isLoggedIn: false,
  token: '',
  client: '',
  uid: '',
  spinner: false
};

const auth = (state = defaultState, action) => {
  switch (action.type) {
    case 'LOGIN':
      return Object.assign({}, state, {
        isLoggedIn: true,
        token: action.token,
        client: action.client,
        uid: action.uid,
        spinner: false
      });
    case 'LOGOUT':
      return Object.assign({}, state, {
        isLoggedIn: false,
        email: '',
        password: '',
        spinner: false
      });
    case 'LOAD_SPINNER':
      return Object.assign({}, state, {
        spinner: true,
      });
    default:
      return state;
  };
};

export auth
</code>```

答: You got Unexpected token auth because of your export. Use export default auth;

Title: Unexpected Token in React/Redux export

Body:
Working on my first React Native app (and new to Redux as well). I keep getting the error: "Unexpected token auth" that points to the last line of my auth.js reducer. I'm using Nuclide on Atom for editing with ESLinter to help out. Any thoughts on either (1) what my problem is? Or (2) how do I get Nuclide Diagnostics to provide more information on my error?

const defaultState = {
  isLoggedIn: false,
  token: '',
  client: '',
  uid: '',
  spinner: false
};

const auth = (state = defaultState, action) => {
  switch (action.type) {
    case 'LOGIN':
      return Object.assign({}, state, {
        isLoggedIn: true,
        token: action.token,
        client: action.client,
        uid: action.uid,
        spinner: false
      });
    case 'LOGOUT':
      return Object.assign({}, state, {
        isLoggedIn: false,
        email: '',
        password: '',
        spinner: false
      });
    case 'LOAD_SPINNER':
      return Object.assign({}, state, {
        spinner: true,
      });
    default:
      return state;
  };
};

export auth


问:
Rails - Using true and false
I have the following in my controller:

```<code>if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end
</code>```

Then later in create.je.erb do:

```<code><% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>
</code>```

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

答:
try:</p>

```<code><% if !@archived_new_status.blank? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Rails - Using true and false

Body:
I have the following in my controller:

if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end

Then later in create.je.erb do:

<% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

Body:
try:

<% if !@archived_new_status.blank? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>


问:
How to read the state of current permission status?
In my app, I need GPS to locate the user. I wish my app provide following kinds of result.

```<code>1.The current location.(Success)
2.Failed to get current location because of device error or something else. (Failed)
3.The user refused the permission. (Permission denied)
</code>```

I use LocationManager to do the job.

```<code>locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
</code>```

If the permission is denied, the location will be null.

But I don't know what the location will be if the function failed. And I 'm not sure whether that location is null and user refuse to open GPS are equal.

With the following code, I might know whether the permission is added in the AndroidManifest.xml. But I can't get the information I need.

```<code>boolean getLocationOn = (PackageManager.PERMISSION_GRANTED ==
           pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", "my_package"));
</code>```

答:
Create a method to check permissions.

```<code>public static final int MULTIPLE_PERMISSIONS = 15;
String[] permissions= new String[]
{
    Manifest.permission.ACCESS_COARSE_LOCATION,
    Manifest.permission.ACCESS_FINE_LOCATION

};
</code>```

Below function will request for permissions.

```<code>@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if (requestCode == MULTIPLE_PERMISSIONS) {

        Log.v("Nopermissionz", "No permission granted , " + permissions.length);

        if (permissions.length == 2
                && grantResults[0] == PackageManager.PERMISSION_GRANTED
                && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

            Log.v("Nopermission1", "Permission granted , " + permissions.length);

        } else {
            Log.v("Nopermission2", "No permission granted");
            Snackbar.make(findViewById(android.R.id.content), "Please allow this App with some permissions", Snackbar.LENGTH_INDEFINITE)
                    .setAction("SETTINGS", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", getPackageName(), null);
                            intent.setData(uri);
                            startActivity(intent);
                        }
                    })
                    .show();
        }
    }
}
</code>```

Call the method checkPermissions() to check if permissions are granted.

```<code>private  boolean checkPermissions()
{
    int result;
    List<String> listPermissionsNeeded = new ArrayList<>();
    for (String p:permissions)
    {
        result = ContextCompat.checkSelfPermission(MainActivity.this,p);
        if (result != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(p);
        }
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(MainActivity.this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),MULTIPLE_PERMISSIONS );
        return false;
    }
    return true;
}
</code>```

Body:
In my app, I need GPS to locate the user. I wish my app provide following kinds of result.

1.The current location.(Success)
2.Failed to get current location because of device error or something else. (Failed)
3.The user refused the permission. (Permission denied)

I use LocationManager to do the job.

locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

If the permission is denied, the location will be null.

But I don't know what the location will be if the function failed. And I 'm not sure whether that location is null and user refuse to open GPS are equal.

With the following code, I might know whether the permission is added in the AndroidManifest.xml. But I can't get the information I need.

boolean getLocationOn = (PackageManager.PERMISSION_GRANTED ==
           pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", "my_package"));

Body:
Create a method to check permissions.

public static final int MULTIPLE_PERMISSIONS = 15;
String[] permissions= new String[]
{
    Manifest.permission.ACCESS_COARSE_LOCATION,
    Manifest.permission.ACCESS_FINE_LOCATION

};

Below function will request for permissions.

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if (requestCode == MULTIPLE_PERMISSIONS) {

        Log.v("Nopermissionz", "No permission granted , " + permissions.length);

        if (permissions.length == 2
                && grantResults[0] == PackageManager.PERMISSION_GRANTED
                && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

            Log.v("Nopermission1", "Permission granted , " + permissions.length);

        } else {
            Log.v("Nopermission2", "No permission granted");
            Snackbar.make(findViewById(android.R.id.content), "Please allow this App with some permissions", Snackbar.LENGTH_INDEFINITE)
                    .setAction("SETTINGS", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", getPackageName(), null);
                            intent.setData(uri);
                            startActivity(intent);
                        }
                    })
                    .show();
        }
    }
}

Call the method checkPermissions() to check if permissions are granted.

private  boolean checkPermissions()
{
    int result;
    List<String> listPermissionsNeeded = new ArrayList<>();
    for (String p:permissions)
    {
        result = ContextCompat.checkSelfPermission(MainActivity.this,p);
        if (result != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(p);
        }
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(MainActivity.this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),MULTIPLE_PERMISSIONS );
        return false;
    }
    return true;
}


问:
Get the value from the given array
I have this given array ,
How can get the value of email and status in loop .

```<code>Array
(
    [0] => Array
        (
            [brandlogo_id] => 1
            [email] => upendtu@gmail.com
            [status] => 2
            [created_time] => 2017-11-13 14:00:10
            [update_time] => 2017-11-13 14:00:10
        )

    [1] => Array
        (
            [brandlogo_id] => 2
            [email] => upen3592@gmail.com
            [status] => 1
            [created_time] => 2017-11-13 13:58:46
            [update_time] => 2017-11-13 13:58:46
        )

    [2] => Array
        (
            [brandlogo_id] => 3
            [email] => ankigupta9492@gmail.com
            [status] => 1
            [created_time] => 2017-11-13 13:57:07
            [update_time] => 2017-11-13 13:57:07
        )

)
</code>```

please let me know how can i get this value
thank you.

答:
Be it any language, the method/ also will be more or less the same apart from the syntax. Search the syntax for the language you are using to parse JSON data.
Giving examples.

For Objective - C:

```<code>    NSArray *resultDataSet=[NSArray array];
    while([results next]) {
        NSString *name = [results stringForColumn:@"brand_name"];
        resultDataSet = [resultDataSet arrayByAddingObject:name ];
    }
</code>```

For Python :

```<code>for array in data:
    print array['email']
</code>```

For PHP :

```<code>foreach($arr as $item) { //foreach element in $array
    $stat = $item['status']; //etc
}
</code>```

Hope that helps.

Title: Get the value from the given array

Body:
I have this given array ,
How can get the value of email and status in loop .

Array
(
    [0] => Array
        (
            [brandlogo_id] => 1
            [email] => upendtu@gmail.com
            [status] => 2
            [created_time] => 2017-11-13 14:00:10
            [update_time] => 2017-11-13 14:00:10
        )

    [1] => Array
        (
            [brandlogo_id] => 2
            [email] => upen3592@gmail.com
            [status] => 1
            [created_time] => 2017-11-13 13:58:46
            [update_time] => 2017-11-13 13:58:46
        )

    [2] => Array
        (
            [brandlogo_id] => 3
            [email] => ankigupta9492@gmail.com
            [status] => 1
            [created_time] => 2017-11-13 13:57:07
            [update_time] => 2017-11-13 13:57:07
        )

)

please let me know how can i get this value
thank you.

Body:
Be it any language, the method/ also will be more or less the same apart from the syntax. Search the syntax for the language you are using to parse JSON data.
Giving examples.

For Objective - C:

    NSArray *resultDataSet=[NSArray array];
    while([results next]) {
        NSString *name = [results stringForColumn:@"brand_name"];
        resultDataSet = [resultDataSet arrayByAddingObject:name ];
    }

For Python :

for array in data:
    print array['email']

For PHP :

foreach($arr as $item) { //foreach element in $array
    $stat = $item['status']; //etc
}

Hope that helps.


问:
What is the correct way to start/stop spark streaming jobs in yarn?
I have been experimenting and googling for many hours, with no luck.

I have a spark streaming app that runs fine in a local spark cluster.  Now I need to deploy it on cloudera 5.4.4.  I need to be able to start it, have it run in the background continually, and be able to stop it.

I tried this:

```<code>$ spark-submit --master yarn-cluster --class MyMain my.jar myArgs
</code>```

But it just prints these lines endlessly.

```<code>15/07/28 17:58:18 INFO Client: Application report for application_1438092860895_0012 (state: RUNNING)
15/07/28 17:58:19 INFO Client: Application report for application_1438092860895_0012 (state: RUNNING)
</code>```

Question number 1: since it is a streaming app, it needs to run continuously.  So how do I run it in a "background" mode?  All the examples I can find of submitting spark jobs on yarn seem to assume that the application will do some work and terminate, and therefore that you would want to run it in the foreground.  But that is not the case for streaming.

Next up... at this point the app does not seem to be functioning.  I figure it could be a bug or misconfiguration on my part, so I tried to look in the logs to see what's happening:

```<code>$ yarn logs -applicationId application_1438092860895_012
</code>```

But it tells me :

```<code>/tmp/logs/hdfs/logs/application_1438092860895_0012does not have any log files.
</code>```

So question number 2: If the application is RUNNING, why does it have no log files?

So eventually I just had to kill it:

```<code>$ yarn application -kill application_1438092860895_012
</code>```

That brings up question number 3: assuming I can eventually get the app launched and running in the background, is "yarn application -kill" the preferred way of stopping it?

答:
The last puzzle element is how to stop Spark Streaming application deployed on YARN in a graceful way. The standard method for stopping (or rather killing) YARN application is using a command yarn application -kill [applicationId]. And this command stops the Spark Streaming application but this could happen in the middle of a batch. So if the job reads data from Kafka, saves processing results on HDFS and finally commits Kafka offsets you should expect duplicated data on HDFS when job was stopped just before committing offsets.

The first attempt to solve graceful shutdown issue was to call Spark streaming context stop method in a shutdown hook.

```<code>sys.addShutdownHook {
    streamingContext.stop(stopSparkContext = true, stopGracefully = true)
}
</code>```

Disappointingly a shutdown hook is called too late to finish started batch and Spark application is killed almost immediately. Moreover there is no guarantee that a shutdown hook will be called by JVM at all.

At the time of writing this blog post the only confirmed way to shutdown gracefully Spark Streaming application on YARN is to notifying somehow the application about planned shutdown, and then stop streaming context programmatically (but not from shutdown hook). Command yarn application -kill should be used only as a last resort if notified application did not stop after defined timeout.

The application can be notified about planned shutdown using marker file on HDFS (the easiest way), or using simple Socket/HTTP endpoint exposed on the driver (sophisticated way).

Because I like KISS principle, below you can find shell script pseudo-code for starting / stopping Spark Streaming application using marker file:

```<code>start() {
    hdfs dfs -touchz /path/to/marker/my_job_unique_name
    spark-submit ...
}

stop() {
    hdfs dfs -rm /path/to/marker/my_job_unique_name
    force_kill=true
    application_id=$(yarn application -list | grep -oe "application_[0-9]*_[0-9]*"`)
    for i in `seq 1 10`; do
        application_status=$(yarn application -status ${application_id} | grep "State : \(RUNNING\|ACCEPTED\)")
        if [ -n "$application_status" ]; then
            sleep 60s
        else
            force_kill=false
            break
        fi
    done
    $force_kill && yarn application -kill ${application_id}
}
</code>```

In the Spark Streaming application, background thread should monitor marker file, and when the file disappears stop the context calling

```<code>streamingContext.stop(stopSparkContext = true, stopGracefully = true)
</code>```

Also you can refer http://blog.parseconsulting.com/2017/02/how-to-shutdown-spark-streaming-job.html

Body:
I have been experimenting and googling for many hours, with no luck.

I have a spark streaming app that runs fine in a local spark cluster.  Now I need to deploy it on cloudera 5.4.4.  I need to be able to start it, have it run in the background continually, and be able to stop it.

I tried this:

$ spark-submit --master yarn-cluster --class MyMain my.jar myArgs

But it just prints these lines endlessly.

15/07/28 17:58:18 INFO Client: Application report for application_1438092860895_0012 (state: RUNNING)
15/07/28 17:58:19 INFO Client: Application report for application_1438092860895_0012 (state: RUNNING)

Question number 1: since it is a streaming app, it needs to run continuously.  So how do I run it in a "background" mode?  All the examples I can find of submitting spark jobs on yarn seem to assume that the application will do some work and terminate, and therefore that you would want to run it in the foreground.  But that is not the case for streaming.

Next up... at this point the app does not seem to be functioning.  I figure it could be a bug or misconfiguration on my part, so I tried to look in the logs to see what's happening:

$ yarn logs -applicationId application_1438092860895_012

But it tells me :

/tmp/logs/hdfs/logs/application_1438092860895_0012does not have any log files.

So question number 2: If the application is RUNNING, why does it have no log files?

So eventually I just had to kill it:

$ yarn application -kill application_1438092860895_012

That brings up question number 3: assuming I can eventually get the app launched and running in the background, is "yarn application -kill" the preferred way of stopping it?

Body:
The last puzzle element is how to stop Spark Streaming application deployed on YARN in a graceful way. The standard method for stopping (or rather killing) YARN application is using a command yarn application -kill [applicationId]. And this command stops the Spark Streaming application but this could happen in the middle of a batch. So if the job reads data from Kafka, saves processing results on HDFS and finally commits Kafka offsets you should expect duplicated data on HDFS when job was stopped just before committing offsets.

The first attempt to solve graceful shutdown issue was to call Spark streaming context stop method in a shutdown hook.

sys.addShutdownHook {
    streamingContext.stop(stopSparkContext = true, stopGracefully = true)
}

Disappointingly a shutdown hook is called too late to finish started batch and Spark application is killed almost immediately. Moreover there is no guarantee that a shutdown hook will be called by JVM at all.

At the time of writing this blog post the only confirmed way to shutdown gracefully Spark Streaming application on YARN is to notifying somehow the application about planned shutdown, and then stop streaming context programmatically (but not from shutdown hook). Command yarn application -kill should be used only as a last resort if notified application did not stop after defined timeout.

The application can be notified about planned shutdown using marker file on HDFS (the easiest way), or using simple Socket/HTTP endpoint exposed on the driver (sophisticated way).

Because I like KISS principle, below you can find shell script pseudo-code for starting / stopping Spark Streaming application using marker file:

start() {
    hdfs dfs -touchz /path/to/marker/my_job_unique_name
    spark-submit ...
}

stop() {
    hdfs dfs -rm /path/to/marker/my_job_unique_name
    force_kill=true
    application_id=$(yarn application -list | grep -oe "application_[0-9]*_[0-9]*"`)
    for i in `seq 1 10`; do
        application_status=$(yarn application -status ${application_id} | grep "State : \(RUNNING\|ACCEPTED\)")
        if [ -n "$application_status" ]; then
            sleep 60s
        else
            force_kill=false
            break
        fi
    done
    $force_kill && yarn application -kill ${application_id}
}

In the Spark Streaming application, background thread should monitor marker file, and when the file disappears stop the context calling

streamingContext.stop(stopSparkContext = true, stopGracefully = true)

Also you can refer http://blog.parseconsulting.com/2017/02/how-to-shutdown-spark-streaming-job.html


问:
Display few cells inside table view and scroll the rest
Inside my UITableView I have 2 types of cells lets say A and B.
Initially, my table shows only cells of type A and when the user taps on any cell, I display a list of type B cells to give sort of a drop-down effect. Now the issue is when I tap on a cell of type A it's drop-down may have a large number of type B cells, so what I want to do is limit the number of cells in the dropdown to 3 and then scroll the rest of them in the same position and then have the list of type A cells after that. I have no idea how to do this, any help is greatly appreciated.

答: Try to set bellow constraint in your internal tableview that is collapse and expand.


问:
Dynamically add ManyToMany relationship to Django objects
My Company class have multiple M2M relationship with itself

class Company(models.Model):

```<code>divisions = models.ManyToManyField('self', symmetrical=False, related_name="parent_companies")
parents = models.ManyToManyField('self', symmetrical=False, related_name="divisions_companies")
comp = models.ManyToManyField('self', symmetrical=False, related_name="comp")
friends = models.ManyToManyField('self', symmetrical=False, related_name="friends")
</code>```

I would like to be able to dynamically add M2M relationship like this, but it obviously does not work. Is there a way to do it dynamically ?

```<code>                    company, was_created = Company.objects.get_or_create(name=info)
                    setattr(self,key, company)
</code>```

答:
The syntax is for adding M2M is field.add(obj_pk or obj)

```<code>company, was_created = Company.objects.get_or_create(name=info)
self.comp.add(company)
</code>```

Body:
My Company class have multiple M2M relationship with itself

class Company(models.Model):

divisions = models.ManyToManyField('self', symmetrical=False, related_name="parent_companies")
parents = models.ManyToManyField('self', symmetrical=False, related_name="divisions_companies")
comp = models.ManyToManyField('self', symmetrical=False, related_name="comp")
friends = models.ManyToManyField('self', symmetrical=False, related_name="friends")

I would like to be able to dynamically add M2M relationship like this, but it obviously does not work. Is there a way to do it dynamically ?

                    company, was_created = Company.objects.get_or_create(name=info)
                    setattr(self,key, company)

Body:
The syntax is for adding M2M is field.add(obj_pk or obj)

company, was_created = Company.objects.get_or_create(name=info)
self.comp.add(company)


问:
orapki command line utility for creating wallet is not working
orapki utility for managing Public Key Infrustrure (PKI) like wallet is not working.
 It is showing following error in Linux shell.

bash: orapki: command not found...

In the system, Oracle 12c is installed, ORACLE_HOME is set and oraclepki jar is also present in Oracle_home/jlib dir.
Anyone, please help me understand the cause and its solution.

答:
orapki is under MIDDLEWARE_HOME/oracle_common/bin

Try invoking orapki from this path, or add to PATH env var.


问:
Java: Comparing two lists, if either contains the value of the other, add all values of both to a new list
I have a HashMap with String keys and ArrayList of MyObject values and now I want to make a new list of lists which contain all overlapping MyObjects.

For example: if ArrayList1 contains MyObjectA, MyObjectB, MyObjectC and ArrayList2 contains MyObjectA, MyObjectD, MyObjectE, then I want to add MyObjectA - E to a new list and put all of these lists in a master list. I want to essentially combine all of each ArrayList's values into a new list if any of the values overlap.

So far I'm just iterating through the map, and over each list, then nesting an iteration again, and if any value matches, doing another iteration of both ArrayLists in the nest to add them to a different list, but this is leading to duplication within the new list of lists.

Sorry if this isn't very clear.

Does anyone have any suggestions or perhaps a better way to accomplish this?

Thank You!

Here's my code:

```<code>public class DetermineOverlaps {

HashMap<String, ArrayList<CustomObject>> pgsPerStMap;

HashSet<HashSet<String>> competingPgs;

public DetermineOverlaps (HashMap<String, ArrayList<CustomObject>> pgsPerStMap2){

    pgsPerStMap = new HashMap<String, ArrayList<CustomObject>>(pgsPerStMap2);

    competingPgs = calculateCompetingPgs();

}

public HashSet<HashSet<String>> calculateCompetingPgs (){

    //This will be the hashset which gets returned from this method
    HashSet<HashSet<String>> competingProdGros = new HashSet<HashSet<String>>();

    //I will iterate over each term (key) within the pgsPerStMap map, which contains search terms | all customObject for that search term
    for (String searchTerm : pgsPerStMap.keySet()){

        //I will iterate over each customObject for the search term
        ArrayList<CustomObject> searchTermsPgs = pgsPerStMap.get(searchTerm);

        for (CustomObject curProdGroup : searchTermsPgs){

            String curProdGroupName = curProdGroup.key;

            //I will store all found matches in this hashset, which I will later put in the competingProdGros map
            HashSet<String> tempPgSet = new HashSet<String>();

            //Compare every other key/value combination of the map to every other key/value combination of the map
            for (String searchTerm2ndLevel : pgsPerStMap.keySet()){
                //Iterate over the customObject
                ArrayList<CustomObject> searchTermsPgsLev2 = pgsPerStMap.get(searchTerm2ndLevel);

                for (CustomObject curProdGroup2ndLevel : searchTermsPgsLev2){

                     String curProdGroupLevel2Name = curProdGroup2ndLevel.key;
                    //If these are different keys, but the same value, i.e. you've got a value which has multiple
                    //overlapping keys, and the temporary hashset doesn't contain the value already
                    //Then add all values from both arraylist<CustomObject> into the temporary hashset...
                    if (!searchTerm2ndLevel.equals(searchTerm) && curProdGroupLevel2Name.equals(curProdGroupName)
                    && !tempPgSet.contains(curProdGroupLevel2Name)){

                        for (CustomObject levelOnePg : searchTermsPgs){

                            String levelOnePgKey = levelOnePg.key;

                            tempPgSet.add(levelOnePgKey);

                        }

                        for (CustomObject levelTwoPg : searchTermsPgsLev2){

                            String levelTwoPgKey = levelTwoPg.key;
                            tempPgSet.add(levelTwoPgKey);

                        }

                    }

                }

            }

            //Add the temporary hashset into the competingProdGros hashset
            if(!competingProdGros.contains(tempPgSet)){competingProdGros.add(tempPgSet);}

        }

    }

    //return the competingprodgros hashset
    return competingProdGros;

}
</code>```

答:
Use addAll() function.
eg: ArrayList1.addAll(ArrayList2)
Now ArrayList1 will contain all values without duplicates</p>

Body:
I have a HashMap with String keys and ArrayList of MyObject values and now I want to make a new list of lists which contain all overlapping MyObjects.

For example: if ArrayList1 contains MyObjectA, MyObjectB, MyObjectC and ArrayList2 contains MyObjectA, MyObjectD, MyObjectE, then I want to add MyObjectA - E to a new list and put all of these lists in a master list. I want to essentially combine all of each ArrayList's values into a new list if any of the values overlap.

So far I'm just iterating through the map, and over each list, then nesting an iteration again, and if any value matches, doing another iteration of both ArrayLists in the nest to add them to a different list, but this is leading to duplication within the new list of lists.

Sorry if this isn't very clear.

Does anyone have any suggestions or perhaps a better way to accomplish this?

Thank You!

Here's my code:

public class DetermineOverlaps {

HashMap<String, ArrayList<CustomObject>> pgsPerStMap;

HashSet<HashSet<String>> competingPgs;

public DetermineOverlaps (HashMap<String, ArrayList<CustomObject>> pgsPerStMap2){

    pgsPerStMap = new HashMap<String, ArrayList<CustomObject>>(pgsPerStMap2);

    competingPgs = calculateCompetingPgs();

}

public HashSet<HashSet<String>> calculateCompetingPgs (){

    //This will be the hashset which gets returned from this method
    HashSet<HashSet<String>> competingProdGros = new HashSet<HashSet<String>>();

    //I will iterate over each term (key) within the pgsPerStMap map, which contains search terms | all customObject for that search term
    for (String searchTerm : pgsPerStMap.keySet()){

        //I will iterate over each customObject for the search term
        ArrayList<CustomObject> searchTermsPgs = pgsPerStMap.get(searchTerm);

        for (CustomObject curProdGroup : searchTermsPgs){

            String curProdGroupName = curProdGroup.key;

            //I will store all found matches in this hashset, which I will later put in the competingProdGros map
            HashSet<String> tempPgSet = new HashSet<String>();

            //Compare every other key/value combination of the map to every other key/value combination of the map
            for (String searchTerm2ndLevel : pgsPerStMap.keySet()){
                //Iterate over the customObject
                ArrayList<CustomObject> searchTermsPgsLev2 = pgsPerStMap.get(searchTerm2ndLevel);

                for (CustomObject curProdGroup2ndLevel : searchTermsPgsLev2){

                     String curProdGroupLevel2Name = curProdGroup2ndLevel.key;
                    //If these are different keys, but the same value, i.e. you've got a value which has multiple
                    //overlapping keys, and the temporary hashset doesn't contain the value already
                    //Then add all values from both arraylist<CustomObject> into the temporary hashset...
                    if (!searchTerm2ndLevel.equals(searchTerm) && curProdGroupLevel2Name.equals(curProdGroupName)
                    && !tempPgSet.contains(curProdGroupLevel2Name)){

                        for (CustomObject levelOnePg : searchTermsPgs){

                            String levelOnePgKey = levelOnePg.key;

                            tempPgSet.add(levelOnePgKey);

                        }

                        for (CustomObject levelTwoPg : searchTermsPgsLev2){

                            String levelTwoPgKey = levelTwoPg.key;
                            tempPgSet.add(levelTwoPgKey);

                        }

                    }

                }

            }

            //Add the temporary hashset into the competingProdGros hashset
            if(!competingProdGros.contains(tempPgSet)){competingProdGros.add(tempPgSet);}

        }

    }

    //return the competingprodgros hashset
    return competingProdGros;

}


问:
Of subtitles & lag times (yet another C overflow doubt)
I'm trying to calculate the time offset to be added to subtitle files to correct the lag. The part shown below is after tokenizing the hh:mm:ss,uuu (uuu stands for microseconds) into the time[] array. I'm converting the time into microseconds then adding the actual & lag time to get the final time.

The program computes the actual & lag time properly. However, it gives the wrong final hour time. Have I hit upon some overflow condition that can't be handled by the code below?

Edit: I have realized the error. I should be dividing rather than taking remainder for hour time.

```<code>int i;
int time[4];
unsigned long totalTime,totalLagTime;
...
for(i=0;i<4;i++)
{
    printf("time[%d] = %d\n",i,time[i]);
}

for(i=0;i<4;i++)
{
printf("lag time[%d] = %d\n",i,lagTime[i]);
}

totalTime = 1000*(3600*time[0] + 60*time[1] + time[2]) + time[3];

printf("total time is %u in milliseconds\n",totalTime);

totalLagTime = 1000*(3600*lagTime[0] + 60*lagTime[1] + lagTime[2]) + lagTime[3];

printf("total lag time is %u in milliseconds\n",totalLagTime);

totalTime += totalLagTime;

printf("Now, total time is %u in milliseconds\n",totalTime);

time[0] = totalTime % 3600000;

printf("hour time is %d\n",time[0]);
</code>```

Test case:

```<code>00:01:24,320

time[0] = 0
time[1] = 1
time[2] = 24
time[3] = 320
lag time[0] = 10
lag time[1] = 10
lag time[2] = 10
lag time[3] = 10
total time is 84320 in milliseconds
total lag time is 36610010 in milliseconds
Now, total time is 36694330 in milliseconds
hour time is 694330
</code>```

答:
You have a logic error: 36694330 mod 3600000 really is 694330.

What are you trying to do, exactly?

Body:
I'm trying to calculate the time offset to be added to subtitle files to correct the lag. The part shown below is after tokenizing the hh:mm:ss,uuu (uuu stands for microseconds) into the time[] array. I'm converting the time into microseconds then adding the actual & lag time to get the final time.

The program computes the actual & lag time properly. However, it gives the wrong final hour time. Have I hit upon some overflow condition that can't be handled by the code below?

Edit: I have realized the error. I should be dividing rather than taking remainder for hour time.

int i;
int time[4];
unsigned long totalTime,totalLagTime;
...
for(i=0;i<4;i++)
{
    printf("time[%d] = %d\n",i,time[i]);
}

for(i=0;i<4;i++)
{
printf("lag time[%d] = %d\n",i,lagTime[i]);
}

totalTime = 1000*(3600*time[0] + 60*time[1] + time[2]) + time[3];

printf("total time is %u in milliseconds\n",totalTime);

totalLagTime = 1000*(3600*lagTime[0] + 60*lagTime[1] + lagTime[2]) + lagTime[3];

printf("total lag time is %u in milliseconds\n",totalLagTime);

totalTime += totalLagTime;

printf("Now, total time is %u in milliseconds\n",totalTime);

time[0] = totalTime % 3600000;

printf("hour time is %d\n",time[0]);

Test case:

00:01:24,320

time[0] = 0
time[1] = 1
time[2] = 24
time[3] = 320
lag time[0] = 10
lag time[1] = 10
lag time[2] = 10
lag time[3] = 10
total time is 84320 in milliseconds
total lag time is 36610010 in milliseconds
Now, total time is 36694330 in milliseconds
hour time is 694330


答:
Assuming that you are using PHP or python (as this is an associative array) and the name of the array is "arr".
This code shall do the job.

For PHP

```<code>foreach($arr as $subarray) {
    echo $subarray["email"]." ".$subarray["status"]."<br>";
}
</code>```

For Python

```<code>for subarray in arr:
    print subarray["email"], " ", subarray["status"]
</code>```

It will display output similar to

```<code>xyz@gmail.com 2
abc@yahoo.com 3
</code>```

Title: Get the value from the given array

Body:
Assuming that you are using PHP or python (as this is an associative array) and the name of the array is "arr".
This code shall do the job.

For PHP

foreach($arr as $subarray) {
    echo $subarray["email"]." ".$subarray["status"]."<br>";
}

For Python

for subarray in arr:
    print subarray["email"], " ", subarray["status"]

It will display output similar to

xyz@gmail.com 2
abc@yahoo.com 3


问:
How to remove border right form last child div?

How do i remove border right form the last div?

.process {
  border-right: 1px solid #e0e0e0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="job-posting">
  <div class="row">
    <div class="col-md-4">
      <div class="process">
        <header>STEP 1</header>
        <div class="process-content">
          <i class="fa fa-user-plus icon" aria-hidden="true"></i>
          <h1>Signup</h1>
          <p>Sign Up as a Company or an Individual</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 2</header>
        <div class="process-content">
          <i class="fa fa-upload icon" aria-hidden="true"></i>
          <h1>Upload Resume</h1>
          <p>Upload your resume and provide us with details of you experience and skills</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 3</header>
        <div class="process-content">
          <i class="fa fa-smile-o icon" aria-hidden="true"></i>
          <h1>Get Hired</h1>
          <p>Browse the available job postings and get hired according to your skills</p>
        </div>
      </div>
    </div>
  </div>
</div></code>```

I'm having trouble removing the right border form the last div I tried using the :last-child:border:remove;

答:
You should think over the condition of multi line adaptation.Use class .row to show a row , and not just limit to class .col-md-4.
Note: Not use last-* on class .process .

.process {
    border-right: 1px solid #e0e0e0;
  }
  .row div:last-child .process{
    border-right: none;
  }```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
  <title>Test</title>
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <style>
  .process {
    border-right: 1px solid #e0e0e0;
  }
  .row div:last-child .process{
    border-right: none;
  }
  </style>
</head>
<body>
  <div class="job-posting">
    <div class="row">
      <div class="col-md-4">
        <div class="process">
          <header>STEP 1</header>
          <div class="process-content">
            <i class="fa fa-user-plus icon" aria-hidden="true"></i>
            <h1>Signup</h1>
            <p>Sign Up as a Company or an Individual</p>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="process">
          <header>STEP 2</header>
          <div class="process-content">
            <i class="fa fa-upload icon" aria-hidden="true"></i>
            <h1>Upload Resume</h1>
            <p>Upload your resume and provide us with details of you experience and skills</p>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="process">
          <header>STEP 3</header>
          <div class="process-content">
            <i class="fa fa-smile-o icon" aria-hidden="true"></i>
            <h1>Get Hired</h1>
            <p>Browse the available job postings and get hired according to your skills</p>
          </div>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-3">
        <div class="process">
          <header>STEP 1</header>
          <div class="process-content">
            <i class="fa fa-user-plus icon" aria-hidden="true"></i>
            <h1>Signup</h1>
            <p>Sign Up as a Company or an Individual</p>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="process">
          <header>STEP 2</header>
          <div class="process-content">
            <i class="fa fa-upload icon" aria-hidden="true"></i>
            <h1>Upload Resume</h1>
            <p>Upload your resume and provide us with details of you experience and skills</p>
          </div>
        </div>
      </div>
      <div class="col-md-5">
        <div class="process">
          <header>STEP 3</header>
          <div class="process-content">
            <i class="fa fa-smile-o icon" aria-hidden="true"></i>
            <h1>Get Hired</h1>
            <p>Browse the available job postings and get hired according to your skills</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html></code>```

Body:
How do i remove border right form the last div?

.process {
  border-right: 1px solid #e0e0e0;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        STEP 1

Signup

Sign Up as a Company or an Individual

        STEP 2

Upload Resume

Upload your resume and provide us with details of you experience and skills

        STEP 3

Get Hired

Browse the available job postings and get hired according to your skills

I'm having trouble removing the right border form the last div I tried using the :last-child:border:remove;

Body:
You should think over the condition of multi line adaptation.Use class .row to show a row , and not just limit to class .col-md-4.
Note: Not use last-* on class .process .

.process {
    border-right: 1px solid #e0e0e0;
  }
  .row div:last-child .process{
    border-right: none;
  }

<html>
<head>
  <title>Test</title>
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <style>
  .process {
    border-right: 1px solid #e0e0e0;
  }
  .row div:last-child .process{
    border-right: none;
  }
  </style>
</head>
<body>
  <div class="job-posting">
    <div class="row">
      <div class="col-md-4">
        <div class="process">
          <header>STEP 1</header>
          <div class="process-content">
            <i class="fa fa-user-plus icon" aria-hidden="true"></i>
            <h1>Signup</h1>
            <p>Sign Up as a Company or an Individual</p>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="process">
          <header>STEP 2</header>
          <div class="process-content">
            <i class="fa fa-upload icon" aria-hidden="true"></i>
            <h1>Upload Resume</h1>
            <p>Upload your resume and provide us with details of you experience and skills</p>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="process">
          <header>STEP 3</header>
          <div class="process-content">
            <i class="fa fa-smile-o icon" aria-hidden="true"></i>
            <h1>Get Hired</h1>
            <p>Browse the available job postings and get hired according to your skills</p>
          </div>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-3">
        <div class="process">
          <header>STEP 1</header>
          <div class="process-content">
            <i class="fa fa-user-plus icon" aria-hidden="true"></i>
            <h1>Signup</h1>
            <p>Sign Up as a Company or an Individual</p>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="process">
          <header>STEP 2</header>
          <div class="process-content">
            <i class="fa fa-upload icon" aria-hidden="true"></i>
            <h1>Upload Resume</h1>
            <p>Upload your resume and provide us with details of you experience and skills</p>
          </div>
        </div>
      </div>
      <div class="col-md-5">
        <div class="process">
          <header>STEP 3</header>
          <div class="process-content">
            <i class="fa fa-smile-o icon" aria-hidden="true"></i>
            <h1>Get Hired</h1>
            <p>Browse the available job postings and get hired according to your skills</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>


问:
How to get auto-width to the absolute position
I'm not sure if there's another method to get this layout without using absolute positioning.

The width of the titleAdd__text class is fixed to 4rem but I want that to change according to the content and not be fixed. How do I go about it?

body {
  background-color: #fff;
}

.titleBody {
  overflow-x: hidden;
  overflow-y: auto;
  height: 200px;
}

.titleAdd {
  background-color: #f4f4f4;
  min-height: 4rem;
  position: relative;
}

.titleAdd__plus {
  border-bottom: 2px solid #fff;
}

.titleAdd__plus:hover {
  background-color: #eee;
}

.titleAdd__text {
  min-width: 4rem;
  position: absolute;
  text-align: center;
  -moz-transform: rotate(-90deg) translate(-100%, 0%);
  -webkit-transform: rotate(-90deg) translate(-100%, 0%);
  -o-transform: rotate(-90deg) translate(-100%, 0%);
  -ms-transform: rotate(-90deg) translate(-100%, 0%);
  transform: rotate(-90deg) translate(-100%, 0%);
  -ms-transform-origin: left top;
  -webkit-transform-origin: left top;
  transform-origin: left top;
  font-family: 'Titillium Web', serif;
  letter-spacing: 0.05em;
  background-color: #2dc8ff;
  color: #fff;
  font-size: 0.9rem;
}

.titleAdd__body {
  padding-left: 2rem;
  font-size: 0.9rem;
  line-height: 1.5rem;
  cursor: pointer;
  height: 4rem;
  display: table-cell;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="titleBody">
  <div class="titleAdd">
    <div class="titleAdd__plus">
      <div class="titleAdd__text">Add</div>
      <div class="titleAdd__body">Overview the processes of the company functioning</div>
    </div>
    <div class="titleAdd__plus">
      <div class="titleAdd__text">Add</div>
      <div class="titleAdd__body">Implemented multiple predictive models and clustering to cross-sell high profit LAP (loan against property) to current clients. Implemented multiple predictive models and clustering to cross-sell high profit LAP (loan against property) to current
        clients. Implemented multiple predictive models and clustering to cross-sell high profit LAP to current clients. </div>
    </div>
    <div class="titleAdd__plus">
      <div class="titleAdd__text">Add</div>
      <div class="titleAdd__body">Enterprise grade machine learning platform for auto-updating. Enterprise grade machine learning platform for auto-updating. Enterprise grade machine learning platform for auto-updating. </div>
    </div>
  </div>
</div></code>```

答:
You have to do titleAdd__text as absolute with top:0 and bottom:0 - this will provide you that blue div will have same height as parent with position relative (add position relative to titleAdd__plus). Then you have to rotate span with text Add inside, not whole div and remove transform-origin

http://jsfiddle.net/b5vx7q63/2/

Looks great. Thank You. There's a final minor issue: the text-align: center in titleAdd__text isn't working anymore. Any idea how to go about that?

I found that there is writing-mode. I changed some styles of span with Add text

http://jsfiddle.net/qztq1osu/2/

Body:
I'm not sure if there's another method to get this layout without using absolute positioning.

The width of the titleAdd__text class is fixed to 4rem but I want that to change according to the content and not be fixed. How do I go about it?

body {
  background-color: #fff;
}

.titleBody {
  overflow-x: hidden;
  overflow-y: auto;
  height: 200px;
}

.titleAdd {
  background-color: #f4f4f4;
  min-height: 4rem;
  position: relative;
}

.titleAdd__plus {
  border-bottom: 2px solid #fff;
}

.titleAdd__plus:hover {
  background-color: #eee;
}

.titleAdd__text {
  min-width: 4rem;
  position: absolute;
  text-align: center;
  -moz-transform: rotate(-90deg) translate(-100%, 0%);
  -webkit-transform: rotate(-90deg) translate(-100%, 0%);
  -o-transform: rotate(-90deg) translate(-100%, 0%);
  -ms-transform: rotate(-90deg) translate(-100%, 0%);
  transform: rotate(-90deg) translate(-100%, 0%);
  -ms-transform-origin: left top;
  -webkit-transform-origin: left top;
  transform-origin: left top;
  font-family: 'Titillium Web', serif;
  letter-spacing: 0.05em;
  background-color: #2dc8ff;
  color: #fff;
  font-size: 0.9rem;
}

.titleAdd__body {
  padding-left: 2rem;
  font-size: 0.9rem;
  line-height: 1.5rem;
  cursor: pointer;
  height: 4rem;
  display: table-cell;
  vertical-align: middle;
}

Add

Overview the processes of the company functioning

Add

Implemented multiple predictive models and clustering to cross-sell high profit LAP (loan against property) to current clients. Implemented multiple predictive models and clustering to cross-sell high profit LAP (loan against property) to current
        clients. Implemented multiple predictive models and clustering to cross-sell high profit LAP to current clients.

Add

Enterprise grade machine learning platform for auto-updating. Enterprise grade machine learning platform for auto-updating. Enterprise grade machine learning platform for auto-updating.


问:
Broadleaf Commerce: Getting started MVN install errors
Non-resolvable parent POM for com.mycompany-community:boot-community-demo:1.0.0-SNAPSHOT: Could not transfer artifact org.broadleafcommerce:broadleaf-boot-starter-parent:pom:5.2.1-SNAPSHOT from/to public snapshots (http://nexus.broadleafcommerce.org/nexus/content/groups/community-snapshots/): Connect to nexus.broadleafcommerce.org:80 [nexus.broadleafcommerce.org/104.130.140.202] failed: Connection timed out: connect and 'parent.relativePath' points at no local POM @ line 5, column 13

I am new to Broadleaf & am a UI Developer. I am trying to setup 'Heat Clinic Demo' in my local but unable to do so. Am getting the above errors and unable to proceed further, can someone please help me out in running the project. Thanks in advance

答:
I am not sure how you got that version for your parent but it should be version 5.2.2.1-GA. That is our latest release version. I recommend changing the root pom.xml to use that version instead (in the  element).

The Maven error indicates that it could not connect to the Broadleaf nexus. On my end it looks like it is up, verify that you can ping it and try again with -U, e.g. mvn clean install -U to force metadata to be refreshed from the nexus.