问:
Use group by inside subquery
I am trying to display progressive_total and cumulative_sum group by the subincome field in house_details table using mysql. I built my schema in this link

working query:

```<code>SELECT *,
       COALESCE(
                  (SELECT SUM(x.rupees)
                   FROM house_details x
                   WHERE MONTH(x.date) < t1.month), '-') AS progressive_total,

  (SELECT SUM(x.rupees)
   FROM house_details x
   WHERE MONTH(x.date) <= t1.month) AS cumulative_sum
FROM
  (SELECT MONTHNAME(t.date) AS `monthname`,
          MONTH(t.date) `month`,
          YEAR(t.date) AS YEAR,
          t.income,
          t.subincome,
          t.ssubincome,
          SUM(rupees) AS amount,
          GROUP_CONCAT(receipt_id) AS receipt_ids
   FROM house_details t
   WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
   GROUP BY month(t.date),
            t.subincome
   ORDER BY t.date) t1
</code>```

but this gives irrelevant cumulative_sum in the field.

I tried to use group by inside the subquery like this:

query:

```<code>SELECT *,
       COALESCE(
                  (SELECT SUM(x.rupees)
                   FROM house_details x
                   WHERE MONTH(x.date) < t1.month
                   GROUP BY x.subincome), '-') AS progressive_total,

  (SELECT SUM(x.rupees)
   FROM house_details x
   WHERE MONTH(x.date) <= t1.month
   GROUP BY x.subincome) AS cumulative_sum
FROM
  (SELECT MONTHNAME(t.date) AS `monthname`,
          MONTH(t.date) `month`,
          YEAR(t.date) AS YEAR,
          t.income,
          t.subincome,
          t.ssubincome,
          SUM(rupees) AS amount,
          GROUP_CONCAT(receipt_id) AS receipt_ids
   FROM house_details t
   WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
   GROUP BY month(t.date),
            t.subincome
   ORDER BY t.date) t1;
</code>```

but it shows error sub query returns more than one row.

答:
Subqueries that written in the previous part of "FROM" must return only one row. Obviously your query turns more than one line here.

Also the query seems a bit complicated.
You can easily get the progressive sum like this:

```<code>set @csum := 0;
select id, date, rupees ,(@csum := @csum + rupees) as proggressive_sum
from house_details
order by date;
</code>```

and you can group on it what you want like this:

Monthly groupped

```<code>set @csum := 0;
select month,sum_rupees, (@csum := @csum + sum_rupees) as progressive_sum_monthly
from (
    select DATE_FORMAT(date,'%Y-%m') month, sum(rupees) sum_rupees
    from house_details
    GROUP BY DATE_FORMAT(date,'%Y-%m')
    ) gg
order by 1;
</code>```

Year and subincome groupped :

```<code>set @csum := 0;
select subincome, year,sum_rupees, (@csum := @csum + sum_rupees) as progressive_sum_subincome
from (
    select year(date) year, subincome, sum(rupees) sum_rupees
    from house_details
    GROUP BY subincome,year(date)
    ) gg
</code>```

Title: Use group by inside subquery

Body:
I am trying to display progressive_total and cumulative_sum group by the subincome field in house_details table using mysql. I built my schema in this link

working query:

SELECT *,
       COALESCE(
                  (SELECT SUM(x.rupees)
                   FROM house_details x
                   WHERE MONTH(x.date) < t1.month), '-') AS progressive_total,

  (SELECT SUM(x.rupees)
   FROM house_details x
   WHERE MONTH(x.date) <= t1.month) AS cumulative_sum
FROM
  (SELECT MONTHNAME(t.date) AS `monthname`,
          MONTH(t.date) `month`,
          YEAR(t.date) AS YEAR,
          t.income,
          t.subincome,
          t.ssubincome,
          SUM(rupees) AS amount,
          GROUP_CONCAT(receipt_id) AS receipt_ids
   FROM house_details t
   WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
   GROUP BY month(t.date),
            t.subincome
   ORDER BY t.date) t1

but this gives irrelevant cumulative_sum in the field.

I tried to use group by inside the subquery like this:

query:

SELECT *,
       COALESCE(
                  (SELECT SUM(x.rupees)
                   FROM house_details x
                   WHERE MONTH(x.date) < t1.month
                   GROUP BY x.subincome), '-') AS progressive_total,

  (SELECT SUM(x.rupees)
   FROM house_details x
   WHERE MONTH(x.date) <= t1.month
   GROUP BY x.subincome) AS cumulative_sum
FROM
  (SELECT MONTHNAME(t.date) AS `monthname`,
          MONTH(t.date) `month`,
          YEAR(t.date) AS YEAR,
          t.income,
          t.subincome,
          t.ssubincome,
          SUM(rupees) AS amount,
          GROUP_CONCAT(receipt_id) AS receipt_ids
   FROM house_details t
   WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
   GROUP BY month(t.date),
            t.subincome
   ORDER BY t.date) t1;

but it shows error sub query returns more than one row.

Body:
Subqueries that written in the previous part of "FROM" must return only one row. Obviously your query turns more than one line here.

Also the query seems a bit complicated.
You can easily get the progressive sum like this:

set @csum := 0;
select id, date, rupees ,(@csum := @csum + rupees) as proggressive_sum
from house_details
order by date;

and you can group on it what you want like this:

Monthly groupped

set @csum := 0;
select month,sum_rupees, (@csum := @csum + sum_rupees) as progressive_sum_monthly
from (
    select DATE_FORMAT(date,'%Y-%m') month, sum(rupees) sum_rupees
    from house_details
    GROUP BY DATE_FORMAT(date,'%Y-%m')
    ) gg
order by 1;

Year and subincome groupped :

set @csum := 0;
select subincome, year,sum_rupees, (@csum := @csum + sum_rupees) as progressive_sum_subincome
from (
    select year(date) year, subincome, sum(rupees) sum_rupees
    from house_details
    GROUP BY subincome,year(date)
    ) gg


来源: stackexchange

问:
webrtc each step success but no video share
chrome version: 62.0.3202.94;
firefox version: 57.0.1;

I write a simple demo use webrtc and socket.io.
It works with pages. For example, I open one page to connect socket, and waiting for PeerConnection info from the main page(which get the local media). When I open the main, I create ice and sdp and then exchange them by socket.io to create connection.
Here is the code.

// The server side:
const express = require('express')
const app = express()
const path = require('path')

app.use(express.static(path.join(__dirname, 'public')))

app.get('/phone', function(req, res) {
  res.sendfile(__dirname + '/phone.html')
})

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html')
})

const server = require('http').createServer(app)
const io = require('socket.io')(server)
let clients = []

io.on('connection', function(socket) {

  clients.push(socket)
  const referer = socket.handshake.headers.referer

  // socket connect from '/phone'
  if (referer.match('/phone')) {
    // send the ice from phone to others
    socket.on('phone_ice_candidate', function(res) {
      socket.broadcast.emit('pc_add_ice', {
        ice: res.ice
      })
    })

    // send the sdp from phone to others
    socket.on('send_phone_sdp', function(data) {
      socket.broadcast.emit('set_pc_remote_sdp', {
        desc: data.desc
      })
    })
  }

  // phone add ice from web
  socket.on('remote_ice_candidate', function(ice) {
    socket.to(getId(clients, '/phone')).emit('send_ice_to_pc', {
      ice: ice
    })
  })

  // phone add sdp from web
  socket.on('send_pc_sdp', function(data) {
    // send to phone
    socket.to(getId(clients, '/phone')).emit('set_phone_remote_sdp', {
      desc: data
    })
  })

  // socket disconnect and remove it from clients
  socket.on('disconnect', () => {
    let id = socket.id
    clients.forEach((client, index) => {
      if (client.id === id) {
        clients.splice(index, 1)
      }
    })
  })
})

// get the socket id to emit
function getId(sockets, exp) {
  let id
  sockets.forEach(socket => {
    if (socket.handshake.headers.referer.match(exp)) {
      id = socket.id
    }
  })
  return id
}

server.listen(3000, function() {
  console.log('port listening at 3000')
})```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// --------------------------------------------- //
// web.js
var socket = io();
var server = {
    // "iceServers": [{
    //     "url": "stun:stun.l.google.com:19302"
    // }]
  },
  pc = new RTCPeerConnection(null),
  v = document.querySelector('#video2')
// web onicecandidate
pc.onicecandidate = function(event) {
  if (event.candidate) {
    socket.emit('remote_ice_candidate', {
      ice: event.candidate
    })
  }
}
// web addIceCandidate
socket.on('pc_add_ice', function(event) {
  pc.addIceCandidate(new RTCIceCandidate(event.ice))
})

// didn't trigger
pc.ontrack = function(e) {
  // v.srcObject = e.streams[0];
  console.log(e, 'pc.ontrack')
}

// web setRemoteDescription and createAnswer
socket.on('set_pc_remote_sdp', function(e) {
  pc.setRemoteDescription(e.desc).then(
    function() {
      console.log('remote setRemoteDescription success')

      pc.createAnswer().then(function(desc) {
        pc.setLocalDescription(desc).then(
          function() {
            socket.emit('send_pc_sdp', {
              desc: desc
            })
          },
          function(err) {
            console.log(err)
          }
        );
      })
    },
    function() {
      console.log('pc setLocalDescription error')
    }
  )

})

// web iceConnectionState
pc.oniceconnectionstatechange = function() {
  console.log('web oniceconnectionstatechange', pc.iceConnectionState)
  // log  checking -> connected
};</code>```

//---------------------------------------------//
// phone.js
var socket = io();
var server = {
    // "iceServers": [{
    //     "url": "stun:stun.l.google.com:19302"
    // }]
  },
  pc = new RTCPeerConnection(null),
  v = document.querySelector('#video1')

// phone onicecandidate
pc.onicecandidate = function(event) {
  if (event.candidate) {
    socket.emit('phone_ice_candidate', {
      ice: event.candidate
    })
  }
}

// phone addIceCandidate
socket.on('send_ice_to_pc', function(event) {
  pc.addIceCandidate(new RTCIceCandidate(event.ice.ice))
})

// getUserMedia
navigator.mediaDevices.getUserMedia({
    video: {
      width: 400,
      height: 300
    },
    audio: false
  })
  .then(function(stream) {
    v.src = window.URL.createObjectURL(stream);
    pc.addStream(stream);
  })
  .then(function() {
    // create offer
    pc.createOffer({
      offerToReceiveVideo: 1
    }).then(function(e) {
      // pc setLocalDescription
      pc.setLocalDescription(e).then(
        function() {
          socket.emit('send_phone_sdp', {
            desc: e
          })
        },
        function() {
          console.log('pc setLocalDescription error')
        }
      )
    });
  })
  .catch(function(err) {
    console.log(err.name + ": " + err.message);
  })

// phone setRemoteDescription
socket.on('set_phone_remote_sdp', function(e) {
  pc.setRemoteDescription(e.desc.desc).then(
    function() {
      console.log('pc setRemoteDescription success')
    },
    function(err) {
      console.log(err)
    })
})
// phone iceConnectionState
pc.oniceconnectionstatechange = function() {
  console.log('phone oniceconnectionstatechange', pc.iceConnectionState)
  // log checking -> connected -> completed
};```

When i use firefox to open it, there is an error ICE failed, add a STUN server and see about:webrtc for more details in console.
In chrome the 'phone iceConnectionState' changed checking -> connected -> completed, the 'web iceConnectionState' changed checking -> connected.

答:
getUserMedia is an async function. You are calling createOffer before you call pc.addStream which means there is nothing to negotiate.
Make the promise callback return your pc.createOffer() after pc.addStream(stream);</p>

ContentLicense: CC BY-SA 3.0

Body:
chrome version: 62.0.3202.94;
firefox version: 57.0.1;

I write a simple demo use webrtc and socket.io.
It works with pages. For example, I open one page to connect socket, and waiting for PeerConnection info from the main page(which get the local media). When I open the main, I create ice and sdp and then exchange them by socket.io to create connection.
Here is the code.

// The server side:
const express = require('express')
const app = express()
const path = require('path')

app.use(express.static(path.join(__dirname, 'public')))

app.get('/phone', function(req, res) {
  res.sendfile(__dirname + '/phone.html')
})

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html')
})

const server = require('http').createServer(app)
const io = require('socket.io')(server)
let clients = []

io.on('connection', function(socket) {

  clients.push(socket)
  const referer = socket.handshake.headers.referer

  // socket connect from '/phone'
  if (referer.match('/phone')) {
    // send the ice from phone to others
    socket.on('phone_ice_candidate', function(res) {
      socket.broadcast.emit('pc_add_ice', {
        ice: res.ice
      })
    })

    // send the sdp from phone to others
    socket.on('send_phone_sdp', function(data) {
      socket.broadcast.emit('set_pc_remote_sdp', {
        desc: data.desc
      })
    })
  }

  // phone add ice from web
  socket.on('remote_ice_candidate', function(ice) {
    socket.to(getId(clients, '/phone')).emit('send_ice_to_pc', {
      ice: ice
    })
  })

  // phone add sdp from web
  socket.on('send_pc_sdp', function(data) {
    // send to phone
    socket.to(getId(clients, '/phone')).emit('set_phone_remote_sdp', {
      desc: data
    })
  })

  // socket disconnect and remove it from clients
  socket.on('disconnect', () => {
    let id = socket.id
    clients.forEach((client, index) => {
      if (client.id === id) {
        clients.splice(index, 1)
      }
    })
  })
})

// get the socket id to emit
function getId(sockets, exp) {
  let id
  sockets.forEach(socket => {
    if (socket.handshake.headers.referer.match(exp)) {
      id = socket.id
    }
  })
  return id
}

server.listen(3000, function() {
  console.log('port listening at 3000')
})

// --------------------------------------------- //
// web.js
var socket = io();
var server = {
    // "iceServers": [{
    //     "url": "stun:stun.l.google.com:19302"
    // }]
  },
  pc = new RTCPeerConnection(null),
  v = document.querySelector('#video2')
// web onicecandidate
pc.onicecandidate = function(event) {
  if (event.candidate) {
    socket.emit('remote_ice_candidate', {
      ice: event.candidate
    })
  }
}
// web addIceCandidate
socket.on('pc_add_ice', function(event) {
  pc.addIceCandidate(new RTCIceCandidate(event.ice))
})

// didn't trigger
pc.ontrack = function(e) {
  // v.srcObject = e.streams[0];
  console.log(e, 'pc.ontrack')
}

// web setRemoteDescription and createAnswer
socket.on('set_pc_remote_sdp', function(e) {
  pc.setRemoteDescription(e.desc).then(
    function() {
      console.log('remote setRemoteDescription success')

      pc.createAnswer().then(function(desc) {
        pc.setLocalDescription(desc).then(
          function() {
            socket.emit('send_pc_sdp', {
              desc: desc
            })
          },
          function(err) {
            console.log(err)
          }
        );
      })
    },
    function() {
      console.log('pc setLocalDescription error')
    }
  )

})

// web iceConnectionState
pc.oniceconnectionstatechange = function() {
  console.log('web oniceconnectionstatechange', pc.iceConnectionState)
  // log  checking -> connected
};

//---------------------------------------------//
// phone.js
var socket = io();
var server = {
    // "iceServers": [{
    //     "url": "stun:stun.l.google.com:19302"
    // }]
  },
  pc = new RTCPeerConnection(null),
  v = document.querySelector('#video1')

// phone onicecandidate
pc.onicecandidate = function(event) {
  if (event.candidate) {
    socket.emit('phone_ice_candidate', {
      ice: event.candidate
    })
  }
}

// phone addIceCandidate
socket.on('send_ice_to_pc', function(event) {
  pc.addIceCandidate(new RTCIceCandidate(event.ice.ice))
})

// getUserMedia
navigator.mediaDevices.getUserMedia({
    video: {
      width: 400,
      height: 300
    },
    audio: false
  })
  .then(function(stream) {
    v.src = window.URL.createObjectURL(stream);
    pc.addStream(stream);
  })
  .then(function() {
    // create offer
    pc.createOffer({
      offerToReceiveVideo: 1
    }).then(function(e) {
      // pc setLocalDescription
      pc.setLocalDescription(e).then(
        function() {
          socket.emit('send_phone_sdp', {
            desc: e
          })
        },
        function() {
          console.log('pc setLocalDescription error')
        }
      )
    });
  })
  .catch(function(err) {
    console.log(err.name + ": " + err.message);
  })

// phone setRemoteDescription
socket.on('set_phone_remote_sdp', function(e) {
  pc.setRemoteDescription(e.desc.desc).then(
    function() {
      console.log('pc setRemoteDescription success')
    },
    function(err) {
      console.log(err)
    })
})
// phone iceConnectionState
pc.oniceconnectionstatechange = function() {
  console.log('phone oniceconnectionstatechange', pc.iceConnectionState)
  // log checking -> connected -> completed
};

When i use firefox to open it, there is an error ICE failed, add a STUN server and see about:webrtc for more details in console.
In chrome the 'phone iceConnectionState' changed checking -> connected -> completed, the 'web iceConnectionState' changed checking -> connected.


问:
How to use git bash in windows for cloning an Android project
I want to create an IME for android in arabic language.

I needed some reference and found this :
 https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+/master/java/res

Now I wanted to clone one of the directory trees onto my system as it was said there.

I installed git on windows and I got a 'git bash' icon. I opened it , what it asked and got this error :

fatal: The remote end hung up unexpectedly

Now I am clueless.

How should I download that source?

答:
The exact line you need is </p>

```<code>git clone https://android.googlesource.com/platform/packages/inputmethods/LatinIME
</code>```

Body:
The exact line you need is

git clone https://android.googlesource.com/platform/packages/inputmethods/LatinIME


问:
Transforming csv file in R
I'm quite new in R. So. could you please tell me how to transform ordinary rows and columns into dataframe?

For example, I have data in such way:

```<code>Id, gender
1   1
2   0
3   1
4   0
5   0
</code>```

but actually that is not a dataframe with rows and columns, just note without being as a table.

Thank you.

答:
If the file is simply a text file and only header row has commas, the file can be read with read.table(). Use the skip= and col.names= arguments to correct the heading row.

```<code>rawData <- "Id, gender
1   1
2   0
3   1
4   0
5   0"

aDataFrame <- read.table(textConnection(rawData),header=FALSE,col.names=c("Id","gender"),skip=1)

aDataFrame
</code>```

...and the output:

```<code>> aDataFrame
  Id gender
1  1      1
2  2      0
3  3      1
4  4      0
5  5      0
>
</code>```

Title: Transforming csv file in R

Body:
I'm quite new in R. So. could you please tell me how to transform ordinary rows and columns into dataframe?

For example, I have data in such way:

Id, gender
1   1
2   0
3   1
4   0
5   0

but actually that is not a dataframe with rows and columns, just note without being as a table.

Thank you.

Body:
If the file is simply a text file and only header row has commas, the file can be read with read.table(). Use the skip= and col.names= arguments to correct the heading row.

rawData <- "Id, gender
1   1
2   0
3   1
4   0
5   0"

aDataFrame <- read.table(textConnection(rawData),header=FALSE,col.names=c("Id","gender"),skip=1)

aDataFrame

...and the output:

> aDataFrame
  Id gender
1  1      1
2  2      0
3  3      1
4  4      0
5  5      0
>


问:
How to append to python dictionary inside a function
I have  the following code:

```<code>def main():
   content = si.RetrieveContent()
   esx_vm = {}
   search_index = si.content.searchIndex
   for child in content.rootFolder.childEntity:
      if hasattr(child, 'vmFolder'):
         datacenter = child
         vmFolder = datacenter.vmFolder
         vmList = vmFolder.childEntity

         for vm in vmList:
            vmname = PrintVmInfo(vm)
            if vmname is not  None:
                hostname = vmname

                vm = si.content.searchIndex.FindByDnsName(None, hostname, True)
                try :
                    ESX = vm.runtime.host.name
                except :
                    pass

   esx_vm.update({ESX:hostname})
   print(esx_vm)

if __name__ == "__main__":
   main()
</code>```

The code is supposed to create a dictionary mapping esx to vm in the below format:

```<code>{'esx1': 'vm1'}
</code>```

But I am getting only one key-value {'esx1': 'vm1'} and not all the esx:vm mappings. I am excepting to get:

```<code>{'esx1': 'vm1','esx2': 'vm2','esx3': 'vm3','esx4': 'vm4'}
</code>```

and so on.

Any advise how to get the the correct values of the dictionary?

答:
You might want to update ESX values inside "for loop". But its happening to be outside, that's why there is one key in the dict. Please add ESX key as part of for loop. Something like this (inside for loop),</p>

```<code>try :
    ESX = vm.runtime.host.name
    esx_vm.update({ESX:hostname}) # Or, just, esx_vm[ESX]=hostname
except :
    pass
</code>```

Body:
I have  the following code:

def main():
   content = si.RetrieveContent()
   esx_vm = {}
   search_index = si.content.searchIndex
   for child in content.rootFolder.childEntity:
      if hasattr(child, 'vmFolder'):
         datacenter = child
         vmFolder = datacenter.vmFolder
         vmList = vmFolder.childEntity

         for vm in vmList:
            vmname = PrintVmInfo(vm)
            if vmname is not  None:
                hostname = vmname

                vm = si.content.searchIndex.FindByDnsName(None, hostname, True)
                try :
                    ESX = vm.runtime.host.name
                except :
                    pass

   esx_vm.update({ESX:hostname})
   print(esx_vm)

if __name__ == "__main__":
   main()

The code is supposed to create a dictionary mapping esx to vm in the below format:

{'esx1': 'vm1'}

But I am getting only one key-value {'esx1': 'vm1'} and not all the esx:vm mappings. I am excepting to get:

{'esx1': 'vm1','esx2': 'vm2','esx3': 'vm3','esx4': 'vm4'}

and so on.

Any advise how to get the the correct values of the dictionary?

Body:
You might want to update ESX values inside "for loop". But its happening to be outside, that's why there is one key in the dict. Please add ESX key as part of for loop. Something like this (inside for loop),

try :
    ESX = vm.runtime.host.name
    esx_vm.update({ESX:hostname}) # Or, just, esx_vm[ESX]=hostname
except :
    pass


问:
Could not transfer artifacts from/to central maven repo when using Spring Framework Cloud
I am trying to create a maven project using Spring Framework Cloud.
I defined pom.xml file as below

```<code><parent>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-parent</artifactId>
        <version>Brixton.RELEASE</version>
    </parent>

    <properties>
        <!-- Stand-alone RESTFul application for testing only -->
        <start-class>io.pivotal.microservices.services.Main</start-class>
    </properties>

    <dependencies>
        <dependency>
            <!-- Setup Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <!-- Setup Spring MVC & REST, use Embedded Tomcat -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <!-- Setup Spring Data common components -->
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>

        <dependency>
            <!-- Testing starter -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <!-- Setup Spring Data JPA Repository support -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <!-- In-memory database for testing/demos -->
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
        </dependency>

        <dependency>
            <!-- Spring Cloud starter -->
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>

        <dependency>
            <!-- Eureka service registration -->
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
    </dependencies>
</code>```

When trying to build maven getting error for all dependencies as

Could not transfer artifacts from/to central (https://repo.maven.apache.org/maven2)

Multiple annotations found at this line:
    - Failure to transfer org.springframework:spring-orm:jar:4.2.6.RELEASE from
  https://repo.maven.apache.org/maven2 was cached in the local
  repository, resolution will not be     reattempted until the update
  interval of central has elapsed or updates are forced. Original error:
  Could not transfer artifact
  org.springframework:spring-orm:jar:4.2.6.RELEASE from/to central

  (https://repo.maven.apache.org/maven2): The operation was cancelled.
  org.eclipse.aether.transfer.ArtifactTransferException: Failure to
  transfer org.springframework:spring-orm:jar:
     4.2.6.RELEASE from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the
  update interval of central has elapsed or updates are      forced.
  Original error: Could not transfer artifact
  org.springframework:spring-orm:jar:4.2.6.RELEASE from/to central
  (https://repo.maven.apache.org/maven2): The operation was cancelled.
  at

  org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.newException(DefaultUpdateCheckManager.java:238)
  at

  org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.checkArtifact(DefaultUpdateCheckManager.java:206)
  at

  org.eclipse.aether.internal.impl.DefaultArtifactResolver.gatherDownloads(DefaultArtifactResolver.java:585)
  at

  org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:503)
  at

  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421)
  at

  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:246)
  at

  org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:367)
  at

When I go to the location, I can clearly see the Jar files are present in that location.
Is there something else I need to add to my pom.xml?

答:
Try force refreshing your dependencies. Specifying -U does that

```<code>mvn clean install -U
</code>```

Edit:
You can purge your local release dependencies and to the normal mvn clean install afterwards:

```<code>mvn dependency:purge-local-repository
</code>```

There is not way to force the release dependencies to be pulled, the -U only works with snapshot dependencies

Body:
I am trying to create a maven project using Spring Framework Cloud.
I defined pom.xml file as below

<parent>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-parent</artifactId>
        <version>Brixton.RELEASE</version>
    </parent>

    <properties>

        <start-class>io.pivotal.microservices.services.Main</start-class>
    </properties>

    <dependencies>
        <dependency>

            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>

            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>

            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
        </dependency>

        <dependency>

            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>

        <dependency>

            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
    </dependencies>

When trying to build maven getting error for all dependencies as

Could not transfer artifacts from/to central (https://repo.maven.apache.org/maven2)

Multiple annotations found at this line:
    - Failure to transfer org.springframework:spring-orm:jar:4.2.6.RELEASE from
  https://repo.maven.apache.org/maven2 was cached in the local
  repository, resolution will not be     reattempted until the update
  interval of central has elapsed or updates are forced. Original error:
  Could not transfer artifact
  org.springframework:spring-orm:jar:4.2.6.RELEASE from/to central

  (https://repo.maven.apache.org/maven2): The operation was cancelled.
  org.eclipse.aether.transfer.ArtifactTransferException: Failure to
  transfer org.springframework:spring-orm:jar:
     4.2.6.RELEASE from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the
  update interval of central has elapsed or updates are      forced.
  Original error: Could not transfer artifact
  org.springframework:spring-orm:jar:4.2.6.RELEASE from/to central
  (https://repo.maven.apache.org/maven2): The operation was cancelled.
  at

  org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.newException(DefaultUpdateCheckManager.java:238)
  at

  org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.checkArtifact(DefaultUpdateCheckManager.java:206)
  at

  org.eclipse.aether.internal.impl.DefaultArtifactResolver.gatherDownloads(DefaultArtifactResolver.java:585)
  at

  org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:503)
  at

  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421)
  at

  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:246)
  at

  org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:367)
  at

When I go to the location, I can clearly see the Jar files are present in that location.
Is there something else I need to add to my pom.xml?

Body:
Try force refreshing your dependencies. Specifying -U does that

mvn clean install -U

Edit:
You can purge your local release dependencies and to the normal mvn clean install afterwards:

mvn dependency:purge-local-repository

There is not way to force the release dependencies to be pulled, the -U only works with snapshot dependencies


问:
Update django model from background task
I am trying to update a django model from a task using django-background-tasks. Here's what I've got:

```<code>@background(schedule=0)
def difficult_work():
    for i in range(0,100):
        time.sleep(1)
        with transaction.atomic():
            workProgress = WorkProgress.objects.filter(id="fixed_work_id_for_testing").select_for_update().get()

            print("updating work progress to " + str(i))
            workProgress.progress = i
            workProgress.currentJobInfo = "test work"

            # if we've finished then make sure to set the status
            if i == 100:
                workProgress.status = "success"

            transfer.save(force_update=True)
</code>```

Additionally, I have an API view to get the progress of a work task.

```<code>class WorkDetail(APIView):
def get(self, request, workId, format=None):
    with transaction.atomic():
        work = WorkProgress.objects.filter(id=workId).select_for_update().get()
        data = WorkProgressSerializer(transfer).data

        return Response(data)
</code>```

The problem is, I'm not seeing any updates to the database while executing a task. I've got python manage.py dbshell running, monitoring the database tables and they aren't updating as the task progresses. I'm making sure to run python manage.py process_tasks, and it's outputting the correct print statements, indicating progress, but the database doesn't update until the task exits.

I found someone who ran into a similar problem here, but they were only experiencing it in tests where they did not get() an updated model. However I'm not even seeing the database update in dbshell.

How do I make sure the table is updated while the task is running?

Note: according to this site, they had some sort of success using celery. Can anyone confirm this? I will try it out and comment on viability.

答:
your project settings.py

```<code>INSTALLED_APPS = [
....
]

...
# Add to Option
BACKGROUND_TASK_RUN_ASYNC=True
</code>```

Body:
I am trying to update a django model from a task using django-background-tasks. Here's what I've got:

@background(schedule=0)
def difficult_work():
    for i in range(0,100):
        time.sleep(1)
        with transaction.atomic():
            workProgress = WorkProgress.objects.filter(id="fixed_work_id_for_testing").select_for_update().get()

            print("updating work progress to " + str(i))
            workProgress.progress = i
            workProgress.currentJobInfo = "test work"

            # if we've finished then make sure to set the status
            if i == 100:
                workProgress.status = "success"

            transfer.save(force_update=True)

Additionally, I have an API view to get the progress of a work task.

class WorkDetail(APIView):
def get(self, request, workId, format=None):
    with transaction.atomic():
        work = WorkProgress.objects.filter(id=workId).select_for_update().get()
        data = WorkProgressSerializer(transfer).data

        return Response(data)

The problem is, I'm not seeing any updates to the database while executing a task. I've got python manage.py dbshell running, monitoring the database tables and they aren't updating as the task progresses. I'm making sure to run python manage.py process_tasks, and it's outputting the correct print statements, indicating progress, but the database doesn't update until the task exits.

I found someone who ran into a similar problem here, but they were only experiencing it in tests where they did not get() an updated model. However I'm not even seeing the database update in dbshell.

How do I make sure the table is updated while the task is running?

Note: according to this site, they had some sort of success using celery. Can anyone confirm this? I will try it out and comment on viability.

Body:
your project settings.py

INSTALLED_APPS = [
....
]

...
# Add to Option
BACKGROUND_TASK_RUN_ASYNC=True


问:
git add -p and trailing whitespace
Very often when I run git add -p, I get warnings like this:

```<code><stdin>:10: trailing whitespace.
... line of code ...
<stdin>:18: trailing whitespace.
... line of code ...
warning: 2 lines added whitespace errors.
</code>```

What is really strange about this, is that the lines mentioned do NOT have trailing whitespace. If there is, git shows the space as a red square.

What is going on ?

Note: I'm using git version 2.13.2 with Cygwin on Win 10.

答: In Windows, linebreaks are CR-LF (two bytes), in Unix, linebreaks are LF. My guess: git complains about the CR as additional whitespace.</p>

Title: git add -p and trailing whitespace

Body:
Very often when I run git add -p, I get warnings like this:

<stdin>:10: trailing whitespace.
... line of code ...
<stdin>:18: trailing whitespace.
... line of code ...
warning: 2 lines added whitespace errors.

What is really strange about this, is that the lines mentioned do NOT have trailing whitespace. If there is, git shows the space as a red square.

What is going on ?

Note: I'm using git version 2.13.2 with Cygwin on Win 10.


问:
XPath axis, get all following nodes until
I have the following example of HTML:

```<code><!-- lots of html -->
<h2>Foo bar</h2>
<p>lorem</p>
<p>ipsum</p>
<p>etc</p>

<h2>Bar baz</h2>
<p>dum dum dum</p>
<p>poopfiddles</p>
<!-- lots more html ... -->
</code>```

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

答:
Just because it's not between the answers, the classic XPath 1.0 set exclusion:

A - B = $A[count(.|$B)!=count($B)]

For this case:

```<code>(//h2[.='Foo bar']
    /following-sibling::p)
       [count(.|../h2[.='Foo bar']
                     /following-sibling::h2[1]
                        /following-sibling::p)
        != count(../h2[.='Foo bar']
                     /following-sibling::h2[1]
                        /following-sibling::p)]
</code>```

Note: This would be the negation of Kaysian Method.

ContentLicense: CC BY-SA 2.5

Body:
I have the following example of HTML:

Foo bar

lorem

ipsum

etc

Bar baz

dum dum dum

poopfiddles

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

Body:
Just because it's not between the answers, the classic XPath 1.0 set exclusion:

A - B = $A[count(.|$B)!=count($B)]

For this case:

(//h2[.='Foo bar']
    /following-sibling::p)
       [count(.|../h2[.='Foo bar']
                     /following-sibling::h2[1]
                        /following-sibling::p)
        != count(../h2[.='Foo bar']
                     /following-sibling::h2[1]
                        /following-sibling::p)]

Note: This would be the negation of Kaysian Method.


问:
Uncaught TypeError: $(...).waterwheelCarousel is not a function
I am new to jquery i am getting couple of errors with this code can u guys plz identify it n rectify my issue thanks in advance

here is the code. I am trying a waterwheel carousel model but not able to view it

```<code><!Doctype html>
<html>
<head>
<title> this is jquery carousel</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery.waterwheelCarousel.min.js"></script>
</head>
<script>
    $(document).ready(function () {
      var carousel = $("#carousel").waterwheelCarousel({
        flankingItems: 3,
      });

      $('#prev').bind('click', function () {
        carousel.prev();
        return false
      });

      $('#next').bind('click', function () {
        carousel.next();
        return false;
      });
    });
</script>
<body>

   <div id="carousel">
        <img src="images/1.jpg" id="item-1"/>
        <img src="images/2.jpg" id="item-2"/>
        <img src="images/3.jpg" id="item-3"/>
        <img src="images/4.jpg" id="item-4"/>
        <img src="images/5.jpg" id="item-5"/>
        <img src="images/6.jpg" id="item-6"/>
    </div>
    <a href="#" id="prev">Prev</a>
    <a href="#" id="next">Next</a>

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

答:
1.Make sure jQuery higher version is there.

2.Make sure that jquery.waterwheelCarousel.min.js path is correct (otherwise file will not be inculded and code will not work)

Working example:-

$(document).ready(function () {
  var carousel = $("#carousel").waterwheelCarousel({
    flankingItems: 3,
  });

  $('#prev').bind('click', function () {
    carousel.prev();
    return false
  });

  $('#next').bind('click', function () {
    carousel.next();
    return false;
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!Doctype html>
<html>
<head>
<title> this is jquery carousel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/js/jquery.waterwheelCarousel.min.js"></script>
</head>
<body>
  <div id="carousel">
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/1.jpg" id="item-1"/>
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/2.jpg" id="item-2"/>
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/3.jpg" id="item-3"/>
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/4.jpg" id="item-4"/>
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/5.jpg" id="item-5"/>
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/6.jpg" id="item-6"/>
  </div>
  Prev
  Next

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

Body:
I am new to jquery i am getting couple of errors with this code can u guys plz identify it n rectify my issue thanks in advance

here is the code. I am trying a waterwheel carousel model but not able to view it

<!Doctype html>

<title> this is jquery carousel</title>

    Prev
    Next

Body:
1.Make sure jQuery higher version is there.

2.Make sure that jquery.waterwheelCarousel.min.js path is correct (otherwise file will not be inculded and code will not work)

Working example:-

$(document).ready(function () {
  var carousel = $("#carousel").waterwheelCarousel({
    flankingItems: 3,
  });

  $('#prev').bind('click', function () {
    carousel.prev();
    return false
  });

  $('#next').bind('click', function () {
    carousel.next();
    return false;
  });
});

<!Doctype html>
<html>
<head>
<title> this is jquery carousel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/js/jquery.waterwheelCarousel.min.js"></script>
</head>
<body>
  <div id="carousel">
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/1.jpg" id="item-1"/>
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/2.jpg" id="item-2"/>
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/3.jpg" id="item-3"/>
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/4.jpg" id="item-4"/>
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/5.jpg" id="item-5"/>
    <img src="https://www.jqueryscript.net/demo/jQuery-Waterwheel-Carousel-Plugin/images/6.jpg" id="item-6"/>
  </div>
  <a href="#" id="prev">Prev</a>
  <a href="#" id="next">Next</a>

</body>
</html>


问:
How can you remove label of key under chart area?
I'm using the chart control from the WPFToolkit.

How can I remove or hide label of "key" under chart area?

I marked it in red on screen:

I have the following XAML code:

```<code><chartingToolkit:Chart Margin="62.14,92.004,0,130.505"
                       Name="chart"
                       HorizontalAlignment="Left"
                       Width="385"
                       BorderThickness="0"
                       Padding="0" >
    <chartingToolkit:LineSeries DependentValuePath="Value"
                                IndependentValuePath="Key"
                                ItemsSource="{Binding}"
                                IsSelectionEnabled="True"
                                DataPointStyle="{StaticResource InvisibleDataPoint}"/>
</chartingToolkit:Chart>
</code>```

答:
According to How does one hide the legend try using:</p>

```<code><charting:Chart.LegendStyle>
 <Style TargetType="Control">
 <Setter Property="Width" Value="0"/>
 <Setter Property="Height" Value="0"/>
 </Style>
</charting:Chart.LegendStyle>
</code>```

Body:
I'm using the chart control from the WPFToolkit.

How can I remove or hide label of "key" under chart area?

I marked it in red on screen:

I have the following XAML code:

<chartingToolkit:Chart Margin="62.14,92.004,0,130.505"
                       Name="chart"
                       HorizontalAlignment="Left"
                       Width="385"
                       BorderThickness="0"
                       Padding="0" >
    <chartingToolkit:LineSeries DependentValuePath="Value"
                                IndependentValuePath="Key"
                                ItemsSource="{Binding}"
                                IsSelectionEnabled="True"
                                DataPointStyle="{StaticResource InvisibleDataPoint}"/>
</chartingToolkit:Chart>

Body:
According to How does one hide the legend try using:

<charting:Chart.LegendStyle>
 <Style TargetType="Control">
 <Setter Property="Width" Value="0"/>
 <Setter Property="Height" Value="0"/>
 </Style>
</charting:Chart.LegendStyle>


问:
How can I remove the last part of a file after a specific text which has different positions?
I have many different text files with different structures. But all of them have a at some point the same text ('TS    1234000'). I want to delete in all these files the text after TS 178000 including the line with TS.

I have written something but it does not work:

```<code>with open('file1.txt', 'r') as input1_dat_file, \
     open('output.txt', 'w') as out:
         f = input1_dat_file.readline()
         if f.startswith('TS   1234000'):
             print("I have found it")
             sys.exit()
         else:
             out.writelines()
</code>```

the outpot file has no text in it.

the input data is like this:

```<code>TS 8888
1
2
3
4
5 6
88
TS    1234000
2
3
8
9
56
</code>```

答:
You seem to be looking for sed '/^TS    1234000/q' but here's a quick way to reimplement it in Python.

```<code>with open('file1.txt', 'r') as inputfile, open('output.txt', 'w') as out:
     for line in inputfile:
         if line.startswith('TS    1234000'):
             break
             #print("I have found it")
             #sys.exit()
         out.write(line)
</code>```

Reading just a line at a time avoids pulling the entire file into memory, so should scale to arbitrarily large files, and the logic seems slightly more straightforward than your attempt.

There is no need to strip the newline because write doesn't add one.

Body:
I have many different text files with different structures. But all of them have a at some point the same text ('TS    1234000'). I want to delete in all these files the text after TS 178000 including the line with TS.

I have written something but it does not work:

with open('file1.txt', 'r') as input1_dat_file, \
     open('output.txt', 'w') as out:
         f = input1_dat_file.readline()
         if f.startswith('TS   1234000'):
             print("I have found it")
             sys.exit()
         else:
             out.writelines()

the outpot file has no text in it.

the input data is like this:

TS 8888
1
2
3
4
5 6
88
TS    1234000
2
3
8
9
56

Body:
You seem to be looking for sed '/^TS    1234000/q' but here's a quick way to reimplement it in Python.

with open('file1.txt', 'r') as inputfile, open('output.txt', 'w') as out:
     for line in inputfile:
         if line.startswith('TS    1234000'):
             break
             #print("I have found it")
             #sys.exit()
         out.write(line)

Reading just a line at a time avoids pulling the entire file into memory, so should scale to arbitrarily large files, and the logic seems slightly more straightforward than your attempt.

There is no need to strip the newline because write doesn't add one.


问:
How to sum/multiply a split of an item in a listbox?
So I am making a program in which you can select products from a combo box, select the quantity and it will return with the price and the quantity in a list box.

However, I want to be able to multiply the price of a product in each line by the quantity, then add up all of the lines cost to figure out a "total cost". How would I be able to do it?

Here is the form:

TL;DR How to multiply the price of a product for each line, then add up all of the total prices in each line. Thank you heaps!!

Here is my code: IGNORE OLEDB PART - SOME OF THE NAMING IS INCORRECT AS IT IS A WIP

```<code>Imports System.Data.OleDb
Public Class frmOrderProduct
    Dim iPadCasePrice As String
    Dim iPad2Price As String
    Dim prod_list As List(Of String)

    Private Sub frmOrderProduct_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        cmboxProduct.Items.Add("iPad Case")
        cmboxProduct.Items.Add("iPad 2")

        iPadCasePrice = "$20.00"
        iPad2Price = "$200.00"

        txtUsername.Text = frmLogin.txtUsername.Text

    End Sub

    Private Sub btnAddToCart_Click(sender As Object, e As EventArgs) Handles btnAddToCart.Click

        If cmboxProduct.SelectedItem = "" Or txtQuantity.Text = "" Then
            MsgBox("Please fill out all required fields", MsgBoxStyle.OkOnly, "Invalid entered data")
        Else
            ListBoxCart.Items.Add("x" & txtQuantity.Text & " " & cmboxProduct.SelectedItem & " " & txtPriceEach.Text)

            'txtShoppingCart.AppendText("x" & txtQuantity.Text & " " & Product1 & Environment.NewLine)
        End If
    End Sub

    Private Sub txtQuantity_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles txtQuantity.KeyPress

        If Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
                e.Handled = True
            End If
        End If

    End Sub

    Private Sub btnOrderProducts_Click(sender As Object, e As EventArgs) Handles btnOrderProducts.Click

        Dim numberOfItems = ListBoxCart.Items.Count
        For Each item As String In ListBoxCart.Items

            Try

                cm = New OleDbCommand
                With cm
                    .Connection = cn
                    .CommandType = CommandType.Text
                    .CommandText = "INSERT INTO tblOrders ([ProductName],[Quantity],[PriceEach],[TotalPrice],[Username]) VALUES (@ProductName,@Quantity,@PriceEach,@TotalPrice,@Username)"

                    prod_list = item.Split(" ").ToList
                    Dim prod_name = prod_list.ElementAt(1)
                    Dim prod_quantity = Integer.Parse(prod_list.ElementAt(0).Remove("x"))
                    Dim price_each = prod_list.ElementAt(2)

                    .Parameters.Add(New OleDbParameter("@ProductName", OleDbType.VarChar, 255, prod_name))
                    .Parameters.Add(New OleDbParameter("@Quantity", OleDbType.VarChar, 255, prod_quantity))
                    .Parameters.Add(New OleDbParameter("@PriceEach", OleDbType.VarChar, 255, price_each))
                    .Parameters.Add(New OleDbParameter("@TotalPrice", OleDbType.VarChar, 255, price_each))
                    .Parameters.Add(New OleDbParameter("@Username", OleDbType.VarChar, 255, txtUsername.Text))
                    prod_list = New List(Of String)

                    cm.Parameters("@ProductName").Value = prod_name
                    cm.Parameters("@Quanity").Value = prod_quantity
                    cm.Parameters("@PriceEach").Value = price_each
                    cm.Parameters("@TotalPrice").Value =
                    cm.Parameters("@Username").Value = txtUsername.Text

                    cm.ExecuteNonQuery()
                    MsgBox("Record saved.", MsgBoxStyle.Information)
                    cmboxProduct.SelectedItem = ""
                    txtQuantity.Text = ListBoxCart.Text = ""

                    Exit Sub
                End With
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
            End Try

        Next

    End Sub

    Private Sub btnClearCart_Click(sender As Object, e As EventArgs) Handles btnClearCart.Click

        ListBoxCart.Items.Clear()

    End Sub

    Private Sub cmboxProduct_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmboxProduct.SelectedIndexChanged

        If cmboxProduct.SelectedItem = "iPad Case" Then
            txtPriceEach.Text = iPadCasePrice
        End If

        If cmboxProduct.SelectedItem = "iPad 2" Then
            txtPriceEach.Text = iPad2Price
        End If

    End Sub
End Class
</code>```

答:
First Add a property for the total

```<code>Dim Total As Decimal
</code>```

Then modify the btnAddToCart_Click and btnClearCart_Click to update it(I assume the name of the text box showing total is txtTotal)

```<code>Private Sub btnAddToCart_Click(sender As Object, e As EventArgs) Handles btnAddToCart.Click
    If cmboxProduct.SelectedItem = "" Or txtQuantity.Text = "" Then
        MsgBox("Please fill out all required fields", MsgBoxStyle.OkOnly, "Invalid entered data")
    Else
        ListBoxCart.Items.Add("x" & txtQuantity.Text & " " & cmboxProduct.SelectedItem & " " & txtPriceEach.Text)

        Dim q = Decimal.Parse(txtQuantity.Text)
        Dim p = Decimal.Parse(txtPriceEach.Text.Remove(0, 1)) 'need to remove the $ before parse
        Total += p * q
        txtTotal.Text = String.Format("${0}", Total)

        'txtShoppingCart.AppendText("x" & txtQuantity.Text & " " & Product1 & Environment.NewLine)
    End If
End Sub

Private Sub btnClearCart_Click(sender As Object, e As EventArgs) Handles btnClearCart.Click

    ListBoxCart.Items.Clear()
    Total = 0
    txtTotal.Text = String.Empty

End Sub
</code>```

Body:
So I am making a program in which you can select products from a combo box, select the quantity and it will return with the price and the quantity in a list box.

However, I want to be able to multiply the price of a product in each line by the quantity, then add up all of the lines cost to figure out a "total cost". How would I be able to do it?

Here is the form:

TL;DR How to multiply the price of a product for each line, then add up all of the total prices in each line. Thank you heaps!!

Here is my code: IGNORE OLEDB PART - SOME OF THE NAMING IS INCORRECT AS IT IS A WIP

Imports System.Data.OleDb
Public Class frmOrderProduct
    Dim iPadCasePrice As String
    Dim iPad2Price As String
    Dim prod_list As List(Of String)

    Private Sub frmOrderProduct_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        cmboxProduct.Items.Add("iPad Case")
        cmboxProduct.Items.Add("iPad 2")

        iPadCasePrice = "$20.00"
        iPad2Price = "$200.00"

        txtUsername.Text = frmLogin.txtUsername.Text

    End Sub

    Private Sub btnAddToCart_Click(sender As Object, e As EventArgs) Handles btnAddToCart.Click

        If cmboxProduct.SelectedItem = "" Or txtQuantity.Text = "" Then
            MsgBox("Please fill out all required fields", MsgBoxStyle.OkOnly, "Invalid entered data")
        Else
            ListBoxCart.Items.Add("x" & txtQuantity.Text & " " & cmboxProduct.SelectedItem & " " & txtPriceEach.Text)

            'txtShoppingCart.AppendText("x" & txtQuantity.Text & " " & Product1 & Environment.NewLine)
        End If
    End Sub

    Private Sub txtQuantity_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles txtQuantity.KeyPress

        If Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
                e.Handled = True
            End If
        End If

    End Sub

    Private Sub btnOrderProducts_Click(sender As Object, e As EventArgs) Handles btnOrderProducts.Click

        Dim numberOfItems = ListBoxCart.Items.Count
        For Each item As String In ListBoxCart.Items

            Try

                cm = New OleDbCommand
                With cm
                    .Connection = cn
                    .CommandType = CommandType.Text
                    .CommandText = "INSERT INTO tblOrders ([ProductName],[Quantity],[PriceEach],[TotalPrice],[Username]) VALUES (@ProductName,@Quantity,@PriceEach,@TotalPrice,@Username)"

                    prod_list = item.Split(" ").ToList
                    Dim prod_name = prod_list.ElementAt(1)
                    Dim prod_quantity = Integer.Parse(prod_list.ElementAt(0).Remove("x"))
                    Dim price_each = prod_list.ElementAt(2)

                    .Parameters.Add(New OleDbParameter("@ProductName", OleDbType.VarChar, 255, prod_name))
                    .Parameters.Add(New OleDbParameter("@Quantity", OleDbType.VarChar, 255, prod_quantity))
                    .Parameters.Add(New OleDbParameter("@PriceEach", OleDbType.VarChar, 255, price_each))
                    .Parameters.Add(New OleDbParameter("@TotalPrice", OleDbType.VarChar, 255, price_each))
                    .Parameters.Add(New OleDbParameter("@Username", OleDbType.VarChar, 255, txtUsername.Text))
                    prod_list = New List(Of String)

                    cm.Parameters("@ProductName").Value = prod_name
                    cm.Parameters("@Quanity").Value = prod_quantity
                    cm.Parameters("@PriceEach").Value = price_each
                    cm.Parameters("@TotalPrice").Value =
                    cm.Parameters("@Username").Value = txtUsername.Text

                    cm.ExecuteNonQuery()
                    MsgBox("Record saved.", MsgBoxStyle.Information)
                    cmboxProduct.SelectedItem = ""
                    txtQuantity.Text = ListBoxCart.Text = ""

                    Exit Sub
                End With
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
            End Try

        Next

    End Sub

    Private Sub btnClearCart_Click(sender As Object, e As EventArgs) Handles btnClearCart.Click

        ListBoxCart.Items.Clear()

    End Sub

    Private Sub cmboxProduct_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmboxProduct.SelectedIndexChanged

        If cmboxProduct.SelectedItem = "iPad Case" Then
            txtPriceEach.Text = iPadCasePrice
        End If

        If cmboxProduct.SelectedItem = "iPad 2" Then
            txtPriceEach.Text = iPad2Price
        End If

    End Sub
End Class

Body:
First Add a property for the total

Dim Total As Decimal

Then modify the btnAddToCart_Click and btnClearCart_Click to update it(I assume the name of the text box showing total is txtTotal)

Private Sub btnAddToCart_Click(sender As Object, e As EventArgs) Handles btnAddToCart.Click
    If cmboxProduct.SelectedItem = "" Or txtQuantity.Text = "" Then
        MsgBox("Please fill out all required fields", MsgBoxStyle.OkOnly, "Invalid entered data")
    Else
        ListBoxCart.Items.Add("x" & txtQuantity.Text & " " & cmboxProduct.SelectedItem & " " & txtPriceEach.Text)

        Dim q = Decimal.Parse(txtQuantity.Text)
        Dim p = Decimal.Parse(txtPriceEach.Text.Remove(0, 1)) 'need to remove the $ before parse
        Total += p * q
        txtTotal.Text = String.Format("${0}", Total)

        'txtShoppingCart.AppendText("x" & txtQuantity.Text & " " & Product1 & Environment.NewLine)
    End If
End Sub

Private Sub btnClearCart_Click(sender As Object, e As EventArgs) Handles btnClearCart.Click

    ListBoxCart.Items.Clear()
    Total = 0
    txtTotal.Text = String.Empty

End Sub


问:
Post json to server in regular intervals in plan javascript
I am building a javascript plugin that a client will include in his. The plugin will track data user activity like page scroll, button clicks  mouse movements etc and then save to web storage. This data then need to be send to a back end server at regular intervals of say 5-10 seconds in json format.

If I use a simple ajax for sending data by using setInterval method
will that impact user browsing experience.?

Will using websockets make more sense in this case or is there any other way?

NOTE: The backend server application is based on Spring MVC and the javascript plugin will push data to server externallly from clients application.

答:
If you really wanted minimal impact on the UI thread, you could spawn a WebWorker and do the AJAX requests from there.

Here is a good answer explaining AJAX requests in the context of a WebWorker.
Here is another short example of implementing AJAX in a WebWorker.


问:
Protobuf-net on UWP/.NET Native and iOS
I have a Xamarin.Forms App based on .NET Standard 1.4 that uses protobuf-net to store objects in the database that will be sent to a WCF service at a later time.

On Android and UWP "managed" everything works fine but - after searching through repositories, articles and blogposts that can no longer be accessed, and also after trying to get the precompilation tool to work, but failing at that - I have one simple (probably not) question: How do I get protobuf-net to work in "restricted" environments like UWP/.NET Native and iOS/Xamarin?

答:
Right now I don't have a great solution for this scenario. I know some people have made it work, but I'm not expert enough in UWP / Native / iOS to give you reliable "here's the path to success" instructions.

UWP / .NET Native and iOS share (as you know) a common issue: lack of full runtime emit. I understand why this is. It is just: tricky.

Historically, protobuf-net has tried to solve this problem via a build tool that repeated the existing IL-emit usually done at runtime - as a build-time tool. This was ugly and nasty, but it worked. Kind of. To hack around some platform restrictions, protobuf-net used some of the IKVM tooling to help with this, but as the .NET framework scene has continued to expand this is basically not viable. Plus: the IKVM tool is now abandoned and won't be being maintained.

In parallel with this, there is increasing impetus to investigate some newer concepts:

full async/await for asynchronous IO sources: note that this is extremely unfriendly to IL emit, but is almost embarrassingly easy to implement in C#

"pipelines" / "channels" / "streams 2" - whatever it is being called this week; but: the new allocation-free IO concept that is being used in Kestrel (I helped kick this ball around a little bit when it was in the early stages, so I'm familiar with what needs doing) - note that this also ties into async/await

and of course: how all of the above relates to pre-generation

Right now, I'm very much of the opinion that the best route forward is for the pre-gen scenario to switch to emitting C# via build-time tooling. I have repeatedly petitioned MS for improved automated C# emit based on Roslyn, but so far: no joy (vexingly: the asp.net stuff even had a fully working proof-of-concept, but it is shelved). So right now I'm thinking: we need to assume that isn't going to happen, and basically write it independently. This isn't necessarily as complex as it sounds (and: codegen of various forms is very familiar to me). The advantage of C# emit here is that I don't need to fight the intricacies of every framework - I just need to make it compile (well, and run, obviously).

So: what's holding me back? In theory: nothing. I just need to get this stuff written and deployed. In reality: life, time, etc. I am guilty of prioritising things that impact me daily, and the reality is that I'm not really a daily user of those platforms, which means I'm not feeling the pain that you're feeling. But: I hear you loud and clear, and I am trying to ramp up the v3 work that should address these points. I genuinely want to have a good story for those things - and my aim is that by moving to a C#-emit model (for pre-gen, at least): it helps me. And if it helps me I know it won't be the forgotten toy in the attic / basement that I know is there but which it is hard to find the motivation to go to the trouble of finding.

Title: Protobuf-net on UWP/.NET Native and iOS


问:
Angular 2 type script define error
When define response data to array, error occured:

```<code>public esriLocation = [];
public testLocation  = [];

 this.service.getData().subscribe(
                  (response) => this.esriLocation = response.json(),
                  (error) => console.log('ESRI ERROR: ' + error)
          );

          this.testLocation = this.esriLocation.suggestions;
</code>```

Property 'suggestions' does not exisits on type 'any'

Responce

```<code>{
    "suggestions": [{
        "text": "DEU",
        "key": "dHA9MCNsb2M9MTAzOTkwNTEjbG5nPTQ0I2xicz0xMDk6NDI2MDI4NzM=",
        "isCollection": false
    }, {
        "text": "ENG",
        "key": "dHA9MCNsb2M9MTA0MDAzOTcjbG5nPTQ0I2xicz0xMDk6NDI2MDI4NzU=",
        "isCollection": false
    }]
}
</code>```

How to fix?

答:
It is async by nature you need to do the assignment inside the success call back.

```<code>public esriLocation = [];
public testLocation  = [];

 this.service.getData().subscribe(
                  (response) => {this.esriLocation = response.json()
                                 this.testLocation = this.esriLocation.suggestions;
                           },
                  (error) => console.log('ESRI ERROR: ' + error)
          );
</code>```

as it is async by nature you cannot guarantee that the result will be available after the subscribe block, if it is available and you find it not assigned properly check if you are getting a JSON object not the string.

Title: Angular 2 type script define error

Body:
When define response data to array, error occured:

public esriLocation = [];
public testLocation  = [];

 this.service.getData().subscribe(
                  (response) => this.esriLocation = response.json(),
                  (error) => console.log('ESRI ERROR: ' + error)
          );

          this.testLocation = this.esriLocation.suggestions;

Property 'suggestions' does not exisits on type 'any'

Responce

{
    "suggestions": [{
        "text": "DEU",
        "key": "dHA9MCNsb2M9MTAzOTkwNTEjbG5nPTQ0I2xicz0xMDk6NDI2MDI4NzM=",
        "isCollection": false
    }, {
        "text": "ENG",
        "key": "dHA9MCNsb2M9MTA0MDAzOTcjbG5nPTQ0I2xicz0xMDk6NDI2MDI4NzU=",
        "isCollection": false
    }]
}

How to fix?

Body:
It is async by nature you need to do the assignment inside the success call back.

public esriLocation = [];
public testLocation  = [];

 this.service.getData().subscribe(
                  (response) => {this.esriLocation = response.json()
                                 this.testLocation = this.esriLocation.suggestions;
                           },
                  (error) => console.log('ESRI ERROR: ' + error)
          );

as it is async by nature you cannot guarantee that the result will be available after the subscribe block, if it is available and you find it not assigned properly check if you are getting a JSON object not the string.


问:
using jquery to load json
I have a variable on a page like this:

var userdetails = "{ 'id': '1',
  'username': 'me', }";

now, I wanna call a function to load those id and username in some divs
like this one:

loaduser(userdetails)

I used this but didn't work

function loaduser(jsoni){

$.getJSON(jsoni, function(data) {
        $('#id').html(data.id);
        $('#username').html(data.username);
    }
  }

thank u guys ;)

答:
Use jQuery.parseJSON. Your example won't work though because it is not valid JSON (valid JSON requires double instead of single quotation marks):</p>

```<code>var userdetails = '{ "id": 1, "username": "me", }';
</code>```

Title: using jquery to load json

Body:
Use jQuery.parseJSON. Your example won't work though because it is not valid JSON (valid JSON requires double instead of single quotation marks):

var userdetails = '{ "id": 1, "username": "me", }';


问:
css active class not working for Tabs
Could you help me with this please ?

css active class not working for Tabs

Demo: http://dev.ktimes.co/was20378/tab/index-nw2.html

CSS

```<code>.filter-button
{
        padding: 6px 20px;
    font-size: 18px;
    border: 1px solid #fd0009;
    border-radius: 20px;
    text-align: center;
    color: #fd0009;
    margin-bottom: 30px;

}
.filter-button:hover, .filter-button.active
{
    font-size: 18px;
    border: 1px solid #fd0009;
   border-radius: 20px;
    text-align: center;
    color: #ffffff;
    background-color: #fd0009;

}
.btn-default.filter-button.active {
    background-color: #fd0009 !important;
    color: #FFF !important;
}
</code>```

答: .active is not getting added to .filter-button class try checking your script for issues

Title: css active class not working for Tabs

Body:
Could you help me with this please ?

css active class not working for Tabs

Demo: http://dev.ktimes.co/was20378/tab/index-nw2.html

CSS

.filter-button
{
        padding: 6px 20px;
    font-size: 18px;
    border: 1px solid #fd0009;
    border-radius: 20px;
    text-align: center;
    color: #fd0009;
    margin-bottom: 30px;

}
.filter-button:hover, .filter-button.active
{
    font-size: 18px;
    border: 1px solid #fd0009;
   border-radius: 20px;
    text-align: center;
    color: #ffffff;
    background-color: #fd0009;

}
.btn-default.filter-button.active {
    background-color: #fd0009 !important;
    color: #FFF !important;
}


问:
MongoDB drop collection, name start with backquote
There is a collection in my MongoDB that im not able to drop.
The name of the collection ends with a ` (backquote) character and I got error when executing the drop command.

```<code>db.MyCollection`.drop()
</code>```

Error is

```<code>2017-12-07T07:42:35.711+0000 SyntaxError: Unexpected token ILLEGAL
</code>```

Is there any other way of removing or is it here forever?

答:
Just use getCollection function.

Example:

```<code>db.getCollection("MyCollection`").drop();
</code>```

Body:
There is a collection in my MongoDB that im not able to drop.
The name of the collection ends with a ` (backquote) character and I got error when executing the drop command.

db.MyCollection`.drop()

Error is

2017-12-07T07:42:35.711+0000 SyntaxError: Unexpected token ILLEGAL

Is there any other way of removing or is it here forever?

Body:
Just use getCollection function.

Example:

db.getCollection("MyCollection`").drop();


问:
Unwanted behavior when scrolling on mobile devices (add / remove classes based on viewport size)
My code adds or removes classes based on the viewport size. Everything works fine on the desktop version. Even when resize the browser window, everything works fine. However, I have the following problem on mobile devices (for example iPhone - Safari):

If I open the readmoresection, it closes again as soon as I scroll the page up or down (sometimes only after a few seconds). What can this behavior be and why does it work in the desktop version but not on mobile devices?

Here is my code:

HTML Template:

```<code><div class="description" >
    <h2 class="sectionheading">Information for <?= $entry->field('title')->value() ?></h2>
    <div class="readmore readmoresection" itemprop="description"><?= $entry->field('description')->value() ?></div>
</div>
</code>```

jQuery:

```<code>function onResizeReadMoreLayout(){
    if ($(window).width() <= 900) {
                $('.readmoresection span.handler').show();
                $('.readmoresection').addClass('reduced');
                if($('.readmoresection').hasClass('reduced')){
                    $('.readmoresection span.handler').html(' » Weiterlesen');
                }else{
                    $('.readmoresection span.handler').html(' » Schließen');
                    $('.readmoresection').removeClass('reduced');
                }
            }
            else{
                $('.readmoresection span.handler').hide();
                $('.readmoresection').removeClass('reduced');
        }
}

// initial state
 onResizeReadMoreLayout();
 // on resize
 $(window).on('resize', onResizeReadMoreLayout);
</code>```

Here is the working live version: CLICK. Check out the read more functionality after the headline "INFORMATIONEN ZUM FERNSTUDIUM FITNESS C-LIZENZ"

答:
The readmore section closes as soon as you scroll up on iOS because the address bar changes height and/or bottom action bar appears, thus causing a window resize. However, here is another proposed solution that is based purely on CSS, so not only will you avoid your issue, but avoid unnecessary bloat from your Javascript.

Here is the proposed solution. I tried to use similar classes with your code so that it makes more sense.

Also, as a side-note, whenever possible try to reduce Javascript listeners to a minimum for performance reasons, especially ones like resize or scroll.

Last, but not least, depending on the browser and the browser scrollbar type, $(window).width() is prone to producing different results - aka 900px versus 900px + scrollbar width.

HTML:

```<code><div class="readmoresection">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis id consectetur purus ut faucibus pulvinar elementum. Gravida neque convallis a cras semper auctor neque vitae. Magna sit
    amet purus gravida quis blandit. Dignissim cras tincidunt lobortis feugiat vivamus at. Leo a diam sollicitudin tempor. Consectetur adipiscing elit ut aliquam purus sit amet luctus. Nisl purus in mollis nunc sed id. Auctor elit sed vulputate mi sit
    amet. Quam elementum pulvinar etiam non. Ultricies mi eget mauris pharetra et ultrices neque ornare aenean. Eget felis eget nunc lobortis mattis aliquam. Feugiat sed lectus vestibulum mattis ullamcorper velit sed ullamcorper. Faucibus ornare suspendisse
    sed nisi lacus. Amet mauris commodo quis imperdiet massa tincidunt nunc. Dolor sit amet consectetur adipiscing elit. Fames ac turpis egestas sed tempus. Egestas tellus rutrum tellus pellentesque.
  </p>
  <p class="content-hidden">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis id consectetur purus ut faucibus pulvinar elementum. Gravida neque convallis a cras semper auctor neque vitae. Magna sit
    amet purus gravida quis blandit. Dignissim cras tincidunt lobortis feugiat vivamus at. Leo a diam sollicitudin tempor. Consectetur adipiscing elit ut aliquam purus sit amet luctus. Nisl purus in mollis nunc sed id. Auctor elit sed vulputate mi sit
    amet. Quam elementum pulvinar etiam non. Ultricies mi eget mauris pharetra et ultrices neque ornare aenean. Eget felis eget nunc lobortis mattis aliquam. Feugiat sed lectus vestibulum mattis ullamcorper velit sed ullamcorper. Faucibus ornare suspendisse
    sed nisi lacus. Amet mauris commodo quis imperdiet massa tincidunt nunc. Dolor sit amet consectetur adipiscing elit. Fames ac turpis egestas sed tempus. Egestas tellus rutrum tellus pellentesque.
  </p>
  <span class="handler"><span class="handler-opened">Toggle close</span><span class="handler-hidden">Toggle open</span></span>
</div>
</code>```

CSS:

```<code>@media (max-width:900px) {
  .content-hidden {
    display: none;
  }
  .handler-opened {
    display: none;
  }
  .opened .handler-opened {
    display: block;
  }
  .opened .handler-hidden {
    display: none;
  }
  .opened .content-hidden {
    display: block;
  }
}

@media (min-width:901px) {
  .content-hidden {
    display: block !important;
  }
  .handler {
    display: none;
  }
}
</code>```

Javasript:

```<code>$('.readmoresection').on('click', 'span.handler', function() {
  $(this).closest('.readmoresection').toggleClass('opened');
});
</code>```

And here is a working fiddle: https://jsfiddle.net/scooterlord/dLjygyrj/

Body:
My code adds or removes classes based on the viewport size. Everything works fine on the desktop version. Even when resize the browser window, everything works fine. However, I have the following problem on mobile devices (for example iPhone - Safari):

If I open the readmoresection, it closes again as soon as I scroll the page up or down (sometimes only after a few seconds). What can this behavior be and why does it work in the desktop version but not on mobile devices?

Here is my code:

HTML Template:

Information for <?= $entry->field('title')->value() ?>

<?= $entry->field('description')->value() ?>

jQuery:

function onResizeReadMoreLayout(){
    if ($(window).width() <= 900) {
                $('.readmoresection span.handler').show();
                $('.readmoresection').addClass('reduced');
                if($('.readmoresection').hasClass('reduced')){
                    $('.readmoresection span.handler').html(' » Weiterlesen');
                }else{
                    $('.readmoresection span.handler').html(' » Schließen');
                    $('.readmoresection').removeClass('reduced');
                }
            }
            else{
                $('.readmoresection span.handler').hide();
                $('.readmoresection').removeClass('reduced');
        }
}

// initial state
 onResizeReadMoreLayout();
 // on resize
 $(window).on('resize', onResizeReadMoreLayout);

Here is the working live version: CLICK. Check out the read more functionality after the headline "INFORMATIONEN ZUM FERNSTUDIUM FITNESS C-LIZENZ"

Body:
The readmore section closes as soon as you scroll up on iOS because the address bar changes height and/or bottom action bar appears, thus causing a window resize. However, here is another proposed solution that is based purely on CSS, so not only will you avoid your issue, but avoid unnecessary bloat from your Javascript.

Here is the proposed solution. I tried to use similar classes with your code so that it makes more sense.

Also, as a side-note, whenever possible try to reduce Javascript listeners to a minimum for performance reasons, especially ones like resize or scroll.

Last, but not least, depending on the browser and the browser scrollbar type, $(window).width() is prone to producing different results - aka 900px versus 900px + scrollbar width.

HTML:

<div class="readmoresection">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis id consectetur purus ut faucibus pulvinar elementum. Gravida neque convallis a cras semper auctor neque vitae. Magna sit
    amet purus gravida quis blandit. Dignissim cras tincidunt lobortis feugiat vivamus at. Leo a diam sollicitudin tempor. Consectetur adipiscing elit ut aliquam purus sit amet luctus. Nisl purus in mollis nunc sed id. Auctor elit sed vulputate mi sit
    amet. Quam elementum pulvinar etiam non. Ultricies mi eget mauris pharetra et ultrices neque ornare aenean. Eget felis eget nunc lobortis mattis aliquam. Feugiat sed lectus vestibulum mattis ullamcorper velit sed ullamcorper. Faucibus ornare suspendisse
    sed nisi lacus. Amet mauris commodo quis imperdiet massa tincidunt nunc. Dolor sit amet consectetur adipiscing elit. Fames ac turpis egestas sed tempus. Egestas tellus rutrum tellus pellentesque.
  </p>
  <p class="content-hidden">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis id consectetur purus ut faucibus pulvinar elementum. Gravida neque convallis a cras semper auctor neque vitae. Magna sit
    amet purus gravida quis blandit. Dignissim cras tincidunt lobortis feugiat vivamus at. Leo a diam sollicitudin tempor. Consectetur adipiscing elit ut aliquam purus sit amet luctus. Nisl purus in mollis nunc sed id. Auctor elit sed vulputate mi sit
    amet. Quam elementum pulvinar etiam non. Ultricies mi eget mauris pharetra et ultrices neque ornare aenean. Eget felis eget nunc lobortis mattis aliquam. Feugiat sed lectus vestibulum mattis ullamcorper velit sed ullamcorper. Faucibus ornare suspendisse
    sed nisi lacus. Amet mauris commodo quis imperdiet massa tincidunt nunc. Dolor sit amet consectetur adipiscing elit. Fames ac turpis egestas sed tempus. Egestas tellus rutrum tellus pellentesque.
  </p>
  <span class="handler"><span class="handler-opened">Toggle close</span><span class="handler-hidden">Toggle open</span></span>
</div>

CSS:

@media (max-width:900px) {
  .content-hidden {
    display: none;
  }
  .handler-opened {
    display: none;
  }
  .opened .handler-opened {
    display: block;
  }
  .opened .handler-hidden {
    display: none;
  }
  .opened .content-hidden {
    display: block;
  }
}

@media (min-width:901px) {
  .content-hidden {
    display: block !important;
  }
  .handler {
    display: none;
  }
}

Javasript:

$('.readmoresection').on('click', 'span.handler', function() {
  $(this).closest('.readmoresection').toggleClass('opened');
});

And here is a working fiddle: https://jsfiddle.net/scooterlord/dLjygyrj/


问:
Using Apache Spark's Time class/type

Note: I am using Spark 2.2.0. I am getting an error when trying to run my Scala code from my Zeppelin notebook

```<code>%spark
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.streaming.{Time, Seconds, StreamingContext}
...
...
case class Record(time: Time, topic: String, count: Integer)
...
...
</code>```

import org.apache.spark.streaming.{Time, Seconds, StreamingContext} should allow me to use Time

When I try to run the paragraph/block in Zeppelin, I am getting this error:

<console>:12: error: not found: type Time

case class Record(time: Time, topic: String, count: Integer)

What could the issue be? Is Time deprecated or something in Spark 2? Any alternative to Time?

答: In general, when using Spark SQL or Spark Structured Streaming, I can recommend sticking to java.sql.Timestamp and java.sql.Date: they are fully integrated with the ecosystems, meaning you won't need custom serializers and there are very nice built-in functions (look them up in the Date functions section) that you can use.

Title: Using Apache Spark's Time class/type

Body:
Note: I am using Spark 2.2.0. I am getting an error when trying to run my Scala code from my Zeppelin notebook

%spark
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.streaming.{Time, Seconds, StreamingContext}
...
...
case class Record(time: Time, topic: String, count: Integer)
...
...

import org.apache.spark.streaming.{Time, Seconds, StreamingContext} should allow me to use Time

When I try to run the paragraph/block in Zeppelin, I am getting this error:

<console>:12: error: not found: type Time

case class Record(time: Time, topic: String, count: Integer)

What could the issue be? Is Time deprecated or something in Spark 2? Any alternative to Time?


问:
Android Force Close on ProgressDialog
I am attempting to show an indeterminate ProgressDialog while grabbing an RSS feed.  I get the dialog to pop, but as soon as the results are returned, I get a force close.  My suspicion is that the adapter is populated and goes to update the UI.  The code is below.  Is my suspicion correct?

```<code>        public void getRSS(String rss)
    {

        new GetRSS().execute(rss);

    }
    private class GetRSS extends AsyncTask<String, Void, Void>
    {
        private ProgressDialog Dialog = new ProgressDialog(View2.this);

        protected void onPreExecute() {

            Dialog.setMessage("Please wait...");
            Dialog.show();
        }

        protected void onPostExecute(Void nothing)
        {
            Dialog.dismiss();
        }

        protected Void doInBackground(String... rss) {
        URL feedUrl;
        try
            {
                feedUrl = new URL(rss[0]);

                SyndFeedInput input = new SyndFeedInput();
                SyndFeed feed = input.build(new XmlReader(feedUrl));
                List entries = feed.getEntries();

                Iterator iterator = entries.listIterator();
                while (iterator.hasNext())
                    {
                        SyndEntry ent = (SyndEntry) iterator.next();
                        String title = ent.getTitle();
                        //String uri = ent.getUri();
                        //d.add(uri);

                        SyndContent content = (SyndContent)ent.getContents().get(0);
                        d.add(content.getValue());
                        adapter.add(title);
                    }
                adapter.notifyDataSetChanged();
            }
        catch (MalformedURLException e)
            {
                e.printStackTrace();
            }
        catch (IllegalArgumentException e)
            {
                e.printStackTrace();
            }
        catch (FeedException e)
            {
                e.printStackTrace();
            }
        catch (IOException e)
            {
                e.printStackTrace();
            }
        return null;
        }
    }
    */
</code>```

Here's the stack dump -- clearly the call to notify is the issue.  Now I'm just having trouble figuring out where to call notify:

```<code>01-22 12:02:28.701: ERROR/WindowManager(571): Activity com.digthisband.dtb.jg.View2 has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@43e6ae88 that was originally added here
</code>```

01-22 12:02:28.701: ERROR/WindowManager(571): android.view.WindowLeaked: Activity com.digthisband.dtb.jg.View2 has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@43e6ae88 that was originally added here
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.view.ViewRoot.(ViewRoot.java:247)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.Dialog.show(Dialog.java:241)
01-22 12:02:28.701: ERROR/WindowManager(571):     at com.digthisband.dtb.jg.View2$GetRSS.onPreExecute(View2.java:97)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.os.AsyncTask.execute(AsyncTask.java:391)
01-22 12:02:28.701: ERROR/WindowManager(571):     at com.digthisband.dtb.jg.View2.getRSS(View2.java:87)
01-22 12:02:28.701: ERROR/WindowManager(571):     at com.digthisband.dtb.jg.View2.onCreate(View2.java:68)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.os.Looper.loop(Looper.java:123)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.ActivityThread.main(ActivityThread.java:4627)
01-22 12:02:28.701: ERROR/WindowManager(571):     at java.lang.reflect.Method.invokeNative(Native Method)
01-22 12:02:28.701: ERROR/WindowManager(571):     at java.lang.reflect.Method.invoke(Method.java:521)
01-22 12:02:28.701: ERROR/WindowManager(571):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-22 12:02:28.701: ERROR/WindowManager(571):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-22 12:02:28.701: ERROR/WindowManager(571):     at dalvik.system.NativeStart.main(Native Method)

答:
It would be best if you could show the error LogCat, it will say what caused the Exception.
I also noticed you were calling notifyDataSetChanged() in the doInBackground method- you should call this only in the UI thread.</p>

Title: Android Force Close on ProgressDialog

Body:
I am attempting to show an indeterminate ProgressDialog while grabbing an RSS feed.  I get the dialog to pop, but as soon as the results are returned, I get a force close.  My suspicion is that the adapter is populated and goes to update the UI.  The code is below.  Is my suspicion correct?

        public void getRSS(String rss)
    {

        new GetRSS().execute(rss);

    }
    private class GetRSS extends AsyncTask<String, Void, Void>
    {
        private ProgressDialog Dialog = new ProgressDialog(View2.this);

        protected void onPreExecute() {

            Dialog.setMessage("Please wait...");
            Dialog.show();
        }

        protected void onPostExecute(Void nothing)
        {
            Dialog.dismiss();
        }

        protected Void doInBackground(String... rss) {
        URL feedUrl;
        try
            {
                feedUrl = new URL(rss[0]);

                SyndFeedInput input = new SyndFeedInput();
                SyndFeed feed = input.build(new XmlReader(feedUrl));
                List entries = feed.getEntries();

                Iterator iterator = entries.listIterator();
                while (iterator.hasNext())
                    {
                        SyndEntry ent = (SyndEntry) iterator.next();
                        String title = ent.getTitle();
                        //String uri = ent.getUri();
                        //d.add(uri);

                        SyndContent content = (SyndContent)ent.getContents().get(0);
                        d.add(content.getValue());
                        adapter.add(title);
                    }
                adapter.notifyDataSetChanged();
            }
        catch (MalformedURLException e)
            {
                e.printStackTrace();
            }
        catch (IllegalArgumentException e)
            {
                e.printStackTrace();
            }
        catch (FeedException e)
            {
                e.printStackTrace();
            }
        catch (IOException e)
            {
                e.printStackTrace();
            }
        return null;
        }
    }
    */

Here's the stack dump -- clearly the call to notify is the issue.  Now I'm just having trouble figuring out where to call notify:

01-22 12:02:28.701: ERROR/WindowManager(571): Activity com.digthisband.dtb.jg.View2 has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@43e6ae88 that was originally added here

01-22 12:02:28.701: ERROR/WindowManager(571): android.view.WindowLeaked: Activity com.digthisband.dtb.jg.View2 has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@43e6ae88 that was originally added here
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.view.ViewRoot.(ViewRoot.java:247)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.Dialog.show(Dialog.java:241)
01-22 12:02:28.701: ERROR/WindowManager(571):     at com.digthisband.dtb.jg.View2$GetRSS.onPreExecute(View2.java:97)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.os.AsyncTask.execute(AsyncTask.java:391)
01-22 12:02:28.701: ERROR/WindowManager(571):     at com.digthisband.dtb.jg.View2.getRSS(View2.java:87)
01-22 12:02:28.701: ERROR/WindowManager(571):     at com.digthisband.dtb.jg.View2.onCreate(View2.java:68)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.os.Looper.loop(Looper.java:123)
01-22 12:02:28.701: ERROR/WindowManager(571):     at android.app.ActivityThread.main(ActivityThread.java:4627)
01-22 12:02:28.701: ERROR/WindowManager(571):     at java.lang.reflect.Method.invokeNative(Native Method)
01-22 12:02:28.701: ERROR/WindowManager(571):     at java.lang.reflect.Method.invoke(Method.java:521)
01-22 12:02:28.701: ERROR/WindowManager(571):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-22 12:02:28.701: ERROR/WindowManager(571):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-22 12:02:28.701: ERROR/WindowManager(571):     at dalvik.system.NativeStart.main(Native Method)


问:
Python Code Chunk Graphs not showing up in R Markdown
I need to include Python code chunks in an R Markdown HTML. However, when I do so, the plot doesn't show up.

This is the code chunk I have which want to implement. I know this works in Python.

```<code>```{python, results='asis'}
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as rng
import matplotlib.cm as cm
from matplotlib.animation import FuncAnimation

radii=(rng.random(int(1e3))+1)**2
iota=2*np.pi*rng.random(int(1e3))
x_posit=np.sqrt(radii)*np.cos(iota)
y_posit=np.sqrt(radii)*np.sin(iota)
plt.plot(x_posit, y_posit, 'go')
```
</code>```

I expect to get a plot like this

But instead I get this, that is no graph in the R markdown Document. I'm knitting to HTML

答:
Install the library reticulate via install.packages("reticulate") and load this chunk before your code presented above:

```<code>```{r setup, include=FALSE}
library(knitr)
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
```

```{python}
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as rng
import matplotlib.cm as cm
from matplotlib.animation import FuncAnimation

radii=(rng.random(int(1e3))+1)**2
iota=2*np.pi*rng.random(int(1e3))
x_posit=np.sqrt(radii)*np.cos(iota)
y_posit=np.sqrt(radii)*np.sin(iota)
plt.plot(x_posit, y_posit, 'go')

plt.show()
```
</code>```

Note the plt.show() command.

This will produce your expected output!

Body:
I need to include Python code chunks in an R Markdown HTML. However, when I do so, the plot doesn't show up.

This is the code chunk I have which want to implement. I know this works in Python.

```{python, results='asis'}
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as rng
import matplotlib.cm as cm
from matplotlib.animation import FuncAnimation

radii=(rng.random(int(1e3))+1)**2
iota=2*np.pi*rng.random(int(1e3))
x_posit=np.sqrt(radii)*np.cos(iota)
y_posit=np.sqrt(radii)*np.sin(iota)
plt.plot(x_posit, y_posit, 'go')
```

I expect to get a plot like this

But instead I get this, that is no graph in the R markdown Document. I'm knitting to HTML

Body:
Install the library reticulate via install.packages("reticulate") and load this chunk before your code presented above:

```{r setup, include=FALSE}
library(knitr)
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
```

```{python}
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as rng
import matplotlib.cm as cm
from matplotlib.animation import FuncAnimation

radii=(rng.random(int(1e3))+1)**2
iota=2*np.pi*rng.random(int(1e3))
x_posit=np.sqrt(radii)*np.cos(iota)
y_posit=np.sqrt(radii)*np.sin(iota)
plt.plot(x_posit, y_posit, 'go')

plt.show()
```

Note the plt.show() command.

This will produce your expected output!