问:
Basic Select with Laravel Eloquent do not work
I have 2 table: User & Demands. Inside the table Demands, I have the user_id as a foreign key.
The User log in with a name (which I have throught the Session).
What I want to do is:
  - Have the name of the User (his log in)-> since I do not have the session implemented, I write the name directly inside the code.
  - Search his ID thanks to his name.
  - Search all of his demands with his id.

```<code>  $name = "Jason";
  $UserID = User::select('id')->where('name', '=', $name)->get();
  $User= User::find($UserID);
  $demands = Demand::where('user_id', '=', $UserID)->get();
  echo $demands;
</code>```

My array is then empty. But inside my database, I do have 3 demands of this user_id...

Do you guys have any clue please ?

Cordially.

答:
get function is returning a Eloquent Collection insteed value. You must want to use the first function. This function will return the first row of the query.

```<code> $name = "Jason";
  $UserID = User::select('id')->where('name', '=', $name)->first();
  $User= User::find($UserID);
  $demands = Demand::where('user_id', '=', $UserID->id)->get();
  echo $demands;

</code>```

Body:
I have 2 table: User & Demands. Inside the table Demands, I have the user_id as a foreign key.
The User log in with a name (which I have throught the Session).
What I want to do is:
  - Have the name of the User (his log in)-> since I do not have the session implemented, I write the name directly inside the code.
  - Search his ID thanks to his name.
  - Search all of his demands with his id.

  $name = "Jason";
  $UserID = User::select('id')->where('name', '=', $name)->get();
  $User= User::find($UserID);
  $demands = Demand::where('user_id', '=', $UserID)->get();
  echo $demands;

My array is then empty. But inside my database, I do have 3 demands of this user_id...

Do you guys have any clue please ?

Cordially.

Body:
get function is returning a Eloquent Collection insteed value. You must want to use the first function. This function will return the first row of the query.

 $name = "Jason";
  $UserID = User::select('id')->where('name', '=', $name)->first();
  $User= User::find($UserID);
  $demands = Demand::where('user_id', '=', $UserID->id)->get();
  echo $demands;


来源: stackexchange

问:
Fingerprint has already been taken - GIT
I am trying to generate a new pair of SSH keys, but upon generating (ssh-keygen -t rsa -C "my@email.com" -b 4096), the existing key in the indicated folder does not get updated despite the status Your identification has been saved in ir_rsa2 and Your public key has been saved in ir_rsa2.pub and a freshly generated key fingerprint in console, so when adding the key to git repository I'm getting error 'Fingerprint has already been taken'. What could be the problem?

Thank you in advance.

答:
```<code>Fingerprint has already been taken.
</code>```

That means you are copying a public key you already registered before.

You should see new files in ~/.ssh

In your case, you should copy the content of ~/.ssh/ir_rsa2.pub to your Git server web GUI.

If you do not see those files, try again this time by specifying the file directly:

```<code>ssh-keygen -t rsa -C "my@email.com" -b 4096 -f ~/.ssh/ir_rsa2
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Fingerprint has already been taken.

That means you are copying a public key you already registered before.

You should see new files in ~/.ssh

In your case, you should copy the content of ~/.ssh/ir_rsa2.pub to your Git server web GUI.

If you do not see those files, try again this time by specifying the file directly:

ssh-keygen -t rsa -C "my@email.com" -b 4096 -f ~/.ssh/ir_rsa2


问:
Auto create directories after uploading with PHP
I'm creating a php site where a company will upload a lot of images. I'd like one folder to contain upto 500-1000 files and PHP automatically creates a new one if previous contains more that 1000 files.

For example, px300 has folder dir1 which stores 500 files, then a new one dir2 will be created.

Are there any existed a solutions?

答:
In this way:</p>

```<code>if ($h = opendir('/dir')) {
    $files = 0;
    while (false !== ($file = readdir($h))) {
        $files++
    }
    if($files > 1000){
    //create dir
    mkdir('/newdir')
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In this way:

if ($h = opendir('/dir')) {
    $files = 0;
    while (false !== ($file = readdir($h))) {
        $files++
    }
    if($files > 1000){
    //create dir
    mkdir('/newdir')
    }
}


答:
If these are the actual values of the array you're using, you can just loop from 1 through 12 and stick it together with a random character from the string "abcdefghijk" using randojs' rando() function (or otherwise if you prefer).

for(var i = 1; i <= 12; i++){
  console.log("assets/music/" + rando("abcdefghijk") + (i < 10 ? "0" : "") + i + ".mp3")
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://randojs.com/1.0.0.js"></script></code>```

This code uses randojs.com to simplify the randomness and make it easier to read, so if you want to use this code, make sure this is in the head tag of your html document:

```<code><script src="https://randojs.com/1.0.0.js"></script>
</code>```

To answer the second part of your question (which you posted as another answer to this question), you don't need to keep your fileName variable to construct the HTML here if you'd rather not. You can do it like this instead:

```<code>var letters = "abcdefghijk";
for(var i = 0; i < letters.length; i++){
    var musicRowID = letters.charAt(i) + "01";
    $("#music-grid").append(`<div id="music-row-${musicRowID}" class="row no-gutters"></div>`);

    for(var j = 1; j <= 12; j++){
        var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
        $(`#music-row-${musicRowID}`).append(`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`);
    }
}
</code>```

Title: Randomising array from a matrix (bidimensional array)

Body:
I Currently have the following matrix

const fileName = [
  ["a01", "b01", "c01", "d01", "e01", "f01", "g01", "h01", "i01", "j01", "k01", "l01"],
  ["a02", "b02", "c02", "d02", "e02", "f02", "g02", "h02", "i02", "j02", "k02", "l02"],
  ["a03", "b03", "c03", "d03", "e03", "f03", "g03", "h03", "i03", "j03", "k03", "l03"],
  ["a04", "b04", "c04", "d04", "e04", "f04", "g04", "h04", "i04", "j04", "k04", "l04"],
  ["a05", "b05", "c05", "d05", "e05", "f05", "g05", "h05", "i05", "j05", "k05", "l05"],
  ["a06", "b06", "c06", "d06", "e06", "f06", "g06", "h06", "i06", "j06", "k06", "l06"],
  ["a07", "b07", "c07", "d07", "e07", "f07", "g07", "h07", "i07", "j07", "k07", "l07"],
  ["a08", "b08", "c08", "d08", "e08", "f08", "g08", "h08", "i08", "j08", "k08", "l08"],
  ["a09", "b09", "c09", "d09", "e09", "f09", "g09", "h09", "i09", "j09", "k09", "l09"],
  ["a10", "b10", "c10", "d10", "e10", "f10", "g10", "h10", "i10", "j10", "k10", "l10"],
  ["a11", "b11", "c11", "d11", "e11", "f11", "g11", "h11", "i11", "j11", "k11", "l11"],
  ["a12", "b12", "c12", "d12", "e12", "f12", "g12", "h12", "i12", "j12", "k12", "l12"]
];

and I create a new array with filenames from it randomising 1 item of each subarray using this function:

function randomise() {
  let sequence = fileName.map(option => {
    const random = Math.floor(Math.random() * 11);
    return option[random];
  });
  let randomSelection = sequence.map(createURL);
  function createURL(fileName) {
    return `assets/music/${fileName}.mp3`;
  }
  console.log(randomSelection);
}

So I get an array such as:

["assets/music/f01.mp3", "assets/music/f02.mp3", "assets/music/b03.mp3", "assets/music/k04.mp3", "assets/music/b05.mp3", "assets/music/f06.mp3", "assets/music/i07.mp3", "assets/music/d08.mp3", "assets/music/d09.mp3", "assets/music/g10.mp3", "assets/music/a11.mp3", "assets/music/d12.mp3"]

But I want to rearrange my matrix in this way:

const fileName = [
  ["a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a10", "a11", "a12"],
  ["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12"],
  ["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12"],
  ["d01", "d02", "d03", "d04", "d05", "d06", "d07", "d08", "d09", "d10", "d11", "d12"],
  ["e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11", "e12"],
  ["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12"],
  ["g01", "g02", "g03", "g04", "g05", "g06", "g07", "g08", "g09", "g10", "g11", "g12"],
  ["h01", "h02", "h03", "h04", "h05", "h06", "h07", "h08", "h09", "h10", "h11", "h12"],
  ["i01", "i02", "i03", "i04", "i05", "i06", "i07", "i08", "i09", "i10", "i11", "i12"],
  ["j01", "j02", "j03", "j04", "j05", "j06", "j07", "j08", "j09", "j10", "j11", "j12"],
  ["k01", "k02", "k03", "k04", "k05", "k06", "k07", "k08", "k09", "k10", "k11", "k12"]
];

I need to randomly select 1 item from each of the indexes of those subarrays, so one random item ending with "1", another ending with "2", etc
Could you help me please? Thanks!

Body:
If these are the actual values of the array you're using, you can just loop from 1 through 12 and stick it together with a random character from the string "abcdefghijk" using randojs' rando() function (or otherwise if you prefer).

for(var i = 1; i <= 12; i++){
  console.log("assets/music/" + rando("abcdefghijk") + (i < 10 ? "0" : "") + i + ".mp3")
}

<script src="https://randojs.com/1.0.0.js"></script>

This code uses randojs.com to simplify the randomness and make it easier to read, so if you want to use this code, make sure this is in the head tag of your html document:

<script src="https://randojs.com/1.0.0.js"></script>

To answer the second part of your question (which you posted as another answer to this question), you don't need to keep your fileName variable to construct the HTML here if you'd rather not. You can do it like this instead:

var letters = "abcdefghijk";
for(var i = 0; i < letters.length; i++){
    var musicRowID = letters.charAt(i) + "01";
    $("#music-grid").append(`<div id="music-row-${musicRowID}" class="row no-gutters"></div>`);

    for(var j = 1; j <= 12; j++){
        var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
        $(`#music-row-${musicRowID}`).append(`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`);
    }
}


问:
Multi-threaded transactional kafka producer - should I flush before close?
Let's consider multithreaded transnational kafka producer. Should I flush() producer before closing?  In other words, does Transactional producer buffers in batches data before sending them ?

答:
As stated in the javadocs

Applications don't need to call flush method for transactional
  producers, since the commitTransaction() will flush all buffered
  records before performing the commit

This is best illustrated in the javadoc example

```<code>Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("transactional.id", "my-transactional-id");
Producer<String, String> producer = new KafkaProducer<>(props, new StringSerializer(), new StringSerializer());

producer.initTransactions();

try {
 producer.beginTransaction();
 for (int i = 0; i < 100; i++)
     producer.send(new ProducerRecord<>("my-topic", Integer.toString(i), Integer.toString(i)));
 producer.commitTransaction();
} catch (ProducerFencedException | OutOfOrderSequenceException | AuthorizationException e) {
 // We can't recover from these exceptions, so our only option is to close the producer and exit.
 producer.close();
} catch (KafkaException e) {
 // For all other exceptions, just abort the transaction and try again.
 producer.abortTransaction();
}
producer.close();
</code>```

In short it is better to use transactional APIs of the producer (which are blocking and will throw exceptions on failure).

Further, in case of multithreaded application, you would need to ensure that there is only one open transaction per producer. And if at all you get an exception during the transaction, you should call producer.abortTransaction() (also highlighted in the example) to maintain the exactly once semantics of the producer's transactional capabilities.

Body:
As stated in the javadocs

Applications don't need to call flush method for transactional
  producers, since the commitTransaction() will flush all buffered
  records before performing the commit

This is best illustrated in the javadoc example

Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("transactional.id", "my-transactional-id");
Producer<String, String> producer = new KafkaProducer<>(props, new StringSerializer(), new StringSerializer());

producer.initTransactions();

try {
 producer.beginTransaction();
 for (int i = 0; i < 100; i++)
     producer.send(new ProducerRecord<>("my-topic", Integer.toString(i), Integer.toString(i)));
 producer.commitTransaction();
} catch (ProducerFencedException | OutOfOrderSequenceException | AuthorizationException e) {
 // We can't recover from these exceptions, so our only option is to close the producer and exit.
 producer.close();
} catch (KafkaException e) {
 // For all other exceptions, just abort the transaction and try again.
 producer.abortTransaction();
}
producer.close();

In short it is better to use transactional APIs of the producer (which are blocking and will throw exceptions on failure).

Further, in case of multithreaded application, you would need to ensure that there is only one open transaction per producer. And if at all you get an exception during the transaction, you should call producer.abortTransaction() (also highlighted in the example) to maintain the exactly once semantics of the producer's transactional capabilities.


问:
Django REST Framework: Using the Accept-Language header to set an instance's "locale"
So, I have a model with the following attribute:

```<code>locale = models.CharField(max_length=10, choices=get_locale_choices(), default='en-gb')
</code>```

The associated serializer for this model is currently:

```<code>class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'
</code>```

I then call a create endpoint:

```<code>serializer = self.get_serializer(data=request.data)

serializer.is_valid(raise_exception=True)

self.perform_create(serializer)
</code>```

I was wondering, how best to modify the above to allow the locale attribute of MyModel to be updated by the Accept-Language header en-GB,en;q=0.5.

I get my locale choices from django.conf.locale.LANG_INFO:

```<code>from django.conf.locale import LANG_INFO

def get_locale_choices():
    return [(k, v['name']) for k, v in LANG_INFO.items() if 'name' in v]
</code>```

I guess I need to pass in the request.headers as some sort of extra context...? But I'm thinking, what if the Accept-Language is not set, etc? I know it is here:

```<code>request.headers['Accept-Language']
</code>```

So, I guess request.headers.get('Accept-Language', 'en-gb') would be acceptable ...

But then, what would be the best way to then set the attribute in the serialzier as this?

N.B. I also believe get_serializer_context() can return the request object?

I also feel this could be robust enough:

```<code>data = request.POST.copy()

serializer = self.get_serializer(data=data.update({'locale': request.headers.get('Accept-Language', 'en')}))
</code>```

But is this, "good practise"?

Opinions are warmly welcome!

答:
Without "much considering the locale" try this method to save any data from request.

First you need to set the locale field to read_only

```<code>class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'
        <b>read_only_fields = ('locale',)</b></code>```

override the perform_create(...) method of the ModelViewset or similar viewclass

```<code>class MyModelViewSet(viewsets.ModelViewSet):
    # other code
    <b>def perform_create(self, serializer):
        serializer.save(locale=self.request.headers.get('Accept-Language', 'en-gb'))</b></code>```

Body:
So, I have a model with the following attribute:

locale = models.CharField(max_length=10, choices=get_locale_choices(), default='en-gb')

The associated serializer for this model is currently:

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'

I then call a create endpoint:

serializer = self.get_serializer(data=request.data)

serializer.is_valid(raise_exception=True)

self.perform_create(serializer)

I was wondering, how best to modify the above to allow the locale attribute of MyModel to be updated by the Accept-Language header en-GB,en;q=0.5.

I get my locale choices from django.conf.locale.LANG_INFO:

from django.conf.locale import LANG_INFO

def get_locale_choices():
    return [(k, v['name']) for k, v in LANG_INFO.items() if 'name' in v]

I guess I need to pass in the request.headers as some sort of extra context...? But I'm thinking, what if the Accept-Language is not set, etc? I know it is here:

request.headers['Accept-Language']

So, I guess request.headers.get('Accept-Language', 'en-gb') would be acceptable ...

But then, what would be the best way to then set the attribute in the serialzier as this?

N.B. I also believe get_serializer_context() can return the request object?

I also feel this could be robust enough:

data = request.POST.copy()

serializer = self.get_serializer(data=data.update({'locale': request.headers.get('Accept-Language', 'en')}))

But is this, "good practise"?

Opinions are warmly welcome!

Body:
Without "much considering the locale" try this method to save any data from request.

First you need to set the locale field to read_only

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'
        read_only_fields = ('locale',)

override the perform_create(...) method of the ModelViewset or similar viewclass

class MyModelViewSet(viewsets.ModelViewSet):
    # other code
    def perform_create(self, serializer):
        serializer.save(locale=self.request.headers.get('Accept-Language', 'en-gb'))


问:
How to compare hashmap key (country name) with country name retrieve from a CSV file?
I would like to seek some opinion or assistance regarding my code for a heatmap based on the number of Wuhan cases each country has, code as shown below.

Currently, I have stored all country coordinates in a hashmap, and I have scraped out data from https://www.worldometers.info/coronavirus/ where I stored the country name and number of cases in a CSV file.

I am trying to compare the names of the country from the CSV file with the country name (key) in the hashmap, such that if such country exists plot the "heat area" on the map. However, currently, when I am trying to do the comparing by using an if-else statement as shown in my codes. However, the issues I am facing is that if the csv file is missing 1 country and it doesn't match with the hashmap, the code will not run. Only when the csv file contain all country name and it matches with the hashmap then the code will display the application as shown below. How do I go about plotting the "heat area" when comparing the country names from the csv file and the hashmap ?

CODE

```<code> @Override public void init() {

    //Input the coordinates of the country, based on the size of the javafx.
    //Limitation is the current coordinates are not the entire list of country in the world.
    HashMap<String, List<Integer>> countryCoordinates = new HashMap<>();
    Integer[] coordinates = {};
    countryCoordinates.put("China", Arrays.asList(700, 180));
    countryCoordinates.put("Diamond Princess", Arrays.asList(810, 170));
    countryCoordinates.put("Singapore", Arrays.asList(726, 310));
    countryCoordinates.put("Japan", Arrays.asList(810, 170));
    countryCoordinates.put("Hong Kong", Arrays.asList(755, 225));
    countryCoordinates.put("Thailand", Arrays.asList(720, 250));
    countryCoordinates.put("S. Korea", Arrays.asList(780, 170));
    countryCoordinates.put("Taiwan", Arrays.asList(775, 220));
    countryCoordinates.put("Malaysia", Arrays.asList(725, 300));
    countryCoordinates.put("Germany", Arrays.asList(440, 115));
    countryCoordinates.put("Vietnam", Arrays.asList(740, 260));
    .
    .
    .

    Reader reader;
    try {
        //Retrieving the data from WorldMap CSV
        reader = Files.newBufferedReader(Paths.get("C:\\Users\\User\\Desktop\\ICT1009_TESTFILE\\WorldMap.csv"));
        CSVReader csvReader = new CSVReader(reader);
        String[] nextRecord;
        while((nextRecord = csvReader.readNext()) != null) {
            String retrieveCountry = nextRecord[0];
            //Comparing the hashmap key with the country name retrieve from CSV file
            //If the names matches, plot the heat area
            List<Integer> coordinatesOfThisCountry = countryCoordinates.get(retrieveCountry);
            if (coordinatesOfThisCountry != null) {
                    events = new Point2D[] {
                            asPoint2D(countryCoordinates.get(retrieveCountry)),
                    };
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

OUTPUT

答:
The outer loop must read the CSV file line by line, the inner loop must compare with the map. However, the purpose of a map is to find matching entries much quicker by a hash code lookup instead of for-loop. So only the outer loop remains:</p>

```<code>while((nextRecord = csvReader.readNext()) != null)
{
    String retrieveCountry = nextRecord[0];
    String retrieveCases = nextRecord[1];

    // Find the existing country in the map
    List<Integer> coordinatesOfThisCountry=countryCoordinates.get(retrieveCountry);

    if (coordinatesOfThisCountry!=null)
    {
        // found
        // TODO: plot the "heat area"
    }
    else
    {
       // not found
    }
}
</code>```

Body:
I would like to seek some opinion or assistance regarding my code for a heatmap based on the number of Wuhan cases each country has, code as shown below.

Currently, I have stored all country coordinates in a hashmap, and I have scraped out data from https://www.worldometers.info/coronavirus/ where I stored the country name and number of cases in a CSV file.

I am trying to compare the names of the country from the CSV file with the country name (key) in the hashmap, such that if such country exists plot the "heat area" on the map. However, currently, when I am trying to do the comparing by using an if-else statement as shown in my codes. However, the issues I am facing is that if the csv file is missing 1 country and it doesn't match with the hashmap, the code will not run. Only when the csv file contain all country name and it matches with the hashmap then the code will display the application as shown below. How do I go about plotting the "heat area" when comparing the country names from the csv file and the hashmap ?

CODE

 @Override public void init() {

    //Input the coordinates of the country, based on the size of the javafx.
    //Limitation is the current coordinates are not the entire list of country in the world.
    HashMap<String, List<Integer>> countryCoordinates = new HashMap<>();
    Integer[] coordinates = {};
    countryCoordinates.put("China", Arrays.asList(700, 180));
    countryCoordinates.put("Diamond Princess", Arrays.asList(810, 170));
    countryCoordinates.put("Singapore", Arrays.asList(726, 310));
    countryCoordinates.put("Japan", Arrays.asList(810, 170));
    countryCoordinates.put("Hong Kong", Arrays.asList(755, 225));
    countryCoordinates.put("Thailand", Arrays.asList(720, 250));
    countryCoordinates.put("S. Korea", Arrays.asList(780, 170));
    countryCoordinates.put("Taiwan", Arrays.asList(775, 220));
    countryCoordinates.put("Malaysia", Arrays.asList(725, 300));
    countryCoordinates.put("Germany", Arrays.asList(440, 115));
    countryCoordinates.put("Vietnam", Arrays.asList(740, 260));
    .
    .
    .

    Reader reader;
    try {
        //Retrieving the data from WorldMap CSV
        reader = Files.newBufferedReader(Paths.get("C:\\Users\\User\\Desktop\\ICT1009_TESTFILE\\WorldMap.csv"));
        CSVReader csvReader = new CSVReader(reader);
        String[] nextRecord;
        while((nextRecord = csvReader.readNext()) != null) {
            String retrieveCountry = nextRecord[0];
            //Comparing the hashmap key with the country name retrieve from CSV file
            //If the names matches, plot the heat area
            List<Integer> coordinatesOfThisCountry = countryCoordinates.get(retrieveCountry);
            if (coordinatesOfThisCountry != null) {
                    events = new Point2D[] {
                            asPoint2D(countryCoordinates.get(retrieveCountry)),
                    };
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

OUTPUT

Body:
The outer loop must read the CSV file line by line, the inner loop must compare with the map. However, the purpose of a map is to find matching entries much quicker by a hash code lookup instead of for-loop. So only the outer loop remains:

while((nextRecord = csvReader.readNext()) != null)
{
    String retrieveCountry = nextRecord[0];
    String retrieveCases = nextRecord[1];

    // Find the existing country in the map
    List<Integer> coordinatesOfThisCountry=countryCoordinates.get(retrieveCountry);

    if (coordinatesOfThisCountry!=null)
    {
        // found
        // TODO: plot the "heat area"
    }
    else
    {
       // not found
    }
}


问:
It's possible to ignore a ServiceFilter controller for one action only?
It's possible to ignore a ServiceFilter controller for one action only and applicate another servicefilter? In my case for the action "MethodTwo"</p>

```<code>[Route("api/test")]
[ServiceFilter(typeof(RequireFilter1))]
public class TestController : BaseApiController
{
  public ActionResult MethodOne()
  {
    //Code
  }

  [ServiceFilter(typeof(RequireFilter2))]
  public ActionResult MethodTwo(int id)
  {
     //Code
  }
}
</code>```

答:
Hello.

For your case, both filters will be executed in MethodTwo.

Here you can read more about filters execute sequence - Filters in ASP.NET Core - MSDN

So for your case you can analyze existing action attributes in RequireFilter1 and do not execute it in case if any other ServiceFilterAttribute is assigned to action.
Or you can create your attribute which will block Controller attribute.

For example (disable controller filter execution if ServiceFilterAttribute attached to action):

```<code>public void OnActionExecuting(ActionExecutingContext context)
    {
        var actDescr = (context.ActionDescriptor as ControllerActionDescriptor);
        if (actDescr!=null)
        {
            var attrs = actDescr.MethodInfo.GetCustomAttributes(typeof(ServiceFilterAttribute),true);
            if (attrs.Any())
                return;
        }
        context.HttpContext.Response.Headers.Add("ActionFilterExample1",
                                             new string[] { "test ActionFilterExample1", "test ActionFilterExample0" });
    }
</code>```

Also, you must do the same for OnActionExecuted of the filter.

Another way - create separate attribute for disabling controller attribute:

```<code>public class DisableAttr : Attribute
{

}
</code>```

And check it in OnActionExecuting :

```<code>actDescr.MethodInfo.GetCustomAttributes(typeof(DisableAttr),true);
</code>```

Body:
It's possible to ignore a ServiceFilter controller for one action only and applicate another servicefilter? In my case for the action "MethodTwo"

[Route("api/test")]
[ServiceFilter(typeof(RequireFilter1))]
public class TestController : BaseApiController
{
  public ActionResult MethodOne()
  {
    //Code
  }

  [ServiceFilter(typeof(RequireFilter2))]
  public ActionResult MethodTwo(int id)
  {
     //Code
  }
}

Body:
Hello.

For your case, both filters will be executed in MethodTwo.

Here you can read more about filters execute sequence - Filters in ASP.NET Core - MSDN

So for your case you can analyze existing action attributes in RequireFilter1 and do not execute it in case if any other ServiceFilterAttribute is assigned to action.
Or you can create your attribute which will block Controller attribute.

For example (disable controller filter execution if ServiceFilterAttribute attached to action):

public void OnActionExecuting(ActionExecutingContext context)
    {
        var actDescr = (context.ActionDescriptor as ControllerActionDescriptor);
        if (actDescr!=null)
        {
            var attrs = actDescr.MethodInfo.GetCustomAttributes(typeof(ServiceFilterAttribute),true);
            if (attrs.Any())
                return;
        }
        context.HttpContext.Response.Headers.Add("ActionFilterExample1",
                                             new string[] { "test ActionFilterExample1", "test ActionFilterExample0" });
    }

Also, you must do the same for OnActionExecuted of the filter.

Another way - create separate attribute for disabling controller attribute:

public class DisableAttr : Attribute
{

}

And check it in OnActionExecuting :

actDescr.MethodInfo.GetCustomAttributes(typeof(DisableAttr),true);


问:
Deny access to AWS S3 files for everyone but the application user
I am creating a web application where users sign in via Amazon Cognito. Once a user is logged in he can start uploading and downloading files from AWS S3 using a pre-signed url. The files are supposed to be secret and only the user who uploaded them should be able to read them. Is it possible to achieve this so that even the AWS account's root user cannot read the files?</p>

答:
Using AWS SDK, there is an option to use client-side encryption out of box.

```<code> EncryptionMaterials encryptionMaterials = new EncryptionMaterials(symKey);

 AmazonS3 s3EncryptionClient = AmazonS3EncryptionClientBuilder.standard()
       .withCredentials(new ProfileCredentialsProvider())
       .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(encryptionMaterials))
        .withRegion(clientRegion)
        .build();
</code>```

Please note:

if the client will need to provide an extra key to encrypt the content. The question is how / where will the client manage the content key. (PBKDF? KMS from different account?)

if the encryption key is lost, the content is unrecoverable

I mean if the encryption key is saved on the user's end and he deletes the application and all of it's data, how is he able to decrypt the data after installing the application again?

I suggest you to create a password-based encryption key, where the user could provide an encryption password (different from user's authentication password which may change).

Maybe I can use Cognito password for this, but what if the user wants to change the password

You (should) have no access to user's password.

Body:
Using AWS SDK, there is an option to use client-side encryption out of box.

 EncryptionMaterials encryptionMaterials = new EncryptionMaterials(symKey);

 AmazonS3 s3EncryptionClient = AmazonS3EncryptionClientBuilder.standard()
       .withCredentials(new ProfileCredentialsProvider())
       .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(encryptionMaterials))
        .withRegion(clientRegion)
        .build();

Please note:

if the client will need to provide an extra key to encrypt the content. The question is how / where will the client manage the content key. (PBKDF? KMS from different account?)

if the encryption key is lost, the content is unrecoverable

I mean if the encryption key is saved on the user's end and he deletes the application and all of it's data, how is he able to decrypt the data after installing the application again?

I suggest you to create a password-based encryption key, where the user could provide an encryption password (different from user's authentication password which may change).

Maybe I can use Cognito password for this, but what if the user wants to change the password

You (should) have no access to user's password.


问:
From array, generate all distinct, non-empty subarrays, with preserved order
I have an array, with subarrays and need an algorithm that generates all possible distinct combinations of the subarrays. The resultant combinations can be any length. For example, if the Array has 4 subarrays, the first subarray by itself would be a unique and valid resultant combination, as would any other unique combination of any length.

A combination with the sub-array with the same items in a different order would not be considered unique.

let mainArray = [[0.3, 1], [0.5, 2], [0.6, 3], [0.3, 4]]

// Valid resultant combinations:
[[0.3, 1]]
[[0.3, 1], [0.5, 2]]
[[0.3, 1], [0.5, 2], [0.6, 3]]
[[0.3, 1], [0.5, 2], [0.6, 3], [0.3, 4]]
[[0.5, 2]]
[[0.5, 2], [0.6, 3]]
[[0.5, 2], [0.6, 3], [0.3, 4]]
[[0.6, 3]]
[[0.6, 3], [0.3, 4]]
[[0.3, 4]]
[[0.3, 1], [0.6, 3], [0.3, 4]]
[[0.3, 1], [0.5, 2], [0.3, 4]]
[[0.3, 1], [0.3, 4]]
[[0.3, 1], [0.6, 3]]
[[0.5, 2], [0.3, 4]]

// Don’t think I missed any.
```

答:
The algorithm would be based on the following logic.   How many total
  possible sub-arrays exist?   I. Let us consider there is only one
  item:   ( _ )   So first sub array -> I don't pick the item.   Second
  array -> I pick the item.   Which means two sub arrays.   II. Let us
  consider there are two items:   ( _ ) ( _ )   So first sub array -> I
  don't pick the 1st item.I pick the 2nd item.   Second array -> I pick
  the 1st item.I pick the 2nd item.   So first sub array -> I don't pick
  the 2nd item.I don't pick the 1st item.   Second array -> I pick the
  2nd item.I pick the 1st item.   Which means 4 sub arrays.

So I can generalise this, at each position, I can either pick it or
  not. Which means two values per position. So for n items -> 2x2x.....2
  (n times) or 2n

So for three items, here's how we can work out a solution for three
  items : ```
    |Item1|Item2|Item3|     |Item1|Item2|Item3|
    ___________________     ___________________
    |  ✘  |  ✘  |  ✘  |  or |  0  |  0  |  0  |
    |  ✘  |  ✘  |  ✔  |  or |  0  |  0  |  1  |
    |  ✘  |  ✔  |  ✘  |  or |  0  |  1  |  0  |
    |  ✘  |  ✔  |  ✔  |  or |  0  |  1  |  1  |
    |  ✔  |  ✘  |  ✘  |  or |  1  |  0  |  0  |
    |  ✔  |  ✘  |  ✔  |  or |  1  |  0  |  1  |
    |  ✔  |  ✔  |  ✘  |  or |  1  |  1  |  0  |
    |  ✔  |  ✔  |  ✔  |  or |  1  |  1  |  1  | ```   So if we run from 0 to (2n - 1), convert to binary and see show the only
  item which matches the ones, and not the zeros.

The pseudocode would be something like this:

``` n -> list.length dummyList -> [] for i:0 to 2^n-1
    dummy2 -> []
    toBinary -> binary(i)
    for j: 0 to n-1
        if toBinary[j] equals 1
           insert list[j] to dummy2
    insert dummy2 to dummyList ```

Time complexity =  n x 2n

function allSubs(list){
    let len = list.length;
    let lenraisedtoTwo = 1<<len;
    let nwArr = Array(lenraisedtoTwo).fill().map((_,idx)=>list.filter(($,ind)=>idx.toString(2).padStart(len)[ind]==="1"))
    return nwArr
}
abc.innerText = JSON.stringify(allSubs([1,2,3]))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="abc">This div contains the result for all possible combinations</div></code>```

Body:
The algorithm would be based on the following logic.   How many total
  possible sub-arrays exist?   I. Let us consider there is only one
  item:   ( _ )   So first sub array -> I don't pick the item.   Second
  array -> I pick the item.   Which means two sub arrays.   II. Let us
  consider there are two items:   ( _ ) ( _ )   So first sub array -> I
  don't pick the 1st item.I pick the 2nd item.   Second array -> I pick
  the 1st item.I pick the 2nd item.   So first sub array -> I don't pick
  the 2nd item.I don't pick the 1st item.   Second array -> I pick the
  2nd item.I pick the 1st item.   Which means 4 sub arrays.

So I can generalise this, at each position, I can either pick it or
  not. Which means two values per position. So for n items -> 2x2x.....2
  (n times) or 2n

So for three items, here's how we can work out a solution for three
  items :

    |Item1|Item2|Item3|     |Item1|Item2|Item3|
    ___________________     ___________________
    |  ✘  |  ✘  |  ✘  |  or |  0  |  0  |  0  |
    |  ✘  |  ✘  |  ✔  |  or |  0  |  0  |  1  |
    |  ✘  |  ✔  |  ✘  |  or |  0  |  1  |  0  |
    |  ✘  |  ✔  |  ✔  |  or |  0  |  1  |  1  |
    |  ✔  |  ✘  |  ✘  |  or |  1  |  0  |  0  |
    |  ✔  |  ✘  |  ✔  |  or |  1  |  0  |  1  |
    |  ✔  |  ✔  |  ✘  |  or |  1  |  1  |  0  |
    |  ✔  |  ✔  |  ✔  |  or |  1  |  1  |  1  |
   So if we run from 0 to (2n - 1), convert to binary and see show the only
  item which matches the ones, and not the zeros.

The pseudocode would be something like this:

 n -> list.length dummyList -> [] for i:0 to 2^n-1
    dummy2 -> []
    toBinary -> binary(i)
    for j: 0 to n-1
        if toBinary[j] equals 1
           insert list[j] to dummy2
    insert dummy2 to dummyList

Time complexity =  n x 2n

function allSubs(list){
    let len = list.length;
    let lenraisedtoTwo = 1<<len;
    let nwArr = Array(lenraisedtoTwo).fill().map((_,idx)=>list.filter(($,ind)=>idx.toString(2).padStart(len)[ind]==="1"))
    return nwArr
}
abc.innerText = JSON.stringify(allSubs([1,2,3]))

<div id="abc">This div contains the result for all possible combinations</div>


问:
In Python Panda: Best way to reverse dataframe column values where col1 > col2
I have a solution, but it uses a for loop and I am looking for a better/ more elegant way to swap Col1 and Col2 values when Col1 > Col2.

Current Solution:
In 2 for loops:
  Finds Rows where Col1 > Col2
  Then adds row Col2 Col1 Score
Afterwards all rows where Col1 > Col2 are dropped. This only took 2 lines.
Is there a better way to swap the Col1 and Col2 values?

import pandas as pd
def drop_all_revd_in_df(df):
    indexNames = df[ (df['col1'] > df['col2'])].index
    df.drop(indexNames , inplace=True)
    return df

# for loops  to check if col1 > col2 and reverse order
def col1GTcol2CleanUp(df):
    col1A_prev = ''
    for col1A in df['col1'] :
        if col1A != col1A_prev :
            col1A_prev = col1A
            for col1B in df[df['col1'] == col1A]['col2']:
                if (col1A > col1B) :
                    score = (df[ (df['col1'] == col1A) & (df['col2'] == col1B)].score).to_frame()['score'].iloc[0]
                    df =  df.append({'col1' : col1B , 'col2' : col1A ,'score' : score}, ignore_index=True)
    df = drop_all_revd_in_df(df)
    return df

# initialize list of lists
dataShort = [["Andy", "Claude", 15],
             ["Vincent", "Frida", 12],  # NOT OK
             ["Vincent", "Pablo", 11]]  # NOT OK

# Create the pandas DataFrame
df = pd.DataFrame(dataShort, columns = ['col1', 'col2', 'score'])
print(df)

col1GTcol2CleanUp(df).sort_values(['col1','col2']).reset_index(drop='True')
```

```Output:
      col1    col2  score
0     Andy  Claude     15
1  Vincent   Frida     12
2  Vincent   Pablo     11

Out[1]:
    col1    col2    score
0   Andy    Claude  15
1   Frida   Vincent 12
2   Pablo   Vincent 11
```

答:
Following up on the answer by instinct246: Pandas .apply() method tends to be slow. Here's yet another approach (method1 in the code below), it's quite a bit faster, but needs temporary storage for an extra column. This can also be written on a single line (method2 in the code below), even faster, but needs temporary storage for two columns.

```<code>np.random.seed(113)
df = pd.DataFrame({'col1':np.random.randint(low=0, high=9, size=10000, dtype='int32'),
                   'col2':np.random.randint(low=0, high=9, size=10000, dtype='int32')})

def method1(df):
    """ Modifies df in place, no return value """
    df['col_tmp'] = df[['col1','col2']].max(axis=1)
    df['col1'] = df[['col1','col2']].min(axis=1)
    df['col2'] = df['col_tmp']
    del df['col_tmp']

def method2(df):
    """ Modifies df in place, no return value """
    df['col1'], df['col2'] = df[['col1','col2']].min(axis=1), df[['col1','col2']].max(axis=1)

# instinct246's answer

def check_row(row):
    if row['col1'] > row['col2']:
        row['col1'],row['col2'] = row['col2'],row['col1']
        return row
    else:
        return row

def method3(df):
    """ Returns modified df """
    return df.apply(check_row, axis =1)
</code>```

Running %%timeit returns:

```<code>method1: 1.92 ms ± 62.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
method2: 1.31 ms ± 11.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
method3: 558 ms ± 8.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Body:
I have a solution, but it uses a for loop and I am looking for a better/ more elegant way to swap Col1 and Col2 values when Col1 > Col2.

Current Solution:
In 2 for loops:
  Finds Rows where Col1 > Col2
  Then adds row Col2 Col1 Score
Afterwards all rows where Col1 > Col2 are dropped. This only took 2 lines.
Is there a better way to swap the Col1 and Col2 values?

import pandas as pd
def drop_all_revd_in_df(df):
    indexNames = df[ (df['col1'] > df['col2'])].index
    df.drop(indexNames , inplace=True)
    return df

# for loops  to check if col1 > col2 and reverse order
def col1GTcol2CleanUp(df):
    col1A_prev = ''
    for col1A in df['col1'] :
        if col1A != col1A_prev :
            col1A_prev = col1A
            for col1B in df[df['col1'] == col1A]['col2']:
                if (col1A > col1B) :
                    score = (df[ (df['col1'] == col1A) & (df['col2'] == col1B)].score).to_frame()['score'].iloc[0]
                    df =  df.append({'col1' : col1B , 'col2' : col1A ,'score' : score}, ignore_index=True)
    df = drop_all_revd_in_df(df)
    return df

# initialize list of lists
dataShort = [["Andy", "Claude", 15],
             ["Vincent", "Frida", 12],  # NOT OK
             ["Vincent", "Pablo", 11]]  # NOT OK

# Create the pandas DataFrame
df = pd.DataFrame(dataShort, columns = ['col1', 'col2', 'score'])
print(df)

col1GTcol2CleanUp(df).sort_values(['col1','col2']).reset_index(drop='True')

Output:
      col1    col2  score
0     Andy  Claude     15
1  Vincent   Frida     12
2  Vincent   Pablo     11

Out[1]:
    col1    col2    score
0   Andy    Claude  15
1   Frida   Vincent 12
2   Pablo   Vincent 11

Body:
Following up on the answer by instinct246: Pandas .apply() method tends to be slow. Here's yet another approach (method1 in the code below), it's quite a bit faster, but needs temporary storage for an extra column. This can also be written on a single line (method2 in the code below), even faster, but needs temporary storage for two columns.

np.random.seed(113)
df = pd.DataFrame({'col1':np.random.randint(low=0, high=9, size=10000, dtype='int32'),
                   'col2':np.random.randint(low=0, high=9, size=10000, dtype='int32')})

def method1(df):
    """ Modifies df in place, no return value """
    df['col_tmp'] = df[['col1','col2']].max(axis=1)
    df['col1'] = df[['col1','col2']].min(axis=1)
    df['col2'] = df['col_tmp']
    del df['col_tmp']

def method2(df):
    """ Modifies df in place, no return value """
    df['col1'], df['col2'] = df[['col1','col2']].min(axis=1), df[['col1','col2']].max(axis=1)

# instinct246's answer

def check_row(row):
    if row['col1'] > row['col2']:
        row['col1'],row['col2'] = row['col2'],row['col1']
        return row
    else:
        return row

def method3(df):
    """ Returns modified df """
    return df.apply(check_row, axis =1)

Running %%timeit returns:

method1: 1.92 ms ± 62.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
method2: 1.31 ms ± 11.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
method3: 558 ms ± 8.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
Wrap code with common functionality, while passing down a parameter
I have the following code:

```<code>public void createProject() throws ServiceException {
    Project project = new ProjectMapper().map(pipeline);

    // repeating code
    Connection conn;
    try {
        conn = JDBCConnectionManager.getConnection(POOL_NAME, DB_CONNECTION_TIMEOUT);
    } catch (SQLException e1) {
        e1.printStackTrace();
        throw new ServiceException(e1);
    }
    try {
    // end repeating code

        ProjectAccess.writeProject(conn, project);

    // repeating code
    } catch (SQLException | JsonProcessingException e) {
        e.printStackTrace();
        throw new ServiceException(e);
    } finally {
        try {
            releaseConnection(conn);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }
    // end repeating code
}
</code>```

Basically I want to get rid of the two try / catch blocks and put them in a wrapper as they are always the same.
I thought about using a functional interface and it almost works, except I have to pass down the conn variable into my code, which doesnt work with my solution:

```<code>@FunctionalInterface
interface DatabaseLogic {
    public void execute() throws SQLException, JsonProcessingException;
}

public void executeSql(DatabaseLogic dl) throws ServiceException {
    Connection conn;
    try {
        conn = JDBCConnectionManager.getConnection(POOL_NAME, DB_CONNECTION_TIMEOUT);
    } catch (SQLException e1) {
        e1.printStackTrace();
        throw new ServiceException(e1);
    }
    try {
        dl.execute(conn);
    } catch (SQLException | JsonProcessingException e) {
        e.printStackTrace();
        throw new ServiceException(e);
    } finally {
        try {
            releaseConnection(conn);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }
}

    new DatabaseRunner().executeSql(() -> {
        IDataCursor pipelineCursor = pipeline.getCursor();
        String projectName = IDataUtil.getString(pipelineCursor, "projectName");
        // how can I access the conn object here?
        ProjectAccess.deleteProject(conn, projectName);
    });
</code>```

So, as I wrote in the comment, is there a way to use a functional interface and access a variable from the enclosing method?

答:
Hmpf, of course I figured it out a few minutes later. I just have to add the Connection parameter to the interface:</p>

```<code>public void execute(Connection conn) throws SQLException, JsonProcessingException;

new DatabaseRunner().executeSql((conn) -> {
    IDataCursor pipelineCursor = pipeline.getCursor();
    String projectName = IDataUtil.getString(pipelineCursor, "projectName");
    ProjectAccess.deleteProject(conn, projectName);
});
</code>```

Body:
I have the following code:

public void createProject() throws ServiceException {
    Project project = new ProjectMapper().map(pipeline);

    // repeating code
    Connection conn;
    try {
        conn = JDBCConnectionManager.getConnection(POOL_NAME, DB_CONNECTION_TIMEOUT);
    } catch (SQLException e1) {
        e1.printStackTrace();
        throw new ServiceException(e1);
    }
    try {
    // end repeating code

        ProjectAccess.writeProject(conn, project);

    // repeating code
    } catch (SQLException | JsonProcessingException e) {
        e.printStackTrace();
        throw new ServiceException(e);
    } finally {
        try {
            releaseConnection(conn);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }
    // end repeating code
}

Basically I want to get rid of the two try / catch blocks and put them in a wrapper as they are always the same.
I thought about using a functional interface and it almost works, except I have to pass down the conn variable into my code, which doesnt work with my solution:

@FunctionalInterface
interface DatabaseLogic {
    public void execute() throws SQLException, JsonProcessingException;
}

public void executeSql(DatabaseLogic dl) throws ServiceException {
    Connection conn;
    try {
        conn = JDBCConnectionManager.getConnection(POOL_NAME, DB_CONNECTION_TIMEOUT);
    } catch (SQLException e1) {
        e1.printStackTrace();
        throw new ServiceException(e1);
    }
    try {
        dl.execute(conn);
    } catch (SQLException | JsonProcessingException e) {
        e.printStackTrace();
        throw new ServiceException(e);
    } finally {
        try {
            releaseConnection(conn);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e);
        }
    }
}

    new DatabaseRunner().executeSql(() -> {
        IDataCursor pipelineCursor = pipeline.getCursor();
        String projectName = IDataUtil.getString(pipelineCursor, "projectName");
        // how can I access the conn object here?
        ProjectAccess.deleteProject(conn, projectName);
    });

So, as I wrote in the comment, is there a way to use a functional interface and access a variable from the enclosing method?

Body:
Hmpf, of course I figured it out a few minutes later. I just have to add the Connection parameter to the interface:

public void execute(Connection conn) throws SQLException, JsonProcessingException;

new DatabaseRunner().executeSql((conn) -> {
    IDataCursor pipelineCursor = pipeline.getCursor();
    String projectName = IDataUtil.getString(pipelineCursor, "projectName");
    ProjectAccess.deleteProject(conn, projectName);
});


问:
write data in binary format in Files in Android
hi all:
making a sample application in which we can store data on File and then could Read it.,
m using the following code.:

Code to Write:

```<code>OutputStreamWriter out = null;
    try {
        out = new OutputStreamWriter(openFileOutput("finear.fin", 0));
        out.write(data); //data is String variable
        out.close();
        Toast.makeText(getApplicationContext(), "Data has been Saved! ", Toast.LENGTH_LONG).show();
    }
</code>```

Code to Read:

```<code>instream = openFileInput("finear.fin");
if(instream!=null)
{
InputStreamReader inputReader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputReader);
String dataRead = buffreader.readLine();
}
</code>```

Now problem is: The Data is stored in simple Text Form but i want that no one could read my data from that file and it should store the data in some binary form or some symbols type format so that when one opens the file in windows it should not display my text stored in the file or should display some other data.. BUT also that data could be readable in String form when i read. PLease Help

答: Encrypt the String before saving it to the stream and the other way to read it. If you want your file's contents to be unreadable, encryption would be a win.</p>

Body:
hi all:
making a sample application in which we can store data on File and then could Read it.,
m using the following code.:

Code to Write:

OutputStreamWriter out = null;
    try {
        out = new OutputStreamWriter(openFileOutput("finear.fin", 0));
        out.write(data); //data is String variable
        out.close();
        Toast.makeText(getApplicationContext(), "Data has been Saved! ", Toast.LENGTH_LONG).show();
    }

Code to Read:

instream = openFileInput("finear.fin");
if(instream!=null)
{
InputStreamReader inputReader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputReader);
String dataRead = buffreader.readLine();
}

Now problem is: The Data is stored in simple Text Form but i want that no one could read my data from that file and it should store the data in some binary form or some symbols type format so that when one opens the file in windows it should not display my text stored in the file or should display some other data.. BUT also that data could be readable in String form when i read. PLease Help


问:
RegEx with notepad++: Remove two groups of text
i have this string on a line:

('some text', 'some text', 'some text', '{\n  {\n  {\n .
Some text
Some text
Some text

 \n} \n} \n}', 'some text' , 'some text')

and i would to have this result using RegEx with notepad++:

('some text', 'some text', 'some text', '
Some text
Some text
Some text

', 'some text' , 'some text')

Is it possible? Someone can help me?
Thank you

答:
Ctrl+H

Find what: {.+?(?=<)|(?<=>)[^<>]+}

Replace with: LEAVE EMPTY

CHECK Match case

CHECK Wrap around

CHECK Regular expression

UNCHECK . matches newline

Replace all

Explanation:

```<code>  {         # opening brace
  .+?       # 1 or more any character but newline
  (?=<)     # positive lookahead, make sure we have < after
|         # OR
  (?<=>)    # positive lookbehind, make sure we have > before
  [^<>]+    # 1 or more any character that is not < or >
  }         # closing brace
</code>```

Screenshot (before):

Screenshot (after):

Body:
Ctrl+H

Find what: {.+?(?=<)|(?<=>)[^<>]+}

Replace with: LEAVE EMPTY

CHECK Match case

CHECK Wrap around

CHECK Regular expression

UNCHECK . matches newline

Replace all

Explanation:

  {         # opening brace
  .+?       # 1 or more any character but newline
  (?=<)     # positive lookahead, make sure we have < after
|         # OR
  (?<=>)    # positive lookbehind, make sure we have > before
  [^<>]+    # 1 or more any character that is not < or >
  }         # closing brace

Screenshot (before):

Screenshot (after):


问:
How can I filter information ordering by two different factors on SQL?
I have the three following tables:

```<code>create table Person (

    id int,
    popularity int,
    primary key (id)
);

create table Movie (

    id int,
    year int,
    primary key (id)
);

create table Person_Movie (

    id_person int,
    id_movie int,
    primary key (id_person, id_movie),
    foreign key (id_person) references Person (id_person),
    foreign key (id_movie) references Movie (id_movie)
);
</code>```

I want to execute a SELECT to check which person has the higher number of popularity BUT has but has participated in less movies.

How can I do this?

To check the most popular person I'd execute this:

```<code>select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by popularity;
</code>```

And, if I am correct, to check the person that has participated in less movies I'd execute this:

```<code>select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by count(M.id);
</code>```

But, how can I filter the two cases in one SELECT?

Thanks in advance.

EDIT

I'm using MySQL.

Also I'll provide an example of what I'm trying to get:

Table Person

```<code>id      popularity
-------------------
1          50
2          35
3          120
4          45
</code>```

Table Movie

```<code>id        year
----------------
1         1999
2         2014
3         1969
4         1977
5         2019
</code>```

Table Person_Movie

```<code>id_person       id_movie
--------------------------
    1              1
    2              4
    2              5
    3              3
    4              1
    4              2
</code>```

So, given this example, the output I would like to get is:

```<code>id_person
----------
    3
</code>```

Because both persons with id 1 and 3 have participated in just ONE movie, but person with id 3 has the higher number of popularity.

答:
How about this:

```<code>select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by max(popularity),count(M.id);
</code>```

This would sort your results by the count of movies if multiple people have the same popularity. If you want only the first row, you can use a top 1. Hope this helps.

Edit:

Based on the sample cases, it looks like the first priority of sorting should go to count:

```<code>select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by count(M.id),max(Popularity) desc;
</code>```

Body:
I have the three following tables:

create table Person (

    id int,
    popularity int,
    primary key (id)
);

create table Movie (

    id int,
    year int,
    primary key (id)
);

create table Person_Movie (

    id_person int,
    id_movie int,
    primary key (id_person, id_movie),
    foreign key (id_person) references Person (id_person),
    foreign key (id_movie) references Movie (id_movie)
);

I want to execute a SELECT to check which person has the higher number of popularity BUT has but has participated in less movies.

How can I do this?

To check the most popular person I'd execute this:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by popularity;

And, if I am correct, to check the person that has participated in less movies I'd execute this:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by count(M.id);

But, how can I filter the two cases in one SELECT?

Thanks in advance.

EDIT

I'm using MySQL.

Also I'll provide an example of what I'm trying to get:

Table Person

id      popularity
-------------------
1          50
2          35
3          120
4          45

Table Movie

id        year
----------------
1         1999
2         2014
3         1969
4         1977
5         2019

Table Person_Movie

id_person       id_movie
--------------------------
    1              1
    2              4
    2              5
    3              3
    4              1
    4              2

So, given this example, the output I would like to get is:

id_person
----------
    3

Because both persons with id 1 and 3 have participated in just ONE movie, but person with id 3 has the higher number of popularity.

Body:
How about this:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by max(popularity),count(M.id);

This would sort your results by the count of movies if multiple people have the same popularity. If you want only the first row, you can use a top 1. Hope this helps.

Edit:

Based on the sample cases, it looks like the first priority of sorting should go to count:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by count(M.id),max(Popularity) desc;


答:
$UserID is a collection, not an integer. Try this:

```<code>$name = "Jason";
$user = User::select('id')->where('name', '=', $name)->first();
$User= User::find($user->id);
$demands = Demand::where('user_id', '=', $User->id)->get();
echo $demands;
</code>```

Title: Basic Select with Laravel Eloquent do not work

Body:
I have 2 table: User & Demands. Inside the table Demands, I have the user_id as a foreign key.
The User log in with a name (which I have throught the Session).
What I want to do is:
  - Have the name of the User (his log in)-> since I do not have the session implemented, I write the name directly inside the code.
  - Search his ID thanks to his name.
  - Search all of his demands with his id.

  $name = "Jason";
  $UserID = User::select('id')->where('name', '=', $name)->get();
  $User= User::find($UserID);
  $demands = Demand::where('user_id', '=', $UserID)->get();
  echo $demands;

My array is then empty. But inside my database, I do have 3 demands of this user_id...

Do you guys have any clue please ?

Cordially.

Body:
$UserID is a collection, not an integer. Try this:

$name = "Jason";
$user = User::select('id')->where('name', '=', $name)->first();
$User= User::find($user->id);
$demands = Demand::where('user_id', '=', $User->id)->get();
echo $demands;


问:
Schematic input does not validate against the Schema: {"name":"testng7"} on Angular 7
I updated the Angular CLI to the latest @angular/cli@7.0.2 on a Mac OS. When issuing the command ng new testng7, I get this error:

```<code>Schematic input does not validate against the Schema: {"name":"testng7"}
Errors:
  Data path "" should have required property 'version'.
</code>```

And nothing is created. Any clues how to fix?

答:
I added this flag to make it work --client-project

ng add @nguniversal/express-engine --client-project=launcher

Body:
I updated the Angular CLI to the latest @angular/cli@7.0.2 on a Mac OS. When issuing the command ng new testng7, I get this error:

Schematic input does not validate against the Schema: {"name":"testng7"}
Errors:
  Data path "" should have required property 'version'.

And nothing is created. Any clues how to fix?


问:
Why Visual Studio gets focused although there is no breakpoint?
there is no breakpoint in my application but sometimes Visual Studio get the focus when there is no reason. (in debug mode or not in debug mode) (like there was a breakpoint)

What can be the reason?

答:
If the debugger isn't breaking because you've manually set a breakpoint or because the application has thrown an exception or encountered some other unexpected error, the most likely explanation is that your application is giving up the focus.

For example, you destroy the window that currently has the focus and is in the foreground before setting that focus to another window in your application. And then, because some window always has to have the focus, the window manager sets activation to the next available window, which just happens to be the one owned by Visual Studio. The resulting effect would be just as if you pressed Alt+Tab.

Raymond Chen has a blog article about this, The correct order for disabling and enabling windows:

If you are finished with a modal dialog, your temptation would be to clean up in the following order:

Destroy the modal dialog.

Re-enable the owner.

But if you do that, you'll find that foreground activation doesn't go back to your owner. Instead, it goes to some random other window. Explicitly setting activation to the intended owner "fixes" the problem, but you still have all the flicker, and the Z-order of the interloper window gets all messed up.

What's going on?

When you destroy the modal dialog, you are destroying the window with foreground activation. The window manager now needs to find somebody else to give activation to. It tries to give it to the dialog's owner, but the owner is still disabled, so the window manager skips it and looks for some other window, somebody who is not disabled.

That's why you get the weird interloper window.

The correct order for destroying a modal dialog is

Re-enable the owner.

Destroy the modal dialog.

This time, when the modal dialog is destroyed, the window manager looks to the owner and hey this time it's enabled, so it inherits activation.

No flicker. No interloper.


问:
How to get console.log line numbers shown in Nodejs?
Got an old application, that prints out quite a lot of messages using console.log, but I just can not find in which files and lines console.log is called.

Is there a way to hook into the app and show file name and line numbers?

答:
All solutions to this question so far rely on splitting and matching the stack trace as a string, which will break in (the unlikely) case the format of that string is changed in the future. Inspired by this gist on GitHub and the other answers here, I want to provide my own solution:

```<code>'use strict';

const path = require('path');

['debug', 'log', 'warn', 'error'].forEach((methodName) => {
    const originalLoggingMethod = console[methodName];
    console[methodName] = (firstArgument, ...otherArguments) => {
        const originalPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = (_, stack) => stack;
        const callee = new Error().stack[1];
        Error.prepareStackTrace = originalPrepareStackTrace;
        const relativeFileName = path.relative(process.cwd(), callee.getFileName());
        const prefix = `${relativeFileName}:${callee.getLineNumber()}:`;
        if (typeof firstArgument === 'string') {
            originalLoggingMethod(prefix + ' ' + firstArgument, ...otherArguments);
        } else {
            originalLoggingMethod(prefix, firstArgument, ...otherArguments);
        }
    };
});

// Tests:
console.log('%s %d', 'hi', 42);
console.log({ a: 'foo', b: 'bar'});
</code>```

Unlike the other solutions, this script

outputs no additional lines and

handles string substitutions correctly.

You can color the prefix with chalk or color.js, but I didn't want to introduce dependencies for this here.

The above script uses the V8 API to customize stack traces. The callee is a CallSite object with the following methods in case you want to customize the prefix:

getThis: returns the value of this

getTypeName: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object’s [[Class]] internal property.

getFunction: returns the current function

getFunctionName: returns the name of the current function, typically its name property. If a name property is not available an attempt is made to infer a name from the function’s context.

getMethodName: returns the name of the property of this or one of its prototypes that holds the current function

getFileName: if this function was defined in a script returns the name of the script

getLineNumber: if this function was defined in a script returns the current line number

getColumnNumber: if this function was defined in a script returns the current column number

getEvalOrigin: if this function was created using a call to eval returns a string representing the location where eval was called

isToplevel: is this a top-level invocation, that is, is this the global object?

isEval: does this call take place in code defined by a call to eval?

isNative: is this call in native V8 code?

isConstructor: is this a constructor call?

isAsync: is this an async call (i.e. await or Promise.all())?

isPromiseAll: is this an async call to Promise.all()?

getPromiseIndex: returns the index of the promise element that was followed in Promise.all() for async stack traces, or null if the CallSite is not a Promise.all() call.

This answer is a cross-post of an answer I just gave to a similar question as more people might find this page.

Body:
All solutions to this question so far rely on splitting and matching the stack trace as a string, which will break in (the unlikely) case the format of that string is changed in the future. Inspired by this gist on GitHub and the other answers here, I want to provide my own solution:

'use strict';

const path = require('path');

['debug', 'log', 'warn', 'error'].forEach((methodName) => {
    const originalLoggingMethod = console[methodName];
    console[methodName] = (firstArgument, ...otherArguments) => {
        const originalPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = (_, stack) => stack;
        const callee = new Error().stack[1];
        Error.prepareStackTrace = originalPrepareStackTrace;
        const relativeFileName = path.relative(process.cwd(), callee.getFileName());
        const prefix = `${relativeFileName}:${callee.getLineNumber()}:`;
        if (typeof firstArgument === 'string') {
            originalLoggingMethod(prefix + ' ' + firstArgument, ...otherArguments);
        } else {
            originalLoggingMethod(prefix, firstArgument, ...otherArguments);
        }
    };
});

// Tests:
console.log('%s %d', 'hi', 42);
console.log({ a: 'foo', b: 'bar'});

Unlike the other solutions, this script

outputs no additional lines and

handles string substitutions correctly.

You can color the prefix with chalk or color.js, but I didn't want to introduce dependencies for this here.

The above script uses the V8 API to customize stack traces. The callee is a CallSite object with the following methods in case you want to customize the prefix:

getThis: returns the value of this

getTypeName: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object’s [[Class]] internal property.

getFunction: returns the current function

getFunctionName: returns the name of the current function, typically its name property. If a name property is not available an attempt is made to infer a name from the function’s context.

getMethodName: returns the name of the property of this or one of its prototypes that holds the current function

getFileName: if this function was defined in a script returns the name of the script

getLineNumber: if this function was defined in a script returns the current line number

getColumnNumber: if this function was defined in a script returns the current column number

getEvalOrigin: if this function was created using a call to eval returns a string representing the location where eval was called

isToplevel: is this a top-level invocation, that is, is this the global object?

isEval: does this call take place in code defined by a call to eval?

isNative: is this call in native V8 code?

isConstructor: is this a constructor call?

isAsync: is this an async call (i.e. await or Promise.all())?

isPromiseAll: is this an async call to Promise.all()?

getPromiseIndex: returns the index of the promise element that was followed in Promise.all() for async stack traces, or null if the CallSite is not a Promise.all() call.

This answer is a cross-post of an answer I just gave to a similar question as more people might find this page.


问:
Returning a list of words in alphabetical order - reading from files
For this code, I need to return a list of all unique words (words that only appear once in the file). Here is some of my code:

```<code>    words = []
    with open(self.filepath, 'r') as f:
        for l in f:
            new_word = l.split()

            words.append(new_word)
    return words
</code>```

A word is defined as any text that is separated by whitespace (spaces, newlines, or tabs). In addition to adding unique words to a list, I need to have them all made lowercase and in alphabetical order. I'm stuck on how I should do this. We do not have access to the file.

答:
One way would be to use list comprehension

words = set()
with open(self.filepath, 'r') as f:
    # value can be anything, just added 1
    words.update({str(i.lower()):1 for i in f.split()}.keys())

return sorted(words)

```

Body:
For this code, I need to return a list of all unique words (words that only appear once in the file). Here is some of my code:

    words = []
    with open(self.filepath, 'r') as f:
        for l in f:
            new_word = l.split()

            words.append(new_word)
    return words

A word is defined as any text that is separated by whitespace (spaces, newlines, or tabs). In addition to adding unique words to a list, I need to have them all made lowercase and in alphabetical order. I'm stuck on how I should do this. We do not have access to the file.


问:
htaccess authentication via. cname
I need a .htaccess rule which does not ask for a password when you come from the cname: xxx.example.com but I can't get it to work.

My actual .htaccess file looks like this:

```<code>AuthType Basic
AuthName “Entwurf“
AuthUserFile /my/path/to/.htpasswd
Require valid-user
Order deny,allow
Deny from all
Allow from 11.22.33.44
Satisfy any
</code>```

I tried this:

```<code>AuthType Basic
AuthName “Entwurf“
AuthUserFile /my/path/to/.htpasswd
Require valid-user
Order deny,allow
Deny from all
Allow from 11.22.33.44
Allow from xxx.example.com
Satisfy any
</code>```

But it still asks for the password.

I hope someone can help with it.

答:
By CNAME, it seems you are actually referring to the hostname that is being requested. (The hostname we are going to.)

So, anyone who requests xxx.example.com have unrestricted access OR the client with IP address 11.22.33.44, regardless of the hostname they are requesting (assuming you are serving mutliple hostnames).

```<code>Allow from xxx.example.com
</code>```

This checks the resolved hostname of the client making the request - this is not the same thing. (In order to get the hostname here, the server is required to make a DNS lookup of the client's IP address - this is disabled on some shared servers because of the additional overhead it places on the server). For most users this simply refers to the ISP through which they are accessing the internet.

Also, Order, Deny and Allow directives are Apache 2.2 directives. If you are on Apache 2.4 then you should probably be using the Require ... directives instead. Unless you are maintaining backwards compatibility with a server that is still using the old Apache 2.2 directives (the two should not be mixed).

On Apache 2.4 you can use Apache Expressions... so only use HTTP authentication if the client's IP is not 11.22.33.44 and xxx.example.com is not the host being requested.

For example:

```<code><If "%{HTTP_HOST} != 'xxx.example.com' && %{REMOTE_ADDR} != '11.22.33.44'">
    AuthType Basic
    AuthName "Entwurf"
    AuthUserFile /my/path/to/.htpasswd
    Require valid-user
</If>
</code>```

You also appeared to be using curly quotes in the AuthName directive - maybe this was just a formatting issue in your question?

Title: htaccess authentication via. cname

Body:
I need a .htaccess rule which does not ask for a password when you come from the cname: xxx.example.com but I can't get it to work.

My actual .htaccess file looks like this:

AuthType Basic
AuthName “Entwurf“
AuthUserFile /my/path/to/.htpasswd
Require valid-user
Order deny,allow
Deny from all
Allow from 11.22.33.44
Satisfy any

I tried this:

AuthType Basic
AuthName “Entwurf“
AuthUserFile /my/path/to/.htpasswd
Require valid-user
Order deny,allow
Deny from all
Allow from 11.22.33.44
Allow from xxx.example.com
Satisfy any

But it still asks for the password.

I hope someone can help with it.

Body:
By CNAME, it seems you are actually referring to the hostname that is being requested. (The hostname we are going to.)

So, anyone who requests xxx.example.com have unrestricted access OR the client with IP address 11.22.33.44, regardless of the hostname they are requesting (assuming you are serving mutliple hostnames).

Allow from xxx.example.com

This checks the resolved hostname of the client making the request - this is not the same thing. (In order to get the hostname here, the server is required to make a DNS lookup of the client's IP address - this is disabled on some shared servers because of the additional overhead it places on the server). For most users this simply refers to the ISP through which they are accessing the internet.

Also, Order, Deny and Allow directives are Apache 2.2 directives. If you are on Apache 2.4 then you should probably be using the Require ... directives instead. Unless you are maintaining backwards compatibility with a server that is still using the old Apache 2.2 directives (the two should not be mixed).

On Apache 2.4 you can use Apache Expressions... so only use HTTP authentication if the client's IP is not 11.22.33.44 and xxx.example.com is not the host being requested.

For example:

<If "%{HTTP_HOST} != 'xxx.example.com' && %{REMOTE_ADDR} != '11.22.33.44'">
    AuthType Basic
    AuthName "Entwurf"
    AuthUserFile /my/path/to/.htpasswd
    Require valid-user
</If>

You also appeared to be using curly quotes in the AuthName directive - maybe this was just a formatting issue in your question?


问:
Query database with Ajax and classic ASP
I'm trying to modify a script from w3scools to use a combination of asp and ajax to query a database and return results.

Here is the code:

```<code><html>
<head>
<script type="text/javascript">
function showCustomer(str)
{
    var xmlhttp;
    if (str=="")
    {
        document.getElementById("txtHint").innerHTML="";
        return;
    }
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","getcustomer.asp?q="+str,true);
    xmlhttp.send();
}
</script>
</head>
<body>

<form action="">
    <select name="customers" onchange="showCustomer(this.value)">
        <option value="">Select a customer:</option>
        <option value="ALFKI">Alfreds Futterkiste</option>
    </select>
</form>
<br />

<div id="txtHint">Customer info will be listed here...</div>

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

I would like to replace the select field with 2 input fields.

Can someone please tell me how to amend the javascript so that both the input values are passed with the querystring and what needs to be changed on the form to call the function.

Thanks

答:
Depends on how you want to do it.  Right now the script itself is triggered by the change event of the select element.  If you replace that element, you'll need a different event to trigger the script.  A button, perhaps?  If that's the case, then probably the easiest way to do this is with jQuery:

```<code>Field 1: <input id="text1" type="text" />
Field 2: <input id="text2" type="text" />
<input id="buttonSend" type="button" value="Send" />
<script type="text/javascript">
  $(document).ready(function() {
    $('#buttonSend').click(function() {
      $.get('getcustomer.asp?text1=' +
          $('#text1').val() + '&text2=' + $('#text2').val()
      );
    });
  });
</script>
</code>```

There's more you can do with the $.get() function, documented here, which is really just shorthand for the $.ajax() function, documented here.  The former is shorter, the latter gives you more options and control.

(Note also that if you want to use other JavaScript libraries as well, you may want to replace the $ alias with jQuery in the above code to avoid confusion.)

Notice a benefit here is that it de-couples the script (which can be put in a separate file if need be) from the markup.  As an overall design paradigm, this is generally preferred over the onchange="someFunctionCall()" syntax in the markup.

Body:
I'm trying to modify a script from w3scools to use a combination of asp and ajax to query a database and return results.

Here is the code:

<form action="">
    <select name="customers" onchange="showCustomer(this.value)">
        <option value="">Select a customer:</option>
        <option value="ALFKI">Alfreds Futterkiste</option>
    </select>
</form>

Customer info will be listed here...

I would like to replace the select field with 2 input fields.

Can someone please tell me how to amend the javascript so that both the input values are passed with the querystring and what needs to be changed on the form to call the function.

Thanks

Body:
Depends on how you want to do it.  Right now the script itself is triggered by the change event of the select element.  If you replace that element, you'll need a different event to trigger the script.  A button, perhaps?  If that's the case, then probably the easiest way to do this is with jQuery:

Field 1: <input id="text1" type="text" />
Field 2: <input id="text2" type="text" />
<input id="buttonSend" type="button" value="Send" />
<script type="text/javascript">
  $(document).ready(function() {
    $('#buttonSend').click(function() {
      $.get('getcustomer.asp?text1=' +
          $('#text1').val() + '&text2=' + $('#text2').val()
      );
    });
  });
</script>

There's more you can do with the $.get() function, documented here, which is really just shorthand for the $.ajax() function, documented here.  The former is shorter, the latter gives you more options and control.

(Note also that if you want to use other JavaScript libraries as well, you may want to replace the $ alias with jQuery in the above code to avoid confusion.)

Notice a benefit here is that it de-couples the script (which can be put in a separate file if need be) from the markup.  As an overall design paradigm, this is generally preferred over the onchange="someFunctionCall()" syntax in the markup.


问:
Exclude category from list
i need to exclude a category from category list in wordpress. i have used below code.
wants to exclude category = "featured_home"

```<code>   $categories = get_categories();
   foreach($categories as $category) {
   echo '<button class="button" data-filter=".' .$category->name. '">'.$category->name.'</button>';
                    }
</code>```

Please help me as soon as possible.

Thanks in advance.

答:
By using wp_get_post_categories, you can specify one or more category ID's you want to exclude:</p>

```<code>$categories = wp_get_post_categories($test->ID, array('exclude' => [1, 2, 3]); // It should exclude categories with ID 1, 2, and 3
</code>```

Title: Exclude category from list

Body:
i need to exclude a category from category list in wordpress. i have used below code.
wants to exclude category = "featured_home"

   $categories = get_categories();
   foreach($categories as $category) {
   echo '<button class="button" data-filter=".' .$category->name. '">'.$category->name.'</button>';
                    }

Please help me as soon as possible.

Thanks in advance.

Body:
By using wp_get_post_categories, you can specify one or more category ID's you want to exclude:

$categories = wp_get_post_categories($test->ID, array('exclude' => [1, 2, 3]); // It should exclude categories with ID 1, 2, and 3


问:
Using Apache as a proxy for backend JavaScript (Strapi) server
I am trying to get a Strapi.io installation set up so that it works on an existing Apache site running on Port 80.

Details:

The Strapi server is running on Port 1337.

The Strapi server has both a front page at / and an admin panel /admin

My Apache site is running at http://example.com on port 80

I have edited my apache configuration file and added the following lines:

```<code>ProxyPass /admin http://localhost:1337/admin
ProxyPassReverse /admin http://localhost:1337/admin

ProxyPass /api http://localhost:1337/
ProxyPassReverse /api http://localhost:1337/
</code>```

Currently that works fine for the /api page, but not the admin page. On the Admin page I get the following console errors:

main.js:40 Uncaught (in promise) SyntaxError: Unexpected token < in
  JSON at position 0
      at r (main.js:40) r @ main.js:40 Promise.then (async) u @ main.js:1 ./node_modules/strapi-helper-plugin/lib/src/app.js @
  main.js:40 t @ main.js:1 (anonymous) @ main.js:1 (anonymous) @
  main.js:1

main.js:45 Uncaught (in promise) SyntaxError: Unexpected
  token < in JSON at position 0
      at t (main.js:45) t @ main.js:45 Promise.then (async) u @ main.js:1 ./node_modules/strapi-helper-plugin/lib/src/app.js @
  main.js:45 a @ main.js:1 (anonymous) @ main.js:1 (anonymous) @

main.js:1 main.js:40 Uncaught (in promise) SyntaxError: Unexpected
  token < in JSON at position 0
      at n (main.js:40)

If I refresh the page, some or all of the main.js show as admin.js. Not sure if it makes a difference:

main.js:40 Uncaught (in promise) SyntaxError: Unexpected token < in
  JSON at position 0
      at r (main.js:40) r @ main.js:40 Promise.then (async) u @ main.js:1 ./node_modules/strapi-helper-plugin/lib/src/app.js @
  main.js:40 t @ main.js:1 (anonymous) @ main.js:1 (anonymous) @
  main.js:1

admin:1 Uncaught (in promise) SyntaxError: Unexpected token
  < in JSON at position 0 Promise.then (async) u @ main.js:1
  ./node_modules/strapi-helper-plugin/lib/src/app.js @ main.js:40 t @
  main.js:1 (anonymous) @ main.js:1 (anonymous) @ main.js:1

admin:1
  Uncaught (in promise) SyntaxError: Unexpected token < in JSON at
  position 0

Why am I experiencing this problem. What do I have to do to get this working correctly with my Apache server?

To clarify:

This was a very simple two minute install. I have not started to add any content to the site yet. I'm just trying to get the admin panel to work through Apache.

答:
You're probably running into issues because Strapi doesn't currently implement URL prefixes.

To get around this, you will probably want to use a subdomain or run Strapi on port 80 from the root directory with "/" instead of "/api". If you have other projects or apps on the same Apache server, you can use ProxyPassMatch to ignore those paths. For example:

```<code>ProxyPassMatch ^/otherproject !
ProxyPass "/" http://localhost:1337/
ProxyPassReverse "/" http://localhost:1337/
</code>```

In this case the "/admin" route will also work without further modifications.

Alternatively, some people use Strapi middleware to apply prefixes to their routes (see example here).

Body:
I am trying to get a Strapi.io installation set up so that it works on an existing Apache site running on Port 80.

Details:

The Strapi server is running on Port 1337.

The Strapi server has both a front page at / and an admin panel /admin

My Apache site is running at http://example.com on port 80

I have edited my apache configuration file and added the following lines:

ProxyPass /admin http://localhost:1337/admin
ProxyPassReverse /admin http://localhost:1337/admin

ProxyPass /api http://localhost:1337/
ProxyPassReverse /api http://localhost:1337/

Currently that works fine for the /api page, but not the admin page. On the Admin page I get the following console errors:

main.js:40 Uncaught (in promise) SyntaxError: Unexpected token < in
  JSON at position 0
      at r (main.js:40) r @ main.js:40 Promise.then (async) u @ main.js:1 ./node_modules/strapi-helper-plugin/lib/src/app.js @
  main.js:40 t @ main.js:1 (anonymous) @ main.js:1 (anonymous) @
  main.js:1

main.js:45 Uncaught (in promise) SyntaxError: Unexpected
  token < in JSON at position 0
      at t (main.js:45) t @ main.js:45 Promise.then (async) u @ main.js:1 ./node_modules/strapi-helper-plugin/lib/src/app.js @
  main.js:45 a @ main.js:1 (anonymous) @ main.js:1 (anonymous) @

main.js:1 main.js:40 Uncaught (in promise) SyntaxError: Unexpected
  token < in JSON at position 0
      at n (main.js:40)

If I refresh the page, some or all of the main.js show as admin.js. Not sure if it makes a difference:

main.js:40 Uncaught (in promise) SyntaxError: Unexpected token < in
  JSON at position 0
      at r (main.js:40) r @ main.js:40 Promise.then (async) u @ main.js:1 ./node_modules/strapi-helper-plugin/lib/src/app.js @
  main.js:40 t @ main.js:1 (anonymous) @ main.js:1 (anonymous) @
  main.js:1

admin:1 Uncaught (in promise) SyntaxError: Unexpected token
  < in JSON at position 0 Promise.then (async) u @ main.js:1
  ./node_modules/strapi-helper-plugin/lib/src/app.js @ main.js:40 t @
  main.js:1 (anonymous) @ main.js:1 (anonymous) @ main.js:1

admin:1
  Uncaught (in promise) SyntaxError: Unexpected token < in JSON at
  position 0

Why am I experiencing this problem. What do I have to do to get this working correctly with my Apache server?

To clarify:

This was a very simple two minute install. I have not started to add any content to the site yet. I'm just trying to get the admin panel to work through Apache.

Body:
You're probably running into issues because Strapi doesn't currently implement URL prefixes.

To get around this, you will probably want to use a subdomain or run Strapi on port 80 from the root directory with "/" instead of "/api". If you have other projects or apps on the same Apache server, you can use ProxyPassMatch to ignore those paths. For example:

ProxyPassMatch ^/otherproject !
ProxyPass "/" http://localhost:1337/
ProxyPassReverse "/" http://localhost:1337/

In this case the "/admin" route will also work without further modifications.

Alternatively, some people use Strapi middleware to apply prefixes to their routes (see example here).


问:
How to render the ReactDOM every second?
I'm new to React, I'm trying to follow this ticking clock example but do something a bit different. I'd like the ReactDOM to be rendered in the index.js. Here is my code:

Timer.js:

import React from 'react';

const Timer = () => {
    const tick = () => {
        return new Date().toLocaleTimeString().toString();
    };

    const element = (

Hello World!

It is {tick()} !

    );

    return (
        element
    );
};

export default Timer;```
</div>
</div>
</p>

<p><strong>App.js:</strong> </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>/*jshint esversion: 8 */
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Timer from './Timer'

function App() {
  return (
    <div className="App">
      <Timer />
    </div>
  );
}

export default App;</code>```

index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import App from './App';

setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000);

serviceWorker.unregister();```

But it only prints the current time on screen, not ticking. Why does the code setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000); not work on index.js?

答:
You can use React.useEffect passing an array as second argument, which is the equivalent of componentDidMount.

You then want to use setInterval to set the state every second.

Return a function from useEffect to clear the interval when the component unmounts.

See working codesandbox here.

You code would look as follows:

```<code>const function Timer() {
  const [time, setTime] = React.useState(null);
  React.useEffect(() => {
    const tick = () => {
      return new Date().toLocaleTimeString().toString();
    };
    const intervalId = setInterval(() => {
      setTime(tick());
      return () => clearInterval(intervalId);
    }, 1000);
  }, []);

  return <h2>It is {time} !</h2>;
}
</code>```

Body:
I'm new to React, I'm trying to follow this ticking clock example but do something a bit different. I'd like the ReactDOM to be rendered in the index.js. Here is my code:

Timer.js:

import React from 'react';

const Timer = () => {
    const tick = () => {
        return new Date().toLocaleTimeString().toString();
    };

    const element = (

Hello World!

It is {tick()} !

    );

    return (
        element
    );
};

export default Timer;

App.js:

/*jshint esversion: 8 */
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Timer from './Timer'

function App() {
  return (

      <Timer />

  );
}

export default App;

index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import App from './App';

setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000);

serviceWorker.unregister();

But it only prints the current time on screen, not ticking. Why does the code setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000); not work on index.js?

Body:
You can use React.useEffect passing an array as second argument, which is the equivalent of componentDidMount.

You then want to use setInterval to set the state every second.

Return a function from useEffect to clear the interval when the component unmounts.

See working codesandbox here.

You code would look as follows:

const function Timer() {
  const [time, setTime] = React.useState(null);
  React.useEffect(() => {
    const tick = () => {
      return new Date().toLocaleTimeString().toString();
    };
    const intervalId = setInterval(() => {
      setTime(tick());
      return () => clearInterval(intervalId);
    }, 1000);
  }, []);

  return <h2>It is {time} !</h2>;
}


问:
Clarify Objective-C categories in separate file
I have added some methods to existing class in engine by category. This category is declared and implemented in my separate files. Then I include these files (but all engine files stay not modified, so only original declarations are included in engine). Engine is built into static lib and linked with my app. When I call a method of my category the app crashes with error "unrecognized selector sent to instance...". But if I declare category in file with original engine class all works.

Why selector of category is not recognized if it's declared and implemented in separate files? Does order of including files matter?

答:
This is a linker bug where category methods declared in their own compilation unit are not correctly linked into an app. See the technical note from apple here:

Building Objective-C static libraries with categories

You must either specify the linker flag -all_load in your application, or a 'hacky' technique would be to define a macro which will define a dummy class and implementation, and call that macro in each category implementation:

```<code>#define FIX_CATEGORY_LINKER_BUG(name) \
    @interface FIX_CATEGORY_LINKER_BUG_##name @end \
    @implementation FIX_CATEGORY_LINKER_BUG_##name @end
</code>```

And use it as follows above your category implementation:

```<code>FIX_CATEGORY_LINKER_BUG(NSStringMyAdditions)

@implementation NSString (MyAdditions)
// ...
</code>```

Body:
This is a linker bug where category methods declared in their own compilation unit are not correctly linked into an app. See the technical note from apple here:

Building Objective-C static libraries with categories

You must either specify the linker flag -all_load in your application, or a 'hacky' technique would be to define a macro which will define a dummy class and implementation, and call that macro in each category implementation:

#define FIX_CATEGORY_LINKER_BUG(name) \
    @interface FIX_CATEGORY_LINKER_BUG_##name @end \
    @implementation FIX_CATEGORY_LINKER_BUG_##name @end

And use it as follows above your category implementation:

FIX_CATEGORY_LINKER_BUG(NSStringMyAdditions)

@implementation NSString (MyAdditions)
// ...


问:
Laravel 6 api 401 Unauthorized from ajax
Laravel 6
Ajax
MY api route:

```<code>Route::middleware(['auth:api'])->group(function(){
   Route::resource('academic_year','AcademicYear\AcademicYearController')->except(['create', 'edit']);
}
</code>```

There ajax request and still get unauthorized this my request:

```<code>var token = "{{Auth()->user()->api_token}}";
    console.log('token: '+token);
    var basicData = {
      'headers': {
          'Authorization' : 'Bearer '+token,
          'Accept' : 'application/json',
      },
      '_token': "{{csrf_token()}}"
    };
    var data = basicData;
    data['title'] = $('input.academic-title').val();
    console.log(data);
    $.ajax({
      url: "{{route('academic_year.index')}}",
      method: 'POST',
      datatype: 'application/json',
      data: basicData,
      success: function(data, status, xhr){
       console.log(status);
      },
      error: function(xhr, status, message){
        console.log(status);
      },
    });
</code>```

I don't know where the problem!!

答:
I think the issue is sending token with header. can you try like this way to set token with header

var token = "{{Auth()->user()->api_token}}";
    var basicData = {
      '_token': "{{csrf_token()}}"
    };
    var data = basicData;
    data['title'] = $('input.academic-title').val();
    console.log(data);
    $.ajax({
      url: "{{route('academic_year.index')}}",
      method: 'POST',
      headers: {"Authorization": 'Bearer '+token,'Accept' : 'application/json'}
      datatype: 'application/json',
      data: basicData,
      success: function(data, status, xhr){
       console.log(status);
      },
      error: function(xhr, status, message){
        console.log(status);
      },
    });```

Body:
Laravel 6
Ajax
MY api route:

Route::middleware(['auth:api'])->group(function(){
   Route::resource('academic_year','AcademicYear\AcademicYearController')->except(['create', 'edit']);
}

There ajax request and still get unauthorized this my request:

var token = "{{Auth()->user()->api_token}}";
    console.log('token: '+token);
    var basicData = {
      'headers': {
          'Authorization' : 'Bearer '+token,
          'Accept' : 'application/json',
      },
      '_token': "{{csrf_token()}}"
    };
    var data = basicData;
    data['title'] = $('input.academic-title').val();
    console.log(data);
    $.ajax({
      url: "{{route('academic_year.index')}}",
      method: 'POST',
      datatype: 'application/json',
      data: basicData,
      success: function(data, status, xhr){
       console.log(status);
      },
      error: function(xhr, status, message){
        console.log(status);
      },
    });

I don't know where the problem!!