问:
How do I add a map view to an OpenGL ES view?
I am making a 3-D iOS application using OpenGL ES.  I have created a square frame that gets rendered to my OpenGL ES context.

How do I add a map view to this square frame?  I'd like to be able to apply a 3-D effect to this map.

I tried adding the map as a subview of the OpenGL ES hosting view, but didn't see any 3-D effect applied to it.  What am I doing wrong?

答:
I think you might be going about this the wrong way.  First, all OpenGL ES rendering is self-contained within your CAEAGLLayer, so you can't just add a subview and expect it to be part of your scene.  The OpenGL ES content will render within a flat layer, and anything added on top of it will just be stacked on that layer.

You could grab an image of the map view, convert that to a texture, and then upload that texture into your OpenGL scene, but that would probably have terrible performance and I don't think you'd be able to maintain user interaction with the map.

If you are just attempting to provide a perspective effect to your map, you could use a Core Animation CATransform3D to rotate the map view in 3-D and apply perspective to it.  See my answer here for an example of how that could be achieved.  Using Core Animation for this would require far less code than OpenGL ES.


来源: stackexchange

问:
Return different datatypes in a method in java
I have a very silly question in java. I have a main method which in turns calls a method passing one string value. But in return I need to get 3 string values. Can someone please assist?

In main method, I pass only one string value and it has to return 3 string or may be at times 2 string and one int.

```<code>public static void main(String[] args) {
        List <String> ls= cusmethod("string1");
        ls.get(0); //get string A
}

Private static string cusmethod(String test)
{
    String A = "A"+test;
    String B = "B"+test;
    String C = "C"+test;

    // Need to return all these 3 string to main method.
    return A , B, C;
}
</code>```

The method should return the 3 string values to the main method. Please advise how to achieve this. I am not sure how to return these strings to main method and how to retrieve these string in main

答:
You cannot return more then one value in java. You can wrap your result in a class and return that class.

If you need to return n values of the same type you can create a List or an array and return that.

You can create a class which hold this 3 string and return that class, like ...

```<code>class String3 {
    private String res1;
    private String res2;
    private String res3;
    public String3(String res1, String res2, String res3) {
        super();
        this.res1 = res1;
        this.res2 = res2;
        this.res3 = res3;
    }
    public String getRes1() {
        return res1;
    }
    public String getRes2() {
        return res2;
    }
    public String getRes3() {
        return res3;
    }
}
</code>```

Then you can use your Custom class like this.

```<code>private String3 method(String test) {
    String a = "A"+test;
    String b = "B"+test;
    String c = "C"+test;

    // Need to return all these 3 string to main method.
    return new String3(a, b, c);
}
</code>```

You can use a library like vavr to return a tuple.

```<code>Tuple3<String, String, String> result = Tuple.of(A, B, C);
</code>```

The best option is to re-evaluate your code to see how you should do that in java.

You are trying use a solution that is not idiomatic in java, you should try to see how to decompose your problem in a java idiomatic way, not trying to apply solution which are typical of other languages, in the long run it will pay off.

ContentLicense: CC BY-SA 4.0

Body:
I have a very silly question in java. I have a main method which in turns calls a method passing one string value. But in return I need to get 3 string values. Can someone please assist?

In main method, I pass only one string value and it has to return 3 string or may be at times 2 string and one int.

public static void main(String[] args) {
        List <String> ls= cusmethod("string1");
        ls.get(0); //get string A
}

Private static string cusmethod(String test)
{
    String A = "A"+test;
    String B = "B"+test;
    String C = "C"+test;

    // Need to return all these 3 string to main method.
    return A , B, C;
}

The method should return the 3 string values to the main method. Please advise how to achieve this. I am not sure how to return these strings to main method and how to retrieve these string in main

Body:
You cannot return more then one value in java. You can wrap your result in a class and return that class.

If you need to return n values of the same type you can create a List or an array and return that.

You can create a class which hold this 3 string and return that class, like ...

class String3 {
    private String res1;
    private String res2;
    private String res3;
    public String3(String res1, String res2, String res3) {
        super();
        this.res1 = res1;
        this.res2 = res2;
        this.res3 = res3;
    }
    public String getRes1() {
        return res1;
    }
    public String getRes2() {
        return res2;
    }
    public String getRes3() {
        return res3;
    }
}

Then you can use your Custom class like this.

private String3 method(String test) {
    String a = "A"+test;
    String b = "B"+test;
    String c = "C"+test;

    // Need to return all these 3 string to main method.
    return new String3(a, b, c);
}

You can use a library like vavr to return a tuple.

Tuple3<String, String, String> result = Tuple.of(A, B, C);

The best option is to re-evaluate your code to see how you should do that in java.

You are trying use a solution that is not idiomatic in java, you should try to see how to decompose your problem in a java idiomatic way, not trying to apply solution which are typical of other languages, in the long run it will pay off.


问:
Can't solve MongoParseError: Invalid connection string
I'm not able to solve MongoParseError.

First I had tried this

```<code>mongoose.connect(`mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017/${process.env.DB_NAME}`, {useNewUrlParser: true});
</code>```

made me ending up in this error

```<code>MongoParseError: Unescaped slash in userinfo section
</code>```

Then I escaped all the slashes

```<code>mongoose.connect(`mongodb:\\/\\/${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017\\/${process.env.DB_NAME}`, {useNewUrlParser: true});
</code>```

and I ended up in this error which I'm not able to solve

```<code>MongoParseError: Invalid connection string
</code>```

This is my index.js

```<code>'use strict';

const mongoose = require('mongoose');
mongoose.connect(`mongodb:\\/\\/${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017\\/${process.env.DB_NAME}`, {useNewUrlParser: true});

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('ok');
});

const express = require('express');

// Constants
const PORT = 8080;
const HOST = 'localhost';

var kittySchema = new mongoose.Schema({
  name: String
});

var Kitten = mongoose.model('Kitten', kittySchema);

var silence = new Kitten({ name: 'Test1234' });

// App
const app = express();
app.get('/', (req, res) => {
  res.send(silence.name);
});

app.listen(PORT);
console.log(`Running on http://${HOST}:${PORT}`);
</code>```

And here's the docker-compose.yml

```<code>version: '3.7'
services:
  web:
    build: .
    command: npm start
    volumes:
      - ./src:/usr/app/
      - ./src/node_modules:/usr/app/node_modules
    ports:
      - 80:8080
    environment:
      DB_NAME: websitedb
      DB_USER: /run/secrets/db_user
      DB_PASSWORD: /run/secrets/db_password
    secrets:
      - db_user
      - db_password
  db:
    image: mongo:latest
    volumes:
      - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_DATABASE: websitedb
      MONGO_INITDB_ROOT_USERNAME_FILE: /run/secrets/db_user
      MONGO_INITDB_ROOT_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_user
      - db_password
volumes:
  mongo:
secrets:
  db_user:
    file: ./db_user.txt
  db_password:
    file: ./db_password.txt
</code>```

Can anyone tell me what I'm doing wrong?

答:
Looking through the guide on managing secrets in docker compose, it looks like any secrets are passed into the container as a file mounted in /run/secrets/SECRET_NAME, and the suggestion is to pass the path to this file as an environment variable and then read the file in your app:

When you deploy, Docker mounts a file under /run/secrets/ in the services. These files are never persisted in disk, but are managed in memory.

Each service uses environment variables to specify where the service should look for that secret data.

You have passed the path to these secrets as process.env.DB_USER, but to get the actual secret you need to read the file:

```<code>const fs = require('fs');
const mongoose = require('mongoose');

let dbUser = fs.readFileSync(process.env.DB_USER);
let dbPassword = fs.readFileSync(process.env.DB_PASSWORD);

mongoose.connect(`mongodb://${dbUser}:${dbPassword}@db:27017/${process.env.DB_NAME}`, {useNewUrlParser: true});
</code>```

Body:
I'm not able to solve MongoParseError.

First I had tried this

mongoose.connect(`mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017/${process.env.DB_NAME}`, {useNewUrlParser: true});

made me ending up in this error

MongoParseError: Unescaped slash in userinfo section

Then I escaped all the slashes

mongoose.connect(`mongodb:\\/\\/${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017\\/${process.env.DB_NAME}`, {useNewUrlParser: true});

and I ended up in this error which I'm not able to solve

MongoParseError: Invalid connection string

This is my index.js

'use strict';

const mongoose = require('mongoose');
mongoose.connect(`mongodb:\\/\\/${process.env.DB_USER}:${process.env.DB_PASSWORD}@db:27017\\/${process.env.DB_NAME}`, {useNewUrlParser: true});

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('ok');
});

const express = require('express');

// Constants
const PORT = 8080;
const HOST = 'localhost';

var kittySchema = new mongoose.Schema({
  name: String
});

var Kitten = mongoose.model('Kitten', kittySchema);

var silence = new Kitten({ name: 'Test1234' });

// App
const app = express();
app.get('/', (req, res) => {
  res.send(silence.name);
});

app.listen(PORT);
console.log(`Running on http://${HOST}:${PORT}`);

And here's the docker-compose.yml

version: '3.7'
services:
  web:
    build: .
    command: npm start
    volumes:
      - ./src:/usr/app/
      - ./src/node_modules:/usr/app/node_modules
    ports:
      - 80:8080
    environment:
      DB_NAME: websitedb
      DB_USER: /run/secrets/db_user
      DB_PASSWORD: /run/secrets/db_password
    secrets:
      - db_user
      - db_password
  db:
    image: mongo:latest
    volumes:
      - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_DATABASE: websitedb
      MONGO_INITDB_ROOT_USERNAME_FILE: /run/secrets/db_user
      MONGO_INITDB_ROOT_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_user
      - db_password
volumes:
  mongo:
secrets:
  db_user:
    file: ./db_user.txt
  db_password:
    file: ./db_password.txt

Can anyone tell me what I'm doing wrong?

Body:
Looking through the guide on managing secrets in docker compose, it looks like any secrets are passed into the container as a file mounted in /run/secrets/SECRET_NAME, and the suggestion is to pass the path to this file as an environment variable and then read the file in your app:

When you deploy, Docker mounts a file under /run/secrets/ in the services. These files are never persisted in disk, but are managed in memory.

Each service uses environment variables to specify where the service should look for that secret data.

You have passed the path to these secrets as process.env.DB_USER, but to get the actual secret you need to read the file:

const fs = require('fs');
const mongoose = require('mongoose');

let dbUser = fs.readFileSync(process.env.DB_USER);
let dbPassword = fs.readFileSync(process.env.DB_PASSWORD);

mongoose.connect(`mongodb://${dbUser}:${dbPassword}@db:27017/${process.env.DB_NAME}`, {useNewUrlParser: true});


问:
C: is there any way to prevent open a file repeatedly?
I want that each file can only be opened at most once at a time. For example, I have such a c file

```<code>int main()
{
  const char *filename = "test";
  fun1();
  fun2();
  ...
}

void fun1()
{
  fd_1 = open(filename, O_RDWR | O_CREAT | O_APPEND, 0666);
}

void fun2()
{
  fd_2 = open(filename, O_RDWR | O_CREAT | O_APPEND, 0666);
}
</code>```

i.e. to prevent fun2 to open test before the file_descriptor of it has closed the file. I there any way to do this? (except scan the directory fd/)

答:
There is no portable way to determine if a file is already open. You cannot use O_EXCL for your purpose, because you do not want to create a new file.

A simple solution for your purpose, appending to a log file, is to open the file in O_APPEND mode in main and pass the handle to both fun1 and fun2, or make it a global variable. Depending on the details of fun1 and fun2, and if there are nested calls, the output into the log file might be mixed in an undesired fashion. Reorganising the output functions may be required for this problem.

Body:
I want that each file can only be opened at most once at a time. For example, I have such a c file

int main()
{
  const char *filename = "test";
  fun1();
  fun2();
  ...
}

void fun1()
{
  fd_1 = open(filename, O_RDWR | O_CREAT | O_APPEND, 0666);
}

void fun2()
{
  fd_2 = open(filename, O_RDWR | O_CREAT | O_APPEND, 0666);
}

i.e. to prevent fun2 to open test before the file_descriptor of it has closed the file. I there any way to do this? (except scan the directory fd/)


问:
Trying to reverse a linked list using recursion and pointer to pointer but reversell function not giving expected proper output
I was trying to reverse a linked list using recursion and pointer to pointer but reversell function is not working properly as expected. Only reversell function has some problem all other functions are working totally fine. I have used pointer to pointer in insertlast function also and it is working correctly.

Actually i am following
https://www.youtube.com/watch?v=KYH83T4q6Vs&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P&index=11
This video but I tried using pointer to pointer. The code shown in video didn't use pointer to pointer. He has used head as global variable.

```<code>#include <iostream>
using namespace std;

struct node{
    int data;
    struct node* next;
};

void print(node* head){
    while(head !=  NULL){
        cout<<head->data<<" ";
        head=head->next;
    }
}

void reversell(node** head){
    node* temp = (*head);
    if(temp->next == NULL){
        (*head)=temp;
        return;
    }
    reversell(&(temp->next));
    node* temp1 = temp->next;
    temp1->next = temp;
    temp->next = NULL;

}

void insertlast(node** head,int x){
    node* temp = new node;
    temp->data=x;
    if((*head)==NULL){
        (*head)=temp;
        temp->next=NULL;
        return;
    }
    node* temp1=(*head);
    while((temp1->next) != NULL){
        temp1=temp1->next;
    }
    temp1->next=temp;
    temp->next=NULL;
}

int main()
{
    cout<<"How many numbers do you want to add to linked list"<<endl;
    int x;
    cin>>x;
    node* head=NULL;
    cout<<"Please Enter your numbers now"<<endl;
    for (int i=0;i<x;i++){
        int num;
        cin>>num;
        insertlast(&head,num);
    }
    print(head);
    cout<<endl;
    reversell(&head);
    print(head);
    return 0;
}
</code>```

I am currently getting output as shown below:

How many numbers do you want to add to linked list

5

Please Enter your numbers now

1 2 3 4 5

1 2 3 4 5

1

Process finished with exit code 0

Expected output is:

How many numbers do you want to add to linked list

5

Please Enter your numbers now

1 2 3 4 5

1 2 3 4 5

5 4 3 2 1

Process finished with exit code 0

答:
try this

```<code>node *reverse (node *head) {
    // 2) reach the last element and return it
    if(head->next == NULL) {
        return head;
    } else {
        // 1) run revers for tail of our list
        node *new_head = reverse(head->next);
        // 3) relocate pointers
        // new_head = 5;
        // head = 4, head->next = 5, head->next->next = null
        head->next->next = head; // after this line head = 4, head->next = 5, head->next->next = 4
        head->next = NULL; // after this line head = 4, head->next = null, head->next->next = 4
        return new_head; // new_head = 5, new_head->next = 4 similarly recursion takes place further
    }
}
</code>```

And then:

```<code>head = reverse (head);
print(head);
</code>```

Body:
I was trying to reverse a linked list using recursion and pointer to pointer but reversell function is not working properly as expected. Only reversell function has some problem all other functions are working totally fine. I have used pointer to pointer in insertlast function also and it is working correctly.

Actually i am following
https://www.youtube.com/watch?v=KYH83T4q6Vs&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P&index=11
This video but I tried using pointer to pointer. The code shown in video didn't use pointer to pointer. He has used head as global variable.

#include <iostream>
using namespace std;

struct node{
    int data;
    struct node* next;
};

void print(node* head){
    while(head !=  NULL){
        cout<data<<" ";
        head=head->next;
    }
}

void reversell(node** head){
    node* temp = (*head);
    if(temp->next == NULL){
        (*head)=temp;
        return;
    }
    reversell(&(temp->next));
    node* temp1 = temp->next;
    temp1->next = temp;
    temp->next = NULL;

}

void insertlast(node** head,int x){
    node* temp = new node;
    temp->data=x;
    if((*head)==NULL){
        (*head)=temp;
        temp->next=NULL;
        return;
    }
    node* temp1=(*head);
    while((temp1->next) != NULL){
        temp1=temp1->next;
    }
    temp1->next=temp;
    temp->next=NULL;
}

int main()
{
    cout<<"How many numbers do you want to add to linked list"<<endl;
    int x;
    cin>>x;
    node* head=NULL;
    cout<<"Please Enter your numbers now"<<endl;
    for (int i=0;i<x;i++){
        int num;
        cin>>num;
        insertlast(&head,num);
    }
    print(head);
    cout<<endl;
    reversell(&head);
    print(head);
    return 0;
}

I am currently getting output as shown below:

How many numbers do you want to add to linked list

5

Please Enter your numbers now

1 2 3 4 5

1 2 3 4 5

1

Process finished with exit code 0

Expected output is:

How many numbers do you want to add to linked list

5

Please Enter your numbers now

1 2 3 4 5

1 2 3 4 5

5 4 3 2 1

Process finished with exit code 0

Body:
try this

node *reverse (node *head) {
    // 2) reach the last element and return it
    if(head->next == NULL) {
        return head;
    } else {
        // 1) run revers for tail of our list
        node *new_head = reverse(head->next);
        // 3) relocate pointers
        // new_head = 5;
        // head = 4, head->next = 5, head->next->next = null
        head->next->next = head; // after this line head = 4, head->next = 5, head->next->next = 4
        head->next = NULL; // after this line head = 4, head->next = null, head->next->next = 4
        return new_head; // new_head = 5, new_head->next = 4 similarly recursion takes place further
    }
}

And then:

head = reverse (head);
print(head);


问:
Getting method as undefined while running karma test
I have created a scope method inside my controller which is executing when a button is pressed. I am writing unit test cases for the same. I have injected my module in beforeEach block and created spyon my scope function and then using it in 'it' method and checking whether it is called or not. But getting an error as a method not found.

Controller

```<code>    'use strict';

angular.module('myApp.view1', ['ngRoute'])

  .config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/view1', {
      templateUrl: 'view1/view1.html',
      controller: 'View1Ctrl'
    });
  }])

  .controller('View1Ctrl', ['$scope',View1Ctrl])

  function View1Ctrl($scope) {
    $scope.user = {
      name: '',
      last: ''
    }
    $scope.showFormData = function() {
      $scope.formData = $scope.user.name + $scope.user.last;
    }
  }
</code>```

spec.js

```<code>   'use strict';

describe('myApp.view1 module', function () {

  var $controller, $rootScope;
  beforeEach(module('myApp.view1'));

  beforeEach(inject(function (_$controller_, _$rootScope_) {
    $controller = _$controller_;
    $rootScope = _$rootScope_;
  }));

  describe('view1 controller', function () {

    var $scope, controller, formData;
    beforeEach(function () {
      $scope = $rootScope.$new();
      controller = $controller('View1Ctrl', {
        $scope: $scope
      });
      spyOn(controller, 'showFormData');
    });

    it('should check for the show form details', function () {
      $scope.user.name = "Sandeep";
      $scope.user.last = "Gupta";
      expect($scope.showFormData).toHaveBeenCalled();
      expect($scope.user.name + $scope.user.last).toEqual(firstname);
    });

  });
});
</code>```

Need help to resolve this issue.

答:
It looks like you're trying to spy on the showFormData method of the controller:

```<code>  spyOn(controller, 'showFormData');
</code>```

However, the showFormData doesn't exist on the controller, it's a method of the controller's scope.

You'll need to use:

```<code>  spyOn($scope, 'showFormData');
</code>```

It's also important to know that you need to use the same object to both spyOn and expect(...).toHaveBeenCalled(). In your case you where spying on controller.showFormData(), yet expecting $scope.showFormData() to have been called.

Body:
I have created a scope method inside my controller which is executing when a button is pressed. I am writing unit test cases for the same. I have injected my module in beforeEach block and created spyon my scope function and then using it in 'it' method and checking whether it is called or not. But getting an error as a method not found.

Controller

    'use strict';

angular.module('myApp.view1', ['ngRoute'])

  .config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/view1', {
      templateUrl: 'view1/view1.html',
      controller: 'View1Ctrl'
    });
  }])

  .controller('View1Ctrl', ['$scope',View1Ctrl])

  function View1Ctrl($scope) {
    $scope.user = {
      name: '',
      last: ''
    }
    $scope.showFormData = function() {
      $scope.formData = $scope.user.name + $scope.user.last;
    }
  }

spec.js

   'use strict';

describe('myApp.view1 module', function () {

  var $controller, $rootScope;
  beforeEach(module('myApp.view1'));

  beforeEach(inject(function (_$controller_, _$rootScope_) {
    $controller = _$controller_;
    $rootScope = _$rootScope_;
  }));

  describe('view1 controller', function () {

    var $scope, controller, formData;
    beforeEach(function () {
      $scope = $rootScope.$new();
      controller = $controller('View1Ctrl', {
        $scope: $scope
      });
      spyOn(controller, 'showFormData');
    });

    it('should check for the show form details', function () {
      $scope.user.name = "Sandeep";
      $scope.user.last = "Gupta";
      expect($scope.showFormData).toHaveBeenCalled();
      expect($scope.user.name + $scope.user.last).toEqual(firstname);
    });

  });
});

Need help to resolve this issue.

Body:
It looks like you're trying to spy on the showFormData method of the controller:

  spyOn(controller, 'showFormData');

However, the showFormData doesn't exist on the controller, it's a method of the controller's scope.

You'll need to use:

  spyOn($scope, 'showFormData');

It's also important to know that you need to use the same object to both spyOn and expect(...).toHaveBeenCalled(). In your case you where spying on controller.showFormData(), yet expecting $scope.showFormData() to have been called.


问:
Uncaught TypeError: Cannot read property 'class function' of undefined in reactjs
Error: Uncaught TypeError: Cannot read property 'manageChange' of undefined

I have bound the method to "this" as well. I have even tried the arrow function format to define "manageChange". It still does not work.

Please help out with identifying the issue?
Code:

```<code> class App extends React.Component {
  constructor() {
    super();
    this.state = { todos: TodoData };
    this.manageChange = this.manageChange.bind(this);
  }

  manageChange(id) {
    console.log(id);
  }

  render() {
    const todoItems = this.state.todos.map(function (item) {
      return (<TodoItem key={item.id} items={item}
        handleChange={this.manageChange} />);
    }
    );
    return
    (
      <div className="app">
        {todoItems}
      </div>
    );
  }
}
</code>```

答:
There is problem with map function. use arrow function in map. if you use normal function it will have it's own this which won't have manageChange function.</p>

```<code>const todoItems=this.state.todos.map((item) =>
    {
                   return (<TodoItem key={item.id} items={item}
                    handleChange={this.manageChange}/>);
    }
);
</code>```

Body:
Error: Uncaught TypeError: Cannot read property 'manageChange' of undefined

I have bound the method to "this" as well. I have even tried the arrow function format to define "manageChange". It still does not work.

Please help out with identifying the issue?
Code:

 class App extends React.Component {
  constructor() {
    super();
    this.state = { todos: TodoData };
    this.manageChange = this.manageChange.bind(this);
  }

  manageChange(id) {
    console.log(id);
  }

  render() {
    const todoItems = this.state.todos.map(function (item) {
      return (<TodoItem key={item.id} items={item}
        handleChange={this.manageChange} />);
    }
    );
    return
    (

        {todoItems}

    );
  }
}

Body:
There is problem with map function. use arrow function in map. if you use normal function it will have it's own this which won't have manageChange function.

const todoItems=this.state.todos.map((item) =>
    {
                   return (<TodoItem key={item.id} items={item}
                    handleChange={this.manageChange}/>);
    }
);


问:
ggplot2: faceted bar chart using proportions from multiple dummy vars, how to restructure data?
I'm looking for a data visualization for multiple dummy variables faceted by gender. Because my sample size has way more women than men, I'd like to use proportions instead of counts, and I only want the proportion of successes (1). I don't wants bars for both 0 and 1.

I have a sense that I'll need to transform/restructure my data, but I'm not sure how. I know that y = ..prop.., group = 1 will come into play, and that I'll probably have to use faceting, but I haven't come across any questions similar to what I'm trying to do.

My actual data set has 9 different forms of transport, not the 3 included here. I'm imagining a plot with three rows of bar plots, three variables per row. The y-axis is percentages and the X has a transport type, and above that, "Men" and "Women" with the percent of people who have 1 for that variable represented by the bar above. So six bars total per row, for three variables per row, and three rows total.

Here's a link to a very quick and rough sketch of what I'm looking for (but bear in mind the actual datasets has 9 variables, not the 3 pictured here).  Honestly though, I'm not super picky about the specifics so long as its a visualization that captures how men and women utilize transport differently.

```<code>#data
dfTrans <- data.frame(
  "transBus" = c(0, 0, 0, 1, 0, 1),
  "transCar" = c(1, 1, 1, 0, 1, 0),
  "transTaxi" = c(0, 1, 0, 1, 0, 1),
  "gender" = c("Man", "Woman", "Woman", "Woman", "Woman", "Man")
)

#This is the closest I've been able to come, which is not that close
ggplot(data = dfTrans) +
  geom_bar(mapping = aes(x = transBus, y = ..prop.., group = 1), stat = "count") +
  scale_y_continuous(labels = scales::percent_format()) +
  facet_grid(. ~ gender)
</code>```

答:
Try gathering the data and the faceting by transport mode

```<code>dfTrans %>%
  gather(key = mode, value = value, -gender) %>%
  mutate(value = factor(value)) %>%
  ggplot(aes(x = gender, fill = value)) +
  geom_bar(position = position_fill()) +
  scale_y_continuous(labels = scales::percent_format()) +
  facet_wrap(~mode)
</code>```

Update

To just show the blue part you need to summarise the data before hand

```<code>dfTrans %>%
  gather(key = mode, value = value, -gender) %>%
  group_by(mode, gender) %>%
  summarise(prop = mean(value) ) %>%
  ggplot(aes(x = gender, y = prop)) +
  geom_col() +
  scale_y_continuous(labels = scales::percent_format()) +
  facet_wrap(~mode)
</code>```

Body:
I'm looking for a data visualization for multiple dummy variables faceted by gender. Because my sample size has way more women than men, I'd like to use proportions instead of counts, and I only want the proportion of successes (1). I don't wants bars for both 0 and 1.

I have a sense that I'll need to transform/restructure my data, but I'm not sure how. I know that y = ..prop.., group = 1 will come into play, and that I'll probably have to use faceting, but I haven't come across any questions similar to what I'm trying to do.

My actual data set has 9 different forms of transport, not the 3 included here. I'm imagining a plot with three rows of bar plots, three variables per row. The y-axis is percentages and the X has a transport type, and above that, "Men" and "Women" with the percent of people who have 1 for that variable represented by the bar above. So six bars total per row, for three variables per row, and three rows total.

Here's a link to a very quick and rough sketch of what I'm looking for (but bear in mind the actual datasets has 9 variables, not the 3 pictured here).  Honestly though, I'm not super picky about the specifics so long as its a visualization that captures how men and women utilize transport differently.

#data
dfTrans <- data.frame(
  "transBus" = c(0, 0, 0, 1, 0, 1),
  "transCar" = c(1, 1, 1, 0, 1, 0),
  "transTaxi" = c(0, 1, 0, 1, 0, 1),
  "gender" = c("Man", "Woman", "Woman", "Woman", "Woman", "Man")
)

#This is the closest I've been able to come, which is not that close
ggplot(data = dfTrans) +
  geom_bar(mapping = aes(x = transBus, y = ..prop.., group = 1), stat = "count") +
  scale_y_continuous(labels = scales::percent_format()) +
  facet_grid(. ~ gender)

Body:
Try gathering the data and the faceting by transport mode

dfTrans %>%
  gather(key = mode, value = value, -gender) %>%
  mutate(value = factor(value)) %>%
  ggplot(aes(x = gender, fill = value)) +
  geom_bar(position = position_fill()) +
  scale_y_continuous(labels = scales::percent_format()) +
  facet_wrap(~mode)

Update

To just show the blue part you need to summarise the data before hand

dfTrans %>%
  gather(key = mode, value = value, -gender) %>%
  group_by(mode, gender) %>%
  summarise(prop = mean(value) ) %>%
  ggplot(aes(x = gender, y = prop)) +
  geom_col() +
  scale_y_continuous(labels = scales::percent_format()) +
  facet_wrap(~mode)


问:
Gitlab Docker build: calling shell command in .gitlab-ci.yml
I'm trying to call shell command in .gitlab-ci.yml, whose relevant parts are:

```<code>image: docker:latest
services:
  - docker:dind

stages:
  - build
  - deploy

...

build:
  stage: build
  script:
    - apt-get update -y
    - GIT_TAG=$(git tag | tail -1)
    - GIT_TAG=$(/usr/bin/git tag | tail -1)
    - docker ...
</code>```

However all top three shell command callings have failed, all with "command not found" error. The git command being failing is really odd, because it has to get the git repo first before start the script section. I.e., I can see that git is working, but I just can't use it myself.

Is there any way to make it working?

答:
from the documentation of GitLab, here is the definition of CI_COMMIT_TAG:

CI_COMMIT_TAG - The commit tag name. Present only when building tags

means - when you will push a commit to GitLab, then it will start a pipeline without CI_COMMIT_TAG variable. When you make a tag on this commit and push this tag to GitLab, then another pipeline (this time for the tag, not for the commit) will be started. In that case CI_COMMIT_TAG will be present.

@xpt - thanks for the vote confidence and asking to write up this as an answer, hope this helps the community!

Body:
I'm trying to call shell command in .gitlab-ci.yml, whose relevant parts are:

image: docker:latest
services:
  - docker:dind

stages:
  - build
  - deploy

...

build:
  stage: build
  script:
    - apt-get update -y
    - GIT_TAG=$(git tag | tail -1)
    - GIT_TAG=$(/usr/bin/git tag | tail -1)
    - docker ...

However all top three shell command callings have failed, all with "command not found" error. The git command being failing is really odd, because it has to get the git repo first before start the script section. I.e., I can see that git is working, but I just can't use it myself.

Is there any way to make it working?


问:
How do I get elements from an array without repetition?
How do I get 5 elements from an array without repetition?

I'm trying to create an online version of story dice using Tumult Hype. All that I need to do is choose 5 image names from an array without repetition. But I just can't get it to work.

I've tried borrowing code from other stackoverflow answers and I can't get them working.

The code below is currently working but gives me repeats. How do I tinker with it to eliminate the repeats?

(You can see it in action here: https://davebirss.com/storydice/)

I know that it's probably verbose and inelegant. I only speak pidgin javascript, I'm afraid. And what I'm trying to do is currently beyond my ability.

Thank you so much in advance for your help.

```<code>var diceRoll = ['${resourcesFolderName}/story_dice1.png',
        '${resourcesFolderName}/story_dice2.png',
        '${resourcesFolderName}/story_dice3.png',
        ...,
        '${resourcesFolderName}/story_dice51.png']

function choose(n, arr) {
    while (arr.length > n) {
        var del = Math.floor(Math.random() * arr.length);
        arr = arr.filter(function(item, i) {
            return i !== del;
        });
    }
    return arr;}

var result1 = [choose(1, diceRoll)];
var result2 = [choose(1, diceRoll)];
var result3 = [choose(1, diceRoll)];
var result4 = [choose(1, diceRoll)];
var result5 = [choose(1, diceRoll)];

hypeDocument.getElementById("dice1").innerHTML = "<img src='"+result1+" 'height='125' width='125'>";
hypeDocument.getElementById("dice2").innerHTML = "<img src='"+result2+" 'height='125' width='125'>";
hypeDocument.getElementById("dice3").innerHTML = "<img src='"+result3+" 'height='125' width='125'>";
hypeDocument.getElementById("dice4").innerHTML = "<img src='"+result4+" 'height='125' width='125'>";
hypeDocument.getElementById("dice5").innerHTML = "<img src='"+result5+" 'height='125' width='125'>";
</code>```

Update

Thank you all for your help. I'm sure all the answers were great but the snippet from U25lYWt5IEJhc3RhcmQg is the code that I managed to successfully incorporate. For the record, this is how I did it:

```<code>const rollTheDice = (arr, n) => {
  const randomN = [];
  while(randomN.length < n){
    const randomIndex = Math.floor(Math.random()*arr.length);
    randomN.push(arr[randomIndex]);
    arr.splice(randomIndex, 1);
  }
  return randomN;}

var result1 = (rollTheDice(images,1));
var result2 = (rollTheDice(images,1));
var result3 = (rollTheDice(images,1));
var result4 = (rollTheDice(images,1));
var result5 = (rollTheDice(images,1));
</code>```

I've been repeatedly reloading the page and haven't seen any repeats yet. Perfect!

答:
Make a copy of diceRoll array (diceRollCopy).

Use the new array(diceRollCopy) as argument of choose method.

Whenever you get a
result using choose method remove that result from the Copy array
(diceRollCopy).

You would need to reset the diceRollCopy to diceRoll
after each set of results have been accessed.

Body:
How do I get 5 elements from an array without repetition?

I'm trying to create an online version of story dice using Tumult Hype. All that I need to do is choose 5 image names from an array without repetition. But I just can't get it to work.

I've tried borrowing code from other stackoverflow answers and I can't get them working.

The code below is currently working but gives me repeats. How do I tinker with it to eliminate the repeats?

(You can see it in action here: https://davebirss.com/storydice/)

I know that it's probably verbose and inelegant. I only speak pidgin javascript, I'm afraid. And what I'm trying to do is currently beyond my ability.

Thank you so much in advance for your help.

var diceRoll = ['${resourcesFolderName}/story_dice1.png',
        '${resourcesFolderName}/story_dice2.png',
        '${resourcesFolderName}/story_dice3.png',
        ...,
        '${resourcesFolderName}/story_dice51.png']

function choose(n, arr) {
    while (arr.length > n) {
        var del = Math.floor(Math.random() * arr.length);
        arr = arr.filter(function(item, i) {
            return i !== del;
        });
    }
    return arr;}

var result1 = [choose(1, diceRoll)];
var result2 = [choose(1, diceRoll)];
var result3 = [choose(1, diceRoll)];
var result4 = [choose(1, diceRoll)];
var result5 = [choose(1, diceRoll)];

hypeDocument.getElementById("dice1").innerHTML = "";
hypeDocument.getElementById("dice2").innerHTML = "";
hypeDocument.getElementById("dice3").innerHTML = "";
hypeDocument.getElementById("dice4").innerHTML = "";
hypeDocument.getElementById("dice5").innerHTML = "";

Update

Thank you all for your help. I'm sure all the answers were great but the snippet from U25lYWt5IEJhc3RhcmQg is the code that I managed to successfully incorporate. For the record, this is how I did it:

const rollTheDice = (arr, n) => {
  const randomN = [];
  while(randomN.length < n){
    const randomIndex = Math.floor(Math.random()*arr.length);
    randomN.push(arr[randomIndex]);
    arr.splice(randomIndex, 1);
  }
  return randomN;}

var result1 = (rollTheDice(images,1));
var result2 = (rollTheDice(images,1));
var result3 = (rollTheDice(images,1));
var result4 = (rollTheDice(images,1));
var result5 = (rollTheDice(images,1));

I've been repeatedly reloading the page and haven't seen any repeats yet. Perfect!


问:
How to setup my crontab in order to execute process_tasks in Django?
I decided to use a library for my Django project called django-background-tasks (link to the documentation: https://django-background-tasks.readthedocs.io/en/latest/). I want to deploy my Django application to a Linux server (Ubuntu 19.0.4). How should I write the crontab in order to call the command "process_tasks" every five seconds?

Here Running a cron every 30 seconds is a workaround to achieve the seconds part, but since I am new to this part of the job (deploying and automation of process), how should I create my crontab file in order to achieve my desired purpose?

I'll be using process_tasks for a lot of different functionalities like: do some analysis at night and send results in the morning, expire some codes, etc. So basically I'll need to be running it almost constantly.

Thank you in advance for any suggestion, if you need something more I would be happy to provide it to you.

答: Not knowing any details, this may be a completely inapplicable alternative. However, if there is a guarantee that there will be nothing to be done until (an) instance(s) of (a) particular model(s) is saved, and provided that this save doesn't happen far too frequently, then you might look at Django post_save signals instead. Whenever that save happens, either execute the task, or execute the task if it wasn't run already in the last five seconds.


问:
Kendo UI Jquery ContextMenu inside Kendo UI ListView
I am trying to use a kendo ui contextMenu on kendo ui listView items but it does work , and there is no error.</p>

```<code>//The ListView HTML
<div id="listView"></div>
<div id="pager" class="k-pager-wrap"></div>

 <script type="text/x-kendo-template" id="template">
        <div class="document">
            <img width="65px" height="65px" src="../Content/extensionsIcon/#=FileExtension#.png" alt="#: DocTitle #" />
            <h5>#:DocTitle#</h5>
        </div>
    </script>

 //The ContextMenu HTML
 <ul id="context-menu">
<li id="download">Download</li>
<li id="remove">Remove</li>
</ul>

 $("#context-menu").kendoContextMenu({
    target: "#listView .document",
    select: function (e) {

    }
});
</code>```

答:
Refer to the context menu demo. You should use the filter property of context menu.</p>

```<code>      $("#context-menu").kendoContextMenu({
                    target: "#listView",
                    filter: ".document",
                    select: function(e) {
                        // Do something on select
                    }
       });
</code>```

Body:
I am trying to use a kendo ui contextMenu on kendo ui listView items but it does work , and there is no error.

//The ListView HTML

 //The ContextMenu HTML

Download

Remove

 $("#context-menu").kendoContextMenu({
    target: "#listView .document",
    select: function (e) {

    }
});

Body:
Refer to the context menu demo. You should use the filter property of context menu.

      $("#context-menu").kendoContextMenu({
                    target: "#listView",
                    filter: ".document",
                    select: function(e) {
                        // Do something on select
                    }
       });


问:
what is the equivalent concept in apache royale for flexmdi.swc , flexlib.swc
When I am migrating the flex to royale application , i am unable to implement the concept MDIWindow Concept in royale.

I am able to find in Visual Studio Code IDE the implementation

```<code>//Generated from: C:\RemoteObjectAMFTest\external\flexlib.swc
package flexlib.mdi.containers

public class MDIWindow extends mx.containers.Panel
</code>```

but not able to find at compile time.

could you please help to compile MDIWindow  successfully in royale?

col: 9 Warning: Definition flexlib.containers.MDIWindow could not be found.

  import flexmdi.containers.MDIWindow; or flexlib.containers.MDIWindow

答: As far as I know, MDIWindow has not been ported to Royale. Your best bet might be to decide on the features you actually need for your app and implement those parts yourself. Hope this helps.</p>

Body:
When I am migrating the flex to royale application , i am unable to implement the concept MDIWindow Concept in royale.

I am able to find in Visual Studio Code IDE the implementation

//Generated from: C:\RemoteObjectAMFTest\external\flexlib.swc
package flexlib.mdi.containers

public class MDIWindow extends mx.containers.Panel

but not able to find at compile time.

could you please help to compile MDIWindow  successfully in royale?

col: 9 Warning: Definition flexlib.containers.MDIWindow could not be found.

  import flexmdi.containers.MDIWindow; or flexlib.containers.MDIWindow


问:
Auth::id() can't find user id and return null, laravel
I am setting like and unlike options on articles. but in LikeController there is problem. when I push the like button it says ->

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id'
  cannot be null (SQL: insert into likes (user_id, article_id,
  updated_at, created_at) values (?, 5, 2019-05-30 07:58:34,
  2019-05-30 07:58:34))

Updated JWT and Routes

Like model:

```<code>class Like extends Model
{
    public $timestamps = true;
    public $with = ["user"];

    protected $fillable = ["user_id", "article_id"];

    public function article()
    {
        return $this->belongsTo("App\Article");
    }

    public function user()
    {
        return $this->belongsTo("App\User");
    }
}
</code>```

and LikeController:

```<code>use Auth;
use App\Article;
use App\Like;

public function like($id)
{
    $article = Article::find($id);

    $like =  Like::create([
        "user_id" => Auth::id(),
        "article_id" => $article->id
    ]);

    return Like::find($like->id);
}

public function unlike($id)
{
    $article = Article::find($id);

    Like::where("user_id", Auth::id())
        ->where("article_id", $article->id)
        ->first()
        ->delete();

    return 1;
}
</code>```

I am not very sure why Auth::id() can't find the user id and return null?

Using JWT with vue.js

Routes:

```<code>Route::group(['prefix' => 'auth'], function ($router) {

  Route::post('register', 'AuthController@register');
  Route::post('login', 'AuthController@login');
  Route::post('logout', 'AuthController@logout');
  Route::post('refresh', 'AuthController@refresh');
  Route::post('me', 'AuthController@me');

});

Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);
</code>```

AuthController and User

to set controller and user model I followed the docs: https://jwt-auth.readthedocs.io/en/develop/quick-start/

答:
first: ensure that   route or Controller protected by auth middleware.

second: ensure that you are using correct guard for auth, if using multiple guard.

```<code>you should specify your guard name like this: `Auth::guard('admin')->id()`
</code>```

Body:
I am setting like and unlike options on articles. but in LikeController there is problem. when I push the like button it says ->

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id'
  cannot be null (SQL: insert into likes (user_id, article_id,
  updated_at, created_at) values (?, 5, 2019-05-30 07:58:34,
  2019-05-30 07:58:34))

Updated JWT and Routes

Like model:

class Like extends Model
{
    public $timestamps = true;
    public $with = ["user"];

    protected $fillable = ["user_id", "article_id"];

    public function article()
    {
        return $this->belongsTo("App\Article");
    }

    public function user()
    {
        return $this->belongsTo("App\User");
    }
}

and LikeController:

use Auth;
use App\Article;
use App\Like;

public function like($id)
{
    $article = Article::find($id);

    $like =  Like::create([
        "user_id" => Auth::id(),
        "article_id" => $article->id
    ]);

    return Like::find($like->id);
}

public function unlike($id)
{
    $article = Article::find($id);

    Like::where("user_id", Auth::id())
        ->where("article_id", $article->id)
        ->first()
        ->delete();

    return 1;
}

I am not very sure why Auth::id() can't find the user id and return null?

Using JWT with vue.js

Routes:

Route::group(['prefix' => 'auth'], function ($router) {

  Route::post('register', 'AuthController@register');
  Route::post('login', 'AuthController@login');
  Route::post('logout', 'AuthController@logout');
  Route::post('refresh', 'AuthController@refresh');
  Route::post('me', 'AuthController@me');

});

Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

AuthController and User

to set controller and user model I followed the docs: https://jwt-auth.readthedocs.io/en/develop/quick-start/

Body:
first: ensure that   route or Controller protected by auth middleware.

second: ensure that you are using correct guard for auth, if using multiple guard.

you should specify your guard name like this: `Auth::guard('admin')->id()`


问:
AWS Glue: Maximum needed executors < active executors
I was looking at my AWS Glue job metrics and found something weird ...

Why is the number of active executors needed > the maximum needed executors? Why are they not killed?

In Glue at some times as shown in the graph, the number of active executors changes, am I charged based on the number of active executors or what I specified in the job settings?

答:
The maximum needed executors number is computed from the actively
  running and pending task counts, so it might be smaller than the
  number of active executors. This is because there can be executors
  that are partially or completely idle for a short period of time and
  are not yet decommissioned.

Reference: https://docs.aws.amazon.com/glue/latest/dg/monitor-debug-capacity.html

No, you are charged based on number of max DPUs allocated and glue job execution time.


问:
Best canonical String to represent a Calendar object?
I need to store a Calendar object as a String and also be able to load a Calendar object from that String. What do I need in my String to accurately represent everything a Calendar holds?

For instance, if I used SimpleDateFormatter and use the pattern yyyyMMddHHmmssSSSzz, which is year, month, date, hour, minute, second, millisecond, and timezone, would I be able to reliably recreate the Calendar object from that String?

答: You can just use millis to represent datetime and have extra field for TZ offset + Locale. That would be enough.</p>

ContentLicense: CC BY-SA 3.0


问:
How can I add multiple domains to Access-Control-Allow-Origin in Spring Boot?
My REST API is server multiple domains. How can i allow more than one domain in my headers.

My Code in Java:

```<code>    public class CORSFilter implements Filter {

        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin","abc.com","xyz.com");
            response.setHeader("Cache-Control", "no-store, public, max-age=0");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Strict-Transport-Security", "max-age=63072000; includeSubDomains;");
            chain.doFilter(req, res);
        }

    }
</code>```

答:
Using CorsRegistry:

```<code>@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**")
        .allowedOrigins("http://domain1.com","http://domain2.com");
}
</code>```

Using @CrossOrigin:

```<code>@CrossOrigin(origins = {"http://domain1.com","http://domain2.com"})
</code>```

Using application.properties

```<code>management.endpoints.web.cors.allowed-origins=http://domain1.com,http://domain2.com
</code>```

Body:
My REST API is server multiple domains. How can i allow more than one domain in my headers.

My Code in Java:

    public class CORSFilter implements Filter {

        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin","abc.com","xyz.com");
            response.setHeader("Cache-Control", "no-store, public, max-age=0");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Strict-Transport-Security", "max-age=63072000; includeSubDomains;");
            chain.doFilter(req, res);
        }

    }

Body:
Using CorsRegistry:

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**")
        .allowedOrigins("http://domain1.com","http://domain2.com");
}

Using @CrossOrigin:

@CrossOrigin(origins = {"http://domain1.com","http://domain2.com"})

Using application.properties

management.endpoints.web.cors.allowed-origins=http://domain1.com,http://domain2.com


问:
how to parse output of new Date().toString()
I need a date format (maybe SimpleDateFormat) that parses reliable the output I get when I call toString() on a Date object. Output on my german(!) system is: "Sun Dec 12 13:45:12 CET 2010", so it doesn't seem to honor locales, which seems to make it easy.

Anyone?

答:
TL;DR

```<code>    Instant parsedBack = Instant.parse(Instant.now().toString());
    System.out.println(parsedBack);
</code>```

2019-05-30T08:36:47.966274Z

Use ISO 8601 and java.time

If your real goal is to serialize and deserialize a date and time (for data transfer or for persistence, for example), serialize to ISO 8601, the standard format for date and time data.

Skip the long outdated Date class. The modern Java date and time API known as java.time is so much nicer to work with. The class you need from it is probably Instant (this depends on your more exact requirements).

The two points go nicely hand in hand:

```<code>    Instant i = Instant.now();
    String s = i.toString();
    Instant theSameInstant = Instant.parse(s);
</code>```

The modern classes’ toString methods produce ISO 8601 format (e.g., 2018-01-11T10:59:45.036Z), and their parse methods read the same format back. So this snippet is all you need, and you get an instant equal to the first, with nanosecond precision.

If you cannot control the string you get, and you get the result from Date.toString(), the format pattern string in BalusC’s answer works with java.time too:

```<code>    DateTimeFormatter dtf
            = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
    Date d = new Date();
    String s = d.toString();
    Instant nearlyTheSameInstant = ZonedDateTime.parse(s, dtf).toInstant();
</code>```

Some warnings, though:

Milliseconds from the original Date are lost since they are not in the string, leading to an inaccuracy of up to 999 milliseconds (which was why I named the variable nearlyTheSameInstant).

The era from the original Date is not in the string either. So if your original Date was in year 44 BCE, you will get the corresponding date in year 44 CE (AD) (in which case the variable name nearlyTheSameInstant was a lie anyway).

The time zone abbreviation in the string is often (most often?) ambiguous, so there is a great risk of getting the wrong time zone and hence a wrong time. To make matters worse, an ambiguous time zone abbreviation will be interpreted differently on different JVMs

It’s essential to provide a locale. Otherwise the JVM’s default locale will be used, and if it’s not English, parsing will fail. In the worst case you will see your code running fine for many years and suddenly it will break when one day someone runs it on a computer or device with a different locale setting. I use Locale.ROOT for “the locale neutral locale” or “don’t apply any locale specific processing”. It seems to be the correct approach here.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Wikipedia article: ISO 8601

ContentLicense: CC BY-SA 2.5

Body:
TL;DR

    Instant parsedBack = Instant.parse(Instant.now().toString());
    System.out.println(parsedBack);

2019-05-30T08:36:47.966274Z

Use ISO 8601 and java.time

If your real goal is to serialize and deserialize a date and time (for data transfer or for persistence, for example), serialize to ISO 8601, the standard format for date and time data.

Skip the long outdated Date class. The modern Java date and time API known as java.time is so much nicer to work with. The class you need from it is probably Instant (this depends on your more exact requirements).

The two points go nicely hand in hand:

    Instant i = Instant.now();
    String s = i.toString();
    Instant theSameInstant = Instant.parse(s);

The modern classes’ toString methods produce ISO 8601 format (e.g., 2018-01-11T10:59:45.036Z), and their parse methods read the same format back. So this snippet is all you need, and you get an instant equal to the first, with nanosecond precision.

If you cannot control the string you get, and you get the result from Date.toString(), the format pattern string in BalusC’s answer works with java.time too:

    DateTimeFormatter dtf
            = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
    Date d = new Date();
    String s = d.toString();
    Instant nearlyTheSameInstant = ZonedDateTime.parse(s, dtf).toInstant();

Some warnings, though:

Milliseconds from the original Date are lost since they are not in the string, leading to an inaccuracy of up to 999 milliseconds (which was why I named the variable nearlyTheSameInstant).

The era from the original Date is not in the string either. So if your original Date was in year 44 BCE, you will get the corresponding date in year 44 CE (AD) (in which case the variable name nearlyTheSameInstant was a lie anyway).

The time zone abbreviation in the string is often (most often?) ambiguous, so there is a great risk of getting the wrong time zone and hence a wrong time. To make matters worse, an ambiguous time zone abbreviation will be interpreted differently on different JVMs

It’s essential to provide a locale. Otherwise the JVM’s default locale will be used, and if it’s not English, parsing will fail. In the worst case you will see your code running fine for many years and suddenly it will break when one day someone runs it on a computer or device with a different locale setting. I use Locale.ROOT for “the locale neutral locale” or “don’t apply any locale specific processing”. It seems to be the correct approach here.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Wikipedia article: ISO 8601


问:
Flexible date/time parsing in Go (Adding default values in parsing)
Further to this question, I want to parse a date/time passed on the command line to a Go program. At the moment, I use the flag package to populate a string variable ts and then the following code:

```<code>if ts == "" {
    config.Until = time.Now()
} else {
    const layout = "2006-01-02T15:04:05"
    if config.Until, err = time.Parse(layout, ts); err != nil {
        log.Errorf("Could not parse %s as a time string: %s. Using current date/time instead.", ts, err.Error())
        config.Until = time.Now()
    }
}
</code>```

This works OK, provided the user passes exactly the right format - e.g. 2019-05-20T09:07:33 or some such.

However, what I would like, if possible, is the flexibility to pass e.g. 2019-05-20T09:07 or 2019-05-20T09 or maybe even 2019-05-20 and have the hours, minutes and seconds default to 0 where appropriate.

Is there a sane1 way to do this?

  1 not requiring me to essentially write my own parser

UPDATE

I've kind of got a solution to this, although it's not particularly elegant, it does appear to work for most of the cases I am likely to encounter.

```<code>package main

import (
    "fmt"
    "time"
)

func main() {

    const layout = "2006-01-02T15:04:05"
    var l string
    var input string

    for _, input = range []string{"2019-05-30", "2019-05-30T16", "2019-05-30T16:04", "2019-05-30T16:04:34",
                                "This won't work", "This is extravagantly long and won't work either"} {
        if len(input) < len(layout) {
            l = layout[:len(input)]
        } else {
            l = layout
        }
        if d, err := time.Parse(l, input); err != nil {
            fmt.Printf("Error %s\n", err.Error())
        } else {
            fmt.Printf("Layout %-20s gives time %v\n", l, d)
        }
    }
}
</code>```

答: In the specific scenario you describe, you could check the length of the input datestamp string, and add the proper length of zero stuff at the end of it to correspond to your layout. So basically you could append as much of the string "T00:00:00" (counting from the end), to the input as is missing in length compared to the layout format string.

Body:
Further to this question, I want to parse a date/time passed on the command line to a Go program. At the moment, I use the flag package to populate a string variable ts and then the following code:

if ts == "" {
    config.Until = time.Now()
} else {
    const layout = "2006-01-02T15:04:05"
    if config.Until, err = time.Parse(layout, ts); err != nil {
        log.Errorf("Could not parse %s as a time string: %s. Using current date/time instead.", ts, err.Error())
        config.Until = time.Now()
    }
}

This works OK, provided the user passes exactly the right format - e.g. 2019-05-20T09:07:33 or some such.

However, what I would like, if possible, is the flexibility to pass e.g. 2019-05-20T09:07 or 2019-05-20T09 or maybe even 2019-05-20 and have the hours, minutes and seconds default to 0 where appropriate.

Is there a sane1 way to do this?

  1 not requiring me to essentially write my own parser

UPDATE

I've kind of got a solution to this, although it's not particularly elegant, it does appear to work for most of the cases I am likely to encounter.

package main

import (
    "fmt"
    "time"
)

func main() {

    const layout = "2006-01-02T15:04:05"
    var l string
    var input string

    for _, input = range []string{"2019-05-30", "2019-05-30T16", "2019-05-30T16:04", "2019-05-30T16:04:34",
                                "This won't work", "This is extravagantly long and won't work either"} {
        if len(input) < len(layout) {
            l = layout[:len(input)]
        } else {
            l = layout
        }
        if d, err := time.Parse(l, input); err != nil {
            fmt.Printf("Error %s\n", err.Error())
        } else {
            fmt.Printf("Layout %-20s gives time %v\n", l, d)
        }
    }
}


问:
Using React.lazy with TypeScript
I am trying to use React.lazy for code splitting in my TypeScript React app.

All I am doing is changing that line:

```<code>import {ScreensProductList} from "./screens/Products/List";
</code>```

to this line:

```<code>const ScreensProductList = lazy(() => import('./screens/Products/List'));
</code>```

But the import('./screens/Products/List') part triggers a TypeScript error, stating:

```<code>Type error: Type 'Promise<typeof import("/Users/johannesklauss/Documents/Development/ay-coding-challenge/src/screens/Products/List")>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'.
  Property 'default' is missing in type 'typeof import("/Users/johannesklauss/Documents/Development/ay-coding-challenge/src/screens/Products/List")' but required in type '{ default: ComponentType<any>; }'.
</code>```

I am not quite sure what I am supposed to do here to get it to work.

答:
You can create an index.ts file where you can export all your components like in this eg. :

```<code>export {default as YourComponentName} from "./YourComponentName";
</code>```

After that you can use React.lazy:

```<code>React.lazy(() => import("../components/folder-name-where-the-index-file-is-created").then(({YourComponentName}) => ({default: YourComponentName})))
</code>```

Title: Using React.lazy with TypeScript

Body:
I am trying to use React.lazy for code splitting in my TypeScript React app.

All I am doing is changing that line:

import {ScreensProductList} from "./screens/Products/List";

to this line:

const ScreensProductList = lazy(() => import('./screens/Products/List'));

But the import('./screens/Products/List') part triggers a TypeScript error, stating:

Type error: Type 'Promise<typeof import("/Users/johannesklauss/Documents/Development/ay-coding-challenge/src/screens/Products/List")>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'.
  Property 'default' is missing in type 'typeof import("/Users/johannesklauss/Documents/Development/ay-coding-challenge/src/screens/Products/List")' but required in type '{ default: ComponentType<any>; }'.

I am not quite sure what I am supposed to do here to get it to work.

Body:
You can create an index.ts file where you can export all your components like in this eg. :

export {default as YourComponentName} from "./YourComponentName";

After that you can use React.lazy:

React.lazy(() => import("../components/folder-name-where-the-index-file-is-created").then(({YourComponentName}) => ({default: YourComponentName})))


问:
Python 3.6: Signature of {method} incompatible with super type {Class}
While trying to update my code to be PEP-484 compliant (I'm using mypy 0.610) I've ran into the following report:

$ mypy mymodule --strict-optional --ignore-missing-imports --disallow-untyped-calls --python-version 3.6

myfile.py:154: error: Signature of "deliver" incompatible with supertype "MyClass"

MyClass:

```<code>from abc import abstractmethod

from typing import Any

class MyClass(object):

@abstractmethod
def deliver(self, *args: Any, **kwargs: Any) -> bool:
    raise NotImplementedError
</code>```

myfile.py:

```<code>class MyImplementation(MyClass):

[...]

    def deliver(self, source_path: str,
                dest_branches: list,
                commit_msg: str = None,
                exclude_files: list = None) -> bool:

        [...]

        return True
</code>```

I'm definitely doing something wrong here, but I can't quite understand what :)

Any pointers would be much appreciated.

答:
Maybe you should work it around this way:

Define abstract method without arguments:

```<code>class MyClass:
    @abstractmethod
    def deliver(self) -> bool:
        raise NotImplementedError
</code>```

In implementations get all your data from self:

```<code>class MyImplementation(MyClass):
    def __init__(
            self,
            source_path: str,
            dest_branches: list,
            commit_msg: str = None,
            exclude_files: list = None
    ) -> None:
        super().__init__()
        self.source_path = source_path
        self.dest_branches = dest_branches
        self.commit_msg = commit_msg
        self.exclude_files = exclude_files

    def deliver(self) -> bool:
        # some logic
        if self.source_path and self.commit_msg:
            return True
        return False
</code>```

This way you will have completely compatible method declarations and still can implement methods as you want.

Body:
While trying to update my code to be PEP-484 compliant (I'm using mypy 0.610) I've ran into the following report:

$ mypy mymodule --strict-optional --ignore-missing-imports --disallow-untyped-calls --python-version 3.6

myfile.py:154: error: Signature of "deliver" incompatible with supertype "MyClass"

MyClass:

from abc import abstractmethod

from typing import Any

class MyClass(object):

@abstractmethod
def deliver(self, *args: Any, **kwargs: Any) -> bool:
    raise NotImplementedError

myfile.py:

class MyImplementation(MyClass):

[...]

    def deliver(self, source_path: str,
                dest_branches: list,
                commit_msg: str = None,
                exclude_files: list = None) -> bool:

        [...]

        return True

I'm definitely doing something wrong here, but I can't quite understand what :)

Any pointers would be much appreciated.

Body:
Maybe you should work it around this way:

Define abstract method without arguments:

class MyClass:
    @abstractmethod
    def deliver(self) -> bool:
        raise NotImplementedError

In implementations get all your data from self:

class MyImplementation(MyClass):
    def __init__(
            self,
            source_path: str,
            dest_branches: list,
            commit_msg: str = None,
            exclude_files: list = None
    ) -> None:
        super().__init__()
        self.source_path = source_path
        self.dest_branches = dest_branches
        self.commit_msg = commit_msg
        self.exclude_files = exclude_files

    def deliver(self) -> bool:
        # some logic
        if self.source_path and self.commit_msg:
            return True
        return False

This way you will have completely compatible method declarations and still can implement methods as you want.


问:
Checked List Box with data value property for each item?
Does anyone know of a control such as a Checked List Box where each item can have a value against it.

For example you have a list of fruits and in the listbox it displays Apple, Orange & Banana but the values for those items are A, O & B.

答:
The CheckedListBox control can already do that. Its Items collection accepts any object that derives from System.Objects. The objects are displayed in the list using the value returned from their ToString method.

Therefore, you can create your own custom classes and add them to the CheckedListBox. Make sure that you overload the ToString method to return the string you want to be displayed in the list box. Then, you can add any other methods or properties to the class that you want. When you get a reference to a selected item, you can cast it to your Fruit class and call any method you want.


问:
An AutoHotkey script to move the cursor two words
I'm attempting to write an AutoHotkey script that moves the cursor to the beginning of the second next word, in a similar way that Window's ctrl + arrows and fn + arrows shortcuts works.

I use very often this pair of shortcuts, but I frequently find that the first one moves the cursor too slowly and the second one too fast. So I would like to get a script that moves the caret, as described, two words instead of one (for example, when pressing ctrl + alt + arrows).

I've never scripted for automated actions on the keyboard before, so this is all new territory for me. I assume anyone with some experience could implement the above in a minute or two.

答: I have realized that it is much easier than writing an AutoHotkey script, it can be done by recording a macro in Microsoft Word.</p>


问:
Why my code is not able to convert each item of list from string to integer?
I am stuck on a problem due to a small portion of my code. I can't find why that portion of code is not working properly.

By debugging each portion of my code, I found which lines are causing unexpected results. I have written that lines below. I have defined the list here so that I do not have to copy my full code.

```<code>list1=["-7","-7","-6"]

for test in list1:

    test=int(test)

print( type( list1[0] ) )
</code>```

I expected type to be int but output is coming as str instead.

答:
You need to modify the content of the list:

```<code>list1=["-7","-7","-6"]

for i in range(len(list1)):
    list1[i] = int(list1[i])

print(type(list1[0]))
</code>```

A more pythonic approach would be to use a comprehension to change it all at once:

```<code>list1 = [int(x) for x in list1]
</code>```

Body:
I am stuck on a problem due to a small portion of my code. I can't find why that portion of code is not working properly.

By debugging each portion of my code, I found which lines are causing unexpected results. I have written that lines below. I have defined the list here so that I do not have to copy my full code.

list1=["-7","-7","-6"]

for test in list1:

    test=int(test)

print( type( list1[0] ) )

I expected type to be int but output is coming as str instead.

Body:
You need to modify the content of the list:

list1=["-7","-7","-6"]

for i in range(len(list1)):
    list1[i] = int(list1[i])

print(type(list1[0]))

A more pythonic approach would be to use a comprehension to change it all at once:

list1 = [int(x) for x in list1]


问:
Set the table column width constant regardless of the amount of text in its cells?
In my table I set the width of the first cell in a column to be 100px.

However, when the text in one of the cell in this column is too long, the width of the column becomes more than 100px. How could I disable this expansion?

答:
Setting this:

```<code>style="min-width:100px;"
</code>```

Worked for me.

Body:
Setting this:

style="min-width:100px;"

Worked for me.


问:
Configuration setting updates
How can I remove author name and datetime from drupal article from admin section? I have already tried admin content type configuration setting for the same, but that didn't work.</p>

答: If solution @PraveenKumar suggested didn't work for you it means that your theme is not reading this settings but always displaying author's info. Find what theme your site uses and then find template file used for content type from which you want to remove author's info. Edit template file and remove rows which are displaying that info.</p>

Title: Configuration setting updates


问:
Save option form and pass JS variable
I have a form that has radiobuttons and listboxes. I am trying to call a php file on button press to save the selected options into a MySQL database. I would like to pass the selected options as well as the total_cost, which is a JS variable.

How can I pass the JS variable to the php file when the form submit button is pressed?

```<code><form action="saveConfig.php" class="hide-submit" method="post">

<div class="btn-configure step2button">
<span class="pcButtonText">
Save
</span>
</div>

<ul id="radio" class="input-list">
  <li>
    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    <label for="item-1">Item 1 [£1.00]</label>
  </li>
  <li>
    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    <label for="item-2">Item 2 [£12.34]</label>
  </li>
  <li>
    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    <label for="item-3">Item 3 [£9.99]</label>
  </li>
</ul>

<select id="plist" name="partlist" onchange="updateTotal();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>

</form>
<br>
Total: <input id="total" type="text">
</code>```

JS:

```<code>let buildcost = 25.00;

function updateTotal() {
  let radios = document.getElementsByName('config-prod');
  let select = document.getElementById('plist');
  let partcost = 0;

  for (let i = 0, j = radios.length; i < j; i++) {
    if (radios[i].checked) {
      partcost = parseFloat(radios[i].value);
      break;
    }
  }

  partcost += parseFloat(select.options[select.selectedIndex].value);

  let total_cost = buildcost + partcost;
  document.getElementById('total').value = total_cost.toFixed(2);
}
</code>```

I cannot figure out how to pass the variable total_cost. Any advice would be appreciated.

答:
No 1 : you have kept Total: <input id="total" type="text"> out from closing </form> tag.
keep it inside the </form> tag.

No2 : Input field <input id="total" type="text"> is missing name attribute.
it should be like <input id="total" type="text" name="total">

Hope this will work

Title: Save option form and pass JS variable

Body:
I have a form that has radiobuttons and listboxes. I am trying to call a php file on button press to save the selected options into a MySQL database. I would like to pass the selected options as well as the total_cost, which is a JS variable.

How can I pass the JS variable to the php file when the form submit button is pressed?

<form action="saveConfig.php" class="hide-submit" method="post">

Save

    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    Item 1 [£1.00]

    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    Item 2 [£12.34]

    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    Item 3 [£9.99]

<select id="plist" name="partlist" onchange="updateTotal();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>

</form>

Total: <input id="total" type="text">

JS:

let buildcost = 25.00;

function updateTotal() {
  let radios = document.getElementsByName('config-prod');
  let select = document.getElementById('plist');
  let partcost = 0;

  for (let i = 0, j = radios.length; i < j; i++) {
    if (radios[i].checked) {
      partcost = parseFloat(radios[i].value);
      break;
    }
  }

  partcost += parseFloat(select.options[select.selectedIndex].value);

  let total_cost = buildcost + partcost;
  document.getElementById('total').value = total_cost.toFixed(2);
}

I cannot figure out how to pass the variable total_cost. Any advice would be appreciated.


问:
How to show documentation in Clojure
I do the following :

```<code>(defn ss [] "kjhhj")
(doc ss)
</code>```

but get "nil" returned. Why is this?

Update:

If I do :

```<code>(defn tt "kjhhj" [] 1)
(str (doc tt) )
</code>```

as shown I get back an empty string... Does the "doc" output go to out or something?

答:
To capture the output of something that prints to *out*, use</p>

```<code>(with-out-str (doc f))
</code>```

Title: How to show documentation in Clojure

Body:
I do the following :

(defn ss [] "kjhhj")
(doc ss)

but get "nil" returned. Why is this?

Update:

If I do :

(defn tt "kjhhj" [] 1)
(str (doc tt) )

as shown I get back an empty string... Does the "doc" output go to out or something?

Body:
To capture the output of something that prints to *out*, use

(with-out-str (doc f))


问:
How do I get elements from an array without repetition?
How do I get 5 elements from an array without repetition?

I'm trying to create an online version of story dice using Tumult Hype. All that I need to do is choose 5 image names from an array without repetition. But I just can't get it to work.

I've tried borrowing code from other stackoverflow answers and I can't get them working.

The code below is currently working but gives me repeats. How do I tinker with it to eliminate the repeats?

(You can see it in action here: https://davebirss.com/storydice/)

I know that it's probably verbose and inelegant. I only speak pidgin javascript, I'm afraid. And what I'm trying to do is currently beyond my ability.

Thank you so much in advance for your help.

```<code>var diceRoll = ['${resourcesFolderName}/story_dice1.png',
        '${resourcesFolderName}/story_dice2.png',
        '${resourcesFolderName}/story_dice3.png',
        ...,
        '${resourcesFolderName}/story_dice51.png']

function choose(n, arr) {
    while (arr.length > n) {
        var del = Math.floor(Math.random() * arr.length);
        arr = arr.filter(function(item, i) {
            return i !== del;
        });
    }
    return arr;}

var result1 = [choose(1, diceRoll)];
var result2 = [choose(1, diceRoll)];
var result3 = [choose(1, diceRoll)];
var result4 = [choose(1, diceRoll)];
var result5 = [choose(1, diceRoll)];

hypeDocument.getElementById("dice1").innerHTML = "<img src='"+result1+" 'height='125' width='125'>";
hypeDocument.getElementById("dice2").innerHTML = "<img src='"+result2+" 'height='125' width='125'>";
hypeDocument.getElementById("dice3").innerHTML = "<img src='"+result3+" 'height='125' width='125'>";
hypeDocument.getElementById("dice4").innerHTML = "<img src='"+result4+" 'height='125' width='125'>";
hypeDocument.getElementById("dice5").innerHTML = "<img src='"+result5+" 'height='125' width='125'>";
</code>```

Update

Thank you all for your help. I'm sure all the answers were great but the snippet from U25lYWt5IEJhc3RhcmQg is the code that I managed to successfully incorporate. For the record, this is how I did it:

```<code>const rollTheDice = (arr, n) => {
  const randomN = [];
  while(randomN.length < n){
    const randomIndex = Math.floor(Math.random()*arr.length);
    randomN.push(arr[randomIndex]);
    arr.splice(randomIndex, 1);
  }
  return randomN;}

var result1 = (rollTheDice(images,1));
var result2 = (rollTheDice(images,1));
var result3 = (rollTheDice(images,1));
var result4 = (rollTheDice(images,1));
var result5 = (rollTheDice(images,1));
</code>```

I've been repeatedly reloading the page and haven't seen any repeats yet. Perfect!

答:
You could take an array of indices and check if the index exist, then get a new index or push this index.

var length = 51,  // your count of items
    indices = [], // the result set with indices
    count = 5,    // the amount of wanted indices
    random;       // guess what?

while (indices.length < count) {                 // check length
    random = Math.floor(Math.random() * length); // get random value
    if (indices.includes(random)) continue;      // continue if already selected
    indices.push(random);                        // if not take it
}

console.log(indices);```

Body:
How do I get 5 elements from an array without repetition?

I'm trying to create an online version of story dice using Tumult Hype. All that I need to do is choose 5 image names from an array without repetition. But I just can't get it to work.

I've tried borrowing code from other stackoverflow answers and I can't get them working.

The code below is currently working but gives me repeats. How do I tinker with it to eliminate the repeats?

(You can see it in action here: https://davebirss.com/storydice/)

I know that it's probably verbose and inelegant. I only speak pidgin javascript, I'm afraid. And what I'm trying to do is currently beyond my ability.

Thank you so much in advance for your help.

var diceRoll = ['${resourcesFolderName}/story_dice1.png',
        '${resourcesFolderName}/story_dice2.png',
        '${resourcesFolderName}/story_dice3.png',
        ...,
        '${resourcesFolderName}/story_dice51.png']

function choose(n, arr) {
    while (arr.length > n) {
        var del = Math.floor(Math.random() * arr.length);
        arr = arr.filter(function(item, i) {
            return i !== del;
        });
    }
    return arr;}

var result1 = [choose(1, diceRoll)];
var result2 = [choose(1, diceRoll)];
var result3 = [choose(1, diceRoll)];
var result4 = [choose(1, diceRoll)];
var result5 = [choose(1, diceRoll)];

hypeDocument.getElementById("dice1").innerHTML = "";
hypeDocument.getElementById("dice2").innerHTML = "";
hypeDocument.getElementById("dice3").innerHTML = "";
hypeDocument.getElementById("dice4").innerHTML = "";
hypeDocument.getElementById("dice5").innerHTML = "";

Update

Thank you all for your help. I'm sure all the answers were great but the snippet from U25lYWt5IEJhc3RhcmQg is the code that I managed to successfully incorporate. For the record, this is how I did it:

const rollTheDice = (arr, n) => {
  const randomN = [];
  while(randomN.length < n){
    const randomIndex = Math.floor(Math.random()*arr.length);
    randomN.push(arr[randomIndex]);
    arr.splice(randomIndex, 1);
  }
  return randomN;}

var result1 = (rollTheDice(images,1));
var result2 = (rollTheDice(images,1));
var result3 = (rollTheDice(images,1));
var result4 = (rollTheDice(images,1));
var result5 = (rollTheDice(images,1));

I've been repeatedly reloading the page and haven't seen any repeats yet. Perfect!


问:
How can I make ipdb show more lines of context while debugging?
By default, during debugging in IPython, ipdb shows one line above and one line below the current position in code.

Is there an easy way to make the area shown a bit bigger? I'd think it would be configurable, but haven't been able to find it.

答:
If you want to stop execution in a running system, as others said, use:

ipdb.set_trace(context=number_of_lines)
```

<p>For running some function or an object's method modifying this context lines is a little bit tricky. The only way I found was:</p>

<pre class="lang-py prettyprint-override"><code>ipdb.__main__._init_pdb(context=number_of_lines).runcall(callable, *args, **kwargs)
</code>```

In case it serves someone.

Body:
If you want to stop execution in a running system, as others said, use:

ipdb.set_trace(context=number_of_lines)

For running some function or an object's method modifying this context lines is a little bit tricky. The only way I found was:

ipdb.__main__._init_pdb(context=number_of_lines).runcall(callable, *args, **kwargs)

In case it serves someone.


问:
Replace all occurrences of stirng in a string excluding other words starting with same characters
I want to replace all occurrences of string in a sentence but it should not replace other words starting with same string. Example If string is "abc bb bb bbcv cc ccv" and I want to replace bb and cc with "" so my expected output should be "abc bbcv cc".

I am using .replace method with but it is replacing bb and cc in word "bbcv" & "ccv" as well.

答:
Here's a shorter way, it removes every space (\s) followed by a word bb or cc:

var str = 'abc bb bb bbcv cc ccv';
var res = str.replace(/\s(bb|cc)\b/g, '');
console.log(res);```


答:
Copy it, then shuffle the copy, and remove the first element from the array each time:

```<code>const copy = [...diceRoll].sort(e => 0.5 - Math.random());
</code>```

And in your choosing function:

```<code>const chosen = copy.shift();
</code>```

Title: How do I get elements from an array without repetition?

Body:
Copy it, then shuffle the copy, and remove the first element from the array each time:

const copy = [...diceRoll].sort(e => 0.5 - Math.random());

And in your choosing function:

const chosen = copy.shift();


问:
Avoiding compiler issues with abs()
When using the double variant of the std::abs() function without the std with g++ 4.6.1, no warning or error is given.

```<code>#include <algorithm>
#include <cmath>

double foobar(double a)
{
     return abs(a);
}
</code>```

This version of g++ seems to be pulling in the double variant of abs() into the global namespace through one of the includes from algorithm. This looks like it is now allowed by the standard (see this question), but not required.

If I compile the above code using a compiler that does not pull the double variant of abs() into the global namespace (such as g++ 4.2), then the following error is reported:

```<code>warning: passing 'double' for argument 1 to 'int abs(int)'
</code>```

How can I force g++ 4.6.1, and other compilers that pull functions into the global namespace, to give a warning so that I can prevent errors when used with other compilers?

答:
Be warned, you don't need to explicitly #include <cmath>, <iostream> does the damage as well (and maybe some other headers).  Also, note that -Wall doesn't give you any warnings about it.

```<code>#include <iostream>

int main() {
  std::cout << abs(.5) << std::endl;
  std::cout << typeid(decltype(abs)).name() << std::endl;
}
</code>```

Gives output

```<code>0
FiiE
</code>```

On

```<code>gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04)
</code>```

Title: Avoiding compiler issues with abs()

Body:
When using the double variant of the std::abs() function without the std with g++ 4.6.1, no warning or error is given.

#include <algorithm>
#include <cmath>

double foobar(double a)
{
     return abs(a);
}

This version of g++ seems to be pulling in the double variant of abs() into the global namespace through one of the includes from algorithm. This looks like it is now allowed by the standard (see this question), but not required.

If I compile the above code using a compiler that does not pull the double variant of abs() into the global namespace (such as g++ 4.2), then the following error is reported:

warning: passing 'double' for argument 1 to 'int abs(int)'

How can I force g++ 4.6.1, and other compilers that pull functions into the global namespace, to give a warning so that I can prevent errors when used with other compilers?

Body:
Be warned, you don't need to explicitly #include <cmath>, <iostream> does the damage as well (and maybe some other headers).  Also, note that -Wall doesn't give you any warnings about it.

#include <iostream>

int main() {
  std::cout << abs(.5) << std::endl;
  std::cout << typeid(decltype(abs)).name() << std::endl;
}

Gives output

0
FiiE

On

gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04)


问:
how to insert JSON array of objects into PostgreSQL as separate elements
I have JSON and I'm sending it to postgresql function. I need to insert every object inside weekDays array in a separate row and every key inside the object in a separate column and it needs to include weekId.

My table looks like this:

```<code>{
   "weekId":20,
   "weekDays":[
      {
         "day_of_week":"Monday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      },
      {
         "day_of_week":"Tuesday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      }
   ]
}
</code>```

So what is the best way to do this? I can do something like this:

```<code>INSERT INTO timesheet(day_of_week, working_hours, description, date)
SELECT day_of_week, working_hours, description, date
FROM json_to_recordset(weeks_days)
AS x(day_of_week varchar, working_hours REAL, description text, date timestamp);
</code>```

But how to include weekId that is not in array?

答:
Use ->> operator to get weekId as text and cast it to integer, e.g.:

```<code>WITH my_data(jsonb_column) AS (
VALUES
('{
   "weekId":20,
   "weekDays":[
      {
         "day_of_week":"Monday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      },
      {
         "day_of_week":"Tuesday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      }
   ]
}'::jsonb)
)

INSERT INTO timesheet(weekid, day_of_week, working_hours, description, date)
SELECT (jsonb_column->>'weekId')::int, day_of_week, working_hours, description, date
FROM my_data
CROSS JOIN jsonb_to_recordset(jsonb_column->'weekDays')
AS x(day_of_week varchar, working_hours REAL, description text, date timestamp)
RETURNING *;

 id | weekid | day_of_week | working_hours | description |        date
----+--------+-------------+---------------+-------------+---------------------
  1 |     20 | Monday      |          22.5 | text        | 2019-05-22 00:00:00
  2 |     20 | Tuesday     |          22.5 | text        | 2019-05-22 00:00:00
(2 rows)
</code>```

In Postgres 11 you can cast jsonb number to integer (-> instead of ->>):

```<code>SELECT (jsonb_column->'weekId')::int, day_of_week, working_hours, description, date
</code>```

Body:
I have JSON and I'm sending it to postgresql function. I need to insert every object inside weekDays array in a separate row and every key inside the object in a separate column and it needs to include weekId.

My table looks like this:

{
   "weekId":20,
   "weekDays":[
      {
         "day_of_week":"Monday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      },
      {
         "day_of_week":"Tuesday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      }
   ]
}

So what is the best way to do this? I can do something like this:

INSERT INTO timesheet(day_of_week, working_hours, description, date)
SELECT day_of_week, working_hours, description, date
FROM json_to_recordset(weeks_days)
AS x(day_of_week varchar, working_hours REAL, description text, date timestamp);

But how to include weekId that is not in array?

Body:
Use ->> operator to get weekId as text and cast it to integer, e.g.:

WITH my_data(jsonb_column) AS (
VALUES
('{
   "weekId":20,
   "weekDays":[
      {
         "day_of_week":"Monday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      },
      {
         "day_of_week":"Tuesday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      }
   ]
}'::jsonb)
)

INSERT INTO timesheet(weekid, day_of_week, working_hours, description, date)
SELECT (jsonb_column->>'weekId')::int, day_of_week, working_hours, description, date
FROM my_data
CROSS JOIN jsonb_to_recordset(jsonb_column->'weekDays')
AS x(day_of_week varchar, working_hours REAL, description text, date timestamp)
RETURNING *;

 id | weekid | day_of_week | working_hours | description |        date
----+--------+-------------+---------------+-------------+---------------------
  1 |     20 | Monday      |          22.5 | text        | 2019-05-22 00:00:00
  2 |     20 | Tuesday     |          22.5 | text        | 2019-05-22 00:00:00
(2 rows)

In Postgres 11 you can cast jsonb number to integer (-> instead of ->>):

SELECT (jsonb_column->'weekId')::int, day_of_week, working_hours, description, date


问:
How to make an activity popup with timer
Hello guys how are you today I hope you are OK
I have an application with many activity's :

Main-activity

activity1

activity2

activity3

what I need to do is make the activity3 popup every (x) minute, for example, every 2 or 3 minutes the activity3 popup how can I do that and thanks in advance.

public class MainActivity extends Activity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Remove notification bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //Remove title bar
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    //load the xml file for the starting loading screen
    setContentView(R.layout.activity_main);

    Log.d("MainActivity:", "onCreate: created activity_main.xml UI succesfully.");

    new Timer().schedule(new TimerTask(){
        public void run() {
            startActivity(new Intent(MainActivity.this, PrimaryActivity.class));
            finish();

            Log.d("MainActivity:", "onCreate: waiting 5 seconds for MainActivity... loading PrimaryActivity.class");
        }
    }, 5000 );
}
</code>```

}

I didn't know how to try this before posting so I need your help thanks in advance.

答:
'Make the popup function static and call it with class name like'

yourclassname.popupFunction(Context);

'in on create method where you want to open the primary activity'

```<code>public static void popupFunction(Activity activity){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
              startActivity(new Intent(activity, PrimaryActivity.class));
              finish();

              Log.d("MainActivity:", "onCreate: waiting 5 seconds for MainActivity...
                     loading PrimaryActivity.class");

            }
        },5000);
    }
</code>```

'Hope you get the answer Thanks'

Body:
Hello guys how are you today I hope you are OK
I have an application with many activity's :

Main-activity

activity1

activity2

activity3

what I need to do is make the activity3 popup every (x) minute, for example, every 2 or 3 minutes the activity3 popup how can I do that and thanks in advance.

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Remove notification bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //Remove title bar
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    //load the xml file for the starting loading screen
    setContentView(R.layout.activity_main);

    Log.d("MainActivity:", "onCreate: created activity_main.xml UI succesfully.");

    new Timer().schedule(new TimerTask(){
        public void run() {
            startActivity(new Intent(MainActivity.this, PrimaryActivity.class));
            finish();

            Log.d("MainActivity:", "onCreate: waiting 5 seconds for MainActivity... loading PrimaryActivity.class");
        }
    }, 5000 );
}

}

I didn't know how to try this before posting so I need your help thanks in advance.

Body:
'Make the popup function static and call it with class name like'

yourclassname.popupFunction(Context);

'in on create method where you want to open the primary activity'

public static void popupFunction(Activity activity){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
              startActivity(new Intent(activity, PrimaryActivity.class));
              finish();

              Log.d("MainActivity:", "onCreate: waiting 5 seconds for MainActivity...
                     loading PrimaryActivity.class");

            }
        },5000);
    }

'Hope you get the answer Thanks'


答:
Try this to convert each item of a list to integer format :

```<code>list1=["-7","-7","-6"]
list1 = list(map(int, list1))
</code>```

list1 becomes [-7, -7, -6].

Now type(list1[0]) would be <class 'int'>

Title: Why my code is not able to convert each item of list from string to integer?

Body:
Try this to convert each item of a list to integer format :

list1=["-7","-7","-6"]
list1 = list(map(int, list1))

list1 becomes [-7, -7, -6].

Now type(list1[0]) would be <class 'int'>