问:
How to convert RDD[GenericRecord] to dataframe in scala?
I get tweets from kafka topic with Avro (serializer and deserializer).
Then i create a spark consumer which extracts tweets in Dstream of RDD[GenericRecord].
Now i want to convert each rdd to a dataframe to analyse these tweets via SQL.
Any solution to convert RDD[GenericRecord] to dataframe please ?</p>

答:
You can use createDataFrame(rowRDD: RDD[Row], schema: StructType), which is available in the SQLContext object. Example for converting an RDD of an old DataFrame:

```<code>import sqlContext.implicits.
val rdd = oldDF.rdd
val newDF = oldDF.sqlContext.createDataFrame(rdd, oldDF.schema)
</code>```

Note that there is no need to explicitly set any schema column. We reuse the old DF's schema, which is of StructType class and can be easily extended. However, this approach sometimes is not possible, and in some cases can be less efficient than the first one.

Body:
You can use createDataFrame(rowRDD: RDD[Row], schema: StructType), which is available in the SQLContext object. Example for converting an RDD of an old DataFrame:

import sqlContext.implicits.
val rdd = oldDF.rdd
val newDF = oldDF.sqlContext.createDataFrame(rdd, oldDF.schema)

Note that there is no need to explicitly set any schema column. We reuse the old DF's schema, which is of StructType class and can be easily extended. However, this approach sometimes is not possible, and in some cases can be less efficient than the first one.


来源: stackexchange

问:
Daily scheduling talend etl job at particular time
I have an ETL talend job which works on manual run button click. i want to automate this job daily at particular time with out any human interaction. ETL talend tool is installed in windows 10 machine. </p>

答:
Check this link shedule talend job on daily basis in windows

Note: You'll get a detailed explaination of how to build an autonomus job and how to schedule it using the standard windows tasks scheduler.

ContentLicense: CC BY-SA 3.0


问:
Running SQL query after AJAX completes
I currently have 2 html dropdowns. Once I select from one, it filters the data in my HTML table and displays data based on the selection. I can also make changes to each row and, by clicking a save button, run an update query that updates the table. After, running that update, I want it to re-run the same query that was used to filter the results based on the dropdown selection so you can see the most up-to-date results of what you selected after clicking save and running the update statement. Right now, you can see that I have window.location.href = window.location.href; under the success callback in my AJAX function, but that reloads the entire page and runs the default query that displays on page load, so that doesn't work for me.

All of my queries that filter the table results after a dropdown selection are in my dropdown-display.php page that is called once I select something.

HTML Dropdowns:

```<code><form name="testForm" action="">
    <select id="collector">
        <option value="" selected="selected" disabled="disabled">Collector Name</option>
        <?php foreach($collect->fetchAll() as $name) { ?>
            <option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
        <?php } ?>
    </select>

    <select id="date">
        <option value="" selected="selected" disabled="disabled">Bill Date</option>
        <?php foreach($bill_date->fetchAll() as $date) { ?>
            <option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
        <?php } ?>
    </select>
</form>
</code>```

JavaScript (index.js):

```<code>$(document).ready(function () {

    $('.save').click(function (event) {

        var $row = $(this).parents('tr');
            var acct = $row.find('td[name="account"]').text();
            var date = $row.find('td[name="date"]').text();
            var checked = $row.find('input[name="selected"]').is(':checked');
            var currency = $row.find('input[name="currency"]').val();
            var datepicker = $row.find('input[name="datepicker"]').val();
            var notes = $row.find('textarea[name="notes"]').val();
            var paid = $row.find('input[name="paid"]').is(':checked');

    var request = $.ajax({

          type: "POST",
          url: "update.php",
          data: { acct: acct, date: date, checked: checked, currency: currency, datepicker: datepicker, notes: notes, paid: paid },
          success: function(data){
              alert('Row successfully saved');
              //window.location.href = window.location.href;
              }
            });

        });

    });
</code>```

And this is my javascript that is run in my head tag in my main index.php page:

```<code>function showUser(collector,date) {
  $('#billing_table').hide();
  if (collector == "") {
      document.getElementById("txtHint").innerHTML = "";
      return;
  } else {
      if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;

            var newTableObject = document.getElementById('billing_table');
            sorttable.makeSortable(newTableObject);

        }
    }

    $.ajax(
      "dropdown-display.php"
      ,{
        data:{
          q:collector,
          data:date||undefined
        }
      }
    ).then(
      function(responseText){
        $("#txtHint").html(responseText);
        sorttable.makeSortable($('#billing_table')[0]);
      }
      ,function(error){
        console.warn("something went wrong:",error);
        debugger;
      }
    )

  }
}

$(document).ready(function(){

    $("#collector, #date").change(function(e){
    showUser(
      $("#collector").val()
      ,$("#date").val()
    );
  });

    $("#collector").change(function(e){
        $.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
            $("#date .choice").hide();
            $.each(data, function(key,row) {
                $("#date option").filter(function(i){
                    return $(this).attr("value").indexOf( row.item ) != -1;
                }).show();
            });
        },"JSON");
    });

});
</code>```

答:
You need to send the filters (in your Ajax call) as parameters to the page that gets the result. You could name them collector_sel and date_sel.

Once the update has been completed, you must return these parameters.

For example, you could return them in the same GET string you use for window.location. href.

window. location. href = "index.php?collector_sel=abc&date_sel=bcd"

Then on the page you initially load it compares the filter values to select them again.

```<code><form name="testForm" action="">
    <select id="collector">
        <option value="">Collector Name</option>
        <?php
          $selected = "";
          foreach($collect->fetchAll() as $name) {
             if (isset($collect_sel)){
                if (strpos($_GET['collect_val'],$name['Collector Name'])==0)
                    $selected = "selected";
                }
             } ?>

            <option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"
             selected="<?php echo $selected; ?>" ><?php echo $name['Collector Name'];?></option>
        <?php } ?>
    </select>

// ....
</form>
</code>```

Title: Running SQL query after AJAX completes

Body:
I currently have 2 html dropdowns. Once I select from one, it filters the data in my HTML table and displays data based on the selection. I can also make changes to each row and, by clicking a save button, run an update query that updates the table. After, running that update, I want it to re-run the same query that was used to filter the results based on the dropdown selection so you can see the most up-to-date results of what you selected after clicking save and running the update statement. Right now, you can see that I have window.location.href = window.location.href; under the success callback in my AJAX function, but that reloads the entire page and runs the default query that displays on page load, so that doesn't work for me.

All of my queries that filter the table results after a dropdown selection are in my dropdown-display.php page that is called once I select something.

HTML Dropdowns:

<form name="testForm" action="">
    <select id="collector">
        <option value="" selected="selected" disabled="disabled">Collector Name</option>
        <?php foreach($collect->fetchAll() as $name) { ?>
            <option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
        <?php } ?>
    </select>

    <select id="date">
        <option value="" selected="selected" disabled="disabled">Bill Date</option>
        <?php foreach($bill_date->fetchAll() as $date) { ?>
            <option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
        <?php } ?>
    </select>
</form>

JavaScript (index.js):

$(document).ready(function () {

    $('.save').click(function (event) {

        var $row = $(this).parents('tr');
            var acct = $row.find('td[name="account"]').text();
            var date = $row.find('td[name="date"]').text();
            var checked = $row.find('input[name="selected"]').is(':checked');
            var currency = $row.find('input[name="currency"]').val();
            var datepicker = $row.find('input[name="datepicker"]').val();
            var notes = $row.find('textarea[name="notes"]').val();
            var paid = $row.find('input[name="paid"]').is(':checked');

    var request = $.ajax({

          type: "POST",
          url: "update.php",
          data: { acct: acct, date: date, checked: checked, currency: currency, datepicker: datepicker, notes: notes, paid: paid },
          success: function(data){
              alert('Row successfully saved');
              //window.location.href = window.location.href;
              }
            });

        });

    });

And this is my javascript that is run in my head tag in my main index.php page:

function showUser(collector,date) {
  $('#billing_table').hide();
  if (collector == "") {
      document.getElementById("txtHint").innerHTML = "";
      return;
  } else {
      if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;

            var newTableObject = document.getElementById('billing_table');
            sorttable.makeSortable(newTableObject);

        }
    }

    $.ajax(
      "dropdown-display.php"
      ,{
        data:{
          q:collector,
          data:date||undefined
        }
      }
    ).then(
      function(responseText){
        $("#txtHint").html(responseText);
        sorttable.makeSortable($('#billing_table')[0]);
      }
      ,function(error){
        console.warn("something went wrong:",error);
        debugger;
      }
    )

  }
}

$(document).ready(function(){

    $("#collector, #date").change(function(e){
    showUser(
      $("#collector").val()
      ,$("#date").val()
    );
  });

    $("#collector").change(function(e){
        $.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
            $("#date .choice").hide();
            $.each(data, function(key,row) {
                $("#date option").filter(function(i){
                    return $(this).attr("value").indexOf( row.item ) != -1;
                }).show();
            });
        },"JSON");
    });

});

Body:
You need to send the filters (in your Ajax call) as parameters to the page that gets the result. You could name them collector_sel and date_sel.

Once the update has been completed, you must return these parameters.

For example, you could return them in the same GET string you use for window.location. href.

window. location. href = "index.php?collector_sel=abc&date_sel=bcd"

Then on the page you initially load it compares the filter values to select them again.

<form name="testForm" action="">
    <select id="collector">
        <option value="">Collector Name</option>
        <?php
          $selected = "";
          foreach($collect->fetchAll() as $name) {
             if (isset($collect_sel)){
                if (strpos($_GET['collect_val'],$name['Collector Name'])==0)
                    $selected = "selected";
                }
             } ?>

            <option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"
             selected="<?php echo $selected; ?>" ><?php echo $name['Collector Name'];?></option>
        <?php } ?>
    </select>

// ....
</form>


问:
jquery validate and error styles

how do i get rid of the borders in ul > li ?

i have :

```<code>    errorLabelContainer: $("ul", $('div.error')), wrapper: 'li',

errorContainer: $('div.error'),
</code>```

i tried :

```<code> div.message{
background: transparent url(images\ad_next.png) no-repeat scroll left center;
padding-left: 17px; border:0px;
}
div.message ul, li { border:0px; }
div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid solid;
    border-width: 2px;
    padding: 5px;
}
</code>```

答:
take a look at class="error", if you're looking at styling an error message from Jörn Zaefferer validate plugin.</p>

```<code><label for="description" generated="true" class="error">error</label>
</code>```

ContentLicense: CC BY-SA 2.5

Title: jquery validate and error styles

Body:
how do i get rid of the borders in ul > li ?

i have :

    errorLabelContainer: $("ul", $('div.error')), wrapper: 'li',

errorContainer: $('div.error'),

i tried :

 div.message{
background: transparent url(images\ad_next.png) no-repeat scroll left center;
padding-left: 17px; border:0px;
}
div.message ul, li { border:0px; }
div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid solid;
    border-width: 2px;
    padding: 5px;
}

Body:
take a look at class="error", if you're looking at styling an error message from Jörn Zaefferer validate plugin.

<label for="description" generated="true" class="error">error</label>


问:
Using res.locals.user to show user object in all frontend views
I am trying to use res.locals.user to show the user object in the frontend.

Below you can see in my main app.js file the middleware I have created:

```<code>...
const passport = require('passport')

const auth = require('./routes/auth')
const index = require('./routes/index')

const app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger(process.env.LOG_ENV))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(express.static(path.join(__dirname, '/../public')))
app.use(cookieParser())

app.use(session({
  secret: 'super-mega-hyper-secret',
  resave: false,
  saveUninitialized: true,
}))
app.use(passport.initialize())
app.use(passport.session())
app.use((req, res, next) => { //This middleware checks the local user
  res.locals.user = req.user
  next()
})
...
</code>```

My passport file looks like the following:

```<code>const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const serviceAuth = require('../service/auth')

passport.serializeUser((user, done) => {
  done(null, user.id)
})

passport.deserializeUser(async(id, done) => {
  const user = await serviceAuth.findById(id)
  done(null, user)
})

// Sign in with username and Password
passport.use('local', new LocalStrategy({
  usernameField: 'username',
}, async(username, password, done) => {
  const user = await serviceAuth.signin(username, password)
  done(null, user)
}))

/**
 * Login Required middleware.
 */
exports.isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    res.locals.user = req.session.user
    return next()
  }
  res.redirect('/')
}
</code>```

However, I get the following error, when trying to display in my pug view the user object:

```<code>TypeError: /home/ubuntu/workspace/src/views/includes/_sidebar.pug:6
    4|          .user-panel
    5|                  .pull-left.info
  > 6|                          p= user.name
    7|                          p= user.role
    8|
    9|          // Sidebar Menu

Cannot read property 'name' of undefined
</code>```

Any suggestions why the user object is not available in the views AFTER I have properly logged in a user?

答:
EDIT[1]
You will need 2 entry views in your app:

A index for the case a user is authenticated

A loginPage for the case user is not authenticated

You can also handle these both cases in the main view(index) but you need to show/hide elements based on the presence of the currentUser. But i find having separate views more clean.

Step 1 - add your authentication middleware:

```<code>const isAuthenticated = require('./path/to/isAuthenticated');
app.use(isAuthenticated)
</code>```

Step 2 - render your app root / (is very important to do this after you registered the auth middleware so that your res.locals.user is populated):

```<code>app.get('/', function(req, res){
    if(res.locals && res.locals.user){
        res.render('index', { currentUser: res.locals.user });
    } else {
        res.render('loginPage');
    }
});
</code>```

Step 3 - Add the injected user to the window in index.pug:

```<code>if !!currentUser
    script.
        window.currentUser = !{currentUser}
</code>```

Body:
I am trying to use res.locals.user to show the user object in the frontend.

Below you can see in my main app.js file the middleware I have created:

...
const passport = require('passport')

const auth = require('./routes/auth')
const index = require('./routes/index')

const app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger(process.env.LOG_ENV))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(express.static(path.join(__dirname, '/../public')))
app.use(cookieParser())

app.use(session({
  secret: 'super-mega-hyper-secret',
  resave: false,
  saveUninitialized: true,
}))
app.use(passport.initialize())
app.use(passport.session())
app.use((req, res, next) => { //This middleware checks the local user
  res.locals.user = req.user
  next()
})
...

My passport file looks like the following:

const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const serviceAuth = require('../service/auth')

passport.serializeUser((user, done) => {
  done(null, user.id)
})

passport.deserializeUser(async(id, done) => {
  const user = await serviceAuth.findById(id)
  done(null, user)
})

// Sign in with username and Password
passport.use('local', new LocalStrategy({
  usernameField: 'username',
}, async(username, password, done) => {
  const user = await serviceAuth.signin(username, password)
  done(null, user)
}))

/**
 * Login Required middleware.
 */
exports.isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    res.locals.user = req.session.user
    return next()
  }
  res.redirect('/')
}

However, I get the following error, when trying to display in my pug view the user object:

TypeError: /home/ubuntu/workspace/src/views/includes/_sidebar.pug:6
    4|          .user-panel
    5|                  .pull-left.info
  > 6|                          p= user.name
    7|                          p= user.role
    8|
    9|          // Sidebar Menu

Cannot read property 'name' of undefined

Any suggestions why the user object is not available in the views AFTER I have properly logged in a user?

Body:
EDIT[1]
You will need 2 entry views in your app:

A index for the case a user is authenticated

A loginPage for the case user is not authenticated

You can also handle these both cases in the main view(index) but you need to show/hide elements based on the presence of the currentUser. But i find having separate views more clean.

Step 1 - add your authentication middleware:

const isAuthenticated = require('./path/to/isAuthenticated');
app.use(isAuthenticated)

Step 2 - render your app root / (is very important to do this after you registered the auth middleware so that your res.locals.user is populated):

app.get('/', function(req, res){
    if(res.locals && res.locals.user){
        res.render('index', { currentUser: res.locals.user });
    } else {
        res.render('loginPage');
    }
});

Step 3 - Add the injected user to the window in index.pug:

if !!currentUser
    script.
        window.currentUser = !{currentUser}


问:
How to make my h1 in the center of the image background without using absolute position?

/*General*/
@import url('https://fonts.googleapis.com/css?family=Oxygen');

.wrapper {
    max-width: 630px;
    margin: 0 auto;
}

/*Header*/
#header .navbar .navbar-header a {
    color: white;
    font-size: 25px;
    font-family: 'Oxygen', sans-serif;
}
#header .navbar-inverse {
    background-color: #2C3E50;
    border-color: #2C3E50;
}
#header .navbar {
    border-radius: 0;
}
#header .navbar-nav > li > a {
    color:white;
}
#header .navbar {
    margin-bottom: 0;
}
.nav.navbar-nav.navbar-right li a {
    color: white;
}

/*Content*/
#content .content-content .responsive-image {
    width: 100%;
    background-size: 100% 100%;
    z-index:0;
}
#content .content-content h1 {
    font-family: 'Open Sans', sans-serif;
    color: #2c3e50;
    font-size: 50px;
    font-weight: bold;
    z-index: 2;
    text-align: center;
}

/*Footer*/

/*Responsiveness*/

/*Desktop*/
@media screen and (min-width: 992px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Tablet*/
@media screen and (min-width: 768px) and (max-width: 991px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Mobile*/
@media screen and (max-width: 767px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Custom*/
@media screen and (max-width: 574px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');height:250px;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <title>Magic Gate</title>
    <link rel="stylesheet" type="text/css" href="Custom.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <div id="header">
        <nav class="navbar navbar-inverse">
            <div class="container-fluid">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    Magic Gate
                </div>
                <div class="collapse navbar-collapse" id="myNavbar">
                    <ul class="nav navbar-nav navbar-right">
                        <li>
                            Play
                        </li>
                        <li>
                            Log Out
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </div>
    <div id="content">
        <div class="content-content">
            <img src="https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg" class="responsive-image">
            <div class="wrapper">
                <h1>Welcome to Magic Gate</h1>
            </div>
        </div>
    </div>
    <div id="footer">
    </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html></code>```

I don't want to use absolute positioning because it disrupts the centering of objects/controls at the center of the banner. Can you help me with this one without also changing the img to a div background unless it will be responsive, since everything is responsive. My goal is to center the h1 text at the middle of the banner.

答:
You can use display:flex in css I am just posting an example to how to get it.

use below css part

```<code>.content-content {
  position:relative;
}

.wrapper {
    max-width: 630px;
    margin: 0 auto;
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    margin: 0 auto;
}
</code>```

Working fiddle

Body:
/*General*/
@import url('https://fonts.googleapis.com/css?family=Oxygen');

.wrapper {
    max-width: 630px;
    margin: 0 auto;
}

/*Header*/
#header .navbar .navbar-header a {
    color: white;
    font-size: 25px;
    font-family: 'Oxygen', sans-serif;
}
#header .navbar-inverse {
    background-color: #2C3E50;
    border-color: #2C3E50;
}
#header .navbar {
    border-radius: 0;
}
#header .navbar-nav > li > a {
    color:white;
}
#header .navbar {
    margin-bottom: 0;
}
.nav.navbar-nav.navbar-right li a {
    color: white;
}

/*Content*/
#content .content-content .responsive-image {
    width: 100%;
    background-size: 100% 100%;
    z-index:0;
}
#content .content-content h1 {
    font-family: 'Open Sans', sans-serif;
    color: #2c3e50;
    font-size: 50px;
    font-weight: bold;
    z-index: 2;
    text-align: center;
}

/*Footer*/

/*Responsiveness*/

/*Desktop*/
@media screen and (min-width: 992px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Tablet*/
@media screen and (min-width: 768px) and (max-width: 991px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Mobile*/
@media screen and (max-width: 767px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');
    }
}

/*Custom*/
@media screen and (max-width: 574px)
{
    #content .content-content .responsive-image {
        background-image: url('https://wallpaperscraft.com/image/board_black_line_texture_background_wood_55220_1920x1080.jpg');height:250px;
    }
}

<!DOCTYPE html>

    <title>Magic Gate</title>
    <link rel="stylesheet" type="text/css" href="Custom.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                    </button>
                    Magic Gate

                            Play

                            Log Out

Welcome to Magic Gate

I don't want to use absolute positioning because it disrupts the centering of objects/controls at the center of the banner. Can you help me with this one without also changing the img to a div background unless it will be responsive, since everything is responsive. My goal is to center the h1 text at the middle of the banner.

Body:
You can use display:flex in css I am just posting an example to how to get it.

use below css part

.content-content {
  position:relative;
}

.wrapper {
    max-width: 630px;
    margin: 0 auto;
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    margin: 0 auto;
}

Working fiddle


问:
Compare null value for datetime
I am storing date as string in sql table. If date is not passed then it will be null. Now I want to check whether date is null from the design page of asp.net. I am getting error of type cast. Any one is having idea how to overcome this?

```<code><%# ((DateTime)Eval("Date")).ToString("yyy-MM-dd hh:mm tt") %>">
</code>```

Here data is getting as string input.

Thanks

答:
Your result variable must be of nullable type (you can not assign null to DateTime). Use DateTime.TryParseExact(). If parsing fails, assign null, else assign the parsed value.

As DavidG noted, this is a hack, actually you should store dates as datetime or datetime2 SQL type!

```<code>using System.Globalization;

const string format = "yyyy-MM-dd hh:mm tt";
CultureInfo enUS = new CultureInfo("en-US");

string dateString = Eval("Date"); // e.g. "2017-11-13 02:16 PM"

DateTime? result; // final result or null stored here

DateTime parseResult;
if (DateTime.TryParseExact(dateString, format, enUS, DateTimeStyles.None, out parseResult)) {
    result = parseResult;
}
else {
    result = null;
}

// check for null before displaying
string display = result.HasValue ? result.Value.ToString(format) : "null";
</code>```

.net Fiddle

Title: Compare null value for datetime

Body:
I am storing date as string in sql table. If date is not passed then it will be null. Now I want to check whether date is null from the design page of asp.net. I am getting error of type cast. Any one is having idea how to overcome this?

<%# ((DateTime)Eval("Date")).ToString("yyy-MM-dd hh:mm tt") %>">

Here data is getting as string input.

Thanks

Body:
Your result variable must be of nullable type (you can not assign null to DateTime). Use DateTime.TryParseExact(). If parsing fails, assign null, else assign the parsed value.

As DavidG noted, this is a hack, actually you should store dates as datetime or datetime2 SQL type!

using System.Globalization;

const string format = "yyyy-MM-dd hh:mm tt";
CultureInfo enUS = new CultureInfo("en-US");

string dateString = Eval("Date"); // e.g. "2017-11-13 02:16 PM"

DateTime? result; // final result or null stored here

DateTime parseResult;
if (DateTime.TryParseExact(dateString, format, enUS, DateTimeStyles.None, out parseResult)) {
    result = parseResult;
}
else {
    result = null;
}

// check for null before displaying
string display = result.HasValue ? result.Value.ToString(format) : "null";

.net Fiddle


问:
self signed certificate in certificate chain node js?
code snippet for nodemailer and gmail

```<code>var transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,
        // service: 'Gmail',
        auth: {
            user: 'mail_id',
            pass: 'password'
        }

});
</code>```

Please help find the mistake for solving the issue - self signed certificate in certificate chain

答:
You want reconfigure your code like below

```<code>var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
</code>```

var transporter = nodemailer.createTransport(smtpTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,
        // service: 'Gmail',
        auth: {
            user: 'your mail_id',
            pass: 'Your password'
        },
        tls: {
            rejectUnauthorized: false
        }
    }));

ContentLicense: CC BY-SA 4.0

Body:
code snippet for nodemailer and gmail

var transporter = nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,
        // service: 'Gmail',
        auth: {
            user: 'mail_id',
            pass: 'password'
        }

});

Please help find the mistake for solving the issue - self signed certificate in certificate chain

Body:
You want reconfigure your code like below

var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');

var transporter = nodemailer.createTransport(smtpTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,
        // service: 'Gmail',
        auth: {
            user: 'your mail_id',
            pass: 'Your password'
        },
        tls: {
            rejectUnauthorized: false
        }
    }));


问:
Sql query to add Zero between string with character and digits
What will be the generic sql query to update id by adding zeros in id. containing alphabets as well as numbers? In between the character and digits 00 needs to be padded e.g QTX23675  should turn into QTX0023675

```<code>UPDATE Table
    SET QID = 'QTX0023675'
    WHERE QID='QTX23675';
</code>```

There are many records to update and i found query with leading zeros.
Tried with spliting the string.

答:
```<code>UPDATE TABLE SET QID= STUFF(QID,PATINDEX('%[0-9]%',QID),0,'00')
</code>```

Body:
What will be the generic sql query to update id by adding zeros in id. containing alphabets as well as numbers? In between the character and digits 00 needs to be padded e.g QTX23675  should turn into QTX0023675

UPDATE Table
    SET QID = 'QTX0023675'
    WHERE QID='QTX23675';

There are many records to update and i found query with leading zeros.
Tried with spliting the string.


问:
Confusion about realloc function
I read about dynamic memory allocation in C using this reference.

That document Say's :

realloc() should only be used for dynamically allocated memory. If the
  memory is not dynamically allocated, then behavior is undefined.

If we use realloc() something like this:

```<code>int main()
{
    int *ptr;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}
</code>```

According to that reference, this program is undefined because pointer ptr not allocated dynamically.

But, If I use something like:

```<code>int main()
{
    int *ptr = NULL;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}
</code>```

Is it also undefined behavior according to that reference?

I thing second case does not invoked undefined behaviour. Am I right?

答:
The first case has undefined behavior, and the second doesn't. In the first case, the value of ptr is indeterminate. So passing that value to realloc or any function, is undefined by itself.

On the other hand, since realloc has well defined behavior when passed a null pointer value (it's just like calling malloc)1, the second piece of code is perfectly legitimate (other than the fact you don't free anything).

1 7.22.3.5 The realloc function / p3

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size.

Title: Confusion about realloc function

Body:
I read about dynamic memory allocation in C using this reference.

That document Say's :

realloc() should only be used for dynamically allocated memory. If the
  memory is not dynamically allocated, then behavior is undefined.

If we use realloc() something like this:

int main()
{
    int *ptr;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}

According to that reference, this program is undefined because pointer ptr not allocated dynamically.

But, If I use something like:

int main()
{
    int *ptr = NULL;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}

Is it also undefined behavior according to that reference?

I thing second case does not invoked undefined behaviour. Am I right?


问:
Appending values to a google sheet
What am i doing wrong? I wanna append values to a sheet:

```<code>    String valueInputOption = "USER_ENTERED";
    String range = "1:1";
    String ranges = "Student!2:2";

    ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();

    AppendValuesResponse appendValuesResponse = service.spreadsheets()
            .values()
            .append(spreadsheetId, ranges, response)
            .setValueInputOption(valueInputOption)
            .execute();
</code>```

but i get exception:

```<code>{
 "code" : 400,
 "errors" : [ {
 "domain" : "global",
 "message" : "Request range[Student!2:2] does not match value's
  range[Student!A1:Z1]",
 "reason" : "badRequest"
} ],
"message" : "Request range[Student!2:2] does not match value's
range[Student!A1:Z1]",
"status" : "INVALID_ARGUMENT"
}
</code>```

i dont know why my range is wrong...

答: Check the Reading a single range and Appending values and it should demonstrate how to use the API properly. It seems the error stems from using 2 different ranges. Try to use only one to get rid of this error and work your way from there.</p>

Title: Appending values to a google sheet

Body:
What am i doing wrong? I wanna append values to a sheet:

    String valueInputOption = "USER_ENTERED";
    String range = "1:1";
    String ranges = "Student!2:2";

    ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();

    AppendValuesResponse appendValuesResponse = service.spreadsheets()
            .values()
            .append(spreadsheetId, ranges, response)
            .setValueInputOption(valueInputOption)
            .execute();

but i get exception:

{
 "code" : 400,
 "errors" : [ {
 "domain" : "global",
 "message" : "Request range[Student!2:2] does not match value's
  range[Student!A1:Z1]",
 "reason" : "badRequest"
} ],
"message" : "Request range[Student!2:2] does not match value's
range[Student!A1:Z1]",
"status" : "INVALID_ARGUMENT"
}

i dont know why my range is wrong...


问:
Disabling the fullscreen editing view for soft keyboard input in landscape?
On Android devices that use soft keyboards, I want to prevent the fullscreen keyboard editing view (shown below) from appearing when in landscape mode (i.e. I want to see only the soft keyboard itself and my view behind it).

I assume this can be achieved using the setExtractViewShown(false) method on InputMethodService, but I am unable to access the default instance of this and do not want to implement a custom input method.

Edited to add: the view to which input is going is not a TextView (it's a View with a custom InputConnection implementation), so android:imeOptions="flagNoExtractUi" won't work here.

答:
I finally answered my own question:

The extract UI (i.e. the fullscreen editing mode) can be disabled at the point at which the input connection is hooked up:

```<code>@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {

    outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI;

    // etc.
}
</code>```

Body:
I finally answered my own question:

The extract UI (i.e. the fullscreen editing mode) can be disabled at the point at which the input connection is hooked up:

@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {

    outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI;

    // etc.
}


问:
IOS Swift how can hide the space of an Image inside a TableView
I have a tableView that contains a UIImageView and if the Image has a URL then the image displays and if not then no Image is displayed. The issue I have is that if there is no Image then a big blank spot occurs in the TableView as if there was an image. Is there a way to reduce the blank spot or hide it (Images below) ? The image is the big UIImageView in the center . This is my code when it comes to the Images

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyFeed", for: indexPath) as! MyFeed

    if stream_image_string[indexPath.row].characters.count > 2  {
        let strCellImageURL = self.stream_image_string[indexPath.row]
        let imgURL: NSURL = NSURL(string: strCellImageURL)!
        let request:NSURLRequest =  NSURLRequest(url: imgURL as URL)
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        let task = session.dataTask(with: request as URLRequest,    completionHandler: {(data, response, error) in
            DispatchQueue.main.async(execute: { () -> Void in

                cell.post_image.image = UIImage(data: data!)

            })
        });
        task.resume()
    } else {
    cell.post_image!.isHidden = true
        cell.post_image!.image = nil
    }

    return cell
}
</code>```

Essentially if the String coming back has 2 or more characters then it's a valid URL and the image is downloaded; the part that I am focused on is the else statement and this code

```<code>else {
        cell.post_image!.isHidden = true
            cell.post_image!.image = nil
        }
</code>```

So obviously if it goes in the else statement then there is no image and I set the Image to null or nil then I try to hide the extra white space by setting the Image to hidden however that does not work . Any idea on how I can hide the white space ? I have also been reading this question but it does not work iOS swift imageView cannot be hidden in TableViewCell

答:
I experienced the same problem myself. You need to create 2 cells for this. Like this:

```<code>override func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (stream_image_string[indexPath.row] == "")
     {
       let cell = tableView.dequeueReusableCell (withIdentifier: "noImageMyFeed", for: indexPath) as! noImageMyFeed
       return cell

     }
    else
     {
       let cell = tableView.dequeueReusableCell (withIdentifier: "MyFeed", for: indexPath) as! MyFeed
       return cell
     }
    }
</code>```

this video will help you in detail : https://www.youtube.com/watch?v=FAxtWtqeMIM

adapt the video to its own content, create a cell from scratch by simply deleting the image part

Body:
I have a tableView that contains a UIImageView and if the Image has a URL then the image displays and if not then no Image is displayed. The issue I have is that if there is no Image then a big blank spot occurs in the TableView as if there was an image. Is there a way to reduce the blank spot or hide it (Images below) ? The image is the big UIImageView in the center . This is my code when it comes to the Images

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyFeed", for: indexPath) as! MyFeed

    if stream_image_string[indexPath.row].characters.count > 2  {
        let strCellImageURL = self.stream_image_string[indexPath.row]
        let imgURL: NSURL = NSURL(string: strCellImageURL)!
        let request:NSURLRequest =  NSURLRequest(url: imgURL as URL)
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        let task = session.dataTask(with: request as URLRequest,    completionHandler: {(data, response, error) in
            DispatchQueue.main.async(execute: { () -> Void in

                cell.post_image.image = UIImage(data: data!)

            })
        });
        task.resume()
    } else {
    cell.post_image!.isHidden = true
        cell.post_image!.image = nil
    }

    return cell
}

Essentially if the String coming back has 2 or more characters then it's a valid URL and the image is downloaded; the part that I am focused on is the else statement and this code

else {
        cell.post_image!.isHidden = true
            cell.post_image!.image = nil
        }

So obviously if it goes in the else statement then there is no image and I set the Image to null or nil then I try to hide the extra white space by setting the Image to hidden however that does not work . Any idea on how I can hide the white space ? I have also been reading this question but it does not work iOS swift imageView cannot be hidden in TableViewCell

Body:
I experienced the same problem myself. You need to create 2 cells for this. Like this:

override func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (stream_image_string[indexPath.row] == "")
     {
       let cell = tableView.dequeueReusableCell (withIdentifier: "noImageMyFeed", for: indexPath) as! noImageMyFeed
       return cell

     }
    else
     {
       let cell = tableView.dequeueReusableCell (withIdentifier: "MyFeed", for: indexPath) as! MyFeed
       return cell
     }
    }

this video will help you in detail : https://www.youtube.com/watch?v=FAxtWtqeMIM

adapt the video to its own content, create a cell from scratch by simply deleting the image part


问:
Android SOAP WCF Service Call - Partial response
Calling a .NET 4.0 Soap based WCF Service. There is no exception during the call and the code is working fine.
 The problem is that the soap resposne only contains the starting xml tag and its end tag but no body.
 Maybe there is some issue parsing the XML or do we need a REST Based WCF Service for communication. Also the XML returned is pretty huge(~50-150kb)

Here is that code that I am using:

```<code>SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapObject param = new SoapObject(NAMESPACE, METHOD_NAME);

request.addProperty("CompanyID",CompanyId);
request.addProperty(METHOD_NAME, param);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
        SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);

androidHttpTransport.call(SOAP_ACTION,envelope);
response = (SoapObject) envelope.getResponse(); //Only starting xml tag is returned
</code>```

the response object when seen in debugger contains the usual SoapObject properties and drilling down contains an value object inside SoapPrimitive "". But the web service is returning lots of data inside this element. Where is that?

UPDATE: On returning a small xml string the android app using KSOAP is getting the complete xml and able to parse it using the above code.

EDIT: WCF Web Service Method

```<code>public string GetOffersString(string companyID)
        {
            DataTable dtGetTopOffers;
            dtGetTopOffers = SprocWrapper.PROC_GETTOPOFFERS(companyID);
            dtGetTopOffers.TableName = "GETTOPOFFERS";
            XElement xGetTopOffers = Common.SerializeDataTable(dtGetTopOffers);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xGetTopOffers.Value);
            return doc.InnerXml;
}
</code>```

答:
Parameter name was typed uncorrectly. Changing the following line

```<code>request.addProperty("CompanyID",CompanyId);
</code>```

To

```<code>request.addProperty("companyID",CompanyId);
</code>```

fixed the issue.

Body:
Calling a .NET 4.0 Soap based WCF Service. There is no exception during the call and the code is working fine.
 The problem is that the soap resposne only contains the starting xml tag and its end tag but no body.
 Maybe there is some issue parsing the XML or do we need a REST Based WCF Service for communication. Also the XML returned is pretty huge(~50-150kb)

Here is that code that I am using:

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapObject param = new SoapObject(NAMESPACE, METHOD_NAME);

request.addProperty("CompanyID",CompanyId);
request.addProperty(METHOD_NAME, param);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
        SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);

androidHttpTransport.call(SOAP_ACTION,envelope);
response = (SoapObject) envelope.getResponse(); //Only starting xml tag is returned

the response object when seen in debugger contains the usual SoapObject properties and drilling down contains an value object inside SoapPrimitive "". But the web service is returning lots of data inside this element. Where is that?

UPDATE: On returning a small xml string the android app using KSOAP is getting the complete xml and able to parse it using the above code.

EDIT: WCF Web Service Method

public string GetOffersString(string companyID)
        {
            DataTable dtGetTopOffers;
            dtGetTopOffers = SprocWrapper.PROC_GETTOPOFFERS(companyID);
            dtGetTopOffers.TableName = "GETTOPOFFERS";
            XElement xGetTopOffers = Common.SerializeDataTable(dtGetTopOffers);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xGetTopOffers.Value);
            return doc.InnerXml;
}

Body:
Parameter name was typed uncorrectly. Changing the following line

request.addProperty("CompanyID",CompanyId);

To

request.addProperty("companyID",CompanyId);

fixed the issue.


问:
ToggleButton image does not maintain aspect ratio
The two toggle buttons don't maintain aspect ratio. How can I make it a square? It shouldn't fill the width but just wrap it's content.

```<code>            <LinearLayout
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginTop="24dp"
                android:orientation="horizontal">

                <ToggleButton
                    android:id="@+id/btn1"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:textOff=""
                    android:scaleType="centerCrop"
                    android:textOn=""
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector"
                    />

                <ToggleButton
                    android:id="@+id/btn2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:scaleType="centerCrop"
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector" />
            </LinearLayout>
</code>```

feedback_btn_selector

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_pressed="true" android:drawable="@drawable/btn_average" />
    <item android:state_pressed="true" android:drawable="@drawable/btn_average"/>
    <item android:state_checked="true" android:drawable="@drawable/btn_average"/>
    <item android:drawable="@drawable/btn_average_selected"/>
</selector>
</code>```

drawable-xhdpi:

答:
Correct answer:</p>

```<code><LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:orientation="horizontal"
                    android:gravity="center_horizontal">

        <ToggleButton
            android:id="@+id/btn1"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:textOff=""
            android:scaleType="centerCrop"
            android:textOn=""
            android:layout_margin="8dp"
            android:background="@drawable/feedback_btn_selector"
            />

        <ToggleButton
            android:id="@+id/btn2"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:scaleType="centerCrop"
            android:layout_margin="8dp"
            android:background="@drawable/feedback_btn_selector" />
    </LinearLayout>
</code>```

Body:
The two toggle buttons don't maintain aspect ratio. How can I make it a square? It shouldn't fill the width but just wrap it's content.

            <LinearLayout
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginTop="24dp"
                android:orientation="horizontal">

                <ToggleButton
                    android:id="@+id/btn1"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:textOff=""
                    android:scaleType="centerCrop"
                    android:textOn=""
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector"
                    />

                <ToggleButton
                    android:id="@+id/btn2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:scaleType="centerCrop"
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector" />
            </LinearLayout>

feedback_btn_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_pressed="true" android:drawable="@drawable/btn_average" />
    <item android:state_pressed="true" android:drawable="@drawable/btn_average"/>
    <item android:state_checked="true" android:drawable="@drawable/btn_average"/>
    <item android:drawable="@drawable/btn_average_selected"/>
</selector>

drawable-xhdpi:

Body:
Correct answer:

<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:orientation="horizontal"
                    android:gravity="center_horizontal">

        <ToggleButton
            android:id="@+id/btn1"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:textOff=""
            android:scaleType="centerCrop"
            android:textOn=""
            android:layout_margin="8dp"
            android:background="@drawable/feedback_btn_selector"
            />

        <ToggleButton
            android:id="@+id/btn2"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:scaleType="centerCrop"
            android:layout_margin="8dp"
            android:background="@drawable/feedback_btn_selector" />
    </LinearLayout>


问:
get modified date of subfolder within folder
There are about 1000 share folders, and I need to find out when they are last modified.
So, these share folders contain subfolder and user can modify data in those subfolder.

I have a script that can get the last modified date of parent folder but it is not giving the correct data.

```<code>$CSVFilePath = Get-Content "C:\RA\main.txt"
$outputsss = "C:\RA\output.csv"
foreach ($fileName in $CSVFilePath) {
    echo $fileName;
    if (Test-Path $fileName) {
        $d = Get-ItemProperty -Path $fileName -Name LastWriteTime
        $times = $fileName + " - " + $d.LastWriteTime
        $times
    }
    $times | Out-File $outputsss -Encoding utf8 -Append
    #Get-Content $filename | Out-File $outputsss -Encoding utf8 -Append
}
</code>```

Is there any way I can get the last modified datetime of share location?

答:
I tried multiple times and below is the script that helped me. I need to verify it because it is still running.

```<code>$CSVFilePath = Get-Content "C:\RA\main.txt"
$outputsss = "C:\RA\output.csv"
foreach($fileName in $CSVFilePath)
{
echo $fileName;
If (Test-Path $fileName) {

$latest = Get-ChildItem -Recurse  -Path $fileName | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.LastWriteTime

    #$d = Get-ItemProperty -path $fileName -Name LastWriteTime
    $times = $fileName + " - " + $latest.LastWriteTime
$times
    }
$times |Out-File $outputsss -Encoding utf8 -append

}
</code>```

I hope it worth for someone.

Body:
There are about 1000 share folders, and I need to find out when they are last modified.
So, these share folders contain subfolder and user can modify data in those subfolder.

I have a script that can get the last modified date of parent folder but it is not giving the correct data.

$CSVFilePath = Get-Content "C:\RA\main.txt"
$outputsss = "C:\RA\output.csv"
foreach ($fileName in $CSVFilePath) {
    echo $fileName;
    if (Test-Path $fileName) {
        $d = Get-ItemProperty -Path $fileName -Name LastWriteTime
        $times = $fileName + " - " + $d.LastWriteTime
        $times
    }
    $times | Out-File $outputsss -Encoding utf8 -Append
    #Get-Content $filename | Out-File $outputsss -Encoding utf8 -Append
}

Is there any way I can get the last modified datetime of share location?

Body:
I tried multiple times and below is the script that helped me. I need to verify it because it is still running.

$CSVFilePath = Get-Content "C:\RA\main.txt"
$outputsss = "C:\RA\output.csv"
foreach($fileName in $CSVFilePath)
{
echo $fileName;
If (Test-Path $fileName) {

$latest = Get-ChildItem -Recurse  -Path $fileName | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.LastWriteTime

    #$d = Get-ItemProperty -path $fileName -Name LastWriteTime
    $times = $fileName + " - " + $latest.LastWriteTime
$times
    }
$times |Out-File $outputsss -Encoding utf8 -append

}

I hope it worth for someone.


问:
Hudson projects RSS feed, build parameters
Is there any way to have Hudson include, in the RSS feed for a project set up in Hudson, the name and value of any build parameters used in a build?

Thanks,

Tom

答:
Sure but they would need to setup their own namespace.  a number of rss feeds have extended past generic RSS by including namespaces.  Take a look at Techcrunch's feedburner feed <rss> node.

<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

Here's an element that isn't part of the RSS spec but linked to the feedburner namespace.  <feedburner:browserFriendly>

So hudson could create a :hudeson namespace and use a node <hudson:buildparams>.

The problem is that no RSS reader that I know of will parse and display the elements in the hudson namespace.  So you would have to pretty much build your own.


问:
rx-java2 Schedulers.io() steel invokes method from mainThread
I'm trying to retrieve data from database using room with Rx way.
This is how I'm trying to do that

```<code>override fun onStart() {
    super.onStart()
    disposable.add(presenter.getAllBooks()
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe({
                 println(it.size())
              }))
}
</code>```

this is getAllBooks() method inside presenter

```<code>fun getAllBooks() : Flowable<List<Book>> {
    val isMainThread = Looper.myLooper() == Looper.getMainLooper()
    if (!isMainThread) {
        updateBooks()
        return db.bookDao().allBooks
    }
    return Flowable.empty()
}
</code>```

Here isMainThread variable is always true,
I have also tried observeOn(Shcedulers.io()), but same problem.

答:
This is a common misunderstanding with RxJava. getAllBooks executes its content before RxJava gets into the picture.

```<code>fun method() : Flowable<String> {
   println("method()")
   return Flowable.just("hello")
}

println("Preparing...")
val f = method();
println("Subscribing...")
f.subscribe({ println(it) })
</code>```

It will print

```<code>Preparing...
method()
Subscribing...
hello
</code>```

You have to wrap your action into a Flowable to make it happen when a subscription happens:

```<code>disposable.add(
    Flowable.defer(() -> presenter.getAllBooks())  // <----------------------
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
               println(it.size())
            })
)
</code>```

Body:
I'm trying to retrieve data from database using room with Rx way.
This is how I'm trying to do that

override fun onStart() {
    super.onStart()
    disposable.add(presenter.getAllBooks()
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe({
                 println(it.size())
              }))
}

this is getAllBooks() method inside presenter

fun getAllBooks() : Flowable<List<Book>> {
    val isMainThread = Looper.myLooper() == Looper.getMainLooper()
    if (!isMainThread) {
        updateBooks()
        return db.bookDao().allBooks
    }
    return Flowable.empty()
}

Here isMainThread variable is always true,
I have also tried observeOn(Shcedulers.io()), but same problem.

Body:
This is a common misunderstanding with RxJava. getAllBooks executes its content before RxJava gets into the picture.

fun method() : Flowable<String> {
   println("method()")
   return Flowable.just("hello")
}

println("Preparing...")
val f = method();
println("Subscribing...")
f.subscribe({ println(it) })

It will print

Preparing...
method()
Subscribing...
hello

You have to wrap your action into a Flowable to make it happen when a subscription happens:

disposable.add(
    Flowable.defer(() -> presenter.getAllBooks())  // <----------------------
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
               println(it.size())
            })
)


问:
ng-bootstrap modal TypeError in promise
I am using @ng-bootstrap in angular 4 app.

I am able to open a modal instance and was able to pass data to modal.
on modal close i was able to get results from modal.

The issue i am facing is i tried to assign the result with some existing variable inside the parent component where the modal is used.
But it's showing below error.

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
  TypeError: Cannot read property 'push' of undefined

Below is the code i have written to show modal

```<code>import { Component, OnInit, Input } from '@angular/core';
import { AdminService } from "../admin.service";
import { NgbModal, ModalDismissReasons, NgbAlertConfig } from '@ng-bootstrap/ng-bootstrap';
import { NgAddModalComponent } from './add-modal.component';

@Component({
  selector: 'app-name-list',
  templateUrl: './name-list.component.html',
  styleUrls: ['./name-list.component.css'],
  providers: [NgbAlertConfig]
})
export class NameListComponent implements OnInit {
  errorMessage: string;
  name: string;
  nameList: [];

  constructor(private adminService: AdminService, private modalService: NgbModal) {}

    ngOnInit() {
        this.adminService.getNamelist()
        .subscribe(res => {
            this.nameList = res.name; //["john", "smith", "todd"]
        },
        error => this.errorMessage = <any>error);
    }

   onAddClick() {
        const modalRef = this.modalService.open(NgAddModalComponent, {size: 'lg'});//To open Modal
        modalRef.componentInstance.name = this.name;//To send data to Modal
        modalRef.result.then((result) => {//To subscribe data from Modal
        this.nameList.push(result.name); //Getting error on this line
    });
  }
}
</code>```

Any Help will be appreciated!!!

答:
You declaration for namelist is wrong.

You need to declare it like this:
nameList = [];

not like this:
nameList: [];

Title: ng-bootstrap modal TypeError in promise

Body:
I am using @ng-bootstrap in angular 4 app.

I am able to open a modal instance and was able to pass data to modal.
on modal close i was able to get results from modal.

The issue i am facing is i tried to assign the result with some existing variable inside the parent component where the modal is used.
But it's showing below error.

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
  TypeError: Cannot read property 'push' of undefined

Below is the code i have written to show modal

import { Component, OnInit, Input } from '@angular/core';
import { AdminService } from "../admin.service";
import { NgbModal, ModalDismissReasons, NgbAlertConfig } from '@ng-bootstrap/ng-bootstrap';
import { NgAddModalComponent } from './add-modal.component';

@Component({
  selector: 'app-name-list',
  templateUrl: './name-list.component.html',
  styleUrls: ['./name-list.component.css'],
  providers: [NgbAlertConfig]
})
export class NameListComponent implements OnInit {
  errorMessage: string;
  name: string;
  nameList: [];

  constructor(private adminService: AdminService, private modalService: NgbModal) {}

    ngOnInit() {
        this.adminService.getNamelist()
        .subscribe(res => {
            this.nameList = res.name; //["john", "smith", "todd"]
        },
        error => this.errorMessage = <any>error);
    }

   onAddClick() {
        const modalRef = this.modalService.open(NgAddModalComponent, {size: 'lg'});//To open Modal
        modalRef.componentInstance.name = this.name;//To send data to Modal
        modalRef.result.then((result) => {//To subscribe data from Modal
        this.nameList.push(result.name); //Getting error on this line
    });
  }
}

Any Help will be appreciated!!!


问:
SubscribeOn(Schedulers.io()) + blockingGet() = UI skipped frames
I wrote a RxJava implementation of a TokenManager for a remote API (that I'm consuming via Retrofit).  However I ran into a snag where a method call with blockingGet() is resulting in skipped UI frames even though I subscribeOn(Schedulers.io())

Basically, I've included getToken() as a parameter in the API search() call method.  If the token exists, it will be provided, if not, it will be fetched via the API token() call. <-- This is the problem.  When this method gets called, it's resulting in skipped frames in the UI (progressbar freezes momentarily + respective logcat Choreographer skipped frames!! message)

Looking for suggestions on how to remedy the skipped frames, or suggestions on how to better implement this code.

ListFetcher (class that calls TokenManager getToken() )

```<code>public Single<List<Business>> getList(final String latitude, final String longitude) {
    return api
            .search(
                    tokenManager.getToken(),  // <-- Here's the TokenManager reference
                    AppSettings.SEARCH_TERM,
                    latitude,
                    longitude,
                    AppSettings.SEARCH_RADIUS,
                    Yelp3Api.SEARCH_LIMIT)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .flatMap(searchResponse -> {
                if (searchResponse.getBusinesses().size() < searchResponse.getTotal()) {
                    return subsequentSearchCalls(searchResponse, latitude, longitude)
                            .map(businesses -> {
                                List<Business> list = new ArrayList<>();
                                list.addAll(searchResponse.getBusinesses());
                                list.addAll(businesses);
                                return list;
                            });
                } else {
                    return Single.just(searchResponse.getBusinesses());
                }
            });
}
</code>```

TokenManager getToken()

```<code>public synchronized String getToken() {
    final String cachedToken = sharedPrefs.getString(tokenKey, "null");
    if (cachedToken.equals("null")) {
        String tokenString = api
                .token(
                        Yelp3Api.GrantType.CLIENT_CREDENTIALS,
                        BuildConfig.YELPFUSION_CLIENT_ID,
                        BuildConfig.YELPFUSION_CLIENT_SECRET)
                .subscribeOn(Schedulers.io())
                .doOnSuccess(this::setSharedPrefToken)
                .map(tokenResponse -> String.format(AUTH_FORMAT, tokenResponse.getAccessToken()))
                .blockingGet();
        return tokenString;
    } else {
        return String.format(AUTH_FORMAT, cachedToken);
    }
}
</code>```

Yelp3Api (Retrofit interface)

```<code>@FormUrlEncoded
@POST("oauth2/token")
Single<TokenResponse> token(
        @Field("grant_type") String grantType,
        @Field("client_id") String clientId,
        @Field("client_secret") String clientSecret
);

@GET("v3/businesses/search")
Single<SearchResponse> search(
        @Header("Authorization") String authorization,
        @Query("term") String term,
        @Query("latitude") String latitude,
        @Query("longitude") String longitude,
        @Query("radius") int radius,
        @Query("limit") int limit
);
</code>```

答:
When you call getToken() it is not executed lazily. It executes blocking call on your UI thread.
To fix it, wrap getToken in Single.fromCallable and flatMap it above api.search()

Hope this clears out what is actually happening

Body:
I wrote a RxJava implementation of a TokenManager for a remote API (that I'm consuming via Retrofit).  However I ran into a snag where a method call with blockingGet() is resulting in skipped UI frames even though I subscribeOn(Schedulers.io())

Basically, I've included getToken() as a parameter in the API search() call method.  If the token exists, it will be provided, if not, it will be fetched via the API token() call. <-- This is the problem.  When this method gets called, it's resulting in skipped frames in the UI (progressbar freezes momentarily + respective logcat Choreographer skipped frames!! message)

Looking for suggestions on how to remedy the skipped frames, or suggestions on how to better implement this code.

ListFetcher (class that calls TokenManager getToken() )

public Single<List<Business>> getList(final String latitude, final String longitude) {
    return api
            .search(
                    tokenManager.getToken(),  // <-- Here's the TokenManager reference
                    AppSettings.SEARCH_TERM,
                    latitude,
                    longitude,
                    AppSettings.SEARCH_RADIUS,
                    Yelp3Api.SEARCH_LIMIT)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .flatMap(searchResponse -> {
                if (searchResponse.getBusinesses().size() < searchResponse.getTotal()) {
                    return subsequentSearchCalls(searchResponse, latitude, longitude)
                            .map(businesses -> {
                                List<Business> list = new ArrayList<>();
                                list.addAll(searchResponse.getBusinesses());
                                list.addAll(businesses);
                                return list;
                            });
                } else {
                    return Single.just(searchResponse.getBusinesses());
                }
            });
}

TokenManager getToken()

public synchronized String getToken() {
    final String cachedToken = sharedPrefs.getString(tokenKey, "null");
    if (cachedToken.equals("null")) {
        String tokenString = api
                .token(
                        Yelp3Api.GrantType.CLIENT_CREDENTIALS,
                        BuildConfig.YELPFUSION_CLIENT_ID,
                        BuildConfig.YELPFUSION_CLIENT_SECRET)
                .subscribeOn(Schedulers.io())
                .doOnSuccess(this::setSharedPrefToken)
                .map(tokenResponse -> String.format(AUTH_FORMAT, tokenResponse.getAccessToken()))
                .blockingGet();
        return tokenString;
    } else {
        return String.format(AUTH_FORMAT, cachedToken);
    }
}

Yelp3Api (Retrofit interface)

@FormUrlEncoded
@POST("oauth2/token")
Single<TokenResponse> token(
        @Field("grant_type") String grantType,
        @Field("client_id") String clientId,
        @Field("client_secret") String clientSecret
);

@GET("v3/businesses/search")
Single<SearchResponse> search(
        @Header("Authorization") String authorization,
        @Query("term") String term,
        @Query("latitude") String latitude,
        @Query("longitude") String longitude,
        @Query("radius") int radius,
        @Query("limit") int limit
);


问:
C++ Variadic parameters with out first one
it's any possibility to use a variadic parameters with out specification of first one?

For example:

This code is perfectly fine:

```<code>void something(const char* layoutAndButton, ...)
{
    va_list ap;
    va_start(ap, layoutAndButton);
    std::map<std::string, std::string> data;
    while (*layoutAndButton != '\0') {
        std::string layout = va_arg(ap, const char*);
        ++layoutAndButton;
        std::string button = va_arg(ap, const char*);
        ++layoutAndButton;
        data.insert(std::make_pair(layout, button));
    }
    for (auto const& x : data)
    {
        std::cout << x.first << ':' << x.second << std::endl;
    }
    va_end(ap);
}
</code>```

But I would like to have the something function in this way:

```<code>void something(const char*...)
</code>```

It's any possibility to do something like that? and after that to access the members? if yes, how?

Thanks

答:
Here is how you would use a C++ variadic template. You can call something() with any even number of const char* arguments e.g. something("k1", "v1", "k2", "v2"). It will build a map<string,string> from these arguments by recursively calling the buildMap() function, and then call useMap() to do whatever actual work you want done with the map.

```<code>void buildMap(std::map<std::string, std::string>& data)
{
}

template<typename... Args>
void buildMap(
    std::map<std::string, std::string>& data,
    const char* layout,
    const char* button,
    Args... args)
{
    data.insert(std::make_pair(layout, button));
    buildMap(data, args...);
}

void useMap(std::map<std::string, std::string>& data)
{
    // TODO: do something here
}

template<typename... Args>
void something(Args... args) {
    std::map<std::string, std::string> data;
    buildMap(data, args...);
    useMap(data);
}
</code>```

Body:
it's any possibility to use a variadic parameters with out specification of first one?

For example:

This code is perfectly fine:

void something(const char* layoutAndButton, ...)
{
    va_list ap;
    va_start(ap, layoutAndButton);
    std::map<std::string, std::string> data;
    while (*layoutAndButton != '\0') {
        std::string layout = va_arg(ap, const char*);
        ++layoutAndButton;
        std::string button = va_arg(ap, const char*);
        ++layoutAndButton;
        data.insert(std::make_pair(layout, button));
    }
    for (auto const& x : data)
    {
        std::cout << x.first << ':' << x.second << std::endl;
    }
    va_end(ap);
}

But I would like to have the something function in this way:

void something(const char*...)

It's any possibility to do something like that? and after that to access the members? if yes, how?

Thanks

Body:
Here is how you would use a C++ variadic template. You can call something() with any even number of const char* arguments e.g. something("k1", "v1", "k2", "v2"). It will build a map<string,string> from these arguments by recursively calling the buildMap() function, and then call useMap() to do whatever actual work you want done with the map.

void buildMap(std::map<std::string, std::string>& data)
{
}

template<typename... Args>
void buildMap(
    std::map<std::string, std::string>& data,
    const char* layout,
    const char* button,
    Args... args)
{
    data.insert(std::make_pair(layout, button));
    buildMap(data, args...);
}

void useMap(std::map<std::string, std::string>& data)
{
    // TODO: do something here
}

template<typename... Args>
void something(Args... args) {
    std::map<std::string, std::string> data;
    buildMap(data, args...);
    useMap(data);
}


问:
Docker port 80:80 127.0.0.1
Im having a huge issue and I can't get round it

Basically i went through the Laravel installation and installed homestead 7 and im using virtual box... vagrant

Now before this I'm using docker to run other application through it... which worked and it looks like something i've done is using the same port so I now cant use docker on that port

Cannot start service website: driver failed programming external connectivity on endpoint distinctly_website_1 (edc81f653cb3ac8c2af9b7ce070d0a0ccbb3ec255af452338ff4677ce99b156a): Error starting userland proxy: Bind for 0.0.0.0:80: unexpected error (Failure EADDRINUSE)
  ERROR: Encountered errors while bringing up the project.

I just need some help with removing this conflict with the port so I can run my docker applications. I dont care about anything than docker

答:
You can determine which process is listening on the port by running the command

```<code>netstat -nlp | grep 80
</code>```

Once you find that program, you can kill it by running

```<code>kill <pid>
</code>```

Title: Docker port 80:80 127.0.0.1

Body:
You can determine which process is listening on the port by running the command

netstat -nlp | grep 80

Once you find that program, you can kill it by running

kill <pid>


问:
Logistic model solution in r
I have fit a logistic model and I want to know the value of x when y=0.5.

```<code>library("faraway")

data = read.table("SBay.txt", header=T)
female = subset(data,sex==2)

amat = c(0,1)
mod1 = glm(amat[maturity]~age,family=binomial,data=female)
summary(mod1)
(len_50 = (log(1)-mod1$coef[1]) /mod1$coef[2])

(plot(female$age,amat[female$maturity],pch=1,col=2))
s = seq(0, 20, 0.1)
lines(s,ilogit(mod1$coef[1]+mod1$coef[2]*s),col=2,lty=2,lwd=2)
</code>```

I google the answer and get:

```<code>F1 = ilogit(mod1$coef[1]+mod1$coef[2])
F2 = 0.5
solve(F1,F2)
</code>```

I got the answer equal to 9.931613, however, it doesn't match the graph I've plot. SO I think there might be something wrong with my code.
Here are my graph, it seem the answer is between 2 and 3.

https://imgur.com/a/Dn3Rk

答:
What you need is the predict function followed by an ifelse expression:

```<code># Logistic Regression Classifier
mod1 = glm( amat[maturity]~age,family=binomial,data=female)

# Probabilities
prob_pred = predict( mod1, type = "response", newdata = female) # probability outcomes

# Outcomes (True/False)
y_pred = ifelse( prob_pred > 0.5, 1, 0)  # NOTE: the 0.5, it filters outcomes > 0.5 probability
</code>```

Title: Logistic model solution in r

Body:
I have fit a logistic model and I want to know the value of x when y=0.5.

library("faraway")

data = read.table("SBay.txt", header=T)
female = subset(data,sex==2)

amat = c(0,1)
mod1 = glm(amat[maturity]~age,family=binomial,data=female)
summary(mod1)
(len_50 = (log(1)-mod1$coef[1]) /mod1$coef[2])

(plot(female$age,amat[female$maturity],pch=1,col=2))
s = seq(0, 20, 0.1)
lines(s,ilogit(mod1$coef[1]+mod1$coef[2]*s),col=2,lty=2,lwd=2)

I google the answer and get:

F1 = ilogit(mod1$coef[1]+mod1$coef[2])
F2 = 0.5
solve(F1,F2)

I got the answer equal to 9.931613, however, it doesn't match the graph I've plot. SO I think there might be something wrong with my code.
Here are my graph, it seem the answer is between 2 and 3.

https://imgur.com/a/Dn3Rk

Body:
What you need is the predict function followed by an ifelse expression:

# Logistic Regression Classifier
mod1 = glm( amat[maturity]~age,family=binomial,data=female)

# Probabilities
prob_pred = predict( mod1, type = "response", newdata = female) # probability outcomes

# Outcomes (True/False)
y_pred = ifelse( prob_pred > 0.5, 1, 0)  # NOTE: the 0.5, it filters outcomes > 0.5 probability


问:
How to set Spinner default value to null?
I'm trying to get a Spinner to load up with no selected value. Once the user selects a value it then takes them to another page.

This is proving to be a problem because at present, the page just loads straight away before the user gets a choice to choose.

My spinner class is set up the same way as Google's: http://developer.android.com/resources/tutorials/views/hello-spinner.html

So basically, is it possible have a spinner that loads with nothing selected because at present, it loads the first item in my string array.

答:
is it possible have a spinner that loads with nothing selected

Only if there is no data. If you have 1+ items in the SpinnerAdapter, the Spinner will always have a selection.

Spinners are not designed to be command widgets. Users will not expect a selection in a Spinner to start an activity. Please consider using something else, like a ListView or GridView, instead of a Spinner.

EDIT

BTW, I forgot to mention -- you can always put an extra entry in your adapter that represents "no selection", and make it the initial selected item in the Spinner.


问:
Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug when i use AdCash monatisation (Android)
When I include AdCash library (compile 'com.adcash:adcash-sdk-lib:2.4.0'), I have this error:

```<code>Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.
java.io.IOException: Can't write [C:\NovaDevelopment\xxx\app\build\intermediates\multi-dex\debug\componentClasses.jar] (Can't read [C:\Program Files\Android\Android Studio\gradle\m2repository\org\jetbrains\annotations\13.0\annotations-13.0.jar(;;;;;;**.class)] (Duplicate zip entry [annotations-13.0.jar:org/intellij/lang/annotations/Flow.class]))
</code>```

But without this library, everything works as expected.

My build.gradle file:

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
compileSdkVersion 26
buildToolsVersion "27.0.0"

defaultConfig {
    applicationId "com.xxx"
    minSdkVersion 16
    targetSdkVersion 22
    versionCode 23
    versionName "2.8"
    multiDexEnabled true
}
buildTypes {
    release {
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

dexOptions {
    javaMaxHeapSize "4g"
}

packagingOptions{
    exclude 'META-INF/rxjava.properties'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/notice'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license'
    exclude 'META-INF/license.txt'
}

repositories {
    maven {
        url "https://jitpack.io"
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.googlecode.android-query:android-query:0.25.9'
compile 'com.android.support:support-v4:26.1.0'
compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.eftimoff:android-patternview:1.0.6@aar'
compile 'com.google.android.gms:play-services-ads:11.4.2'
compile 'com.google.firebase:firebase-core:11.4.2'
//    compile 'com.flurry.android:analytics:6.9.2'
compile 'com.android.support:design:26.1.0'
compile 'com.jakewharton:butterknife:8.5.1'
compile 'com.android.support:multidex:1.0.2'
compile 'com.google.android.gms:play-services-analytics:11.4.2'
compile 'com.github.chrisbanes:PhotoView:2.0.0'
compile('com.smartyads:ad-container:0.4.5') {
    transitive = true
}
compile 'com.android.support.constraint:constraint-layout:1.0.2'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile 'com.inmobi.monetization:inmobi-ads:7.0.0'
compile 'com.ironsource.sdk:mediationsdk:6.7.0.1@jar'
compile 'com.github.vungle:vungle-android-sdk:5.3.0'
compile 'com.adcolony:sdk:3.2.1'
compile 'com.adcash:adcash-sdk-lib:2.4.0'
implementation files('src/lib/aerserv-sdk.jar')
implementation project(':SDKAndroid')
}

apply plugin: 'com.google.gms.google-services'

repositories {
mavenCentral()
}
</code>```

Any advice?

UPD

I resolve this problem, using *.aar library of AdCash instead compile dependency.
Hope, it help anybody!

答:
I resolve this problem, using *.aar library of AdCash instead compile dependency. Hope, it help anybody!

UPD

In fact, i resolved this problem, by deleting modules in project folder by finder manually.

Body:
When I include AdCash library (compile 'com.adcash:adcash-sdk-lib:2.4.0'), I have this error:

Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.
java.io.IOException: Can't write [C:\NovaDevelopment\xxx\app\build\intermediates\multi-dex\debug\componentClasses.jar] (Can't read [C:\Program Files\Android\Android Studio\gradle\m2repository\org\jetbrains\annotations\13.0\annotations-13.0.jar(;;;;;;**.class)] (Duplicate zip entry [annotations-13.0.jar:org/intellij/lang/annotations/Flow.class]))

But without this library, everything works as expected.

My build.gradle file:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
compileSdkVersion 26
buildToolsVersion "27.0.0"

defaultConfig {
    applicationId "com.xxx"
    minSdkVersion 16
    targetSdkVersion 22
    versionCode 23
    versionName "2.8"
    multiDexEnabled true
}
buildTypes {
    release {
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

dexOptions {
    javaMaxHeapSize "4g"
}

packagingOptions{
    exclude 'META-INF/rxjava.properties'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/notice'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license'
    exclude 'META-INF/license.txt'
}

repositories {
    maven {
        url "https://jitpack.io"
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.googlecode.android-query:android-query:0.25.9'
compile 'com.android.support:support-v4:26.1.0'
compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.eftimoff:android-patternview:1.0.6@aar'
compile 'com.google.android.gms:play-services-ads:11.4.2'
compile 'com.google.firebase:firebase-core:11.4.2'
//    compile 'com.flurry.android:analytics:6.9.2'
compile 'com.android.support:design:26.1.0'
compile 'com.jakewharton:butterknife:8.5.1'
compile 'com.android.support:multidex:1.0.2'
compile 'com.google.android.gms:play-services-analytics:11.4.2'
compile 'com.github.chrisbanes:PhotoView:2.0.0'
compile('com.smartyads:ad-container:0.4.5') {
    transitive = true
}
compile 'com.android.support.constraint:constraint-layout:1.0.2'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile 'com.inmobi.monetization:inmobi-ads:7.0.0'
compile 'com.ironsource.sdk:mediationsdk:6.7.0.1@jar'
compile 'com.github.vungle:vungle-android-sdk:5.3.0'
compile 'com.adcolony:sdk:3.2.1'
compile 'com.adcash:adcash-sdk-lib:2.4.0'
implementation files('src/lib/aerserv-sdk.jar')
implementation project(':SDKAndroid')
}

apply plugin: 'com.google.gms.google-services'

repositories {
mavenCentral()
}

Any advice?

UPD

I resolve this problem, using *.aar library of AdCash instead compile dependency.
Hope, it help anybody!


问:
In what cases does a C++ compiler infer noexcept?
Suppose a C++ compiler is compiling a function whose definition is available in the same translation unit as its invocation. Suppose that it does not throw itself nor calls a function that is know to throw. Suppose also no extern C code is called, nor a numeric division with a potentially-zero value.

Under these assumptions, will the compiler treat the function as noexcept? If not, are there additional conditions under which noexcept is inferred?

Specifically, what about super-simple functions such as

```<code>void foo() { } /* this one */
class A {
    int x_;
public:
    x() const { return x_; }  /* ... and this one */
}
</code>```

?

I'd like an answer based only on the standard, foremost, and possibly also what GCC and clang do.

答:
Almost all functions are assumed to be potentially throwing unless you explicitly use a noexcept specifier. The exceptions are for your own definitions of delete (deallocation functions), and some special member functions: constructors, destructors, and assignment operators. (C++17)

From [except.spec]

If a declaration of a function does not have a noexcept-specifier, the declaration has a potentially throwing
  exception specification unless it is a destructor or a deallocation function or is defaulted on its first declaration,
  in which cases the exception specification is as specified below and no other declaration for that function shall
  have a noexcept-specifier.

Constructors

Are implicitly noexcept unless any initialization performed for any member (or a member's member etc) is potentially throwing

Destructors

Are implicitly noexcept unless any destructor for a potentially constructed sub-object is potentially throwing.

Assignment operators

Are implicitly noexcept unless any use of assignment within is potentially-throwing.

Here's some sample code that demonstrates the above (clang 6.0.0, gcc 8.0.0):

```<code>int foo() { return 1; }
int bar() noexcept{ return 1; }

struct Foo{};

struct Bar{
 Bar(){}
};

int main()
{
    static_assert(noexcept(bar()));
    static_assert(!noexcept(foo()));
    static_assert(noexcept(Foo()));
    static_assert(noexcept(Foo().~Foo()));
    static_assert(noexcept(Foo().operator=(Foo())));
    static_assert(!noexcept(Bar()));
    Bar b;
    static_assert(noexcept(b.~Bar()));
}
</code>```

Yet another reason to use =default or allow the compiler to generate its own versions of your special member functions via omission.

Body:
Suppose a C++ compiler is compiling a function whose definition is available in the same translation unit as its invocation. Suppose that it does not throw itself nor calls a function that is know to throw. Suppose also no extern C code is called, nor a numeric division with a potentially-zero value.

Under these assumptions, will the compiler treat the function as noexcept? If not, are there additional conditions under which noexcept is inferred?

Specifically, what about super-simple functions such as

void foo() { } /* this one */
class A {
    int x_;
public:
    x() const { return x_; }  /* ... and this one */
}

?

I'd like an answer based only on the standard, foremost, and possibly also what GCC and clang do.

Body:
Almost all functions are assumed to be potentially throwing unless you explicitly use a noexcept specifier. The exceptions are for your own definitions of delete (deallocation functions), and some special member functions: constructors, destructors, and assignment operators. (C++17)

From [except.spec]

If a declaration of a function does not have a noexcept-specifier, the declaration has a potentially throwing
  exception specification unless it is a destructor or a deallocation function or is defaulted on its first declaration,
  in which cases the exception specification is as specified below and no other declaration for that function shall
  have a noexcept-specifier.

Constructors

Are implicitly noexcept unless any initialization performed for any member (or a member's member etc) is potentially throwing

Destructors

Are implicitly noexcept unless any destructor for a potentially constructed sub-object is potentially throwing.

Assignment operators

Are implicitly noexcept unless any use of assignment within is potentially-throwing.

Here's some sample code that demonstrates the above (clang 6.0.0, gcc 8.0.0):

int foo() { return 1; }
int bar() noexcept{ return 1; }

struct Foo{};

struct Bar{
 Bar(){}
};

int main()
{
    static_assert(noexcept(bar()));
    static_assert(!noexcept(foo()));
    static_assert(noexcept(Foo()));
    static_assert(noexcept(Foo().~Foo()));
    static_assert(noexcept(Foo().operator=(Foo())));
    static_assert(!noexcept(Bar()));
    Bar b;
    static_assert(noexcept(b.~Bar()));
}

Yet another reason to use =default or allow the compiler to generate its own versions of your special member functions via omission.