问:
how to set field in constructor in java
there are 3 fields in constructor( name , points ,weapon ) and they are stored in arrayList and I want to modify name from another method..how can I do this?
and what is the meaning of passing "this" keyword as parameter..
I am new in java programming

i used below code to update name and its changing name but points becomes 0 and and weapon "null"

```<code>public void modify(String name) {
    if(savedValues!= null && savedValues.size()>0) {
        for (int i = 0; i < savedValues.size(); i++) {
            if (savedValues.get(i).getName().equals(name)) {
                System.out.println("enter new name");
                Scanner scanner=new Scanner(System.in);
                //this.name = scanner.next();
                savedValues.set(i,this);
            }
        }
    }
}
</code>```

答:
Try something like this

```<code>String newName = scanner.next();
savedValues.get(i).setName(newName);
</code>```

savedValues.get(i) will give you an object and you are trying to update the name property of that particular object. this is a reference to the object instance in which your code is running. It does not make sense to use this here.

Title: how to set field in constructor in java

Body:
there are 3 fields in constructor( name , points ,weapon ) and they are stored in arrayList and I want to modify name from another method..how can I do this?
and what is the meaning of passing "this" keyword as parameter..
I am new in java programming

i used below code to update name and its changing name but points becomes 0 and and weapon "null"

public void modify(String name) {
    if(savedValues!= null && savedValues.size()>0) {
        for (int i = 0; i < savedValues.size(); i++) {
            if (savedValues.get(i).getName().equals(name)) {
                System.out.println("enter new name");
                Scanner scanner=new Scanner(System.in);
                //this.name = scanner.next();
                savedValues.set(i,this);
            }
        }
    }
}

Body:
Try something like this

String newName = scanner.next();
savedValues.get(i).setName(newName);

savedValues.get(i) will give you an object and you are trying to update the name property of that particular object. this is a reference to the object instance in which your code is running. It does not make sense to use this here.


来源: stackexchange

问:
React multi-select selected value undefined
I'm using this component to make a react multi-select. When I use a normal select if works perfectly. I have the following code.

```<code>handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Selected: ${selectedOption.label}`);
  }
  render() {
    return (
      <Select
        name="form-field-name"
        value={this.state.selectedOption.value}
        onChange={this.handleChange}
        options={[
          { value: 'one', label: 'One' },
          { value: 'two', label: 'Two' },
        ]}
      />
    );
  }
</code>```

But when I add, multi={true} it gives undefined in the console. What am I doing wrong? Is there anything else to be added to the attributes?

Plus the value inside the select box doesn't change. Here is an example- https://jsfiddle.net/69z2wepo/94309/

答:
If you would read the docs that you linked to, you would find the following statement here

The onChange event provides an array of selected options or a comma-separated string of values (eg "1,2,3") if simpleValue is true

So, in your case you have to take an array as input, your handleChange would therefor be something like

```<code>handleChange = (selectedOptions) => {
  this.setState({ selectedOptions });
  selectedOptions.forEach( selectedOption =>
    console.log( `Selected: ${selectedOption.label}` )
  );
}
</code>```

Your render would then also change to

```<code>render() {
  return (
    <Select
      name="form-field-name"
      value={this.state.selectedOptions}
      onChange={this.handleChange}
      options={[
        { value: 'one', label: 'One' },
        { value: 'two', label: 'Two' },
      ]}
    />
  );
}
</code>```

as you want to pass in the values that got selected or undefined. If the value would be anything else but the property value on your options, you would need to supply the valueKey property to your component, but it is set by default on "value" so in your case you don't seem to need it.

The props you can find here

A working version can be found here (note that in your fiddle and in your example, the multi prop was missing)

class Hello extends React.Component {
  handleChange(selectedOptions) {
    this.setState({ value: selectedOptions });
  }
  render() {
    return (
      <Select
        name="form-field-name"
        value={this.state && this.state.value}
        multi={true}
        onChange={(...args) => this.handleChange(...args)}
        options={[
          { value: 'one', label: 'One' },
          { value: 'two', label: 'Two' },
        ]}
      />
    );
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/classnames/2.2.5/index.js"></script>
<script src="https://unpkg.com/react-input-autosize@2.0.0/dist/react-input-autosize.js"></script>
<script src="https://unpkg.com/react-select/dist/react-select.js"></script>
<link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css" type="text/css" />

<div id="container"></div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using this component to make a react multi-select. When I use a normal select if works perfectly. I have the following code.

handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Selected: ${selectedOption.label}`);
  }
  render() {
    return (
      <Select
        name="form-field-name"
        value={this.state.selectedOption.value}
        onChange={this.handleChange}
        options={[
          { value: 'one', label: 'One' },
          { value: 'two', label: 'Two' },
        ]}
      />
    );
  }

But when I add, multi={true} it gives undefined in the console. What am I doing wrong? Is there anything else to be added to the attributes?

Plus the value inside the select box doesn't change. Here is an example- https://jsfiddle.net/69z2wepo/94309/

Body:
If you would read the docs that you linked to, you would find the following statement here

The onChange event provides an array of selected options or a comma-separated string of values (eg "1,2,3") if simpleValue is true

So, in your case you have to take an array as input, your handleChange would therefor be something like

handleChange = (selectedOptions) => {
  this.setState({ selectedOptions });
  selectedOptions.forEach( selectedOption =>
    console.log( `Selected: ${selectedOption.label}` )
  );
}

Your render would then also change to

render() {
  return (
    <Select
      name="form-field-name"
      value={this.state.selectedOptions}
      onChange={this.handleChange}
      options={[
        { value: 'one', label: 'One' },
        { value: 'two', label: 'Two' },
      ]}
    />
  );
}

as you want to pass in the values that got selected or undefined. If the value would be anything else but the property value on your options, you would need to supply the valueKey property to your component, but it is set by default on "value" so in your case you don't seem to need it.

The props you can find here

A working version can be found here (note that in your fiddle and in your example, the multi prop was missing)

class Hello extends React.Component {
  handleChange(selectedOptions) {
    this.setState({ value: selectedOptions });
  }
  render() {
    return (
      <Select
        name="form-field-name"
        value={this.state && this.state.value}
        multi={true}
        onChange={(...args) => this.handleChange(...args)}
        options={[
          { value: 'one', label: 'One' },
          { value: 'two', label: 'Two' },
        ]}
      />
    );
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/classnames/2.2.5/index.js"></script>
<script src="https://unpkg.com/react-input-autosize@2.0.0/dist/react-input-autosize.js"></script>
<script src="https://unpkg.com/react-select/dist/react-select.js"></script>
<link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css" type="text/css" />

<div id="container"></div>


问:
jQuery toggle function not called after creation of dynamic list
created a dynamic li list field which is having a toggle functionality. but toggle is working only for first field not the rest dynamically created lists

```<code><html>
  <head>
    <title>add / remove textbox</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <style type="text/css">
      div{
        padding:8px;
      }
    </style>

    <style>
      #toggle-view {
        list-style: none;
        font-family: arial;
        font-size: 11px;
        margin: 0;
        padding: 0;
        width: 300px;
      }

      #toggle-view li {
        margin: 10px;
        border:1px solid #ccc;
        padding:4px 3px;
        position: relative;
        cursor: pointer;
      }

      #toggle-view h3 {
        margin: 0;
        font-size: 14px;
      }

      #toggle-view span{
        position: absolute;
        right: 5px;
        top: 0;
        color: #ccc;
        font-size: 13px;
      }
      #toggle-view dd {
        margin: 5px 0;
        display: none;
      }
    </style>
  </head>
  <body>
    <script type="text/javascript">
      window.onload = $(function() {
        var counter = 2;
        $("#addButton").click(function () {
          var newTextBoxDiv = $(document.createElement('li'))
            .attr("id", 'TextBoxDiv' + counter);

          newTextBoxDiv.after().html('<h3>Page No#'+counter+'</h3><dd>' +
          '<input type="text" name="textbox' + counter +
          '" id="textbox' + counter + '" value=""  /></dd>');

          newTextBoxDiv.appendTo("#toggle-view");
          counter++;
        });

        $("#removeButton").click(function () {
          if(counter==1){
            alert("No more textbox to remove");
            return false;
          }

          counter--;
          $("#TextBoxDiv" + counter).remove();
        });

  var parent = $('#toggle-view'), // storing main ul for use below
  delay = 200; // storing delay for easier configuration

// bind the click to all headers 'li h3', parent
$('#toggle-view li').on( 'click', function( event ) {

    //console.log( 'clicked', $( this ).text() );

    // get the li that this header belongs to
    var li = $(this).closest('li');

    // check to see if this li is not already being displayed
    if (!$('dd', li).is(':visible'))
    {
        // loop on all the li elements
        $('li', parent).each(function() {
           //alert();
            // slide up the element and set it's marker to '+'
            $('dd', $(this)).slideUp(delay);
            //$('dd', $(this)).text('+');
        });

        // display the current li with a '-' marker
        $('dd', li).slideDown(delay);
        //$('dd', li).text('-');
    }
});
  //}
    //setTimeout(togg, 100);

  });

</script>
</head><body>

<div id='TextBoxesGroup'>
  <ul id="toggle-view">

    <li id="TextBoxDiv1" >
        <h3>Page No#1</h3>
        <dd><input type='textbox' id='textbox1' ></dd>
    </li>

    </ul>

</div>
<input type='button' value='Add Page' id='addButton'>
<input type='button' value='Remove Page' id='removeButton'>

</body>
</html>
</code>```

答:
You can catch event in parent element.

An event-delegation approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

```<code>$( "#dataTable tbody" ).on( "click", "tr", function() {
  console.log( $( this ).text() );
});
</code>```

And you don't need to window.onload.

$(function() {
  var counter = 2;
  $("#addButton").click(function() {

    var newTextBoxDiv = $(document.createElement('li'))
      .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('
Page No#' + counter + '

' +
      '<input type="text" name="textbox' + counter +
      '" id="textbox' + counter + '" value=""  />
');

    newTextBoxDiv.appendTo("#toggle-view");

    counter++;
  });

  $("#removeButton").click(function() {
    if (counter == 1) {
      alert("No more textbox to remove");
      return false;
    }

    counter--;

    $("#TextBoxDiv" + counter).remove();

  });

  var parent = $('#toggle-view'), // storing main ul for use below
    delay = 200; // storing delay for easier configuration

  // bind the click to all headers 'li h3', parent
  $('#toggle-view').on('click', 'li', function(event) {

    var li = $(this);

    // check to see if this li is not already being displayed
    if (!$('dd', li).is(':visible')) {
      // loop on all the li elements
      $('li', parent).each(function() {
        // slide up the element and set it's marker to '+'
        $('dd', $(this)).slideUp(delay);

      });

      $('dd', li).slideDown(delay);

    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  padding: 8px;
}

#toggle-view {
  list-style: none;
  font-family: arial;
  font-size: 11px;
  margin: 0;
  padding: 0;
  width: 300px;
}

#toggle-view li {
  margin: 10px;
  border: 1px solid #ccc;
  padding: 4px 3px;
  position: relative;
  cursor: pointer;
}

#toggle-view h3 {
  margin: 0;
  font-size: 14px;
}

#toggle-view span {
  position: absolute;
  right: 5px;
  top: 0;
  color: #ccc;
  font-size: 13px;
}

#toggle-view dd {
  margin: 5px 0;
  display: none;
}</code>```

Page No#1

<input type='textbox' id='textbox1'>

  <input type='button' value='Add Page' id='addButton'>
  <input type='button' value='Remove Page' id='removeButton'>

```

Body:
created a dynamic li list field which is having a toggle functionality. but toggle is working only for first field not the rest dynamically created lists

    <title>add / remove textbox</title>

Page No#1

<input type='textbox' id='textbox1' >

<input type='button' value='Add Page' id='addButton'>
<input type='button' value='Remove Page' id='removeButton'>

Body:
You can catch event in parent element.

An event-delegation approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

$( "#dataTable tbody" ).on( "click", "tr", function() {
  console.log( $( this ).text() );
});

And you don't need to window.onload.

$(function() {
  var counter = 2;
  $("#addButton").click(function() {

    var newTextBoxDiv = $(document.createElement('li'))
      .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<h3>Page No#' + counter + '</h3><dd>' +
      '<input type="text" name="textbox' + counter +
      '" id="textbox' + counter + '" value=""  /></dd>');

    newTextBoxDiv.appendTo("#toggle-view");

    counter++;
  });

  $("#removeButton").click(function() {
    if (counter == 1) {
      alert("No more textbox to remove");
      return false;
    }

    counter--;

    $("#TextBoxDiv" + counter).remove();

  });

  var parent = $('#toggle-view'), // storing main ul for use below
    delay = 200; // storing delay for easier configuration

  // bind the click to all headers 'li h3', parent
  $('#toggle-view').on('click', 'li', function(event) {

    var li = $(this);

    // check to see if this li is not already being displayed
    if (!$('dd', li).is(':visible')) {
      // loop on all the li elements
      $('li', parent).each(function() {
        // slide up the element and set it's marker to '+'
        $('dd', $(this)).slideUp(delay);

      });

      $('dd', li).slideDown(delay);

    }
  });

});

div {
  padding: 8px;
}

#toggle-view {
  list-style: none;
  font-family: arial;
  font-size: 11px;
  margin: 0;
  padding: 0;
  width: 300px;
}

#toggle-view li {
  margin: 10px;
  border: 1px solid #ccc;
  padding: 4px 3px;
  position: relative;
  cursor: pointer;
}

#toggle-view h3 {
  margin: 0;
  font-size: 14px;
}

#toggle-view span {
  position: absolute;
  right: 5px;
  top: 0;
  color: #ccc;
  font-size: 13px;
}

#toggle-view dd {
  margin: 5px 0;
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

  <div id='TextBoxesGroup'>
    <ul id="toggle-view">

      <li id="TextBoxDiv1">
        <h3>Page No#1</h3>
        <dd><input type='textbox' id='textbox1'></dd>
      </li>

    </ul>

  </div>
  <input type='button' value='Add Page' id='addButton'>
  <input type='button' value='Remove Page' id='removeButton'>

</body>


问:
Instant Run performed a full build and install since the installation on the device does not match the local build on disk
Android Studio gives error when running application with instant run enabled. I have updated my android studio to 2.3 today and since then its showing me above information.</p>

答:
On android studio 3.0.1
I ran a full build right after I enabled instant run.
Once that was done . The error was gone and instant run worked. </p>


问:
MySQL query to get sum where month = January
I am trying to get renew_total sum from my database where expiry date = 1st month of year i.e: January

Here is my table user_pages structure

```<code>   id  |        expiry         |renew_total|renewal_flag|  self_managed |
    1  | 2017-01-08 15:03:57   |  1000     |      0     |        0      |
    2  | 2017-02-31 07:17:01   |  1500     |      0     |        0      |
</code>```

I am trying this:

```<code>public function jan_renewal()
   {
        return $this->db->select("
        SELECT sum((renew_total*12)/100)
        as janrenewal FROM user_pages
        WHERE renewal_flag=0
        AND self_managed = 0
        ");
   }
</code>```

I am Not getting correct results as expected

sum = 120

答:
Use MySQL's MONTH() function to select only dates in January:</p>

```<code>SELECT SUM(renew_total) AS janrenewal
FROM user_pages
WHERE MONTH(expiry) = 1
AND renewal_flag = 0
AND self_managed = 0;
</code>```

Body:
I am trying to get renew_total sum from my database where expiry date = 1st month of year i.e: January

Here is my table user_pages structure

   id  |        expiry         |renew_total|renewal_flag|  self_managed |
    1  | 2017-01-08 15:03:57   |  1000     |      0     |        0      |
    2  | 2017-02-31 07:17:01   |  1500     |      0     |        0      |

I am trying this:

public function jan_renewal()
   {
        return $this->db->select("
        SELECT sum((renew_total*12)/100)
        as janrenewal FROM user_pages
        WHERE renewal_flag=0
        AND self_managed = 0
        ");
   }

I am Not getting correct results as expected

sum = 120

Body:
Use MySQL's MONTH() function to select only dates in January:

SELECT SUM(renew_total) AS janrenewal
FROM user_pages
WHERE MONTH(expiry) = 1
AND renewal_flag = 0
AND self_managed = 0;


问:
How to scale point size and color at the same time in ggvis?
Considering a data.frame like this:

```<code>df <- data.frame(t = rep(seq(from=as.POSIXct('00:15:00',format='%H:%M:%S'),
                             to=as.POSIXct('24:00:00',format='%H:%M:%S'),by='15 min'),times=2),
                     y = c(rnorm(96,10,10),rnorm(96,40,5)),
                     group = factor(rep(1:2,each=96)),
                     type = factor(rep(1:3,each=64)))
</code>```

Using ggvis, I want to generate a point-line plot in which the line is grouped by group. The size of points with type==3 should be 100 while the size of points withtype==1 and type==2 are all 50. The colour of the points should be green, blue and red corresponding to type1,type2 and type3. Here is my ggvis code:

```<code>df <- data.frame(df,id=1:nrow(df))

all_values <- function(x) {
  if(is.null(x)) return(NULL)
  row <- df[df$id == x$id, ]
  paste0(names(row), ": ", format(row), collapse = "<br />")
}

ggvis(data=df,x=~t,y=~y,stroke=~group) %>%
  layer_points(fill=~type,size=~type, key:=~id, fillOpacity := 0.5,
               fillOpacity.hover := 0.8,size.hover := 500) %>%
  scale_nominal("size",domain = c(1,2,3), range = c(50,50,100)) %>%
  scale_nominal("fill",domain = c(1,2,3), range = c('green','blue','red')) %>%
  layer_lines() %>%
  add_tooltip(all_values,'click') %>%
  add_legend(scales=c("fill","size"), properties = legend_props(legend = list(y = 150))) %>%
  set_options(duration = 0) %>%
  add_axis(type="x",format="%H:%M")
</code>```

I get the error of Error: length(x) not less than or equal to 2.
Why this happened and how can I fix it?

答:
The culprit for the error is more than 2 values defined for range. The definition for range suggests : For numeric values, the range can take the form of a two-element array with minimum and maximum values.

For ordinal data, the range may by an array of desired output values, which are mapped to elements in the specified domain. In this case, value should be defined in character.

This should resolve your error.

Body:
Considering a data.frame like this:

df <- data.frame(t = rep(seq(from=as.POSIXct('00:15:00',format='%H:%M:%S'),
                             to=as.POSIXct('24:00:00',format='%H:%M:%S'),by='15 min'),times=2),
                     y = c(rnorm(96,10,10),rnorm(96,40,5)),
                     group = factor(rep(1:2,each=96)),
                     type = factor(rep(1:3,each=64)))

Using ggvis, I want to generate a point-line plot in which the line is grouped by group. The size of points with type==3 should be 100 while the size of points withtype==1 and type==2 are all 50. The colour of the points should be green, blue and red corresponding to type1,type2 and type3. Here is my ggvis code:

df <- data.frame(df,id=1:nrow(df))

all_values <- function(x) {
  if(is.null(x)) return(NULL)
  row <- df[df$id == x$id, ]
  paste0(names(row), ": ", format(row), collapse = "
")
}

ggvis(data=df,x=~t,y=~y,stroke=~group) %>%
  layer_points(fill=~type,size=~type, key:=~id, fillOpacity := 0.5,
               fillOpacity.hover := 0.8,size.hover := 500) %>%
  scale_nominal("size",domain = c(1,2,3), range = c(50,50,100)) %>%
  scale_nominal("fill",domain = c(1,2,3), range = c('green','blue','red')) %>%
  layer_lines() %>%
  add_tooltip(all_values,'click') %>%
  add_legend(scales=c("fill","size"), properties = legend_props(legend = list(y = 150))) %>%
  set_options(duration = 0) %>%
  add_axis(type="x",format="%H:%M")

I get the error of Error: length(x) not less than or equal to 2.
Why this happened and how can I fix it?


问:
Problems converting HDF5 files to .CSV Pandas
I am trying to convert many .h5 files to a format that can be opened in tableau. since I am new to the python debugger, I can't detect any runtime errors that may be happening. Also,I'm not sure whether itd be better to split up the resulting CSV, or just save it all to one file. I'm not positive how to do either of these things.

```<code>from pandas import HDFStore
import pdb

import os
indir = 'C:\Users\Aktosar\data'
for root, dirs, filenames in os.walk(indir)
    for f in filenames:
        Pandas.convert(f)
</code>```

I also can't decide whether to use .toCSV or the other saving method. Any method that successfully converts all the data to a csv that can be opened in tableau is the right methodfor this excercise. :)

Any help with the completion of this would be much appreciated!

答:
I think os.walk can be tricky. It's easy to lose track of where you are. On top of it, .h5 with pandas can also be tricky whether you read from pd.HDFStore or use pd.read_hdf. Figuring out dataset names within an h5 file is even more ridiculous. This to say, lots of things can go wrong.

```<code>import pandas as pd
import numpy as np
import h5py
import os

dfs = []
for path, dirs, filenames in os.walk(os.curdir):
    if path != os.curdir:
        print(path, dirs, filenames)
        for file in filenames:
            file_path = os.path.join(path, file)
            h5_store = h5py.File(file_path, mode='r')
            dataset_names = list(h5_store.keys())
            for dataset in dataset_names:
                df = pd.DataFrame(h5_store[dataset].value)
                print(file, df.shape)
                dfs.append(df)
            h5_store.close()

final = pd.concat(dfs, ignore_index=True).reset_index()
print(final.shape)
</code>```

My directory looks something like:

```<code>  dir1
      arr0.h5
     dir4
         arr0.h5
         arr1.h5
         arr2.h5
         arr3.h5
  dir2
      arr0.h5
      arr1.h5
  dir3
      arr0.h5
      arr1.h5
      arr2.h5
     dir5
         arr0.h5
     dir6
         arr0.h5
         arr1.h5
         arr2.h5
         arr3.h5
        dir7
            arr0.h5
            arr1.h5
            arr2.h5
            arr3.h5
</code>```

That df = pd.DataFrame(h5_store[dataset].value) part is key though. That might not work. It depends on the type of data that is. You might try pd.read_hdf(...) if that doesn't work. It also depends on if you have multiple datasets in each .h5 file.

Body:
I am trying to convert many .h5 files to a format that can be opened in tableau. since I am new to the python debugger, I can't detect any runtime errors that may be happening. Also,I'm not sure whether itd be better to split up the resulting CSV, or just save it all to one file. I'm not positive how to do either of these things.

from pandas import HDFStore
import pdb

import os
indir = 'C:\Users\Aktosar\data'
for root, dirs, filenames in os.walk(indir)
    for f in filenames:
        Pandas.convert(f)

I also can't decide whether to use .toCSV or the other saving method. Any method that successfully converts all the data to a csv that can be opened in tableau is the right methodfor this excercise. :)

Any help with the completion of this would be much appreciated!

Body:
I think os.walk can be tricky. It's easy to lose track of where you are. On top of it, .h5 with pandas can also be tricky whether you read from pd.HDFStore or use pd.read_hdf. Figuring out dataset names within an h5 file is even more ridiculous. This to say, lots of things can go wrong.

import pandas as pd
import numpy as np
import h5py
import os

dfs = []
for path, dirs, filenames in os.walk(os.curdir):
    if path != os.curdir:
        print(path, dirs, filenames)
        for file in filenames:
            file_path = os.path.join(path, file)
            h5_store = h5py.File(file_path, mode='r')
            dataset_names = list(h5_store.keys())
            for dataset in dataset_names:
                df = pd.DataFrame(h5_store[dataset].value)
                print(file, df.shape)
                dfs.append(df)
            h5_store.close()

final = pd.concat(dfs, ignore_index=True).reset_index()
print(final.shape)

My directory looks something like:

  dir1
      arr0.h5
     dir4
         arr0.h5
         arr1.h5
         arr2.h5
         arr3.h5
  dir2
      arr0.h5
      arr1.h5
  dir3
      arr0.h5
      arr1.h5
      arr2.h5
     dir5
         arr0.h5
     dir6
         arr0.h5
         arr1.h5
         arr2.h5
         arr3.h5
        dir7
            arr0.h5
            arr1.h5
            arr2.h5
            arr3.h5

That df = pd.DataFrame(h5_store[dataset].value) part is key though. That might not work. It depends on the type of data that is. You might try pd.read_hdf(...) if that doesn't work. It also depends on if you have multiple datasets in each .h5 file.


问:
Shiny slider restrict reaction to releasing left mouse button
I am using a Shiny application in which it may take some time to set a slider to the right value.

So while trying to set the slider to the right value (and not releasing my left mouse button!) the (i.e. my local) server observed several new values and reacts accordingly.

As the response of my server on any new value may take a few seconds I would be pleased if I could either:

postpone signalling the server till the release of the left mouse button, or

at the server side, abort any earlier responses if it receive a new value

答:
Shiny's sliderInput uses Ion.RangeSlider, which has an onFinish callback for when a user releases their mouse. That sounds like just what we need.

Here's a custom input binding for a "lazy" slider input that only signals a value change when a user releases their mouse (onFinish) or when the slider is forcibly updated (onUpdate).

For the example, I just inlined code that changes the behavior of ALL sliderInputs. You'll want to move this to an external script and customize further. Also, onUpdate gets called when the slider is initialized, but before Shiny initializes input values. You have to wait until Shiny does this to call the value change callback in onUpdate. The solution I worked in isn't fantastic, but I was too lazy to find a cleaner way.

```<code>library(shiny)

ui <- fluidPage(
  tags$head(
    tags$script(HTML("
      (function() {
        var sliderInputBinding = Shiny.inputBindings.bindingNames['shiny.sliderInput'].binding;

        var lazySliderInputBinding = $.extend({}, sliderInputBinding, {
          subscribe: function(el, callback) {
            var $el = $(el);
            var slider = $el.data('ionRangeSlider');

            var handleChange = function() {
              if (!inputsInitialized) return;
              callback(!$el.data('immediate') && !$el.data('animating'));
            };

            slider.update({
              onUpdate: handleChange,
              onFinish: handleChange
            });
          },

          unsubscribe: function(el, callback) {
            var slider = $(el).data('ionRangeSlider');
            slider.update({
              onUpdate: null,
              onFinish: null
            });
          }
        });

        Shiny.inputBindings.register(lazySliderInputBinding, 'shiny.lazySliderInput');

        var inputsInitialized = false;
        $(document).one('shiny:connected', function() {
          inputsInitialized = true;
        });
      })();
    "))
  ),
  sliderInput("sliderA", "A", 0, 10, 5),
  uiOutput("sliderB"),
  verbatimTextOutput("sliderValues"),
  actionButton("resetSliders", "Reset Sliders")
)

server <- function(input, output, session) {
  observeEvent(input$resetSliders, {
    updateSliderInput(session, "sliderA", value = 5)
    updateSliderInput(session, "sliderB", value = c(4, 6))
  })

  output$sliderB <- renderUI({
    sliderInput("sliderB", "B", 0, 10, c(4, 6))
  })

  output$sliderValues <- renderPrint({
    cat(paste("Slider A =", input$sliderA), "\n")
    cat(paste("Slider B =", paste(input$sliderB, collapse = " ")))
  })
}

shinyApp(ui, server)
</code>```

Body:
Shiny's sliderInput uses Ion.RangeSlider, which has an onFinish callback for when a user releases their mouse. That sounds like just what we need.

Here's a custom input binding for a "lazy" slider input that only signals a value change when a user releases their mouse (onFinish) or when the slider is forcibly updated (onUpdate).

For the example, I just inlined code that changes the behavior of ALL sliderInputs. You'll want to move this to an external script and customize further. Also, onUpdate gets called when the slider is initialized, but before Shiny initializes input values. You have to wait until Shiny does this to call the value change callback in onUpdate. The solution I worked in isn't fantastic, but I was too lazy to find a cleaner way.

library(shiny)

ui <- fluidPage(
  tags$head(
    tags$script(HTML("
      (function() {
        var sliderInputBinding = Shiny.inputBindings.bindingNames['shiny.sliderInput'].binding;

        var lazySliderInputBinding = $.extend({}, sliderInputBinding, {
          subscribe: function(el, callback) {
            var $el = $(el);
            var slider = $el.data('ionRangeSlider');

            var handleChange = function() {
              if (!inputsInitialized) return;
              callback(!$el.data('immediate') && !$el.data('animating'));
            };

            slider.update({
              onUpdate: handleChange,
              onFinish: handleChange
            });
          },

          unsubscribe: function(el, callback) {
            var slider = $(el).data('ionRangeSlider');
            slider.update({
              onUpdate: null,
              onFinish: null
            });
          }
        });

        Shiny.inputBindings.register(lazySliderInputBinding, 'shiny.lazySliderInput');

        var inputsInitialized = false;
        $(document).one('shiny:connected', function() {
          inputsInitialized = true;
        });
      })();
    "))
  ),
  sliderInput("sliderA", "A", 0, 10, 5),
  uiOutput("sliderB"),
  verbatimTextOutput("sliderValues"),
  actionButton("resetSliders", "Reset Sliders")
)

server <- function(input, output, session) {
  observeEvent(input$resetSliders, {
    updateSliderInput(session, "sliderA", value = 5)
    updateSliderInput(session, "sliderB", value = c(4, 6))
  })

  output$sliderB <- renderUI({
    sliderInput("sliderB", "B", 0, 10, c(4, 6))
  })

  output$sliderValues <- renderPrint({
    cat(paste("Slider A =", input$sliderA), "\n")
    cat(paste("Slider B =", paste(input$sliderB, collapse = " ")))
  })
}

shinyApp(ui, server)


问:
No Items in RecyclerView after adding item in sqlite
I am trying to add a name in sqlite and as soon as data is inserted in sqlite, i am updating the recyclerview. Following is my code

```<code>public class DbContract {
    public static final int SYNC_STATUS_OK=0;
    public static final int SYNC_STATUS_FAILED=1;
    public static final String DATABASE_NAME="contactdb";
    public static final String TABLE_NAME="contactinfo";
    public static final String NAME="name";
    public static final String SYNC_STATUS="syncstatus";
}

public class DbHelper extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION=1;
    public static final String CREATE_TABLE="create table "+DbContract.TABLE_NAME+" (id integer primary key autoincrement, "+DbContract.NAME+" text,"+
            DbContract.SYNC_STATUS+" integer);";
    public static final String DROP_TABLE="drop table if exists "+DbContract.TABLE_NAME;

    public DbHelper(Context context) {
        super(context, DbContract.DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL(DROP_TABLE);
        onCreate(sqLiteDatabase);
    }

    public void saveToLocalDatabase(String name,int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.NAME,name);
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        sqLiteDatabase.insert(DbContract.TABLE_NAME,null,contentValues);
    }

    public Cursor readFromLocalDatabase(SQLiteDatabase sqLiteDatabase){
        String[] projection={DbContract.NAME,DbContract.SYNC_STATUS};
      //  Log.i("frff", "readFromLocalDatabase: "+projection.toString());
        return (sqLiteDatabase.query(DbContract.TABLE_NAME,projection,null,null,null,null,null));
    }

    public void updateLocalDatabase(String name, int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        String selection = DbContract.NAME+" LIKE ? ";
        String[] selection_args={name};
        sqLiteDatabase.update(DbContract.TABLE_NAME,contentValues,selection,selection_args);
    }
}

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText editText;
    private Button button;
    private ArrayList<Contact> arrayList;
    private RecyclerAdapter recyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recyclerview);
        editText = findViewById(R.id.et);
        button = findViewById(R.id.button);
        arrayList = new ArrayList<>();
        recyclerAdapter = new RecyclerAdapter(arrayList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(recyclerAdapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = editText.getText().toString();
                saveToLocalStorage(name);
                editText.setText("");
            }
        });
    }

    public void submitName(View view) {

    }

    public boolean checkNetworkConnection() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    private void readFromLocalStorage() {
        arrayList.clear();
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
        Cursor cursor = dbHelper.readFromLocalDatabase(sqLiteDatabase);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(DbContract.NAME));
            int sync_status = cursor.getInt(cursor.getColumnIndex(DbContract.SYNC_STATUS));
            arrayList.add(new Contact(name, sync_status));

        }
        recyclerAdapter.notifyDataSetChanged();
        cursor.close();
        dbHelper.close();
    }

    private void saveToLocalStorage(String name) {
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
        if (checkNetworkConnection()) {

        } else {
            dbHelper.saveToLocalDatabase(name, DbContract.SYNC_STATUS_FAILED, sqLiteDatabase);
        }
        readFromLocalStorage();
        dbHelper.close();
    }
}
</code>```

Whenever an item is added through edittext and button is cliked,  no item can be seen in my recyclerview . I am not getting any error in my logcat and neither does the app crashes. Any help would be  greatly appreciated.

答:
Try following code : </p>

```<code>    public class DbContract {
    public static final int SYNC_STATUS_OK=0;
    public static final int SYNC_STATUS_FAILED=1;
    public static final String DATABASE_NAME="contactdb";
    public static final String TABLE_NAME="contactinfo";
    public static final String NAME="name";
    public static final String SYNC_STATUS="syncstatus";
    }

    public class DbHelper extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION=1;
    public static final String CREATE_TABLE="create table "+DbContract.TABLE_NAME+" id integer primary key autoincrement, "+DbContract.NAME+" text,"+
            DbContract.SYNC_STATUS+" integer);";
    public static final String DROP_TABLE="drop table if exists "+DbContract.TABLE_NAME;

    public DbHelper(Context context) {
        super(context, DbContract.DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL(DROP_TABLE);
        onCreate(sqLiteDatabase);
    }

    public void saveToLocalDatabase(String name,int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.NAME,name);
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        sqLiteDatabase.insert(DbContract.TABLE_NAME,null,contentValues);
    }

    public Cursor readFromLocalDatabase(SQLiteDatabase sqLiteDatabase){
        String[] projection={DbContract.NAME,DbContract.SYNC_STATUS};
      //  Log.i("frff", "readFromLocalDatabase: "+projection.toString());
        return (sqLiteDatabase.query(DbContract.TABLE_NAME,projection,null,null,null,null,null));
    }

    public void updateLocalDatabase(String name, int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        String selection = DbContract.NAME+" LIKE ? ";
        String[] selection_args={name};
        sqLiteDatabase.update(DbContract.TABLE_NAME,contentValues,selection,selection_args);
    }
}

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText editText;
    private Button button;
    private ArrayList<Contact> arrayList;
    private RecyclerAdapter recyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recyclerview);
        editText = findViewById(R.id.et);
        button = findViewById(R.id.button);
        arrayList = new ArrayList<>();
        recyclerAdapter = new RecyclerAdapter(arrayList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(recyclerAdapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = editText.getText().toString();
                saveToLocalStorage(name);
                editText.setText("");
            }
        });
    }

    public void submitName(View view) {

    }

    public boolean checkNetworkConnection() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    private void readFromLocalStorage() {
        arrayList.clear();
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
        Cursor cursor = dbHelper.readFromLocalDatabase(sqLiteDatabase);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(DbContract.NAME));
            int sync_status = cursor.getInt(cursor.getColumnIndex(DbContract.SYNC_STATUS));
            arrayList.add(new Contact(name, sync_status));

        }
        recyclerAdapter.notifyDataSetChanged();
        cursor.close();
        dbHelper.close();
    }

    private void saveToLocalStorage(String name) {
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
        if (checkNetworkConnection()) {

        } else {
            dbHelper.saveToLocalDatabase(name, DbContract.SYNC_STATUS_FAILED, sqLiteDatabase);
        }
        dbHelper.close();
        readFromLocalStorage();

    }
}
</code>```

Body:
I am trying to add a name in sqlite and as soon as data is inserted in sqlite, i am updating the recyclerview. Following is my code

public class DbContract {
    public static final int SYNC_STATUS_OK=0;
    public static final int SYNC_STATUS_FAILED=1;
    public static final String DATABASE_NAME="contactdb";
    public static final String TABLE_NAME="contactinfo";
    public static final String NAME="name";
    public static final String SYNC_STATUS="syncstatus";
}

public class DbHelper extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION=1;
    public static final String CREATE_TABLE="create table "+DbContract.TABLE_NAME+" (id integer primary key autoincrement, "+DbContract.NAME+" text,"+
            DbContract.SYNC_STATUS+" integer);";
    public static final String DROP_TABLE="drop table if exists "+DbContract.TABLE_NAME;

    public DbHelper(Context context) {
        super(context, DbContract.DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL(DROP_TABLE);
        onCreate(sqLiteDatabase);
    }

    public void saveToLocalDatabase(String name,int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.NAME,name);
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        sqLiteDatabase.insert(DbContract.TABLE_NAME,null,contentValues);
    }

    public Cursor readFromLocalDatabase(SQLiteDatabase sqLiteDatabase){
        String[] projection={DbContract.NAME,DbContract.SYNC_STATUS};
      //  Log.i("frff", "readFromLocalDatabase: "+projection.toString());
        return (sqLiteDatabase.query(DbContract.TABLE_NAME,projection,null,null,null,null,null));
    }

    public void updateLocalDatabase(String name, int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        String selection = DbContract.NAME+" LIKE ? ";
        String[] selection_args={name};
        sqLiteDatabase.update(DbContract.TABLE_NAME,contentValues,selection,selection_args);
    }
}

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText editText;
    private Button button;
    private ArrayList<Contact> arrayList;
    private RecyclerAdapter recyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recyclerview);
        editText = findViewById(R.id.et);
        button = findViewById(R.id.button);
        arrayList = new ArrayList<>();
        recyclerAdapter = new RecyclerAdapter(arrayList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(recyclerAdapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = editText.getText().toString();
                saveToLocalStorage(name);
                editText.setText("");
            }
        });
    }

    public void submitName(View view) {

    }

    public boolean checkNetworkConnection() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    private void readFromLocalStorage() {
        arrayList.clear();
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
        Cursor cursor = dbHelper.readFromLocalDatabase(sqLiteDatabase);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(DbContract.NAME));
            int sync_status = cursor.getInt(cursor.getColumnIndex(DbContract.SYNC_STATUS));
            arrayList.add(new Contact(name, sync_status));

        }
        recyclerAdapter.notifyDataSetChanged();
        cursor.close();
        dbHelper.close();
    }

    private void saveToLocalStorage(String name) {
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
        if (checkNetworkConnection()) {

        } else {
            dbHelper.saveToLocalDatabase(name, DbContract.SYNC_STATUS_FAILED, sqLiteDatabase);
        }
        readFromLocalStorage();
        dbHelper.close();
    }
}

Whenever an item is added through edittext and button is cliked,  no item can be seen in my recyclerview . I am not getting any error in my logcat and neither does the app crashes. Any help would be  greatly appreciated.

Body:
Try following code :

    public class DbContract {
    public static final int SYNC_STATUS_OK=0;
    public static final int SYNC_STATUS_FAILED=1;
    public static final String DATABASE_NAME="contactdb";
    public static final String TABLE_NAME="contactinfo";
    public static final String NAME="name";
    public static final String SYNC_STATUS="syncstatus";
    }

    public class DbHelper extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION=1;
    public static final String CREATE_TABLE="create table "+DbContract.TABLE_NAME+" id integer primary key autoincrement, "+DbContract.NAME+" text,"+
            DbContract.SYNC_STATUS+" integer);";
    public static final String DROP_TABLE="drop table if exists "+DbContract.TABLE_NAME;

    public DbHelper(Context context) {
        super(context, DbContract.DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL(DROP_TABLE);
        onCreate(sqLiteDatabase);
    }

    public void saveToLocalDatabase(String name,int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.NAME,name);
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        sqLiteDatabase.insert(DbContract.TABLE_NAME,null,contentValues);
    }

    public Cursor readFromLocalDatabase(SQLiteDatabase sqLiteDatabase){
        String[] projection={DbContract.NAME,DbContract.SYNC_STATUS};
      //  Log.i("frff", "readFromLocalDatabase: "+projection.toString());
        return (sqLiteDatabase.query(DbContract.TABLE_NAME,projection,null,null,null,null,null));
    }

    public void updateLocalDatabase(String name, int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        String selection = DbContract.NAME+" LIKE ? ";
        String[] selection_args={name};
        sqLiteDatabase.update(DbContract.TABLE_NAME,contentValues,selection,selection_args);
    }
}

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText editText;
    private Button button;
    private ArrayList<Contact> arrayList;
    private RecyclerAdapter recyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recyclerview);
        editText = findViewById(R.id.et);
        button = findViewById(R.id.button);
        arrayList = new ArrayList<>();
        recyclerAdapter = new RecyclerAdapter(arrayList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(recyclerAdapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = editText.getText().toString();
                saveToLocalStorage(name);
                editText.setText("");
            }
        });
    }

    public void submitName(View view) {

    }

    public boolean checkNetworkConnection() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    private void readFromLocalStorage() {
        arrayList.clear();
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
        Cursor cursor = dbHelper.readFromLocalDatabase(sqLiteDatabase);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(DbContract.NAME));
            int sync_status = cursor.getInt(cursor.getColumnIndex(DbContract.SYNC_STATUS));
            arrayList.add(new Contact(name, sync_status));

        }
        recyclerAdapter.notifyDataSetChanged();
        cursor.close();
        dbHelper.close();
    }

    private void saveToLocalStorage(String name) {
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
        if (checkNetworkConnection()) {

        } else {
            dbHelper.saveToLocalDatabase(name, DbContract.SYNC_STATUS_FAILED, sqLiteDatabase);
        }
        dbHelper.close();
        readFromLocalStorage();

    }
}


问:
Warning publishing Azure service bus queue trigger can't find named value in local.settings.json
I have a Azure service bus queue trigger function and when I created it it asked me 3 fields, access rights, connection and queue name.

I put in listen for the access rights. For the connection I used the the 'primary connection' name given in the 'RootManageSharedAccessKey' in the service bus I created.
It looks something like this

Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=JG0gwJ90bkbGl1BU=

and I created a queue in my service bus called yogaband and that is what I used for the queue name as the third parameter.

My function looks like this

```<code>public static class PostEventEmails
{
    [FunctionName("PostEventEmails")]
    public static void Run([ServiceBusTrigger("yogaband2017", AccessRights.Listen, Connection = "Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=gkbGl1BU=")]string myQueueItem, TraceWriter log)
    {
        log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
    }
}
</code>```

When I publish the function I get this warning

.nuget\packages\microsoft.net.sdk.functions\1.0.2\build\netstandard1.0\Microsoft.NET.Sdk.Functions.Build.targets(31,5): warning : Function [PostEventEmails]: cannot find value named 'Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=0bkbGl1BU=' in local.settings.json that matches 'connection' property set on 'serviceBusTrigger' [C:\Users\Source\Workspaces\YogaBand2017\YogaBand2017\PostEventEmails\PostEventEmails.csproj]

and in my site I can pass the queue a message and I see the message in the queue in my Azure portal, but the function isn't picking up the message and processing it. So I still see '1 message' in the active message count in the queue. I assume it would be 0 after the function picks it up and processes it and I would see the log trace in the window? But I don't so I think the connection isn't correct or I didn't configure something correctly but I don't know what!

Here is what I put into the local.settings.json file

```<code>{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=bGl1BU=",
"AzureWebJobsDashboard": ""}}
</code>```

FYI - here is how I send the mesage to the queue in c#

```<code> var queueClient = QueueClient.Create("yogaband2017");
            BrokeredMessage message = new BrokeredMessage("some test message");
            message.MessageId = newEvent.YogaSpaceEventId.ToString();

            queueClient.Send(message);
</code>```

and in my web.config file I added this

```<code><add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=0gwJ90bkbGl1BU="/>
</code>```

答:
Connection property of ServiceBusTrigger should be set to a setting name, not connection string itself:

[ServiceBusTrigger("yogaband2017", AccessRights.Listen, Connection = "MyConn")]
```

<p>You then define a setting with this name in <code>local.settings.json</code> for local development environment:</p>

<pre class="lang-json prettyprint-override"><code>{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "... azure storage connection string ...",
    "MyConn": "... service bus connection string ..."
  }
}
</code>```

and in App Settings for Azure deployment.

Note that AzureWebJobsStorage is NOT service bus connection.

Body:
I have a Azure service bus queue trigger function and when I created it it asked me 3 fields, access rights, connection and queue name.

I put in listen for the access rights. For the connection I used the the 'primary connection' name given in the 'RootManageSharedAccessKey' in the service bus I created.
It looks something like this

Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=JG0gwJ90bkbGl1BU=

and I created a queue in my service bus called yogaband and that is what I used for the queue name as the third parameter.

My function looks like this

public static class PostEventEmails
{
    [FunctionName("PostEventEmails")]
    public static void Run([ServiceBusTrigger("yogaband2017", AccessRights.Listen, Connection = "Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=gkbGl1BU=")]string myQueueItem, TraceWriter log)
    {
        log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
    }
}

When I publish the function I get this warning

.nuget\packages\microsoft.net.sdk.functions\1.0.2\build\netstandard1.0\Microsoft.NET.Sdk.Functions.Build.targets(31,5): warning : Function [PostEventEmails]: cannot find value named 'Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=0bkbGl1BU=' in local.settings.json that matches 'connection' property set on 'serviceBusTrigger' [C:\Users\Source\Workspaces\YogaBand2017\YogaBand2017\PostEventEmails\PostEventEmails.csproj]

and in my site I can pass the queue a message and I see the message in the queue in my Azure portal, but the function isn't picking up the message and processing it. So I still see '1 message' in the active message count in the queue. I assume it would be 0 after the function picks it up and processes it and I would see the log trace in the window? But I don't so I think the connection isn't correct or I didn't configure something correctly but I don't know what!

Here is what I put into the local.settings.json file

{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=bGl1BU=",
"AzureWebJobsDashboard": ""}}

FYI - here is how I send the mesage to the queue in c#

 var queueClient = QueueClient.Create("yogaband2017");
            BrokeredMessage message = new BrokeredMessage("some test message");
            message.MessageId = newEvent.YogaSpaceEventId.ToString();

            queueClient.Send(message);

and in my web.config file I added this

<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=0gwJ90bkbGl1BU="/>

Body:
Connection property of ServiceBusTrigger should be set to a setting name, not connection string itself:

[ServiceBusTrigger("yogaband2017", AccessRights.Listen, Connection = "MyConn")]

You then define a setting with this name in local.settings.json for local development environment:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "... azure storage connection string ...",
    "MyConn": "... service bus connection string ..."
  }
}

and in App Settings for Azure deployment.

Note that AzureWebJobsStorage is NOT service bus connection.


问:
The wan of EternalBlue and DoublePulsar
I have an ideea how the thing works in a LAN sceneryo but on WAN...
So my question is simple, is there any way to use EternalBlue and DoublePulsar to hack outside the LAN ?</p>

答: If I opened a NGROK tcp tunnel on port 445 Which is smb port then we can exploit the port through the ngrok url along with the port. We can't use this trick in real pentesting  because we need to set the ngrok tunnel first to exploit. We can do it however if we use social engineering on victim and then victim himself opens the port for us and then we can hack it.</p>

Title: The wan of EternalBlue and DoublePulsar


问:
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.Writer.write(java.lang.String)' on a null object reference

java.lang.NullPointerException: Attempt to invoke virtual method 'void
  java.io.Writer.write(java.lang.String)' on a null object reference
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at
  com.end.myapplication.MainActivity$SendingRunnable.run(MainActivity.java:124)
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at android.os.Handler.handleCallback(Handler.java:751) 12-09
  07:18:35.259 2419-2419/com.end.myapplication W/System.err:     at
  android.os.Handler.dispatchMessage(Handler.java:95) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  android.os.Looper.loop(Looper.java:154) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  android.app.ActivityThread.main(ActivityThread.java:6119) 12-09
  07:18:35.259 2419-2419/com.end.myapplication W/System.err:     at
  java.lang.reflect.Method.invoke(Native Method) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

MainActivity

```<code>package com.end.myapplication;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private String html = "";
    private Handler mHandler;

    private Socket socket;

    private BufferedReader networkReader;
    private BufferedWriter networkWriter;

    private String ip = "192.168.56.1"; // IP
    private int port = 5516; // PORT번호

    boolean check=false;

    EditText et;
    TextView tv;
    NetworkThread thread;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et = (EditText) findViewById(R.id.EditText01);
        Button btn = (Button) findViewById(R.id.Button01);
        tv = (TextView) findViewById(R.id.TextView01);

        btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if (et.getText().toString() != null || !et.getText().toString().equals("")) {
                    check=true;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Thread(){
            @Override
            public void run(){
                try {
                    socket = new Socket(ip, port);
                    networkWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    networkReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }.start();
        thread = new NetworkThread(networkReader, networkWriter);
        thread.start();
    }

    private class NetworkThread extends Thread {
        BufferedReader br;
        BufferedWriter bw;
        Handler mHandler;
        SendingRunnable sendingRunnable;

        private NetworkThread(BufferedReader br, BufferedWriter bw){
            this.br = br;
            this.bw = bw;
            mHandler = new Handler();
            sendingRunnable = new SendingRunnable(bw);
        }

        @Override
        public void run() {
            super.run();
            boolean isError = false;
            String result = "";
            String error = "";

            try{
                this.bw.write("CONNECTED\n");
                this.bw.flush();
            }catch (Exception e){
                e.printStackTrace();
            }
            while (true){
                try{
                    if (check){
                        mHandler.post(sendingRunnable);

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

    private class SendingRunnable implements Runnable {
        BufferedWriter bw;

        private SendingRunnable(BufferedWriter bw){
            this.bw = bw;
        }

        @Override
        public void run() {
            String formula = et.getText().toString();
            try{
                bw.write(formula+"\n");
                bw.flush();
                et.setText("");
            }catch (Exception e){e.printStackTrace();}
        }
    }
}
</code>```

答:
There is possibility of race condition in your Thread usage. Try removing former Thread.

Change

```<code>new Thread(){
        @Override
        public void run(){
            try {
                socket = new Socket(ip, port);
                networkWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                networkReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }.start();
</code>```

to

```<code>try {
   socket = new Socket(ip, port);
   networkWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
   networkReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e1) {
    throw new AssertionError(e1);
}
</code>```

Body:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
  java.io.Writer.write(java.lang.String)' on a null object reference
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at
  com.end.myapplication.MainActivity$SendingRunnable.run(MainActivity.java:124)
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at android.os.Handler.handleCallback(Handler.java:751) 12-09
  07:18:35.259 2419-2419/com.end.myapplication W/System.err:     at
  android.os.Handler.dispatchMessage(Handler.java:95) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  android.os.Looper.loop(Looper.java:154) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  android.app.ActivityThread.main(ActivityThread.java:6119) 12-09
  07:18:35.259 2419-2419/com.end.myapplication W/System.err:     at
  java.lang.reflect.Method.invoke(Native Method) 12-09 07:18:35.259
  2419-2419/com.end.myapplication W/System.err:     at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
  12-09 07:18:35.259 2419-2419/com.end.myapplication W/System.err:

  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

MainActivity

package com.end.myapplication;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private String html = "";
    private Handler mHandler;

    private Socket socket;

    private BufferedReader networkReader;
    private BufferedWriter networkWriter;

    private String ip = "192.168.56.1"; // IP
    private int port = 5516; // PORT번호

    boolean check=false;

    EditText et;
    TextView tv;
    NetworkThread thread;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et = (EditText) findViewById(R.id.EditText01);
        Button btn = (Button) findViewById(R.id.Button01);
        tv = (TextView) findViewById(R.id.TextView01);

        btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if (et.getText().toString() != null || !et.getText().toString().equals("")) {
                    check=true;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Thread(){
            @Override
            public void run(){
                try {
                    socket = new Socket(ip, port);
                    networkWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    networkReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }.start();
        thread = new NetworkThread(networkReader, networkWriter);
        thread.start();
    }

    private class NetworkThread extends Thread {
        BufferedReader br;
        BufferedWriter bw;
        Handler mHandler;
        SendingRunnable sendingRunnable;

        private NetworkThread(BufferedReader br, BufferedWriter bw){
            this.br = br;
            this.bw = bw;
            mHandler = new Handler();
            sendingRunnable = new SendingRunnable(bw);
        }

        @Override
        public void run() {
            super.run();
            boolean isError = false;
            String result = "";
            String error = "";

            try{
                this.bw.write("CONNECTED\n");
                this.bw.flush();
            }catch (Exception e){
                e.printStackTrace();
            }
            while (true){
                try{
                    if (check){
                        mHandler.post(sendingRunnable);

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

    private class SendingRunnable implements Runnable {
        BufferedWriter bw;

        private SendingRunnable(BufferedWriter bw){
            this.bw = bw;
        }

        @Override
        public void run() {
            String formula = et.getText().toString();
            try{
                bw.write(formula+"\n");
                bw.flush();
                et.setText("");
            }catch (Exception e){e.printStackTrace();}
        }
    }
}

Body:
There is possibility of race condition in your Thread usage. Try removing former Thread.

Change

new Thread(){
        @Override
        public void run(){
            try {
                socket = new Socket(ip, port);
                networkWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                networkReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }.start();

to

try {
   socket = new Socket(ip, port);
   networkWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
   networkReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e1) {
    throw new AssertionError(e1);
}


问:
Android: Nougat (Huawei Honor 6x) : Urdu text not displaying correctly
Urdu/Arabic Text is scrambled every where in the operating system ever since I have updated my Huawei Honor 6x from Marshmallow to Nougat. Screenshot is attached. Even when i type the urdu text, incorrect text is typed.

There is no option in the OS to add Arabic language.

What can be the possible solution except downgrading?

答:
After the update. Performing a reset again solved the issue.

Note: Please backup your data before doing so.


问:
Cannot connect to Cloudera Manager, not listening on port 7180
I'd really appreciate some help to get cloudera manager running on AWS EC2.
Its my first install,  and I'm aiming to use the  AWS Free Tier to spin up a few nodes and do some training on Hadoop cluster and the cloudera distribution. I'm using the RedHat RHEL 7.2 image on AWS EC2.

I am following the instructions here... Cloudera Manager installation

I have installed cloudera manager OK, and get to the screen where it invites you to use a browser to log-in to the cloudera manager server.  But that's where the problem starts. It seems the app is not listening on port 7180,  so there's no hope of connecting from another machine across the network.  I can't even connect locally, on the server,  yet the service appears to be running OK.  But its not listening on port 7180.

Q1 - How can I confirm the config is set to use port 7180.?

Q2 - are there obvious steps that I'm missing here ?

Thanks in advance,

[Edit..]
I'm beginning to wonder if the Free EC2 host is running short on memory to run cloudera manager.  I saw one comment that implied that....AWS Forum post .  But the process doesn't crash or report any problems in its logfile. So it must be OK,  right?

[Edit.... with more diagnostic info....]

Here's a list of the diagnostics I've checked:-

SELinux is not running [for install and testing purposes],

WAN firewalls,

EC2 firewall/Security group,

Local firewall on server,

Cloudera manager log,

Is the service up and running?

Can you connect locally?

Securtity group on the EC2 instance, it contains:-
SSH and Port 7180,

Firewall/iptables/firewalld  on the RedHat instance,  tried:-
adding ports to iptables, then
dissabling iptables, then
adding ports to firewalld, then
dissabling the firewalld service,

```<code>$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere             state NEW tcp dpt:7180
ACCEPT     tcp  --  anywhere             anywhere             state NEW tcp dpt:7182
</code>```

But I'm getting the feeling that  the installation of cloudera manager is not happy,  or not running correctly.

I've checked the cloudera manager log, and it ends with the following.

```<code>$ tail /var/log/cloudera-scm-server/cloudera-scm-server.log
2016-02-25 11:02:23,581 INFO main:com.cloudera.cmon.components.MetricSchemaUpdate: persisting 19264 new metrics
2016-02-25 11:02:28,920 INFO main:com.cloudera.cmon.components.MetricSchemaUpdate: persisting 0 updated metrics
2016-02-25 11:02:28,924 INFO main:com.cloudera.cmon.components.MetricSchemaManager: Cross entity aggregates processed.
</code>```

And when I  use tail -f,  and restart the cloudera-scm-server service,  the log scrolls a lot,  and comes back the same state.  If I search for ERROR,  there are no lines with "ERR".

```<code>$ sudo service cloudera-scm-server start
Starting cloudera-scm-server (via systemctl):              [  OK  ]

$ sudo systemctl status cloudera-scm-server
● cloudera-scm-server.service - LSB: Cloudera SCM Server
   Loaded: loaded (/etc/rc.d/init.d/cloudera-scm-server)
   Active: active (exited) since Thu 2016-02-25 12:23:03 EST; 44s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 747 ExecStart=/etc/rc.d/init.d/cloudera-scm-server start (code=exited, status=0/SUCCESS)
</code>```

So,  if I try to test the service, by connecting from the local machine I get  the sort of behavious that makes me thing its just not listening,  and maybe not started correctly.

Try poke it with a curl from the same shell as the cloudera-scm-server service was started

```<code>$ curl localhost:7180
curl: (7) Failed connect to localhost:7180; Connection refused

$ wget localhost:7180
--2016-02-25 08:00:16--  http://localhost:7180/
Resolving localhost (localhost)... ::1, 127.0.0.1
Connecting to localhost (localhost)|::1|:7180... failed: Connection refused.
Connecting to localhost (localhost)|127.0.0.1|:7180... failed: Connection refused.
</code>```

Try check what ports are listening on that machine,  no 7180 ,  what's up with that???

```<code>$ netstat -nltp
(No info could be read for "-p": geteuid()=1000 but you should be root.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:7432            0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      -
tcp6       0      0 :::7432                 :::*                    LISTEN      -
tcp6       0      0 :::22                   :::*                    LISTEN      -
tcp6       0      0 ::1:25                  :::*                    LISTEN      -
</code>```

答:
I was having the exact same issue, cannot hit the CM login using public DNS or IP on port 7180.

Following steps will help you :

```<code>iptables stopped (service iptables stop)
SELinux disabled (got to /etc/selinux/config and disbaled the selinux)
curl/wget localhost:7180 works (check the curl status)
ufw allow 7180
service httpd status should be running.
check va/log/cloudera-scm-server log : if any error found then troubleshoot the error
cloudera-scm-server status (should be running state)
netstat -nap | grep 7180 returns  (if running other service then kill it)
</code>```

telnet localhost 7180 (should be connected)

Body:
I'd really appreciate some help to get cloudera manager running on AWS EC2.
Its my first install,  and I'm aiming to use the  AWS Free Tier to spin up a few nodes and do some training on Hadoop cluster and the cloudera distribution. I'm using the RedHat RHEL 7.2 image on AWS EC2.

I am following the instructions here... Cloudera Manager installation

I have installed cloudera manager OK, and get to the screen where it invites you to use a browser to log-in to the cloudera manager server.  But that's where the problem starts. It seems the app is not listening on port 7180,  so there's no hope of connecting from another machine across the network.  I can't even connect locally, on the server,  yet the service appears to be running OK.  But its not listening on port 7180.

Q1 - How can I confirm the config is set to use port 7180.?

Q2 - are there obvious steps that I'm missing here ?

Thanks in advance,

[Edit..]
I'm beginning to wonder if the Free EC2 host is running short on memory to run cloudera manager.  I saw one comment that implied that....AWS Forum post .  But the process doesn't crash or report any problems in its logfile. So it must be OK,  right?

[Edit.... with more diagnostic info....]

Here's a list of the diagnostics I've checked:-

SELinux is not running [for install and testing purposes],

WAN firewalls,

EC2 firewall/Security group,

Local firewall on server,

Cloudera manager log,

Is the service up and running?

Can you connect locally?

Securtity group on the EC2 instance, it contains:-
SSH and Port 7180,

Firewall/iptables/firewalld  on the RedHat instance,  tried:-
adding ports to iptables, then
dissabling iptables, then
adding ports to firewalld, then
dissabling the firewalld service,

$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere             state NEW tcp dpt:7180
ACCEPT     tcp  --  anywhere             anywhere             state NEW tcp dpt:7182

But I'm getting the feeling that  the installation of cloudera manager is not happy,  or not running correctly.

I've checked the cloudera manager log, and it ends with the following.

$ tail /var/log/cloudera-scm-server/cloudera-scm-server.log
2016-02-25 11:02:23,581 INFO main:com.cloudera.cmon.components.MetricSchemaUpdate: persisting 19264 new metrics
2016-02-25 11:02:28,920 INFO main:com.cloudera.cmon.components.MetricSchemaUpdate: persisting 0 updated metrics
2016-02-25 11:02:28,924 INFO main:com.cloudera.cmon.components.MetricSchemaManager: Cross entity aggregates processed.

And when I  use tail -f,  and restart the cloudera-scm-server service,  the log scrolls a lot,  and comes back the same state.  If I search for ERROR,  there are no lines with "ERR".

$ sudo service cloudera-scm-server start
Starting cloudera-scm-server (via systemctl):              [  OK  ]

$ sudo systemctl status cloudera-scm-server
● cloudera-scm-server.service - LSB: Cloudera SCM Server
   Loaded: loaded (/etc/rc.d/init.d/cloudera-scm-server)
   Active: active (exited) since Thu 2016-02-25 12:23:03 EST; 44s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 747 ExecStart=/etc/rc.d/init.d/cloudera-scm-server start (code=exited, status=0/SUCCESS)

So,  if I try to test the service, by connecting from the local machine I get  the sort of behavious that makes me thing its just not listening,  and maybe not started correctly.

Try poke it with a curl from the same shell as the cloudera-scm-server service was started

$ curl localhost:7180
curl: (7) Failed connect to localhost:7180; Connection refused

$ wget localhost:7180
--2016-02-25 08:00:16--  http://localhost:7180/
Resolving localhost (localhost)... ::1, 127.0.0.1
Connecting to localhost (localhost)|::1|:7180... failed: Connection refused.
Connecting to localhost (localhost)|127.0.0.1|:7180... failed: Connection refused.

Try check what ports are listening on that machine,  no 7180 ,  what's up with that???

$ netstat -nltp
(No info could be read for "-p": geteuid()=1000 but you should be root.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:7432            0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      -
tcp6       0      0 :::7432                 :::*                    LISTEN      -
tcp6       0      0 :::22                   :::*                    LISTEN      -
tcp6       0      0 ::1:25                  :::*                    LISTEN      -

Body:
I was having the exact same issue, cannot hit the CM login using public DNS or IP on port 7180.

Following steps will help you :

iptables stopped (service iptables stop)
SELinux disabled (got to /etc/selinux/config and disbaled the selinux)
curl/wget localhost:7180 works (check the curl status)
ufw allow 7180
service httpd status should be running.
check va/log/cloudera-scm-server log : if any error found then troubleshoot the error
cloudera-scm-server status (should be running state)
netstat -nap | grep 7180 returns  (if running other service then kill it)

telnet localhost 7180 (should be connected)


问:
iOS " current graphics context" - What is that
When I draw lines and shapes etc I get the " current graphics context" in iOS.

What exactly though is " current graphics context" - I'm looking for the 30,000 foot description.

Right now I just copy and paste UI code, not exactly sure what it's doing.

答:
A graphics context is the place where information about the drawing state is stored. This includes fill color, stroke color, line width, line pattern, winding rule, mask, current path, transparency layers, transform, text transform, etc. When using CoreGraphics calls, you specify the context to use to every single function. This means you can use multiple contexts at once, though typically you only use one. At the UIKit layer, there is the concept of a "current" graphics context, which is a graphics context that's used by all UIKit-level drawing calls (such as -[UIColor set] or UIBezierPath drawing). The current context is stored in a stack of contexts, so you can create a new context for some drawing, then when you finish with it the previous context is restored. Typically you get a context for free inside of -[UIView drawRect:] inside of CALayer display-related methods, but not otherwise.

It used to be that the "current" context was an application-wide global state, and therefore was not safe to touch outside of the main thread. As of iOS 4.0 (I believe), this became a thread-local state and UIKit-level drawing methods became safe to use on background threads.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Missing packages with python-xbee library and raspberry
I'm trying to send some packages from an MSP to a Raspberry Pi 3 through 2 Xbee S1 modules.

Xbee are configured as DigiMesh 2.4 with escaped frames, one as router and other as coordinator. At the raspberry the connection is made with USB dongle.

My code, at MSP, sends a package at every 10 us with CTS flow control. When the coordinator is plugged into my PC running windows, I can see, through XCTU, all packages arriving, everything just fine!!!

But, when the dongle is at raspberry, running Raspbian and the following code, some packages can not arrive.

As everything works properly with XCTU, the problem resides in the code, probably handling serial port or anything similar to that.

So, any help would be much appreciate!!!

start.py:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# copyright: Thiago Cruz <thiagoalberto@gmail.com>

import sys
import os

from PyQt4 import QtGui
from middleware.QueueMiddleware import QueueMiddleware
from jobs.ScheduleJob import ScheduleJob

def startQueue():
    queue = QueueMiddleware()
    queue.start()

def assyncSchedule():
    schedule = ScheduleJob()
    schedule.run()

def runApp():
    startQueue()

    app = QtGui.QApplication(sys.argv)

    sys.exit(app.exec_())

if __name__ == '__main__':
    runApp()
</code>```

QueueMiddleware.py:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# copyright: Thiago Cruz <thiagoalberto@gmail.com>

import threading
import time
import serial
import Queue

from middleware.DataProcessorGear import DataProcessorGear
from xbee import ZigBee

minutes = 0

class QueueMiddleware(threading.Thread):
    __instance = None

    PORT = '/dev/ttyUSB0'
    BAUD_RATE = 9600

    # The XBee addresses I'm dealing with
    BROADCAST = '\x00\x00\x00\x00\x00\x00\xFF\xFF'
    UNKNOWN = '\xFF\xFE' # This is the 'I don't know' 16 bit address

    def __new__(cls):
        if QueueMiddleware.__instance is None:
            QueueMiddleware.__instance = super(QueueMiddleware, cls).__new__(cls)

        return QueueMiddleware.__instance

    def __init__(self):
        QueueMiddleware.__instance = self
        threading.Thread.__init__(self)
        self.dataPacketsQueue = Queue.Queue()
        # Create API object, which spawns a new thread
        self.ser = serial.Serial(
                                    port='/dev/ttyUSB0',
                                    baudrate = 9600,
                                    parity=serial.PARITY_NONE,
                                    stopbits=serial.STOPBITS_ONE,
                                    bytesize=serial.EIGHTBITS,
                                    timeout=1
                                )
        self.xbeeApi = ZigBee(self.ser, callback=self.message_received, escaped=True)
        print 'start queue'

    def __del__(self):
        # halt() must be called before closing the serial
        # port in order to ensure proper thread shutdown
        self.xbeeApi.halt()
        self.ser.close()
        self.processor = None

    def run(self):
        # Do other stuff in the main thread
        while True:
            try:
                time.sleep(1)
                #if self.dataPacketsQueue.qsize() > 0:
                #    lock = threading.Lock()
                #    processor = DataProcessorGear(self.dataPacketsQueue, lock)
                #    processor.start()
            except KeyboardInterrupt:
                break

    def message_received(self, data):
        global minutes

        minutes += 1
        print minutes
        self.dataPacketsQueue.put(data, block=True, timeout=None)
</code>```

I already tried to change the values of time.sleep() and have suppressed the execution of the subsequent threads to "isolate" the problem.

My console displays values from ~120 to ~170. MSP only sends 200 data packages!!

So... any guesses ??

Thanks in advance.

答:
Enable hardware flow control and change the baudrate from 9600 to 115200.  You'll have to update your XBee module configuration for the new baudrate, but you'll stand a chance of getting your packets through.

I assume you meant to write that you're sending packets every 10ms instead of every 10us.  At 10ms/packet, you're at 100 packets/second.  9600 baud is only about 960 characters per second, and your packets are surely larger than 9 characters with the API overhead.

Body:
I'm trying to send some packages from an MSP to a Raspberry Pi 3 through 2 Xbee S1 modules.

Xbee are configured as DigiMesh 2.4 with escaped frames, one as router and other as coordinator. At the raspberry the connection is made with USB dongle.

My code, at MSP, sends a package at every 10 us with CTS flow control. When the coordinator is plugged into my PC running windows, I can see, through XCTU, all packages arriving, everything just fine!!!

But, when the dongle is at raspberry, running Raspbian and the following code, some packages can not arrive.

As everything works properly with XCTU, the problem resides in the code, probably handling serial port or anything similar to that.

So, any help would be much appreciate!!!

start.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# copyright: Thiago Cruz <thiagoalberto@gmail.com>

import sys
import os

from PyQt4 import QtGui
from middleware.QueueMiddleware import QueueMiddleware
from jobs.ScheduleJob import ScheduleJob

def startQueue():
    queue = QueueMiddleware()
    queue.start()

def assyncSchedule():
    schedule = ScheduleJob()
    schedule.run()

def runApp():
    startQueue()

    app = QtGui.QApplication(sys.argv)

    sys.exit(app.exec_())

if __name__ == '__main__':
    runApp()

QueueMiddleware.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# copyright: Thiago Cruz <thiagoalberto@gmail.com>

import threading
import time
import serial
import Queue

from middleware.DataProcessorGear import DataProcessorGear
from xbee import ZigBee

minutes = 0

class QueueMiddleware(threading.Thread):
    __instance = None

    PORT = '/dev/ttyUSB0'
    BAUD_RATE = 9600

    # The XBee addresses I'm dealing with
    BROADCAST = '\x00\x00\x00\x00\x00\x00\xFF\xFF'
    UNKNOWN = '\xFF\xFE' # This is the 'I don't know' 16 bit address

    def __new__(cls):
        if QueueMiddleware.__instance is None:
            QueueMiddleware.__instance = super(QueueMiddleware, cls).__new__(cls)

        return QueueMiddleware.__instance

    def __init__(self):
        QueueMiddleware.__instance = self
        threading.Thread.__init__(self)
        self.dataPacketsQueue = Queue.Queue()
        # Create API object, which spawns a new thread
        self.ser = serial.Serial(
                                    port='/dev/ttyUSB0',
                                    baudrate = 9600,
                                    parity=serial.PARITY_NONE,
                                    stopbits=serial.STOPBITS_ONE,
                                    bytesize=serial.EIGHTBITS,
                                    timeout=1
                                )
        self.xbeeApi = ZigBee(self.ser, callback=self.message_received, escaped=True)
        print 'start queue'

    def __del__(self):
        # halt() must be called before closing the serial
        # port in order to ensure proper thread shutdown
        self.xbeeApi.halt()
        self.ser.close()
        self.processor = None

    def run(self):
        # Do other stuff in the main thread
        while True:
            try:
                time.sleep(1)
                #if self.dataPacketsQueue.qsize() > 0:
                #    lock = threading.Lock()
                #    processor = DataProcessorGear(self.dataPacketsQueue, lock)
                #    processor.start()
            except KeyboardInterrupt:
                break

    def message_received(self, data):
        global minutes

        minutes += 1
        print minutes
        self.dataPacketsQueue.put(data, block=True, timeout=None)

I already tried to change the values of time.sleep() and have suppressed the execution of the subsequent threads to "isolate" the problem.

My console displays values from ~120 to ~170. MSP only sends 200 data packages!!

So... any guesses ??

Thanks in advance.


问:
Create multiple origins in one cloudfront distribution
I want to create cloudfront distribution with two origins. One origin which server S3 bucket static Website without using signed cookies or url. Second origin is also S3 Bucket where i have stored my images and i want access this bucket content using signed cookies. How should i do it? Thanks in advance.</p>

答:
Not sure where is your bottleneck.

Create two origins in CloudFront distribution and have the signed url setting in the behaviour for your created origin.

Hope it helps.


问:
What is the difference between bridge network and overlay network?
I have checked videos and docs related to bridge network as well as overlay network, but I just can't find the difference. Both are used to create a connection between two networks. But what is the difference? When should I use bridge and when should I use overlay network?</p>

答:
Bridge networks connect two networks while creating a single aggregate network from multiple communication networks or network segments, hence the name bridge.

In the above image Station A and Station B are connected by a bridge. Thus by using the bridge we aggregated both network in a single unit (on a high level). Bridge can even be used to create connection between networks on same host. This is generally required if the host is running multiple VM's  or containers.

Overlay networks are usually used to create a virtual network between two separate hosts. Virtual, since the network is build over an existing network.

In the above image host A and host B are connected over an external network and an overlay network is built over that network. For example initially internet was built as an overlay over telephone lines, but now many telephone networks (using VoIP) are an overlay over internet.