问:
Kafka JDBC Source Connector is not reading data from mysql with sql query?
I have created a local database for testing purpose on MySQL. When I'm trying to read the data from the database, it's reading fine. When I use the SQL query in connector configuration, it's just running but not reading any data from the database. Any idea what might cause this?

Here is my connector config:

```<code>name=just-like
acks=0
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
key.converter=io.confluent.connect.avro.AvroConverter
key.converter.schema.registry.url=http://localhost:8081
value.converter=io.confluent.connect.avro.AvroConverter
value.converter.schema.registry.url=http://localhost:8081
connection.url=jdbc:mysql://localhost:3306/DBtest?user=**&password=**
connection.user=**
connection.password=**
table.whitelist=test
mode=timestamp
timestamp.column.name=createddate
query= select column_name from table_name
validate.non.null=False
topic.prefix=sql-
</code>```

Database Schema

答: We shouldn't use the tag table.whitelist with the custom query. If you want to use the query tag, I suggest removing the table.whitelist tag. You can't use them both together.

Body:
I have created a local database for testing purpose on MySQL. When I'm trying to read the data from the database, it's reading fine. When I use the SQL query in connector configuration, it's just running but not reading any data from the database. Any idea what might cause this?

Here is my connector config:

name=just-like
acks=0
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
key.converter=io.confluent.connect.avro.AvroConverter
key.converter.schema.registry.url=http://localhost:8081
value.converter=io.confluent.connect.avro.AvroConverter
value.converter.schema.registry.url=http://localhost:8081
connection.url=jdbc:mysql://localhost:3306/DBtest?user=**&password=**
connection.user=**
connection.password=**
table.whitelist=test
mode=timestamp
timestamp.column.name=createddate
query= select column_name from table_name
validate.non.null=False
topic.prefix=sql-

Database Schema


来源: stackexchange

问:
The bootstrap features of checkbox not working when done using jquery append
The Bootstrap works perfectly fine in html section for the checkbox, but when I use it in the JavaScript section to append a tag, it doesn't work.

I am unable to find any solution.
I want the way it works in html, it to work in the same way when adding with java script.

The bootstrap is not getting used for the checkbox

```<code>let addItem = (value) => {
  $("#todo").append(`<li>
  <div class="custom-control custom-checkbox mb-3">
  <input type="checkbox" class="custom-control-input" id="customCheck" name="example1">
  <label class="custom-control-label" for="customCheck">${value}</label>
  <button type="button" class="btn btn-danger" id="delete"><i class="fas fa-trash"></i></button>
  </div>
  </li>`);
}
</code>```

答:
```<code>$('#todo').on('click', '.delete', () => { $(this).parent().remove();});
</code>```

You are using an arrow function as the callback.Arrow functions don't bind the 'this' variable by default.What you need to do is use the function declaration for the callback.The following would work

```<code>$("#todo").on("click", ".delete", function() {
  console.log("this", this);
  $(this)
    .parent()
    .remove();
});
</code>```

That being said,if you still want to use arrow functions for the callback,you could specify the callback with the event parameter as follows which will also work

```<code>$("#todo").on("click", ".delete", event => {
  console.log("this", event);
  $(event.currentTarget)
    .parent()
    .remove();
});
</code>```

Also,since you are using Babel in npm run build, it will convert the ES6 code to ES5 implementation so that all browsers which may not support ES6 javascript up and until now will be able to run your code without errors.

For further reading on the usage of arrow functions, refer the following article.

https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/

ContentLicense: CC BY-SA 4.0

Body:
The Bootstrap works perfectly fine in html section for the checkbox, but when I use it in the JavaScript section to append a tag, it doesn't work.

I am unable to find any solution.
I want the way it works in html, it to work in the same way when adding with java script.

The bootstrap is not getting used for the checkbox

let addItem = (value) => {
  $("#todo").append(`

  <input type="checkbox" class="custom-control-input" id="customCheck" name="example1">
  ${value}
  <button type="button" class="btn btn-danger" id="delete"></button>

`);
}

Body:
$('#todo').on('click', '.delete', () => { $(this).parent().remove();});

You are using an arrow function as the callback.Arrow functions don't bind the 'this' variable by default.What you need to do is use the function declaration for the callback.The following would work

$("#todo").on("click", ".delete", function() {
  console.log("this", this);
  $(this)
    .parent()
    .remove();
});

That being said,if you still want to use arrow functions for the callback,you could specify the callback with the event parameter as follows which will also work

$("#todo").on("click", ".delete", event => {
  console.log("this", event);
  $(event.currentTarget)
    .parent()
    .remove();
});

Also,since you are using Babel in npm run build, it will convert the ES6 code to ES5 implementation so that all browsers which may not support ES6 javascript up and until now will be able to run your code without errors.

For further reading on the usage of arrow functions, refer the following article.

https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/


问:
Javascript - Image dimensions form multiple file input
Can't get the dimensions - height and width: the result is always "undefined". I clearly don't understand how JavaScript works here. I am however, able to display the file.

The PHP file contains the following input tag, which selects multiple pictures:

```<code>$output = "<input class=\"wpisNazwyWkladow\"
id=\"wpis_tabela_zdjecie_wybieracz\" type=\"file\" multiple
name=\"ads_photofile\">";
</code>```

This is the JavaScript script in question:

```<code>var input = $(this); // works
var ilosc = input[0].files.length;
var pliki = input[0].files;

for (var i = 0; i < ilosc; i++)
{
   var tmppath = URL.createObjectURL(pliki[i]); // works - displays
   var nazwa = pliki[i].name; // works
   var tempRozmiar = pliki[i].size; // works
   var typ = pliki[i].type; // typ fotki // works

   // The part that does not work:
   tempWysokosc = tmppath.height;
   tempSzerokosc = tmppath.width;

}
</code>```

I'm expecting an integer value for "tempWysokosc" and "tempSzerokosc".

Need help please.

答:
In your code tmppath is the result of URL.createObjectURL(), that is, a String.

This string obviously doesn't have a width nor an height.
What you want, is to retrieve these values from a loaded  element whose src will be set to tmppath. But this process is always asynchronous, so you'll probably need to refactor your code to embrace this asynchronicity:

input.oninput = e => {
const ilosc = input.files.length;
const pliki = input.files;

for (let i = 0; i < ilosc; i++)
{
   const tmppath = URL.createObjectURL(pliki[i]); // works - displays
   const nazwa = pliki[i].name; // works
   const tempRozmiar = pliki[i].size; // works
   const typ = pliki[i].type; // typ fotki // works

   const img = new Image();
   // async
   img.onload = e => {
    const tempWysokosc = img.height;
    const tempSzerokosc = img.width;
    console.log({
      name: nazwa,
      size: tempRozmiar,
      type: typ,
      width: tempWysokosc,
      height: tempSzerokosc
    });
   };
   img.src = tmppath;
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="input" type="file" accept="image/*" multiple></code>```

Note that if you have a lot of such images you want to retrieve the dimensions of, you might be interested in this Q/A which exposes a way of getting it from reading the files directly, avoiding the big overhead of decoding the images.

Body:
Can't get the dimensions - height and width: the result is always "undefined". I clearly don't understand how JavaScript works here. I am however, able to display the file.

The PHP file contains the following input tag, which selects multiple pictures:

$output = "<input class=\"wpisNazwyWkladow\"
id=\"wpis_tabela_zdjecie_wybieracz\" type=\"file\" multiple
name=\"ads_photofile\">";

This is the JavaScript script in question:

var input = $(this); // works
var ilosc = input[0].files.length;
var pliki = input[0].files;

for (var i = 0; i < ilosc; i++)
{
   var tmppath = URL.createObjectURL(pliki[i]); // works - displays
   var nazwa = pliki[i].name; // works
   var tempRozmiar = pliki[i].size; // works
   var typ = pliki[i].type; // typ fotki // works

   // The part that does not work:
   tempWysokosc = tmppath.height;
   tempSzerokosc = tmppath.width;

}

I'm expecting an integer value for "tempWysokosc" and "tempSzerokosc".

Need help please.

Body:
In your code tmppath is the result of URL.createObjectURL(), that is, a String.

This string obviously doesn't have a width nor an height.
What you want, is to retrieve these values from a loaded <img> element whose src will be set to tmppath. But this process is always asynchronous, so you'll probably need to refactor your code to embrace this asynchronicity:

input.oninput = e => {
const ilosc = input.files.length;
const pliki = input.files;

for (let i = 0; i < ilosc; i++)
{
   const tmppath = URL.createObjectURL(pliki[i]); // works - displays
   const nazwa = pliki[i].name; // works
   const tempRozmiar = pliki[i].size; // works
   const typ = pliki[i].type; // typ fotki // works

   const img = new Image();
   // async
   img.onload = e => {
    const tempWysokosc = img.height;
    const tempSzerokosc = img.width;
    console.log({
      name: nazwa,
      size: tempRozmiar,
      type: typ,
      width: tempWysokosc,
      height: tempSzerokosc
    });
   };
   img.src = tmppath;
  }

}

<input id="input" type="file" accept="image/*" multiple>

Note that if you have a lot of such images you want to retrieve the dimensions of, you might be interested in this Q/A which exposes a way of getting it from reading the files directly, avoiding the big overhead of decoding the images.


问:
Dotenv not getting value as string
I have installed dotenv to set enviroment variables for development and production, one of those variable is the ROOT_API, my env file look like this

```<code>NODE_ENV=dev
ROOT_API=http://localhost/project/public/
PORT=8000
</code>```

I set my api request configuration in axios and followed the steps in the dotenv repo like this

```<code>require('dotenv').config({path: `${__dirname}/../.env`})
//I asume this is right as the value get returned
//but there does not say that i have to configure anything else
export const http = axios.create({
  baseURL: process.env.ROOT_API + 'api/',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': tokenType + ' ' + token
  }
})
</code>```

I expect that process.env.ROOT_API return the value as a string but in the console i see the error Uncaught SyntaxError: Unexpected token : when i see where is the problem the values is shown as

```<code>var http = __WEBPACK_IMPORTED_MODULE_5_axios___default.a.create({
  baseURL: http://localhost/project/public/ + 'api/',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': tokenType + ' ' + token
  }
});
</code>```

i have tried

using different quotes in the .env file

convert the process.env.ROOT_API to string or logging the type of the value but get erro SyntaxError: missing ) after argument list as the value seems like plain text in js.

using template literals like this ${process.env.ROOT_API}; show in console > sources '' + http://localhost/project/public/;
//i dont know how to show the ` quotes it display it like code sorry.

I do a console.log to see what process.env have in console and this is what it shows

```<code>   ...
   PWD: 'C:/xampp/htdocs/project',
   ROOT_API: 'http://localhost/erp-api/public/',
   SESSIONNAME: 'Console',
   ...
</code>```

how can i fix this? i do not understand why it not get the value as a string?

答:
Install this package as a development dependency (https://www.npmjs.com/package/dotenv-webpack):

```<code>npm install  --dev  dotenv-webpack
</code>```

or

```<code>yarn add -D dotenv-webpack
</code>```

After it, just add this code to your webpack file:

```<code>     const Dotenv = require('dotenv-webpack');

        module.exports = {
          ...
          plugins: [
            new Dotenv()
          ]
          ...
        };
</code>```

Reference Link: https://www.npmjs.com/package/dotenv-webpack

Title: Dotenv not getting value as string

Body:
I have installed dotenv to set enviroment variables for development and production, one of those variable is the ROOT_API, my env file look like this

NODE_ENV=dev
ROOT_API=http://localhost/project/public/
PORT=8000

I set my api request configuration in axios and followed the steps in the dotenv repo like this

require('dotenv').config({path: `${__dirname}/../.env`})
//I asume this is right as the value get returned
//but there does not say that i have to configure anything else
export const http = axios.create({
  baseURL: process.env.ROOT_API + 'api/',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': tokenType + ' ' + token
  }
})

I expect that process.env.ROOT_API return the value as a string but in the console i see the error Uncaught SyntaxError: Unexpected token : when i see where is the problem the values is shown as

var http = __WEBPACK_IMPORTED_MODULE_5_axios___default.a.create({
  baseURL: http://localhost/project/public/ + 'api/',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': tokenType + ' ' + token
  }
});

i have tried

using different quotes in the .env file

convert the process.env.ROOT_API to string or logging the type of the value but get erro SyntaxError: missing ) after argument list as the value seems like plain text in js.

using template literals like this ${process.env.ROOT_API}; show in console > sources '' + http://localhost/project/public/;
//i dont know how to show the ` quotes it display it like code sorry.

I do a console.log to see what process.env have in console and this is what it shows

   ...
   PWD: 'C:/xampp/htdocs/project',
   ROOT_API: 'http://localhost/erp-api/public/',
   SESSIONNAME: 'Console',
   ...

how can i fix this? i do not understand why it not get the value as a string?

Body:
Install this package as a development dependency (https://www.npmjs.com/package/dotenv-webpack):

npm install  --dev  dotenv-webpack

or

yarn add -D dotenv-webpack

After it, just add this code to your webpack file:

     const Dotenv = require('dotenv-webpack');

        module.exports = {
          ...
          plugins: [
            new Dotenv()
          ]
          ...
        };

Reference Link: https://www.npmjs.com/package/dotenv-webpack


问:
Instantiate content in resusable UIViewController
I'm creating a set of tutorial screens to introduce my App.

Previously I've had three different viewcontrollers and then loaded them into my UIPageViewController. However this is inefficient since they use the same colors and format.

That format (for reference) is here:

So I want to create three instances of this view controller and put them into an array for my UIPageViewController. I instantiate with:

```<code>UIStoryboard(name : "Main" , bundle : nil).instantiateViewController(withIdentifier: "test")
</code>```

So previously I've done this, and then created a func in the view controller to set the text

```<code>let vc = UIStoryboard(name : "Main" , bundle : nil).instantiateViewController(withIdentifier: "test")
vc.setMainText(text: "label Text")
</code>```

I want to set my view up using the storyboard so  setting up the view controller entirely programmatically is out of the question.

I'm thinking I should use an initializer for the view - So how can I use an initializer if I'm using instantiateViewController:withIdentifier?

答:
So how can I use an initializer if I'm using instantiateViewController:withIdentifier

You can't. The view controller arrives already initialized.

You could have three different instances of the same view controller class in your storyboard, each designed in its own way. That way, each identifier would give you an instance already themed as you want it.

Alternatively, you could arm your view controller class with instance properties that you can set so as to customize the theme, and set those properties on each instance after you get it from the storyboard.

Body:
I'm creating a set of tutorial screens to introduce my App.

Previously I've had three different viewcontrollers and then loaded them into my UIPageViewController. However this is inefficient since they use the same colors and format.

That format (for reference) is here:

So I want to create three instances of this view controller and put them into an array for my UIPageViewController. I instantiate with:

UIStoryboard(name : "Main" , bundle : nil).instantiateViewController(withIdentifier: "test")

So previously I've done this, and then created a func in the view controller to set the text

let vc = UIStoryboard(name : "Main" , bundle : nil).instantiateViewController(withIdentifier: "test")
vc.setMainText(text: "label Text")

I want to set my view up using the storyboard so  setting up the view controller entirely programmatically is out of the question.

I'm thinking I should use an initializer for the view - So how can I use an initializer if I'm using instantiateViewController:withIdentifier?


问:
How would I remove words from dictionary key lists that contain 6 or more letters?
I can't figure out how to create a function that is able to remove words with less than 6 characters from each list that is a value of a key of a dictionary.

I'm trying to pop each word that is less than 6 out of the list but I'm getting "TypeError: cannot unpack non-iterable int object". I don't know if the method I am using is correct.

```<code>def remove_word(words_dict):
    items_list = list(words_dict.items())

    for key, value in range(len(items_list) -1, -1, -1):
        if len(value) < 6:
            items_list.pop()
    words_dict = items_list.sort()
    return words_dict
</code>```

```<code>words_dict = {'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey',
                'zebra'],
    }
</code>```

Should print:

```<code>1.
colours : []
places : ['america', 'malaysia', 'argentina']
animals : ['monkey']
</code>```

答:
```<code># input data
words_dict = {'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey',
                'zebra'],
    }
# creating a final output dictionary

#looping through each key value pair present in dictionary and adding the key
# the final dictionary and processed valeus to the corresponding key
# using lambda function, fast readable and easy to understand
result = {k:list(filter(lambda x:len(x)>=6, v)) for k,v in words_dict.items()}
print(result)
</code>```

<p>output </p>

```<code>    {'colours': [], 'places': ['america', 'malaysia', 'argentina'], 'animals': []}
</code>```

Body:
I can't figure out how to create a function that is able to remove words with less than 6 characters from each list that is a value of a key of a dictionary.

I'm trying to pop each word that is less than 6 out of the list but I'm getting "TypeError: cannot unpack non-iterable int object". I don't know if the method I am using is correct.

def remove_word(words_dict):
    items_list = list(words_dict.items())

    for key, value in range(len(items_list) -1, -1, -1):
        if len(value) < 6:
            items_list.pop()
    words_dict = items_list.sort()
    return words_dict

words_dict = {'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey',
                'zebra'],
    }

Should print:

1.
colours : []
places : ['america', 'malaysia', 'argentina']
animals : ['monkey']

Body:
# input data
words_dict = {'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey',
                'zebra'],
    }
# creating a final output dictionary

#looping through each key value pair present in dictionary and adding the key
# the final dictionary and processed valeus to the corresponding key
# using lambda function, fast readable and easy to understand
result = {k:list(filter(lambda x:len(x)>=6, v)) for k,v in words_dict.items()}
print(result)

output

    {'colours': [], 'places': ['america', 'malaysia', 'argentina'], 'animals': []}


问:
How do I move an object in opengles using vertices?
I am wondering if there is a way to update and move a triangle in OpenGL ES using the vertices. These are the vertices of my triangle:

```<code>// in counterclockwise order :

static float triangleCoords[] = {
        0.0f,  0.622008459f, 0.0f,  // top
        -0.5f, -0.311004243f, 0.0f, // bottom left
        0.5f, -0.311004243f, 0.0f   // bottom right
};
</code>```

I wanted to know if it was possible to move the triangle without the matrices.

Thank you!

答: Yes it's possible, however it's basically pointless. The fastest way to transform vertices is with a matrix, and there happens to be specialised circuitry on the GPU to make this extremely fast. So if you want to transform and update those vertices yourself, just modify the vertex values prior to submission. It will however be far slower than transforming them in a vertex shader via a matrix. </p>

Body:
I am wondering if there is a way to update and move a triangle in OpenGL ES using the vertices. These are the vertices of my triangle:

// in counterclockwise order :

static float triangleCoords[] = {
        0.0f,  0.622008459f, 0.0f,  // top
        -0.5f, -0.311004243f, 0.0f, // bottom left
        0.5f, -0.311004243f, 0.0f   // bottom right
};

I wanted to know if it was possible to move the triangle without the matrices.

Thank you!


问:
How to avoid nested loop in a real Javascript coding test
Between two input arrays, find the same array or arrays and return them.

I just could come up with nested loop solution.

```<code>
const compareArrs = (arr1, arr2) => {
  const rtnArr = []
  for (let ar1 of arr1){
    for (let ar2 of arr2){
      if (JSON.stringify(ar1) === JSON.stringify(ar2)){
        rtnArr.push(ar1)
      }
    }
  }
  return rtnArr
}

// compare [1, 2] [3, 4] with [1, 2]
console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]))

</code>```

[[1, 2]] should be returned.

答:
Map each subarray of one argument and put it into a Set. With the other argument, iterate through it, stringifying as you go, and find the element for which the stringified array is already in the Set, for an overall complexity of O(N):

const compareArrs = (arr1, arr2) => {
  const arr1StringifiedSet = new Set(arr1.map(JSON.stringify));
  return arr2.find(
    subarr2 => arr1StringifiedSet.has(JSON.stringify(subarr2))
  );
};

console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]));```
</div>
</div>
</p>

<p>(In comparison, a nested loop has a complexity of <code>O(N^2)</code>)</p>

<p>As comment notes, if you actually need <em>all</em> matching arrays, not just the first, then use <code>.filter</code> instead of <code>.find</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const compareArrs = (arr1, arr2) => {
  const arr1StringifiedSet = new Set(arr1.map(JSON.stringify));
  return arr2.filter(
    subarr2 => arr1StringifiedSet.has(JSON.stringify(subarr2))
  );
};

console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]));</code>```

Body:
Between two input arrays, find the same array or arrays and return them.

I just could come up with nested loop solution.

const compareArrs = (arr1, arr2) => {
  const rtnArr = []
  for (let ar1 of arr1){
    for (let ar2 of arr2){
      if (JSON.stringify(ar1) === JSON.stringify(ar2)){
        rtnArr.push(ar1)
      }
    }
  }
  return rtnArr
}

// compare [1, 2] [3, 4] with [1, 2]
console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]))

[[1, 2]] should be returned.

Body:
Map each subarray of one argument and put it into a Set. With the other argument, iterate through it, stringifying as you go, and find the element for which the stringified array is already in the Set, for an overall complexity of O(N):

const compareArrs = (arr1, arr2) => {
  const arr1StringifiedSet = new Set(arr1.map(JSON.stringify));
  return arr2.find(
    subarr2 => arr1StringifiedSet.has(JSON.stringify(subarr2))
  );
};

console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]));

(In comparison, a nested loop has a complexity of O(N^2))

As comment notes, if you actually need all matching arrays, not just the first, then use .filter instead of .find:

const compareArrs = (arr1, arr2) => {
  const arr1StringifiedSet = new Set(arr1.map(JSON.stringify));
  return arr2.filter(
    subarr2 => arr1StringifiedSet.has(JSON.stringify(subarr2))
  );
};

console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]));


问:
Simple login and logout capabilities for my web app(JSF 2.0)
This morning i rode chapters 39,40 and 41 of the JEE6 tutorial. But i am very, very confused. I don't have a background on web-app security with JEE6, and i am having big difficulties to understand and implement.

I need to create an authorization mechanism for my web app, my scenario is also not very simple for a begginer in JEE6 like me so i decided to try to find the easiest way to do it.

I thought to explain my idea, so you can correct me and give me some advice on how it would be the best easiest way to do it.

Idea:

My web app uses a primefaces component called dock that pops a log in dialog when the use clicks in the last item. Also this navigation tool is located in a JSF template that is used by all the other pages in the application.

```<code>    <h:body>
<p:dock position="top">
    <p:menuitem value="Naslovna" icon="unsecuredimages/naslovna.png" url="main.xhtml"
        alt="The image could not be found." />
    <p:menuitem value="Register" icon="unsecuredimages/register.png"
        url="registration.xhtml" alt="The image could not be found." />
    <p:menuitem value="Cesta pitanja" icon="unsecuredimages/faq.png"
        url="faq.xhtml" alt="The image could not be found." />
        <!-- The login will not have a page, it will pop up a login dialog -->
    <p:menuitem value="Login" icon="unsecuredimages/login.png" url="#" onclick="dlg.show()"/>
</p:dock>
<p:dialog header="Prijavite se" widgetVar="dlg"  modal="true" draggable="false" resizable="false" effect="SLIDE">
     <h:outputText value="Em@il:" /><h:inputText id="email" value=""/>
     <br/>
     <h:outputText value="Lozinka:" /><h:inputText id="password" value=""/>
     <br/>
     <h:commandButton value="Prijavi se" />
</p:dialog>
    <br/><br/><br/><br/><br/><br/>
<ui:insert name="mainForm" />
<ui:insert name="registrationForm" />
<ui:insert name="registrationBuyerForm" />
<ui:insert name="registrationSellerForm" />
<ui:insert name="faqForm" />
<ui:insert name="registrationSuccessForm" />
  </h:body>
</code>```

That JSF i think should have a backing bean that handles the email and the password over to an EJB.

```<code>import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import ejbinterfaces.IAuthentificationEJB;
@ManagedBean
@SessionScoped
public class SecurityController {
@EJB
private IAuthentificationEJB authentificationEJB;
private String email;
private String password;

public void logIn() {
    authentificationEJB.saveUserState(email, password);
}

public String getEmail() {
    return email;
}

public String getPassword() {
    return password;
}

public void setEmail(String email) {
    this.email = email;
}

public void setPassword(String password) {
    this.password = password;
}
</code>```

}

Then the EJB should do the login and log out(This is where i get very confused):

```<code>@Stateful(name = "ejbs/AuthentificationEJB")
public class AuthentificationEJB implements IAuthentificationEJB {
//Login
public boolean saveUserState(String email,String password) {
    //1-Send query to database to see if that user exist
    //2-If the query returns the user object, store it somewhere in the session(HOW?)
    //3-return true if the user state was saved
    //4-return false otherwise
    return false;
}

//Logout
public void releaseUserState() {
    //1-Check if there is something saved in the session(or wherever the state is saved)
    //2-If 1 then flush it
}

//Check if user is logged in
public boolean checkAuthentificationStatus() {
    //1-Check if there is something saved in the session(This means the user is logged in)
    //2-If there is not a user already loged, then return false
    return false;
}
</code>```

}

I decided not to use a jdbc realm or other of the authentification mechanisms explained in the JEE6 tutorial, because i get really confused, so i think that for now it is easier for me to do it manually. This are some doubts i have about my approach:

Is this approach correct(Can it be done this way)?

Should the EJB be @Stateless or @Statefull in this case(The user retrived from the database ony has 2 String fields)?

Where should i store the id of the retrieved user from the database, to last until the user decides to logout?

If i have to store the user state in the session until he/she decides to logout, how can i do it?

With this approach will the session for the user be delated when closes the browser without logging out(If no, how can i expire his/her session automatically after a while if there is not activity?)

Ill appreciate a lot your help.

答:
Some pieces of the puzzle:

Is this approach correct(Can it be
  done this way)?

Yes it can. You can choose between container managed security or application managed.

Should the EJB be @Stateless or
  @Statefull in this case(The user
  retrived from the database ony has 2
  String fields)?

If you store the id of the currently logged in user in session context (see below), I think you can do it with a stateless bean (from theory).

Where should i store the id of the
  retrieved user from the database, to
  last until the user decides to logout?

You can store it in session context:

```<code>FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("userID", email);
</code>```

Use getSessionMap()#get("userID") in order to check the stored userID.

With this approach will the session
  for the user be delated when closes
  the browser without logging out(If no,
  how can i expire his/her session
  automatically after a while if there
  is not activity?)

No, the session will expire automatically when reaching a timeout. The timeout can be set in your web.xml:

```<code><session-config>
   <session-timeout>60</session-timeout>
</session-config>
</code>```

This setting means, that sessions will time out after 60 minutes of server inactivity.

ContentLicense: CC BY-SA 3.0

Body:
This morning i rode chapters 39,40 and 41 of the JEE6 tutorial. But i am very, very confused. I don't have a background on web-app security with JEE6, and i am having big difficulties to understand and implement.

I need to create an authorization mechanism for my web app, my scenario is also not very simple for a begginer in JEE6 like me so i decided to try to find the easiest way to do it.

I thought to explain my idea, so you can correct me and give me some advice on how it would be the best easiest way to do it.

Idea:

My web app uses a primefaces component called dock that pops a log in dialog when the use clicks in the last item. Also this navigation tool is located in a JSF template that is used by all the other pages in the application.

    <h:body>

     <h:outputText value="Em@il:" /><h:inputText id="email" value=""/>

     <h:outputText value="Lozinka:" /><h:inputText id="password" value=""/>

     <h:commandButton value="Prijavi se" />

<ui:insert name="mainForm" />
<ui:insert name="registrationForm" />
<ui:insert name="registrationBuyerForm" />
<ui:insert name="registrationSellerForm" />
<ui:insert name="faqForm" />
<ui:insert name="registrationSuccessForm" />
  </h:body>

That JSF i think should have a backing bean that handles the email and the password over to an EJB.

import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import ejbinterfaces.IAuthentificationEJB;
@ManagedBean
@SessionScoped
public class SecurityController {
@EJB
private IAuthentificationEJB authentificationEJB;
private String email;
private String password;

public void logIn() {
    authentificationEJB.saveUserState(email, password);
}

public String getEmail() {
    return email;
}

public String getPassword() {
    return password;
}

public void setEmail(String email) {
    this.email = email;
}

public void setPassword(String password) {
    this.password = password;
}

}

Then the EJB should do the login and log out(This is where i get very confused):

@Stateful(name = "ejbs/AuthentificationEJB")
public class AuthentificationEJB implements IAuthentificationEJB {
//Login
public boolean saveUserState(String email,String password) {
    //1-Send query to database to see if that user exist
    //2-If the query returns the user object, store it somewhere in the session(HOW?)
    //3-return true if the user state was saved
    //4-return false otherwise
    return false;
}

//Logout
public void releaseUserState() {
    //1-Check if there is something saved in the session(or wherever the state is saved)
    //2-If 1 then flush it
}

//Check if user is logged in
public boolean checkAuthentificationStatus() {
    //1-Check if there is something saved in the session(This means the user is logged in)
    //2-If there is not a user already loged, then return false
    return false;
}

}

I decided not to use a jdbc realm or other of the authentification mechanisms explained in the JEE6 tutorial, because i get really confused, so i think that for now it is easier for me to do it manually. This are some doubts i have about my approach:

Is this approach correct(Can it be done this way)?

Should the EJB be @Stateless or @Statefull in this case(The user retrived from the database ony has 2 String fields)?

Where should i store the id of the retrieved user from the database, to last until the user decides to logout?

If i have to store the user state in the session until he/she decides to logout, how can i do it?

With this approach will the session for the user be delated when closes the browser without logging out(If no, how can i expire his/her session automatically after a while if there is not activity?)

Ill appreciate a lot your help.

Body:
Some pieces of the puzzle:

Is this approach correct(Can it be
  done this way)?

Yes it can. You can choose between container managed security or application managed.

Should the EJB be @Stateless or
  @Statefull in this case(The user
  retrived from the database ony has 2
  String fields)?

If you store the id of the currently logged in user in session context (see below), I think you can do it with a stateless bean (from theory).

Where should i store the id of the
  retrieved user from the database, to
  last until the user decides to logout?

You can store it in session context:

FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("userID", email);

Use getSessionMap()#get("userID") in order to check the stored userID.

With this approach will the session
  for the user be delated when closes
  the browser without logging out(If no,
  how can i expire his/her session
  automatically after a while if there
  is not activity?)

No, the session will expire automatically when reaching a timeout. The timeout can be set in your web.xml:

<session-config>
   <session-timeout>60</session-timeout>
</session-config>

This setting means, that sessions will time out after 60 minutes of server inactivity.


问:
https redirect for every url doesn't work
I have an issue that came out after I have successfully transferred my website from a server to another (it's always the same url). Basically I have a forums created with xenforo that can be reached at https://forums.mywebsite.com.

Of course you can log in with your account and save username/password in the browser if needed. The problem is the following:

With https://forums.mywebsite.com you are still logged

With http://forums.mywebsite.com you have to login every time

With www.forums.mywebsite.com you have to login every time

I guess that there is an issue with the cookies, because the cookies for the https work while the others not. My idea was to redirect every single url to an https url; so:

With https://forums.mywebsite.com > no changes

With http://forums.mywebsite.com > https://forums.mywebsite.com

With www.forums.mywebsite.com > https://forums.mywebsite.com

I really need this and telling users to use only https is not a great solution because there always be someone that uses http or www. My idea was this:

```<code>RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule (.*) https://www.forums.mywebsite.com%{REQUEST_URI} [R=301,L]
</code>```

Anyway when I type www.forums.mywebsite.com I still don't get a redirect to https://forums.mywebsite.com. Do I have to change any config file?

I am editing this  .htaccess that can be found at the root of the system as you can see here (taken from WinSCP).

答:
On my Xenforo board I require the same thing, redirect everything to https://example.com without www.

This is what I use:

```<code>#Redirect www and http
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</code>```

Never had a problem with it like this.

Body:
I have an issue that came out after I have successfully transferred my website from a server to another (it's always the same url). Basically I have a forums created with xenforo that can be reached at https://forums.mywebsite.com.

Of course you can log in with your account and save username/password in the browser if needed. The problem is the following:

With https://forums.mywebsite.com you are still logged

With http://forums.mywebsite.com you have to login every time

With www.forums.mywebsite.com you have to login every time

I guess that there is an issue with the cookies, because the cookies for the https work while the others not. My idea was to redirect every single url to an https url; so:

With https://forums.mywebsite.com > no changes

With http://forums.mywebsite.com > https://forums.mywebsite.com

With www.forums.mywebsite.com > https://forums.mywebsite.com

I really need this and telling users to use only https is not a great solution because there always be someone that uses http or www. My idea was this:

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule (.*) https://www.forums.mywebsite.com%{REQUEST_URI} [R=301,L]

Anyway when I type www.forums.mywebsite.com I still don't get a redirect to https://forums.mywebsite.com. Do I have to change any config file?

I am editing this  .htaccess that can be found at the root of the system as you can see here (taken from WinSCP).

Body:
On my Xenforo board I require the same thing, redirect everything to https://example.com without www.

This is what I use:

#Redirect www and http
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Never had a problem with it like this.


问:
How to create own annotation for junit that will skip test if concrete exception was thrown during execution?
My application have several execution modes, and in 1 mode it is normal that some of my tests will throw a concrete exception. I need to annotate this methods with something like @SkipOnFail that will set method as skipped if exception was thrown.

thanks in advance!

@Edit(for my question to be more clear)

```<code>@Test(expected=ConcreteException.class)
</code>```

does not work for me because i need my tests to pass even if ConcreteException.class was not thrown(expected tag in junit will mark my test as failed if this exception won't be thrown), and to be skipped otherwise. In all other cases it should work as always.

@Solution that worked for me(junit v4.7) thx to @axtavt

```<code>@Rule
public MethodRule skipRule = new MethodRule() {
    public Statement apply(final Statement base, FrameworkMethod method, Object target) {
        if(method.getAnnotation(SkipOnFail.class) == null) return base;

        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try{
                    base.evaluate();
                } catch (ConcreteException e) {
                    Assume.assumeTrue(false);
                }
            }
        };
    }
};
</code>```

@Thx

答:
Also using the Assume class (since jUnit 4.4), you can use assumeNoException():</p>

```<code>try{
    base.evaluate();
} catch (ConcreteException e) {
    Assume.assumeNoException("Concrete exception: skipping test", e);
}
</code>```

Body:
My application have several execution modes, and in 1 mode it is normal that some of my tests will throw a concrete exception. I need to annotate this methods with something like @SkipOnFail that will set method as skipped if exception was thrown.

thanks in advance!

@Edit(for my question to be more clear)

@Test(expected=ConcreteException.class)

does not work for me because i need my tests to pass even if ConcreteException.class was not thrown(expected tag in junit will mark my test as failed if this exception won't be thrown), and to be skipped otherwise. In all other cases it should work as always.

@Solution that worked for me(junit v4.7) thx to @axtavt

@Rule
public MethodRule skipRule = new MethodRule() {
    public Statement apply(final Statement base, FrameworkMethod method, Object target) {
        if(method.getAnnotation(SkipOnFail.class) == null) return base;

        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try{
                    base.evaluate();
                } catch (ConcreteException e) {
                    Assume.assumeTrue(false);
                }
            }
        };
    }
};

@Thx

Body:
Also using the Assume class (since jUnit 4.4), you can use assumeNoException():

try{
    base.evaluate();
} catch (ConcreteException e) {
    Assume.assumeNoException("Concrete exception: skipping test", e);
}


问:
Why is my code sending the prompts to my phone, but not to anyone else who attempts to send a message to the bot?
When I send a message to the Twilio phone number from my phone, it displays the questions that I want the user to see. However, if someone else sends a message no prompts are shown to the user. This is stored in a database. At first, I thought it was because the number sending a message was not getting stored as phoneNumber, but after checking in the database it is stored as phoneNumber.

I already tried adding a Status Callback function to the code but it doesn't say anything about the status of the message.

```<code>if(body === 'x'){ //checks body to have a key phrase, it it does it creates the message
    let newMessage = new Message();
    newMessage.phoneNumber = from;
    newMessage.save(() => {
        client.messages.create({ //sends message to the patient
            to: `${from}`,
            from: `${to}`,
            body: 'What is your full name?'
        })
        .then(message => console.log(message.sid));

        res.end();
    })
}
</code>```

The expected output would be the prompt of full name if someone sends a message to the Twilio number. However, it doesn't display anything.

答:
Twilio developer evangelist here.

I can think of a couple of reasons that might be affecting you here.

First up, if you are still using a trial account then you can only send SMS messages to numbers that you have verified with your account. There are instructions for how to verify numbers with your Twilio account here. You can remove this restriction by upgrading your account.

Secondly, depending on the platform you are using, there may be a race condition between sending the message and the response ending. You call client.messages.create and handle the promise when it resolves, but your code goes straight on to end the response synchronously. It is the case with Twilio Functions and it may be on other platforms, that ending the response ends all processing and that might result in the request to send a message getting cancelled. You say you are getting messages when you try from your phone, so this may not be the issue, I just thought I'd share in case.

Let me know if that helps at all.

Body:
When I send a message to the Twilio phone number from my phone, it displays the questions that I want the user to see. However, if someone else sends a message no prompts are shown to the user. This is stored in a database. At first, I thought it was because the number sending a message was not getting stored as phoneNumber, but after checking in the database it is stored as phoneNumber.

I already tried adding a Status Callback function to the code but it doesn't say anything about the status of the message.

if(body === 'x'){ //checks body to have a key phrase, it it does it creates the message
    let newMessage = new Message();
    newMessage.phoneNumber = from;
    newMessage.save(() => {
        client.messages.create({ //sends message to the patient
            to: `${from}`,
            from: `${to}`,
            body: 'What is your full name?'
        })
        .then(message => console.log(message.sid));

        res.end();
    })
}

The expected output would be the prompt of full name if someone sends a message to the Twilio number. However, it doesn't display anything.


问:
Can only be rectangular objects stored in pygame.sprite.Group
Because it has a method known as draw. Which considers the text attribute of the sprite so we can store surfaces , images and rectangles .But what if we want to store the circle sprite which requires position and radius to be drawn</p>

答:
A sprite is an image; images happen to have rectangular shape because that's a natural consequence of the way they are represented.

If you want to draw a circle, you have two options: you can draw an image of the circle, which would be a sprite that you position like any other sprite, using its corner as its reference point; or you can draw an actual circle, where a sprite library would not be a huge help.


问:
C++ Create fixed size queue
In C++, how do you create a simple fixed size queue?

I have done it multiple times in Java and Python but am looking for a C++ based way of doing so.

I need a simple FIFO queue with only 2 elements in order to use the push and pop utilities: I am already aware of the fact that I could implement my own class to perform this kind of restriction but my question aims to know if there exist any already available solution to this.

Or is it maybe possible to accomplish the same task with an array? That would work as well.

答:
You could inherit from queue, and then reimplement the push method. Here is a basic example.

```<code>#include <queue>
#include <deque>
#include <iostream>

template <typename T, int MaxLen, typename Container=std::deque<T>>
class FixedQueue : public std::queue<T, Container> {
public:
    void push(const T& value) {
        if (this->size() == MaxLen) {
           this->c.pop_front();
        }
        std::queue<T, Container>::push(value);
    }
};

int main() {
    FixedQueue<int, 3> q;
    q.push(1);
    q.push(2);
    q.push(3);
    q.push(4);
    q.push(5);
    q.push(6);
    q.push(7);

    while (q.size() > 0)
    {
        std::cout << q.front() << std::endl;
        q.pop();
    }
}
</code>```

This will print

```<code>$ g++ fixedqueue.cpp -std=c++17 -o fixedqueue && ./fixedqueue
5
6
7
</code>```

Title: C++ Create fixed size queue

Body:
You could inherit from queue, and then reimplement the push method. Here is a basic example.

#include <queue>
#include <deque>
#include <iostream>

template <typename T, int MaxLen, typename Container=std::deque<T>>
class FixedQueue : public std::queue<T, Container> {
public:
    void push(const T& value) {
        if (this->size() == MaxLen) {
           this->c.pop_front();
        }
        std::queue<T, Container>::push(value);
    }
};

int main() {
    FixedQueue<int, 3> q;
    q.push(1);
    q.push(2);
    q.push(3);
    q.push(4);
    q.push(5);
    q.push(6);
    q.push(7);

    while (q.size() > 0)
    {
        std::cout << q.front() << std::endl;
        q.pop();
    }
}

This will print

$ g++ fixedqueue.cpp -std=c++17 -o fixedqueue && ./fixedqueue
5
6
7


问:
Algorithm for finding a formula that connects inputs and outputs
I seem to recall having learned a method for finding the formula that connects inputs and outputs from a table. For example:

```<code>a b c | r
1 1 0 | 0
0 1 1 | 1
1 1 1 | 1
</code>```

where "r" is the result, and a, b and c are the inputs. The method involved equations with many unknowns and ended up with a formula that explained it all. (This is an example that is not that meaningful, since r = c, but you get the idea).

However, I can not remember the details, and not enough keywords to be able to find it on the web. The subject teaching this method also included a lot of boolean algebra.

I know this is a vague question, but what could this method for finding the formula from a table of values be?

答:
There are disjunctive and conjuctive normalform. Depending on which you want you can build them from the (complete) logic tables by building terms for the 0 or 1 results by ors or ands and combining these terms with ands and ors (and the others match to 1 or 0). It sounds here more complex at it is. Wiki/Google will give you some examples when you look for conjunctive or disjunctive normalform.

EDIT: Here is the example from the wiki for both forms (DNF = disjunctive normal form, KNF = conjunctive normal form):

Body:
I seem to recall having learned a method for finding the formula that connects inputs and outputs from a table. For example:

a b c | r
1 1 0 | 0
0 1 1 | 1
1 1 1 | 1

where "r" is the result, and a, b and c are the inputs. The method involved equations with many unknowns and ended up with a formula that explained it all. (This is an example that is not that meaningful, since r = c, but you get the idea).

However, I can not remember the details, and not enough keywords to be able to find it on the web. The subject teaching this method also included a lot of boolean algebra.

I know this is a vague question, but what could this method for finding the formula from a table of values be?


问:
How to get a product from woocommerce using custom meta value
I am trying to get specific product using meta key value. Any help would be highly appreciated.
I am trying to display a specific product when the product code is passed via a shortcode.

I have setup metabox and confirmed that the items have custom meta values with key "neproductinfo-ne_item_code"

        $atts = shortcode_atts(
            array(
                'itemcode'  => '',
            ),
            $atts, 'products_catalog'
        );

        $woocommerce_loop['columns'] = 1;

        $meta_query_args = array(
            array(
                'key' => 'neproductinfo-ne_item_code',
                'value' => $atts['itemcode'],
                'compare'   => '='
            )
        );
        $meta_query = new WP_Meta_Query( $meta_query_args );

        $products = new WP_Query( array (
            'post_type'         => 'product',
            'post_status'       => 'publish',
            //'posts_per_page'    => 1,
            'meta_query'        => $meta_query
        ));
```

I am getting list of all products regardless of any itemcode passed through shortcode

shortcode example
[products_catalog itemcode='1001']

答:
No if condition found where you are checking the attribute value exists or not.
Based on existence of attribute value, you need to pass meta query. If there is no value then y you passs the meta_query to WP_Query ?

Body:
I am trying to get specific product using meta key value. Any help would be highly appreciated.
I am trying to display a specific product when the product code is passed via a shortcode.

I have setup metabox and confirmed that the items have custom meta values with key "neproductinfo-ne_item_code"

        $atts = shortcode_atts(
            array(
                'itemcode'  => '',
            ),
            $atts, 'products_catalog'
        );

        $woocommerce_loop['columns'] = 1;

        $meta_query_args = array(
            array(
                'key' => 'neproductinfo-ne_item_code',
                'value' => $atts['itemcode'],
                'compare'   => '='
            )
        );
        $meta_query = new WP_Meta_Query( $meta_query_args );

        $products = new WP_Query( array (
            'post_type'         => 'product',
            'post_status'       => 'publish',
            //'posts_per_page'    => 1,
            'meta_query'        => $meta_query
        ));

I am getting list of all products regardless of any itemcode passed through shortcode

shortcode example
[products_catalog itemcode='1001']


问:
"declaration has no storage class or type specifier" in C++
I'm learning C++ through the book (5th Edition),today I encounter a problem when doing the exercise 12.6.

The code is shown below, the error is this declaration has no storage class or type specifier. But the program can run normally. The error locates at the last line on '}'.

```<code>#include<iostream>
#include<vector>
#include<new>

using namespace std;

vector<int>* func(){
    return new vector<int>();
}

void read_vec(istream &in, vector<int>* vp){
    int i;
    while(in>>i)
        vp->push_back(i);
}

void print_vec(vector<int>* vp){
    for(int i:*vp)
        cout<<i<<" ";
    cout<<endl;
}

int main(){
    auto vec = func();
    cout<<"Enter a sequence of integers"<<endl;
    read_vec(cin,vec);
    print_vec(vec);
    delete vec;
    vec = nullptr;

    system("pause");
}
</code>```

I have searched the message, but still cannot figure out where my code is wrong.

I would be appreciative for all hints.

答:
You need the standard library header <cstdlib> to use system.

Add

```<code>#include <cstdlib>
</code>```

at the top of the file. Then, use std::system instead of just system.

```<code>std::system("pause");
</code>```

Body:
I'm learning C++ through the book (5th Edition),today I encounter a problem when doing the exercise 12.6.

The code is shown below, the error is this declaration has no storage class or type specifier. But the program can run normally. The error locates at the last line on '}'.

#include<iostream>
#include<vector>
#include<new>

using namespace std;

vector<int>* func(){
    return new vector<int>();
}

void read_vec(istream &in, vector<int>* vp){
    int i;
    while(in>>i)
        vp->push_back(i);
}

void print_vec(vector<int>* vp){
    for(int i:*vp)
        cout<<i<<" ";
    cout<<endl;
}

int main(){
    auto vec = func();
    cout<<"Enter a sequence of integers"<<endl;
    read_vec(cin,vec);
    print_vec(vec);
    delete vec;
    vec = nullptr;

    system("pause");
}

I have searched the message, but still cannot figure out where my code is wrong.

I would be appreciative for all hints.

Body:
You need the standard library header <cstdlib> to use system.

Add

#include <cstdlib>

at the top of the file. Then, use std::system instead of just system.

std::system("pause");


问:
Making CIContext.render(CIImage, CVPixelBuffer) work with AVAssetWriter
I want to use Core Image for processing a bunch of CGImage objects and turning them into a QuickTime movie on macOS. The following code demonstrates what's needed, but the output contains a lot of blank (black) frames:

import AppKit
import AVFoundation
import CoreGraphics
import Foundation
import CoreVideo
import Metal

// Video output url.
let url: URL = try! FileManager.default.url(for: .downloadsDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("av.mov")
try? FileManager.default.removeItem(at: url)

// Video frame size, total frame count, frame rate and frame image.
let frameSize: CGSize = CGSize(width: 2000, height: 1000)
let frameCount: Int = 100
let frameRate: Double = 1 / 30
let frameImage: CGImage

frameImage = NSImage(size: frameSize, flipped: false, drawingHandler: {
    NSColor.red.setFill()
    $0.fill()
    return true
}).cgImage(forProposedRect: nil, context: nil, hints: nil)!

let pixelBufferAttributes: [CFString: Any]
let outputSettings: [String: Any]

pixelBufferAttributes = [
    kCVPixelBufferPixelFormatTypeKey: Int(kCVPixelFormatType_32ARGB),
    kCVPixelBufferWidthKey: Float(frameSize.width),
    kCVPixelBufferHeightKey: Float(frameSize.height),
    kCVPixelBufferMetalCompatibilityKey: true,
    kCVPixelBufferCGImageCompatibilityKey: true,
    kCVPixelBufferCGBitmapContextCompatibilityKey: true,
]

outputSettings = [
    AVVideoCodecKey: AVVideoCodecType.h264,
    AVVideoWidthKey: Int(frameSize.width),
    AVVideoHeightKey: Int(frameSize.height),
]

let writer: AVAssetWriter = try! AVAssetWriter(outputURL: url, fileType: .mov)
let input: AVAssetWriterInput = AVAssetWriterInput(mediaType: .video, outputSettings: outputSettings)
let pixelBufferAdaptor: AVAssetWriterInputPixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: pixelBufferAttributes as [String: Any])

input.expectsMediaDataInRealTime = true

precondition(writer.canAdd(input))
writer.add(input)

precondition(writer.startWriting())
writer.startSession(atSourceTime: CMTime.zero)

let colorSpace: CGColorSpace = CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB()
let context = CIContext(mtlDevice: MTLCreateSystemDefaultDevice()!)

Swift.print("Starting the render…")

// Preferred scenario: using CoreImage to fill the buffer from the pixel buffer adapter. Shows that
// CIImage + AVAssetWriterInputPixelBufferAdaptor are not working together.

for frameNumber in 0 ..< frameCount {
    var pixelBuffer: CVPixelBuffer?
    guard let pixelBufferPool: CVPixelBufferPool = pixelBufferAdaptor.pixelBufferPool else { preconditionFailure() }
    precondition(CVPixelBufferPoolCreatePixelBuffer(nil, pixelBufferPool, &pixelBuffer) == kCVReturnSuccess)

    precondition(CVPixelBufferLockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess)
    defer { precondition(CVPixelBufferUnlockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess) }

    let ciImage = CIImage(cgImage: frameImage)
    context.render(ciImage, to: pixelBuffer!)

    //  This fails – the pixel buffer doesn't get filled. AT ALL! Why? How to make it work?
    let bytes = UnsafeBufferPointer(start: CVPixelBufferGetBaseAddress(pixelBuffer!)!.assumingMemoryBound(to: UInt8.self), count: CVPixelBufferGetDataSize(pixelBuffer!))
    precondition(bytes.contains(where: { $0 != 0 }))

    while !input.isReadyForMoreMediaData { Thread.sleep(forTimeInterval: 10 / 1000) }
    precondition(pixelBufferAdaptor.append(pixelBuffer!, withPresentationTime: CMTime(seconds: Double(frameNumber) * frameRate, preferredTimescale: 600)))
}

// Unpreferred scenario: using CoreImage to fill the manually created buffer. Proves that CIImage
// can fill buffer and working.

// for frameNumber in 0 ..< frameCount {
//     var pixelBuffer: CVPixelBuffer?
//     precondition(CVPixelBufferCreate(nil, frameImage.width, frameImage.height, kCVPixelFormatType_32ARGB, pixelBufferAttributes as CFDictionary, &pixelBuffer) == kCVReturnSuccess)
//
//     precondition(CVPixelBufferLockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess)
//     defer { precondition(CVPixelBufferUnlockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess) }
//
//     let ciImage = CIImage(cgImage: frameImage)
//     context.render(ciImage, to: pixelBuffer!)
//
//     // ✅ This passes.
//     let bytes = UnsafeBufferPointer(start: CVPixelBufferGetBaseAddress(pixelBuffer!)!.assumingMemoryBound(to: UInt8.self), count: CVPixelBufferGetDataSize(pixelBuffer!))
//     precondition(bytes.contains(where: { $0 != 0 }))
//
//     while !input.isReadyForMoreMediaData { Thread.sleep(forTimeInterval: 10 / 1000) }
//     precondition(pixelBufferAdaptor.append(pixelBuffer!, withPresentationTime: CMTime(seconds: Double(frameNumber) * frameRate, preferredTimescale: 600)))
// }

// Unpreferred scenario: using CoreGraphics to fill the buffer from the pixel buffer adapter. Shows that
// buffer from pixel buffer adapter can be filled and working.

// for frameNumber in 0 ..< frameCount {
//     var pixelBuffer: CVPixelBuffer?
//     guard let pixelBufferPool: CVPixelBufferPool = pixelBufferAdaptor.pixelBufferPool else { preconditionFailure() }
//     precondition(CVPixelBufferPoolCreatePixelBuffer(nil, pixelBufferPool, &pixelBuffer) == kCVReturnSuccess)
//
//     precondition(CVPixelBufferLockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess)
//     defer { precondition(CVPixelBufferUnlockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess) }
//
//     guard let context: CGContext = CGContext(data: CVPixelBufferGetBaseAddress(pixelBuffer!), width: frameImage.width, height: frameImage.height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) else { preconditionFailure() }
//     context.clear(CGRect(origin: .zero, size: frameSize))
//     context.draw(frameImage, in: CGRect(origin: .zero, size: frameSize))
//
//     // ✅ This passes.
//     let bytes = UnsafeBufferPointer(start: CVPixelBufferGetBaseAddress(pixelBuffer!)!.assumingMemoryBound(to: UInt8.self), count: CVPixelBufferGetDataSize(pixelBuffer!))
//     precondition(bytes.contains(where: { $0 != 0 }))
//
//     while !input.isReadyForMoreMediaData { Thread.sleep(forTimeInterval: 10 / 1000) }
//     precondition(pixelBufferAdaptor.append(pixelBuffer!, withPresentationTime: CMTime(seconds: Double(frameNumber) * frameRate, preferredTimescale: 600)))
// }

let semaphore = DispatchSemaphore(value: 0)

input.markAsFinished()
writer.endSession(atSourceTime: CMTime(seconds: Double(frameCount) * frameRate, preferredTimescale: 600))
writer.finishWriting(completionHandler: { semaphore.signal() })

semaphore.wait()

Swift.print("Successfully finished rendering to \(url.path)")
```

The following, however, works with CGContext, but I need CIContext in order to make use of GPU. The problem seems to be with pixel buffers provided by the AVAssetWriterInputPixelBufferAdaptor's buffer pool. Rendering CIContext into individually created buffers and appending them to the adapter works, but is highly inefficient. Rendering CIContext into buffers provided by the adapter's pool results in no data being written into buffer at all, it literally contains all zeroes as if two are incompatible! However, rendering using CGImage works, so as copying the data manually.

The main observation is that CIContext.render appears to work asynchronously or something goes wrong between the buffer getting filled and data being written into the video stream. In other words there's no data in the buffer when it gets flushed. The following is kind of pointing in that direction:

Removing buffer locking results in almost all frames being written, except for the first few, the above code actually produces a correct output, but with the actual data the behaviour is as described.

Using a different codec, like ProRes422, results in almost all frames being written correctly, with just a few blanks – also the above code produces correct output, but larger and complex images result in skipped frames.

What's wrong with this code and what's the right way to do it?

P.S. Most iOS examples use pretty much the same implementation and seem to work perfectly fine. I found a hint that it might differ for macOS, but can't see any official documentation on this.

答:
After speaking with Apple Developer Technical Support it appears that:

Core Image defers the rendering until the client requests the access to the frame buffer, i.e. CVPixelBufferLockBaseAddress.

So, the solution is simply to do CVPixelBufferLockBaseAddress after calling CIContext.render as shown below:

for frameNumber in 0 ..< frameCount {
    var pixelBuffer: CVPixelBuffer?
    guard let pixelBufferPool: CVPixelBufferPool = pixelBufferAdaptor.pixelBufferPool else { preconditionFailure() }
    precondition(CVPixelBufferPoolCreatePixelBuffer(nil, pixelBufferPool, &pixelBuffer) == kCVReturnSuccess)

    let ciImage = CIImage(cgImage: frameImage)
    context.render(ciImage, to: pixelBuffer!)

    precondition(CVPixelBufferLockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess)
    defer { precondition(CVPixelBufferUnlockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess) }

    let bytes = UnsafeBufferPointer(start: CVPixelBufferGetBaseAddress(pixelBuffer!)!.assumingMemoryBound(to: UInt8.self), count: CVPixelBufferGetDataSize(pixelBuffer!))
    precondition(bytes.contains(where: { $0 != 0 }))

    while !input.isReadyForMoreMediaData { Thread.sleep(forTimeInterval: 10 / 1000) }
    precondition(pixelBufferAdaptor.append(pixelBuffer!, withPresentationTime: CMTime(seconds: Double(frameNumber) * frameRate, preferredTimescale: 600)))
}
```

Body:
I want to use Core Image for processing a bunch of CGImage objects and turning them into a QuickTime movie on macOS. The following code demonstrates what's needed, but the output contains a lot of blank (black) frames:

import AppKit
import AVFoundation
import CoreGraphics
import Foundation
import CoreVideo
import Metal

// Video output url.
let url: URL = try! FileManager.default.url(for: .downloadsDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("av.mov")
try? FileManager.default.removeItem(at: url)

// Video frame size, total frame count, frame rate and frame image.
let frameSize: CGSize = CGSize(width: 2000, height: 1000)
let frameCount: Int = 100
let frameRate: Double = 1 / 30
let frameImage: CGImage

frameImage = NSImage(size: frameSize, flipped: false, drawingHandler: {
    NSColor.red.setFill()
    $0.fill()
    return true
}).cgImage(forProposedRect: nil, context: nil, hints: nil)!

let pixelBufferAttributes: [CFString: Any]
let outputSettings: [String: Any]

pixelBufferAttributes = [
    kCVPixelBufferPixelFormatTypeKey: Int(kCVPixelFormatType_32ARGB),
    kCVPixelBufferWidthKey: Float(frameSize.width),
    kCVPixelBufferHeightKey: Float(frameSize.height),
    kCVPixelBufferMetalCompatibilityKey: true,
    kCVPixelBufferCGImageCompatibilityKey: true,
    kCVPixelBufferCGBitmapContextCompatibilityKey: true,
]

outputSettings = [
    AVVideoCodecKey: AVVideoCodecType.h264,
    AVVideoWidthKey: Int(frameSize.width),
    AVVideoHeightKey: Int(frameSize.height),
]

let writer: AVAssetWriter = try! AVAssetWriter(outputURL: url, fileType: .mov)
let input: AVAssetWriterInput = AVAssetWriterInput(mediaType: .video, outputSettings: outputSettings)
let pixelBufferAdaptor: AVAssetWriterInputPixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: pixelBufferAttributes as [String: Any])

input.expectsMediaDataInRealTime = true

precondition(writer.canAdd(input))
writer.add(input)

precondition(writer.startWriting())
writer.startSession(atSourceTime: CMTime.zero)

let colorSpace: CGColorSpace = CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB()
let context = CIContext(mtlDevice: MTLCreateSystemDefaultDevice()!)

Swift.print("Starting the render…")

// Preferred scenario: using CoreImage to fill the buffer from the pixel buffer adapter. Shows that
// CIImage + AVAssetWriterInputPixelBufferAdaptor are not working together.

for frameNumber in 0 ..< frameCount {
    var pixelBuffer: CVPixelBuffer?
    guard let pixelBufferPool: CVPixelBufferPool = pixelBufferAdaptor.pixelBufferPool else { preconditionFailure() }
    precondition(CVPixelBufferPoolCreatePixelBuffer(nil, pixelBufferPool, &pixelBuffer) == kCVReturnSuccess)

    precondition(CVPixelBufferLockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess)
    defer { precondition(CVPixelBufferUnlockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess) }

    let ciImage = CIImage(cgImage: frameImage)
    context.render(ciImage, to: pixelBuffer!)

    //  This fails – the pixel buffer doesn't get filled. AT ALL! Why? How to make it work?
    let bytes = UnsafeBufferPointer(start: CVPixelBufferGetBaseAddress(pixelBuffer!)!.assumingMemoryBound(to: UInt8.self), count: CVPixelBufferGetDataSize(pixelBuffer!))
    precondition(bytes.contains(where: { $0 != 0 }))

    while !input.isReadyForMoreMediaData { Thread.sleep(forTimeInterval: 10 / 1000) }
    precondition(pixelBufferAdaptor.append(pixelBuffer!, withPresentationTime: CMTime(seconds: Double(frameNumber) * frameRate, preferredTimescale: 600)))
}

// Unpreferred scenario: using CoreImage to fill the manually created buffer. Proves that CIImage
// can fill buffer and working.

// for frameNumber in 0 ..< frameCount {
//     var pixelBuffer: CVPixelBuffer?
//     precondition(CVPixelBufferCreate(nil, frameImage.width, frameImage.height, kCVPixelFormatType_32ARGB, pixelBufferAttributes as CFDictionary, &pixelBuffer) == kCVReturnSuccess)
//
//     precondition(CVPixelBufferLockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess)
//     defer { precondition(CVPixelBufferUnlockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess) }
//
//     let ciImage = CIImage(cgImage: frameImage)
//     context.render(ciImage, to: pixelBuffer!)
//
//     // ✅ This passes.
//     let bytes = UnsafeBufferPointer(start: CVPixelBufferGetBaseAddress(pixelBuffer!)!.assumingMemoryBound(to: UInt8.self), count: CVPixelBufferGetDataSize(pixelBuffer!))
//     precondition(bytes.contains(where: { $0 != 0 }))
//
//     while !input.isReadyForMoreMediaData { Thread.sleep(forTimeInterval: 10 / 1000) }
//     precondition(pixelBufferAdaptor.append(pixelBuffer!, withPresentationTime: CMTime(seconds: Double(frameNumber) * frameRate, preferredTimescale: 600)))
// }

// Unpreferred scenario: using CoreGraphics to fill the buffer from the pixel buffer adapter. Shows that
// buffer from pixel buffer adapter can be filled and working.

// for frameNumber in 0 ..< frameCount {
//     var pixelBuffer: CVPixelBuffer?
//     guard let pixelBufferPool: CVPixelBufferPool = pixelBufferAdaptor.pixelBufferPool else { preconditionFailure() }
//     precondition(CVPixelBufferPoolCreatePixelBuffer(nil, pixelBufferPool, &pixelBuffer) == kCVReturnSuccess)
//
//     precondition(CVPixelBufferLockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess)
//     defer { precondition(CVPixelBufferUnlockBaseAddress(pixelBuffer!, []) == kCVReturnSuccess) }
//
//     guard let context: CGContext = CGContext(data: CVPixelBufferGetBaseAddress(pixelBuffer!), width: frameImage.width, height: frameImage.height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) else { preconditionFailure() }
//     context.clear(CGRect(origin: .zero, size: frameSize))
//     context.draw(frameImage, in: CGRect(origin: .zero, size: frameSize))
//
//     // ✅ This passes.
//     let bytes = UnsafeBufferPointer(start: CVPixelBufferGetBaseAddress(pixelBuffer!)!.assumingMemoryBound(to: UInt8.self), count: CVPixelBufferGetDataSize(pixelBuffer!))
//     precondition(bytes.contains(where: { $0 != 0 }))
//
//     while !input.isReadyForMoreMediaData { Thread.sleep(forTimeInterval: 10 / 1000) }
//     precondition(pixelBufferAdaptor.append(pixelBuffer!, withPresentationTime: CMTime(seconds: Double(frameNumber) * frameRate, preferredTimescale: 600)))
// }

let semaphore = DispatchSemaphore(value: 0)

input.markAsFinished()
writer.endSession(atSourceTime: CMTime(seconds: Double(frameCount) * frameRate, preferredTimescale: 600))
writer.finishWriting(completionHandler: { semaphore.signal() })

semaphore.wait()

Swift.print("Successfully finished rendering to \(url.path)")

The following, however, works with CGContext, but I need CIContext in order to make use of GPU. The problem seems to be with pixel buffers provided by the AVAssetWriterInputPixelBufferAdaptor's buffer pool. Rendering CIContext into individually created buffers and appending them to the adapter works, but is highly inefficient. Rendering CIContext into buffers provided by the adapter's pool results in no data being written into buffer at all, it literally contains all zeroes as if two are incompatible! However, rendering using CGImage works, so as copying the data manually.

The main observation is that CIContext.render appears to work asynchronously or something goes wrong between the buffer getting filled and data being written into the video stream. In other words there's no data in the buffer when it gets flushed. The following is kind of pointing in that direction:

Removing buffer locking results in almost all frames being written, except for the first few, the above code actually produces a correct output, but with the actual data the behaviour is as described.

Using a different codec, like ProRes422, results in almost all frames being written correctly, with just a few blanks – also the above code produces correct output, but larger and complex images result in skipped frames.

What's wrong with this code and what's the right way to do it?

P.S. Most iOS examples use pretty much the same implementation and seem to work perfectly fine. I found a hint that it might differ for macOS, but can't see any official documentation on this.


问:
How can I remove animate of the header when I move the next screen?
I am using react-navigation. I set headerBackground of the option because I want to achieve gradient of the header. But it will appear white of flicker when I move the next screen, I guess this is the reason for the animation. I am trying to configuration transitionConfig but it not work. This is my navigationOptions:

```<code>headerBackground: (
      <Image
        style={{height: setHeight(58), width: setWidth(375), resizeMode: 'stretch'}}
        source={require('./assets/images/top-bg.jpg')}
      />
),
transitionConfig: () => ({
    screenInterpolator: StackViewStyleInterpolator.forHorizontal,
    transitionSpec: {
      duration: 0,
      timing: Animated.timing,
      easing: Easing.step0
    }
})
</code>```

enter link view renderings here

How can I remove animate of the header when I move the next screen? Thanks!

答: All animations are handled in CSS, and it seems like the stackViewStyleInterpolator.forHorizontal is the tag responsible here. I would look in my CSS for something that resembles that, or use the inspector to tell you where exactly that element is being acted upon and then edit the CSS directly.</p>

Body:
I am using react-navigation. I set headerBackground of the option because I want to achieve gradient of the header. But it will appear white of flicker when I move the next screen, I guess this is the reason for the animation. I am trying to configuration transitionConfig but it not work. This is my navigationOptions:

headerBackground: (
      <Image
        style={{height: setHeight(58), width: setWidth(375), resizeMode: 'stretch'}}
        source={require('./assets/images/top-bg.jpg')}
      />
),
transitionConfig: () => ({
    screenInterpolator: StackViewStyleInterpolator.forHorizontal,
    transitionSpec: {
      duration: 0,
      timing: Animated.timing,
      easing: Easing.step0
    }
})

enter link view renderings here

How can I remove animate of the header when I move the next screen? Thanks!


问:
Having problems with writing a method to find the index of the biggest integer in my ArrayList
I am having problems in creating a method that will find the index of the biggest integer.

I have tried creating plenty of methods but I was only recently introduced to finding the index of a value in a list, and I still am unable to find the best, let alone a working way. By index I assumed that it is the position of the value within the list given (please correct me if I am wrong).

My Current Code:

```<code>import java.util.ArrayList;
import java.util.Scanner;

public class FindBiggest2 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    ArrayList<Integer> integerList = new ArrayList<Integer>();

    System.out.println("Enter any amount integers (0 to stop): ");

    int integer = input.nextInt();
    while(integer != 0) {
        integerList.add(integer);
        integer = input.nextInt();
    }
    input.close();
    if(integerList.size() == 0) {
        System.out.println("list is empty");
        return;
    }
     System.out.println("\nThe integers entered are: ");
    // displaying ids
    for(int i=0; i<integerList.size(); i++)
        System.out.print(integerList.get(i)+" ");
        System.out.println();

    // finding biggest id
    int bInt = integerList.get(0); // initializing bid id with first element
    for(int i=1; i<integerList.size(); i++)
        if(bInt < integerList.get(i))
        bInt = integerList.get(i);

    System.out.println("The biggest integer in the array is: "+ bInt);
    }

}
</code>```

My current output (Example):

```<code>Enter any amount of integers (0 to stop):
1
2
3
4
5
6
0

The integers entered are:
1 2 3 4 5 6
The biggest integer in the array is: 6
</code>```

These are my requirements of my output:

The output of the program should firstly display all integers, and then
indicate the biggest integer among them as well as the index of the biggest integer in the 1D
array.

答:
I am having problems in creating a method that will find the index of
  the biggest integer.

In the same way that you are storing the largest value, also store the value of "i" in a separate variable:

```<code>// finding biggest id AND the index where it was found
int index = 0;
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++) {
    if(bInt < integerList.get(i)) {
        bInt = integerList.get(i);
        index = i;
    }
}
System.out.println("The biggest integer in the array is: "+ bInt);
System.out.println("It was found at Index: "+ index);
</code>```

Body:
I am having problems in creating a method that will find the index of the biggest integer.

I have tried creating plenty of methods but I was only recently introduced to finding the index of a value in a list, and I still am unable to find the best, let alone a working way. By index I assumed that it is the position of the value within the list given (please correct me if I am wrong).

My Current Code:

import java.util.ArrayList;
import java.util.Scanner;

public class FindBiggest2 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    ArrayList<Integer> integerList = new ArrayList<Integer>();

    System.out.println("Enter any amount integers (0 to stop): ");

    int integer = input.nextInt();
    while(integer != 0) {
        integerList.add(integer);
        integer = input.nextInt();
    }
    input.close();
    if(integerList.size() == 0) {
        System.out.println("list is empty");
        return;
    }
     System.out.println("\nThe integers entered are: ");
    // displaying ids
    for(int i=0; i<integerList.size(); i++)
        System.out.print(integerList.get(i)+" ");
        System.out.println();

    // finding biggest id
    int bInt = integerList.get(0); // initializing bid id with first element
    for(int i=1; i<integerList.size(); i++)
        if(bInt < integerList.get(i))
        bInt = integerList.get(i);

    System.out.println("The biggest integer in the array is: "+ bInt);
    }

}

My current output (Example):

Enter any amount of integers (0 to stop):
1
2
3
4
5
6
0

The integers entered are:
1 2 3 4 5 6
The biggest integer in the array is: 6

These are my requirements of my output:

The output of the program should firstly display all integers, and then
indicate the biggest integer among them as well as the index of the biggest integer in the 1D
array.

Body:
I am having problems in creating a method that will find the index of
  the biggest integer.

In the same way that you are storing the largest value, also store the value of "i" in a separate variable:

// finding biggest id AND the index where it was found
int index = 0;
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++) {
    if(bInt < integerList.get(i)) {
        bInt = integerList.get(i);
        index = i;
    }
}
System.out.println("The biggest integer in the array is: "+ bInt);
System.out.println("It was found at Index: "+ index);


问:
How to add letter to the beginning of each string element of the array?
I have array with string elements.

```<code>val phoneNumbers = "7774589658,7056589658"
val arr = phoneNumbers.split(",")
</code>```

My question is how to add letter to the beginning of each element of the array. For example:

```<code>[ "A7774589658", "A7056589658"]
</code>```

I tried such code but it add letter to the end of each element of the array.

```<code>val result = arr.indices.foreach(arr(_) += "A")
</code>```

答:
You can do it using map

```<code>val result = arr.map("A"+_)
</code>```

Body:
I have array with string elements.

val phoneNumbers = "7774589658,7056589658"
val arr = phoneNumbers.split(",")

My question is how to add letter to the beginning of each element of the array. For example:

[ "A7774589658", "A7056589658"]

I tried such code but it add letter to the end of each element of the array.

val result = arr.indices.foreach(arr(_) += "A")

Body:
You can do it using map

val result = arr.map("A"+_)


问:
Control Screen with Python
is there a way to control the screen/monitor with python, like for example turn it off an on again (comparable to the shortcut-buttons on laptop keyboards)?

Thank you!

答:
In python</p>

```<code>    import win32gui
    import win32con

    #to turn off use :-
    win32gui.SendMessage(win32con.HWND_BROADCAST,
                     win32con.WM_SYSCOMMAND, win32con.SC_MONITORPOWER, 2)
    #turn on use :-
    win32gui.SendMessage(win32con.HWND_BROADCAST,
                     win32con.WM_SYSCOMMAND, win32con.SC_MONITORPOWER, -1)
</code>```

Title: Control Screen with Python

Body:
In python

    import win32gui
    import win32con

    #to turn off use :-
    win32gui.SendMessage(win32con.HWND_BROADCAST,
                     win32con.WM_SYSCOMMAND, win32con.SC_MONITORPOWER, 2)
    #turn on use :-
    win32gui.SendMessage(win32con.HWND_BROADCAST,
                     win32con.WM_SYSCOMMAND, win32con.SC_MONITORPOWER, -1)


问:
How does spring boot find the path of the META-INF/spring.factories
I am learning how spring boot auto-configuration works and I have known that spring boot can scan all jars to find the files named META-INF/spring.factories.

But I am confused about how does the spring boot decide the path to scan.

It scans all .jars in the maven repository or somewhere else？

I can‘t find the detail in the source code，can anyone help me figure it out?

答:
It definitely will not scan the whole maven repository. Instead ,it scans from the class-path only which the paths are normally specified when the application starts.

For the source codes , you can refer to SpringFactoriesLoader.loadSpringFactories()


问:
CloudFormation stack "sls-dev",

serverless deploy

Error :
 The serverless deployment bucket "sls-dev-serverlessdeploymentbucket-b27t7pcj7wgb" does not exist. Create it manually if you want to reuse the CloudFormation stack "sls-dev", or delete the stack if it is no longer required.

答:
If you have defined the bucket name it will consider the bucket should exist. Does not seem to be your case since you have this strange name.

You may have delete part of your stack manually and now it is not matching. Delete the stack through the cloudformation or serverless command and then deploy it again. This will create your stack as opposed of updating it.

I also suggest you to defined a better name for your "service", SLS is not very intuitive.

Title: CloudFormation stack "sls-dev",


问:
How to add a scheduler job after last job is over
I know that apscheduler was able to do schedule jobs with:

```<code>scheduler = BackgroundScheduler()
scheduler.add_job(run, 'interval', seconds=60)
</code>```

but now I want the next job started after last job is finished 1mins later, I wonder if it can be relized.

答:
Probably, you can try using the sleep() between your two jobs or as a part of the first job definition:</p>

```<code>from time import sleep
sleep(60)
</code>```

Body:
I know that apscheduler was able to do schedule jobs with:

scheduler = BackgroundScheduler()
scheduler.add_job(run, 'interval', seconds=60)

but now I want the next job started after last job is finished 1mins later, I wonder if it can be relized.

Body:
Probably, you can try using the sleep() between your two jobs or as a part of the first job definition:

from time import sleep
sleep(60)


问:
Symfony3.4 Form errors rendered twice
I have a form with author and message fields and NotBlank() validation on both.

In twig, I do this:

```<code>{{ form_start(form) }}

    {{ form_errors(form.author) }}
    {{ form_label(form.author) }}
    {{ form_widget(form.author) }}

    {{ form_errors(form.message) }}
    {{ form_label(form.message) }}
    {{ form_widget(form.message) }}

{{ form_end(form) }}
</code>```

If I press Save button with empty fields I EXPECT to see this:

But I get this:

Somehow the bottom error message comes from the {{ form_label(...) }} I say this, because if I comment the labels out and use static HTML for labels, the output is like on first picture.

I would prefer not to use static HTML for labels, but I don't understand where the second error messages came from.

Below my code:

Form

```<code>class TestFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('author', TextType::class, ['required' => false, 'constraints' => [new NotBlank()]])
            ->add('message', TextType::class, ['required' => false, 'constraints' => [new NotBlank()]])
            ->add('save', SubmitType::class)
        ;
    }
}
</code>```

Controller

```<code>class TestController extends Controller
{
    /**
     * @Route("/testing", name="test")
     * @param Request $request
     * @return RedirectResponse|Response
     */
    public function index(Request $request)
    {
        $form = $this->createForm(TestFormType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid())
        {
            return $this->redirectToRoute('test');
        }

        return $this->render('test/index.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}
</code>```

Template
    {% extends 'base.html.twig' %}
    {% block title %}Hello TestController!{% endblock %}

```<code>{% block body %}

    <p>This is a test...</p>

    {{ form_start(form) }}

        {{ form_errors(form.author) }}
        {{ form_label(form.author) }}
        {{ form_widget(form.author) }}

        {{ form_errors(form.message) }}
        {{ form_label(form.message) }}
        {{ form_widget(form.message) }}

    {{ form_end(form) }}

{% endblock %}
</code>```

答: You've explicitly added form_errors whereas error message already rendered via form_label. either you can remove form_errors or form_label.</p>

Title: Symfony3.4 Form errors rendered twice

Body:
I have a form with author and message fields and NotBlank() validation on both.

In twig, I do this:

{{ form_start(form) }}

    {{ form_errors(form.author) }}
    {{ form_label(form.author) }}
    {{ form_widget(form.author) }}

    {{ form_errors(form.message) }}
    {{ form_label(form.message) }}
    {{ form_widget(form.message) }}

{{ form_end(form) }}

If I press Save button with empty fields I EXPECT to see this:

But I get this:

Somehow the bottom error message comes from the {{ form_label(...) }} I say this, because if I comment the labels out and use static HTML for labels, the output is like on first picture.

I would prefer not to use static HTML for labels, but I don't understand where the second error messages came from.

Below my code:

Form

class TestFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('author', TextType::class, ['required' => false, 'constraints' => [new NotBlank()]])
            ->add('message', TextType::class, ['required' => false, 'constraints' => [new NotBlank()]])
            ->add('save', SubmitType::class)
        ;
    }
}

Controller

class TestController extends Controller
{
    /**
     * @Route("/testing", name="test")
     * @param Request $request
     * @return RedirectResponse|Response
     */
    public function index(Request $request)
    {
        $form = $this->createForm(TestFormType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid())
        {
            return $this->redirectToRoute('test');
        }

        return $this->render('test/index.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}

Template
    {% extends 'base.html.twig' %}
    {% block title %}Hello TestController!{% endblock %}

{% block body %}

This is a test...

    {{ form_start(form) }}

        {{ form_errors(form.author) }}
        {{ form_label(form.author) }}
        {{ form_widget(form.author) }}

        {{ form_errors(form.message) }}
        {{ form_label(form.message) }}
        {{ form_widget(form.message) }}

    {{ form_end(form) }}

{% endblock %}


问:
Faster way to convert large binary string to BigInteger
The code below is converting big binary string binaryAsString = "1010101011101011......." to BigInteger decimal but this is very slow, it takes very long time to finish. Is there any faster way to make this done? Before this I had a problem with converting BitArray to string. My first code take so long but I found new code which was much faster in a way I didn't imagine. I hope I can find a similarly faster way to do this, because it's really taking a long time.

I tried to use String whatever = Convert.ToString(binaryAsString, 2); but this is not working at all.

```<code>// converting the binary String to decimal
BigInteger Decimalvalue = 0;

foreach (char c in binaryAsString)
{
    Decimalvalue <<= 1;

    Decimalvalue += c == '1' ? 1 : 0;

}
</code>```

I would like to have faster code to do exactly what the code above should do.

答:
I think process the large string by each char is not a good way.

```<code>char c in binaryAsString
</code>```

Look at the constructors of BigInteger, you can find:

```<code>BigInteger(Byte[])
</code>```

So the first thing is convert the string into byte array, then construct your big integer. the rest codes are copy from this answer: Convert a binary string representation to a byte array

```<code>int numOfBytes = binaryAsString.Length / 8;
byte[] bytes = new byte[numOfBytes];
for(int i = 0; i < numOfBytes; ++i)
    bytes[i] = Convert.ToByte(binaryAsString.Substring(8 * i, 8), 2);
</code>```

Option 1. Use string.PadLeft

```<code>if((binaryAsString.Length % 8) != 0)
{
    var totalWidth = (binaryAsString.Length / 8 + 1) * 8;
    binaryAsString = binaryAsString.PadLeft(totalWidth, '0');
}
</code>```

Option 2. Convert from tail side

```<code>int numOfBytes = binaryAsString.Length / 8;
if((binaryAsString.Length % 8) != 0)
    numOfBytes++;
byte[] bytes = new byte[numOfBytes];
for(int i = 1; i <= numOfBytes; ++i)
{
    int start = binaryAsString.Length - i * 8;
    int length = 8;
    if(start < 0)
    {
        length += start;
        start = 0;
    }
    bytes[numOfBytes - i] = Convert.ToByte(binaryAsString.Substring(start, length), 2);
}
</code>```

Body:
The code below is converting big binary string binaryAsString = "1010101011101011......." to BigInteger decimal but this is very slow, it takes very long time to finish. Is there any faster way to make this done? Before this I had a problem with converting BitArray to string. My first code take so long but I found new code which was much faster in a way I didn't imagine. I hope I can find a similarly faster way to do this, because it's really taking a long time.

I tried to use String whatever = Convert.ToString(binaryAsString, 2); but this is not working at all.

// converting the binary String to decimal
BigInteger Decimalvalue = 0;

foreach (char c in binaryAsString)
{
    Decimalvalue <<= 1;

    Decimalvalue += c == '1' ? 1 : 0;

}

I would like to have faster code to do exactly what the code above should do.

Body:
I think process the large string by each char is not a good way.

char c in binaryAsString

Look at the constructors of BigInteger, you can find:

BigInteger(Byte[])

So the first thing is convert the string into byte array, then construct your big integer. the rest codes are copy from this answer: Convert a binary string representation to a byte array

int numOfBytes = binaryAsString.Length / 8;
byte[] bytes = new byte[numOfBytes];
for(int i = 0; i < numOfBytes; ++i)
    bytes[i] = Convert.ToByte(binaryAsString.Substring(8 * i, 8), 2);

Option 1. Use string.PadLeft

if((binaryAsString.Length % 8) != 0)
{
    var totalWidth = (binaryAsString.Length / 8 + 1) * 8;
    binaryAsString = binaryAsString.PadLeft(totalWidth, '0');
}

Option 2. Convert from tail side

int numOfBytes = binaryAsString.Length / 8;
if((binaryAsString.Length % 8) != 0)
    numOfBytes++;
byte[] bytes = new byte[numOfBytes];
for(int i = 1; i <= numOfBytes; ++i)
{
    int start = binaryAsString.Length - i * 8;
    int length = 8;
    if(start < 0)
    {
        length += start;
        start = 0;
    }
    bytes[numOfBytes - i] = Convert.ToByte(binaryAsString.Substring(start, length), 2);
}