问:
Kubernetes cannot access grafana and prometheus fron Google cloud platform
I have followed this link to install Grafana/Prometheus in Google cloud kubernetes. I hope it is deployed successfully please find the following response for reference,

Service Created successfully :

```<code>kubectl --namespace=monitoring get services
NAME         TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
grafana      NodePort   10.27.249.8     <none>        3000:32703/TCP   1h
prometheus   NodePort   10.27.249.233   <none>        9090:31939/TCP   1h
</code>```

Namespace created successfully :

```<code>kubectl get namespaces
NAME          STATUS    AGE
default       Active    19h
kube-public   Active    19h
kube-system   Active    19h
monitoring    Active    1h
</code>```

PODS response :

```<code>kubectl --namespace=monitoring get pods
NAME                          READY     STATUS             RESTARTS   AGE
grafana-1323121529-8614m      1/1       Running            0          1h
node-exporter-lw8cr           0/1       CrashLoopBackOff   17         1h
node-exporter-nv85s           0/1       CrashLoopBackOff   17         1h
node-exporter-r2rfl           0/1       CrashLoopBackOff   17         1h
prometheus-3259208887-x2zjc   1/1       Running            0          1h
</code>```

Now i am trying to expose the external-Ip for Grafana but i couldn't keep on getting following exception "Error from server (AlreadyExists): services "prometheus" already exists"

```<code>kubectl --namespace=monitoring expose deployment/prometheus --type=LoadBalancer

Error from server (AlreadyExists): services "prometheus" already exists
</code>```

Edited

```<code>kubectl -n monitoring edit service prometheus

Edit cancelled, no changes made.
</code>```

答:
As you have already deployed the Prometheus service manifest file in the monitoring namespace. However, you are trying to deploy a service with the same name at the same namespace.That's not acceptable As Two Service cannot co-exist in the same namespace with same name.

Solutions for your problem

I would use the following command to edit the already deployed Service.

```<code>kubectl -n monitoring edit service prometheus
</code>```

Then your favourite text editor would pop up, you just need to update
type: LoadBalancer

Basically, your service will be edited.

Edited

If you are not able to use the above command, then you do following steps :
you need to edit the Prometheus service manifest file and update it with type: LoadBalancer.

Now you need to apply kubectl apply -f prometheus-service.yaml

Body:
I have followed this link to install Grafana/Prometheus in Google cloud kubernetes. I hope it is deployed successfully please find the following response for reference,

Service Created successfully :

kubectl --namespace=monitoring get services
NAME         TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
grafana      NodePort   10.27.249.8     <none>        3000:32703/TCP   1h
prometheus   NodePort   10.27.249.233   <none>        9090:31939/TCP   1h

Namespace created successfully :

kubectl get namespaces
NAME          STATUS    AGE
default       Active    19h
kube-public   Active    19h
kube-system   Active    19h
monitoring    Active    1h

PODS response :

kubectl --namespace=monitoring get pods
NAME                          READY     STATUS             RESTARTS   AGE
grafana-1323121529-8614m      1/1       Running            0          1h
node-exporter-lw8cr           0/1       CrashLoopBackOff   17         1h
node-exporter-nv85s           0/1       CrashLoopBackOff   17         1h
node-exporter-r2rfl           0/1       CrashLoopBackOff   17         1h
prometheus-3259208887-x2zjc   1/1       Running            0          1h

Now i am trying to expose the external-Ip for Grafana but i couldn't keep on getting following exception "Error from server (AlreadyExists): services "prometheus" already exists"

kubectl --namespace=monitoring expose deployment/prometheus --type=LoadBalancer

Error from server (AlreadyExists): services "prometheus" already exists

Edited

kubectl -n monitoring edit service prometheus

Edit cancelled, no changes made.

Body:
As you have already deployed the Prometheus service manifest file in the monitoring namespace. However, you are trying to deploy a service with the same name at the same namespace.That's not acceptable As Two Service cannot co-exist in the same namespace with same name.

Solutions for your problem

I would use the following command to edit the already deployed Service.

kubectl -n monitoring edit service prometheus

Then your favourite text editor would pop up, you just need to update
type: LoadBalancer

Basically, your service will be edited.

Edited

If you are not able to use the above command, then you do following steps :
you need to edit the Prometheus service manifest file and update it with type: LoadBalancer.

Now you need to apply kubectl apply -f prometheus-service.yaml


来源: stackexchange

问:
Smooth animation on scroll
I have a navbar with a function that changes it's size on scroll by adding a class named "shrink", it's working fine but when it adds the class and changes it's size it happens fast which doesn't look nice to me, i want to smooth this animation to make the shrinking look nicer but it's not working with me, here is my code:

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding-top: 50px;
  min-height:800px
}

nav a {
  padding-top: 20px !important;
  padding-bottom: 20px !important;
  font-size: 18px;
}

nav .navbar-toggle {
  margin: 13px 15px 13px 0;
}

.navbar-brand {
  font-size: 30px;
}

nav.navbar.shrink {
  min-height: 35px;
}

nav.shrink a {
  padding-top: 10px !important;
  padding-bottom: 10px !important;
  font-size: 15px;
}

nav.shrink .navbar-brand {
  font-size: 25px;
}

nav.shrink .navbar-toggle {
  padding: 4px 5px;
  margin: 8px 15px 8px 0;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

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

      </button>
      Brand

Home

Bootstrap starter template

Use this document as a way to quickly start any new project.
 All you get is this text and a mostly barebones HTML document.

Use this document as a way to quickly start any new project.
 All you get is this text and a mostly barebones HTML document.

```

答:
check this. I just add only transition here..

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding-top: 50px;
  min-height:800px
}

nav a {
  padding-top: 20px !important;
  padding-bottom: 20px !important;
  font-size: 18px;
}

nav .navbar-toggle {
  margin: 13px 15px 13px 0;
  -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}

.navbar-brand {
  font-size: 30px;
      -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}

nav.navbar.shrink {
  min-height: 35px;
    -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}

nav.shrink a {
  padding-top: 10px !important;
  padding-bottom: 10px !important;
  font-size: 15px;
}

nav.shrink .navbar-brand {
  font-size: 25px;
}

nav.shrink .navbar-toggle {
  padding: 4px 5px;
  margin: 8px 15px 8px 0;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

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

      </button>
      Brand

Home

Bootstrap starter template

Use this document as a way to quickly start any new project.
 All you get is this text and a mostly barebones HTML document.

Use this document as a way to quickly start any new project.
 All you get is this text and a mostly barebones HTML document.

```

ContentLicense: CC BY-SA 3.0

Title: Smooth animation on scroll

Body:
I have a navbar with a function that changes it's size on scroll by adding a class named "shrink", it's working fine but when it adds the class and changes it's size it happens fast which doesn't look nice to me, i want to smooth this animation to make the shrinking look nicer but it's not working with me, here is my code:

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
});

body {
  padding-top: 50px;
  min-height:800px
}

nav a {
  padding-top: 20px !important;
  padding-bottom: 20px !important;
  font-size: 18px;
}

nav .navbar-toggle {
  margin: 13px 15px 13px 0;
}

.navbar-brand {
  font-size: 30px;
}

nav.navbar.shrink {
  min-height: 35px;
}

nav.shrink a {
  padding-top: 10px !important;
  padding-bottom: 10px !important;
  font-size: 15px;
}

nav.shrink .navbar-brand {
  font-size: 25px;
}

nav.shrink .navbar-toggle {
  padding: 4px 5px;
  margin: 8px 15px 8px 0;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

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

      </button>
      Brand

Home

Bootstrap starter template

Use this document as a way to quickly start any new project.
 All you get is this text and a mostly barebones HTML document.

Use this document as a way to quickly start any new project.
 All you get is this text and a mostly barebones HTML document.

Body:
check this. I just add only transition here..

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
});

body {
  padding-top: 50px;
  min-height:800px
}

nav a {
  padding-top: 20px !important;
  padding-bottom: 20px !important;
  font-size: 18px;
}

nav .navbar-toggle {
  margin: 13px 15px 13px 0;
  -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}

.navbar-brand {
  font-size: 30px;
      -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}

nav.navbar.shrink {
  min-height: 35px;
    -moz-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
}

nav.shrink a {
  padding-top: 10px !important;
  padding-bottom: 10px !important;
  font-size: 15px;
}

nav.shrink .navbar-brand {
  font-size: 25px;
}

nav.shrink .navbar-toggle {
  padding: 4px 5px;
  margin: 8px 15px 8px 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Brand</a>
    </div>
    <div class="collapse navbar-collapse">
      <ul class="nav navbar-nav pull-right">
        <li class="active"><a href="#">Home</a></li>
      </ul>
    </div><!--/.nav-collapse -->
  </div>
</nav>

<div class="container">
  <div class="text-center">
    <h1>Bootstrap starter template</h1>
    <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
  </div>
  <div class="text-center">
    <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
  </div>

</div>


问:
Socket.io emitting values inside ES6 class
I wonder if any smart individuals could show me how to implement Socket.IO in an OOP environment with ES6 classes. The main problem I keep running into with Socket.io is passing around the server object, in my case called 'io'. Almost every example I've seen of socket.io has been pure spaghetti code, one file with many socket related events and logic. First I tried to pass the server object, io, to new class's constructor, but for some reason you end up with a nasty "RangeError: Maximum call stack size exceeded" error message. Then I've tried to wrap my classes in module.exports function which parameter should contain the io object. Which is fine for the first class. Let's say I pass the io object into my Game, great works as expected. But when I try to reference the io object down to the Round class(Game holds an array of Rounds) I can't. Because that is one hell of a bad practice in NodeJS, require should be global and not inside the modules/functions. So I'm once again back with the same issue.

app.js(where I require the main sockets file)

```<code>const io = socketio(server, { origins: '*:*' });
...
require('./sockets')(io);
</code>```

sockets/index.js(where I initialize my game server, and handle incoming messages from client sockets)

```<code>const actions = require('../actions.js');
const chatSockets = require('./chat-sockets');
const climbServer = require('./climb-server');
const authFunctions = require('../auth-functions');

module.exports = (io) => {
    io.on('connection', (client) => {
        console.log('client connected...');
        // Standard join, verify the requested room; if it exists let the client join it.
        client.on('join', (data) => {
            console.log(data);
            console.log(`User ${data.username} tries to join ${data.room}`);
            console.log(`Client joined ${data.room}`);
            client.join(data.room);
        });

        client.on('disconnect', () => {
            console.log('Client disconnected');
        });

        client.on(actions.CREATE_GAME, (hostParticipant) => {
            console.log('CREATE_GAME', hostParticipant);

            // Authorize socket sender by token?
            // Create a new game, and set the host to the host participant
            climbServer.createGame(io, hostParticipant);
        });

        client.on(actions.JOIN_GAME, (tokenizedGameId) => {
            console.log('JOIN_GAME');

            const user = authFunctions.getPayload(tokenizedGameId.token);

            // Authorize socket sender by token?
            // Create a new game, and set the host to the host participant
            const game = climbServer.findGame(tokenizedGameId.content);
            game.joinGame(user);
        });
    });
};
</code>```

climbServer.js(My game server that keeps track of active games)

```<code>const actions = require('../actions.js');
const Game = require('../models/game');

const climbServer = { games: { }, gameCount: 0 };

climbServer.createGame = (io, hostParticipant) => {
    // Create a new game instance
    const newGame = new Game(hostParticipant);
    console.log('New game object created', newGame);

    // Store it in the list of game
    climbServer.games[newGame.id] = newGame;

    // Keep track
    climbServer.gameCount += 1;

    // Notify clients that a new game was created
    io.sockets.in('climb').emit(actions.CLIMB_GAME_CREATED, newGame);
};

climbServer.findGame = gameId => climbServer.games[gameId];

module.exports = climbServer;
</code>```

Game.js(ES6 class that SHOULD be able to emit to all connected sockets)

```<code>const UUID = require('uuid');
const Round = require('./round');

class Game {
    // Constructor
    constructor(hostParticipant) {
        this.id = UUID();
        this.playerHost = hostParticipant;
        this.playerClient = null;
        this.playerCount = 1;
        this.rounds = [];
        this.timestamp = Date.now();
    }

    joinGame(clientParticipant) {
        console.log('Joining game', clientParticipant);
        this.playerClient = clientParticipant;
        this.playerCount += 1;

        // Start the game by creating the first round
        return this.createRound();
    }

    createRound() {
        console.log('Creating new round at Game: ', this.id);
        const newRound = new Round(this.id);

        return this.rounds.push(newRound);
    }
}

module.exports = Game;
</code>```

Round.js(ES6 class that is used by the Game class(stored in a rounds array))

```<code>const actions = require('../actions.js');

class Round {
    constructor(gameId) {
        console.log('Initializing round of gameId', gameId);
        this.timeLeft = 60;
        this.gameId = gameId;
        this.winner = null;
        this.timestamp = Date.now();

        // Start countdown when class is instantiated
        this.startCountdown();
    }

    startCountdown() {
        const countdown = setInterval(() => {
            // broadcast to every client
            io.sockets.in(this.gameId).emit(actions.ROUND_TIMER, { gameId: this.gameId, timeLeft: this.timeLeft });
            if (this.timeLeft === 0) {
                // when no time left, stop counting down
                clearInterval(countdown);
                this.onRoundEnd();
            } else {
                // Countdown
                this.timeLeft -= 1;
                console.log('Countdown', this.timeLeft);
            }
        }, 1000);
    }

    onRoundEnd() {
        // Evaluate who won
        console.log('onRoundEnd: ', this.gameId);
    }
}

module.exports = Round;
</code>```

TO SUMMARIZE with a question: How can I pass a reference of io to my classes so that I'm able to emit to connected sockets within these classes?
This doesn't necessarily have to be ES6 classes, it can be NodeJS objects using the .prototype property. I just want a mainatainable way to handle my game server with sockets... ANY HELP IS APPRECIATED!

答:
After hours upon hours I figured out a solution. If anyone runs into the same thing check my solution out below. Not the best, but much better than putting all socket related code in one file...

Game.js(ES6 Class). Focus on the first line containing 'module.exports'.

```<code>const GameFactory = require('../models/game');

const climbServer = { games: { }, gameCount: 0 };

climbServer.createGame = (io, hostParticipant) => {
    // Create a new game instance
    const Game = GameFactory(io);
    const newGame = new Game(hostParticipant);
    console.log('New game object created', newGame);

    // Store it in the list of game
    climbServer.games[newGame.id] = newGame;

    // Keep track
    climbServer.gameCount += 1;

    return newGame;
};

climbServer.findGame = gameId => climbServer.games[gameId];

module.exports = climbServer;
</code>```

The trick is to use this factory pattern where you first declare:

```<code>const GameFactory = require('../models/game');
</code>```

Then initialize the factory with passing in the Socket.io server object, in my case 'io'. IF YOU pass it in via the constructor you end up with a RangeError, therefore this is the only way. Once again not certain how this code performs in comparison to spaghetti code.

```<code>const Game = GameFactory(io);
</code>```

Finally, you can now instantiate instances of your class:

```<code>const newGame = new Game(hostParticipant);
</code>```

If anyone have improvements or thoughts, please leave me a comment. Still uncertain about the quality of this code.

Body:
I wonder if any smart individuals could show me how to implement Socket.IO in an OOP environment with ES6 classes. The main problem I keep running into with Socket.io is passing around the server object, in my case called 'io'. Almost every example I've seen of socket.io has been pure spaghetti code, one file with many socket related events and logic. First I tried to pass the server object, io, to new class's constructor, but for some reason you end up with a nasty "RangeError: Maximum call stack size exceeded" error message. Then I've tried to wrap my classes in module.exports function which parameter should contain the io object. Which is fine for the first class. Let's say I pass the io object into my Game, great works as expected. But when I try to reference the io object down to the Round class(Game holds an array of Rounds) I can't. Because that is one hell of a bad practice in NodeJS, require should be global and not inside the modules/functions. So I'm once again back with the same issue.

app.js(where I require the main sockets file)

const io = socketio(server, { origins: '*:*' });
...
require('./sockets')(io);

sockets/index.js(where I initialize my game server, and handle incoming messages from client sockets)

const actions = require('../actions.js');
const chatSockets = require('./chat-sockets');
const climbServer = require('./climb-server');
const authFunctions = require('../auth-functions');

module.exports = (io) => {
    io.on('connection', (client) => {
        console.log('client connected...');
        // Standard join, verify the requested room; if it exists let the client join it.
        client.on('join', (data) => {
            console.log(data);
            console.log(`User ${data.username} tries to join ${data.room}`);
            console.log(`Client joined ${data.room}`);
            client.join(data.room);
        });

        client.on('disconnect', () => {
            console.log('Client disconnected');
        });

        client.on(actions.CREATE_GAME, (hostParticipant) => {
            console.log('CREATE_GAME', hostParticipant);

            // Authorize socket sender by token?
            // Create a new game, and set the host to the host participant
            climbServer.createGame(io, hostParticipant);
        });

        client.on(actions.JOIN_GAME, (tokenizedGameId) => {
            console.log('JOIN_GAME');

            const user = authFunctions.getPayload(tokenizedGameId.token);

            // Authorize socket sender by token?
            // Create a new game, and set the host to the host participant
            const game = climbServer.findGame(tokenizedGameId.content);
            game.joinGame(user);
        });
    });
};

climbServer.js(My game server that keeps track of active games)

const actions = require('../actions.js');
const Game = require('../models/game');

const climbServer = { games: { }, gameCount: 0 };

climbServer.createGame = (io, hostParticipant) => {
    // Create a new game instance
    const newGame = new Game(hostParticipant);
    console.log('New game object created', newGame);

    // Store it in the list of game
    climbServer.games[newGame.id] = newGame;

    // Keep track
    climbServer.gameCount += 1;

    // Notify clients that a new game was created
    io.sockets.in('climb').emit(actions.CLIMB_GAME_CREATED, newGame);
};

climbServer.findGame = gameId => climbServer.games[gameId];

module.exports = climbServer;

Game.js(ES6 class that SHOULD be able to emit to all connected sockets)

const UUID = require('uuid');
const Round = require('./round');

class Game {
    // Constructor
    constructor(hostParticipant) {
        this.id = UUID();
        this.playerHost = hostParticipant;
        this.playerClient = null;
        this.playerCount = 1;
        this.rounds = [];
        this.timestamp = Date.now();
    }

    joinGame(clientParticipant) {
        console.log('Joining game', clientParticipant);
        this.playerClient = clientParticipant;
        this.playerCount += 1;

        // Start the game by creating the first round
        return this.createRound();
    }

    createRound() {
        console.log('Creating new round at Game: ', this.id);
        const newRound = new Round(this.id);

        return this.rounds.push(newRound);
    }
}

module.exports = Game;

Round.js(ES6 class that is used by the Game class(stored in a rounds array))

const actions = require('../actions.js');

class Round {
    constructor(gameId) {
        console.log('Initializing round of gameId', gameId);
        this.timeLeft = 60;
        this.gameId = gameId;
        this.winner = null;
        this.timestamp = Date.now();

        // Start countdown when class is instantiated
        this.startCountdown();
    }

    startCountdown() {
        const countdown = setInterval(() => {
            // broadcast to every client
            io.sockets.in(this.gameId).emit(actions.ROUND_TIMER, { gameId: this.gameId, timeLeft: this.timeLeft });
            if (this.timeLeft === 0) {
                // when no time left, stop counting down
                clearInterval(countdown);
                this.onRoundEnd();
            } else {
                // Countdown
                this.timeLeft -= 1;
                console.log('Countdown', this.timeLeft);
            }
        }, 1000);
    }

    onRoundEnd() {
        // Evaluate who won
        console.log('onRoundEnd: ', this.gameId);
    }
}

module.exports = Round;

TO SUMMARIZE with a question: How can I pass a reference of io to my classes so that I'm able to emit to connected sockets within these classes?
This doesn't necessarily have to be ES6 classes, it can be NodeJS objects using the .prototype property. I just want a mainatainable way to handle my game server with sockets... ANY HELP IS APPRECIATED!

Body:
After hours upon hours I figured out a solution. If anyone runs into the same thing check my solution out below. Not the best, but much better than putting all socket related code in one file...

Game.js(ES6 Class). Focus on the first line containing 'module.exports'.

const GameFactory = require('../models/game');

const climbServer = { games: { }, gameCount: 0 };

climbServer.createGame = (io, hostParticipant) => {
    // Create a new game instance
    const Game = GameFactory(io);
    const newGame = new Game(hostParticipant);
    console.log('New game object created', newGame);

    // Store it in the list of game
    climbServer.games[newGame.id] = newGame;

    // Keep track
    climbServer.gameCount += 1;

    return newGame;
};

climbServer.findGame = gameId => climbServer.games[gameId];

module.exports = climbServer;

The trick is to use this factory pattern where you first declare:

const GameFactory = require('../models/game');

Then initialize the factory with passing in the Socket.io server object, in my case 'io'. IF YOU pass it in via the constructor you end up with a RangeError, therefore this is the only way. Once again not certain how this code performs in comparison to spaghetti code.

const Game = GameFactory(io);

Finally, you can now instantiate instances of your class:

const newGame = new Game(hostParticipant);

If anyone have improvements or thoughts, please leave me a comment. Still uncertain about the quality of this code.


问:
How to get values of custom Azure AD B2C user profiles properties
I have an Azure AD B2C tenant and app within it with enabled authentication using Facebook, other AAD and local accounts. Users in B2C have some custom fields which are populated on registration and used as claims in JWT token.

But I cannot see this fields value's anywhere in the Azure portal nor using Microsoft Graph API.

Where they are stored and how to get access to them?

答:
See this guide to include custom claims/attributes in your JWT: Use custom attributes to collect information about your consumers

See this guide: Use the Azure AD Graph API and sample app to view custom claims via Azure AD Graph API.

In the Graph API they will come back as: extension_[GUID]_[ClaimName]


问:
Detect when iPhone is being unplugged and plugged in
I am just trying to write simple code that detects when the iPhone is unplugged and then plugged in. But being event-driven, instead of using a while loop. This code does work, but doesn't detect if the phone is unplugged and will not update the printed text.

EDIT
In the long run I just want the phone to play a sound whenever the iPhone is unplugged. (Sorry for leaving the end goal out.). I was using this print statements just so I can make sure it was working.

```<code>func startCharger()
    {

        printscreen.text="Started charger protocol"

       UIDevice.current.isBatteryMonitoringEnabled=true

        if(UIDevice.current.batteryState == .unplugged)
        {
            printscreen.text="Battery is unplugged"
        }
        else
        {
            printscreen.text="Battery is plugged in"
        }
    }
</code>```

答:
Quick implementation of Dule' code.
Check if the power is connected.
Copy these functions into your class.
Call isPowerConnected() in the viewDidLoad</p>

```<code>func isPowerConnected(){
    UIDevice.current.isBatteryMonitoringEnabled = true
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(batteryStateChanged),
        name: .UIDeviceBatteryStateDidChange,
        object: nil)
}

var chargingVar = "" //Empty Variable

func batteryStateChanged(){
    if (UIDevice.current.batteryState == .charging) {    //Here we check if the device is charging
        UIApplication.shared.isIdleTimerDisabled = true  //Here we disable the lock screen time out value
        self.chargingVar = "is charging. \u{1F603}" //Here we change the variable to "is charging"
             chargingAlaer()    //If power is pluged in we send an Alert
      }else{
        self.chargingVar = "is not charging. \u{1F622} "  //Here we change the variable to "is not charging"
             chargingAlaer()         //If power is not pluged we send an Alert
    }

}

func chargingAlaer(){
    let alertController = UIAlertController(title: "Charging Status",
                                            message: "Your device \(chargingVar)",
        preferredStyle: UIAlertControllerStyle.alert)
    let ok = UIAlertAction(title: "OK",
                           style: UIAlertActionStyle.default,
                           handler: {(action) -> Void in
    })
    alertController.addAction(ok)
    self.present(alertController, animated: true, completion: nil)
}
</code>```

Body:
I am just trying to write simple code that detects when the iPhone is unplugged and then plugged in. But being event-driven, instead of using a while loop. This code does work, but doesn't detect if the phone is unplugged and will not update the printed text.

EDIT
In the long run I just want the phone to play a sound whenever the iPhone is unplugged. (Sorry for leaving the end goal out.). I was using this print statements just so I can make sure it was working.

func startCharger()
    {

        printscreen.text="Started charger protocol"

       UIDevice.current.isBatteryMonitoringEnabled=true

        if(UIDevice.current.batteryState == .unplugged)
        {
            printscreen.text="Battery is unplugged"
        }
        else
        {
            printscreen.text="Battery is plugged in"
        }
    }

Body:
Quick implementation of Dule' code.
Check if the power is connected.
Copy these functions into your class.
Call isPowerConnected() in the viewDidLoad

func isPowerConnected(){
    UIDevice.current.isBatteryMonitoringEnabled = true
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(batteryStateChanged),
        name: .UIDeviceBatteryStateDidChange,
        object: nil)
}

var chargingVar = "" //Empty Variable

func batteryStateChanged(){
    if (UIDevice.current.batteryState == .charging) {    //Here we check if the device is charging
        UIApplication.shared.isIdleTimerDisabled = true  //Here we disable the lock screen time out value
        self.chargingVar = "is charging. \u{1F603}" //Here we change the variable to "is charging"
             chargingAlaer()    //If power is pluged in we send an Alert
      }else{
        self.chargingVar = "is not charging. \u{1F622} "  //Here we change the variable to "is not charging"
             chargingAlaer()         //If power is not pluged we send an Alert
    }

}

func chargingAlaer(){
    let alertController = UIAlertController(title: "Charging Status",
                                            message: "Your device \(chargingVar)",
        preferredStyle: UIAlertControllerStyle.alert)
    let ok = UIAlertAction(title: "OK",
                           style: UIAlertActionStyle.default,
                           handler: {(action) -> Void in
    })
    alertController.addAction(ok)
    self.present(alertController, animated: true, completion: nil)
}


问:
how to get post category id
i have a loop in my index.php
and i want to add category id to post class

i try'd many code but i did't got the right code

here is what i have:

```<code><?php if (have_posts()):?>
    <?php $catID = get_the_category('id');?>
    <ul>
        <?php while(have_posts()): the_post();?>
        <li class="cat<?php get_the_category( $post->ID );?>">
            <a href="<?php the_permalink();?>">
                <?php $src= wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), array(250,220), false, ''); $thumbnailSrc = $src[0]; ?>
                <img class="thumbnail" src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php echo $thumbnailSrc;?>&w=250&h=220&zc=1q=100" alt="">
                <span class="hover"></span>
                <h2><?php the_title();?></h2>
                <h3>توضیحات بیشتر<?php echo $catID; ?></h3>
            </a>
        </li>
        <?php endwhile;?>
    </ul>
<?php endif;?>
</code>```

答:
Since you're inside a loop, you should use the_category() instead of get_the_category()

```<code> <?php if (have_posts()):?>

        <ul>
            <?php while(have_posts()): the_post();?>
            <li class="cat<?php the_category();?>">
                <a href="<?php the_permalink();?>">
                    <?php $src= wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), array(250,220), false, ''); $thumbnailSrc = $src[0]; ?>
                    <img class="thumbnail" src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php echo $thumbnailSrc;?>&w=250&h=220&zc=1q=100" alt="">
                    <span class="hover"></span>
                    <h2><?php the_title();?></h2>
                    <h3>توضیحات بیشتر<?php echo $catID; ?></h3>
                </a>
            </li>
            <?php endwhile;?>
        </ul>
    <?php endif;?>
</code>```

Title: how to get post category id

Body:
i have a loop in my index.php
and i want to add category id to post class

i try'd many code but i did't got the right code

here is what i have:

<?php if (have_posts()):?>
    <?php $catID = get_the_category('id');?>

        <?php while(have_posts()): the_post();?>
        <li class="cat<?php get_the_category( $post->ID );?>">
            <a href="<?php the_permalink();?>">
                <?php $src= wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), array(250,220), false, ''); $thumbnailSrc = $src[0]; ?>
                <img class="thumbnail" src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php echo $thumbnailSrc;?>&w=250&h=220&zc=1q=100" alt="">

<?php the_title();?>

توضیحات بیشتر<?php echo $catID; ?>

        <?php endwhile;?>

<?php endif;?>

Body:
Since you're inside a loop, you should use the_category() instead of get_the_category()

 <?php if (have_posts()):?>

        <ul>
            <?php while(have_posts()): the_post();?>
            <li class="cat<?php the_category();?>">
                <a href="<?php the_permalink();?>">
                    <?php $src= wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), array(250,220), false, ''); $thumbnailSrc = $src[0]; ?>
                    <img class="thumbnail" src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php echo $thumbnailSrc;?>&w=250&h=220&zc=1q=100" alt="">
                    <span class="hover"></span>
                    <h2><?php the_title();?></h2>
                    <h3>توضیحات بیشتر<?php echo $catID; ?></h3>
                </a>
            </li>
            <?php endwhile;?>
        </ul>
    <?php endif;?>


问:
Button not centering after moving it to bottom of div
I'm trying to create a form where the submit is always at the bottom and in the center.

I'm centering by using text-align: center in the parent div and moving it to the bottom with position: absolute and bottom: 20px, but it seems that after I do that it moves slightly off center - why is this case and how do I remedy this?

HTML:

```<code><div class='container'>
  <form>
    <p>
      <input name='group 1' type='radio' id='1' />
      <label for='1'>option 1</label>
    </p>
    <p>
      <input name='group 1' type='radio' id='2' />
      <label for='2'>option 2</label>
    </p>
    <p>
      <input name='group 2' type='radio' id='3' />
      <label for='3'>option 1</label>
    </p>
    <p>
      <input name='group 1' type='radio' id='4' />
      <label for='4'>option 1</label>
    </p>
    <button type='submit'>
      Submit
    </button>
  </form>
</div>
</code>```

CSS:

```<code>.container {
  width: 400px;
  height: 400px;
  border: 2px solid red;
  text-align: center;
}

button {
  position: absolute;
  bottom: 20px;
}
</code>```

Demo: https://jsfiddle.net/f9ktLn9o/3/

答:
Taking a look at Computed styles you will see left and right position values defined in the box model.

You'll need to unset these values with your own, with a few other adjustments, you will achieve the intended behaviour.

Updated JSFiddle

Code Snippet Demonstration:

.container {
  width: 400px;
  height: 400px;
  border: 2px solid red;
  text-align: center;
  /* Additional */
  position: relative; /* position absolute child relative to parent */
}

button {
  position: absolute;
  bottom: 20px;
  /* Additional */
  left: 0;
  right: 0;
  display: block;
  margin: auto;
  width: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <form>
    <p>
      <input name='group 1' type='radio' id='1' />
      <label for='1'>option 1</label>
    </p>
    <p>
      <input name='group 1' type='radio' id='2' />
      <label for='2'>option 2</label>
    </p>
    <p>
      <input name='group 2' type='radio' id='3' />
      <label for='3'>option 1</label>
    </p>
    <p>
      <input name='group 1' type='radio' id='4' />
      <label for='4'>option 1</label>
    </p><button type='submit'>
      Submit
    </button>
  </form>
</div></code>```

Body:
I'm trying to create a form where the submit is always at the bottom and in the center.

I'm centering by using text-align: center in the parent div and moving it to the bottom with position: absolute and bottom: 20px, but it seems that after I do that it moves slightly off center - why is this case and how do I remedy this?

HTML:

  <form>

      <input name='group 1' type='radio' id='1' />
      option 1

      <input name='group 1' type='radio' id='2' />
      option 2

      <input name='group 2' type='radio' id='3' />
      option 1

      <input name='group 1' type='radio' id='4' />
      option 1

    <button type='submit'>
      Submit
    </button>
  </form>

CSS:

.container {
  width: 400px;
  height: 400px;
  border: 2px solid red;
  text-align: center;
}

button {
  position: absolute;
  bottom: 20px;
}

Demo: https://jsfiddle.net/f9ktLn9o/3/

Body:
Taking a look at Computed styles you will see left and right position values defined in the box model.

You'll need to unset these values with your own, with a few other adjustments, you will achieve the intended behaviour.

Updated JSFiddle

Code Snippet Demonstration:

.container {
  width: 400px;
  height: 400px;
  border: 2px solid red;
  text-align: center;
  /* Additional */
  position: relative; /* position absolute child relative to parent */
}

button {
  position: absolute;
  bottom: 20px;
  /* Additional */
  left: 0;
  right: 0;
  display: block;
  margin: auto;
  width: 100px;
}

<div class='container'>
  <form>
    <p>
      <input name='group 1' type='radio' id='1' />
      <label for='1'>option 1</label>
    </p>
    <p>
      <input name='group 1' type='radio' id='2' />
      <label for='2'>option 2</label>
    </p>
    <p>
      <input name='group 2' type='radio' id='3' />
      <label for='3'>option 1</label>
    </p>
    <p>
      <input name='group 1' type='radio' id='4' />
      <label for='4'>option 1</label>
    </p><button type='submit'>
      Submit
    </button>
  </form>
</div>


问:
can i have 2 different link settings on Branch.io?
We already set up a branch project, with branch links and it works fine, is it possible to have 2 different behaviors on 2 links on branch?

i am talking about the behavior of the desktop click:

for example, i want that one link will open site A, and another will open site B (not under the same domain)
or to have one link redirect to a web page, and another to be redirected to the  Branch-hosted SMS Landing Page

couldn't find the option on branch.io link settings
thanks.

答:
Full disclosure, I work at Branch. You can definitely have each of your Branch links redirect to different sites.

For a Quick link, you need to update the Desktop redirect to the web address you want the link to redirect to.

For the Branch links you create in the Mobile SDK or using the HTTP API, you can add the $desktop_url:"http://www.example.com" parameter to the links.

To learn more about Deep links, you can refer to the documentation here.


问:
Progressbar foreground color
Does anybody know how to change the foreground color of a WPF-Progressbar. It always seems to be merged with green.</p>

答:
just try with this

```<code>   <ProgressBar Height="25" IsIndeterminate="True" Width="150" Foreground="Red" ></ProgressBar>
</code>```

If it is not working as you required you have to modify the Style or ControlTemplate of Progressbar.

To do that you can use Expression Blend from Microsoft or you can get a copy the existing template and modify it.

Title: Progressbar foreground color

Body:
just try with this

   <ProgressBar Height="25" IsIndeterminate="True" Width="150" Foreground="Red" ></ProgressBar>

If it is not working as you required you have to modify the Style or ControlTemplate of Progressbar.

To do that you can use Expression Blend from Microsoft or you can get a copy the existing template and modify it.


问:
Create Record Error
HI any help please I have this code odoo 10 ,I try to create a one2many relation history_line

the first class

```<code> class db_backup_ept(models.Model):
_name = 'db.autobackup.ept'

name = fields.Char('Database', size=100, required='True',help='Database you want to schedule backups for')
host = fields.Char('Host', size=100, required='True', default='localhost')
port = fields.Char('Port', size=10, required='True', default='8069')
history_line = fields.One2many('db.backup.line', 'backup_id', 'History', readonly=True)
active = fields.Boolean('Active', default=True)
def ept_backup(self,cr,uid,ids,db_name,bkup_dir,automatic,ftp_enable,FTP_id,bak_conf,keep_backup_local):
for obj in self:
                backup_status = 'Backup completed successfully at path : %s ' %(tar_file_path)
                self.env['db.backup.line'].create(cr,uid,{
                 'backup_id' : obj.id,
                 'name' : obj.name,
                 'date_time' : time.strftime('%Y-%m-%d %H:%M:%S'),
                 'message' : backup_status,
                 'automatic' : automatic,
                 'done_by' : user_id,
                 'path' : tar_file_path,
                 'file_size' : str(os.path.getsize(tar_file_path)),
                })
</code>```

the second class

```<code>class db_backup_line(models.Model):
_name = 'db.backup.line'
backup_id = fields.Many2one('db.autobackup.ept','Backup')
name = fields.Char('DB Name', size=100)
date_time = fields.Datetime('Date', size=100)
path = fields.Text('Backup Path')
file_size = fields.Char('File Size',size=100)
automatic = fields.Boolean('Automatic Backup?')
done_by = fields.Many2one('res.users','Done By')
message = fields.Text('Message')

  db_backup_line()
</code>```

self.env['db.backup.line'].create d'ont work (odoo 10)

答:
Ofcourse it will not work because you are using new+old api in the same time which is not correct also Odoo 10 only supports new api so there is no cr or uid or ids anymore. You should use api multi instead,so your code should be like this:</p>

```<code>def ept_backup(self ,db_name,bkup_dir,automatic,ftp_enable,FTP_id,bak_conf,keep_backup_local):
        for obj in self:
                    backup_status = 'Backup completed successfully at path : %s ' %(tar_file_path)
                    self.env['db.backup.line'].create({
                     'backup_id' : obj.id,
                     'name' : obj.name,
                     'date_time' : time.strftime('%Y-%m-%d %H:%M:%S'),
                     'message' : backup_status,
                     'automatic' : automatic,
                     'done_by' : user_id,
                     'path' : tar_file_path,
                     'file_size' : str(os.path.getsize(tar_file_path)),
                    })
</code>```

Title: Create Record Error

Body:
HI any help please I have this code odoo 10 ,I try to create a one2many relation history_line

the first class

 class db_backup_ept(models.Model):
_name = 'db.autobackup.ept'

name = fields.Char('Database', size=100, required='True',help='Database you want to schedule backups for')
host = fields.Char('Host', size=100, required='True', default='localhost')
port = fields.Char('Port', size=10, required='True', default='8069')
history_line = fields.One2many('db.backup.line', 'backup_id', 'History', readonly=True)
active = fields.Boolean('Active', default=True)
def ept_backup(self,cr,uid,ids,db_name,bkup_dir,automatic,ftp_enable,FTP_id,bak_conf,keep_backup_local):
for obj in self:
                backup_status = 'Backup completed successfully at path : %s ' %(tar_file_path)
                self.env['db.backup.line'].create(cr,uid,{
                 'backup_id' : obj.id,
                 'name' : obj.name,
                 'date_time' : time.strftime('%Y-%m-%d %H:%M:%S'),
                 'message' : backup_status,
                 'automatic' : automatic,
                 'done_by' : user_id,
                 'path' : tar_file_path,
                 'file_size' : str(os.path.getsize(tar_file_path)),
                })

the second class

class db_backup_line(models.Model):
_name = 'db.backup.line'
backup_id = fields.Many2one('db.autobackup.ept','Backup')
name = fields.Char('DB Name', size=100)
date_time = fields.Datetime('Date', size=100)
path = fields.Text('Backup Path')
file_size = fields.Char('File Size',size=100)
automatic = fields.Boolean('Automatic Backup?')
done_by = fields.Many2one('res.users','Done By')
message = fields.Text('Message')

  db_backup_line()

self.env['db.backup.line'].create d'ont work (odoo 10)

Body:
Ofcourse it will not work because you are using new+old api in the same time which is not correct also Odoo 10 only supports new api so there is no cr or uid or ids anymore. You should use api multi instead,so your code should be like this:

def ept_backup(self ,db_name,bkup_dir,automatic,ftp_enable,FTP_id,bak_conf,keep_backup_local):
        for obj in self:
                    backup_status = 'Backup completed successfully at path : %s ' %(tar_file_path)
                    self.env['db.backup.line'].create({
                     'backup_id' : obj.id,
                     'name' : obj.name,
                     'date_time' : time.strftime('%Y-%m-%d %H:%M:%S'),
                     'message' : backup_status,
                     'automatic' : automatic,
                     'done_by' : user_id,
                     'path' : tar_file_path,
                     'file_size' : str(os.path.getsize(tar_file_path)),
                    })


问:
The most efficient way to compare object's property in two arrays
I need to check in Angular2 if one object's property in one array is the same in another array and return value. Is there any more efficient way to do it or maybe something similar to .contains in Swift?

```<code>doSomething(){
    for (let element1 of array1) {
        for (let element2 of array2) {
            if (element1.id == element2.id) {
                return Observable.fromPromise(element2);
            }
        }
    }
}
</code>```

EDIT:

I have to subscribe to this value because I am loading value from the database (in fromPromise):

```<code>this.doSomething().subscribe(id => {
...
}
</code>```

答:
The intersection of array1 and array2:
array1.filter((item) => array2.includes(item));

Body:
I need to check in Angular2 if one object's property in one array is the same in another array and return value. Is there any more efficient way to do it or maybe something similar to .contains in Swift?

doSomething(){
    for (let element1 of array1) {
        for (let element2 of array2) {
            if (element1.id == element2.id) {
                return Observable.fromPromise(element2);
            }
        }
    }
}

EDIT:

I have to subscribe to this value because I am loading value from the database (in fromPromise):

this.doSomething().subscribe(id => {
...
}


问:
How to read AS2 (EDI - RFC 4130) payload with PHP?
I'm trying to implement an AS2 client in PHP. I'm running PHP7 behind a NGinx http server.

If i'm able to get access to headers (AS2-Version, etc.), I can't access the HTTP payload with file_get_contents('pĥp://input'). This instruction returns a zero-length string.

Any idea, please? See sources below.

Example, call to http://localhost/send.php?file=AS2PlainText.txt returns :

```<code>Send AS2PlainText.txt
-----------------------
HTTP/1.1 200 OK
Server: nginx/1.10.3 (Ubuntu)
Date: Fri, 17 Nov 2017 15:54:23 GMT
Content-Type: text/plain;charset=UTF-8
Transfer-Encoding: chunked
Connection: close

14b
---HEADER---
HTTP_CONTENT_TYPE => Application/EDI-X12
HTTP_AS2_FROM => FromCompanyXYZ
HTTP_AS2_TO => ToCompanyABC
HTTP_AS2_VERSION => 1.0
HTTP_MESSAGE_ID => 1234567890@evalusercompany.com
HTTP_USER_AGENT => AS2 Company Server
HTTP_CONNECTION => close
HTTP_HOST => localhost
---BODY---
string(0) ""
---END---

0
</code>```

I wonder if this would not be NGinx related as removing Connection: close from send.php returns the same output as above (excepted HTTP_CONNECTION, of course), plus a second HTTP/1.1 request:

```<code>[...]
HTTP_USER_AGENT => AS2 Company Server
HTTP_HOST => localhost
---BODY---
string(0) ""
---END---

0

HTTP/1.1 400 Bad Request
Server: nginx/1.10.3 (Ubuntu)
Date: Fri, 17 Nov 2017 16:07:06 GMT
Content-Type: text/html
Content-Length: 182
Connection: close

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.10.3 (Ubuntu)</center>
</body>
</html>
</code>```

SOURCES

send.php

```<code><?php
header('Content-type: text/plain');
echo "Send {$_GET['file']}\r\n";
echo "-----------------------\r\n";

$fp = fsockopen('127.0.0.1', 80);
fwrite($fp, "POST /echo.php HTTP/1.1\r\n");
fwrite($fp, "Host: localhost\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, file_get_contents($_GET['file']) . "\r\n");
fwrite($fp, "\r\n");

while (!feof($fp)) {
    echo fgets($fp, 1024);
}
</code>```

echo.php

```<code><?php
header('Content-type: text/plain');
echo "---HEADER---\r\n";
foreach (array_filter(
        $_SERVER,
        function($k) {
            return (substr($k,0,5) == 'HTTP_');
        },
        ARRAY_FILTER_USE_KEY
        ) as $key => $value) {
        echo "$key => $value\n";
    }

echo "---BODY---\r\n";
var_dump(file_get_contents('php://input'));
echo "---END---\r\n";
</code>```

AS2PlainText.txt

```<code>User-Agent: AS2 Company Server
Message-ID: 1234567890@evalusercompany.com
AS2-Version: 1.0
AS2-To: ToCompanyABC
AS2-From: FromCompanyXYZ
Content-Type: Application/EDI-X12

ISA*00*          *00*          *ZZ*SENDERISA      *14*0073268795005
*960807*1548*U*00401*000000020*0*T*>~
GS*PO*SENDERGS*007326879*19960807*1548*1*X*004010~
ST*850*000000001~
BEG*00*SA*A99999-01**19971207~
REF*VR*54321~
ITD*01*3*1**15**16~
DTM*002*19971219~
N1*BT*BUYSNACKS INC.*9*1223334444~
N3*P.O. BOX 0000~
N4*TEMPLE*TX*76503~
N1*ST*BUYSNACKS PORT*9*1223334445~
N3*1000 N. SAMPLE HIGHWAY~
N4*ATHENS*GA*30603~
N1*VN*FOODSELLER*9*12345QQQQ~
N3*P.O. BOX 222222~
N4*DALLAS*TX*723224444~
PO1**16*CA*12.34**CB*000111111*UA*002840022222~
PID*F****CRUNCHY CHIPS LSS~
PO4*48*7.89*LB~
PO1**13*CA*12.34**CB*000555555*UA*002840033333~
PID*F****NACHO CHIPS LSS~
PO4*48*8.9*LB~
CTT*7~
SE*22*000000001~
GE*1*1~
IEA*1*000000020~
</code>```

答: Found the issue: missing Content-Length in HTTP request headers...

Body:
I'm trying to implement an AS2 client in PHP. I'm running PHP7 behind a NGinx http server.

If i'm able to get access to headers (AS2-Version, etc.), I can't access the HTTP payload with file_get_contents('pĥp://input'). This instruction returns a zero-length string.

Any idea, please? See sources below.

Example, call to http://localhost/send.php?file=AS2PlainText.txt returns :

Send AS2PlainText.txt
-----------------------
HTTP/1.1 200 OK
Server: nginx/1.10.3 (Ubuntu)
Date: Fri, 17 Nov 2017 15:54:23 GMT
Content-Type: text/plain;charset=UTF-8
Transfer-Encoding: chunked
Connection: close

14b
---HEADER---
HTTP_CONTENT_TYPE => Application/EDI-X12
HTTP_AS2_FROM => FromCompanyXYZ
HTTP_AS2_TO => ToCompanyABC
HTTP_AS2_VERSION => 1.0
HTTP_MESSAGE_ID => 1234567890@evalusercompany.com
HTTP_USER_AGENT => AS2 Company Server
HTTP_CONNECTION => close
HTTP_HOST => localhost
---BODY---
string(0) ""
---END---

0

I wonder if this would not be NGinx related as removing Connection: close from send.php returns the same output as above (excepted HTTP_CONNECTION, of course), plus a second HTTP/1.1 request:

[...]
HTTP_USER_AGENT => AS2 Company Server
HTTP_HOST => localhost
---BODY---
string(0) ""
---END---

0

HTTP/1.1 400 Bad Request
Server: nginx/1.10.3 (Ubuntu)
Date: Fri, 17 Nov 2017 16:07:06 GMT
Content-Type: text/html
Content-Length: 182
Connection: close

<title>400 Bad Request</title>

400 Bad Request

nginx/1.10.3 (Ubuntu)

SOURCES

send.php

<?php
header('Content-type: text/plain');
echo "Send {$_GET['file']}\r\n";
echo "-----------------------\r\n";

$fp = fsockopen('127.0.0.1', 80);
fwrite($fp, "POST /echo.php HTTP/1.1\r\n");
fwrite($fp, "Host: localhost\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, file_get_contents($_GET['file']) . "\r\n");
fwrite($fp, "\r\n");

while (!feof($fp)) {
    echo fgets($fp, 1024);
}

echo.php

<?php
header('Content-type: text/plain');
echo "---HEADER---\r\n";
foreach (array_filter(
        $_SERVER,
        function($k) {
            return (substr($k,0,5) == 'HTTP_');
        },
        ARRAY_FILTER_USE_KEY
        ) as $key => $value) {
        echo "$key => $value\n";
    }

echo "---BODY---\r\n";
var_dump(file_get_contents('php://input'));
echo "---END---\r\n";

AS2PlainText.txt

User-Agent: AS2 Company Server
Message-ID: 1234567890@evalusercompany.com
AS2-Version: 1.0
AS2-To: ToCompanyABC
AS2-From: FromCompanyXYZ
Content-Type: Application/EDI-X12

ISA*00*          *00*          *ZZ*SENDERISA      *14*0073268795005
*960807*1548*U*00401*000000020*0*T*>~
GS*PO*SENDERGS*007326879*19960807*1548*1*X*004010~
ST*850*000000001~
BEG*00*SA*A99999-01**19971207~
REF*VR*54321~
ITD*01*3*1**15**16~
DTM*002*19971219~
N1*BT*BUYSNACKS INC.*9*1223334444~
N3*P.O. BOX 0000~
N4*TEMPLE*TX*76503~
N1*ST*BUYSNACKS PORT*9*1223334445~
N3*1000 N. SAMPLE HIGHWAY~
N4*ATHENS*GA*30603~
N1*VN*FOODSELLER*9*12345QQQQ~
N3*P.O. BOX 222222~
N4*DALLAS*TX*723224444~
PO1**16*CA*12.34**CB*000111111*UA*002840022222~
PID*F****CRUNCHY CHIPS LSS~
PO4*48*7.89*LB~
PO1**13*CA*12.34**CB*000555555*UA*002840033333~
PID*F****NACHO CHIPS LSS~
PO4*48*8.9*LB~
CTT*7~
SE*22*000000001~
GE*1*1~
IEA*1*000000020~


问:
Python - Retrieve and use a cookie to download a file
Trying to download the following file:

https://e4ftl01.cr.usgs.gov/MOLA/MYD14A2.006/2017.10.24/MYD14A2.A2017297.h19v01.006.2017310142443.hdf

I first need to sign into the following site before doing so:

https://urs.earthdata.nasa.gov

After reviewing my browser's web console, I believe it's using a cookie to allow me to download the file.  How can I do this using python?  I find out how to retrieve the cookies:

```<code>import os, requests

username = 'user'
password = 'pwd'

url = 'https://urs.earthdata.nasa.gov'
r = requests.get(url, auth=(username,password))
cookies = r.cookies
</code>```

How can I then use this to download the HDF file?  I've tried the following but always receive 401 error.

```<code>url2 = "https://e4ftl01.cr.usgs.gov/MOLA/MYD14A2.006/2017.10.24/MYD14A2.A2017297.h19v01.006.2017310142443.hdf"
r2 = requests.get(url2, cookies=r.cookies)
</code>```

答:
Have you tried a simple basic authentification :

```<code>from requests.auth import HTTPBasicAuth

url2='https://e4ftl01.cr.usgs.gov/MOLA/MYD14A2.006/2017.10.24/MYD14A2.A2017297.h19v01.006.2017310142443.hdf'
requests.get(url2, auth=HTTPBasicAuth('user', 'pass'))
</code>```

or read this example

Body:
Trying to download the following file:

https://e4ftl01.cr.usgs.gov/MOLA/MYD14A2.006/2017.10.24/MYD14A2.A2017297.h19v01.006.2017310142443.hdf

I first need to sign into the following site before doing so:

https://urs.earthdata.nasa.gov

After reviewing my browser's web console, I believe it's using a cookie to allow me to download the file.  How can I do this using python?  I find out how to retrieve the cookies:

import os, requests

username = 'user'
password = 'pwd'

url = 'https://urs.earthdata.nasa.gov'
r = requests.get(url, auth=(username,password))
cookies = r.cookies

How can I then use this to download the HDF file?  I've tried the following but always receive 401 error.

url2 = "https://e4ftl01.cr.usgs.gov/MOLA/MYD14A2.006/2017.10.24/MYD14A2.A2017297.h19v01.006.2017310142443.hdf"
r2 = requests.get(url2, cookies=r.cookies)

Body:
Have you tried a simple basic authentification :

from requests.auth import HTTPBasicAuth

url2='https://e4ftl01.cr.usgs.gov/MOLA/MYD14A2.006/2017.10.24/MYD14A2.A2017297.h19v01.006.2017310142443.hdf'
requests.get(url2, auth=HTTPBasicAuth('user', 'pass'))

or read this example


问:
MS SQL Server not using index when WHERE has IN with more than 6 values
So i have a very strange issue, If i run a query like this:

```<code>SELECT *
FROM tbl_x
WHERE tbl_x.SomeCode IN ('1','2','3','4','5','6')
</code>```

The query uses the index on the table, however if i do query this:

```<code>SELECT *
FROM tbl_x
WHERE tbl_x.SomeCode IN ('1','2','3','4','5','6','7')
</code>```

The query ignores the index and decides to do a Table Scan

Why is MS SQL Server not using the index when there are more than 6 values in the Where clause?

答:
I guess that based on data distribution and cardinality query optimizer decides to use full table scan, because it is cheaper than to use index.

You could check:

```<code>SELECT COUNT(*)
FROM tbl_x;
</code>```

and

```<code>SELECT COUNT(*)
FROM tbl_x
WHERE tbl_x.SomeCode IN ('1','2','3','4','5','6','7');
</code>```

Probably you exceeded 20% rows of entire table.

Body:
So i have a very strange issue, If i run a query like this:

SELECT *
FROM tbl_x
WHERE tbl_x.SomeCode IN ('1','2','3','4','5','6')

The query uses the index on the table, however if i do query this:

SELECT *
FROM tbl_x
WHERE tbl_x.SomeCode IN ('1','2','3','4','5','6','7')

The query ignores the index and decides to do a Table Scan

Why is MS SQL Server not using the index when there are more than 6 values in the Where clause?

Body:
I guess that based on data distribution and cardinality query optimizer decides to use full table scan, because it is cheaper than to use index.

You could check:

SELECT COUNT(*)
FROM tbl_x;

and

SELECT COUNT(*)
FROM tbl_x
WHERE tbl_x.SomeCode IN ('1','2','3','4','5','6','7');

Probably you exceeded 20% rows of entire table.


问:
How to reset mysql modes to default after doing SET sql_mode = ''
I accidentally did SET sql_mode = '' while trying to disable ONLY_FULL_GROUP_BY which resets all modes currently enabled. How can I revert to the default settings? I'm running MySQL 5.7.20 on a Homestead Vagrant box.

Thanks

答:
The query

```<code> SET sql_mode = '';
</code>```

only works on the current connection.

So you can disconnect and reconnect your client and your default sql_mode should be restored.

To disable 'ONLY_FULL_GROUP_BY' without disabling other sql_mode can be done like this.

```<code>  SET SESSION sql_mode = CONCAT(REPLACE(@@sql_mode, ',ONLY_FULL_GROUP_BY', ''));
</code>```

p.s
Keep in mind that ONLY_FULL_GROUP_BY is enabled with a reason in the modern MySQL versions, i don't advice to disable it.

Body:
The query

 SET sql_mode = '';

only works on the current connection.

So you can disconnect and reconnect your client and your default sql_mode should be restored.

To disable 'ONLY_FULL_GROUP_BY' without disabling other sql_mode can be done like this.

  SET SESSION sql_mode = CONCAT(REPLACE(@@sql_mode, ',ONLY_FULL_GROUP_BY', ''));

p.s
Keep in mind that ONLY_FULL_GROUP_BY is enabled with a reason in the modern MySQL versions, i don't advice to disable it.

ContentLicense: CC BY-SA 4.0


答:
Here is an example</p>

```<code>array1 = [1,2,4,5,6]
array2 = [3,4,2,6]
array1.filter(a1=> array2.includes(a1)) //To print matching results
array1.filter(a1=> array2.includes(a1)).length == array1.length ? true:false //to validate similarity
</code>```

Title: The most efficient way to compare object's property in two arrays

Body:
Here is an example

array1 = [1,2,4,5,6]
array2 = [3,4,2,6]
array1.filter(a1=> array2.includes(a1)) //To print matching results
array1.filter(a1=> array2.includes(a1)).length == array1.length ? true:false //to validate similarity


问:
Pointer in for loop in c program
I have the following structure:

```<code>struct Matrix
{
    int     numOfRows;
    int     numOfColumns;
    double* values;
    int*    permutationVector;
}
</code>```

Also I have the following function:

```<code>void SetRowToZero(Matrix* m, int row)
{
    int rowBegin = row*(m->numOfColumns);
    for (int c = 0; c < (m->numOfColumns); c++)
    {
        m->values[rowBegin + c] = 0;
    }
}
</code>```

I wonder is there any performance slowdown during operation c < (m->numOfColumns)?
Is there any difference if i write function like this:

```<code>void SetRowToZero(Matrix* m, int row)
{
    // Unpacking structure
    int numOfColumns = m->numOfColumns;
    double* values = m->values;

    int rowBegin = row*(m->numOfColumns);

    for (int c = 0; c < numOfColumns; c++)
    {
        values[rowBegin + c] = 0;
    }
}
</code>```

And in general, should i even care about performace on such a small scale?

答:
Compiler optimizations will result in both pieces of code being optimized to use a register for that value.
I tested this little program on x86_64 and compiled with gcc 5.4 with level 4 optimizations

```<code>#include <stdlib.h>

struct Matrix
{
    int     numOfRows;
    int     numOfColumns;
    double* values;
    int*    permutationVector;
};

void SetRowToZero1(struct Matrix* m, int row)
{
    int rowBegin = row*(m->numOfColumns);
    for (int c = 0; c < (m->numOfColumns); c++)
    {
        m->values[rowBegin + c] = 0;
    }
}

void SetRowToZero2(struct Matrix* m, int row)
{
    // Unpacking structure
    int numOfColumns = m->numOfColumns;
    double* values = m->values;

    int rowBegin = row*(m->numOfColumns);

    for (int c = 0; c < numOfColumns; c++)
    {
        values[rowBegin + c] = 0;
    }
}

int main() {
    struct Matrix matrix = {5,1000000, malloc(5 * 1000000 * sizeof(double)), NULL};
    SetRowToZero1(&matrix, 1);
}
</code>```

I compiled it:

```<code>gcc -O4 main.c -o test1.out
</code>```

and then i changed

```<code>SetRowToZero1(&matrix, 1);
</code>```

to

```<code>SetRowToZero2(&matrix, 1);
</code>```

compiled:

```<code>gcc -O4 main.c -o test2.out
</code>```

then:
$md5sum test1.out test2.out

504fb75e97173a6864750f5feb7cea58  test12.out

504fb75e97173a6864750f5feb7cea58  test1.out

So you can say with certainty the implementations make no difference :)

Title: Pointer in for loop in c program

Body:
I have the following structure:

struct Matrix
{
    int     numOfRows;
    int     numOfColumns;
    double* values;
    int*    permutationVector;
}

Also I have the following function:

void SetRowToZero(Matrix* m, int row)
{
    int rowBegin = row*(m->numOfColumns);
    for (int c = 0; c < (m->numOfColumns); c++)
    {
        m->values[rowBegin + c] = 0;
    }
}

I wonder is there any performance slowdown during operation c < (m->numOfColumns)?
Is there any difference if i write function like this:

void SetRowToZero(Matrix* m, int row)
{
    // Unpacking structure
    int numOfColumns = m->numOfColumns;
    double* values = m->values;

    int rowBegin = row*(m->numOfColumns);

    for (int c = 0; c < numOfColumns; c++)
    {
        values[rowBegin + c] = 0;
    }
}

And in general, should i even care about performace on such a small scale?

Body:
Compiler optimizations will result in both pieces of code being optimized to use a register for that value.
I tested this little program on x86_64 and compiled with gcc 5.4 with level 4 optimizations

#include <stdlib.h>

struct Matrix
{
    int     numOfRows;
    int     numOfColumns;
    double* values;
    int*    permutationVector;
};

void SetRowToZero1(struct Matrix* m, int row)
{
    int rowBegin = row*(m->numOfColumns);
    for (int c = 0; c < (m->numOfColumns); c++)
    {
        m->values[rowBegin + c] = 0;
    }
}

void SetRowToZero2(struct Matrix* m, int row)
{
    // Unpacking structure
    int numOfColumns = m->numOfColumns;
    double* values = m->values;

    int rowBegin = row*(m->numOfColumns);

    for (int c = 0; c < numOfColumns; c++)
    {
        values[rowBegin + c] = 0;
    }
}

int main() {
    struct Matrix matrix = {5,1000000, malloc(5 * 1000000 * sizeof(double)), NULL};
    SetRowToZero1(&matrix, 1);
}

I compiled it:

gcc -O4 main.c -o test1.out

and then i changed

SetRowToZero1(&matrix, 1);

to

SetRowToZero2(&matrix, 1);

compiled:

gcc -O4 main.c -o test2.out

then:
$md5sum test1.out test2.out

504fb75e97173a6864750f5feb7cea58  test12.out

504fb75e97173a6864750f5feb7cea58  test1.out

So you can say with certainty the implementations make no difference :)


问:
Android - Keeping users logged in not working (Firebase)
In my application I am trying to keep the user logged in, after they log in the first time. This is not working.

In my application I have multiple usertypes: "School" and "Students". In my activity I have the AuthStateListener method, but nothing happens in my activity. The application just sticks to the starting activity without running the code in the AuthStateListener method.

```<code> mAuthListener = new FirebaseAuth.AuthStateListener() {
       @Override
       public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
           FirebaseUser user = firebaseAuth.getCurrentUser();
           if (user != null) {
               // User is signed in
               rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                   public void onDataChange(DataSnapshot dataSnapshot) {
                       if (dataSnapshot.child("usertype").getValue(String.class).equals("Students") && dataSnapshot.child("verified").getValue(boolean.class).equals(true)) {
                            Intent intent = new Intent(WaitingActivity.this, StudentsActivity.class);
                            startActivity(intent);
                            finish();
                        }

                        if (dataSnapshot.child("usertype").getValue(String.class).equals("School") && dataSnapshot.child("verified").getValue(boolean.class).equals(true)) {
                            Intent intent = new Intent(WaitingActivity.this, SchoolsActivity.class);
                            startActivity(intent);
                            finish();
                        }

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            } else {
                // User is signed out
                Intent intent = new Intent(WaitingActivity.this, LoginActivity.class);
                startActivity(intent);
            }
            // ...
        }
    };
</code>```

Am I doing something wrong? Or have I missed something?

答:
If you want to check login state every time that an Activity starts or resumes, you have two options.

You can use code like this in the Activity's onCreate() or onResume() method:

```<code>FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
    // User is signed in, do whatever you need to do
} else {
    // User is not signed in, do whatever you need to do
}
</code>```

Alternatively, you can use the AuthStateListener as you indicated, but make sure that you add the listener:

```<code>FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
</code>```

Just make sure that you remove the AuthStateListener at an appropriate time using the removeAuthStateListener() method.

Body:
In my application I am trying to keep the user logged in, after they log in the first time. This is not working.

In my application I have multiple usertypes: "School" and "Students". In my activity I have the AuthStateListener method, but nothing happens in my activity. The application just sticks to the starting activity without running the code in the AuthStateListener method.

 mAuthListener = new FirebaseAuth.AuthStateListener() {
       @Override
       public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
           FirebaseUser user = firebaseAuth.getCurrentUser();
           if (user != null) {
               // User is signed in
               rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                   public void onDataChange(DataSnapshot dataSnapshot) {
                       if (dataSnapshot.child("usertype").getValue(String.class).equals("Students") && dataSnapshot.child("verified").getValue(boolean.class).equals(true)) {
                            Intent intent = new Intent(WaitingActivity.this, StudentsActivity.class);
                            startActivity(intent);
                            finish();
                        }

                        if (dataSnapshot.child("usertype").getValue(String.class).equals("School") && dataSnapshot.child("verified").getValue(boolean.class).equals(true)) {
                            Intent intent = new Intent(WaitingActivity.this, SchoolsActivity.class);
                            startActivity(intent);
                            finish();
                        }

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            } else {
                // User is signed out
                Intent intent = new Intent(WaitingActivity.this, LoginActivity.class);
                startActivity(intent);
            }
            // ...
        }
    };

Am I doing something wrong? Or have I missed something?

Body:
If you want to check login state every time that an Activity starts or resumes, you have two options.

You can use code like this in the Activity's onCreate() or onResume() method:

FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
    // User is signed in, do whatever you need to do
} else {
    // User is not signed in, do whatever you need to do
}

Alternatively, you can use the AuthStateListener as you indicated, but make sure that you add the listener:

FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);

Just make sure that you remove the AuthStateListener at an appropriate time using the removeAuthStateListener() method.


问:
Deadlock when unit testing with Algolia Android client
I am trying to use searchAsync from algolia in a JUnit test, but it ends in a deadlock as the search results are not coming back. Here is my code:

```<code>    final Index index = AlgoClient.initIndex("contacts");

    Query query = new Query();

    query.setHitsPerPage(100);

    CountDownLatch signal = new CountDownLatch(1);

    index.searchAsync(query, new CompletionHandler() {

        @Override
        public void requestCompleted(JSONObject content, AlgoliaException e) {

           signal.countDown();
        });

    signal.await();
</code>```

答:
You need to use await with a timeout, and fail if it does timeout. Also, you should test for an error in your CompletionHandler:

```<code>final Index index = client.getIndex("contacts");
    Query query = new Query().setHitsPerPage(100);
    final CountDownLatch signal = new CountDownLatch(1);

    index.searchAsync(query, new CompletionHandler() {
        @Override
        public void requestCompleted(JSONObject content, AlgoliaException e) {
            if (e == null) {
                signal.countDown(); // Request success
            } else {
                fail(e.getMessage()); // Request error
            }
        }
    });

    try {
        if (!signal.await(10, TimeUnit.SECONDS)) { // returns false when timeout
            fail("Didn't count down");
        }
    } catch (InterruptedException e) {
        fail("interrupted");
    }
</code>```

Body:
I am trying to use searchAsync from algolia in a JUnit test, but it ends in a deadlock as the search results are not coming back. Here is my code:

    final Index index = AlgoClient.initIndex("contacts");

    Query query = new Query();

    query.setHitsPerPage(100);

    CountDownLatch signal = new CountDownLatch(1);

    index.searchAsync(query, new CompletionHandler() {

        @Override
        public void requestCompleted(JSONObject content, AlgoliaException e) {

           signal.countDown();
        });

    signal.await();

Body:
You need to use await with a timeout, and fail if it does timeout. Also, you should test for an error in your CompletionHandler:

final Index index = client.getIndex("contacts");
    Query query = new Query().setHitsPerPage(100);
    final CountDownLatch signal = new CountDownLatch(1);

    index.searchAsync(query, new CompletionHandler() {
        @Override
        public void requestCompleted(JSONObject content, AlgoliaException e) {
            if (e == null) {
                signal.countDown(); // Request success
            } else {
                fail(e.getMessage()); // Request error
            }
        }
    });

    try {
        if (!signal.await(10, TimeUnit.SECONDS)) { // returns false when timeout
            fail("Didn't count down");
        }
    } catch (InterruptedException e) {
        fail("interrupted");
    }


问:
adding tabs in java (swing)
i was given a project to make a java program named doctors care which has login panel( username and password) and a panel which has 3 tabs. the problem is i could add only one tab and when i tried to add another tab by duplicating the objects( like label2, panel2 etc) it does not appear in the executed JAR file. i have posted the code below.

public void actionPerformed(ActionEvent ae)

```<code>   {String value1 = text1.getText();
    String value2 = text2.getText();
    if(value1.equals("admin") && value2.equals("admin123456")) {
        NextPage page=new NextPage();
        page.setVisible(true);

        JTabbedPane tabbedPane1 = new JTabbedPane();
        ImageIcon icon1 = createImageIcon("images/middle.gif");
        JComponent panel1 = makeTextPanel("panel#1");
        tabbedPane1.addTab("Booking", icon1, panel1, "For booking appointments");
        JLabel label = new JLabel("Welcome "+value1);
        page.getContentPane().add(label);
        page.getContentPane().add(tabbedPane1);
        //page.add(icon);
        page.getContentPane().add(panel1);

  JTabbedPane tabbedPane2 = new JTabbedPane();
    ImageIcon icon2 = createImageIcon("images/middle.gif");
    JComponent panel2 = makeTextPanel("panel#2");
    tabbedPane2.addTab("Doctors", icon2, panel2, "For choosing appointments");
    JLabel label2 = new JLabel("Welcome "+value2);
    page.getContentPane().add(label2);
    page.getContentPane().add(tabbedPane2);
    //page.add(icon2);
    page.getContentPane().add(panel2);}
</code>```

答:
Here's a sample from my program I wrote awhile ago that uses tabbedPanes, if I had a larger picture I could help a bit more. Instead just use this as a possible resources to see if order might matter for adding in the pane then the tabs.

Note that contentPane is the generated JPanel in WindowsBuilder.

```<code>tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
    tabbedPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
    tabbedPane.setBackground(Color.DARK_GRAY);
    tabbedPane.setForeground(Color.white);
    tabbedPane.setBounds(10, 11, 1900, 1058 - taskBarSize);
    tabbedPane.setFont(new Font("Arial Black", Font.BOLD, 14));
    contentPane.add(tabbedPane);

    te = new TournamentEnlisting();
    tabbedPane.add("<html><body><table width='250'>Tournament Enlisting</table></body></html>", te);

    su = new StreamUpdater();
    tabbedPane.addTab("<html><body><table width='250'>Stream Updating</table></body></html>", su);

    sc = new StreamCapture();
    tabbedPane.addTab("<html><body><table width='250'>Stream Capture</table></body></html>", sc);

    thumb = new ThumbnailEditor();
    tabbedPane.addTab("<html><body><table width='250'>Thumbnail Editor</table></body></html>", thumb);
</code>```

Title: adding tabs in java (swing)

Body:
i was given a project to make a java program named doctors care which has login panel( username and password) and a panel which has 3 tabs. the problem is i could add only one tab and when i tried to add another tab by duplicating the objects( like label2, panel2 etc) it does not appear in the executed JAR file. i have posted the code below.

public void actionPerformed(ActionEvent ae)

   {String value1 = text1.getText();
    String value2 = text2.getText();
    if(value1.equals("admin") && value2.equals("admin123456")) {
        NextPage page=new NextPage();
        page.setVisible(true);

        JTabbedPane tabbedPane1 = new JTabbedPane();
        ImageIcon icon1 = createImageIcon("images/middle.gif");
        JComponent panel1 = makeTextPanel("panel#1");
        tabbedPane1.addTab("Booking", icon1, panel1, "For booking appointments");
        JLabel label = new JLabel("Welcome "+value1);
        page.getContentPane().add(label);
        page.getContentPane().add(tabbedPane1);
        //page.add(icon);
        page.getContentPane().add(panel1);

  JTabbedPane tabbedPane2 = new JTabbedPane();
    ImageIcon icon2 = createImageIcon("images/middle.gif");
    JComponent panel2 = makeTextPanel("panel#2");
    tabbedPane2.addTab("Doctors", icon2, panel2, "For choosing appointments");
    JLabel label2 = new JLabel("Welcome "+value2);
    page.getContentPane().add(label2);
    page.getContentPane().add(tabbedPane2);
    //page.add(icon2);
    page.getContentPane().add(panel2);}

Body:
Here's a sample from my program I wrote awhile ago that uses tabbedPanes, if I had a larger picture I could help a bit more. Instead just use this as a possible resources to see if order might matter for adding in the pane then the tabs.

Note that contentPane is the generated JPanel in WindowsBuilder.

tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
    tabbedPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
    tabbedPane.setBackground(Color.DARK_GRAY);
    tabbedPane.setForeground(Color.white);
    tabbedPane.setBounds(10, 11, 1900, 1058 - taskBarSize);
    tabbedPane.setFont(new Font("Arial Black", Font.BOLD, 14));
    contentPane.add(tabbedPane);

    te = new TournamentEnlisting();
    tabbedPane.add("<html><body><table width='250'>Tournament Enlisting</table></body></html>", te);

    su = new StreamUpdater();
    tabbedPane.addTab("<html><body><table width='250'>Stream Updating</table></body></html>", su);

    sc = new StreamCapture();
    tabbedPane.addTab("<html><body><table width='250'>Stream Capture</table></body></html>", sc);

    thumb = new ThumbnailEditor();
    tabbedPane.addTab("<html><body><table width='250'>Thumbnail Editor</table></body></html>", thumb);


问:
jasmine - javascript testing closures
I have the following methods.. I'd like to be able to mock something up so I can test whether or not pete() has been called. Not sure how to do this when im using closures. Any ideas ?</p>

```<code>bla = (function(){
     var a = 0;
     jim = function(){
         if(a==1){
             pete();
         }
     },
     pete = function(){
         return 1;
     }

     var publicInterface = {
         "publicjim": jim
     }
     return publicInterface;
})();
</code>```

答:
In your self-executing anonymous function, you're using object propertys.

jim and pete need to be local variables in order to "hide" them via closure.

```<code>var bla = (function(){
    var a = 1;
    var jim = function() {
      if (a == 1) {
         pete();
      }
    };
    var pete = function() {
        return 1;
    };

    return {
       "publicjim": jim
    };
})();
</code>```

Title: jasmine - javascript testing closures

Body:
I have the following methods.. I'd like to be able to mock something up so I can test whether or not pete() has been called. Not sure how to do this when im using closures. Any ideas ?

bla = (function(){
     var a = 0;
     jim = function(){
         if(a==1){
             pete();
         }
     },
     pete = function(){
         return 1;
     }

     var publicInterface = {
         "publicjim": jim
     }
     return publicInterface;
})();

Body:
In your self-executing anonymous function, you're using object propertys.

jim and pete need to be local variables in order to "hide" them via closure.

var bla = (function(){
    var a = 1;
    var jim = function() {
      if (a == 1) {
         pete();
      }
    };
    var pete = function() {
        return 1;
    };

    return {
       "publicjim": jim
    };
})();


问:
Unity - using enum properties to detect objects colliding
Last night I was working on a C-Sharp project trying to code around GameObjects hitting each other.  I wanted different gate types (e.g. wood, stone, metal) that could be broken down by different weapons (e.g. club, sword, axe).

For detecting the collisions on the GateManager I was using tags for each gate. So for example:

```<code>    void OnTriggerEnter(Collider collider) {
       switch (gameObject.tag) {
         case "WoodenGate":
             ...
         case "StoneGate":
             ...
</code>```

The above code isn't exact but should give an idea.  It felt wrong to have each gate type set as a different tag (if every gate type has a different tag and every material type has a different tag, etc, then I will end up with hundreds of tags).

So I came up with an alternative.  I set up an enum of GateType and created 3 values (WoodenGate, StoneGate, MetalGate).  I then attached a public GateType property to the GateManager class.  This allowed me to select which enum was relevant to each prefab within the 'Inspector' window of unity.  It was very neat and I was really happy.

Then a problem arose: I added a 4th enum halfway up the list (e.g. GlassGate). Because the enums are simply int values, the 3rd item was no longer MetalGate but was now StoneGate.  This meant the metal gate prefab suddenly had a GateType of stonegate.  Which broke my game.

Apologies, for the wordy question, but my question therefore is how should I best label and identify lots of different types of items?  I don't want to use tags (because I would need too many) and I don't want to use enums (because they form the brittle issue when used in conjuction with the unity inspector.

I assume this must be a common requirement for many games (e.g. in games you can use your pickaxe on lots of different gameobjects to gathering different resources) so just wondering the best practice?

答:
1.You can declare and use many interface to accomplish this but the downside is that you will need to declare many of them and implement them in many of your script that is attached to each object:

```<code>public interface IDestroyable { }

public interface IOpenable { }
</code>```

then you inherit from itin your scripts:

```<code>public class MyScript : MonoBehaviour, IDestroyable{}

public class MyOtherScript : MonoBehaviour, IOpenable{}
</code>```

Check which one it is during collision:

```<code>void OnTriggerEnter(Collider collider)
{
    if (collider.GetComponent<IOpenable>() != null)
    {

    }

    else if (collider.GetComponent<IDestroyable>() != null)
    {

    }
}
</code>```

2.You can also use enum you mentioned.

```<code>public enum GateType
{
    WoodenGate,
    StoneGate,
    MetalGate
}
</code>```

Attach the single script that describes what type of gate this object is to all the Gate object prefabs then chose the enum for each one from the Editor or script

```<code>public class GateDescription : MonoBehaviour
{
    public GateType gateType;
}
</code>```

Check which one it is during collision:

```<code>void OnTriggerEnter(Collider collider)
{
    GateDescription gateType = collider.GetComponent<GateDescription>();

    if (gateType != null)
    {
        switch (gateType.gateType)
        {
            case GateType.StoneGate:
                break;

            case GateType.WoodenGate:
                break;

            case GateType.MetalGate:
                break;
        }
    }
}
</code>```

Body:
Last night I was working on a C-Sharp project trying to code around GameObjects hitting each other.  I wanted different gate types (e.g. wood, stone, metal) that could be broken down by different weapons (e.g. club, sword, axe).

For detecting the collisions on the GateManager I was using tags for each gate. So for example:

    void OnTriggerEnter(Collider collider) {
       switch (gameObject.tag) {
         case "WoodenGate":
             ...
         case "StoneGate":
             ...

The above code isn't exact but should give an idea.  It felt wrong to have each gate type set as a different tag (if every gate type has a different tag and every material type has a different tag, etc, then I will end up with hundreds of tags).

So I came up with an alternative.  I set up an enum of GateType and created 3 values (WoodenGate, StoneGate, MetalGate).  I then attached a public GateType property to the GateManager class.  This allowed me to select which enum was relevant to each prefab within the 'Inspector' window of unity.  It was very neat and I was really happy.

Then a problem arose: I added a 4th enum halfway up the list (e.g. GlassGate). Because the enums are simply int values, the 3rd item was no longer MetalGate but was now StoneGate.  This meant the metal gate prefab suddenly had a GateType of stonegate.  Which broke my game.

Apologies, for the wordy question, but my question therefore is how should I best label and identify lots of different types of items?  I don't want to use tags (because I would need too many) and I don't want to use enums (because they form the brittle issue when used in conjuction with the unity inspector.

I assume this must be a common requirement for many games (e.g. in games you can use your pickaxe on lots of different gameobjects to gathering different resources) so just wondering the best practice?

Body:
1.You can declare and use many interface to accomplish this but the downside is that you will need to declare many of them and implement them in many of your script that is attached to each object:

public interface IDestroyable { }

public interface IOpenable { }

then you inherit from itin your scripts:

public class MyScript : MonoBehaviour, IDestroyable{}

public class MyOtherScript : MonoBehaviour, IOpenable{}

Check which one it is during collision:

void OnTriggerEnter(Collider collider)
{
    if (collider.GetComponent<IOpenable>() != null)
    {

    }

    else if (collider.GetComponent<IDestroyable>() != null)
    {

    }
}

2.You can also use enum you mentioned.

public enum GateType
{
    WoodenGate,
    StoneGate,
    MetalGate
}

Attach the single script that describes what type of gate this object is to all the Gate object prefabs then chose the enum for each one from the Editor or script

public class GateDescription : MonoBehaviour
{
    public GateType gateType;
}

Check which one it is during collision:

void OnTriggerEnter(Collider collider)
{
    GateDescription gateType = collider.GetComponent<GateDescription>();

    if (gateType != null)
    {
        switch (gateType.gateType)
        {
            case GateType.StoneGate:
                break;

            case GateType.WoodenGate:
                break;

            case GateType.MetalGate:
                break;
        }
    }
}


答:
Try this instead of your css:

```<code>button {
  position: relative;
  margin-top: 40%;
}
</code>```

It work for chrome, Firefox, Edge and IE (just tested these)
By using position: absolute;, the button is fixed in the page, but not fixed in the div.
Always try  to use percentage and not pixel if you can (responsive design is way beter for end users)

Title: Button not centering after moving it to bottom of div

Body:
I'm trying to create a form where the submit is always at the bottom and in the center.

I'm centering by using text-align: center in the parent div and moving it to the bottom with position: absolute and bottom: 20px, but it seems that after I do that it moves slightly off center - why is this case and how do I remedy this?

HTML:

  <form>

      <input name='group 1' type='radio' id='1' />
      option 1

      <input name='group 1' type='radio' id='2' />
      option 2

      <input name='group 2' type='radio' id='3' />
      option 1

      <input name='group 1' type='radio' id='4' />
      option 1

    <button type='submit'>
      Submit
    </button>
  </form>

CSS:

.container {
  width: 400px;
  height: 400px;
  border: 2px solid red;
  text-align: center;
}

button {
  position: absolute;
  bottom: 20px;
}

Demo: https://jsfiddle.net/f9ktLn9o/3/

Body:
Try this instead of your css:

button {
  position: relative;
  margin-top: 40%;
}

It work for chrome, Firefox, Edge and IE (just tested these)
By using position: absolute;, the button is fixed in the page, but not fixed in the div.
Always try  to use percentage and not pixel if you can (responsive design is way beter for end users)


问:
delete whitespace in regular expression
I'm learning python and also english. And I have a problem that might be easy, but I can't solve it. I have a folder of .txt's, I was able to extract by regular expression a sequence of 17 numbers of each one.I need to rename each file with the sequence I extracted from .txt

```<code>import os
import re

path_txt = (r'C:\Users\usuario\Desktop\files')

name_files = os.listdir(path_txt)

for TXT in name_files:
    with open(path_txt + '\\' + TXT, "r") as content:
        search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())
        if search is not None:
            print(search.group(0))
            f = open(os.path.join( "Processes" , search.group(0) + ".txt"), "w")
        for line in content:
            print(line)
            f.write(line)
            f.close()
</code>```

there are .txt where the sequences appear with spaces between characters, and my regular expression can not find them (example: 00372.2004 .442.02.00-1, 00572.2008.872.02.00- 5)

edit: They are serial numbers, were typed, so sometimes they appear with "." and "-" and other times without them. Sometimes spaces appear because of typos.

答:
You want this regex:

```<code>   search = re.search(r'(\d{5}.*\d{4}.*\d{3}.*\d{2}.*\d{2}-.*\d)', content.read())
</code>```

Dot . is any character. By putting \ in front of the dot you escaped it and searched for dots and not any character.

Title: delete whitespace in regular expression

Body:
I'm learning python and also english. And I have a problem that might be easy, but I can't solve it. I have a folder of .txt's, I was able to extract by regular expression a sequence of 17 numbers of each one.I need to rename each file with the sequence I extracted from .txt

import os
import re

path_txt = (r'C:\Users\usuario\Desktop\files')

name_files = os.listdir(path_txt)

for TXT in name_files:
    with open(path_txt + '\\' + TXT, "r") as content:
        search = re.search(r'(\d{5}\.?\d{4}\.?\d{3}\.?\d{2}\.?\d{2}\-?\d)', content.read())
        if search is not None:
            print(search.group(0))
            f = open(os.path.join( "Processes" , search.group(0) + ".txt"), "w")
        for line in content:
            print(line)
            f.write(line)
            f.close()

there are .txt where the sequences appear with spaces between characters, and my regular expression can not find them (example: 00372.2004 .442.02.00-1, 00572.2008.872.02.00- 5)

edit: They are serial numbers, were typed, so sometimes they appear with "." and "-" and other times without them. Sometimes spaces appear because of typos.

Body:
You want this regex:

   search = re.search(r'(\d{5}.*\d{4}.*\d{3}.*\d{2}.*\d{2}-.*\d)', content.read())

Dot . is any character. By putting \ in front of the dot you escaped it and searched for dots and not any character.


问:
change font on click
I want change font after click button
Its my code :

```<code><div id="page">Hello world</div>
<div id="font-load"></div>
<a id="iransans">click me</a>
<script type="text/javascript">
    $("#iransans").click(function(){
        $(document).ready(function() {
            $('#font-load').load("class/client_setting.php?font=iransans", function(){});
            $("#page").addClass("iransans-font");
        });
    });
</script>
<style>
    .iransans-font{
        font-family: iransans !important;
    }
</style>
</code>```

It isn't work for me.
I want change font after click and add class

答:
Try something like this:

$(document).ready(function(){
    $("#iransans").click(function(){
         //$("#page").css("font-family", 'Arial'); //to change the font directly
         $("#page").addClass("iransans-font"); //to add the class on click
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.iransans-font{
    font-family: Arial !important; //change your font here..
}
</style>

<div id="page">Hello world</div>
<div id="font-load"></div>
click me</code>```

Title: change font on click

Body:
I want change font after click button
Its my code :

Hello world

click me

It isn't work for me.
I want change font after click and add class

Body:
Try something like this:

$(document).ready(function(){
    $("#iransans").click(function(){
         //$("#page").css("font-family", 'Arial'); //to change the font directly
         $("#page").addClass("iransans-font"); //to add the class on click
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.iransans-font{
    font-family: Arial !important; //change your font here..
}
</style>

<div id="page">Hello world</div>
<div id="font-load"></div>
<a id="iransans">click me</a>


问:
How to catch exceptions for observables subscribed in Angular template?
In an Angular (4.3.6) application I suscbribe observables in the temnplate with async pipe.

In some cases, when I get a 404 from an HTTP GET, the exception is bubbled up by Angular and the application become unresponsive.
I have seen I could use the .catch() method in my service, but non having directly a .subscribe() method in my component, how can I handle the exception?

documentService:

```<code>public getDocument() {
   return this.getDocument(serverUrl).catch((err) => this.handleError(err));
}

private handleError(error: Response) {
    return Observable.throw(error);
}
</code>```

component:

```<code>public ngOnInit() {

   const document$ = this.reference$
        .filter((i) => !!i)
        .combineLatest(this.documentService.getBranch(),
        (r: any, branch: string) => {
            return this.documentService.getDocument(r.Id, r.targetId, this.GetHeadBranch(branch));
        }).switch();
   }
</code>```

template:

```<code><div *ngIf="document$|async; let document;">
  ....
</div>
</code>```

Is there a best practice to catch exception with observables used like in my case?

答:
As far as I can see from the async source code, there is no way to instruct the pipe what to do when an error occurs. The pipe just throws the error. So it seems you have two choices:

You could create a pipe of your own that takes an additional parameter. Perhaps a callback function to execute when an error occurs. The callback could be passed the source observable along with the error thrown so you can display an appropriate error message and even resubscribe if you want.

You could use catchand handle the error in your service in a way that will format what gets returned so it's suitable for the view.

```<code>private handleError(error: Response) {
    // return Observable.throw(error); //will crash the app when fed to async pipe
    return Observable.of(this.errorDocument); //something the async pipe can display
}
</code>```

See my example

Body:
In an Angular (4.3.6) application I suscbribe observables in the temnplate with async pipe.

In some cases, when I get a 404 from an HTTP GET, the exception is bubbled up by Angular and the application become unresponsive.
I have seen I could use the .catch() method in my service, but non having directly a .subscribe() method in my component, how can I handle the exception?

documentService:

public getDocument() {
   return this.getDocument(serverUrl).catch((err) => this.handleError(err));
}

private handleError(error: Response) {
    return Observable.throw(error);
}

component:

public ngOnInit() {

   const document$ = this.reference$
        .filter((i) => !!i)
        .combineLatest(this.documentService.getBranch(),
        (r: any, branch: string) => {
            return this.documentService.getDocument(r.Id, r.targetId, this.GetHeadBranch(branch));
        }).switch();
   }

template:

  ....

Is there a best practice to catch exception with observables used like in my case?

Body:
As far as I can see from the async source code, there is no way to instruct the pipe what to do when an error occurs. The pipe just throws the error. So it seems you have two choices:

You could create a pipe of your own that takes an additional parameter. Perhaps a callback function to execute when an error occurs. The callback could be passed the source observable along with the error thrown so you can display an appropriate error message and even resubscribe if you want.

You could use catchand handle the error in your service in a way that will format what gets returned so it's suitable for the view.

private handleError(error: Response) {
    // return Observable.throw(error); //will crash the app when fed to async pipe
    return Observable.of(this.errorDocument); //something the async pipe can display
}

See my example