text:
Q: How to iterate over an array of hashes in Ruby to compare each member with the following members in the array? So, I have an array of hashes, let's use this as an example
arr = [
  {:series=>"GOT", :rating=>"Good", :type=>"Fantasy"},
  {:series=>"BB", :rating=>"Great", :type=>"Crime"},
  {:series=>"E", :rating=>"Poor", :type=>"Drama"}
]

I'm trying to loop over this array so that I can compare each member with all following members.
E.g. Hash 1 compares with Hash 2 and Hash 3,  Hash 2 compares with Hash 3
The actual comparison function I already have written:
output = (data[X].keys & data[Y].keys).select { |k| data[X][k] == data[Y][k] }

X would be the current array and Y is the next element we are comparing to.
EDIT
Here's what I've got so far
for i in 0..data.length
  for j in i..data.length
    # puts data[j + 1]
    output = (data[j].keys & data[j+1].keys).select { |k| data[j][k] == data[j+1][k] }
    puts data[j]
    puts data[j+1]
    puts output
  end
  puts "*****"
end

My desired output is to print the hash and the other hash we are comparing with, as well as what keys they share a value for.
For example this array:
{:series=>"GOT", :rating=>"Great", :type=>"Fantasy"}
{:series=>"BB", :rating=>"Great", :type=>"Crime"}

Should print this:
{:series=>"GOT", :rating=>"Great", :type=>"Fantasy"}
{:series=>"BB", :rating=>"Great", :type=>"Crime"}
rating

If the key is nil, it should not compare. I think that's why I'm also getting this error when running the above code:
Traceback (most recent call last):
        4: from match_users.rb:18:in `<main>'
        3: from match_users.rb:18:in `each'
        2: from match_users.rb:19:in `block in <main>'
        1: from match_users.rb:19:in `each'
match_users.rb:21:in `block (2 levels) in <main>': undefined method `keys' for nil:NilClass (NoMethodError)

A: Note that you're not using "i" inside your loop, which looks like a bug.  Also, your index "j+1" is going off the end of the array, resulting in accessing the nil element.  Actually, even "j" goes off the end of the array.  Arrays are accessed from 0...length-1, whereas "0..data.length" will access the element at index data.length.  I'm guessing you mean something more like:
for i in 0..data.length-2
  for j in i+1..data.length-1
    output = (data[i].keys & data[j].keys).select { |k| data[i][k] == data[j][k] }
  end
end

A: Create an Iterable Collection
First of all, the data you posted isn't a valid Ruby array of hashes; it's just a sequential list of Hash objects, so you can't iterate over it. You need to wrap your Hash objects into something iterable first, such as an Array. Here's an example:
titles =
  [{:series=>"GOT", :rating=>"Good", :type=>"Fantasy"},
   {:series=>"BB", :rating=>"Great", :type=>"Crime"},
   {:series=>"E", :rating=>"Poor", :type=>"Drama"}]

Relative Comparisons of Consecutive Elements
Now that you have an iterable collection, you can use Enumerable#each_cons (which is already mixed into Array in Ruby's core) in order to iterate over each sequential pair of Hash objects. For demonstration purposes, I've chosen to store the relative comparisons as part of an Array within each title. For example, using the Array of Hash objects stored in titles as above:
STAR_MAPPINGS = {'great' => 5, 'good' => 4, 'fair' => 2,
                 'poor' => 1, 'unwatchable' => 0}.freeze

COMPARISON_MAP = {
  -1 => 'is worse than',
   0  => 'the same as',
   1  => 'is better than'
}.freeze

def compare_ratings_for title_1, title_2
  fmt = '_%s_ %s _%s_'
  series_1, series_2 = title_1[:series], title_2[:series]
  ratings_1, ratings_2 =
    STAR_MAPPINGS[title_1[:rating].downcase],
    STAR_MAPPINGS[title_2[:rating].downcase]
  comparison_str = COMPARISON_MAP[ratings_1 <=> ratings_2]
  format fmt, series_1, comparison_str, series_2
end

titles.each_cons(2).each do |h1, h2|
  # Array#| return an ordered, deduplicated union of keys
  matching_keys = (h1.keys | h2.keys).flatten.uniq
  next if matching_keys.none?

  # perform whatever comparisons you want here; this example
  # compares ratings by assigning stars to each rating
  h1[:comparisons] =
    h1.fetch(:comparisons, []) << compare_ratings_for(h1, h2)
  h2[:comparisons] =
    h2.fetch(:comparisons, []) << compare_ratings_for(h2, h1)
end

titles

The titles variable now holds and returns the following data:
[{:series=>"GOT", :rating=>"Good", :type=>"Fantasy", :comparisons=>["_GOT_ is worse than _BB_"]},
 {:series=>"BB", :rating=>"Great", :type=>"Crime", :comparisons=>["_BB_ is better than _GOT_", "_BB_ is better than _E_"]},
 {:series=>"E", :rating=>"Poor", :type=>"Drama", :comparisons=>["_E_ is worse than _BB_"]}]

Here's the same data again, but this time titles was pretty-printed with amazing_print for improved readability:
[
  {
         :series => "GOT",
         :rating => "Good",
           :type => "Fantasy",
    :comparisons => [
      "_GOT_ is worse than _BB_"
    ]
  },
  {
         :series => "BB",
         :rating => "Great",
           :type => "Crime",
    :comparisons => [
      "_BB_ is better than _GOT_",
      "_BB_ is better than _E_"
    ]
  },
  {
         :series => "E",
         :rating => "Poor",
           :type => "Drama",
    :comparisons => [
      "_E_ is worse than _BB_"
    ]
  }
]

See Also

*

*Array#|

*Array#<=>


text:
Q: Sum the infinite series How to solve this:
\begin{equation*}
\sum_{n=1}^{\infty }\left[ \frac{1\cdot 3\cdot 5\cdots \left( 2n-1\right) }{
2\cdot 4\cdot 6\cdots 2n}\right] ^{3}
\end{equation*}
I can make the bracket thing, $\left[ C(2n,n)/4^{n}\right] ^{3}$, but how to proceed now.

A: We have:
$$ \sum_{n\geq 0}\frac{1}{4^n}\binom{2n}{n}\,x^n = \frac{1}{\sqrt{1-x}},\tag{1} $$
$$\frac{1}{4^n}\binom{2n}{n}=\frac{1}{2\pi}\int_{-\pi}^{\pi}\left(\sin x\right)^{2n}\,dx \tag{2}$$
$$ \sum_{n\geq 0}\left(\frac{1}{4^n}\binom{2n}{n}\right)^2 x^n = \frac{2}{\pi}\,K(x)=\frac{2}{\pi}\int_{0}^{\pi/2}\frac{d\theta}{\sqrt{1-x\sin^2\theta}}\tag{3} $$
hence by $(2)$ and $(3)$ it follows that:
$$\begin{eqnarray*}\sum_{n\geq 0}\left(\frac{1}{4^n}\binom{2n}{n}\right)^3 &=& \frac{1}{\pi^2}\int_{-\pi}^{\pi}K(\sin^2 x)\,dx\\&=&\frac{4}{\pi^2}\int_{0}^{\pi/2}\int_{0}^{\pi/2}\frac{1}{\sqrt{1-\sin^2\varphi\sin^2\theta}}\,d\theta\,d\varphi\\&=&\frac{4}{\pi^2}\,K\left(\frac{1}{2}\right)^2=\color{red}{\frac{\pi}{\Gamma\left(\frac{3}{4}\right)^4}},\tag{4}\end{eqnarray*}$$
so the original series equals $\displaystyle\color{purple}{-1+\frac{\pi}{\Gamma\left(\frac{3}{4}\right)^4}=0.39320392968567685918424626\ldots}.$
Footnote: this is just a very special case of the identity $(6)$ for the square of the complete elliptic integral of the first kind, plus the fact that $K(1/2)$ can be computed through the reflection and multiplication formulas for the $\Gamma$ function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix SyntaxError: function statement requires a name I am trying to pull data from a json file and display it in a table on my web page. The json file is updated dynamically with data about movies from an api. The function that I am using right now is giving a syntax error about needing a name.
I have tried naming the function but so far nothing has worked. I'm new to web development so if it's an obvious answer I'm sorry.
index.html
<!DOCTYPE html>

<title>Furby</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="static/layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">

Find A Movie

Search from thousands of online movies!

              <form class="group" method="post" action="search" onsubmit="function();">
                <fieldset>
                  <legend>Search:</legend>
                  <input type="text" value="" placeholder="Search Here…" name="search">
                  <button class="fa fa-sign-in" type="submit" title="Submit">Submit</button>
                </fieldset>
              </form>

                  Title
                  Cover

The code below will update my table with the movie titles and images once but I have to do a hard refresh on the page to get it to update. I assume it's the name error that is preventing it from running this code every time I search a movie.

EDIT: Added more relevant code. Sorry this is my first time posting.

A: Remove the inline event listener from the form.
<form class="group" method="post" action="search">

Name your function
function performSearch () {
  var table = document.getElementById('userdata');
  for (var i = table.rows.length - 1; i > 0; i--) {
    table.deleteRow(i);
  }
  $.getJSON('static/movies.json', function(data) {
    $.each(data.movie, function(i, f) {
      var url = "https://image.tmdb.org/t/p/w92/" + f.url;
      var tblRow = "
" + "" + f.title + "	" + "" + "" + "	" + "
"
      $(tblRow).appendTo("#userdata tbody");
      document.getElementById('url_img').src = url;
      document.getElementById('url_img').id = url;
    });
  });
}

Call your function on page load.
$(function(){
    performSearch();
});

And setup the form to perform the search on submit.
$(function(){
    performSearch();

    $('.group[action="search"]').on('submit', function(e){
        e.preventDefault();
        performSearch();
    });
});

A: 1 ) You have 2 jQuery Lib, that wrong,  you need only one also check versions

. . .

2) your HTML table is not valid : you forget placing forget
 ....

        Title
        Cover

I also place the id="userdata-tbody" on the
 otherwise you also delete your
 row
so place your jQuery lib before the code :
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Furby</title>
  <link href="static/layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">

...

        Title
        Cover

...


text:
Q: I can't get access to my hdd So I've got this hdd, it stopped working a few months ago. Now I'm trying to see it with gparted,I'm trying to unmount all the partitions but with one of them I get this error:
https://imgur.com/YWbew8D
What can I do? Also the partitions I can't unmount are marked with a key, I don't know if the hdd is dead or something. Thanks for reading, I hope someone can help me c:
https://imgur.com/bvfS8Ji    [Gparted]


text:
Q: PyQt QFileDialog getOpenFileName not working from command line (windows) I'm trying to make a gui (Qt Designer) to import an excel file and display the data in the gui.
The script works fine when I run it from within my IDE (Spyder), but if I run it from the command window or by opening the python file from windows explorer, the import function does not work. (The gui starts up fine but when the import button is pressed and the file is selected, nothing happens and no error is produced. When running from Spyder, the data is imported and displayed in the gui as expected).
If I pre-select the file location (commented out in the code below), then the script works fine from the command line or by clicking from explorer.
Thanks for any help!
Python 2.7 (Anaconda), Windows 10, PyQt4
import sys
from PyQt4 import QtGui
from excel_import_gui import Ui_MainWindow
import xlrd

class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setupSignals()

    def set_import_data(self,data_to_import,table_to_change):
        for row in range(len(data_to_import)):
            for col in range(len(data_to_import[0])):
                table_to_change.setRowCount(len(data_to_import))
                table_to_change.setColumnCount(len(data_to_import[0]))
                item = data_to_import[row][col]
                table_to_change.setItem(row,col,QtGui.QTableWidgetItem(str(item)))

    def setupSignals(self):
        self.ui.importData_btn.clicked.connect(self.select_file)

    def select_file(self):
        excel_file = QtGui.QFileDialog.getOpenFileName(self,
        "Select Excel file to import","","Excel (*.xls *.xlsx)")

#        excel_file = "C:/Users/Ben/Work/Python tests/Qt GUIs/Excel_import_GUI/fish_test.xlsx"

        if excel_file:
            open_excel_file = xlrd.open_workbook(excel_file)
            self.start_import_data(open_excel_file)

    def start_import_data(self, workbook):
        #import data from excel file
        workbook_data = []
        for sheetNum in range (workbook.nsheets):
            worksheet = workbook.sheet_by_index(sheetNum)
            workbook_data.append([[worksheet.cell_value(row,col) for col in range (worksheet.ncols)] for row in range(worksheet.nrows)])

        # Set each worksheet of workbook_data to each tab in GUI widget
        self.set_import_data(workbook_data[0],self.ui.fish_table)
        self.set_import_data(workbook_data[1],self.ui.boats_table)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = Main()
    window.show()
    sys.exit(app.exec_())

A: Well I found a solution myself by converting the excel_file variable to a string.
excel_file = str(QtGui.QFileDialog.getOpenFileName(self, "Select Excel file to import","","Excel (*.xls *.xlsx)"))


text:
Q: Appending a python dictionary to csv I'm trying to export some API JSON data to a csv, but I only want some bits of it. I've tried row.append, but I'm getting the error TypeError: string indices must be integers.
I'm new to python, and a bit confused as to why it wants an integer.
import urllib2
import json
import csv

outfile_path='/NYTComments.csv'

writer = csv.writer(open(outfile_path, 'w'))

url = urllib2.Request('http://api.nytimes.com/svc/community/v2/comments/recent?api-key=ea7aac6c5d0723d7f1e06c8035d27305:5:66594855')

parsed_json = json.load(urllib2.urlopen(url))

print parsed_json

for comment in parsed_json['results']:
    row = []
    row.append(str(comment['commentSequence'].encode('utf-8')))
    row.append(str(comment['commentBody'].encode('utf-8')))
    row.append(str(comment['commentTitle'].encode('utf-8')))
    row.append(str(comment['approveDate'].encode('utf-8')))
    writer.writerow(row)

The parsed_json printed looks like this:
{u'status': u'OK',
u'results':
    {u'totalCommentsReturned': 25,
    u'comments':
        [{
            u'status': u'approved',
            u'sharing': 0,
            u'approveDate': u'1349378866',
            u'display_name': u'Seymour B Moore',
            u'userTitle': None,
            u'userURL': None,
            u'replies': [],
            u'parentID': None,
            u'articleURL': u'http://fifthdown.blogs.nytimes.com/2012/10/03/thursday-matchup-cardinals-vs-rams/',
            u'location': u'SoCal',
            u'userComments': u'api.nytimes.com/svc/community/v2/comments/user/id/26434659.xml',
            u'commentSequence': 2,
            u'editorsSelection': 0,
            u'times_people': 1,
            u'email_status': u'0',
            u'commentBody': u"I know most people won't think this is a must watch game, but it will go a long way .... (truncated)",
            u'recommendationCount': 0,
            u'commentTitle': u'n/a'
        }]
    }
}

A: Looks like you're making a mistake that I make all the time. Instead of
for comment in parsed_json['results']:

you want
for comment_name, comment in parsed_json['results'].iteritems():

(or .items() if you're using Python 3).
Just iterating over a dictionary (like parsed_json['results'] presumably is) gives you the keys of the dictionary, not the elements. If you do
for thing in {'a': 1, 'b': 2}:

then thing will loop over 'a' and 'b'.
Then, because that key is apparently a string, you're trying to do something like "some_name"['commentSequence'], which is causing the error message you're seeing.
dict.iteritems(), on the other hand, gives you an iterator that'll give you elements like ('a', 1) and then ('b', 2); the two variables in the for loop then get assigned to the two elements there, so comment_name == 'a' and comment == 1 here.
Since it seems like you're not actually using the key from parsed_json['results'], you could also loop for comment in parsed_json['results'].itervalues() instead.

A: for comment in parsed_json['results']: #'comment' contains keys, not values

should be
for comment in parsed_json['results']['comments']:

parsed_json['results'] itself is another dictionary.
parsed_json['results']['comments'] is the list of dictionaries you want to iterate.


text:
Q: "Stack Exchange requires external JavaScript from another domain" error I have to say that Stack Exchange website is a good one. However, for quite a long time I can not leave any messages on it and when I open the page.
I just saw 'Stack Exchange requires external JavaScript from another domain, which is blocked or failed to load'.
I just wanna know what the problem with the Stack Exchange network or something with my computer?  How to deal with this situation?

A: The message normally comes up if some JavaScript files failed to load from the network - why that happened is not something we can tell from here, or from your description.
It could be a temporary network glitch where the files are hosted. Or by your ISP/Network. It may be that you have a blocker setup somewhere, or an anti-virus that did that. Could be one of many things.
That you have posted this question shows that the issue has resolved itself - is this something that you are still experiencing then? If so - specifics like OS, browser (with versions of both) and what extensions/add-ons/plugins you have can help with figuring out the issue.


text:
Q: JMESPath - Unable to query a value in a list within another list Given the following JSON:
[
  {
    "json": {
       "buildInfo": [
         {
           "first": "James",
           "last": "d"
         },
         {
           "first": "James2",
           "last": "d2"
         }
       ]
     },
     "status": 200
   },
   {
    "json": {
       "buildInfo": [
         {
           "first": "Jacob",
           "last": "e"
         },
         {
           "first": "Jacob2",
           "last": "e2"
         }
       ]
    },
    "status": 200
  }
]

I am trying to query the inner list key json.buildInfo."last" for a value to then extract an number of  key value ie json.buildInfo.*."first".    HOwever I am struggling to get this to work.
I can find the data using a flattening operator...
[*].json.build[].last[contains(@,`d`)]

...but I cannot work out how to perform a query on this that then allows me to obtain extra information list "first" key.   On a json with no inner list on buildInfo, I can do something like
[?json.buildInfo.last==`d`].json.buildInfo.first

The switch to list of buildInfo items is proving challenging.
Can someone provide me an guidance here?
Thanks

A: OK this works - but not sure I know why...
[?json.buildInfo[?contains(last,'d2')]].json.build_info[]|[?last=='d'].first


text:
Q: How to find out which device corresponds for /sys/bus/usb/devices/deviceN I have a device connected to my Debian linux box, lsusb says:
Bus 002 Device 005: ID 0525:a4a7 Netchip Technology, Inc. Linux-USB Serial Gadget (CDC ACM mode)

In
/sys/bus/usb/devices/

I have
drwxr-xr-x 4 root root 0 Sep  7 14:27 ..
lrwxrwxrwx 1 root root 0 Sep  7 14:27 1-0:1.0 -> ../../../devices/pci0000:00/0000:00:1a.7/usb1/1-0:1.0
lrwxrwxrwx 1 root root 0 Sep  7 14:27 2-0:1.0 -> ../../../devices/pci0000:00/0000:00:1d.7/usb2/2-0:1.0
lrwxrwxrwx 1 root root 0 Sep 13 08:32 2-3 -> ../../../devices/pci0000:00/0000:00:1d.7/usb2/2-3
lrwxrwxrwx 1 root root 0 Sep 13 08:32 2-3:2.0 -> ../../../devices/pci0000:00/0000:00:1d.7/usb2/2-3/2-3:2.0
lrwxrwxrwx 1 root root 0 Sep 13 08:32 2-3:2.1 -> ../../../devices/pci0000:00/0000:00:1d.7/usb2/2-3/2-3:2.1
lrwxrwxrwx 1 root root 0 Sep  7 14:27 3-0:1.0 -> ../../../devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0
lrwxrwxrwx 1 root root 0 Sep  7 14:27 4-0:1.0 -> ../../../devices/pci0000:00/0000:00:1d.0/usb4/4-0:1.0
lrwxrwxrwx 1 root root 0 Sep  7 14:27 5-0:1.0 -> ../../../devices/pci0000:00/0000:00:1d.1/usb5/5-0:1.0
lrwxrwxrwx 1 root root 0 Sep  7 14:27 6-0:1.0 -> ../../../devices/pci0000:00/0000:00:1d.2/usb6/6-0:1.0
lrwxrwxrwx 1 root root 0 Sep  7 14:27 usb1 -> ../../../devices/pci0000:00/0000:00:1a.7/usb1
lrwxrwxrwx 1 root root 0 Sep  7 14:27 usb2 -> ../../../devices/pci0000:00/0000:00:1d.7/usb2
lrwxrwxrwx 1 root root 0 Sep  7 14:27 usb3 -> ../../../devices/pci0000:00/0000:00:1a.0/usb3
lrwxrwxrwx 1 root root 0 Sep  7 14:27 usb4 -> ../../../devices/pci0000:00/0000:00:1d.0/usb4
lrwxrwxrwx 1 root root 0 Sep  7 14:27 usb5 -> ../../../devices/pci0000:00/0000:00:1d.1/usb5
lrwxrwxrwx 1 root root 0 Sep  7 14:27 usb6 -> ../../../devices/pci0000:00/0000:00:1d.2/usb6

How to find out which device is this?

A: I found / modify a script to get the /sys device based on lsusb output.
#!/bin/bash
#
# usb2sys - find lsusb device in /sys file system
#

die()
{
    echo "$@"
    exit 1
}

[[ $# -lt 1 ]] && die "need vendor and product ids (from lsusb) as dddd:dddd"

vendor=${1%:*}
product=${1##*:}

sys=/sys/bus/usb/devices/
cd $sys

for d in *; do
    path=$sys$d
    if [ -f $path/idProduct ]; then
      prod=$( cat $path/idProduct )
      vend=$( cat $path/idVendor )

      if [ $prod = $product -a $vend = $vendor ]; then
        echo prod = $prod
        echo vend = $vend
        echo /sys device is $path
      fi
    fi
done

the idea is to get the string 1d6b:0002 and check agains which is the idProduct:idVendor couple and compare it to the existing usb in /sys
You can use the script like this
lsusb | cut -d ' ' -f 6 | xargs -L 1 ./usb2sys

The output would be something like
prod = 0002
vend = 1d6b
/sys device is /sys/bus/usb/devices/usb1


text:
Q: What is the equivalent of bash export in Perl? I am converting a bash script to Perl. I am not sure what the equivalent of an export is.
LOC=/tmp/1/
export LOC

For example, for the above two lines, what would be the equivalent Perl code?
my $LOC = '/tmp/1/';
# what should go here?

A: $ENV{LOC} = "/tmp/1";

The contents of %ENV are propagated to the environment of the child processes of a Perl script.

A: Module Env (see http://perldoc.perl.org/Env.html)

A: Inside the bash, you might want to do something like this:
EXPORT_CMD=/tmp/${0}_exports.bsh
perl ...
chmod +x $EXPORT_CMD
$EXPORT_CMD
rm $EXPORT_CMD

Inside the Perl, this:
sub export (@) {
    state $exh;
    unless ( $exh ) {
        my $export_cmd_path = $ENV{EXPORT_CMD};
        open( $exh, '>>', $export_cmd_path )
            or die "Could not open $export_cmd_path!"
            ;
    }
    while ( @_ > 1 ) {
        my ( $name, $value ) = (( uc shift ), shift );
        # If you want it visible in the current script:
        {   no strict 'refs';
            ${"::$name"} = $value;
        }
        $exh->print( qq{export $name "$value"\n} );
    }
}

And then, it's simply a matter of coding this:
export LOC => '/tmp/1/';

The problem is that most programs cannot change shell variables that they were called from.


text:
Q: Pass data from RecyclerView in Fragment to another Fragment I have application with RecycleView and after click on row I need open another RecycleView in another Fragment based on data which was in clicked row in first RecycleView. I had application where it was working, and now I want DrawerMenu and Fragments, and I don't know how to do it. I'm newbie on Android and all what I know is from tutorials.
BaseActivity
package cz.revelio.mhdapp;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;

public class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private DrawerLayout drawer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    drawer = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                new ZapisFragment()).commit();
        navigationView.setCheckedItem(R.id.nav_message);
    }
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {

        case R.id.nav_chat:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new ZapFragment()).commit();
            break;
        case R.id.nav_profile:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new SeznamFragment()).commit();
            break;
        case R.id.nav_message:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new ZapisFragment()).commit();
            break;
        case R.id.nav_share:
            Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
            break;
        case R.id.nav_send:
            Toast.makeText(this, "Send", Toast.LENGTH_SHORT).show();
            break;
    }

    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}
}

From BaseActivity I can call SeznamFragment where is first RecyclerView:
   package cz.revelio.mhdapp;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;

public class SeznamFragment extends Fragment {
    RecyclerView recyclerView;
    DatabaseHelper mDatabaseHelper;
    TextView info;
    Context context;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v =  inflater.inflate(R.layout.fragment_seznam, container, false);
    info = (TextView) v.findViewById(R.id.info_count_in_dash);
    recyclerView= (RecyclerView) v.findViewById(R.id.recyclerview);
    mDatabaseHelper = new DatabaseHelper(context);
    int vsechyZaznamy = mDatabaseHelper.getCountAllLogs();
    int unikatniZaznamy = mDatabaseHelper.getCountUniqueLogs();
    info.setText(vsechyZaznamy+" záznamů, z toho "+unikatniZaznamy+" unikátních.");
    getData();
    return v;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = getContext();

}
public void getData(){
    List<String> dataZaznamy = mDatabaseHelper.getAllLogs();
    String[] zaznamy = new String[dataZaznamy.size()];
    zaznamy = dataZaznamy.toArray(zaznamy);
    recyclerView.setLayoutManager(new LinearLayoutManager(context));
    recyclerView.setAdapter(new Adapter(context,zaznamy));
}

}

Adapter.java of RecycleView:
package cz.revelio.mhdapp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    Context context;
    String[] items;
    public Adapter(Context context, String[] items){
        this.context=context;
        this.items=items;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View row = inflater.inflate(R.layout.costume_row, viewGroup, false);
    Item item=new Item(row);
    return item;
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
    String text = items[position];
    final String casti[] = text.split(",");
    ((Item)viewHolder).itemName.setText(casti[0]);
    ((Item)viewHolder).itemCount.setText(casti[2]+"x");
    ((Item)viewHolder).itemLast.setText("Naposledy zapsáno:  "+casti[3]);
    ((Item) viewHolder).lay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Toast.makeText(context, "OnClick Called on position "+position+" a lince "+ casti[0], Toast.LENGTH_SHORT).show();
         Fragment fragment = new VehicleFragment();
         Bundle b = new Bundle();
         b.putString("vehicle_id", casti[0]);
         fragment.setArguments(b);

         //android.support.v4.app.FragmentManager fragmentManager = get
          /*  Intent intent = new Intent(context, VehicleList.class);
            intent.putExtra("vehicle_id", casti[0]);
            context.startActivity(intent);*/
        }
    });
    ((Item) viewHolder).lay.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            //Toast.makeText(context, "OnLongClick Called on position "+position, Toast.LENGTH_SHORT).show();
            return true;
        }
    });
}

@Override
public int getItemCount() {
    return items.length;
}
public class Item extends RecyclerView.ViewHolder {
    TextView itemName;
    TextView itemCount;
    TextView itemLast;
    ConstraintLayout lay;

    public Item(View itemView){
        super(itemView);
        itemName= (TextView) itemView.findViewById(R.id.item_name);
        itemCount= (TextView) itemView.findViewById(R.id.item_count);
        itemLast= (TextView) itemView.findViewById(R.id.item_last);
        lay = (ConstraintLayout) itemView.findViewById(R.id.item_rr);
    }
}

}

VehicleFragment where is second RecyclerView and where I need data from SeznamFragment.java:
package cz.revelio.mhdapp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

public class VehicleFragment  extends Fragment {

    private static final String TAG = "LineList";
    RecyclerView recyclerView;
    DatabaseHelper mDatabaseHelper;
    Context context;
    String vehicle_id;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_seznam, container, false);

    }

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = getContext();
    mDatabaseHelper = new DatabaseHelper(context);

    //getIncomingIntent();
}

/*private void getIncomingIntent(){

    if(getActivity().getIntent().hasExtra("vehicle_id")){
        String vehicle_id =  getActivity().getIntent().getStringExtra("vehicle_id");
        getData(vehicle_id);
    }
}*/

public void getData(String id_vehicle){
    List<String> dataZaznamy = mDatabaseHelper.getAllLogsByVehId(id_vehicle);
    String[] zaznamy = new String[dataZaznamy.size()];
    zaznamy = dataZaznamy.toArray(zaznamy);
    recyclerView.setLayoutManager(new LinearLayoutManager(context));
    recyclerView.setAdapter(new AdapterVehicle(context,zaznamy));
    }

}

AdapterVehicle of second RecyclerView:
package cz.revelio.mhdapp;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class AdapterVehicle extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    DatabaseHelper mDatabaseHelper;
    Context context;
    String[] items;

    public AdapterVehicle(Context context, String[] items){
        this.context=context;
        this.items=items;

    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View row = inflater.inflate(R.layout.costume_row_veh, viewGroup, false);
        Item item=new Item(row);
        return item;
    }
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
    mDatabaseHelper = new DatabaseHelper(context);
    String text = items[position];
    final String casti[] = text.split(",");
    if(casti[5].equals("true")) {
        ((Item) viewHolder).itemName.setText("Jízda linkou " + casti[1]);
    }else{
        ((Item) viewHolder).itemName.setText("Linka " + casti[1]);
    }
    ((Item)viewHolder).itemCount.setText(casti[2]);
    ((Item)viewHolder).itemLast.setText(casti[3]);
    ((Item) viewHolder).lay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Toast.makeText(context, "OnClick Called on position "+position+" a lince "+ casti[0], Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(context, VehicleEdit.class);
            intent.putExtra("vehicle_id", casti[0]);
            intent.putExtra("line", casti[1]);
            intent.putExtra("datum", casti[2]);
            intent.putExtra("cas", casti[3]);
            intent.putExtra("jedu", casti[5]);
            intent.putExtra("id", casti[4]);
            context.startActivity(intent);
        }
    });
    ((Item) viewHolder).lay.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            //Toast.makeText(context, "OnLongClick Called on position "+position, Toast.LENGTH_SHORT).show();
            //pass the 'context' here
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
            alertDialog.setTitle("Smazat záznam");
            alertDialog.setMessage("Chcete záznam smazat?");
            alertDialog.setPositiveButton("Ano", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Toast.makeText(context, "Záznam vozidla "+casti[0]+" na lince "+casti[1]+" byl smazán.", Toast.LENGTH_SHORT).show();
                    mDatabaseHelper.removeItem(casti[4]);
                    notifyDataSetChanged();
                    Intent intent = new Intent(context, SeznamFragment.class);
                    context.startActivity(intent);
                }
            });
            alertDialog.setNegativeButton("Ne", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            AlertDialog dialog = alertDialog.create();
            dialog.show();
            return true;
        }
    });
}

@Override
public int getItemCount() {
    return items.length;
}
public class Item extends RecyclerView.ViewHolder {
    TextView itemName;
    TextView itemCount;
    TextView itemLast;
    ConstraintLayout lay;

    public Item(View itemView){
        super(itemView);
        itemName= (TextView) itemView.findViewById(R.id.item_name_veh);
        itemCount= (TextView) itemView.findViewById(R.id.item_count_veh);
        itemLast= (TextView) itemView.findViewById(R.id.item_last_veh);
            lay = (ConstraintLayout) itemView.findViewById(R.id.item_rr_veh);
        }
    }
}

I  tried another solutions from StackOvreflow but nothing work for me.
Here you can find my actual codes
https://drive.google.com/file/d/1W6OzBCjwH4PJkix73woLCHHDBrh26-U1/view?usp=sharing

A: you can pass with Bundle :
public static VehicleFragment newInstance(String your_data_if_its_string) {
        VehicleFragment frag = new VehicleFragment();
        Bundle args = new Bundle();
        args.putString(PersonDBFields.ID, person_id);
        frag.setArguments(args);
        return frag;
    }

place it in your VehicleFragment,
and use VehicleFragment.newInstance("yourData"); or you can create a field in your class and make a Setter for it  , then call setter method instead of Bundle  inside your new instance.

A: you are doing everything right except you are not adding it to the fragment manager that's why you are not able to start SecondFragment. Do it like this :
    VehicleFragment frag = new VehicleFragment();
    Bundle args = new Bundle();
    args.putString(PersonDBFields.ID, person_id);
    frag.setArguments(args);
    return frag;

//now add it to the fragment manager.like you are doing in your activity
getFragmentManager().beginTransaction().add(R.id.container, frag).commit();

In onCreateView of the new VehicleFragment:
//Retrieve the value
String value = getArguments().getString("YourKey");

you have to get the fragment manager inside your adapter class.
   @Override
    public void onClick(View view){
     VehicleFragment vehicleFragment =VehicleFragment.getInstance();
     Bundle b = new Bundle();
     b.putString("vehicle_id", casti[0]);
     vehicleFragment.setArguments(b);
    AppCompatActivity activity = (AppCompatActivity) view.getContext();
    activity.getSupportFragmentManager().beginTransaction()
   .replace(R.id.fragment_container,
    myFragment).addToBackStack(null).commit();

 }

A: Recently, Android Jetpack has some pretty good libraries that have ViewModel objects that make it easier to manage and store data.
It lets you access data at different activities or fragments in an application. You try it and hope it will be useful to you


text:
Q: how to disable listview column resizing? I want to disable listview column resizing. How can i do it?

A: Add a new class to your project and paste the code shown below.  Build.  Drag the new control from the top of your toolbox onto a form.

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class FixedColumnView : ListView {
  private HeaderWindow mHeader;
  public FixedColumnView() {
    this.View = View.Details;
  }
  protected override void WndProc(ref Message m) {
    Console.WriteLine(m.ToString());
    if (m.Msg == WM_DESTROY) {
      // Un-subclass header control
      if (mHeader != null) mHeader.ReleaseHandle();
      mHeader = null;
    }
    if (m.Msg == WM_NOTIFY) {
      // Prevent dragging
      NMHDR nm = (NMHDR)m.GetLParam(typeof(NMHDR));
      if (nm.code == HDN_BEGINTRACK) {
        m.Result = (IntPtr)1;
        return;
      }
    }
    base.WndProc(ref m);
    if (m.Msg == WM_CREATE) {
      // Subclass the header control
      IntPtr hWnd = SendMessage(this.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);
      if (mHeader == null || mHeader.Handle != hWnd) {
        if (mHeader != null) mHeader.ReleaseHandle();
        else mHeader = new HeaderWindow();
        mHeader.AssignHandle(hWnd);
      }
    }
  }
  private class HeaderWindow : NativeWindow {
    protected override void WndProc(ref Message m) {
      if (m.Msg == WM_SETCURSOR) {
        // Prevent cursor from changing
        m.Result = (IntPtr)1;
        return;
      }
      if (m.Msg == WM_LBUTTONDBLCLICK) {
        // Prevent double-click from changing column
        return;
      }
      base.WndProc(ref m);
    }
  }
  // P/Invoke declarations
  private const int WM_CREATE = 0x0001;
  private const int WM_DESTROY = 0x0002;
  private const int WM_SETCURSOR = 0x0020;
  private const int WM_NOTIFY = 0x004e;
  private const int WM_LBUTTONDBLCLICK = 0x0203;
  private const int LVM_GETHEADER = 0x101f;
  private const int HDN_FIRST = -300;
  private const int HDN_BEGINTRACK = HDN_FIRST - 26;
  [StructLayout(LayoutKind.Sequential)]
  private struct NMHDR {
    public int hWndFrom;
    public int idFrom;
    public int code;
  }
  [DllImport("user32.dll")]
  private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

}

And also view this
http://www.codeproject.com/KB/cpp/LVHeaderSubclass.aspx

A: If you want some columns resizable and other not resizeable, use ObjectListView. In that control, each column can be given a Max/Min width. See this recipe for instructions.


text:
Q: Objects into two bags puzzle I found a maths puzzle somewhere and a part of it as below:
Kelly wants to place n objects $a_1,a_2,⋅⋅⋅,a_n$ into two bags.
For each $i=1,2,⋅⋅⋅,n$, the weight of $a_i$ is $w_i$ kilograms.
The capacity of each bag is not a problem as it is not limited.
Kelly wants to minimize the weight of the most heavy bag. So this is what she does:
She ordered in an arbitrary order.
She always places the object under consideration into the least heavy bag.
At the end when all objects are in the bags, Kelly finds that the weight of the most heavy bag is at most 3/2 times the optimum.
How? ? ? How can she get to know that?
Extended version of Weights - Objects into bags puzzle.
Any examples would make me understand better.Can we deduce a formula for such cases?

A: let the sum of weights be $2s+m$ and let $m$ be the weight of the heaviest bag, then the heaviest the heavier side can get with the proposed method is $s+m$.
On the other hand the heavier side will always weight at least $\frac{2s+m}{2}$.
So we get the ratio of the heavy bag over the optimum is at most $\dfrac{s+m}{\frac{2s+m}{2}}=\dfrac{2s+2m}{2s+m}=1+\frac{m}{2s+m}$.
if $m$ is less than half of the total weight we are done, if $m$ is more than half of the total weight the optimum is clearly when $m$ is alone in the bag. And the worst case scenario is when the heavier bag has $m+s$ and the other side $s$. In this case the ratio of the worst case vs the optimum is $\frac{s+m}{m}=1+\frac{s}{m}$ which is less than $1+\frac{1}{2}$ since $m$ is at least twice as $s$ in this case.

A: Hints:

*

*Use exactly the same reasoning as in my answer to your previous question, just devise a stronger inequality.

*When adding an item of weight $w$, the weight of the bag with the smallest load is at most $$\frac{2M-w}{2}.$$

I hope that helps $\ddot\smile$


text:
Q: How to understand the master and worker processes---R package "parallel"? As I tried to understand the documentation of the R package parallel, I encountered this question as I read some lines of codes on Page 8 in the package's documentation. I have copied the code in the following. Please note that mc is just equal to 2.
# mc = 2
cl <- makeCluster(mc)
cd4.rg <- function(data, mle) MASS::mvrnorm(nrow(data), mle$m, mle$v)
cd4.mle <- list(m = colMeans(cd4), v = var(cd4))
clusterExport(cl, c("cd4.rg", "cd4.mle"))
junk <- clusterEvalQ(cl, library(boot)) # discard result
clusterSetRNGStream(cl, 123)
res <- clusterEvalQ(cl, boot(cd4, corr, R = 500,
+                   sim = "parametric", ran.gen = cd4.rg, mle = cd4.mle))
library(boot) # needed for c() method on master
cd4.boot <- do.call(c, res)
boot.ci(cd4.boot, type = c("norm", "basic", "perc"),
+                   conf = 0.9, h = atanh, hinv = tanh)
stopCluster(cl)

In Line 5, the command library(boot) has been evaluated on cl, but in line 8 library(boot) is run again and the author says it is needed for c() method on master.
My original understanding is that: makeCluster(mc) creates two worker processes, and the master process is one of them. Now it looks that each of the workers created by makeCluster(mc) is different from the master process. And thus library(boot) has to be run on the master process. Am I right on this?
If I have an 8-core CPU, does this mean that creating more than seven (>7) worker processes is totally non-useful? Thank you.

A: On my system, makeCluster(2) can be seen to create 2 additional R processes (I'm on Windows and can see them in Resource Monitor). So the "workers" appear to be different from, and additional to, the "master" process.
As regards the libraries, a quick way to check is to ask each worker for its loadedNamespaces(). The below transcript shows this for the example of the foreach package  being loaded on the two workers, with the loadedNamespaces() for the workers and the master before and after.
Since only the worker processes are used to execute the expression by clusterEvalQ, increasing the number of workers to a maximum of 8 would seem sensible at face value. Real performance will depend on other factors like the number of logical cores available on your 8-core system, what each core is doing in your processing, and what else is happening on the system at the time, ...
Transcript:
library(parallel)
cl <- makeCluster(2)
loadedNamespaces() # get loaded namespaces on master
# [1] "base"      "datasets"  "graphics"  "grDevices" "methods"   "parallel"  "stats"     "utils"
clusterEvalQ(cl, loadedNamespaces()) # get loaded namespaces on workers
# [[1]]
# [1] "base"      "datasets"  "graphics"  "grDevices" "methods"   "parallel"  "stats"     "utils"
#
# [[2]]
# [1] "base"      "datasets"  "graphics"  "grDevices" "methods"   "parallel"  "stats"     "utils"
#
invisible( clusterEvalQ(cl, library(foreach)) ) # load foreach on workers
loadedNamespaces() # check master
# [1] "base"      "datasets"  "graphics"  "grDevices" "methods"   "parallel"  "stats"     "utils"
clusterEvalQ(cl, loadedNamespaces()) # check workers
# [[1]]
#  [1] "base"      "codetools" "datasets"  "foreach"   "graphics"  "grDevices" "iterators" "methods"   "parallel"  "stats"     "utils"
#
# [[2]]
#  [1] "base"      "codetools" "datasets"  "foreach"   "graphics"  "grDevices" "iterators" "methods"   "parallel"  "stats"     "utils"
#
library(foreach) # load foreach on master
# foreach: simple, scalable parallel programming from Revolution Analytics
# Use Revolution R for scalability, fault tolerance and more.
# http://www.revolutionanalytics.com
loadedNamespaces() # check again
# [1] "base"      "codetools" "datasets"  "foreach"   "graphics"  "grDevices" "iterators" "methods"   "parallel"  "stats"     "utils"
stopCluster(cl) # tidy up


text:
Q: Make Tinymce listbox work with mobile devices I am using a standard tinymce ui listbox (basically a button with a dropdown) with a few options.
I would like to make it work on mobile devices. But i do not seem to be able to achieve this.
I can access the control element of the listbox, but i am not able to find the dom elements that hold the options using the control element. If i would be able to get to them i could bind a touchstart handler and trigger the necessary function.
Does anyone know a solution to this problem or has a workaround?
Thx in advance

A: Found out it seems to work out of the box, but what i am trying to do onselect causes a problem.
Here is working a tinymce fiddle example just in case someone needs help.


text:
Q: копирование строки в ассемблере без счётчика Не могу понять как сделать, изучаю ассемблер. Создаю две локальные переменные. В одну записываю строку из четырех байт. нужно скопировать из этой строки в другую без счётчика. проверять нужно только байт на ноль. если байт равен нулю, то циклю копирования закончить. и вот проблема. если я загружу в esi [ebp - 0x17], то загрузится значение, а не адрес. и ещё нельзя делать так mov byte [ebp + edx], al. в общем вот код, посмотрите пожалуйста.
  1 section .text
  2
  3 global _start
  4
  5 dd:
  6         push ebp
  7         mov ebp, esp
  8         sub esp, 0x28
  9         mov dword [ebp - 0x17], 0x34333231
 10         mov word [ebp - 0x13], 0x0
 11
 12         cld
 13         mov esi, [ebp - 0x17]
 14         mov ecx, 0x19
 15 ;       mov edi, [ebp - 0x19]
 16 loop:
 17         lodsb
 18         mov byte [ebp - ecx], al
 19         inc ecx
 20         test al, al
 21         jnz loop
 22         leave
 23         retn
 24
 25 _start:
 26         push ebp
 27         mov ebp, esp
 28         and esp, 0xfffffff0
 29         call dd
 30
 31         mov eax, 1
 32         mov ebx, 0
 33         int 0x80
 34         ret
 35

A: Сделал так, вроде работает.
  1 section .text
  2
  3 global _start
  4
  5 dd:
  6         push ebp
  7         mov ebp, esp
  8         sub esp, 0x28
  9         mov dword [ebp - 0x17], 0x34333231
 10         mov word [ebp - 0x13], 0x0
 11
 12         cld
 13         lea esi, [ebp - 0x17]
 14         mov ecx, 0x19
 15 ;       mov edi, [ebp - 0x19]
 16 loop:
 17         lodsb
 18         mov byte [ebp + ecx], al
 19         inc ecx
 20         test al, al
 21         jnz loop
 22         leave
 23         retn
 24
 25 _start:
 26         push ebp
 27         mov ebp, esp
 28         and esp, 0xfffffff0
 29         call dd
 30
 31         mov eax, 1
 32         mov ebx, 0
 33         int 0x80
 34         ret


text:
Q: Persistent error : http status 503 Here's the scenario:
At work, for a glassfish server, i'm having a persistent error http status 503, whenever I test a specific wsdl (corresponding to a specific glassfish module),  in a web browser.
For te same server glassfish, i have other wsdl's corresponding to other glassfish modules. I've tested these very same wsdl's and it works.
I've already tried to :

*

*Desactivate and Activate the glassfish module ;

*Reinstall again the problematique glassfish module ;

*Reinstall an older version of the very same glassfish module
(Returns http status 503);

*Ping pools fron the server glassfish

*Reboot only the glassfish server ;

*Reboot the physical machine ;

Despite all these actions, i'm having weird error messages in the log file that i don't understand. Can anyone please help ?
Thanks in advance.
Log file :

[#|2018-06-19T23:34:21.311+0200|SEVERE|sun-appserver2.1.1|javax.enterprise.system.container.web|_ThreadID=30;_ThreadName=Thread-200;_RequestID=c23284fb-2dea-4a9a-86fc-5d764902c84a;|WebModule[/echange_operateur]PWC1275: Exception sending context initialized event to listener instance of class fr.bouyguestelecom.dolmen.access.ftth.exchange.servlet.TimerServletListener
javax.ejb.EJBException: Unable to complete container-managed transaction.; nested exception is: javax.transaction.SystemException: org.omg.CORBA.INTERNAL: JTS5022: Unexpected exception [com.sun.jts.CosTransactions.LogException: Log exception at point 14:
LOG-003: Read failure] from log.  vmcid: 0x0  minor code: 0  completed: No
javax.transaction.SystemException: org.omg.CORBA.INTERNAL: JTS5022: Unexpected exception [com.sun.jts.CosTransactions.LogException: Log exception at point 14:
LOG-003: Read failure] from log.  vmcid: 0x0  minor code: 0  completed: No
           at fr.bouyguestelecom.dolmen.access.ftth.exchange.servlet.TimerServletListener.contextInitialized(TimerServletListener.java:22)
javax.ejb.EJBException: Unable to complete container-managed transaction.; nested exception is: javax.transaction.SystemException: org.omg.CORBA.INTERNAL: JTS5022: Unexpected exception [com.sun.jts.CosTransactions.LogException: Log exception at point 14:
LOG-003: Read failure] from log.  vmcid: 0x0  minor code: 0  completed: No

A: I still can not figure out the error messages found in the log file, but I've managed to solve the problem by :

*

*Stop problematic Glassfish module ;

*Restart glassfish Server ;

*Start problematic Glassfish module ;
After this action I got a response from the wsdl.
I hope it can help other people with the same or similar probleme.


text:
Q: Why this simple sql transaction wanna a S lock more after it holding an X lock? my table's definition is like:
 CREATE TABLE `test_table` (
  `a` int,
  `b` int,
  PRIMARY KEY (`a`),
  UNIQUE KEY `idx_b` (`b`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

and Isolation Level is: Read Committed (RC)
and query sql is like: update test_table set a=LAST_INSERT_ID(a + 1) WHERE b= 1;
when multiple clients requests to execute the same SQL at the same time, mysql maybe occur a deadlock error, and deadlock log is like :
------------------------
LATEST DETECTED DEADLOCK
------------------------
2020-05-26 18:04:12 0x7efb06c5d700
*** (1) TRANSACTION:
TRANSACTION 261901143, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 1136, 1 row lock(s)
MySQL thread id 6018875, OS thread handle 139617907197696, query id 3320727857 10.202.6.165 ma88 updating
update test_table set a=LAST_INSERT_ID(a + 1) WHERE b=1
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 6485 page no 4 n bits 272 index idx_b of table test_db.test_table trx id 261901143 lock_mode X locks rec but not gap waiting
Record lock, heap no 148 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
 0: len 1; hex 06; asc  ;;
 1: len 4; hex 00aeae62; asc    b;;

*** (2) TRANSACTION:
TRANSACTION 261901142, ACTIVE 0 sec updating or deleting, thread declared inside InnoDB 4999
mysql tables in use 1, locked 1
4 lock struct(s), heap size 1136, 3 row lock(s), undo log entries 2
MySQL thread id 6018874, OS thread handle 139616615520000, query id 3320727856 10.202.6.165 ma88 updating
update test_table set a=LAST_INSERT_ID(a + 1) WHERE b=1
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 6485 page no 4 n bits 272 index idx_b of table test_db.test_table trx id 261901142 lock_mode X locks rec but not gap
Record lock, heap no 148 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
 0: len 1; hex 06; asc  ;;
 1: len 4; hex 00aeae62; asc    b;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 6485 page no 4 n bits 272 index idx_b of table test_db.test_table trx id 261901142 lock mode S waiting
Record lock, heap no 148 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
 0: len 1; hex 06; asc  ;;
 1: len 4; hex 00aeae62; asc    b;;

*** WE ROLL BACK TRANSACTION (1)

via this deadlock log, I found that:
the transation-1 is waiting for the an X lock which is holding by transaction-2, and transaction-2 want a S Lock for the same data, then deadlock.
what i couldn't understand is why the transaction-2 want a S Lock while it hold an X Lock in this case.
can anyone give me an answer or some idea?

A: Consider pulling the UPDATE out of the transaction.  It may lead to "burning" some sequence numbers.


text:
Q: QLPreviewController and UTF8 characters I have an iPhone app that saves text files with UTF8 characters (umlauts, etc).  If I then view the file with the QLPreviewController, the UTF8 characters are not displayed correctly.  If I view the same file with other apps (Evernote, for example), or copy them to the desktop and view them with textedit, they appear correct.
Is anyone aware of a problem or a workaround for this problem?

A: I came across the same problem and found that QLPreviewController only seems to display UTF16-encoded text correctly. So I re-encoded my text file before presenting it:
NSString* text = ... // Load UTF8-encoded text

NSError* error = nil;

if( [text writeToURL:localFileURL atomically:YES encoding:NSUTF16StringEncoding error:&error] )
{
    // Continue presenting the QLPreviewController from localFileURL
}
else
{
    NSLog( @"An error occured: %@", error );
}

Tested on iOS 6.0.1.


text:
Q: Pass Data between two view controllers using 'Delegation' : Objective-C I am implementing an library(.a), and I want to send notification count from library to app so they can show in their UI, notification count. I want them to implement the only method like,
-(void)updateCount:(int)count{
    NSLog(@"count *d", count);
}

How can I send the count from my library continuously so they can use it in updateCount method to show.
I searched and come to know about call back functions. I have no idea how to implement them. Is there any other way to do this.

A: You have 3 options

*

*Delegate

*Notification

*Block,also known callback

I think what you want is Delegate
Assume you have this file as lib
TestLib.h
#import <Foundation/Foundation.h>
@protocol TestLibDelegate<NSObject>
-(void)updateCount:(int)count;
@end

@interface TestLib : NSObject
@property(weak,nonatomic)id<TestLibDelegate> delegate;
-(void)startUpdatingCount;
@end

TestLib.m
#import "TestLib.h"

@implementation TestLib
-(void)startUpdatingCount{
    int count = 0;//Create count
    if ([self.delegate respondsToSelector:@selector(updateCount:)]) {
        [self.delegate updateCount:count];
    }
}
@end

Then in the class you want to use
#import "ViewController.h"
#import "TestLib.h"
@interface ViewController ()<TestLibDelegate>
@property (strong,nonatomic)TestLib * lib;
@end

@implementation ViewController
-(void)viewDidLoad{
self.lib = [[TestLib alloc] init];
self.lib.delegate = self;
[self.lib startUpdatingCount];
}
-(void)updateCount:(int)count{
    NSLog(@"%d",count);
}

@end


text:
Q: Accessing WPDB Multidimensional JSON Array w/ Javascript I am having trouble accessing json values return from an ajax call.
Here is the call:
    $.ajax({
    type: 'POST',
    data: 'user_id=' + user.user_id + '&user_login='+ user.user_login,
    //dataType: 'json',
    url: 'http://###/user-stats.php',
    success: function(data){
        alert(data);
        //alert(data.games_won[0]['winner_id']);
        //console.log(data);
        if(data) {
            $('#hand-stats-display').html(data);
            //$.mobile.changePage( "#user-home", { transition: "fade"} );
        }else{
            $('.messages').html("No stats available at this time... Please try again later.");
            //alert(data);
        }

    },
    error: function(){
        //console.log(data);
        alert('Ajax Login Request ✗');
    }
    });

Here is the PHP:
$myrows['hands_won'] = $wpdb->get_results( "SELECT * FROM wp_winners WHERE user_id=" . $user_id );

if ( $myrows )
{
    //echo('Rows Exist ✓');
    //echo "List of {$meta_key1} posts, sorted by {$meta_key2}";
    foreach ( $myrows as $id )
    {
        $creds[]=$id;
        //echo('MyRows: ' . $myrows[id]);
    }
}

//echo "Winner ID:" .$myrows[0]->win_id;
//echo "Winner 2 ID:" .$myrows[1]->win_id;

echo json_encode($creds);

It returns a json object like:
[{"win_id":"1","user_id":"1","game_id":"1"},{"win_id":"2","user_id":"1","game_id":"2"}]

I can not seem to access these with the javascript I am using. Any advice is appreciated.

A: Looks like you want to use something like result = $.parseJSON(data).  Then you can access the data with result.win_id, for example.
As an aside, you should sanitize the input to that database query using prepare with something like:
$wpdb->get_results( $wpdb->prepare( "SELECT * FROM wp_winners WHERE user_id=%d", $user_id ) );


text:
Q: Short story about creating a math of facial expressions I'm looking for a short story I read either in Asimov's or Analog, probably in the late 90's. It starts with a bag of frozen peas spilling all over the floor in a world where everyone instinctually knows exactly how many peas there are without counting.  A world in which 1st grades don't need to learn addition and subtraction because it's obvious and instead learn calculus.  Math, in terms of numbers, is unheard of in his society, however the calculation of facial  expressions is a very difficult task involving the angle and height of eyebrows etc.  One child cannot figure out numbers but reads facial expression with ease.  It's sort of like a reverse autism story.  Does anybody know the title of this story or what issue it was in?
Thanks so much!!

A:
Analog SF&F magazine, March 2007 "Trucks" by Amy Bechtel.  From a review site:

Amy Bechtel postulates a world in which the typical person
  demonstrates savant skills when it comes to numbers in "Trucks." The
  flipside, however, is that daily tasks like reading expressions and
  basic social interactions are more difficult for people.  Ryan is a
  young boy who has been labeled slow because of his inability to
  understand numbers, but his mom slowly comes to realize there are more
  ways to look at his situation than first meet the eye.  However,
  Bechtel never really explains how her world and the rewiring of
  people's minds came to happen, so even though the story is meant to be
  read allegorically, the fact that there is no explanation for her
  world tends to get in the way.

An interesting flip-flop world where the children want to be the "Slipstick Libby" calculators on the first trip to the Moon, but adults have to measure eyebrows, lips, and eyes on faces by millimeters to guess emotions.


text:
Q: Today solution (?) using modified and JS I had no luck with a solution for the [Today] Problem so far, pretty much all the solutions on the web have a catch. So I thought, why not use the Modified field instead of Today? All that is needed is to keep updating the items daily. I want to avoid the workflow Loop, thus the best solution seems to include a Script Editor Web Part, that will update the column for all items (let's call it "ColumnUpdate") every time the page is refreshed.
So the idea is every time the user opens the page with the list, the script will update the ColumnUpdate for all items, thus Modified is set to today, thus calculated fields (eg "due days") are updated.
I tried to figure out the script, but I'm not very familiar with JavaScript and pretty much nothing succeeded so far.
This is the last one I tried:
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript">   </script>
<script type="text/javascript">

$("input[title='ColumnUpdate']").val('abc');

</script>

Any help will be highly appreciated!!

A: Edit to handle Minimal Download Strategy (MDS) which is turned on by default
If you don't need to store the Next Due value I would just use Client-Side Rendering to generate it on each view and render it to your users.
I have an answer to another question that is quite similar to the situation I'm proposing, you can find it here: Days Past Since List Item Created - SharePoint Online 2013
To summarize and provide some instructions specific to your situation though:

*

*Create the Next Due field in your list. The type and value don't
actually matter, we're just going to use it as a place-holder.

*Create a new JS file (I named mine jsLinkTest.js) and store it in
somewhere like an Asset Library (I use SharePoint Online, so I don't
have access to put stuff in _layouts, or anything like that -- plus
using an Asset Library just makes the approach less complex)

Here is the code for the JS file:
// SharePoint Online / 2013 enables MDS by default, so we'll setup our
// custom rendering to play nicely
RegisterModuleInit('/<yourSiteName>/SiteAssets/jsLinkTest.js', registerDueDateCalc);
// this will call the rendering function though on first load or when MDS doesn't apply
registerDueDateCalc();

function registerDueDateCalc() {
    // the name for this object doesn't matter
    var timeSinceFieldViewCtx = {};
    // just use the Templates and Templates.Fields convention below
    timeSinceFieldViewCtx.Templates = {};
    timeSinceFieldViewCtx.Templates.Fields = {
        // Each key value in this object should be the field name
        // so spelling and case matter and should match your list
        "Next_x0020_Due": {
            /* Each key here should be the view/form you want to use
               this custom rendering, choices include: 'View', 'DisplayForm',
               'EditForm', 'NewForm'. The value should point to the function
               that will actually perform the rendering, which we will define
               below -- outside of this function. */
            "View": timeSinceFieldViewTemplate
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(timeSinceFieldViewCtx);
}

function timeSinceFieldViewTemplate(ctx) {
    // you access the current list item properties with ctx.CurrentItem
    var dateDiff = new Date(ctx.CurrentItem.Next_x0020_Due_x0020_Date) - new Date();
    var daysDiff = Math.floor(dateDiff / 1000 / 60 / 60 / 24);
    return daysDiff + " Days Until Due";
}

*

*Save the file, and copy a link to it (make sure to replace the <yoursite> placeholder in the file path with your actual site name).

*Go to the list view that you want to apply this rendering to; edit the page (you may need to look in the dropdown under the gear); edit the list view web part. Under 'Miscellaneous' you'll see the "JS Link" property.

Something that I got caught up on, is that you can't just use a normal URL here as the link property, you have to use a URL token like the ones listed here. Like I said earlier, I put my file in the Assets Library, and I called it jsLinkTest.js so my JS Link value was:
~site/SiteAssets/jsLinkTest.js

That should get you headed in the right direction, you can adjust the timeSinceFieldViewTemplate function if you'd like as well...
Notice the field names use the _x0020_ encoding for spaces, since this is how SharePoint handles spaces internally on field names.
If you're still set on updating every list item, you'll find it's not terribly difficult to perform the actual updates, you just introduce a bunch of other issues as I mentioned in comments to your question.
A possible downside of this approach is that you can't directly sort or filter on this custom rendered column, you would need to do that on the actual due date column, but you can use today in view filters or sort on the due date field directly.
Hope this helps,


text:
Q: How to use underscore headers with waitress? I've been working in a Flask project using waitress for production environement (Targeting Linux ARM and Windows), and I need to recieve a request from a service which has a headers like "dev_id" and "request_code" (doc).
Waitress got a pull request in 2015 (link) basically skipping headers containing _, which explains why the headers are not present in the request object.

*

*I've considered switching to Gunicorn, but Windows support is a must-have.

*Using flask as a self-WSGI works, but do not seems to be the perfect approach for a production environement.

*Using raw socket for HTTP instead of Flask sounds acceptable, but demands some work for refactoring.

*Changing the header name is not an option as I do not have access.

I want to read the header dev_id sent by my client in a Flask application, but waitress doesn't let me do that. Is there any way to ignore this rule? Any workarounds?


text:
Q: Microsoft Teams - invoke HTTP request on message/reply in team channel In MS Teams whenever someone replies to a message in a particular team channel, I want to invoke a HTTP request or publish a message to something like Azure Service Bus.
Is there a way to do this?
FWIW I'm trying to do 2-way SMS between a users mobile device and an agent using MS Teams. I'm using Azure Logic App(s) as the glue between the SMS provider and MS Teams, but the 1 part of the communication loop that I don't know how to handle is when the agent replies to messages in MS Teams. I know I can get messages via MS Graph API, but I don't really like this polling approach - I'd prefer more of an event based approach.

A: Bartsch, currently we don't have any such event to trigger whenever someone replies to a message in a particular team channel. But have an option when a new channel message is added. As this feature is not available at present, could you please raise an User Voice if this needs to be consider as a future request.


text:
Q: How to open the phone camera using the "Choose File" button when called from responsive program (HTML5) I have a Responsive Program written in HTML5 and an app written in Android Studios. I'm told I have to have the Android program handle the opening of the camera when a user presses the  "Choose File" option on the program page to take a picture. We had our web-base program converted in the Responsive Program format so that it can be used from the phones and a small Android app so people can access it. If I go directly to my browser on my phone and select the "Choose File" option it works find, but I'm not sure how to write the code to get it to open up from the app I created when the same button is pressed. I'm new at Android Programming and could use some help to get this up and running. Here are copies of what my program looks like so far. Thanks in advance for any help anyone can give me.
MainActivity.java
package com.wastefreemail.wfmconnect;

    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;

public class MainActivity extends Activity {

public WebView web1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    web1 = (WebView) findViewById(R.id.web1);
    WebSettings webSettings = web1.getSettings();
    webSettings.setJavaScriptEnabled(true);
    web1.loadUrl("https://wastefreemail.com");
    web1.setWebViewClient(new WebViewClient());
    webSettings.setAllowFileAccessFromFileURLs(true);
    webSettings.setAllowUniversalAccessFromFileURLs(true);

}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wastefreemail.wfmconnect">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

   <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

        </activity>
       <activity android:name=".SplashScreenActivity">
           <intent-filter>
           <action android:name="android.intent.action.MAIN" />

           <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>

    </activity>
</application>

</manifest>

SplashScreenActivity.java
package com.wastefreemail.wfmconnect;

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class SplashScreenActivity extends AppCompatActivity {

private int SLEEP_TIMER = 3;

  @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,         WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_splash_screen);
    getSupportActionBar().hide();

     LogoLauncher logoLauncher = new LogoLauncher();
    logoLauncher.start();

}

private class LogoLauncher extends Thread{
  public void run(){
      try{
          sleep(1000 * SLEEP_TIMER);
      }catch(InterruptedException e){
          e.printStackTrace();

      }

      Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
      startActivity(intent);
      SplashScreenActivity.this.finish();
  }
}
}

A: You can use Android-AdvancedWebView to load a webpage in android app,it will handle file choose action automatically.
reedit:
In AdvancedWebView's init method,there is some code:
super.setWebChromeClient(new WebChromeClient() {
   ...
}

In this WebChromeClient ,there is a method  onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams),change this method's logic by following code snippet:
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP
                        &&fileChooserParams != null && fileChooserParams.getAcceptTypes()[0].startsWith("image")) {
        webview.selfDefineImageChoose(null,filePathCallback);//add selfDefineImageChoose method for AdvancedWebView
        //trigger photo shoot with your code
        });
        return true;
    } else {
      return true;
    }
//  return super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
}

//add following method for your self defined AdvancedWebView.
public void selfDefineImageChoose(final ValueCallback<Uri> fileUploadCallbackFirst, final ValueCallback<Uri[]> fileUploadCallbackSecond){
        if (mFileUploadCallbackFirst != null) {
            mFileUploadCallbackFirst.onReceiveValue(null);
        }
        mFileUploadCallbackFirst = fileUploadCallbackFirst;

        if (mFileUploadCallbackSecond != null) {
            mFileUploadCallbackSecond.onReceiveValue(null);
        }
        mFileUploadCallbackSecond = fileUploadCallbackSecond;

}

A: Here's a complete solution, ripped from this GitHub Project, I suggest you to take a look at the mentioned repo to understand better how following script works.
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity{
    WebView web1;
    private static final String TAG = MainActivity.class.getSimpleName();
    private String mCM;
    private ValueCallback mUM;
    private ValueCallback<Uri[]> mUMA;
    private final static int FCR=1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        super.onActivityResult(requestCode, resultCode, intent);
        if(Build.VERSION.SDK_INT >= 21){
            Uri[] results = null;
            //Check if response is positive
            if(resultCode== Activity.RESULT_OK){
                if(requestCode == FCR){
                    if(null == mUMA){
                        return;
                    }
                    if(intent == null || intent.getData() == null){
                        //Capture Photo if no image available
                        if(mCM != null){
                            results = new Uri[]{Uri.parse(mCM)};
                        }
                    }else{
                        String dataString = intent.getDataString();
                        if(dataString != null){
                            results = new Uri[]{Uri.parse(dataString)};
                        }
                    }
                }
            }
            mUMA.onReceiveValue(results);
            mUMA = null;
        }else{
            if(requestCode == FCR){
                if(null == mUM) return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                mUM.onReceiveValue(result);
                mUM = null;
            }
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(Build.VERSION.SDK_INT >=23
           && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
           || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
        }

        web1 = (WebView) findViewById(R.id.web1);
        assert web1 != null;
        WebSettings webSettings = web1.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);

        if(Build.VERSION.SDK_INT >= 21){
            webSettings.setMixedContentMode(0);
            web1.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else if(Build.VERSION.SDK_INT >= 19){
            web1.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else {
            web1.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        web1.setWebViewClient(new Callback());
        web1.loadUrl("https://wastefreemail.com");
        web1.setWebChromeClient(new WebChromeClient() {
            //Handling input[type="file"] requests for android API 16+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUM = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
            }

            //Handling input[type="file"] requests for android API 21+
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

                //Checking for storage permission to write images for upload
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, perms, FCR);

                    //Checking for WRITE_EXTERNAL_STORAGE permission
                } else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, FCR);

                    //Checking for CAMERA permissions
                } else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, FCR);
                }
                if (mUMA != null) {
                    mUMA.onReceiveValue(null);
                }
                mUMA = filePathCallback;
                Intent takePictureIntent = null;
                takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCM);
                    } catch (IOException ex) {
                        Log.e(TAG, "Image file creation failed", ex);
                    }
                    if (photoFile != null) {
                        mCM = "file:" + photoFile.getAbsolutePath();
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    } else {
                        takePictureIntent = null;
                    }
                }
                Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("image/*");
                Intent[] intentArray;
                if (takePictureIntent != null) {
                    intentArray = new Intent[]{takePictureIntent};
                } else {
                    intentArray = new Intent[0];
                }

                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "File Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                startActivityForResult(chooserIntent, FCR);
                return true;
            }
        });
    }

    // Create an image file
    private File createImageFile() throws IOException{
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "img_"+timeStamp+"_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName,".jpg",storageDir);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
    }

    public class Callback extends WebViewClient{
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
            Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
        }
    }

    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event){
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            switch(keyCode){
                case KeyEvent.KEYCODE_BACK:
                    if(web1.canGoBack()){
                        web1.goBack();
                    }else{
                        finish();
                    }
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}

Keep your Manifest as it is and let me know if this works for you.


text:
Q: Python Paramiko Ctrl Z is not working for threading I am implementing few application which will run in remote Machines over ssh protocol.
I have opted paramiko to perform ssh connections.
I have below VM's

*

*Control VM----> This machine has trigger.py and remote.py scripts

*remote VM1----> This has time1.py script

*remote VM2----> This has time1.py script

I am using Threading script and when I am hitting Ctrl z and Program is not terminating . Can any fix a problem. i am thinking it may be bug..
trigger.py is used execute script:
def time_trigger(ip):
    """
    Trigger Onboard Deploy
    """
    cmd = ""
    remote.remote_cmd(ip, cmd)

    t1 = threading.Thread(target=time_trigger, args=(ip1,))
    t2 = threading.Thread(target=time_trigger, args=(ip2,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

remote.py script is used to establish remote ssh connection:
import paramiko
import os
from paramiko import SSHClient
from scp import SCPClient

class Remote:
    def __init__(self, username, password, port):
        self.port = port
        self.user = username
        self.password = password

    def createSSHClient(self, server):
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(server, self.port, self.user, self.password)
        return client

    def remote_cmd(self, hostname, command):
        try:
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(hostname, port=self.port, username=self.user, password=self.password)
            stdin, stdout, stderr = client.exec_command(command)
            print stdout.read()

        finally:
            client.close()

time1.py (wait 5 Mins):
 import time
 time.sleep(300)

I am using Python 2.7


text:
Q: CSS triangle filling for a progress bar I actually googled and searched some info but couldn't find it.
My aim is to achieve something similar to progress bar styling such as filling inside of triangle. Is there any ways?
JSFiddle
.angle {
    width: 0;
    height: 0;
    border-left: 75px solid transparent;
    border-right: 75px solid transparent;
    border-bottom: 75px solid black;
}

A: In order to make the triangle, I would use two pseudo elements to 'cut it out' of the square div. Then, with a nested div, use absolute positioning to allow you to 'fill' it to a certain value (by setting the .amount div's height in %).

.amount {
  position: absolute;
  height: 0%;
  width: 100%;
  bottom: 0;
  left: 0;
  transition: all 1s;
  background: tomato;
}
.tri {
  position: relative;
  height: 200px;
  width: 200px;
  background: lightgray;
}
.tri:before,
.tri:after {
  content: "";
  position: absolute;
  border-top: 200px solid white;
  top: 0;
  z-index: 8;
}
.tri:before {
  border-left: 100px solid transparent;
  left: 50%;
}
.tri:after {
  border-right: 100px solid transparent;
  left: 0;
}
.tri:hover .amount {
  height: 100%;
}

A: May something like this?
.angle {
    position: relative;
    width: 0;
    height: 0;
    border-left: 100px solid transparent;
    border-right: 100px solid transparent;
    border-bottom: 100px solid blue;
}

.angle:after {
    position: absolute;
    content: "";
    top: 0;
    left: 50%;
    margin-left: -50px;
    width: 0;
    height: 0;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 50px solid black;
}

fiddle: http://jsfiddle.net/bkaxzLnu/3/

A: Here is another CSS ONLY, NO-BORDERS, NO AFTER/BEFORE HACKS option:
You could use clip-path. It allows you to show only part of an element and hide the rest.
So you could do something like this:

  .amount {
    position: absolute;
    height: 100%;
    width: 0%;
    bottom: 0;
    left: 0;
    transition: all 1s;
    background: tomato;
  }

  .tri {
    position: relative;
    width: 500px;
    height: 50px;
    background: #ddd;

    /* triangle */
    clip-path: polygon( 100% 0%,100% 100%, 0% 100%);
  }
  .tri:hover .amount {
    width: 100%;
    background: chartreuse ;
  }


text:
Q: How to create provide modules that support multiple AWS regions? We are trying to create Terraform modules for below activities in AWS, so that we can use them where ever that is required.

*

*VPC creation

*Subnets creation

*Instance creation etc.

But while creating these modules we have to define the provider in all above listed modules. So we decided to create one more module for provider so that we can call that provider module in other modules (VPC, Subnet, etc.).
Issue in above approach is that it is not taking provider value, and asking for the user input for region.
Terraform configuration is as follow:
$HOME/modules/providers/main.tf
provider "aws" {
  region = "${var.region}"
}

$HOME/modules/providers/variables.tf
variable "region" {}

$HOME/modules/vpc/main.tf
module "provider" {
  source = "../../modules/providers"
  region = "${var.region}"
}

resource "aws_vpc" "vpc" {
  cidr_block = "${var.vpc_cidr}"
  tags = {
    "name" = "${var.environment}_McD_VPC"
  }
}

$HOME/modules/vpc/variables.tf
variable "vpc_cidr" {}
variable "environment" {}
variable "region" {}

$HOME/main.tf
module "dev_vpc" {
  source = "modules/vpc"
  vpc_cidr = "${var.vpc_cidr}"
  environment = "${var.environment}"
  region = "${var.region}"
}

$HOME/variables.tf
variable "vpc_cidr" {
  default = "192.168.0.0/16"
}

variable "environment" {
  default = "dev"
}

variable "region" {
  default = "ap-south-1"
}

Then when running terraform plan command at $HOME/ location it is not taking provider value and instead asking for the user input for region.
I need help from the Terraform experts, what approach we should follow to address below concerns:

*

*Wrap provider in a Terraform module

*Handle multiple region use case using provider module or any other way.

A: I knew a long time back that it wasn't possible to do this because Terraform built a graph that required a provider for any resource before it included any dependencies and it didn't used to be possible to force a dependency on a module.
However since Terraform 0.8 it is now possible to set a dependency on modules with the following syntax:
module "network" {
  # ...
}

resource "aws_instance" "foo" {
  # ...

  depends_on = ["module.network"]
}

However, if I try that with your setup by changing modules/vpc/main.tf to look something like this:
module "aws_provider" {
  source = "../../modules/providers"
  region = "${var.region}"
}

resource "aws_vpc" "vpc" {
  cidr_block = "${var.vpc_cidr}"
  tags = {
    "name" = "${var.environment}_McD_VPC"
  }
  depends_on = ["module.aws_provider"]
}

And run terraform graph | dot -Tpng > graph.png against it it looks like the graph doesn't change at all from when the explicit dependency isn't there.
This seems like it might be a potential bug in the graph building stage in Terraform that should probably be raised as an issue but I don't know the core code base well enough to spot where the change needs to be.
For our usage we use symlinks heavily in our Terraform code base, some of which is historic from before Terraform supported other ways of doing things but could work for you here.
We simply define the provider in a single .tf file (such as environment.tf) along with any other generic config needed for every place you would ever run Terraform (ie not at a module level) and then symlink this into each location. That allows us to define the provider in a single place with overridable variables if necessary.

A: Step 1
Add region alias in the main.tf file where you gonna execute the terraform plan.
provider "aws" {
  region = "eu-west-1"
  alias = "main"
}

provider "aws" {
  region = "us-east-1"
  alias = "useast1"
}

Step 2
Add providers block inside your module definition block
module "lambda_edge_rule" {
  providers = {
    aws = aws.useast1
  }
  source            = "../../../terraform_modules/lambda"
  tags              = var.tags
}

Step 3
Define "aws" as providers inside your module. (  source  = ../../../terraform_modules/lambda")
terraform {
    required_providers {
    aws = {
          source  = "hashicorp/aws"
          version = ">= 2.7.0"
        }
      }
    }

resource "aws_lambda_function" "lambda" {
  function_name     = "blablabla"
    .
    .
    .
    .
    .
    .
    .
}

Note: Terraform version v1.0.5 as of now.


text:
Q: Не меняется текст! Код ошибки:

10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime: FATAL EXCEPTION: main
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime: java.lang.NullPointerException
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime:     at com.develope.vladimir.devilsbones.game$1.run(game.java:39)
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:725)
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:92)
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5041)
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
  10-22 15:35:48.055 21698-21698/com.develope.vladimir.devilsbones E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)

Сам код:
public class game extends Activity {
ImageButton imageButton5;
TextView textView3;
TextView textView4;
TextView textview5;
Timer timer;
Handler handler;
Runnable tadada;
@Override
protected void onCreate(Bundle savedInstanceState) {
    textView3 = (TextView) findViewById(R.id.textView3);
    textView4 = (TextView) findViewById(R.id.textView4);
    textview5 = (TextView) findViewById(R.id.textView5);
    imageButton5 = (ImageButton) findViewById(R.id.imageButton5);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);
    handler = new Handler() ;
    tadada = new Runnable() {
        public void run() {
            Random rand = new Random();
            final int pS = rand.nextInt(6) + 1;
            final int cS = rand.nextInt(6) + 1;
            textView3.setText("Ваш результат:" + pS);
            textView4.setText("Результат компьютера:" + cS);
            if (pS < cS) {
                textview5.setText("Победил компьютер!Повезёт в следующий раз!");
            } else {
                textview5.setText("Вы выиграли!Поздравляю!");
            }
            if (pS == cS) {
                textview5.setText("Победила дружба;)");

            }
        }
    };
}

public void onClick(View v) {
    timer = new Timer();
    imageButton5 = (ImageButton) findViewById(R.id.imageButton5);
    imageButton5.setEnabled(false);
    handler.postDelayed(tadada, 2000);
}
}

Смысл в том,что при нажатии на кнопку текст должен поменяться через определенное время(2 секунды),но оно не меняется и выбивает ошибку!

A: textView3 = (TextView) findViewById(R.id.textView3);
textView4 = (TextView) findViewById(R.id.textView4);
textview5 = (TextView) findViewById(R.id.textView5);
imageButton5 = (ImageButton) findViewById(R.id.imageButton5);

Все  эти 4 переменных равны null, потому что они идет перед этими строками, а не после:
super.onCreate(savedInstanceState);
setContentView(R.layout.game);


text:
Q: How to remove background of an image and copy into another? I'm researching about captchas. In this idea, the task is: create a image from a JPEG and remove the white background, than create another image from another JPEG, than create the final image by adding the second as a background, and copying the first one over this background preserving the transparent area created, of course. Here is the code:
header("Content-Type: image/jpeg");

$nFundo = rand(0,4);
$Dirs = array(rand(0,7), rand(0,7), rand(0,7), rand(0,7)); // Will be four times all

$_SESSION["form_captcha"] = $Dirs;

$image = ImageCreatetruecolor(320, 80);
ImageAlphaBlending($image, FALSE);
ImageSaveAlpha($image, TRUE);

$image_seta = ImageCreateFromJPEG("_captcha-seta.jpg"); // Image do copy over
$image_fundo = ImageCreateFromJPEG("_captcha-fundo-".$nFundo.".jpg"); // Image to make the background

for($i=0; $i<4; $i++){
    ImageCopy($image, $image_fundo, $i*80, 0, 0, 0, 80, 80);
}
// So far so good, a background with a pattern repeated four times
$color_white = ImageColorAllocate($image_seta, 255, 255, 255);
ImageColorTransparent($image_seta, $color_white);
ImageSaveAlpha($image_seta, TRUE);

for($i=0; $i<4; $i++){
    $image_seta_rot = imageRotate($image_seta, $Dirs[$i]*45, $color_white);
    ImageCopyResampled($image, $image_seta_rot, $i*80, 0, 0, 0, 80, 80, 80, 80); // Try
}

echo(imagejpeg($image));

imagedestroy($image);

I tried to replace $image_seta_rot by $image_seta ("Try" line) to see if the rotation is the problem, but even without rotation, the white wasn't removed and the image just "erase" the background created before. So the copy is failing or the white were never removed... I may create a PNG with transparent background, but will be interesting to learn how to make it dynamically, don't you think? Any ideas?


text:
Q: how to implement add expression for date in drupal 7 When i try to use timestamp in time format in expression .I got error
For example
$query->addExpression('date("H:i:s","dept_timestamp")','time_val');

A: I think the problem is that you've put a PHP function into addExpression. It's feeding your expression straight into the database, so you'll want to use a date-formatting function that your db will understand. Assuming you're using MySQL as a backend, you'd want something like this:
$query->addExpression('from_unixtime("dept_timestamp", "%h:%i:%s")', 'time_val');

Here's a full example that, for no good reason, joins the node table and the field_data_body table:
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title'));
$query->join('field_data_body', 'b', 'n.nid = b.entity_id');
$query->fields('b', array('body_value'));
$query->addExpression("from_unixtime(created, '%h:%i:%s')", 'my_timestamp');
$result = $query->execute();