text:
Q: Socket.IO: Swift client connecting to Node.js server but server won't register connection? So I'm having an issue where my Swift/Xcode stuff is telling me I've connected to the server while my node file isn't telling me a 'user has connected' in terminal, this is sort of a repost but I didn't frame the original question well enough so it got no replies.
My node file looks like:
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;

app.use(express.static(__dirname + '/public'));

function onConnection(socket){
  console.log('a user connected');
  socket.on('disconnect', onDisconnection);
}

function onDisconnection(socket){
  console.log('a user disconnected');
}

io.on('connection', onConnection);

http.listen(port, () => console.log('listening on port ' + port));

My Swift looks like:
class PDSocketManager: NSObject {

class var shared: PDSocketManager {
    struct Static{
        static let instance = PDSocketManager()
    }
    return Static.instance
}

var socket: SocketIOClient?
fileprivate var manager: SocketManager?

fileprivate override init(){}

func establishConnection(_ completion: (() -> Void)? = nil) {
    let socketUrlString: String = "http://ip-address:3000"
    self.manager = SocketManager(socketURL: URL(string: socketUrlString)!, config: [.log(true), .reconnects(true), .extraHeaders(["header": "customheader"])])
    self.socket = manager?.defaultSocket
    self.socket?.connect()

    self.socket?.once(clientEvent: .connect, callback: { (data, emitter) in
        print("\n\n\n connection done!! \n\n\n")
        if completion != nil{
            completion!()
        }
    })
}

func connect()  {
    socket?.connect()
    print("socket connect")
}

func disconnect()  {
    socket?.disconnect()
}

func checkSocktConnect() -> Bool {
    if let myManager = self.manager{
        if myManager.status == SocketIOStatus.connected{
          return true
        } else {
            self.socket?.connect()
            return false
        }
    } else{
        return false
    }
    } }

This is the XCode log output:
2021-03-02 08:47:41.669119-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: statusChange with data: [connecting, 2]
2021-03-02 08:47:41.669315-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Joining namespace /
2021-03-02 08:47:41.669392-0500 sockettest[992:1229560] LOG SocketManager: Tried connecting socket when engine isn't open. Connecting
2021-03-02 08:47:41.669435-0500 sockettest[992:1229560] LOG SocketManager: Adding engine
2021-03-02 08:47:41.672334-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Adding once handler for event: connect
2021-03-02 08:47:41.672357-0500 sockettest[992:1229845] LOG SocketEngine: Starting engine. Server: http://ip-address:3000/
2021-03-02 08:47:41.672444-0500 sockettest[992:1229845] LOG SocketEngine: Handshaking
2021-03-02 08:47:41.697783-0500 sockettest[992:1229845] LOG SocketEnginePolling: Doing polling GET http://ip-address:3000/socket.io/?transport=polling&b64=1
2021-03-02 08:47:41.877242-0500 sockettest[992:1229843] LOG SocketEnginePolling: Got polling response
2021-03-02 08:47:41.877321-0500 sockettest[992:1229843] LOG SocketEnginePolling: Got poll message: 0{"sid":"jNuRNaYlTU1zFzXAAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
2021-03-02 08:47:41.879715-0500 sockettest[992:1229843] LOG SocketEngine: Got message: 0{"sid":"jNuRNaYlTU1zFzXAAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
2021-03-02 08:47:41.886369-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: ping with data: []
2021-03-02 08:47:41.886399-0500 sockettest[992:1229843] LOG SocketEnginePolling: Doing polling GET http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=jNuRNaYlTU1zFzXAAAAA
2021-03-02 08:47:41.886459-0500 sockettest[992:1229560] LOG SocketManager: Engine opened Connect
2021-03-02 08:47:41.886712-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Socket connected
2021-03-02 08:47:41.886870-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: statusChange with data: [connected, 3]
2021-03-02 08:47:41.887384-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: connect with data: ["/"]
2021-03-02 08:47:41.888137-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Removing handler with id: 05D5AFD6-5108-4EBB-A774-FB350D145FDA
2021-03-02 08:47:41.888195-0500 sockettest[992:1229843] LOG SocketEngine: Writing poll:  has data: false

 connection done!!

2021-03-02 08:47:41.888598-0500 sockettest[992:1229843] LOG SocketEnginePolling: Sending poll:  as type: 2
2021-03-02 08:47:41.888905-0500 sockettest[992:1229843] LOG SocketEnginePolling: Created POST string: 1:2
2021-03-02 08:47:41.889085-0500 sockettest[992:1229843] LOG SocketEnginePolling: POSTing
2021-03-02 08:47:41.889134-0500 sockettest[992:1229843] LOG SocketEnginePolling: Doing polling POST http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=jNuRNaYlTU1zFzXAAAAA
2021-03-02 08:47:41.900166-0500 sockettest[992:1229845] LOG SocketEngineWebSocket: Sending ws: probe as type: 2
2021-03-02 08:47:41.900316-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: websocketUpgrade with data: [["sec-websocket-accept": "3ydGn/18kSKfrJyp/ElciaZtQPI=", "upgrade": "websocket", "connection": "Upgrade"]]
2021-03-02 08:47:41.905261-0500 sockettest[992:1229840] LOG SocketEngine: Flushing probe wait
2021-03-02 08:47:41.906380-0500 sockettest[992:1229847] LOG SocketEnginePolling: Got polling response
2021-03-02 08:47:41.906615-0500 sockettest[992:1229847] LOG SocketEnginePolling: Doing polling GET http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=jNuRNaYlTU1zFzXAAAAA
2021-03-02 08:47:41.914247-0500 sockettest[992:1229845] ERROR SocketEnginePolling: Error during long poll request
2021-03-02 08:47:41.914306-0500 sockettest[992:1229845] ERROR SocketEngine: Error
2021-03-02 08:47:41.914378-0500 sockettest[992:1229560] ERROR SocketManager: Error
2021-03-02 08:47:41.914382-0500 sockettest[992:1229845] LOG SocketEngine: Engine is being closed.
2021-03-02 08:47:41.914430-0500 sockettest[992:1229845] LOG SocketEnginePolling: Created POST string: 1:1
2021-03-02 08:47:41.914436-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: error with data: ["Error"]
2021-03-02 08:47:41.914626-0500 sockettest[992:1229845] LOG SocketEnginePolling: Doing polling POST http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=jNuRNaYlTU1zFzXAAAAA
2021-03-02 08:47:41.915164-0500 sockettest[992:1229560] LOG SocketManager: Starting reconnect
2021-03-02 08:47:41.915268-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: statusChange with data: [connecting, 2]
2021-03-02 08:47:41.915373-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: reconnect with data: ["Error"]
2021-03-02 08:47:41.915468-0500 sockettest[992:1229560] LOG SocketManager: Trying to reconnect
2021-03-02 08:47:41.915559-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: reconnectAttempt with data: [-1]
2021-03-02 08:47:41.915747-0500 sockettest[992:1229844] LOG SocketEngine: Starting engine. Server: http://ip-address:3000/
2021-03-02 08:47:41.915920-0500 sockettest[992:1229844] LOG SocketEngine: Handshaking
2021-03-02 08:47:41.916043-0500 sockettest[992:1229844] LOG SocketEnginePolling: Doing polling GET http://ip-address:3000/socket.io/?transport=polling&b64=1
2021-03-02 08:47:41.916365-0500 sockettest[992:1229560] LOG SocketManager: Scheduling reconnect in 22.380244474166073s
2021-03-02 08:47:41.931050-0500 sockettest[992:1229845] LOG SocketEnginePolling: Got polling response
2021-03-02 08:47:41.931126-0500 sockettest[992:1229845] LOG SocketEnginePolling: Got poll message: 0{"sid":"GncBvYHRVuwBwT4qAAAB","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
2021-03-02 08:47:41.931198-0500 sockettest[992:1229845] LOG SocketEngine: Got message: 0{"sid":"GncBvYHRVuwBwT4qAAAB","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
2021-03-02 08:47:41.932181-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: ping with data: []
2021-03-02 08:47:41.932231-0500 sockettest[992:1229845] LOG SocketEnginePolling: Doing polling GET http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=GncBvYHRVuwBwT4qAAAB
2021-03-02 08:47:41.932235-0500 sockettest[992:1229560] LOG SocketManager: Engine opened Connect
2021-03-02 08:47:41.932271-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Socket connected
2021-03-02 08:47:41.932314-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: statusChange with data: [connected, 3]
2021-03-02 08:47:41.932393-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: connect with data: ["/"]
2021-03-02 08:47:41.932697-0500 sockettest[992:1229845] LOG SocketEngine: Writing poll:  has data: false
2021-03-02 08:47:41.932972-0500 sockettest[992:1229845] LOG SocketEnginePolling: Sending poll:  as type: 2
2021-03-02 08:47:41.933028-0500 sockettest[992:1229845] LOG SocketEnginePolling: Created POST string: 1:2
2021-03-02 08:47:41.933490-0500 sockettest[992:1229845] LOG SocketEnginePolling: POSTing
2021-03-02 08:47:41.933547-0500 sockettest[992:1229845] LOG SocketEnginePolling: Doing polling POST http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=GncBvYHRVuwBwT4qAAAB
2021-03-02 08:47:41.942594-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: websocketUpgrade with data: [["connection": "Upgrade", "upgrade": "websocket", "sec-websocket-accept": "pa1QhnQkCVWnN+kL1zMm+z0mEX4="]]
2021-03-02 08:47:41.942612-0500 sockettest[992:1229844] LOG SocketEngineWebSocket: Sending ws: probe as type: 2
2021-03-02 08:47:41.944832-0500 sockettest[992:1229840] LOG SocketEnginePolling: Got polling response
2021-03-02 08:47:41.945680-0500 sockettest[992:1229840] LOG SocketEnginePolling: Doing polling GET http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=GncBvYHRVuwBwT4qAAAB
2021-03-02 08:47:41.946001-0500 sockettest[992:1229840] LOG SocketEngine: Flushing probe wait
2021-03-02 08:47:41.951337-0500 sockettest[992:1229845] ERROR SocketEnginePolling: Error during long poll request
2021-03-02 08:47:41.951418-0500 sockettest[992:1229845] ERROR SocketEngine: Error
2021-03-02 08:47:41.951495-0500 sockettest[992:1229560] ERROR SocketManager: Error
2021-03-02 08:47:41.951551-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: error with data: ["Error"]
2021-03-02 08:47:41.951683-0500 sockettest[992:1229845] LOG SocketEngine: Engine is being closed.
2021-03-02 08:47:41.951744-0500 sockettest[992:1229845] LOG SocketEnginePolling: Created POST string: 1:1
2021-03-02 08:47:41.952027-0500 sockettest[992:1229845] LOG SocketEnginePolling: Doing polling POST http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=GncBvYHRVuwBwT4qAAAB
2021-03-02 08:47:41.952431-0500 sockettest[992:1229560] LOG SocketManager: Starting reconnect
2021-03-02 08:47:41.952545-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: statusChange with data: [connecting, 2]
2021-03-02 08:47:41.952657-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: reconnect with data: ["Error"]
2021-03-02 08:47:41.952759-0500 sockettest[992:1229560] LOG SocketManager: Trying to reconnect
2021-03-02 08:47:41.952856-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: reconnectAttempt with data: [-1]
2021-03-02 08:47:41.952988-0500 sockettest[992:1229560] LOG SocketManager: Scheduling reconnect in 17.378798001778488s
2021-03-02 08:47:41.953118-0500 sockettest[992:1229845] LOG SocketEngine: Starting engine. Server: http://ip-address:3000/
2021-03-02 08:47:41.953264-0500 sockettest[992:1229845] LOG SocketEngine: Handshaking
2021-03-02 08:47:41.953632-0500 sockettest[992:1229845] LOG SocketEnginePolling: Doing polling GET http://ip-address:3000/socket.io/?transport=polling&b64=1
2021-03-02 08:47:41.967543-0500 sockettest[992:1229843] LOG SocketEnginePolling: Got polling response
2021-03-02 08:47:41.967609-0500 sockettest[992:1229843] LOG SocketEnginePolling: Got poll message: 0{"sid":"dGUd1NjkROAspt3hAAAC","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
2021-03-02 08:47:41.967688-0500 sockettest[992:1229843] LOG SocketEngine: Got message: 0{"sid":"dGUd1NjkROAspt3hAAAC","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
2021-03-02 08:47:41.968632-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: ping with data: []
2021-03-02 08:47:41.968803-0500 sockettest[992:1229560] LOG SocketManager: Engine opened Connect
2021-03-02 08:47:41.968840-0500 sockettest[992:1229843] LOG SocketEnginePolling: Doing polling GET http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=dGUd1NjkROAspt3hAAAC
2021-03-02 08:47:41.968850-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Socket connected
2021-03-02 08:47:41.968952-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: statusChange with data: [connected, 3]
2021-03-02 08:47:41.969027-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: connect with data: ["/"]
2021-03-02 08:47:41.969291-0500 sockettest[992:1229843] LOG SocketEngine: Writing poll:  has data: false
2021-03-02 08:47:41.969328-0500 sockettest[992:1229843] LOG SocketEnginePolling: Sending poll:  as type: 2
2021-03-02 08:47:41.969369-0500 sockettest[992:1229843] LOG SocketEnginePolling: Created POST string: 1:2
2021-03-02 08:47:41.970487-0500 sockettest[992:1229843] LOG SocketEnginePolling: POSTing
2021-03-02 08:47:41.970545-0500 sockettest[992:1229843] LOG SocketEnginePolling: Doing polling POST http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=dGUd1NjkROAspt3hAAAC
2021-03-02 08:47:41.979132-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: websocketUpgrade with data: [["connection": "Upgrade", "upgrade": "websocket", "sec-websocket-accept": "qXRyRflDO2o0fPGslzplhreoK+8="]]
2021-03-02 08:47:41.979201-0500 sockettest[992:1229844] LOG SocketEngineWebSocket: Sending ws: probe as type: 2
2021-03-02 08:47:41.983692-0500 sockettest[992:1229845] LOG SocketEngine: Got message: 3probe
2021-03-02 08:47:41.983814-0500 sockettest[992:1229845] LOG SocketEngine: Received probe response, should upgrade to WebSockets
2021-03-02 08:47:41.983862-0500 sockettest[992:1229845] LOG SocketEngine: Upgrading transport to WebSockets
2021-03-02 08:47:41.983904-0500 sockettest[992:1229845] LOG SocketEnginePolling: Sending poll:  as type: 6
2021-03-02 08:47:41.984048-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: pong with data: []
2021-03-02 08:47:41.985388-0500 sockettest[992:1229840] LOG SocketEnginePolling: Got polling response
2021-03-02 08:47:41.985457-0500 sockettest[992:1229840] LOG SocketEngine: Switching to WebSockets
2021-03-02 08:47:41.985503-0500 sockettest[992:1229840] LOG SocketEngineWebSocket: Sending ws:  as type: 5
2021-03-02 08:47:41.985545-0500 sockettest[992:1229840] LOG SocketEngine: Flushing probe wait
2021-03-02 08:47:41.986551-0500 sockettest[992:1229840] ERROR SocketEngine: connection closed by server. code=1000, type=protocolError
2021-03-02 08:47:41.986866-0500 sockettest[992:1229560] ERROR SocketManager: connection closed by server. code=1000, type=protocolError
2021-03-02 08:47:41.987293-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: error with data: ["connection closed by server. code=1000, type=protocolError"]
2021-03-02 08:47:41.987443-0500 sockettest[992:1229560] LOG SocketManager: Starting reconnect
2021-03-02 08:47:41.987494-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: statusChange with data: [connecting, 2]
2021-03-02 08:47:41.987556-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: reconnect with data: ["connection closed by server. code=1000, type=protocolError"]
2021-03-02 08:47:41.987605-0500 sockettest[992:1229560] LOG SocketManager: Trying to reconnect
2021-03-02 08:47:41.987676-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: reconnectAttempt with data: [-1]
2021-03-02 08:47:41.987783-0500 sockettest[992:1229560] LOG SocketManager: Scheduling reconnect in 21.743261523169984s
2021-03-02 08:47:41.987783-0500 sockettest[992:1229850] LOG SocketEngine: Starting engine. Server: http://ip-address:3000/
2021-03-02 08:47:41.988147-0500 sockettest[992:1229850] LOG SocketEngine: Handshaking
2021-03-02 08:47:41.988303-0500 sockettest[992:1229850] LOG SocketEnginePolling: Doing polling GET http://ip-address:3000/socket.io/?transport=polling&b64=1
2021-03-02 08:47:42.005212-0500 sockettest[992:1229843] LOG SocketEnginePolling: Got polling response
2021-03-02 08:47:42.005291-0500 sockettest[992:1229843] LOG SocketEnginePolling: Got poll message: 0{"sid":"S0NLdRPF5uCHUoKaAAAD","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
2021-03-02 08:47:42.005704-0500 sockettest[992:1229843] LOG SocketEngine: Got message: 0{"sid":"S0NLdRPF5uCHUoKaAAAD","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
2021-03-02 08:47:42.006542-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: ping with data: []
2021-03-02 08:47:42.006648-0500 sockettest[992:1229560] LOG SocketManager: Engine opened Connect
2021-03-02 08:47:42.006989-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Socket connected
2021-03-02 08:47:42.007041-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: statusChange with data: [connected, 3]
2021-03-02 08:47:42.007084-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: connect with data: ["/"]
2021-03-02 08:47:42.007179-0500 sockettest[992:1229843] LOG SocketEnginePolling: Doing polling GET http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=S0NLdRPF5uCHUoKaAAAD
2021-03-02 08:47:42.009173-0500 sockettest[992:1229843] LOG SocketEngine: Writing poll:  has data: false
2021-03-02 08:47:42.009252-0500 sockettest[992:1229843] LOG SocketEnginePolling: Sending poll:  as type: 2
2021-03-02 08:47:42.009302-0500 sockettest[992:1229843] LOG SocketEnginePolling: Created POST string: 1:2
2021-03-02 08:47:42.009431-0500 sockettest[992:1229843] LOG SocketEnginePolling: POSTing
2021-03-02 08:47:42.009690-0500 sockettest[992:1229843] LOG SocketEnginePolling: Doing polling POST http://ip-address:3000/socket.io/?transport=polling&b64=1&sid=S0NLdRPF5uCHUoKaAAAD
2021-03-02 08:47:42.021928-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: websocketUpgrade with data: [["upgrade": "websocket", "sec-websocket-accept": "/i3oWtmlG0z06qeeQyi4FPgnkvI=", "connection": "Upgrade"]]
2021-03-02 08:47:42.022166-0500 sockettest[992:1229850] LOG SocketEngineWebSocket: Sending ws: probe as type: 2
2021-03-02 08:47:42.026699-0500 sockettest[992:1229845] LOG SocketEngine: Got message: 3probe
2021-03-02 08:47:42.026815-0500 sockettest[992:1229845] LOG SocketEngine: Received probe response, should upgrade to WebSockets
2021-03-02 08:47:42.026860-0500 sockettest[992:1229845] LOG SocketEngine: Upgrading transport to WebSockets
2021-03-02 08:47:42.026905-0500 sockettest[992:1229845] LOG SocketEnginePolling: Sending poll:  as type: 6
2021-03-02 08:47:42.026992-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: pong with data: []
2021-03-02 08:47:42.029955-0500 sockettest[992:1229850] LOG SocketEngine: Flushing probe wait
2021-03-02 08:47:42.031221-0500 sockettest[992:1229845] LOG SocketEnginePolling: Got polling response
2021-03-02 08:47:42.031283-0500 sockettest[992:1229845] LOG SocketEngine: Switching to WebSockets
2021-03-02 08:47:42.031324-0500 sockettest[992:1229845] LOG SocketEngineWebSocket: Sending ws:  as type: 5
2021-03-02 08:47:42.031366-0500 sockettest[992:1229845] LOG SocketEngine: Flushing probe wait
2021-03-02 08:48:09.377870-0500 sockettest[992:1229843] LOG SocketEngine: Writing ws:  has data: false
2021-03-02 08:48:09.377870-0500 sockettest[992:1229560] LOG SocketIOClient{/}: Handling event: ping with data: []
2021-03-02 08:48:09.378081-0500 sockettest[992:1229843] LOG SocketEngineWebSocket: Sending ws:  as type: 2

A: You have to delete this in Xcode:
.version(.two)

when you setup SocketManager. Then it will be working.
I assume that it didn't work because of version of Socket.io on the server. I think that you use version3 on server and version2 on Client side (default is version 3) so it doesn't communicate together.
You have to update your pods like:
pod 'Socket.IO-Client-Swift'

then pod install


text:
Q: Remove charsequence from String Got charsequence contains from WUB
String pattern = "WUB";

String song = WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB

if apply method:
song = song.replaceAll(pattern, "");

Get a String
WEARETHECHAMPIONSMYFRIEND
How to get this String with spaces?
WE ARE THE CHAMPIONS MY FRIEND?

A: song = song.replaceAll(pattern, " ").trim();

Just replace it with a whitespace and call trim on it ;)

A: Replace all instances of pattern in song with a space (" ") instead of an empty string ("").
song = song.replaceAll(pattern, " ");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Same Height Elements but responsive variation I found another question on this page about having two elements with the same height even if one of them doesn't have enough elements to cover the entire area. It works really fine but after reaching a max width of 600px I would like to disable this code, like getting back to height: auto; I'm trying to solve this but without any result. Any suggestion? here's actual javascript code.
HTML

JAVASCRIPT
$(document).ready(function() {
var equalize = function () {
    var disableOnMaxWidth = 0; // 767 for bootstrap

    var grouped = {};
    var elements = $('*[data-same-height]');

    elements.each(function () {
        var el = $(this);
        var id = el.attr('data-same-height');

        if (!grouped[id]) {
            grouped[id] = [];
        }

        grouped[id].push(el);
    });

    $.each(grouped, function (key) {
        var elements = $('*[data-same-height="' + key + '"]');

        elements.css('height', '');

        var winWidth = $(window).width();

        if (winWidth <= disableOnMaxWidth) {
            return;
        }

        var maxHeight = 0;

        elements.each(function () {
            var eleq = $(this);
            maxHeight = Math.max(eleq.height(), maxHeight);
        });

        elements.css('height', maxHeight + "px");
    });
};

var timeout = null;

$(window).resize(function () {
    if (timeout) {
        clearTimeout(timeout);
        timeout = null;
    }

    timeout = setTimeout(equalize, 250);
});
equalize();
});

Thanks to everyone!


text:
Q: Unable to understand usage of the Beta function in a previous question In this question, OP says they used the definition of the Beta function on, $$S := \sum_{n=0}^{\infty}(-1)^{n}\frac{\Gamma(n+\frac{3}{4})}{\Gamma(n+\frac{5}{4})}=\frac{\sqrt{\pi}}{2}$$ to get, $$\sqrt{\pi}S=\intop_0^1\frac{x^{-\frac{1}{4}}}{(1+x)\sqrt{1-x}}dx$$ I can't figure out how they ended up with this equation. I tried to think of it as choosing values for $x$ and $y$ to end up on this integral, but I can't figure out which ones they used. I do know the integral definition of the Beta function which is $$\beta(x,y) = \int_{0}^{1}t^{x-1}(1-t)^{y-1}dt$$ Any hints would be helpful.

A: $\newcommand{\B}{\mathfrak{B}}\newcommand{\d}{\,\mathrm{d}}\newcommand{\res}{\operatorname{Res}}$It is known that $\B(x,y)=\frac{\Gamma(x)\Gamma(y)}{\Gamma(x+y)}$ whenever $\Re x,y>0$ (and possibly for a more general case, I don't know). I use $\B$ rather than $\beta$ as $\beta$ can be confused with the Dirichlet Beta function.
Specifically, you have: $$\frac{\Gamma\left(n+\frac{3}{4}\right)}{\Gamma\left(n+\frac{5}{4}\right)}=\frac{1}{\Gamma\left(\frac{1}{2}\right)}\cdot\frac{\Gamma\left(n+\frac{3}{4}\right)\Gamma\left(\frac{1}{2}\right)}{\Gamma\left(n+\frac{3}{4}+\frac{1}{2}\right)}=\pi^{-1/2}\cdot\B\left(n+\frac{3}{4},\frac{1}{2}\right)$$Which evaluates to: $$\pi^{-1/2}\int_0^1t^{n-1/4}(1-t)^{-1/2}\d t$$(for $n\in\Bbb N_0$).
So: $$\sqrt{\pi}\cdot S=\sum_{n\ge0}(-1)^n\int_0^1t^{n-1/4}(1-t)^{-1/2}\d t=\int_0^1(1-t)^{-1/2}\left(\sum_{n\ge0}(-1)^nt^{n-1/4}\right)\d t$$If you accept the sum-integral interchange, this is e.g. justified by uniform convergence of geometric series. Evaluating the geometric series finds: $$\sqrt{\pi}\cdot S=\int_0^1(1-t)^{-1/2}\cdot t^{-1/4}\frac{1}{1-(-t)}\d t=\int_0^1\frac{t^{-1/4}}{(1+t)\sqrt{1-t}}\d t$$
As claimed.

This integral can be evaluated using complex analysis. Unfortunately I can't add this answer to the original post since that one was closed. Firstly, we need to have good symmetry - the fourth root does not match with the singular square root. So I let $t\mapsto t^2$ to instead focus on: $$2\int_0^1\frac{t^{1/2}}{(1+t^2)\sqrt{1-t^2}}\d t$$To use complex analysis, we need to carefully define the two square roots to exploit certain symmetries. Let $\log_1$ denote the logarithm based on $0\le\arg z<2\pi$, and $\log_2$ the principal logarithm based on $-\pi<\arg z\le\pi$. Let $t^{1/2}$ denote (for complex $t$, now) $\exp\left(\frac{1}{2}\log_1(t)\right)$ and $(1-t^2)^{-1/2}$ denote $\exp\left(-\frac{1}{2}\log_2(1-t^2)\right)$. Assemble these two different definitions of square root to $f:z\mapsto\frac{2}{1+z^2}\cdot z^{1/2}(1-z^2)^{-1/2}$, as a function $\Bbb C\setminus\{\pm i\}\to\Bbb C$. I won't check this here, but it is a straightforward-to-verify claim that $f$ is meromorphic on $\Bbb C\setminus[0,1]$. The point is, the two square roots individually have branch cuts $[0,\infty)$ and $[1,\infty)$, but the "jumps" (as the argument goes $-\pi\to\pi$ or $0\to2\pi$) that cause these discontinuities cancel each other out on $(1,\infty)$. This is the most important point.
Given all this, let $D_\epsilon$ (for $\epsilon>0$) denote the "dogbone" contour that runs clockwise around $[0,1]$ as follows: $i\epsilon\to1+i\epsilon$ as a straight line, $1+i\epsilon\to1-i\epsilon$ as an outward clockwise arc of radius $\epsilon$, $1-i\epsilon\to-i\epsilon$ as a straight line, and $-i\epsilon\to i\epsilon$ as an outward clockwise arc of radius $\epsilon$. Since $f$ has zero "residue at infinity" (it's straightforward to check that $\lim_{|z|\to\infty}z\cdot f(z)=0$) I know: $$2\pi i\cdot\res_{z=i}f+2\pi i\cdot\res_{z=-i}f=\oint_{D_\epsilon}f(z)\d z$$But it's also straightforward to check that the integrals on the semicircular arcs vanish, e.g.: $$\left|\int_{-\pi/2}^{\pi/2}f(\epsilon e^{-it})\cdot(-i\epsilon e^{-it})\d t\right|\le\int_{-\pi/2}^{\pi/2}\epsilon^{1/2}\cdot\epsilon\cdot\mathcal{O}(1)\d t\to0$$
Now fix $x\in(0,1)$. As $z=x+i\epsilon\to x$, $f(z)\to\frac{2}{1+x^2}\cdot\frac{x^{1/2}}{\sqrt{1-x^2}}$. But as $z=x-i\epsilon\to x$, $f(z)\to\frac{2}{1+x^2}\cdot\frac{x^{1/2}}{\sqrt{1-x^2}}\color{red}{(-1)}$, where the $-1$ term arises from $\exp\left(\frac{1}{2}(2\pi i)\right)=-1$, recalling that $z^{1/2}$ was defined via $0\le\arg z<2\pi$.
As the poles are simple, the residue calculation is also simple (being careful with branch definitions) and you can find the left hand side to equal $\pi$. So: $$\pi=\int_{0+i\epsilon}^{1+i\epsilon}f(z)\d z-\int_{0-i\epsilon}^{1-i\epsilon}f(z)\d z+o(1)\to\int_0^1f(x)\d x-\int_0^1f(x)(-1)\d x$$That is: $$\pi=2\int_0^1\frac{2x^{1/2}}{(1+x^2)\sqrt{1-x^2}}\d x\\\int_0^1\frac{x^{-1/4}}{(1+x)\sqrt{1-x}}\d x=\frac{\pi}{2}$$

A: I'm the OP. This is how I did it:
$\sum_{n=0}^\infty (-1)^n\frac{\Gamma({n+\frac{3}{4}})}{\Gamma({n+\frac{5}{4}})}=\sum_{n=0}^\infty (-1)^n\frac{\Gamma({n+\frac{3}{4}})}{\Gamma({n+\frac{3}{4}+\frac{1}{2}})}$.
Now multipling by $\Gamma(\frac{1}{2})=\sqrt{\pi}$:
$$\sum_{n=0}^\infty (-1)^n\Gamma(\frac{1}{2})\frac{\Gamma({n+\frac{3}{4}})}{\Gamma({n+\frac{3}{4}+\frac{1}{2}})}$$
The Gamma terms are just $B(\frac{1}{2},n+\frac{3}{4})$
So we get:
$$\sum_{n=0}^\infty (-1)^nB(\frac{1}{2},n+\frac{3}{4})$$
Using the integral form of the Beta function:
$$\sum_{n=0}^\infty (-1)^n \intop_0^1 x^{n+\frac{3}{4}-1}(1-x)^{\frac{1}{2}-1}dx$$
Now, exchanging the sum and the integral (The sum defintely converges, and the integral does too)
$$ \intop_0^1 \sum_{n=0}^\infty (-1)^n x^n*x^{-\frac{1}{4}}(1-x)^{-\frac{1}{2}}dx$$
And finally using the formula for a geometric series:
$$ \intop_0^1 \frac{x^{\frac{1}{4}}}{(1+x)\sqrt{1-x}}dx$$
And since the only change we did to the original sum was Multiply by $\sqrt{\pi}$:
$$\sqrt{\pi}\sum_{n=0}^\infty (-1)^n\frac{\Gamma({n+\frac{3}{4}})}{\Gamma({n+\frac{5}{4}})}=\intop_0^1 \frac{x^{\frac{1}{4}}}{(1+x)\sqrt{1-x}}dx$$


text:
Q: partial_sum() position of previous Using partial_sum(), I am trying to get the position from previous during the recurrence. I don't understand the result. I was expecting to get :
recurrence i=0
recurrence i=1
...

As the recurrence unfolds. But I am getting :
recurrence i=-48115006
recurrence i=-48115006
...

What am doing wrong ?
#include <vector>
#include <algorithm>
#include <numeric>
#include <stdio.h>
using namespace std;

int main()
{
        const int n=15;
        vector<vector<int> > vv(n+1);
        vv[0]={42};

        auto next=[&](const vector<int>& previous, const vector<int>&){
                const int i = &previous - &vv[0];
                printf("recurrence i=%d\n", i);
                fflush(stdout);
                vector<int> v;
                return v;
        };

        partial_sum(vv.begin(), vv.end(), vv.begin(), next);
}

A: The implementation for partial_sum that you are using is probably similar to the one described in cppreference, Possible implementation, Second version:
template<class InputIt, class OutputIt, class BinaryOperation>
constexpr // since C++20
OutputIt partial_sum(InputIt first, InputIt last,
                     OutputIt d_first, BinaryOperation op)
{
    if (first == last)
        return d_first;

    typename std::iterator_traits<InputIt>::value_type sum = *first;
    *d_first = sum;

    while (++first != last)
    {
        sum = op(std::move(sum), *first); // std::move since C++20
        *++d_first = sum;
    }

    return ++d_first;
}

That being the case, the first argument that partial_sum passes to op (the binary operation, next in your code) is fix: it's a reference to an accumulator. It is the second argument the one that varies: it's a reference to the current element in each iteration (starting at the second element). But, in your example, you don't use this second argument to set i. Instead, you always use &vv[0], which is also a fix value (unless vv changes in size, which is not the case). So it's expected that you are always printing the same value: the difference of two fix addresses.
You can see it working here with some more debugging output.


text:
Q: How to create a variable of whose bits are mapped to certain locations? This is an embedded C question for 8-bit PIC microcontrollers.
Let's say there is a 7-Segment LED display that is connected to different pins of different ports and let's say they are defined as follows:
#define _7seg_A         PORTCbits.RC6
#define TRIS_7seg_A     TRISCbits.TRISC6
#define _7seg_B         PORTCbits.RC5
#define TRIS_7seg_B     TRISCbits.TRISC5
#define _7seg_C         PORTAbits.RA5
#define TRIS_7seg_C     TRISAbits.TRISA5
#define _7seg_D         PORTBbits.RB6
#define TRIS_7seg_D     TRISBbits.TRISB6
#define _7seg_E         PORTBbits.RB5
#define TRIS_7seg_E     TRISBbits.TRISB5
#define _7seg_F         PORTBbits.RB7
#define TRIS_7seg_F     TRISBbits.TRISB7
#define _7seg_G         PORTCbits.RC7
#define TRIS_7seg_G     TRISCbits.TRISC7
#define _7seg_DP        PORTAbits.RA4
#define TRIS_7seg_DP    TRISAbits.TRISA4

Also, here is a port definition from the microcontroller definitions header file of the compiler:
typedef union {
    struct {
        unsigned RA0                    :1;
        unsigned RA1                    :1;
        unsigned RA2                    :1;
        unsigned RA3                    :1;
        unsigned RA4                    :1;
        unsigned RA5                    :1;
    };
} PORTAbits_t;
extern volatile PORTAbits_t PORTAbits @ 0x005;

Now, I want to have something called _7seg_DATA which contains all eight of _7seg_X bits and when I write data to it, it will automatically put it into defined pins. Can this be done by unions?
For example, if I do _7seg_DATA = 0x00; it will shut down all the LEDs..
And if I do _7seg_DATA = 0xFF; it will light all of them.

A: No you cannot use a union or struct to map the individual bits of a single byte to multiple memory mapped register addresses.  However, you could create a function that receives the 8-bit byte as a parameter and then the function maps each individual bit to the appropriate port's register.

A: Just to add to what KKrambo said you can use #define to articulate where each bit should go for instance
#define ledA 0x01
#define ledB 0x02

ect...
Then in the function (or before you call the function) you can write something like
u_int8 ledS  |= ledA;

and so on

A: The best solution would be to redesign your hardware to combine all of the bits for the 7-segment display in one port. If this isn't possible, your best alternative is a function to do the mapping for you.


text:
Q: Are quotient groups unique up to isomorphism By this post, it seems quotient groups are unique up to isomorphism. is it correct? More clearly
Let $G$ be a group and let $K,N\unlhd G$ be isomorphic normal subgroups. Are $\frac{G}{N}$ and $\frac{G}{K}$ isomorphic?

A: Your statement is incorrect, but if the subgroups are isomorphic as subobjects (i.e. an isomorphism that commute with the inclusions) then it's true by general nonsense (i.e. category theory).

A: $\mathbb{Z}/2\mathbb{Z}\neq\mathbb{Z}/3\mathbb{Z}$


text:
Q: How can use regex to validate iSCSI target names? I am trying to craft a regexp to validate iSCSI qualified names. An example of a qualified name is iqn.2011-08.com.example:storage This is example is minimal, I have seen other examples that are more extended.
So far what I have to validate off of it this:
print "Enter a new target name: ";

my $target_name = <STDIN>;

chomp $target_name;

if ($target_name =~ /^iqn\.\d{4}-\d{2}/xmi) {

    print GREEN . "Target name is valid!" . RESET . "\n";

} else {

    print RED . "Target name is not valid!" . RESET . "\n";

}

How can I extend that to work with rest up to the : I am not going to parse after the : becuase it is a description tag.
Is there a limit to how big a domain name can be?

A: According to RFC3270 (and in turn RFC1035),
/
   (?(DEFINE)
      (?<IQN_PAT>
         iqn
         \.
         [0-9]{4}-[0-9]{2}
         \.
         (?&REV_SUBDOMAIN_PAT)
         (?: : .* )?
      )

      (?<EUI_PAT>
         eui
         \.
         [0-9A-Fa-f]{16}
      )

      (?<REV_SUBDOMAIN_PAT>
         (?&LABEL_PAT) (?: \. (?&LABEL_PAT) )*
      )

      (?<LABEL_PAT>
         [A-Za-z] (?: [A-Za-z0-9\-]* [A-Za-z0-9] )?
      )
   )

   ^ (?: (?&IQN_PAT) | (?&EUI_PAT) ) \z
/sx

It's not clear if the eui names accept lowercase hex digits or not. I figured it was safer to allow them.
If you condense the above, you get /^(?:iqn\.[0-9]{4}-[0-9]{2}(?:\.[A-Za-z](?:[A-Za-z0-9\-]*[A-Za-z0-9])?)+(?::.*)?|eui\.[0-9A-Fa-f]{16})\z/s.
(By the way, your use /m is wrong, your use of /i is wrong, and \d can match far more than the allowed [0-9].)

A: If you only need part before : then you can use following regexp:
if ($target_name =~ /^iqn\.(\d{4}-\d{2})\.([^:]+):/xmi) {
    my ($date, $reversed_domain_name) = ($1, $2);

Regexp [^:]+ matches to 1 or more non-: symbols. It will match even if domain name is not well formed. Further improvements depends on your goal: do you need just get individual components of iSCSI name or do you need to validate its syntax?

Is there a limit to how big a domain name can be?

From Wikipedia:

The full domain name may not exceed a total length of 253


text:
Q: Generic Kendo MVC Grid Used with Different Models I am trying to use a Kendo Grid generically as a partial view.  Kendo requires either a type defined or a datatable to instantiate the grid in a razor view
@(Html.Kendo().Grid<object>() or @(Html.Kendo().Grid(dataTable)

My issue is i want to use the Grid for whatever object, not a specific one.
@(Html.Kendo().Grid<object>()
    .Name(Model.MetricName)
    .Resizable(resizing => resizing.Columns(true))
    .Reorderable(reorder => reorder.Columns(true))
    .Sortable(sorting => sorting.Enabled(true))
    .Pageable(pager => pager.PageSizes(new int[] { 10, 15, 20, 50 }))
    .ColumnMenu()
    .DataSource(dataSource => dataSource
            .Ajax()
            .Read(read => read.Action(Model.MetricName, "AdHocReport", new { metricId = Model.MetricId }))
    )

)

by using Object i am able to dynamically load the data returned from the ajax .read method.  However the issue is with dates.  They are returned in JSON format.
Ive tried this method and I still get JSON string representation of the date
Kendo ASP.NET MVC helper Grid generic class
Is there a way to define the type of grid from a string representation of the type?  So lets say i have a string property on the viewModel that is the type of the grid. How can i say  Grid ?
ive tried using reflection to instantiate the type but i get the infamous "you are using a variable like a type"
This is driving me nuts... any and all help would be greatly appreciated

A: So i found the way to make this work and bind correctly and as mentioned above my mrmashal it has to do with using dataTables.
@(Html.Kendo().Grid(Model.GridTable)

here is the viewModel property
public DataTable GridTable { get; set; }

To make this dynamic i use reflection to define the dataTable based upon the properties of a the class i want to populate the grid with
Type elementType = Type.GetType(className, true);
var properties = elementType.GetProperties();

DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
    {
        dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
    }
viewModel.GridTable = dataTable;

However, the key is making sure that the data returned from the AJAX read was a dataTable, not an IEnumerable type.
DataTable dataTable = ToDataTable<AssetLocationHistoryMetricData>(metricData);

var result = dataTable.ToDataSourceResult(request);

and this is what i used to convert the List to a dataTable
public static DataTable ToDataTable<T>(IEnumerable<T> items)
    {
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name);
        }
        foreach (T item in items)
        {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
            {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }
        //put a breakpoint here and check datatable
        return dataTable;
    }


text:
Q: Android Firebase Push Notification Bundle data issue After sending a notification to my application then when I tap to the notification bar it goes to the MainActivity with Bundle data.
But after exit from the application then when I enter the application by tapping app_launcher_icon the application gets the previous notification Bundle data.
Now how to solve this issue.

A: Clear your intent data after you consume it
getIntent().setData(null);

A: you can send the data from the receiver to the activity by  intent put extra .


text:
Q: check if table exists in hive using spark 1.6 scala code i am trying to check if a table exists in hive using spark 1.6 and scala coding.
i tried to explore over internet but couldn't find anything more useful than this
spark - scala - How can I check if a table exists in hive
here it is mentioned that if we use
sqlContext.tableNames.contains("mytable")

then it returns boolean. but when i try this it checks in default database and gives me false.
how can i set a database to be looked into while this check?

A: You could set the database first like this:
scala> sqlContext.sql("use dbName")

and then search for the table:
scala> sqlContext.tableNames.contains("tabName")
res3: Boolean = true


text:
Q: Bound the length of level sets Yesterday, I asked a question regarding the relation between the $C^1$ norm of a function $\phi:\Omega\rightarrow \mathbb{R}$, $\Omega\subset \mathbb{R}^2$ and the corresponding length of the zero level set. The conclusion was that the length of the zero level set is independent from $\|\phi\|_{C^1}$, see here.
To be concrete, say we have $\phi\in C^1(\overline{\Omega})$ of a bounded domain $\Omega$ in $\mathbb{R}^2$ and $D=\{x:\phi(x)>0\}$ and $\nabla \phi(x) \neq 0$ for $x$ on the curve satisfying $\phi(x)=0$.
Question: For which subset of $\phi\in C^1$, can I uniformly bound the length $L(\phi^{-1}(0))\leq M$ for some constant $M>0$.
Progress: My question is not very concrete, but I am interested in results of this kind. There is a related problem of determining the maximum length $L$ of a so-called lemniscate $\{x: |\phi|=1\}$. I believe $L=O(n)$, where $n$ is the degree of the polynomial. But already for trigonometric polynomials, this does not hold?
Motivation: I am interested in bounding a Sobolev norm of $\mathbb{1}_{\phi>0}$, where $\phi$ is some kind of Gaussian process. The $H^{\alpha}$-norm of such characteristic function is dependent on $L(\phi^{-1}(0))$, through for example this post.


text:
Q: How do I read the value of a checkbox in a word (*.doc) file in VB.net using a Range object? How do I read the value of a checkbox in a word (*.doc) file in VB.net using a range object?
This is what I have so far:
Dim app As New Word.Application
Dim doc As Document
doc = app.Documents.Open("C:\myDoc.doc")
dim chkBox as Bookmark
chkBox = doc.Bookmarks("MyCheckbox")
Dim rng as Range
rng = chkBox.Range

where "MyCheckbox" is the bookmark of the checkbox in the word document.

A: Any particular reason you're not reading the value of the checkbox using the name of the checkbox itself?
If the range defined by your bookmark contains a checkbox, then, depending upon how the checkbox is inserted, it will be found in either the InlineShapes collection (if checkbox inserted inline with the text) or the Shapes collection (if inserted as a floating object.)
You would then need to iterate through the collection of Shapes or InlineShapes looking for the checkbox in question.
Iterating through controls in InlineShapes collection
Dim ctl As InlineShape
For Each ctl In rng.InlineShapes
    If ctl.Type = wdInlineShapeOLEControlObject Then
        If ctl.OLEFormat.ClassType Like "Forms.CheckBox*" Then
            'current version of ctl is a checkbox, do what you will with it.

        End If
    End If
Next ctl
...

This ought to get you closer, but if the name of the checkbox is predictable, it is better to address it directly by name.


text:
Q: Linux, Installation of FBX SDK, how to automatically confirm? I am currently building a project in a (Singularity) container, and one of the dependencies is the FBX SDK (for building Qt static).
The problem is that the installer of FBX reads the licence conditions and then asks to confirm those, and as the installation by recipe don't allow me answer manually, it produces an endless repetition of the lines
To continue installing the software, you must agree
to the terms of the software license agreement.

Type "yes" to agree and continue the installation. Agree [yes/no] ?

Now I did some research into how to auto confirm such things and found How do I script a "yes" response for installing programs?.
Given the answers there, I tried the following lines:
yes | ./fbx20190_fbxsdk_linux
yes Y | ./fbx20190_fbxsdk_linux
echo yes | ./fbx20190_fbxsdk_linux

(Second line just in case, as the installer clearly wants a "yes".)
None of those worked. Is there some other trick I could try? Or another way to install FBX?
(Note: the lines above do at least something, that is they automatically confirm File(s) will be extracted to: . Please confirm [y/n] ?)

A:
...as the installer clearly wants a "yes"

In that case, try this:
yes yes | ./fbx20190_fbxsdk_linux

By default, the yes command does not send "yes" to the subsequent process, only y. You can override this behavior by giving a command line parameter as you did in your second attempt above. However, there you inokved it as yes Y which does not send a "yes" either, it sends Y.
The parameter to yes must be the string that you want to send to ./fbx20190_fbxsdk_linux, hence yes yes.


text:
Q: Isekai manga where the main character is reincarnated as a grandson of a Hero family It is not Kenja no Mago. The main character (MC) is reincarnated as a grandson of a hero family.
His grandfather in the isekai was a summoned hero who married, became a noble and started a family.
The grandfather started training the MC and his childhood friend. They go dungeon adventuring and the grandfather is killed by the last monster, which is humanoid. The grandson kills the last monster, clearing the dungeon.

A: Continuity is the Father of Magical Power...?
From Baka-Updates:

After diligently training his magic every day, Leons found out that his specialty magic, Creation Magic, is trash! However, with his unbelievable amount of mana and amazingly good luck, Leons is able to turn that useless magic into a very convenient magic to create various things, like a super masochist magic sword that can speak for example! Moreover, he also got closer to Princess Sheria and the grand daughter of the Holy Maiden, Riana, after he presented his creation to them!

The main character, Leo Forster, was reincarnated from another world, as was his grandfather, the former hero, Kento Forster.
Kento begins training Leo in melee combat, and as part of his training, later takes him to a dungeon, along with Leo's two female companions.
They fight their way to the boss of the dungeon, a demonic-looking creature, which deals Kento a mortal wound. This enrages Leo, and he promptly cleaves the monster in twain with his sword.


text: Q: Azure devops extension postinstall page We are building an extension on azure devops board to capture time and on submit we need to sent the details to our endpoint for business use case. After the successful install of the azure devops plugin to company, we need to direct the users to our domain for reading the consent and authorize it. When the app is installed, we are getting the post request with the installed details. But since its a post request, i can't redirect the users to browser for authorization with our end point.. so, i am looking for adding a button on the install success page(attached the screenshot of it), so that user can click and authorize it after install, but i couldn't find any option for that. Can some one guide me on this? Thanks in advance.


text:
Q: Max height of 16,384px for headless Chrome screenshots? No matter what I try, the maximum height of a full-page screenshot with headless Chrome 60 (and 59) is 16,348px.
It is not a memory issue. There are no segfaults and no, for example, FATAL:memory_linux.cc(35) Out of memory. messages. None. Capturing screenshots are "successful". Changing the screenshot format - PNG or JPEG - has no affect.
The screenshot width can vary, but the height of the saved screenshot is always limited to 16,348px. Example,

1600x16384, 1200x16384, 2400x16384, etc.

I'm taking upscaled screenshots with this minimal code (full source):
const upscale = 2;

const viewportWidth = 1200;
const viewportHeight = 800;

....

// Set up viewport resolution, etc.
const deviceMetrics = {
    width: viewportWidth,
    height: viewportHeight,
    deviceScaleFactor: 0,
    mobile: false,
    fitWindow: false,
    scale: 1    // Relative to the upscale
};
await Emulation.setDeviceMetricsOverride(deviceMetrics);
await Emulation.setVisibleSize({width: viewportWidth, height: viewportHeight});
await Emulation.setPageScaleFactor({pageScaleFactor: upscale});

// Navigate to target page
await Page.navigate({url});

const {root: {nodeId: documentNodeId}} = await DOM.getDocument();
const {nodeId: bodyNodeId} = await DOM.querySelector({
    selector: 'body',
    nodeId: documentNodeId,
});
const {model: {height}} = await DOM.getBoxModel({nodeId: bodyNodeId});

// Upscale the dimensions for full page
await Emulation.setVisibleSize({width: Math.round(viewportWidth * upscale), height: Math.round(height * upscale)});

// This forceViewport call ensures that content outside the viewport is
// rendered, otherwise it shows up as grey. Possibly a bug?
await Emulation.forceViewport({x: 0, y: 0, scale: upscale});

const screenshot = await Page.captureScreenshot({format});
const buffer = new Buffer(screenshot.data, 'base64');

file.writeFile(outFile, buffer, 'base64', function (err) {
    if (err) {
        console.error('Exception while saving screenshot:', err);
    } else {
        console.log('Screenshot saved');
    }
    client.close();
});

I was unable to find any useful Chrome switches either. Is this a hardcoded limit of Chrome? 16384 is a suspicious number (2^14 = 16,384). How can this height be increased?

A: This is a limitation of Chromium as documented in this bug
https://bugs.chromium.org/p/chromium/issues/detail?id=770769&desc=2


text:
Q: Using "watch-http-server" for multiple websockets (or alternatives)? I am using watch-http-server from npm to start a localhost server that automatically refreshes the page on file changes.
https://www.npmjs.com/package/watch-http-server
More specifically, I am using this for unit tests. The npm script navigates to the spec folder and starts up the server on localhost:
"spec": "cd karma_html && cd spec && dir && watch-http-server -a localhost -p 3000 -c-1"

I would like to do the same thing for my main application, however it seems like there are no options for the websocket included in this npm package, thus only one can run at a time.
Currently, for my main application I use a regular http-server expression.
https://www.npmjs.com/package/http-server
"start": "cd dist && http-server -a localhost -p 8000 -c-1",

And I handle page refreshes using the livereload application for Windows (http://livereload.com/). However, this always crashes on the initialization phase, as there's a large amount of files being copied in a short timespan. This gets quite annoying.
I'm looking for either an npm package that supports websocket options or another package similar to watch-http-server that has a different websocket configuration, so I can run it in parallel.

A: Gladly, I found the live-server npm package, which I could use for my main application.
https://github.com/tapio/live-server
After installing it, I modified my npm start script to this:
"start": "cd dist && live-server --host=localhost --port=8000",


text:
Q: Extending a class with an other namespace with the same ClassName I'm trying to use namespaces. I want to extend a class inside a different namespace. The name of the class is the same. Example:
Parent:
namespace Base;

class Section extends Skeleton {

protected $id;

protected $title;

protected $stylesheet;
}

Child:
namespace Base2;
use \Base\Section;

class Section
    extends \Base\Section {

}

It is an application which uses Doctrine 2 and Zend Framework. The Skeleton class used by Base/Section is just an abstract class that contains the magic methods (__get, _set, etc).
When I try to instantiate a \Base2\Section class it throws an error:
Fatal error: Cannot declare class Base2\Section because the name is
already in use in /var/www/test/application/Models/Base2/Section.php
on line 7

Any idea's?

A: Just use fully qualified name
namespace Base2;

class Section
    extends \Base\Section {
}

Or aliasing
namespace Base2;
use \Base\Section as BSection;

class Section
    extends BSection {
}

A: when you say
use \Base\Section

you are pulling the Section class into your current scope, causing a conflict when you want to create a new class called Section. just omit the use statement.


text:
Q: Energy loss in capacitor for slow charge transfer From these questions:
Energy loss in Capacitors
What happens to half of the energy in a circuit with a capacitor?
I come to the conclusion that energy loss in a capacitor is explained by the fact that the the potential applied accelerates charges and since the end configuration is stationary, there needs to be some damping to get a steady state.
Now assuming a hypothetical situation where we somehow bring $dq$ charge infinitely slowly. We repeat this a number of times and thus charge the capacitor to charge $Q$. Thus we lose zero energy as heat as we have avoided any acceleration of charges and the work done and the energy stored would both be $\frac{Q^2}{2C}$. Ignoring the practical limitations of this experiment, is this theoretically correct?

The charges are brought from infinity are used to charge a single spherical capacitor of capacitance C.

A:
I come to the conclusion that energy loss in a capacitor is explained
  by the fact that the the potential applied accelerates charges and
  since the end configuration is stationary, there needs to be some
  damping to get a steady state.

First, there is no energy loss in a (ideal) capacitor$^*$.
The first question linked regards the case of 'missing' energy when two capacitors, one charged and one not, are connected together at some instant.  In that case, energy is lost from the circuit to the environment in the form of heat and/or radiation.  This case has been covered in several Q & A, e.g., here.
The second linked question regards the case of 'missing' energy when charging a capacitor with a constant voltage source.  Again, energy is lost to the environment in the form of heat and/or radiation.  And again, this case has been covered in several Q & A, e.g., here.
Regarding your idea of slow charge transfer, note that the results in the answers linked above are independent of the rate at which the capacitor charges.  The essence of the energy loss in these types of problems is in the fact that voltage across the capacitor cannot change instantly.
Note that if, instead of a voltage source, a current source is employed to charge the capacitor, there is no 'missing' energy.  If the current through is given by $i_S(t)$, then the voltage across the capacitor is given by (assume $i_S(t)$ is zero for $t<0$ and the capacitor is initially uncharged)
$$v_S(t) = v_C(t) = \frac{1}{C}\int_0^t\,i_S(\tau)\,\mathrm{d}\tau = \frac{Q(t)}{C}$$
and the work done by the source equals the energy stored in the capacitor for any time $t$.
$^*$ there's a subtlety here that's not worth bringing up in this answer.


text:
Q: How to install Python3 and GCC 7 in the same SCL shell? I am trying to install graph-tool on a RHEL7 within a virtual environment; it uses both, Python 3 and gcc 7 or above.
I am unable to use both of them within the same scl bash shell.
[root@ ~]# scl enable rh-python36 bash
[root@ ~]# python -V
Python 3.6.3
[root@ ~]# gcc --version | grep gcc
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
[root@ ~]# exit
exit

[root@ ~]# scl enable devtoolset-7 bash
[root@ ~]# python -V
Python 2.7.5
[root@ ~]# gcc --version | grep gcc
gcc (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)

Is there a way to update gcc within the first environment (rh-python36)?
Thanks.

A: I figured this out by following the below steps:

*

*enable the virtual environment containing the Python3

[root@ ~]# source /jupyter/bin/activate
(jupyter) [root@ ~]# which python
/jupyter/bin/python
(jupyter) [root@ ~]# python -V
Python 3.6.3

*enabled devtools afterwards:

(jupyter) [root@ ~]# scl enable devtoolset-7 'bash'
[root@ ~]# python -V
Python 3.6.3
[root@ ~]# gcc --version
gcc (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)


text:
Q: Need to show Store name under Order grid I am New to Magento. I have a live Magento site (1.9.3.8). The previous developer created Store name and store views.
Currently having 2 store's  1. default 2. mobile.
If the customer places the order via PC then Store information will be stored as default and if the customer place the order through mobile then store name will be mobile in the order grid column "Purchased From (Store)".
But this functionality is not working. only default store is saving all the time.
I have created folder mobile under root folder and copied all the required files and in Index.php i put
Store or website code */
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'mobile';

/* Run store or run website */
$mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'website';

If I am wrong. Please guide me how to achieve this. I need to show order came through mobile or Website.
Thanks.


text:
Q: Android POST Request to PHP I try to develope an Android application. In this application, I need to send a POST request to a PHP page.
My code is at Java side:
 DefaultHttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://localhost/get.php");

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     nameValuePairs.add(new BasicNameValuePair("mail", "asdasd"));
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

     try{
            HttpResponse httpresponse = httpclient.execute(httppost);

     }catch(Exception e){
         Toast.makeText(getApplicationContext(), "Didn't Happen",10).show();
     }

Manifest.xml
 <?
xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.misman"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:permission="android.permission.INTERNET"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.misman.MainActivity"
            android:label="@string/app_name" >

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

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

</manifest>

I have searched from a lot of websites and the code goes in catch block continuously.I also used HttpURLConnection and didn't work. Can you help me what can be the problem?

A: Use the following code. It is working fine
public class HttpClient {
    private static final String TAG = "HttpClient";

    public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        httpPostRequest.setHeader("Accept-Encoding", "gzip");

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            String resultString= convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(0,resultString.length()-1);

            JSONObject jsonObjRecv = new JSONObject(resultString);
            Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

            return jsonObjRecv;
        }

    }
    catch (Exception e)
    {
        Log.e("Exception", "Exception");
        e.printStackTrace();
    }
    return null;
}

private static String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
    }
}

A: My problem was that I want to run my code in application main thread and main thread doesn't allow that. There are a few ways to solve this problem,

*

*Using AsyncTask to perform background operation

*Run the code in a new thread

*Enable network operation in MainActivity and this is what I choose for now by
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().
                                                detectNetwork().build();
StrictMode.setThreadPolicy(policy);

UPDATE
Because of the name of the question I want to share how to make Http call in android in order to guide people. There are some apis:

*

*Volley

*Retrofit
And there is a training in

*

*Android Developer


text:
Q: Calculus of variations ? electrostatic energy problem.
What is the maximum self-energy of an electrostatic distribution subject to the constraints that:

*

*the total charge is $1$; and

*the areal charge density anywhere is either $1$ or $0$.

How can I formulate this problem in calculus of variations?
I came up with this problem because I was calculating self-energies of a planar hexagon and noticed it is less than the energy of a round disk of same area, and physically it is reasonable that the disk requires more energy to put together. However I want to know if I can solve this with calculus of variations.
I'd try to use
$$E = \iint {\rho(x) \, \rho(y) \over \lvert x-y\rvert}\, dx\,dy + \int \bigl[ \lambda(x)\, \rho(x) \, (1-\rho(x))  +\mu \, \rho(x)\bigr]\, dx$$
Variation with $\rho$ gives
$$2 \int {\rho(y)\over \lvert x-y\rvert} \,dy + \mu + \lambda(x) \,\bigl[1 - 2 \,\rho(x)\bigr] = 0$$
Let $U(x)$ be the first term, then
$$\rho(x) = 0 \implies U(x) = -\mu - \lambda(x)$$
$$\rho(x) = 1 \implies U(x) = -\mu + \lambda(x)$$
This is where I am now.


text:
Q: CORS errors with Express Node.JS backend, React frontend and AWS infrastructure I have a React frontend that lets users add and view recipes, which contain text and a picture.  The backend is an Express Node.JS app which reads from and writes to a DynamoDB database.  The application is deployed on AWS using the Serverless Framework, so it uses API Gateway, Lambda, DynamoDB, and S3 for photo storage.  I'm working on getting the uploadphoto route working, but CORS errors are preventing it from working.
I've imported the cors NPM module and am using it on the app.  I've tried explicity specifying the origin in the config, but that doesn't make a difference.  I also have cors: true on every route in my serverless.yml file.
serverless.yml excerpt:
service: recipes-api

provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: us-east-1
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource:
        - { "Fn::GetAtt": ["RecipesDynamoDBTable", "Arn"] }
  environment:
    RECIPES_TABLE: ${self:custom.tableName}
    S3_BUCKET: ${self:custom.bucketName}

functions:
  app:
    handler: index.handler
    events:
      - http: ANY /
      - http: 'ANY {proxy+}'
  getRecipe:
    handler: index.handler
    events:
      - http:
         path: recipes/{name}
         method: get
         cors: true
  allRecipes:
    handler: index.handler
    events:
      - http:
         path: allrecipes
         method: get
         cors: true
  addRecipe:
    handler: index.handler
    events:
      - http:
         path: recipes
         method: post
         cors: true
  uploadPhoto:
    handler: index.handler
    events:
      - http:
         path: uploadphoto
         method: post
         cors: true
  getPhoto:
    handler: index.handler
    events:
      - http:
         path: photo/{name}
         method: get
         cors: true

index.js excerpt:
const serverless = require('serverless-http');
const express = require('express');
const app = express();
const AWS = require('aws-sdk');
const cors = require('cors');
...
app.use(cors({origin: 'https://recipes.example.co'}))
//Upload Photo Endpoint
app.post('/uploadphoto', function (req, res) {
    const s3 = new AWS.S3();  // Create a new instance of S3
    const fileName = req.body.fileName;
    const fileType = req.body.fileType;

    const s3Params = {
        Bucket: S3_BUCKET,
        Key: fileName,
        Expires: 500,
        ContentType: fileType,
        ACL: 'public-read'
    };

    s3.getSignedUrl('putObject', s3Params, (err, data) => {
        if(err){
            console.log(err);
            res.json({success: false, error: err})
        }
    // Data payload of what we are sending back, the url of the signedRequest and a URL where we can access the content after its saved.
        const returnData = {
            signedRequest: data,
            url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
        };
    // Send it all back
        res.json({success:true, data:{returnData}});
  });

})

AddRecipeForm.js excerpt:
handleUpload = (ev) => {
    console.log("handleUpload")
    console.log(ev)
    let file = this.uploadInput.files[0];
    // Split the filename to get the name and type
    let fileParts = this.uploadInput.files[0].name.split('.');
    let fileName = fileParts[0];
    let fileType = fileParts[1];
    console.log("Preparing the upload");
    axios.post("https://bqdu4plthq.execute-api.us-east-1.amazonaws.com/dev/uploadphoto",{
      fileName : fileName,
      fileType : fileType
    })
    .then(response => {
      var returnData = response.data.data.returnData;
      var signedRequest = returnData.signedRequest;
      var url = returnData.url;
      this.setState({url: url})
      console.log("Recieved a signed request " + signedRequest);

     // Put the fileType in the headers for the upload
      var options = {
        headers: {
          'Content-Type': fileType
        }
      };
      axios.put(signedRequest,file,options)
      .then(result => {
        console.log("Response from s3")
        this.setState({success: true});
      })
      .catch(error => {
        console.error(error);
      })
    })
    .catch(error => {
      console.error(error);
    })
  }

When clicking the Upload Photo button which calls the handleUpload funciton in AddRecipeForm.js, I get the following errors in my console:
Origin https://recipes.example.co is not allowed by Access-Control-Allow-Origin.

XMLHttpRequest cannot load https://bqdu4plthq.execute-api.us-east-1.amazonaws.com/dev/uploadphoto due to access control checks.

Failed to load resource: Origin https://recipes.example.co is not allowed by Access-Control-Allow-Origin.

Note that every other route works (getRecipe, allRecipes, addRecipe) and sends CORS headers, so I'm not sure why my addphoto request from React to API Gateway isn't sending CORS headers, even though it should be using it in index.js.  Thanks in advance for help!

A: Your serverless.yml has the default defined function 'app', which is a catch-all route ({proxy+} matches all). It looks like that's the route you're hitting, instead of uploadPhoto, because your uploadPhoto route is defined as method POST, but your frontend axios request is using PUT.

A: Besides all the technical things (to be added) which are stated on several other Q/A make sure that your function returns the response to the front-end within 29 seconds. This is the default timeout (and maximum timeout) set for your response. After fixing this I was able to break the CORS error.


text:
Q: How to wait until button's disabled state is changed in testing library? I have a React component with a input field and a button disabled at the very beginning. This button's state ( disabled ) changes if input provided by user to input field is validated by API, which is called after anything is typed in input field.
I am testing by providing a valid input but it needs to wait until API's call is completed, so basically i want to test, if on providing a valid input, button get re enabled or not in my test.
I am doing this by following code:
userEvent.type(getByRole("textbox"), "HELLO");
await waitFor(() => expect(getByTestId("my-btn")).not.toBeDisabled());

But its not working even with a valid input

A: You can increase the waitFor timeout as explained in the doc:
await waitFor(() => expect(getByTestId("my-btn")).not.toBeDisabled(), {
  timeout: 5000,
});

Beyond 5000 you will probably need also to increase jest timeout.

A: For me waiting for a disabled state to dissapear doesn't work. I usually wait for something else to happen in the DOM.
Maybe using the input you typed something in...
userEvent.type(getByRole("textbox"), "HELLO");

expect(await expect(screen.getByDisplayValue('HELLO')).toBeInTheDocument());

expect(getByTestId("my-btn")).not.toBeDisabled()

Also, since you are waiting for the response of an API, you might want to mock the response of that call to something that will remove your disabled state.


text:
Q: Android KenBurnEffect Issue I have an issue related to KenBurnsEffect library.
In this library they set an images from remote URL..
like this..
 public static final String[] IMAGES20 = new String[] {

            "http://simpozia.com/pages/images/stories/windows-icon.png",
            "http://radiotray.sourceforge.net/radio.png",
            "http://www.bandwidthblog.com/wp-content/uploads/2011/11/twitter-logo.png",
            "http://weloveicons.s3.amazonaws.com/icons/100907_itunes1.png"
};

 List<String> urls = Arrays.asList(IMAGES20);

 final KenBurnsView kenBurnsView = (KenBurnsView)findViewById(R.id.ken_burns_view);

 kenBurnsView.initUrls(urls);

This works perfectly.
But in my project, i need to set images from drawable folder..
To reference a drawable as URL string, i have used drawable://" + R.drawable.img_splash_1,
Implementation is like this...
     List<String> IMAGES20= Arrays.asList(

               "drawable://" + R.drawable.img_splash_1,
                "drawable://" + R.drawable.img_splash_2,
                "drawable://" + R.drawable.img_splash_3,
                "drawable://" + R.drawable.img_splash_4,
                "drawable://" + R.drawable.img_splash_5,
                "drawable://" + R.drawable.img_splash_6,
                "drawable://" + R.drawable.img_splash_7

             );

   List<String> urls = Arrays.asList(IMAGES20);

   final KenBurnsView kenBurnsView = (KenBurnsView)findViewById(R.id.ken_burns_view);

   kenBurnsView.initUrls(urls);

But this does not work.. It shows a blank screen. No Exceptions nothing.
I can't understand what is the issue...
Please help me..

A: Take a look at this library, It may be helpful:
https://github.com/flavioarfaria/KenBurnsView

A: Did you solve ?
I think you should write like below.
List<Integer> resourceIDs = Arrays.asList(...);
kenBurnsView.initResourceIDs(resourceIDs);


text:
Q: json_encode of special chars from a MySQL database I need to encode a result from a MySQL query to JSON format.
My database is in the encoding utf8_unicode_ci.
In particular, I have some special chars (for example, €) stored in my database which produce a null value when I apply the PHP function json_encode.
How can I fix this?

A: My blind guess is that your MySQL database connection is not set to UTF-8, which leads to ISO-8859-1 characters being returned even if the source database is UTF-8.
Those characters will break json_encode() because they are invalid in the UTF-8 character set, which json_encode() expects.
You will probably have to set your connection encoding to UTF-8. How to do that depends on the library you are using.
In the mysql_* family of functions, one way is
mysql_query("SET names utf8;");

or in MySQL > 5.0.7, the new
mysql_set_charset("utf8");


text:
Q: Sacar valores de una lista y poderlos evaluar en una función Mi programa es de extremos de funciones multivariables y este tiene que graficar y determinar si es minimo relativo, maximo relativo o punto silla o no se puede decir. El problema que tengo es que al sacar valores y si estos son imaginarios hacer que termine el prgrama pero no funciona, el otro problema es para evaluar puntos criticos en una funcion, estos estan dados de forma de lista y al evalular la funcion para resolverla y proseguir me da un error
Mi codigo es este:
#enconding: utf-8

#De numpy se explorta arange y exp
from numpy import exp,arange
#De pylab se importa meshgrid, cm, imshow, contour, clabel, clorbar, axis, title y show
#enconding: utf-8

from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from sympy.matrices import hessian, zeros
import matplotlib.pyplot as plt
import sys
import numpy as np
import sympy as sym
sym.init_printing(use_latex="mathjax")

def gradient(f, varls):
    """ Calcula el gradiente de una función f(x1,x2,...)"""
    n = len(varls)
    G = zeros(n,1)
    for i in range(n):
        G[i] = f.diff(varls[i])
    return G
#Se define la funcion que se va a graficar
def z_func1(x,y):
    return (x**a+y**b+m*x+N*y+r)

def z_func2(x,y):
    return ((a/x)+(b/y)+m*x+N*y+r)

def graficaIntencidad(Z):
    #Se dibuja la funcion
    im = imshow(Z,cmap=cm.RdBu)
    #Se agrega el contorno de lineas con sus etiquetas
    cset = contour(Z,arange(-1,1.5,0.2),linewidths=2,cmap=cm.Set2)
    clabel(cset,inline=True,fmt='%1.1f',fontsize=10)

    #Se agrega la barra de colores a la derecha
    colorbar(im)
    #Se crea el titulo de la grafica con estilo latex
    title('$Hessiano$')
    #Se muestra la grafica
    show()

def grafica3D(X,Y,Z):
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.RdBu,linewidth=0, antialiased=False)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.show()
#entrada de valores
a= float(input("Da un valor para a: "))
b= float(input("Da un valor para b: "))
m= float(input("Da un valor para m: "))

N= int(input("Da un valor para n: "))
r= float(input("Da un valor para r: "))

x,y = sym.symbols("X,Y")
#zeros(shape, dtype). Crea un array de ceros compuesto de "shape" elementos".
print("Funcion 1=x**a+y**b+m*x+N*y+r")
print("Funcion 2=(a/x)+(b/y)+m*x+N*y+r")
f1=x**a+y**b+m*x+N*y+r
f2=(a/x)+(b/y)+m*x+N*y+r

#Primera forma de resolver con herramientas de sympy
G1 = gradient(f1, (x,y))
G2 = gradient(f2, (x,y))
F1= sym.Eq(G1,zeros(2,1))
F2= sym.Eq(G2,zeros(2,1))
sol1 = sym.solve(F1, (x,y))
sol2 = sym.solve(F2, (x,y))

#Si la lista contiene numeros imaginarios debería de salirse del programa
if sol1==False and sol2==False:
    print("No se puede calcular nada")
    sys.exit();
else: #Muestra los puntos críticos
    print("Los puntos críticos de f1 son: ",sol1)
    print("Los puntos críticos de f2 son: ",sol2)
print("------------------------")

print("Calculando la matriz Hessiana")
H1 = hessian(f1, (x,y))
H2 = hessian(f2, (x,y))
if H1 == False and H2 == False:
    print("Error")
    sys.exit()
else:
    print("------------------------")
    if H1 != 0 and H2 !=0:
        print("------------------------")
    elif index == "" :
        print("Error")
        sys.exit()

_x,_y = sol1[0][0], sol1[0][1]
_x,_y = sol2[0][0], sol2[0][1]
w = range(-10, 15)
#else:
print("------------------------")
H1 = H1.subs({x:_x, y:_y})
H2 = H2.subs({x:_x, y:_y})
if H1 is complex and H2 is complex:
    print("Error")
    sys.exit()
print("La matriz Hessiana de f1 es: ",H1)
print("La matriz Hessiana de f2 es: ",H2)
print("Calculando los eigenvalores")
egvals1 = H1.eigenvals()
egvals2 = H2.eigenvals()
if egvals1 is complex and egvals2 is complex:
    print("Son numeros complejos")
print("F1 = ",egvals1)
print("F2 = ",egvals2)
#Segunda forma de resolver el problema
#Primeras derivadas parciales.
diff1x= sym.diff(f1,x)
diff1y= sym.diff(f1,y)
diff2x= sym.diff(f2,x)
diff2y= sym.diff(f2,y)

#Segundas derivadas parciales
#F1
diff12x= sym.diff(diff1x,x)
diff12xy= sym.diff(diff1x,y)
diff12y= sym.diff(diff1y,y)

#F2
diff22x= sym.diff(diff2x,x)
diff22xy= sym.diff(diff2x,y)
diff22y= sym.diff(diff2y,y)

print("Derivada parcial de F1 respecto a x= ",diff1x)
print("Derivada parcial de F1 respecto a y= ",diff1y)
print("Derivada parcial de F2 respecto a x= ",diff2x)
print("Derivada parcial de F2 respecto a y= ",diff2y)

rdif1x=sym.solve(diff1x, [x,y])
rdif1y=sym.solve(diff1y, [x,y])
rdif2x=sym.solve(diff2x, [x,y])
rdif2y=sym.solve(diff2y, [x,y])

print("La solución de La derivada parcial de F1 respecto a x= ",rdif1x)
print("La solución de La derivada parcial de F1 respecto a y= ",rdif1y)
print("La solución de La derivada parcial de F2 respecto a x= ",rdif2x)
print("La solución de La derivada parcial de F2 respecto a y= ",rdif2y)

#Si los resultados tienen numeros complejos el programa deberia de terminar.
if rdif1x is complex and rdif1y is complex and rdif2x is complex and rdif2y is complex:
    sys.exit()

F1M=sym.Matrix([[diff12x,diff12xy],[diff12xy,diff12y]])
F2M=sym.Matrix([[diff22x,diff22xy],[diff22xy,diff22y]])
#Muestra la matriz Hessiana
print("Matriz F1=",F1M)
print("Matriz F1=",F2M)
#Resuelve la matriz de manera manual
RF1M=((diff12x*diff12y)-(diff12xy*diff12xy))
RF2M=((diff22x*diff22y)-(diff22xy*diff22xy))

print("Resultados de la matriz de F1= ",RF1M)
print("Resultados de la matriz de F2= ",RF2M)
#Aqui esta el problema principal.
R1=sym.solve(RF1M,[rdif1x, rdif1y])
R2=sym.solve(RF2M,[rdif2x, rdif2y])

print(R1)
print(R2)

#Grafica
if __name__ == '__main__':
    #rango de valores para x y y.
    x = arange(-3,3,0.10)
    y = arange(-3,3,0.10)

    #Se define la grilla de puntos
    X,Y = meshgrid(x, y)
    #Se evalua la funcion segun los valores de X y Y
    Z1 = z_func1(X, Y)
    Z2 = z_func2(X, Y)
    graficaIntencidad(Z1)
    graficaIntencidad(Z2)
    grafica3D(X,Y,Z1)
    grafica3D(X,Y,Z2)


text:
Q: Table of Outcomes for If/Then? I think I need a "table" of possibilities to go with an if/then command, but I'm not sure if one can do that in LaTeX.
I'm generating random equations in the form y=lx+a where l=slope and a=y-intercept and both l and a are randomly generated integers.
I'd like the equations to appear in fully simplified from. Examples:

*

*If a=o and l=2, I'd like y=lx+a to appear as y=2x.

*If a=-3 and l=0, I'd like y=lx+a to appear as y=-3.

More generally, I think that I need this:

What code can do this without some annoyingly nested set of \ifthenelse commands? Also, if anybody wants to update the tags, that would be great; I'm not actually sure which words to use to describe my type of question.
Thanks!

A: Examine the various cases; in this case \ifnum is much easier to cope with than \ifthenelse.
\documentclass{article}

\newcommand{\printeq}[2]{%
  \ensuremath{
    y=
    \ifnum#1=0 % no slope part
      #2
    \else
      \ifnum#1=1
      \else
        \ifnum#1=-1
         -
        \else
          #1
        \fi
      \fi x
      \ifnum#2>0
        +#2
      \else
        \ifnum#2=0
        \else
          #2
        \fi
      \fi
    \fi
  }%
}

\begin{document}

\printeq{-6}{-5}

\printeq{-6}{0}

\printeq{-6}{7}

\printeq{-1}{-5}

\printeq{-1}{0}

\printeq{-1}{7}

\printeq{0}{-5}

\printeq{0}{0}

\printeq{0}{7}

\printeq{1}{-5}

\printeq{1}{0}

\printeq{1}{7}

\printeq{8}{-5}

\printeq{8}{0}

\printeq{8}{7}

\end{document}

A:
\documentclass{article}

\edef\paa{\the\numexpr 1+\pdfuniformdeviate 9}
\edef\naa{\the\numexpr 1+\pdfuniformdeviate 9}
\edef\pll{\the\numexpr 1+\pdfuniformdeviate 9}
\edef\nll{\the\numexpr 1+\pdfuniformdeviate 9}
\begin{document}

\begin{tabular}{l|lll}
        &$l<0$ say $l=\nll$& $l=0$&$l>0$ say $l=\pll$\\\hline
$a<0$ say $a=-\naa$& $y=-\nll x-\naa$ & $y=-\naa$&$y=\pll x-\naa$\\
$a=0$              & $y=-\nll x$      & $y=0$    &$y=\pll x$     \\
$a>0$ say $a=\paa$ & $y=-\nll x+\paa$ & $y=\paa$ &$y=\pll x+\paa$\\
\end{tabular}

or if you just want one of the 9, then

\ifcase \pdfuniformdeviate 10
 $y=-\nll x-\naa$ \or $y=-\naa$\or$y=\pll x-\naa$\or
$y=-\nll x$      \or $y=0$    \or$y=\pll x$     \or
$y=-\nll x+\paa$ \or $y=\paa$ \or$y=\pll x+\paa$\fi

\end{document}


text:
Q: An object reference is required for the non-static field, method, or property (dataset) Why Method can`t send me values from database using dataset?
Here is example
Example with error
public string dane()
        {
            // Get the DataTable of a DataSet.

            DataTable table = DataSet1.Tables["Products"];
            DataRow[] rows = table.Select();

            string s ="";
            // Print the value one column of each DataRow.
            for (int i = 0; i < rows.Length; i++)
            {
                s += rows[i]["ProductID"] + "  ";
            }

            return s;

        }

Error - An object reference is required for the non-static field, method, or property
It`s not possible to find data. (but error is fixed)
public string dane()
{
    // Get the DataTable of a DataSet.
    DataSet1 dataSet = new DataSet1();
    DataTable table = dataSet.Tables["Products"];
    DataRow[] rows = table.Select();

    string s ="";
    // Print the value one column of each DataRow.
    for (int i = 0; i < rows.Length; i++)
    {
        s += rows[i]["ProductID"] + "  ";
    }

    return s;

}

A: Thats because your DataSet1 class is probably not static, though we don't know because you haven't shown us. You cannot reference Tables without creating a DataSet1 object first. I imagine you get the error here:
DataTable table = DataSet1.Tables["Products"];

And in your second code example, you actually create an instance of DataSet which resolves the error.
You can either keep your fix or make DataSet1 static, though in this case, it doesn't seem that that would be a good solution.

A: You have no reference to the dataset in the first example. You need to pass this in or make it a global variable.


text:
Q: passing SQL "IN" parameter list in jasperreport I am working on Jasper Reports and my query uses SQL 'IN' predicate.
SELECT customer_name AS NAME,
       id_customer   AS ID
  FROM customer
 WHERE customer_role IN ($P{roles})

Here the role parameter can have 1 or more integer values and will be dynamically decided when generating the jasper report.
Can anybody please help me on how to set the value of 'roles' parameter thru Java program dynamically.

A: Jasper Report has a special variable $X for that:
select * from customer where $X{IN,customer_role,roles}

should work. See here and here.

A: The examples linked to in the accepted answer don't come up for me.
An alternative that worked for me is instead of using:
...
WHERE customer_role IN ($P{roles})

I used this:
...
WHERE customer_role IN ($P!{roles})

And for the roles variable I pass in a String containing one or more values, each in single quotes, separated by commas (e.g., '1','2','3').
See here for reference.

A: To complement @Aaron response, you can configure a list parameter ("roles" in your case) within JasperSoft Studio as follows:


text:
Q: Creating many convex hulls MATLAB i'm new here and this is my first post.. i want to know if there is a way to calculate all the possible convex hulls from 100 random points.. i've created a code that does this right but it gives me an error at convhull and everything beneath that part can't be calculated.. in other words i'd like to know if there is a way i can use function convhull inside a for loop without getting an error..
HERE IS THE CODE
hold on
N=100;
Points = zeros(N,2);
for i=1:N
    Points(i,1)= rand(1,1)*100;
    Points(i,2)= rand(1,1)*100;
end

SortedX = sortrows(Points,1);
NewVertices = SortedX;

X = reshape(SortedX(:,1),2,[]);
X = X(:);
Y = reshape(SortedX(:,2),2,[]);
Y = Y(:);
plot(X,Y,'*');

while length(NewVertices)>=3
    NewVertices = NewVertices(NewVertices~=0);
    rowsNV = length(NewVertices(:,1));
    NewVertices = reshape(NewVertices,rowsNV/2,2);
    XNV = reshape(NewVertices(:,1),rowsNV/2,[]);
    XNV = XNV(:);
    YNV = reshape(NewVertices(:,2),rowsNV/2,[]);
    YNV = YNV(:);
    K = convhull(XNV,YNV);
    plot(XNV(K),YNV(K),'r-');
    for i=1:length(K)-1
        NewVertices(K(i),1)=0;
        NewVertices(K(i),2)=0;
    end

end

HERE IS THE ERROR
Error using convhull
Error computing the convex hull. Not
enough unique points specified.

Error in test2 (line 28)
    K = convhull(XNV,YNV);

Thanks in advance
co2ark5
HERE IS THE FINAL CODE THAT WORKS CORRECTLY WITH DAN'S HELP
hold on
N=100;
Points = rand(N,2);

SortedX = sortrows(Points,1);
NewVertices = SortedX;

plot(SortedX(:,1),SortedX(:,2),'*');

while length(NewVertices)>=3
    X=NewVertices(:,1);
    Y=NewVertices(:,2);
    K = convhull(X,Y);
    plot(X(K),Y(K),'r-');
    for i=1:length(K)-1
        NewVertices(K(i),1)=0;
        NewVertices(K(i),2)=0;
    end
    NewVertices = NewVertices(any(NewVertices,2),:);
end

A: The error is fairly expressive, you aren't specifying enough points (i.e. atleast 3 non colinear points). Please explain what you are trying to achieve with this code.
When do you get this error? I'm assuming not on the first run of the loop? After checking that there are more than 3 points you immediately potentially remove more points and then call convhull so it's quite possible that there are fewer than 3 points (and this is still ignoring the chance of colinearity). After the error, what is size(NewVertices)?
Some side comments: please explain that whole reshaping business before you plot (maybe add some comments). Also Points can be initialized much faster and simpler:
Points = rand(N, 2);

EDIT:
From reading your comments below it is clear to me that the logic of your loop is wrong. I cannot work out exactly how you are trying to remove points to create the new subset on which to find the hull, there are no comments and I don't get what you're doing with the reshape but I'm pretty sure all you need to do to fix this is to move the first line of your loop to the end like this:
while length(NewVertices)>=3

    rowsNV = length(NewVertices(:,1));
    NewVertices = reshape(NewVertices,rowsNV/2,2);
    XNV = reshape(NewVertices(:,1),rowsNV/2,[]);
    XNV = XNV(:);
    YNV = reshape(NewVertices(:,2),rowsNV/2,[]);
    YNV = YNV(:);
    K = convhull(XNV,YNV);
    plot(XNV(K),YNV(K),'r-');
    for i=1:length(K)-1
        NewVertices(K(i),1)=0;
        NewVertices(K(i),2)=0;
    end

    NewVertices = NewVertices(NewVertices~=0);

end

This way you find your hull immediately after checking the number of points rather than checking, then removing points, which is why your loop runs on 1 - 2 points.

A: Thanks a lot DAN,
first i tried to change only the line you said but it didn't work again 'cause of the reshape functions i was using.. Then i decided to change them and i made it more simple and it did work!!
HERE IS THE FINAL CODE THAT WORKS CORRECTLY WITH DAN'S HELP
hold on
N=100;
Points = rand(N,2);

SortedX = sortrows(Points,1);
NewVertices = SortedX;

plot(SortedX(:,1),SortedX(:,2),'*');

while length(NewVertices)>=3
    X=NewVertices(:,1);
    Y=NewVertices(:,2);
    K = convhull(X,Y);
    plot(X(K),Y(K),'r-');
    for i=1:length(K)-1
        NewVertices(K(i),1)=0;
        NewVertices(K(i),2)=0;
    end
    NewVertices = NewVertices(any(NewVertices,2),:);
end


text:
Q: Are Hack named functions fully first-class citizens? HHVM 3.9 is not such a fan of ternary statements with named functions, even when passed through fun(), but ≥3.10 is totally fine with them. It seems as though this is one of few cases, however, because 3.9 does accept named functions returned from concrete functions, as well as accepting named functions passed into other functions (3v4l):
<?hh
echo ((() ==> fun('strlen'))())('Hello'); // 5
echo (($f, $v) ==> $f($v))(strlen, 'Hello'); // 5 + Notice: Use of undefined constant strlen - assumed 'strlen'
echo (true ? strlen : intval)('100'); // Fatal error: syntax error, unexpected '(', expecting ',' or ';' on line 3

What changed between 3.9 and 3.10? Are there any cases in HHVM ≥3.10 where named functions cannot be referenced and used this way?

A: First, when writing Hack, don't write your code at toplevel; the hh_client typechecker can't check anything at toplevel. And 3v4l doesn't run the typechecker at all, you need to run it locally.
That said, no, Hack doesn't really have first-class functions. Most of its behaviour here it inherited from PHP, which also doesn't have them. Back when I was working on the Hack team, we tossed around a lot of ideas for adding them to the language; it's an obvious addition and need. But the need was never quite strong enough such that we sat down and actually worked out the details for both the type system and runtime implications; in particular, how to work out some of the scoping issues that the current callables have. Anonymous functions fill out enough of the need, especially with Hack's short lambda syntax, that there was always something more pressing to deal with.
So Hack just has PHP's normal callable forms; fun is one of a few special functions which give information to the typechecker that the string you specified actually represents a function so the typechecker can do proper type analysis. But at the end of the day, fun just boils down to the usual PHP callable forms with a bit of extra magic in the typechecker.
As to the behaviour you indicate in your 3v4l link. Using strlen and intval like that would cause a type error in Hack, since those are syntactically constants but constants with those names don't exist since Hack doesn't have first-class functions -- or it would if the code weren't at toplevel and you were running the typechecker. As to why it causes a parse error in HHVM 3.9 (which masks the "invalid constant" errors you see in 3.10), I'm not 100% sure. Judging from this example which works in PHP7 and HHVM 3.10, but not PHP5 and HHVM 3.9, my guess it is a PHP7 feature that is backwards compatible and so is always enabled in HHVM.


text:
Q: How to choose the right storage technology and design for a tree like date structure that requires fast reads I have a requirement to design a tree like data structure whereby child entities can inherit or override values from parent entities.

*

*client

*

*entity

*

*

*channel

If you could imagine three above entities with client being at level 0, entity at level 1 and channel at level 2. The entity level items can inherit or override attributes from the client level and channels can inherit or override attributes from their entity level parents.
I also need the channel to be sub-sectioned into groups where each channel can be valid from a specific dateTime. So if I make a query to get a specific channel I will pass current instance of time and I will need to get back the top first item which is less than the input datetime parameter.
Hopefully the tree's depth will be set at 3 and there won't be any extensions. My question is what would be the best approach for designing this data structure.
Should I have 3 tables for each type and have a view that is designed to allow for fast access to the data, or should I have a single table and use one of the three tree design methodologies described in this article?
What would be the upside and downside of each approach?

A: Noting the Relational database tag
The Relational Model handles hierarchies beautifully.  There is no need to do strange things, such as in the blog post: it is anti-Relational.  The hierarchy is implemented plainly, and all queries are simple.  Use SQL, the data sub-language for the RM, to obtain whatever "picture" or "view" you need of the data.

*

*If you want Relational, definitely three tables: one table would be horrendous because it is not Normalised.

*The Primary Keys I am giving you (Client, Entity, Channel) are short names or codes that the user has for Identifying their data. In the second and third tables, they are composites.  Such Keys are very fast.

*

*ie. it is not a surrogate, such as a Record ID, ID, id.  A surrogate is always an additional column and an additional index, which would make the tables distinctly slower.  Not to mention, the code required will be buggy and confusing.

*This is adequate for the level of your question, the SQL code required to navigate the structure is simple.

*To cater for the "inheritance or override" of the attributes, I can provide a more Normalised design, which will have no NULL columns, however it will require slightly more complex SQL code, which can be eased with the use of a View.  Please ask.
Relational Data Model

Note • Notation

*

*All my data models are rendered in IDEF1X, the Standard for modelling Relational databases since 1993

*My IDEF1X Introduction is essential reading for beginners.
Enjoy.


text:
Q: Poor fit using nlinfit and fminsearch in Matlab I have some reference data against which I want to fit some model data. I have developed a 5-param model for this purpose. The job now is to optimize the model params using Matlab. However, I have very poor fit for ref vs model data (r^2 in the range 0.6 only). I tried using fminsearch and nlinfit algorithms.
One probable reason might be that my params are not of similar order of magnitude (while 1 param is of range e-09, another is ~e03). I am unsure whether to use scaling/normalization of params, and if so how to go about it. Can anyone help?
Here's my code for your perusal:
voltage = xlsread('co_content_29_07_avik.xlsx','A9:A99'); % voltage
current = xlsread('co_content_29_07_avik.xlsx','B9:B99'); % current

% Cell characteristics from manufacturer's datasheet
V_oc = 0.665; %V
I_sc = 5.75; %A
V_mp = 0.56; % V
I_mp = 5.35; % A

a = 1.2 % educated guess

% Calculate thermal voltage
k = 1.3806e-23; %Boltzmann constant - Joule/Kelvin
T = 298;
q = 1.602e-19; %electron charge - Coulomb
n_cell = 1; % no. of cells
V_t = n_cell*k*T/q;

% Calculate unoptimized cell parameters (R_s, R_sh, I_0, I_ph, n)
A = a*V_t/I_mp;
B = -(V_mp*(2*I_mp - I_sc)/(V_mp*I_sc + V_oc*(I_mp - I_sc)));
C = -((2*V_mp - V_oc)/a*V_t) + (V_mp*I_sc - V_oc*I_mp)/(V_mp*I_sc + V_oc*(I_mp - I_sc));
D = (V_mp-V_oc)/(a*V_t);
R_s = A*lambertw((B*exp(C) - (D+C)))

R_sh_num = (V_mp-I_mp*R_s)*(V_mp - R_s*(I_sc-I_mp) - a*V_t);
R_sh_den = (V_mp-I_mp*R_s)*(I_sc-I_mp) - a*V_t*I_mp;
R_sh = R_sh_num/R_sh_den

I_0 = (I_sc*(R_sh + R_s) - V_oc)/(R_sh*exp(V_oc/(a*V_t)))

I_ph = (R_sh+R_s)*I_sc/R_sh

len = length(voltage);
for i=1:1:len
    non_exp1 = R_s*R_sh*I_0/(a*V_t*(R_s + R_sh));
    lambexp1 = R_sh*(R_s*I_ph + R_s*I_0 + voltage(i,1))/(a*V_t*(R_s + R_sh));
    lambarg1 = non_exp1*exp(lambexp1);
    firstterm1 = -voltage(i,1)/(R_s + R_sh);
    midterm1 = -(lambertw(lambarg1)*a*V_t/R_s);
    third1 = R_sh*(I_0 + I_ph)/(R_s + R_sh);
    I_1(i,1) = firstterm1 + midterm1 + third1;
end

% Optimize using fminsearch algo
 fun = @(p) sum((current - (voltage/(p(1)+p(2)) - (lambertw((p(1)*p(2)*p(3))/(p(5)*V_t*(p(1)+p(2)))))*exp((p(2)*(p(1)*p(4)+p(1)*p(3)+voltage))/(p(5)*V_t*(p(1)+p(2))))*p(5)*V_t/p(1) + (p(2)*(p(3)+p(4))/(p(1)+p(2))))).^2);

% initial guess for param
pguess = [0.005,4.75,0.000000001,5.75,1.2];

%optimize
[x,fval,exitflag,output] = fminsearch(fun,pguess,optimset('MaxFunEvals',1000))


text:
Q: Hibernate persist mapping I have 3 table A ,B and mapping table A_B, which contains Id's of both (A_ID and B_ID). Following is how the java classes which map these 3 tables look like:
@Entity
@Table(name = "A")
public class A {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "ID")
    private Long id;

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name = "FK_A", referencedColumnName="Id", nullable = false)
    private Set<A_B> ab;

    //Other attributes, Getters Setters etc.
}

@Entity
@Table(name = "A_B")
public class A_B {

     @Id
     @GeneratedValue(strategy = GenerationType.SEQUENCE)
     @Column(name = "ID")
     private Long id;

     @ManyToOne(cascade=CascadeType.ALL)
     @JoinColumn(name = "FK_B", nullable = false)
     private B b;

     //Other attributes, Getters Setters etc.
 }

Entity
@Table(name = "B")
public class B  {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "ID")
    private Long id;

    //Other attributes, Getters Setters etc.
}

Now lets say I have already persisted an object of B (b). Now I want to persist an Object of A (a) and the association between these two (ab). I have my code like :
@PersistenceContext(unitName = "demoPU")
private EntityManager em;

B b = em.createNamedQuery(queryName, B); // Getting obj of B
A a = new A();
A_B ab = new A_B();
ab.setB(b); // Setting B in relationship
a.setAb(ab);

em.persist(a);

However this tried to persist b again & since its id is already set, it throws en exception:
org.hibernate.PersistentObjectException: detached entity passed to persist

Can you let me know how can I persist the association in this case without having to persist B again ?

A: Why don't you try to just set a and not b ?
You could also empty the set in a so it doesn't try to persist it.
EDIT: as said in comments it would not have the intended effect. You should use saveOrUpdate() instead of persist() as suggested in org.hibernate.PersistentObjectException: detached entity passed to persist


text:
Q: How to link a pre-installed application to the Android Market? I just got a great news today, my own application will be included on all the phone of the brand "X" in my little country (Belgium)
I got so excited when I am looking at the phones in the shops and I can see my application by default.
Unfortunately, the brand "X" is noobie and seem unable to link my app to the Market, so the users cannot be aware that there is an upgrade in the Android Market.
they just ask me by email

Do you know how to link apps to the market to get the update
  automatic?

I know that I don't work for this company and they will get benefit with this information, but have you got an Idea on how to achieve this?
Thank a lot.
Edit:
Seem that the app installed in system/app does not automatically get the Market link , but app installed in data/app well.

A: It is my understanding that if an app has the same app name (the internal app name that's a package name) and digital signer as an app in the market, the market will show updates for the app even if the app was not originally installed through the market.