问:
Generics : run-time ADT for types with instances
Is it possible with Haskell / GHC, to extract an algebraic data type representing all types with Eq and Ord instances ?  This would probably need Generics, Typeable, etc.

What I would like is something like :

```<code>data Data_Eq_Ord = Data_String String
                 | Data_Int Int
                 | Data_Bool Bool
                 | ...
deriving (Eq, Ord)
</code>```

For all types known to have instances for Eq and Ord. If it makes the solution easier, we can limit our scope to Ord instances, since Eq is implied by Ord. But is would be interesting to know if constraints intersection is possible.

This data type would be useful because it gives the possibility to use it where Eq and Ord constraints are required, and pattern-match at runtime to refine on types.

I would need this to implement a generic Map Key Value, where Key would be this type, in a Document Indexing library, where the keys and their type is known at run-time. This library is here. For the moment I worked around the issue by defining a data DocIndexKey, and a FieldKey class, but this is not fully satisfactory since it requires boilerplate and can't cover all legit candidates.

Any good alternative approach to this situation is welcome. For some reasons, I prefer to avoid Template Haskell.

答:
Well, it's not an ADT, but this definitely works:

```<code>data Satisfying c = forall a. c a => Satisfy a
class (l a, r a) => And l r a where
instance (l a, r a) => And l r a where

ex :: [Satisfying (Typeable `And` Show `And` Ord)]
ex = [ Satisfy (7 :: Int)
     , Satisfy "Hello"
     , Satisfy (5 :: Int)
     , Satisfy [10..20 :: Int]
     , Satisfy ['a'..'z']
     , Satisfy ((), 'a')]

-- An example of use, with "complicated" logic
data With f c = forall a. c a => With (f a)
--                 vvvvvvvvvvvvvvvvvvvvvvvvvv QuantifiedConstraints chokes on this, which is probably a bug...
partitionTypes :: (forall a. c a => TypeRep a) -> [Satisfying c] -> [[] `With` c]
partitionTypes rep = foldr go []
   where go (Satisfy x) [] = [With [x]]
         go x'@(Satisfy (x :: a)) (xs'@(With (xs :: [b])) : xss) =
             case testEquality rep rep :: Maybe (a :~: b) of
                 Just Refl -> With (x : xs) : xss
                 Nothing -> xs' : go x' xss

main :: IO ()
main = traverse_ (\(With xs) -> print (sort xs)) $ partitionTypes typeRep ex
</code>```

Exhaustivity is much harder. Perhaps with a plugin, you could get GHC to do it, but why bother? I don't believe GHC actually tries to keep track of what types it has seen. In particular, you'd have to scan all modules in the project and its dependencies, even those that haven't been loaded by the module containing the type definition. You'd have to implement it from the ground-up. And, as this answer shows, I very much doubt you would actually be able to use such exhaustivity for anything that you can't already do by just taking the open universe as it is.

Body:
Is it possible with Haskell / GHC, to extract an algebraic data type representing all types with Eq and Ord instances ?  This would probably need Generics, Typeable, etc.

What I would like is something like :

data Data_Eq_Ord = Data_String String
                 | Data_Int Int
                 | Data_Bool Bool
                 | ...
deriving (Eq, Ord)

For all types known to have instances for Eq and Ord. If it makes the solution easier, we can limit our scope to Ord instances, since Eq is implied by Ord. But is would be interesting to know if constraints intersection is possible.

This data type would be useful because it gives the possibility to use it where Eq and Ord constraints are required, and pattern-match at runtime to refine on types.

I would need this to implement a generic Map Key Value, where Key would be this type, in a Document Indexing library, where the keys and their type is known at run-time. This library is here. For the moment I worked around the issue by defining a data DocIndexKey, and a FieldKey class, but this is not fully satisfactory since it requires boilerplate and can't cover all legit candidates.

Any good alternative approach to this situation is welcome. For some reasons, I prefer to avoid Template Haskell.

Body:
Well, it's not an ADT, but this definitely works:

data Satisfying c = forall a. c a => Satisfy a
class (l a, r a) => And l r a where
instance (l a, r a) => And l r a where

ex :: [Satisfying (Typeable `And` Show `And` Ord)]
ex = [ Satisfy (7 :: Int)
     , Satisfy "Hello"
     , Satisfy (5 :: Int)
     , Satisfy [10..20 :: Int]
     , Satisfy ['a'..'z']
     , Satisfy ((), 'a')]

-- An example of use, with "complicated" logic
data With f c = forall a. c a => With (f a)
--                 vvvvvvvvvvvvvvvvvvvvvvvvvv QuantifiedConstraints chokes on this, which is probably a bug...
partitionTypes :: (forall a. c a => TypeRep a) -> [Satisfying c] -> [[] `With` c]
partitionTypes rep = foldr go []
   where go (Satisfy x) [] = [With [x]]
         go x'@(Satisfy (x :: a)) (xs'@(With (xs :: [b])) : xss) =
             case testEquality rep rep :: Maybe (a :~: b) of
                 Just Refl -> With (x : xs) : xss
                 Nothing -> xs' : go x' xss

main :: IO ()
main = traverse_ (\(With xs) -> print (sort xs)) $ partitionTypes typeRep ex

Exhaustivity is much harder. Perhaps with a plugin, you could get GHC to do it, but why bother? I don't believe GHC actually tries to keep track of what types it has seen. In particular, you'd have to scan all modules in the project and its dependencies, even those that haven't been loaded by the module containing the type definition. You'd have to implement it from the ground-up. And, as this answer shows, I very much doubt you would actually be able to use such exhaustivity for anything that you can't already do by just taking the open universe as it is.


来源: stackexchange

问:
JScript JSON Array access
I have a JSON array stored in a file data.json - I used the code that was recommended here for a similar problem, explain why when I try to access the array later in the program it tells me it is undefined.

```<code>    var chartData = (function () {
                var chartData = null;
                $.ajax({
                    'async': false,
                    'global': false,
                    'url': "data.json",
                    'dataType': "json",
                    'success': function (data) {
                        chartData = data;
                    }
             });
             return chartData;
        })();
</code>```

Help appreciated!

Edit; For accessing, I'm using the array as a series in dojo-chart: http://dojotoolkit.org/grids-charts

After I attempt to initialize var chartData, the only other point I use it is in:

```<code>    chart.addSeries("Name",chartData);
</code>```

Edit #2; In case it matters the data.json file is formatted like:

```<code>    [#, #, #, ... , #]
</code>```

答:
Perhaps because it was not successful? I found it very useful to debug using console.log (firebug, or most modern web developer panels in chrome or ie support it)

you can try this piece of code to debug it.

```<code>var chartData = (function () {
            var chartData = null;
            $.ajax({
                'async': false,
                'global': false,
                'url': "data.json",
                'dataType': "json",
                'success': function (data) {
                    console.log('success');
                    console.log(data);
                    chartData = data;
                }
                error: function (data) { console.log('error'); console.log(data); },
         });
         return chartData;
})();
</code>```

ContentLicense: CC BY-SA 3.0

Title: JScript JSON Array access

Body:
I have a JSON array stored in a file data.json - I used the code that was recommended here for a similar problem, explain why when I try to access the array later in the program it tells me it is undefined.

    var chartData = (function () {
                var chartData = null;
                $.ajax({
                    'async': false,
                    'global': false,
                    'url': "data.json",
                    'dataType': "json",
                    'success': function (data) {
                        chartData = data;
                    }
             });
             return chartData;
        })();

Help appreciated!

Edit; For accessing, I'm using the array as a series in dojo-chart: http://dojotoolkit.org/grids-charts

After I attempt to initialize var chartData, the only other point I use it is in:

    chart.addSeries("Name",chartData);

Edit #2; In case it matters the data.json file is formatted like:

    [#, #, #, ... , #]

Body:
Perhaps because it was not successful? I found it very useful to debug using console.log (firebug, or most modern web developer panels in chrome or ie support it)

you can try this piece of code to debug it.

var chartData = (function () {
            var chartData = null;
            $.ajax({
                'async': false,
                'global': false,
                'url': "data.json",
                'dataType': "json",
                'success': function (data) {
                    console.log('success');
                    console.log(data);
                    chartData = data;
                }
                error: function (data) { console.log('error'); console.log(data); },
         });
         return chartData;
})();


问:
Should we put a timer on server or mobile?
I am working on both server side (beginning) and mobile side. There is an interesting thing but I am lack of experience to make a decision. I am appreciated any helps from you guys.

```<code>I have to send an email after 50 minutes
</code>```

1/ If we have a timer for each email on server, then 1000 users, 1000 timers?

2/ If we handle it on mobile, there is a case that everything of the app is killed by OS before sending email.

The question is: server and mobile, which one is better?

Please let me know your solution. Thank you in advanced!

答:
This is better to implement the timer on your server. The negative possibility that would happen and block the function if you implement the timer on the device is when the device is on power-off mode or the device couldn't connect to the server to trigger for sending the email.

The server instance is should long-lived, this is should never go down, and this could be more reliable for your case, as @Harish ST answer, you can take a profit from cron job / cron task.

ContentLicense: CC BY-SA 4.0

Body:
I am working on both server side (beginning) and mobile side. There is an interesting thing but I am lack of experience to make a decision. I am appreciated any helps from you guys.

I have to send an email after 50 minutes

1/ If we have a timer for each email on server, then 1000 users, 1000 timers?

2/ If we handle it on mobile, there is a case that everything of the app is killed by OS before sending email.

The question is: server and mobile, which one is better?

Please let me know your solution. Thank you in advanced!


问:
How to pass cardElement to createPaymentMethod(cardElement, customerId, priceId) React+Stripe?
I have their <CardSection /> element in a SignUp form component, on submit I authenticate the user, create the customer, but can't figure out how to pass the <CardSection /> to the createPaymentMethod function.

Some of what I have:
SignUp form:

```<code>handleSignUp = (event) => {
    event.preventDefault();
    let cardElement = document.getElementById('#cardElement');
    signUp(this.state.email, this.state.password, cardElement);
}
</code>```

Where signUp() looks like:

```<code>import firebase from './firebase.js';
import { createCustomer } from './createCustomer.js';
import { createPaymentMethod } from './createPaymentMethod.js';

export function signUp(email, password) {
    firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
        // Handle Errors here.
        console.log(`Error in signUp ${error.code}: ${error.message}`);
    });

    createCustomer().then((customer) => {
        let customerId = customer.customer.id;
        let priceId = "price_HIsuBNTXc2NQ7L";
        createPaymentMethod(cardElement, customerId, priceId);
    });
}
</code>```

This doesn't work (I get TypeError: JSON.stringify cannot serialize cyclic structures.), and I think I'm doing this plain incorrectly. What's the right way to do this part?

The documentation (https://stripe.com/docs/billing/subscriptions/fixed-price) seems to skip this step going from step 4 to 5. I'm pretty green with Stripe and React so take it easy on me. What am I missing here?

答:
I believe Erwan Daniel's comment is correct and your signUp function is missing an argument.  Its signature should probably be:

```<code>export function signUp(email, password, cardElement)
</code>```

Body:
I have their <CardSection /> element in a SignUp form component, on submit I authenticate the user, create the customer, but can't figure out how to pass the <CardSection /> to the createPaymentMethod function.

Some of what I have:
SignUp form:

handleSignUp = (event) => {
    event.preventDefault();
    let cardElement = document.getElementById('#cardElement');
    signUp(this.state.email, this.state.password, cardElement);
}

Where signUp() looks like:

import firebase from './firebase.js';
import { createCustomer } from './createCustomer.js';
import { createPaymentMethod } from './createPaymentMethod.js';

export function signUp(email, password) {
    firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
        // Handle Errors here.
        console.log(`Error in signUp ${error.code}: ${error.message}`);
    });

    createCustomer().then((customer) => {
        let customerId = customer.customer.id;
        let priceId = "price_HIsuBNTXc2NQ7L";
        createPaymentMethod(cardElement, customerId, priceId);
    });
}

This doesn't work (I get TypeError: JSON.stringify cannot serialize cyclic structures.), and I think I'm doing this plain incorrectly. What's the right way to do this part?

The documentation (https://stripe.com/docs/billing/subscriptions/fixed-price) seems to skip this step going from step 4 to 5. I'm pretty green with Stripe and React so take it easy on me. What am I missing here?

Body:
I believe Erwan Daniel's comment is correct and your signUp function is missing an argument.  Its signature should probably be:

export function signUp(email, password, cardElement)


问:
How to build a TFIDF Vectorizer given a corpus and compare its results using Sklearn?
Sklearn does few tweaks in the implementation of its version of TFIDF vectorizer, so to replicate the exact results you would need to add following things to your custom implementation of tfidf vectorizer:

Sklearn has its vocabulary generated from idf sroted in alphabetical order

Sklearn formula of idf is different from the standard textbook formula. Here the constant "1" is added to the numerator and denominator of the idf as if an extra document was seen containing every term in the collection exactly once, which prevents zero divisions. IDF(t)=1+(loge((1 + Total number of documents in collection)/(1+Number of documents with term t in it)).

Sklearn applies L2-normalization to its output matrix.

The final output of sklearn tfidf vectorizer is a sparse matrix.

Now given the following corpus:

```<code>corpus = [
     'this is the first document',
     'this document is the second document',
     'and this is the third one',
     'is this the first document',
]
</code>```

Sklearn implementation:

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()
vectorizer.fit(corpus)
skl_output = vectorizer.transform(corpus)
print(vectorizer.get_feature_names())
output : [‘and’, ‘document’, ‘first’, ‘is’, ‘one’, ‘second’, ‘the’, ‘third’, ‘this’]

print(skl_output[0])
</code>```

Output:

(0, 8)    0.38408524091481483
(0, 6)    0.38408524091481483
(0, 3)    0.38408524091481483
(0, 2)    0.5802858236844359
(0, 1)    0.46979138557992045
```

<p>I need to replicate the above result using a custom implementation i.e write code in simple python.</p>

<p>I wrote the following code:</p>

```from collections import Counter
from tqdm import tqdm
from scipy.sparse import csr_matrix
import math
import operator
from sklearn.preprocessing import normalize
import numpy

# The fit function helps in creating a vocabulary of all the unique words in the corpus

def fit(dataset):
  storage_set = set()
  if isinstance(dataset,list):
    for document in dataset:
      for word in document.split(" "):
        storage_set.add(word)
  storage_set = sorted(list(storage_set))
  vocab = {j:i for i,j in enumerate(storage_set)}
  return vocab

vocab =  fit(corpus)
print(vocab)
output : {‘and’: 0, ‘document’: 1, ‘first’: 2, ‘is’: 3, ‘one’: 4, ‘second’: 5, ‘the’: 6, ‘third’: 7, ‘this’: 8}
This output is matching with the output of the sklearn above
#Returs a sparse matrix of the all non-zero values along with their row and col
def transform(dataset,vocab):
  row = []
  col = []
  values = []
  for ibx,document in enumerate(dataset):
    word_freq = dict(Counter(document.split()))
    for word, freq in word_freq.items():
      col_index = vocab.get(word,-1)
      if col_index != -1:
        if len(word)<2:
          continue
        col.append(col_index)
        row.append(ibx)
        td = freq/float(len(document)) # the number of times a word occured in a document
        idf_ = 1+math.log((1+len(dataset))/float(1+idf(word)))
        values.append((td) * (idf_))
    return normalize(csr_matrix( ((values),(row,col)), shape=(len(dataset),len(vocab))),norm='l2' )

print(transform(corpus,vocab))
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>(0, 1)    0.3989610517704845
(0, 2)    0.602760579899478
(0, 3)    0.3989610517704845
(0, 6)    0.3989610517704845
(0, 8)    0.3989610517704845
</code>```

As you can see this output is not matching with the values from the sklearn’s output. I went through the logic several times, tried debugging everywhere. However, couldn’t locate why my custom implementation is not matching the output by sklearn.
Would appreciate any insights.

答:
Can you please check idf() in idf_ = 1+math.log((1+len(dataset))/float(1+idf(word))).
While trying to replicate your results, my output matched with that of sklearn without doing any significant change in your transform function. So I think, there must be any problem in your idf() which must return the no. of rows in which the word w is present in the corpus

Body:
Sklearn does few tweaks in the implementation of its version of TFIDF vectorizer, so to replicate the exact results you would need to add following things to your custom implementation of tfidf vectorizer:

Sklearn has its vocabulary generated from idf sroted in alphabetical order

Sklearn formula of idf is different from the standard textbook formula. Here the constant "1" is added to the numerator and denominator of the idf as if an extra document was seen containing every term in the collection exactly once, which prevents zero divisions. IDF(t)=1+(loge((1 + Total number of documents in collection)/(1+Number of documents with term t in it)).

Sklearn applies L2-normalization to its output matrix.

The final output of sklearn tfidf vectorizer is a sparse matrix.

Now given the following corpus:

corpus = [
     'this is the first document',
     'this document is the second document',
     'and this is the third one',
     'is this the first document',
]

Sklearn implementation:

from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()
vectorizer.fit(corpus)
skl_output = vectorizer.transform(corpus)
print(vectorizer.get_feature_names())
output : [‘and’, ‘document’, ‘first’, ‘is’, ‘one’, ‘second’, ‘the’, ‘third’, ‘this’]

print(skl_output[0])

Output:

(0, 8)    0.38408524091481483
(0, 6)    0.38408524091481483
(0, 3)    0.38408524091481483
(0, 2)    0.5802858236844359
(0, 1)    0.46979138557992045

I need to replicate the above result using a custom implementation i.e write code in simple python.

I wrote the following code:

from collections import Counter
from tqdm import tqdm
from scipy.sparse import csr_matrix
import math
import operator
from sklearn.preprocessing import normalize
import numpy

# The fit function helps in creating a vocabulary of all the unique words in the corpus

def fit(dataset):
  storage_set = set()
  if isinstance(dataset,list):
    for document in dataset:
      for word in document.split(" "):
        storage_set.add(word)
  storage_set = sorted(list(storage_set))
  vocab = {j:i for i,j in enumerate(storage_set)}
  return vocab

vocab =  fit(corpus)
print(vocab)
output : {‘and’: 0, ‘document’: 1, ‘first’: 2, ‘is’: 3, ‘one’: 4, ‘second’: 5, ‘the’: 6, ‘third’: 7, ‘this’: 8}
This output is matching with the output of the sklearn above
#Returs a sparse matrix of the all non-zero values along with their row and col
def transform(dataset,vocab):
  row = []
  col = []
  values = []
  for ibx,document in enumerate(dataset):
    word_freq = dict(Counter(document.split()))
    for word, freq in word_freq.items():
      col_index = vocab.get(word,-1)
      if col_index != -1:
        if len(word)<2:
          continue
        col.append(col_index)
        row.append(ibx)
        td = freq/float(len(document)) # the number of times a word occured in a document
        idf_ = 1+math.log((1+len(dataset))/float(1+idf(word)))
        values.append((td) * (idf_))
    return normalize(csr_matrix( ((values),(row,col)), shape=(len(dataset),len(vocab))),norm='l2' )

print(transform(corpus,vocab))

Output:

(0, 1)    0.3989610517704845
(0, 2)    0.602760579899478
(0, 3)    0.3989610517704845
(0, 6)    0.3989610517704845
(0, 8)    0.3989610517704845

As you can see this output is not matching with the values from the sklearn’s output. I went through the logic several times, tried debugging everywhere. However, couldn’t locate why my custom implementation is not matching the output by sklearn.
Would appreciate any insights.


问:
Copy data activity in Azure Data Factory
I have an adf pipeline that uses copy data activity for copying data from blob storage to table storage. This pipeline runs on a trigger once every day. I'm curious to know how this copy data activity actually works. During pipeline run, does it clear the table and copy data from blob to table or does it just add any updated rows to table after comparison?

For example:

After 1st run, table contains below rows:

```<code>Row1 xyz 1

Row2 abc **2**
</code>```

Now let's say rows in blob are updated as follows:

```<code>Row1 xyz 1

Row2 abc **5**
</code>```

During 2nd run, does it clear table and  store the above data or only update Row2 with values abc and "5" instead of "2"

答:
ADF copy activity doesn't update any existing rows in the table. It is an append only process. So, If your table has primary key constraint, the copy activity will fail.

To do an upsert process, you can either use mapping data flow or stored procedure.

Body:
I have an adf pipeline that uses copy data activity for copying data from blob storage to table storage. This pipeline runs on a trigger once every day. I'm curious to know how this copy data activity actually works. During pipeline run, does it clear the table and copy data from blob to table or does it just add any updated rows to table after comparison?

For example:

After 1st run, table contains below rows:

Row1 xyz 1

Row2 abc **2**

Now let's say rows in blob are updated as follows:

Row1 xyz 1

Row2 abc **5**

During 2nd run, does it clear table and  store the above data or only update Row2 with values abc and "5" instead of "2"


问:
How to get menu reference from an activity
I am writing JUnit test scripts for an Android project. What I intent to test is the options menu items (you know, the menu invoked by pressing menu key) from an activity.

However, in our project the menu is generated dynamically from some internet content.
Most importantly, the Menu object is a private variable in our activity object.

Now my question is, how can I verify the this menu (verify its number of menuitems, text on each items, etc).

答:
The way you'd typically do this is make the members package private (no qualifier) in Java, then have your junit test live in the same Java package as the class that hosts the menu (probably your activity).

The unit test doesn't have to by physically co-located in the same same package folder, as long as both classes have the same package at runtime.


问:
Undefined value when calling function in Firestore
I'm using Firestore, and wrote the following code:

```<code>export function getAllServices(uid) {
  let services = [];
  firestore.collection('users').doc(uid).collection('services').get().then(snapshot => {
    snapshot.docs.forEach(doc => {
      services.push(doc.data());
      console.log(services);
      return services;
    })
  })
}
</code>```

The function works b/c console.log returns the array I want. However, when I call it like this

```<code>const uid = 'SgUaycgJqzLbdcrOhjQtgcDzddL2';
  const services = getAllServices(uid);
  console.log(services);
</code>```

the console log always returns as undefined. Any ideas?

答:
You already seem to know the cause of the problem, given that you tagged your question with asynchronous. Data is loaded from Firestore asynchronously, and your return services; doesn't in any way return a value from getAllServices. The only way to return something getAllServices is in the first level of code in there, but at that point your then() callback won't have been called yet.

The solution is to bubble up the value from inside the then() callback, and return it as a promise.

```<code>export function getAllServices(uid) {
  return firestore.collection('users').doc(uid).collection('services').get().then(snapshot => {
    let services = [];
    snapshot.docs.forEach(doc => {
      services.push(doc.data());
    })
    return services;
  })
}
</code>```

Then you can call getAllServices and use the result like this:

```<code>const uid = 'SgUaycgJqzLbdcrOhjQtgcDzddL2';
getAllServices(uid).then(function(services) {
  console.log(services);
});
</code>```

You can make the above a bit more familiar looking by using modern JavaScript's async and await keywords

```<code>export async function getAllServices(uid) {
  let services = [];
  return firestore.collection('users').doc(uid).collection('services').get().then(snapshot => {
    let services = [];
    snapshot.docs.forEach(doc => {
      services.push(doc.data());
    })
    return services;
  })
}

const uid = 'SgUaycgJqzLbdcrOhjQtgcDzddL2';
let services = await getAllServices(uid);
console.log(services);
</code>```

Just keep in mind that this is all (wonderfully readable) syntactic sugar, and that the data is still being retrieved asynchronously behind the scenes.

Body:
I'm using Firestore, and wrote the following code:

export function getAllServices(uid) {
  let services = [];
  firestore.collection('users').doc(uid).collection('services').get().then(snapshot => {
    snapshot.docs.forEach(doc => {
      services.push(doc.data());
      console.log(services);
      return services;
    })
  })
}

The function works b/c console.log returns the array I want. However, when I call it like this

const uid = 'SgUaycgJqzLbdcrOhjQtgcDzddL2';
  const services = getAllServices(uid);
  console.log(services);

the console log always returns as undefined. Any ideas?

Body:
You already seem to know the cause of the problem, given that you tagged your question with asynchronous. Data is loaded from Firestore asynchronously, and your return services; doesn't in any way return a value from getAllServices. The only way to return something getAllServices is in the first level of code in there, but at that point your then() callback won't have been called yet.

The solution is to bubble up the value from inside the then() callback, and return it as a promise.

export function getAllServices(uid) {
  return firestore.collection('users').doc(uid).collection('services').get().then(snapshot => {
    let services = [];
    snapshot.docs.forEach(doc => {
      services.push(doc.data());
    })
    return services;
  })
}

Then you can call getAllServices and use the result like this:

const uid = 'SgUaycgJqzLbdcrOhjQtgcDzddL2';
getAllServices(uid).then(function(services) {
  console.log(services);
});

You can make the above a bit more familiar looking by using modern JavaScript's async and await keywords

export async function getAllServices(uid) {
  let services = [];
  return firestore.collection('users').doc(uid).collection('services').get().then(snapshot => {
    let services = [];
    snapshot.docs.forEach(doc => {
      services.push(doc.data());
    })
    return services;
  })
}

const uid = 'SgUaycgJqzLbdcrOhjQtgcDzddL2';
let services = await getAllServices(uid);
console.log(services);

Just keep in mind that this is all (wonderfully readable) syntactic sugar, and that the data is still being retrieved asynchronously behind the scenes.


问:
Cannot get Advanced Custom Fields(ACF) to Laravel
In my project, backend is Wordpress and frontend is Laravel. I have installed “Advanced Custom Fields” plugin to Wordpress becase I want to make some sections dynamic. In normal wordpress site we are getting ACF fields as follows.

```<code><?php
   $title = get_field('title', $id);
?>
   <h2> <?php echo $title; ?></h2>
</code>```

But in a Laravel site, I cannot get Advanced Custom Fields in that manner. Does anyone know a way to get Wordpress backend added Advanced Custom Fields to Laravel frontend?

Thank you.

答:
First of all get_field() function is ACF's function and that won't be available on your Laravel project on front-end.

Steps :
1) Check if your ACF fields are being saved in your WordPress connected database. i.e MySQL.

2) if it's getting saved in your WordPress connected database then check if you are sending that value with your API response. Just check the response of your API. If not then you will have to add the get_field() returned value into your API response.

```<code>//Let's say
$response = $responseData[];
//then just add
$responseData['acf_field_title'] = get_field('title');
//and then send the response.
</code>```

3) Now your ACF value is coming in API's response, your can simply call and use it's stored value.

I hope this helps you.

Body:
In my project, backend is Wordpress and frontend is Laravel. I have installed “Advanced Custom Fields” plugin to Wordpress becase I want to make some sections dynamic. In normal wordpress site we are getting ACF fields as follows.

<?php
   $title = get_field('title', $id);
?>

 <?php echo $title; ?>

But in a Laravel site, I cannot get Advanced Custom Fields in that manner. Does anyone know a way to get Wordpress backend added Advanced Custom Fields to Laravel frontend?

Thank you.

Body:
First of all get_field() function is ACF's function and that won't be available on your Laravel project on front-end.

Steps :
1) Check if your ACF fields are being saved in your WordPress connected database. i.e MySQL.

2) if it's getting saved in your WordPress connected database then check if you are sending that value with your API response. Just check the response of your API. If not then you will have to add the get_field() returned value into your API response.

//Let's say
$response = $responseData[];
//then just add
$responseData['acf_field_title'] = get_field('title');
//and then send the response.

3) Now your ACF value is coming in API's response, your can simply call and use it's stored value.

I hope this helps you.


问:
ZX Spectrum - Issue with RS232 (Serial Port)
I recently got hold of a ZX Spectrum +3 and am trying to get RS232 working with the spectrum. I’ve built a cable (‘BT’ style connector <-> DB9 serial) following the pin out of the cable (Spectrum 128 RS232 data cable) here.
The other end of the cable is connected to the PC using a USB-Serial adapter. I'm using Moserial on Linux to communicate with the Spectrum.

The cable works and I can use LLIST to print BASIC programs over the serial port, but I'm unable to get the Spectrum to read from the serial port reliably - even when enabling hardware handshaking (DTR/CTS) in Moserial.

I wrote a simple program in +3 BASIC to print received characters to the screen. It seems the first character is received OK, but the remaining characters are dropped or become corrupted.

Here is an example of what the Spectrum outputs when attempting to send 'zx spectrum' at 300 baud:

z[dot/box character]. VAL$ [box character]MOVE VAL$ VAL$ ?)

(it seems VAL$ and MOVE$ are each a single character in the Spectrum's ROM)

screenshot:

And the BASIC program which opens the serial port, and prints received characters to the screen:

```<code>10  FORMAT LINE 300
20  FORMAT LPRINT "r"
30  FORMAT LPRINT "e"
40  OPEN #4,"p"
50  PRINT INKEY$#4;
60  GO TO 50
</code>```

I discovered that if I send characters one-by-one from the PC with a long enough delay between them, I can get a much more reliable output from the Spectrum. I tested this with different delays, and 80ms worked the best. I don't really want to use this approach as a solution - it's awfully slow and occasionally some characters are dropped.

Could this be an issue with the Spectrum itself? Or am I missing something in my setup? Something just doesn't seem right, I know there is a program loader for the spectrum over serial - so surely the spectrum must be able to accept serial input without a 80ms delay per character?

答:
In zx spectrum 48k, with interface 1, i must choose how the rs232 will work.
Mode t : text ->rx and tx only character in 7bit
Mode b: byte -> rx and tx full byte (8 bit)

Maybe you must chek that.

On 48k with interface 1
FORMAT "b";9600
Then , the spectrum works in 8bit data at 9600 bauds.

In your code, i dont see how will works.

My best regards.

Body:
I recently got hold of a ZX Spectrum +3 and am trying to get RS232 working with the spectrum. I’ve built a cable (‘BT’ style connector <-> DB9 serial) following the pin out of the cable (Spectrum 128 RS232 data cable) here.
The other end of the cable is connected to the PC using a USB-Serial adapter. I'm using Moserial on Linux to communicate with the Spectrum.

The cable works and I can use LLIST to print BASIC programs over the serial port, but I'm unable to get the Spectrum to read from the serial port reliably - even when enabling hardware handshaking (DTR/CTS) in Moserial.

I wrote a simple program in +3 BASIC to print received characters to the screen. It seems the first character is received OK, but the remaining characters are dropped or become corrupted.

Here is an example of what the Spectrum outputs when attempting to send 'zx spectrum' at 300 baud:

z[dot/box character]. VAL$ [box character]MOVE VAL$ VAL$ ?)

(it seems VAL$ and MOVE$ are each a single character in the Spectrum's ROM)

screenshot:

And the BASIC program which opens the serial port, and prints received characters to the screen:

10  FORMAT LINE 300
20  FORMAT LPRINT "r"
30  FORMAT LPRINT "e"
40  OPEN #4,"p"
50  PRINT INKEY$#4;
60  GO TO 50

I discovered that if I send characters one-by-one from the PC with a long enough delay between them, I can get a much more reliable output from the Spectrum. I tested this with different delays, and 80ms worked the best. I don't really want to use this approach as a solution - it's awfully slow and occasionally some characters are dropped.

Could this be an issue with the Spectrum itself? Or am I missing something in my setup? Something just doesn't seem right, I know there is a program loader for the spectrum over serial - so surely the spectrum must be able to accept serial input without a 80ms delay per character?


问:
Problem with useState, UseEffect when saving data when getting data
I am new to react native and I want on the welcome screen of my application to click on a request to an api using axios and the data is saved in a variable using useState and then use this data in another class (AllProductCategory .js) without having to make the request back to the api.

I am using React native 0.62 hooks react navigation 5 and axios.

I have the following in the Navigation.js file. A context that has a useMemo as its value, which contains a return so that it returns an array with information that it brings from an application using axios. the class looks like this:
In this class skip certain lines of code that have nothing to do with the problem I am currently having.

```<code>export default function Navigation() {
  const [allproducts, setAllproducts] = useState([]);

  useEffect(() => {
    const _loadAllCategories = async () => {
      await axiosClient
        .get("/service/product_available")
        .then(function (response) {
          console.log("Data antes de pasarlo al useState ", response.data);
          setAllproducts(response.data);
          console.log("Los productos son: ", allproducts);
        })
        .catch(function (error) {
          console.log("Error obteniendo el token", error);
        });
    };
    _loadAllCategories();
  }, []);

  const authContext = useMemo(
    () => ({
      getAllProducts: () => {
        return allproducts;
      },
    }),
    []
  );

  return (
    <AuthContext.Provider value={authContext}>
      {state.isLoading ? (
        <SplashStackScreen />
      ) : state.userToken == null ? (
        <PrincipalStackScreen />
      ) : (
        <MyDrawer />
      )}
    </AuthContext.Provider>
  );
}

</code>```

With this file what I want is for the data that brings all the products to be loaded when the splash screen is loading and so when I want to use this data on another screen, just call the context variable and return the data without having to make another request to the api.

Then in the class I implement the call of this data using the context

```<code>const { getAllProducts } = React.useContext(AuthContext);
const allProducts = getAllProducts();
</code>```

The complete class is like this:

```<code>import React, { useState, useEffect } from "react";
import { View, Text, FlatList, StyleSheet, TouchableOpacity, Dimensions, Image } from "react-native";
import { AuthContext } from "../../context";

var { height, width } = Dimensions.get("window");

export default function AllProductCategoryScreen() {
  const { getAllProducts } = React.useContext(AuthContext);
  const allProducts = getAllProducts();

  function Product_Category({ name, image }) {
      console.log("name e image", name);
    return (
      <View>
        <TouchableOpacity>
          <Image style={styles.imageCategory} source={{ uri: image }} />
          <Text>{name}</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <View>
      <Text>Todas las categorias</Text>
      <View style={{ alignItems: "center" }}>
        <FlatList
          scrollEnabled={true}
          numColumns={2}
          data={allProducts}
          renderItem={({ item }) => (
            <Product_Category name={item.name} image={item.imagePath} />
          )}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    </View>
  );
}
</code>```

My app.js is as follows:

```<code>import React from 'react';
import Navigation from "./src/components/Navigation/Navigation"

export default function App() {
  return <Navigation />
}
</code>```

The problem that I currently have is that when I start my app, I show that the request is made with axios and it brings the data correctly, however the useState is not filled with the data that the axios responds to me (it prints []). However if I save changes being in the navigation.js class in visual code the variable allproducts of the navigation class is filled with the data correctly and therefore in the other class where I want to display the data, it paints the data correctly.

I need that when my app loads, the data that the api brings is saved and that when using it in the other class, these data remain so that they can be used and illustrate this data on the screen.

答:
When the function passed to useMemo is created, it captures the first value of allproducts and will always have that value. It will always return [].

In order for useMemo to run again and capture a new value, add that value to the second argument, the array. React will call the memo function whenever a value in that array changes, and then getAllProducts will be created again and capture a new value of allproducts.

```<code> const authContext = useMemo(
    () => ({
      getAllProducts: () => {
        return allproducts;
      },
    }),
    [allproducts]
  );
</code>```

Body:
I am new to react native and I want on the welcome screen of my application to click on a request to an api using axios and the data is saved in a variable using useState and then use this data in another class (AllProductCategory .js) without having to make the request back to the api.

I am using React native 0.62 hooks react navigation 5 and axios.

I have the following in the Navigation.js file. A context that has a useMemo as its value, which contains a return so that it returns an array with information that it brings from an application using axios. the class looks like this:
In this class skip certain lines of code that have nothing to do with the problem I am currently having.

export default function Navigation() {
  const [allproducts, setAllproducts] = useState([]);

  useEffect(() => {
    const _loadAllCategories = async () => {
      await axiosClient
        .get("/service/product_available")
        .then(function (response) {
          console.log("Data antes de pasarlo al useState ", response.data);
          setAllproducts(response.data);
          console.log("Los productos son: ", allproducts);
        })
        .catch(function (error) {
          console.log("Error obteniendo el token", error);
        });
    };
    _loadAllCategories();
  }, []);

  const authContext = useMemo(
    () => ({
      getAllProducts: () => {
        return allproducts;
      },
    }),
    []
  );

  return (
    <AuthContext.Provider value={authContext}>
      {state.isLoading ? (
        <SplashStackScreen />
      ) : state.userToken == null ? (
        <PrincipalStackScreen />
      ) : (
        <MyDrawer />
      )}
    </AuthContext.Provider>
  );
}

With this file what I want is for the data that brings all the products to be loaded when the splash screen is loading and so when I want to use this data on another screen, just call the context variable and return the data without having to make another request to the api.

Then in the class I implement the call of this data using the context

const { getAllProducts } = React.useContext(AuthContext);
const allProducts = getAllProducts();

The complete class is like this:

import React, { useState, useEffect } from "react";
import { View, Text, FlatList, StyleSheet, TouchableOpacity, Dimensions, Image } from "react-native";
import { AuthContext } from "../../context";

var { height, width } = Dimensions.get("window");

export default function AllProductCategoryScreen() {
  const { getAllProducts } = React.useContext(AuthContext);
  const allProducts = getAllProducts();

  function Product_Category({ name, image }) {
      console.log("name e image", name);
    return (
      <View>
        <TouchableOpacity>
          <Image style={styles.imageCategory} source={{ uri: image }} />
          <Text>{name}</Text>
        </TouchableOpacity>
      </View>
    );
  }

  return (
    <View>
      <Text>Todas las categorias</Text>
      <View style={{ alignItems: "center" }}>
        <FlatList
          scrollEnabled={true}
          numColumns={2}
          data={allProducts}
          renderItem={({ item }) => (
            <Product_Category name={item.name} image={item.imagePath} />
          )}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    </View>
  );
}

My app.js is as follows:

import React from 'react';
import Navigation from "./src/components/Navigation/Navigation"

export default function App() {
  return <Navigation />
}

The problem that I currently have is that when I start my app, I show that the request is made with axios and it brings the data correctly, however the useState is not filled with the data that the axios responds to me (it prints []). However if I save changes being in the navigation.js class in visual code the variable allproducts of the navigation class is filled with the data correctly and therefore in the other class where I want to display the data, it paints the data correctly.

I need that when my app loads, the data that the api brings is saved and that when using it in the other class, these data remain so that they can be used and illustrate this data on the screen.

Body:
When the function passed to useMemo is created, it captures the first value of allproducts and will always have that value. It will always return [].

In order for useMemo to run again and capture a new value, add that value to the second argument, the array. React will call the memo function whenever a value in that array changes, and then getAllProducts will be created again and capture a new value of allproducts.

 const authContext = useMemo(
    () => ({
      getAllProducts: () => {
        return allproducts;
      },
    }),
    [allproducts]
  );


问:
C++ - Having a "uninitialized local variable y used" warning in my attempt to make a simple calculator
this is my first post. I am having a issue getting my CML calculator to run, I know there are better ways to make a calculator than the code I have, so please leave suggestions and such in the comments, as i am a beginner programmer and it is important to receive feedback.

functions practice.cpp

```<code>#include "pch.h"
#include <iostream>
#include "functions.cpp"

using namespace std;

int main()
{
    int x;
    int y;
    char oper;
    cout << "Welcome to this test calculator" << endl;
    cout << "Please Enter a operator to use: " << endl;
    cin >> oper;

    cout << "Enter a x and y value " << endl;
    cin >> x, y;

    calculate(x, y, oper);

    return 0;
}

</code>```

functions.cpp

```<code>#include "functions.h"
#include "pch.h"
#include <iostream>

using namespace std;

int calculate(int x, int y, char oper) {

    switch (oper)
    {
    case '-':
        return x - y;
        break;
    case '+':
        return x + y;
        break;
    case '*':
        return x * y;
        break;
    case '/':
        return x / y;
        break;

    default:
        break;
    }
    return 1;
}
</code>```

What am i doing wrong?

答:
In the file practice.cpp:

cin >> x, y; should be cin >> x >> y;

cin >> x, y; will read input only for x.

Here , works as an end of the cin part, and y will work like a separate part.

Understanding of comma operator (,) in the code:

Comma operator will always give priority to the right most operator.

ex: x = (y,z);

In this line, value of z will be assigned to x.

Same way in the line cin >> x, y;, y execute nothing. And after that cin >> x will read input from the user.

Body:
this is my first post. I am having a issue getting my CML calculator to run, I know there are better ways to make a calculator than the code I have, so please leave suggestions and such in the comments, as i am a beginner programmer and it is important to receive feedback.

functions practice.cpp

#include "pch.h"
#include <iostream>
#include "functions.cpp"

using namespace std;

int main()
{
    int x;
    int y;
    char oper;
    cout << "Welcome to this test calculator" << endl;
    cout << "Please Enter a operator to use: " << endl;
    cin >> oper;

    cout << "Enter a x and y value " << endl;
    cin >> x, y;

    calculate(x, y, oper);

    return 0;
}

functions.cpp

#include "functions.h"
#include "pch.h"
#include <iostream>

using namespace std;

int calculate(int x, int y, char oper) {

    switch (oper)
    {
    case '-':
        return x - y;
        break;
    case '+':
        return x + y;
        break;
    case '*':
        return x * y;
        break;
    case '/':
        return x / y;
        break;

    default:
        break;
    }
    return 1;
}

What am i doing wrong?


问:
Binding Generic List Array to GridView
Hi I have a List which returns an array of "Question".  My question is how can I bind this to a grid view?  When I try to call Question.Ordinal I get that it does not exist in the data source.  I am using the following code:

```<code>GridView1.DataSource = myList.GetQ();
GrdiView1.DataBind();
</code>```

myList.GetQ() returns a List which is an array of "Question".

When I set the column DataField to "!" I get the object Question.  My question is how can I get the objects property?  I tried "!.Ordinal" does not work.  I was reading this post for reference, here, any help is greatly appreciated, thanks.

答:
Just set it directly to Ordinal, as the first examples in the post you just linked to:

```<code><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
   <asp:BoundField HeaderText="ID" DataField="CustId" />
   <asp:BoundField HeaderText="Name" DataField="Name" />
   <asp:BoundField HeaderText="City" DataField="City" />
</Columns>
</asp:GridView>
</code>```

Say:

```<code><asp:BoundField HeaderText="A Header" DataField="APropertyOfQuestion" />
</code>```

OwnerDisplayName: OliverS

LastEditorDisplayName: OliverS

ContentLicense: CC BY-SA 2.5

Title: Binding Generic List Array to GridView

Body:
Hi I have a List which returns an array of "Question".  My question is how can I bind this to a grid view?  When I try to call Question.Ordinal I get that it does not exist in the data source.  I am using the following code:

GridView1.DataSource = myList.GetQ();
GrdiView1.DataBind();

myList.GetQ() returns a List which is an array of "Question".

When I set the column DataField to "!" I get the object Question.  My question is how can I get the objects property?  I tried "!.Ordinal" does not work.  I was reading this post for reference, here, any help is greatly appreciated, thanks.

Body:
Just set it directly to Ordinal, as the first examples in the post you just linked to:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
   <asp:BoundField HeaderText="ID" DataField="CustId" />
   <asp:BoundField HeaderText="Name" DataField="Name" />
   <asp:BoundField HeaderText="City" DataField="City" />
</Columns>
</asp:GridView>

Say:

<asp:BoundField HeaderText="A Header" DataField="APropertyOfQuestion" />

OwnerDisplayName: Freddy Rios


问:
shell_exec with PHP
I am attempting to run apktool (just a tool to unpackage android applications) over the web using PHP shell_exec but it isn't working.  Does anyone know why this might be?

This is what the line of code actually looks like:

```<code>   $output = `apktool d -f $file_name`;
</code>```

Any suggestions would help I'm totally at a loss why I run the php and nothing happens.
Thanks!

答:
Make sure that your actual line is:

```<code> $output = shell_exec(`apktool d -f $file_name`);
</code>```

And that your php.ini file does not have safe_mode turned on or have shell_exec listed in
the disable_functions directive.

Title: shell_exec with PHP

Body:
I am attempting to run apktool (just a tool to unpackage android applications) over the web using PHP shell_exec but it isn't working.  Does anyone know why this might be?

This is what the line of code actually looks like:

   $output = `apktool d -f $file_name`;

Any suggestions would help I'm totally at a loss why I run the php and nothing happens.
Thanks!

Body:
Make sure that your actual line is:

 $output = shell_exec(`apktool d -f $file_name`);

And that your php.ini file does not have safe_mode turned on or have shell_exec listed in
the disable_functions directive.


问:
Getting HTTP Error 500.19 - Internal Server Error while running .net project
I have ran a command aspnet_regiis -i from command prompt and then I am getting Server Error while running the project in Visual Studio.
I have ran the command from below path:
C:\Windows\Microsoft.Net\Framework\v4.0.30319

IF anyone have any solution for this please let me know or if I can revert above command.

IIS version is 7.5

Thanks.

答:
aspnet_regiis -i means install this version of ASP.NET  that is associated with the ASP.NET IIS Registration tool, and the error message of your post indicated a problem with the version of asp.net you are using, you could try to change your .NET runtime version.

About how to correct the asp.net version you can refer to this link:

https://www.ibm.com/support/pages/error-occurred50019-internal-server-error-0x800700b7-there-duplicate-systemwebextensionsscriptingscriptresourcehandler-section-defined-when-launching-controller-1021-or-earlier-caused-using-net-40


问:
How to find unused images in an Xcode project?
Has anyone a one-line to find unused images in an Xcode project? (Assuming all the files are referenced by name in code or the project files - no code generated file names.)

These files tend to build up over the life of a project and it can be hard to tell if it's safe to delete any given png.

答:
I have created a python script to identify the unused images: 'unused_assets.py' @ gist. It can be used like this:

```<code>python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'
</code>```

Here are few rules to use the script:

It is important to pass project folder path as first argument, assets
folder path as second argument

It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift files or within storyboards

Limitations in first version:

Doesn't work for objective c files

I will try to improve it over the time, based on feedback, however the first version should be good for most.

Please find below the code. The code should be self explanatory as I have added appropriate comments to each important step.

```<code># Usage e.g.: python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'
# It is important to pass project folder path as first argument, assets folder path as second argument
# It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift files or within storyboards

"""
@author = "Devarshi Kulshreshtha"
@copyright = "Copyright 2020, Devarshi Kulshreshtha"
@license = "GPL"
@version = "1.0.1"
@contact = "kulshreshtha.devarshi@gmail.com"
"""

import sys
import glob
from pathlib import Path
import mmap
import os
import time

# obtain start time
start = time.time()

arguments = sys.argv

# pass project folder path as argument 1
projectFolderPath = arguments[1].replace("\\", "") # replacing backslash with space
# pass assets folder path as argument 2
assetsPath = arguments[2].replace("\\", "") # replacing backslash with space

print(f"assetsPath: {assetsPath}")
print(f"projectFolderPath: {projectFolderPath}")

# obtain all assets / images
# obtain paths for all assets

assetsSearchablePath = assetsPath + '/**/*.imageset'  #alternate way to append: fr"{assetsPath}/**/*.imageset"
print(f"assetsSearchablePath: {assetsSearchablePath}")

imagesNameCountDict = {} # empty dict to store image name as key and occurrence count
for imagesetPath in glob.glob(assetsSearchablePath, recursive=True):
    # storing the image name as encoded so that we save some time later during string search in file
    encodedImageName = str.encode(Path(imagesetPath).stem)
    # initializing occurrence count as 0
    imagesNameCountDict[encodedImageName] = 0

print("Names of all assets obtained")

# search images in swift files
# obtain paths for all swift files

swiftFilesSearchablePath = projectFolderPath + '/**/*.swift' #alternate way to append: fr"{projectFolderPath}/**/*.swift"
print(f"swiftFilesSearchablePath: {swiftFilesSearchablePath}")

for swiftFilePath in glob.glob(swiftFilesSearchablePath, recursive=True):
    with open(swiftFilePath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the swift file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all swift files!")

# search images in storyboards
# obtain path for all storyboards

storyboardsSearchablePath = projectFolderPath + '/**/*.storyboard' #alternate way to append: fr"{projectFolderPath}/**/*.storyboard"
print(f"storyboardsSearchablePath: {storyboardsSearchablePath}")
for storyboardPath in glob.glob(storyboardsSearchablePath, recursive=True):
    with open(storyboardPath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the storyboard file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all storyboard files!")
print("Here is the list of unused assets:")

# printing all image names, for which occurrence count is 0
print('\n'.join({encodedImageName.decode("utf-8", "strict") for encodedImageName, occurrenceCount in imagesNameCountDict.items() if occurrenceCount == 0}))

print(f"Done in {time.time() - start} seconds!")
</code>```

Body:
I have created a python script to identify the unused images: 'unused_assets.py' @ gist. It can be used like this:

python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'

Here are few rules to use the script:

It is important to pass project folder path as first argument, assets
folder path as second argument

It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift files or within storyboards

Limitations in first version:

Doesn't work for objective c files

I will try to improve it over the time, based on feedback, however the first version should be good for most.

Please find below the code. The code should be self explanatory as I have added appropriate comments to each important step.

# Usage e.g.: python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'
# It is important to pass project folder path as first argument, assets folder path as second argument
# It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift files or within storyboards

"""
@author = "Devarshi Kulshreshtha"
@copyright = "Copyright 2020, Devarshi Kulshreshtha"
@license = "GPL"
@version = "1.0.1"
@contact = "kulshreshtha.devarshi@gmail.com"
"""

import sys
import glob
from pathlib import Path
import mmap
import os
import time

# obtain start time
start = time.time()

arguments = sys.argv

# pass project folder path as argument 1
projectFolderPath = arguments[1].replace("\\", "") # replacing backslash with space
# pass assets folder path as argument 2
assetsPath = arguments[2].replace("\\", "") # replacing backslash with space

print(f"assetsPath: {assetsPath}")
print(f"projectFolderPath: {projectFolderPath}")

# obtain all assets / images
# obtain paths for all assets

assetsSearchablePath = assetsPath + '/**/*.imageset'  #alternate way to append: fr"{assetsPath}/**/*.imageset"
print(f"assetsSearchablePath: {assetsSearchablePath}")

imagesNameCountDict = {} # empty dict to store image name as key and occurrence count
for imagesetPath in glob.glob(assetsSearchablePath, recursive=True):
    # storing the image name as encoded so that we save some time later during string search in file
    encodedImageName = str.encode(Path(imagesetPath).stem)
    # initializing occurrence count as 0
    imagesNameCountDict[encodedImageName] = 0

print("Names of all assets obtained")

# search images in swift files
# obtain paths for all swift files

swiftFilesSearchablePath = projectFolderPath + '/**/*.swift' #alternate way to append: fr"{projectFolderPath}/**/*.swift"
print(f"swiftFilesSearchablePath: {swiftFilesSearchablePath}")

for swiftFilePath in glob.glob(swiftFilesSearchablePath, recursive=True):
    with open(swiftFilePath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the swift file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all swift files!")

# search images in storyboards
# obtain path for all storyboards

storyboardsSearchablePath = projectFolderPath + '/**/*.storyboard' #alternate way to append: fr"{projectFolderPath}/**/*.storyboard"
print(f"storyboardsSearchablePath: {storyboardsSearchablePath}")
for storyboardPath in glob.glob(storyboardsSearchablePath, recursive=True):
    with open(storyboardPath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the storyboard file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all storyboard files!")
print("Here is the list of unused assets:")

# printing all image names, for which occurrence count is 0
print('\n'.join({encodedImageName.decode("utf-8", "strict") for encodedImageName, occurrenceCount in imagesNameCountDict.items() if occurrenceCount == 0}))

print(f"Done in {time.time() - start} seconds!")


问:
Change img properties (src, alt...) based on AJAX success (and fix my ajax ;) )
The image link I'm using:

```<code>echo "<br/><div class='right' id='post" . $id . "'>
<img id='thumb' src='/images/like.png' title='Like it?' alt='Like button'
          onClick='likeButton(" . $id . ");'>( " . getLikes($id) . " )</div><br/>";
</code>```

and the JavaScript is:

```<code>function likeButton(id) {
    $.ajax({
        url: "../../likes/" + id,
        type: "post",
        data: {
            id: id},
        success: function(likes) {
        $('#post' + id).html(likes);
    }});
}
</code>```

"likes" is the PHP function that adds the click to the db, and it also returns the number (getLikes($id)).

But there's a couple things wrong here. When I click, the image disappears and I'm only left with the number

Instead, I need it to keep showing the image (and the paranthesis around the number) - but change the image src and alt if the PHP function getLikes($id) == "true".

Any takers?

答:
Instead of replacing the content of the ENTIRE post, just change the value of the likes:

( " . getLikes($id) . " ) => ( " . getLikes($id) . " )

and

```<code>$(`#post${id} .likes`).text(`(${likes})`);
</code>```

EDIT: Follow-up question:

You asked about preventing clicking more than once. You can add a flag to know they have already clicked.

NOTE: This will only one until they reload the page, it's not a great solution if you really want to block them. Your server should prevent it server-side in PHP instead (e.g. check if they have already like it before incrementing the count by user id + post id).

```<code>function likeButton(id) {
    if ($('#post' + id).hasClass('already-liked')) {
        return;
    }
    $('#post' + id).addClass('already-liked');

    $.ajax({
        url: "../../likes/" + id,
        type: "post",
        data: {
            id: id},
        success: function(likes) {
        $('#post' + id).html(likes);
    }});
}
</code>```

Body:
The image link I'm using:

echo "

( " . getLikes($id) . " )

";

and the JavaScript is:

function likeButton(id) {
    $.ajax({
        url: "../../likes/" + id,
        type: "post",
        data: {
            id: id},
        success: function(likes) {
        $('#post' + id).html(likes);
    }});
}

"likes" is the PHP function that adds the click to the db, and it also returns the number (getLikes($id)).

But there's a couple things wrong here. When I click, the image disappears and I'm only left with the number

Instead, I need it to keep showing the image (and the paranthesis around the number) - but change the image src and alt if the PHP function getLikes($id) == "true".

Any takers?

Body:
Instead of replacing the content of the ENTIRE post, just change the value of the likes:

( " . getLikes($id) . " ) => <span class="likes">( " . getLikes($id) . " )</span>

and

$(`#post${id} .likes`).text(`(${likes})`);

EDIT: Follow-up question:

You asked about preventing clicking more than once. You can add a flag to know they have already clicked.

NOTE: This will only one until they reload the page, it's not a great solution if you really want to block them. Your server should prevent it server-side in PHP instead (e.g. check if they have already like it before incrementing the count by user id + post id).

function likeButton(id) {
    if ($('#post' + id).hasClass('already-liked')) {
        return;
    }
    $('#post' + id).addClass('already-liked');

    $.ajax({
        url: "../../likes/" + id,
        type: "post",
        data: {
            id: id},
        success: function(likes) {
        $('#post' + id).html(likes);
    }});
}


问:
Disabling local labels in JWasm
I'm getting an error message when assembling code in which an instruction references a label in a different procedure.

This code generates two errors, assembler is JWasmR v2.12pre:

```<code>single segment stack
assume cs:single,ds:single,ss:single

start:
    mov ax, cs
    mov ds, ax
    mov ax, 4c00h
    int 21h

func1 proc
label1:
    jmp label2
func1 endp

func2 proc
label2:
    call label1
func2 endp

align 2
s16 db 256 dup (0ffh)
single ends
end start
</code>```

Error messages:

```<code>test1.asm(13) : Error A2102: Symbol not defined : label2
test1.asm(20) : Error A2102: Symbol not defined : label1
</code>```

I think each label symbol is local to it's respective procedure. I would like to disable this functionality globally, or bypass it on an individual basis. I've tried using the -Zf option which makes all symbols public. Documentation can be found here.

答:
In MASM 5.1x if you aren't using a .MODEL directive with a language type then code labels inside a PROC are globally scoped. This is why your code assembles in MASM 5.1x. In JWASM and MASM 6.1+ it is a bit different because code labels that are followed by a : are always locally scoped in a PROC. This results in the errors you are seeing. The MASM 6.1 documentation covers this issue:

MASM 5.1 considers code labels defined with a single colon inside a procedure to be local to that procedure if the module contains a .MODEL directive with a language type

The solution is to use :: following a label rather than : to mark a code label as globally defined. The documentation goes on to say:

You can use the double colon operator to define a non-scoped label

Using :: should make your code assemble with MASM 5.1+, 6.1+, and JWASM. This code:

```<code>func1 proc
label1:
    jmp label2
func1 endp

func2 proc
label2:
    call label1
func2 endp
</code>```

Should work if written as:

```<code>func1 proc
label1::
    jmp label2
func1 endp

func2 proc
label2::
    call label1
func2 endp
</code>```

You can use the -Zm option (not to be confused with -mz) enables MASM 5.1 compatibility. Running JWASM this way should allow your code to assemble without any changes:

```<code>jwasm -Zm filename.asm
</code>```

Using this method will make locally scoped labels in a PROC globally scoped. The other changes that occur are:

```<code>Option -Zm (or setting OPTION M510) will do:
- set OPTION OLDSTRUCTS
- set OPTION DOTNAME
- set OPTION SETIF2:TRUE
- set OPTION OFFSET:SEGMENT (if no model is set)
- set OPTION NOSCOPED (if no model with language specifier is set)
- allow to define data items behind code labels
- allow "invalid" use of REP/REPE/REPNE instruction prefixes
- change precedence of [] and () operator from 1 to 9. Hence expression
  -5[bx] is parsed as (-5)[bx], while without -Zm it is
  parsed as -(5[bx]), which generates an error.
</code>```

For JWASM and MASM 6.1+ you can also specify the no scope option at the top of an assembly module with this directive:

```<code>OPTION NOSCOPED
</code>```

This option doesn't exist in MASM 5.1x as this is the behaviour for that assembler. You would have to remove this directive from your assembly code if assembling with MASM 5.1x. The MASM 6.1 documentation describes this option as:

The information in this section applies only if the .MODEL directive in your MASM 5.1 code does not
       specify a language type. Without a language type, MASM 5.1 assumes code labels in procedures
       have no “scope” — that is, the labels are not local to the procedure. When not in compatibility mode,
       MASM 6.1 always gives scope to code labels, even without a language type.
       To force MASM 5.1 behavior, specify either OPTION M510 or OPTION NOSCOPED in your code

Title: Disabling local labels in JWasm

Body:
I'm getting an error message when assembling code in which an instruction references a label in a different procedure.

This code generates two errors, assembler is JWasmR v2.12pre:

single segment stack
assume cs:single,ds:single,ss:single

start:
    mov ax, cs
    mov ds, ax
    mov ax, 4c00h
    int 21h

func1 proc
label1:
    jmp label2
func1 endp

func2 proc
label2:
    call label1
func2 endp

align 2
s16 db 256 dup (0ffh)
single ends
end start

Error messages:

test1.asm(13) : Error A2102: Symbol not defined : label2
test1.asm(20) : Error A2102: Symbol not defined : label1

I think each label symbol is local to it's respective procedure. I would like to disable this functionality globally, or bypass it on an individual basis. I've tried using the -Zf option which makes all symbols public. Documentation can be found here.

Body:
In MASM 5.1x if you aren't using a .MODEL directive with a language type then code labels inside a PROC are globally scoped. This is why your code assembles in MASM 5.1x. In JWASM and MASM 6.1+ it is a bit different because code labels that are followed by a : are always locally scoped in a PROC. This results in the errors you are seeing. The MASM 6.1 documentation covers this issue:

MASM 5.1 considers code labels defined with a single colon inside a procedure to be local to that procedure if the module contains a .MODEL directive with a language type

The solution is to use :: following a label rather than : to mark a code label as globally defined. The documentation goes on to say:

You can use the double colon operator to define a non-scoped label

Using :: should make your code assemble with MASM 5.1+, 6.1+, and JWASM. This code:

func1 proc
label1:
    jmp label2
func1 endp

func2 proc
label2:
    call label1
func2 endp

Should work if written as:

func1 proc
label1::
    jmp label2
func1 endp

func2 proc
label2::
    call label1
func2 endp

You can use the -Zm option (not to be confused with -mz) enables MASM 5.1 compatibility. Running JWASM this way should allow your code to assemble without any changes:

jwasm -Zm filename.asm

Using this method will make locally scoped labels in a PROC globally scoped. The other changes that occur are:

Option -Zm (or setting OPTION M510) will do:
- set OPTION OLDSTRUCTS
- set OPTION DOTNAME
- set OPTION SETIF2:TRUE
- set OPTION OFFSET:SEGMENT (if no model is set)
- set OPTION NOSCOPED (if no model with language specifier is set)
- allow to define data items behind code labels
- allow "invalid" use of REP/REPE/REPNE instruction prefixes
- change precedence of [] and () operator from 1 to 9. Hence expression
  -5[bx] is parsed as (-5)[bx], while without -Zm it is
  parsed as -(5[bx]), which generates an error.

For JWASM and MASM 6.1+ you can also specify the no scope option at the top of an assembly module with this directive:

OPTION NOSCOPED

This option doesn't exist in MASM 5.1x as this is the behaviour for that assembler. You would have to remove this directive from your assembly code if assembling with MASM 5.1x. The MASM 6.1 documentation describes this option as:

The information in this section applies only if the .MODEL directive in your MASM 5.1 code does not
       specify a language type. Without a language type, MASM 5.1 assumes code labels in procedures
       have no “scope” — that is, the labels are not local to the procedure. When not in compatibility mode,
       MASM 6.1 always gives scope to code labels, even without a language type.
       To force MASM 5.1 behavior, specify either OPTION M510 or OPTION NOSCOPED in your code


问:
flutter dart How to remove underscore _ for RegExp, \\W+ doesnt remove underscore?
How to remove underscore _ for RegExp, \W+ doesnt remove underscore? what do i need to add to additional remove _?

This expression doesnt remove _.

```<code>sentence.replaceAll(new RegExp("\\W+"),"").toLowerCase();
</code>```

答:
here the correct answer:

remove _

```<code>sentence.replaceAll(new RegExp('[\\W_]+'),'').toLowerCase();
</code>```

remove _ /

```<code>sentence.replaceAll(new RegExp('[\\W_\/]+'),'').toLowerCase();
</code>```

Body:
How to remove underscore _ for RegExp, \W+ doesnt remove underscore? what do i need to add to additional remove _?

This expression doesnt remove _.

sentence.replaceAll(new RegExp("\\W+"),"").toLowerCase();

Body:
here the correct answer:

remove _

sentence.replaceAll(new RegExp('[\\W_]+'),'').toLowerCase();

remove _ /

sentence.replaceAll(new RegExp('[\\W_\/]+'),'').toLowerCase();


问:
need to pass another value to change event
please give me advise, how can I solve this problem. I need to pass area.id to onChangeArea method to make request, but also I can not change value of options, because I need area.code in formControlName. How can I pass id to onChangeArea?

答:
If the area.code is unique then you can search the particular object from areas array in your controller.

```<code>getArea(code) {
    this.areas.forEach(function(area) {
        if(area.code === code) {
            console.log(area._id);
        }
    });
}
</code>```

You can call this function onChange event.

Hope this will be helpfull.

Body:
If the area.code is unique then you can search the particular object from areas array in your controller.

getArea(code) {
    this.areas.forEach(function(area) {
        if(area.code === code) {
            console.log(area._id);
        }
    });
}

You can call this function onChange event.

Hope this will be helpfull.


问:
How to pass a value from this.state from one js file to another reactjs
I have a file and I have defined there a variable called "approve" in this.state{}

```<code>class cd extends React.Component {
  constructor() {
    super();
    this.state = {
      approve: "",

    };
    this.handleA = this.handleApprove.bind(this);

  }

  handleA(e) {
    console.log(e.target.value);

    this.setState({ approve: e.target.value });

  }
  render() {
    const { approve } = this.state;
    const {

    } = this.props;

    console.log(approveState);

    return (
     <Card>
                    <CardHeader title="Name" />
                    <CardContent>
                      <Field
                        name="Name"
                        component={RenderText}
                        label=""

                      />
                    </CardContent>
                  </Card>)
</code>```

I need to pass it to another js file....

how d oi pass the value of approve to this js file

答:
Hi check this example state and function passing one component to another component

parent.js

```<code>import React from "react";
import Child from "./child.js";

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "Click"
    };
  }
  update = () => {
    console.log("i am called");
  };
  render() {
    return (
      <div>
        <Child value={this.state.value} update={this.update} />
      </div>
    );
  }
}

export default Parent;
</code>```

child.js

```<code>import React from "react";

    class Child extends React.Component {
      render() {
        return <button onClick={this.props.update}>{this.props.value}</button>;
      }
    }
export default Child;
</code>```

Body:
I have a file and I have defined there a variable called "approve" in this.state{}

class cd extends React.Component {
  constructor() {
    super();
    this.state = {
      approve: "",

    };
    this.handleA = this.handleApprove.bind(this);

  }

  handleA(e) {
    console.log(e.target.value);

    this.setState({ approve: e.target.value });

  }
  render() {
    const { approve } = this.state;
    const {

    } = this.props;

    console.log(approveState);

    return (
     <Card>
                    <CardHeader title="Name" />
                    <CardContent>
                      <Field
                        name="Name"
                        component={RenderText}
                        label=""

                      />
                    </CardContent>
                  </Card>)

I need to pass it to another js file....

how d oi pass the value of approve to this js file

Body:
Hi check this example state and function passing one component to another component

parent.js

import React from "react";
import Child from "./child.js";

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "Click"
    };
  }
  update = () => {
    console.log("i am called");
  };
  render() {
    return (
      <div>
        <Child value={this.state.value} update={this.update} />
      </div>
    );
  }
}

export default Parent;

child.js

import React from "react";

    class Child extends React.Component {
      render() {
        return <button onClick={this.props.update}>{this.props.value}</button>;
      }
    }
export default Child;


问:
facet like functionality in NoSQL systems
Does anyone know / can someone point to an nosql db, which would support faceting, like in Apache SOLR, off the shelf?

I have read, that in Sphinx they don't support facet search out of the box, but one can implement it in a form of plugin.

Upd: I'm only interested in enterprise level systems.

答:
CouchDB (Eearlang) and RavenDB (.NET) both are based on Lucene, so it should be possible to make them both support Faceted Search. RavenDB already partially supports that.

And Sphinx isn't a NoSQL DB.


问:
I have error in arrayindexoutofbounds and I've looked up many places and not been able to spot the mistake
```<code>Main Class:
public class Main {

  private static String [] Countries={"UK", "Italy",
            "Germany", "Thailand","Denmark"};
  static double average[] = new double[5];
  double[] results = new double[5];

  public static String getWinner(ArrayList<MissUniverse>alist){
    int champion = 0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() ) {
            winner= s;
        }
    }
    return alist.get(winner).getCountry();
  }

public static String firstRunnerUp(ArrayList<MissUniverse>alist){
    int firstrunnerUp =0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() && alist.get(s).getCountry() != getWinner(alist) ) {
            firstrunnerUp = s;
        }
    }
    return alist.get(firstrunnerUp).getCountry();

  }

 public static void main (String[] args){
   ArrayList<MissUniverse> alist = new ArrayList<MissUniverse>();
 MissUniverse missUniverse[] = new MissUniverse[Countries.length];

        for(int i=0;i<Countries.length;i++)
        {
            missUniverse[i] = new MissUniverse(Countries[i]);
            missUniverse[i].getScore();
            alist.add(missUniverse[i]);
        }

   System.out.printf("%-15s%-5s%-5s%-5s%-5s%-5s%-10s",
                "Countries","1","2","3","4","5","Average");
    System.out.println();
    for (int i = 0; i < Countries.length; i++){
    System.out.print(Countries[i]);
    System.out.print("    ");
    missUniverse[i].printInfo();
    System.out.printf("%5.1f", alist.get(i).average() );  ///this line
    System.out.println();
    }
    System.out.println("The result is");
    System.out.println("Winner: Miss " + getWinner(alist) );
    System.out.println("1st Runner Up: Miss " + firstRunnerUp(alist) );

  }
}

</code>```

MissUniverse class:

```<code>class MissUniverse {
  public static int SIZE=5;
  private String country;
  private double[] score;

  public MissUniverse(String country){
    this.country = country;
    score = new double [SIZE];
  }

  public String getCountry(){
    return country;
  }

  public void getScore(){
      for (int i=0;i<score.length;i++)
        {
            score[i] = Math.random()*10;
        }
  }

  public void setCountry(String newCountry) {
    this.country = newCountry;
  }

 private int highest(){
  int i;
        double highest;
        highest = score[0];

        for (i = 0; i <score.length; i++)
        {
            if (highest < score [i])
            {
                highest = score[i] ;
            }
        }
        return i;
  }

  private int lowest(){
  int i;
        double lowest;
        lowest = score[0];
        for (i = 0; i <score.length; i++)
        {
            if (lowest > score [i])
            {
                lowest = score[i];
            }
        }
        return i;
  }

  public double average(){

    double sum = 0.0;
     for (int i = 0; i < score.length; i++){
        sum +=  score[i];
     }
    double average;
    average = (sum - score[lowest()] - score[highest()] )/ score.length -2;
  }

  public void printInfo(){

      for(int i=0;i< score.length;i++){
      System.out.printf("%-5.1f",score[i]);
      }

  }
}
</code>```

The error:

```<code>Countries      1    2    3    4    5    Average
UK    3.3  5.8  6.6  4.8  0.2  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at MissUniverse.average(Main.java:121)
    at Main.main(Main.java:50)

</code>```

I think the problem is in the average() or lowest() or highest() methods but I cant find the bug. I dont think there is anything wrong in those methods that can lead to counting outside the array length (length is 8) and index is 0-7. I've looked at other links in stackoverflow but I can't find whats wrong. I hope someone can help me?

The output I am trying to achieve is:

```<code>Countries       1    2    3    4    5   Average
UK             6.2  2.5  9.7  4.3  0.1  3.4
Italy          7.1  1.2  1.6  5.5  1.9  3.7
Germany        8.5  3.3  6.7  4.0  6.0  5.9
Thailand       5.3  8.5  1.5 10.0  2.7  4.1
Denmark        3.1  4.9  5.4  0.8  3.2  3.4

The result is:
Winner: Miss Germany
1st runner up: Miss Thailand
</code>```

答:
The problem is actually in your average method.  This line:

```<code>average = (sum - score[lowest()] - score[highest()] )/ score.length -2;
</code>```

Needs to be changed to:

```<code>average = (sum - lowest() - highest() )/ score.length -2;
</code>```

Remember that all indices start at 0 in arrays.

You also forgot to return a value, so you need to put return average; at the end of the average method.  Also, in your getWinner method, you need to declare the variable winner by putting int winner = 0; at the beginning of the getWinner method.

highest() also needs to be edited to return highest;, and lowest() needs to be edited to return lowest;.  You will need to change those return types to double to make this work.

Body:
Main Class:
public class Main {

  private static String [] Countries={"UK", "Italy",
            "Germany", "Thailand","Denmark"};
  static double average[] = new double[5];
  double[] results = new double[5];

  public static String getWinner(ArrayList<MissUniverse>alist){
    int champion = 0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() ) {
            winner= s;
        }
    }
    return alist.get(winner).getCountry();
  }

public static String firstRunnerUp(ArrayList<MissUniverse>alist){
    int firstrunnerUp =0;
    for (int s = 0; s < alist.size(); s++){
        if (alist.get(s).average() > alist.get(0).average() && alist.get(s).getCountry() != getWinner(alist) ) {
            firstrunnerUp = s;
        }
    }
    return alist.get(firstrunnerUp).getCountry();

  }

 public static void main (String[] args){
   ArrayList<MissUniverse> alist = new ArrayList<MissUniverse>();
 MissUniverse missUniverse[] = new MissUniverse[Countries.length];

        for(int i=0;i<Countries.length;i++)
        {
            missUniverse[i] = new MissUniverse(Countries[i]);
            missUniverse[i].getScore();
            alist.add(missUniverse[i]);
        }

   System.out.printf("%-15s%-5s%-5s%-5s%-5s%-5s%-10s",
                "Countries","1","2","3","4","5","Average");
    System.out.println();
    for (int i = 0; i < Countries.length; i++){
    System.out.print(Countries[i]);
    System.out.print("    ");
    missUniverse[i].printInfo();
    System.out.printf("%5.1f", alist.get(i).average() );  ///this line
    System.out.println();
    }
    System.out.println("The result is");
    System.out.println("Winner: Miss " + getWinner(alist) );
    System.out.println("1st Runner Up: Miss " + firstRunnerUp(alist) );

  }
}

MissUniverse class:

class MissUniverse {
  public static int SIZE=5;
  private String country;
  private double[] score;

  public MissUniverse(String country){
    this.country = country;
    score = new double [SIZE];
  }

  public String getCountry(){
    return country;
  }

  public void getScore(){
      for (int i=0;i<score.length;i++)
        {
            score[i] = Math.random()*10;
        }
  }

  public void setCountry(String newCountry) {
    this.country = newCountry;
  }

 private int highest(){
  int i;
        double highest;
        highest = score[0];

        for (i = 0; i <score.length; i++)
        {
            if (highest < score [i])
            {
                highest = score[i] ;
            }
        }
        return i;
  }

  private int lowest(){
  int i;
        double lowest;
        lowest = score[0];
        for (i = 0; i <score.length; i++)
        {
            if (lowest > score [i])
            {
                lowest = score[i];
            }
        }
        return i;
  }

  public double average(){

    double sum = 0.0;
     for (int i = 0; i < score.length; i++){
        sum +=  score[i];
     }
    double average;
    average = (sum - score[lowest()] - score[highest()] )/ score.length -2;
  }

  public void printInfo(){

      for(int i=0;i< score.length;i++){
      System.out.printf("%-5.1f",score[i]);
      }

  }
}

The error:

Countries      1    2    3    4    5    Average
UK    3.3  5.8  6.6  4.8  0.2  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at MissUniverse.average(Main.java:121)
    at Main.main(Main.java:50)

I think the problem is in the average() or lowest() or highest() methods but I cant find the bug. I dont think there is anything wrong in those methods that can lead to counting outside the array length (length is 8) and index is 0-7. I've looked at other links in stackoverflow but I can't find whats wrong. I hope someone can help me?

The output I am trying to achieve is:

Countries       1    2    3    4    5   Average
UK             6.2  2.5  9.7  4.3  0.1  3.4
Italy          7.1  1.2  1.6  5.5  1.9  3.7
Germany        8.5  3.3  6.7  4.0  6.0  5.9
Thailand       5.3  8.5  1.5 10.0  2.7  4.1
Denmark        3.1  4.9  5.4  0.8  3.2  3.4

The result is:
Winner: Miss Germany
1st runner up: Miss Thailand

Body:
The problem is actually in your average method.  This line:

average = (sum - score[lowest()] - score[highest()] )/ score.length -2;

Needs to be changed to:

average = (sum - lowest() - highest() )/ score.length -2;

Remember that all indices start at 0 in arrays.

You also forgot to return a value, so you need to put return average; at the end of the average method.  Also, in your getWinner method, you need to declare the variable winner by putting int winner = 0; at the beginning of the getWinner method.

highest() also needs to be edited to return highest;, and lowest() needs to be edited to return lowest;.  You will need to change those return types to double to make this work.


问:
Wordpress JSON API returns normal site page in html. How do I get it to give me JSON like it's supposed to
For example, entering http://mywordpresswebsite.example.com/?json=1 into the browser loads the main site html, the same as omitting the json querystring variable: http://mywordpresswebsite.example.com/

The JSON API is activated.  I have tried reactivating and deactivating, checking .htaccess file settings, and deactivating all other plugins.  None of those have made much difference so far.

TIA

答:
I had the same problem with my localhost test page and was wondering, why my route worked last week and was not accessible this week.

Short explanation

After some tests and a lot of frustration, I was able to use the REST API Route again by following the wordpress documentation about routes-vs-endpoints with “Pretty Permalinks” and “Ugly” Permalinks

Longer explanation

I guess in my case it was based on the reinstall of my MySQL Database. By installing the new database, my previous setup has been reset to the wordpress standard installation with permalinks as "plain", which is an "ugly" permalink. That's the reason, why the answer of Mattygabe work for me after the reinstall of the database.

But with this solution, I had a problem with my filter value and therefore I found the solution with "pretty premalinks" and changed my permalinks to "Month and name", as shown in the picture. After this change, I could access my REST API via the desired route.

There could be also some difficulties with REST APIs related to the following examples:

using "wp" within the REST route

if you work on plugins, which should be shared, keep on mind that some plugins may restrict REST Access, e.g. iThemes Security


问:
How to pass and keep global variable remain unchanged in function in React?
I am new to React. I am trying to import the variable from constants file and use it in function. Here's my demo code. However, if I call the function multiple times, the countries in otherCountryList just keep appending to the COUNTRY_LIST. How can I prevent this happen and everytime I call the function it will just append on COUNTRY_LIST as new list ?

Constants.js:

```<code>export const COUNTRY_LIST = ['USA', 'UK', 'SPAIN'];
</code>```

index.js

```<code>import {COUNTRY_LIST} from './constants/constant';
inputCountry(){
  let countryList = COUNTRY_LIST;
  //let say pushing other country to the countryList
  for (var c = 0; c < this.otherCountryList.length; c ++){
    countryList.push(c);
  }
  console.log(countryList) //expected output:['USA', 'UK', 'SPAIN', 'AUS', 'JAPAN']
  // real output after called this function twice:['USA', 'UK', 'SPAIN', 'AUS', 'JAPAN', 'AUS', 'JAPAN']
}
</code>```

答:
Use this:

```<code>const countryList = [...COUNTRY_LIST];
</code>```

That's it, no push or for loop or anything else. It just copies the array.

Body:
I am new to React. I am trying to import the variable from constants file and use it in function. Here's my demo code. However, if I call the function multiple times, the countries in otherCountryList just keep appending to the COUNTRY_LIST. How can I prevent this happen and everytime I call the function it will just append on COUNTRY_LIST as new list ?

Constants.js:

export const COUNTRY_LIST = ['USA', 'UK', 'SPAIN'];

index.js

import {COUNTRY_LIST} from './constants/constant';
inputCountry(){
  let countryList = COUNTRY_LIST;
  //let say pushing other country to the countryList
  for (var c = 0; c < this.otherCountryList.length; c ++){
    countryList.push(c);
  }
  console.log(countryList) //expected output:['USA', 'UK', 'SPAIN', 'AUS', 'JAPAN']
  // real output after called this function twice:['USA', 'UK', 'SPAIN', 'AUS', 'JAPAN', 'AUS', 'JAPAN']
}

Body:
Use this:

const countryList = [...COUNTRY_LIST];

That's it, no push or for loop or anything else. It just copies the array.