问:
How to match correct answers in a randomly generated array in Android?
So I'm creating a riddle app that when you swipe up on the screen it will come up with a riddle that is randomly generated using an array. Now I have no idea which riddle will pop up because of course, it's random but I want the user to be able to click and hold on the randomly generated riddle and the answer will then pop up replacing the riddle. So far I have the array done to where it will randomly generate a riddle but I'm having a problem getting the answer to match up with riddles. How would I go about matching correct answers to a random array on a long press of the text view?

I did see two other questions (one,two) and similar to this one but it did not answer the question that I have and it really wasn't specific.

```<code>final TextView answerTxt = (TextView) findViewById(R.id.answerTxt);

    //List with the riddles and its values
    HashMap<String, String> h = new Hashmap<String, String>();
    h.put("a", "v");
    h.put("b", "w");
    h.put("c", "x");
    h.put("d", "y");
    h.put("e", "z");

    //rand generator for array
    String[] yourKeyList = h.keySet().toArray(new String[]{});

    String[] yourValueList = h.values().toArray(new String[]{});

    String randomKey = yourKeyList[new Random().nextInt(yourKeyList.length)];

    final String keyValue = yourValueList[yourValueList.length];

    answerTxt.setText(randomKey);

    answerTxt.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            answerTxt.setText(keyValue);
            return true;
        }
    });
</code>```

答: The array of riddles and the array of answers should be linked. When the riddle pops up you should know what index was chosen, and then use that as the index into the answer. </p>

Body:
So I'm creating a riddle app that when you swipe up on the screen it will come up with a riddle that is randomly generated using an array. Now I have no idea which riddle will pop up because of course, it's random but I want the user to be able to click and hold on the randomly generated riddle and the answer will then pop up replacing the riddle. So far I have the array done to where it will randomly generate a riddle but I'm having a problem getting the answer to match up with riddles. How would I go about matching correct answers to a random array on a long press of the text view?

I did see two other questions (one,two) and similar to this one but it did not answer the question that I have and it really wasn't specific.

final TextView answerTxt = (TextView) findViewById(R.id.answerTxt);

    //List with the riddles and its values
    HashMap<String, String> h = new Hashmap<String, String>();
    h.put("a", "v");
    h.put("b", "w");
    h.put("c", "x");
    h.put("d", "y");
    h.put("e", "z");

    //rand generator for array
    String[] yourKeyList = h.keySet().toArray(new String[]{});

    String[] yourValueList = h.values().toArray(new String[]{});

    String randomKey = yourKeyList[new Random().nextInt(yourKeyList.length)];

    final String keyValue = yourValueList[yourValueList.length];

    answerTxt.setText(randomKey);

    answerTxt.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            answerTxt.setText(keyValue);
            return true;
        }
    });


来源: stackexchange

问:
C++ header file with default arguments in C program
I have a C++ library, with functions declared in a header file. My function declarations include default arguments.

I would like to use this library in Mathematica via the Wolfram Mathematica WSTP Template Compiler (wscc). This requires writing a C interface to my library. I have used this pattern

```<code>#ifdef __cplusplus
extern "C" {
#endif

double my_function(double x, double abs_error = 1E-3);

#ifdef __cplusplus
}
#endif
</code>```

to prevent name-mangling in my library (compiled with C++). But what about the default arguments? I don't think they're standard C. From Wolfram Mathematica WSTP Template Compiler (wscc), I find

error: expected ‘;’, ‘,’ or ‘)’ before ‘=’ token
                   double abs_error = 1E-3,

Do I have to make separate C and C++ declarations (essentially two header files)? Is this a common problem or is it related to my use of wscc? Perhaps wscc doesn't support this syntax, although it is usually acceptable?

答:
The extern C does more than stop name mangling. The function has C calling conventions. It's telling the CPP compiler "you should now speak C". That means exceptions won't propagate, etc. And AFAIK C doesn't have default values.

You can have a function with C calling conventions implemented inside a CPP file, which is very useful sometimes. You can have C calling bits of your CPU code, which is useful.

My suspicion is that how a compiler goes about dealing with default values is up to the compiler writer. If that's true, I can think of at least a couple of ways, one of them not involving putting a value for abs_error on the stack when my_function is called. For example the compiler might include a parameter count on the stack which the function itself uses to spot that abs_error has not been passed and to set a default value. However such a compiler would be very unfriendly indeed if it did that with a function that had C calling conventions without reporting errors. I think I'd test it, just to be sure.

ContentLicense: CC BY-SA 3.0

Body:
I have a C++ library, with functions declared in a header file. My function declarations include default arguments.

I would like to use this library in Mathematica via the Wolfram Mathematica WSTP Template Compiler (wscc). This requires writing a C interface to my library. I have used this pattern

#ifdef __cplusplus
extern "C" {
#endif

double my_function(double x, double abs_error = 1E-3);

#ifdef __cplusplus
}
#endif

to prevent name-mangling in my library (compiled with C++). But what about the default arguments? I don't think they're standard C. From Wolfram Mathematica WSTP Template Compiler (wscc), I find

error: expected ‘;’, ‘,’ or ‘)’ before ‘=’ token
                   double abs_error = 1E-3,

Do I have to make separate C and C++ declarations (essentially two header files)? Is this a common problem or is it related to my use of wscc? Perhaps wscc doesn't support this syntax, although it is usually acceptable?


问:
Implementing Custom Session State Store Provider in dotnet core
I was just planning to implement a custom session state provider for a distributed cache product in .net core but I could not find SessionStateStoreProviderBase and related classes in dotnet core. Can somebody tell me where to find them?</p>

答:
Session is very different in ASP.NET Core. It's designed around IDistributedCache and takes the implementation from DI.
https://github.com/aspnet/Caching/blob/rel/1.1.2/src/Microsoft.Extensions.Caching.Abstractions/IDistributedCache.cs</p>


问:
JavaScript/HTML: Changing an image border onclick
I want to write a function that surrounds an image with a border frame each time i click on it. unf. i can't make it work. deny any typos cause i didn't copy paste it. the function works. but no affect is being made on the image when clicking on it. did i access the border attribute right?

my function:

```<code><script>

function mark(imageId) {
    document.getElementById(imageId).style.border = "1";
}

</script>
</code>```

my html body:

```<code><input id="imageId" src="\images\image1.png" onclick="mark(imageId)"/>
</code>```

答:
This is a code for that question.</p>

```<code><html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
    function sayHello() {
        var boyElement = document.getElementById("boy");
        boyElement.style.border = "3px solid red";
    }
</script>
<img src="C:\Users\Acer\Desktop\new web site\js\images\boy.png" id="boy"
onclick="sayHello()">
</body>
</html>
</code>```

Body:
I want to write a function that surrounds an image with a border frame each time i click on it. unf. i can't make it work. deny any typos cause i didn't copy paste it. the function works. but no affect is being made on the image when clicking on it. did i access the border attribute right?

my function:

my html body:

<input id="imageId" src="\images\image1.png" onclick="mark(imageId)"/>

Body:
This is a code for that question.

<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
    function sayHello() {
        var boyElement = document.getElementById("boy");
        boyElement.style.border = "3px solid red";
    }
</script>
<img src="C:\Users\Acer\Desktop\new web site\js\images\boy.png" id="boy"
onclick="sayHello()">
</body>
</html>


问:
Print only each character and number once
I want to not use HashMap or Set when printing Duplicate characters in a String. But in solution I'm using I'm printing all the characters even if they are duplicates. I want to print each character once and with number of times it occurs in the string. Here's my example:

```<code>  public static void printDups(String s1) {
    int count = 0;
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s1.length(); j++) {
            if (s1.charAt(i) == s1.charAt(j)) {
                count++;
            }
        }

        System.out.println(s1.charAt(i) + " --> " + count);

        count = 0;
    }
}
</code>```

public static void main(String[] args) {
    printDups("AABBCCDDD){}
}

And this is the output:

```<code>A --> 2
A --> 2
B --> 2
B --> 2
C --> 2
C --> 2
D --> 3
D --> 3
</code>```

I want to print it like that:

```<code>A --> 2
B --> 2
C --> 2
D --> 3
</code>```

I know I can add this: if (s1.charAt(i) != s1.charAt(i+1))         System.out.println(s1.charAt(i) + " --> " + count);
But then I'll have StringIndexOutOfBoundsException:

If I change my loop to this for (int i = 0; i < s1.length()-1; i++)

It'll skip the last character in the string.

How can I achieve this?

答:
What about adding each printed character to a Set and checking before each print, if this set contains already the character to print.</p>

```<code>public static String eliminateDups(final String s1) {
        final Set<Character> set = new HashSet<>();
        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s1.length(); i++) {
            final char c = s1.charAt(i);
            if (set.contains(c)) {
                // skip
            } else {
                sb.append(c);
            }
            set.add(c);

        }
        return sb.toString();
    }
</code>```

Body:
I want to not use HashMap or Set when printing Duplicate characters in a String. But in solution I'm using I'm printing all the characters even if they are duplicates. I want to print each character once and with number of times it occurs in the string. Here's my example:

  public static void printDups(String s1) {
    int count = 0;
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s1.length(); j++) {
            if (s1.charAt(i) == s1.charAt(j)) {
                count++;
            }
        }

        System.out.println(s1.charAt(i) + " --> " + count);

        count = 0;
    }
}

public static void main(String[] args) {
    printDups("AABBCCDDD){}
}

And this is the output:

A --> 2
A --> 2
B --> 2
B --> 2
C --> 2
C --> 2
D --> 3
D --> 3

I want to print it like that:

A --> 2
B --> 2
C --> 2
D --> 3

I know I can add this: if (s1.charAt(i) != s1.charAt(i+1))         System.out.println(s1.charAt(i) + " --> " + count);
But then I'll have StringIndexOutOfBoundsException:

If I change my loop to this for (int i = 0; i < s1.length()-1; i++)

It'll skip the last character in the string.

How can I achieve this?

Body:
What about adding each printed character to a Set and checking before each print, if this set contains already the character to print.

public static String eliminateDups(final String s1) {
        final Set<Character> set = new HashSet<>();
        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s1.length(); i++) {
            final char c = s1.charAt(i);
            if (set.contains(c)) {
                // skip
            } else {
                sb.append(c);
            }
            set.add(c);

        }
        return sb.toString();
    }


问:
Change link href onclick then run it
I want to open a link to a new window without using window.open() from a link retrieving from an ajax call.

I have an hyperlink with href="#". I want to change the href then go to a link from an ajax call when the user click on the link once.

I am not trying to change the link after the event has been consumed.

Here is my code:

```<code><a href="#" id="preview-btn-link"><i class="fa fa-eye fa-2x" id="save-btn"></i></a>
<script>
                var lockLink = true;
                $("#preview-btn-link").click(function (e) {
                    if (lockLink) {
                        lockLink = false;
                        e.preventDefault();

                        var a = $(this);
                        saveProject("true", function (r) {
                            gvwcProject.id = r;

                            $.post("ajax_path", {"id": r, "pn": paj.non})
                                    .done(function (r) {
                                        console.log(r);
                                        a.attr("href", r);

                                        a.click();
                                    })
                                    .fail(function () {
                                        console.log("fail");
                                    });

                        }, function () {
                            console.log("failed");
                        });
                    } else {
                        lockLink = true;
                    }
                });
</script>
</code>```

I can see the link from the href has been changed. But it does not call the link back even if I click on the link back.

答:
Well, I just get it work by submiting a form.

```<code><form id="form" method="post" action="the_link" target="_blank">
  --some fields --
</form>
</code>```

js:

```<code>$("#preview-btn-link").click(function (e) {
   //some check
   //Edit the form attributes then submit
   $("#form").submit();

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

Title: Change link href onclick then run it

Body:
I want to open a link to a new window without using window.open() from a link retrieving from an ajax call.

I have an hyperlink with href="#". I want to change the href then go to a link from an ajax call when the user click on the link once.

I am not trying to change the link after the event has been consumed.

Here is my code:

I can see the link from the href has been changed. But it does not call the link back even if I click on the link back.

Body:
Well, I just get it work by submiting a form.

<form id="form" method="post" action="the_link" target="_blank">
  --some fields --
</form>

js:

$("#preview-btn-link").click(function (e) {
   //some check
   //Edit the form attributes then submit
   $("#form").submit();

   return false;
 });


问:
Mysql get min, avg and latest from two tables(products and products-prices)
I have two Mysql tables:

products with id, name, link

products-prices with id, id_prod, price, availability and date

In the second one, as you can see I can have more prices for the same product depending on the time it was updated, what I want to do is to have one query to show me the lowest price, average price and latest price. I can get first two (lowest and average price) in one query and latest price in another query but I don't know how to concatenate them or if there is another way.

My first query looks like that:

```<code>SELECT
    `products`.id AS ids, `products`.name, `products`.link,
    `products-prices`.id AS id_p, `products-prices`.price,
    `products-prices`.availability, `products-prices`.date,
    AVG(`products-prices`.price) AS medie,
    MIN(`products-prices`.price) AS minim
FROM
    `products-prices`
INNER JOIN
    `products` ON `products`.id = `products-prices`.id_produs
GROUP BY
    ids
ORDER BY
    ids
</code>```

and the second one is:

```<code>SELECT *
FROM `products-prices`
WHERE date IN (SELECT DISTINCT MAX(date) max_date
               FROM `products-prices`
               GROUP BY id_produs)
</code>```

Can you give me an idea how to combine them? Thank you very much!

(I don't know how UNION works and if it works, I will try it)

//EDIT: And I also have another question, can I get the MIN, AVG values without the latest entry in database ?

答:
You could use a subselect for the max date </p>

```<code>  select
      `products`.id AS ids,
      `products`.name,
      `products`.link,
      t.date,
      t.price,
      t.availability,
       AVG(`products-prices`.price) AS medie,
       MIN(`products-prices`.price) AS minim

  from  `products`
  inner join `products-prices`  ON `products`.id=`products-prices`.id_produs
  inner join ( )
  select id_produs, date, price, availability
  from `products-prices`
  where ( id_produs, date ) = (
  select id_produs, max(date) as max_date
  from `products-prices`
  group by id ) t on t.id_produs = `products`.id_prod
</code>```

Body:
I have two Mysql tables:

products with id, name, link

products-prices with id, id_prod, price, availability and date

In the second one, as you can see I can have more prices for the same product depending on the time it was updated, what I want to do is to have one query to show me the lowest price, average price and latest price. I can get first two (lowest and average price) in one query and latest price in another query but I don't know how to concatenate them or if there is another way.

My first query looks like that:

SELECT
    `products`.id AS ids, `products`.name, `products`.link,
    `products-prices`.id AS id_p, `products-prices`.price,
    `products-prices`.availability, `products-prices`.date,
    AVG(`products-prices`.price) AS medie,
    MIN(`products-prices`.price) AS minim
FROM
    `products-prices`
INNER JOIN
    `products` ON `products`.id = `products-prices`.id_produs
GROUP BY
    ids
ORDER BY
    ids

and the second one is:

SELECT *
FROM `products-prices`
WHERE date IN (SELECT DISTINCT MAX(date) max_date
               FROM `products-prices`
               GROUP BY id_produs)

Can you give me an idea how to combine them? Thank you very much!

(I don't know how UNION works and if it works, I will try it)

//EDIT: And I also have another question, can I get the MIN, AVG values without the latest entry in database ?

Body:
You could use a subselect for the max date

  select
      `products`.id AS ids,
      `products`.name,
      `products`.link,
      t.date,
      t.price,
      t.availability,
       AVG(`products-prices`.price) AS medie,
       MIN(`products-prices`.price) AS minim

  from  `products`
  inner join `products-prices`  ON `products`.id=`products-prices`.id_produs
  inner join ( )
  select id_produs, date, price, availability
  from `products-prices`
  where ( id_produs, date ) = (
  select id_produs, max(date) as max_date
  from `products-prices`
  group by id ) t on t.id_produs = `products`.id_prod


问:
Laravel - How to restrict certain functionality based on user authentication?
Laravel newbie here (obviously :D ). I've set up a new model & controller for a model named Pages.

Every User has many Pages.

Each Page has a single User.

I've created the following functioning controller actions (& views):

```<code>PagesController::index
PagesController::create
PagesController::store
PagesController::show
PagesController::edit
PagesController::delete
</code>```

So you can edit a Page by going to url.dev/pages/{id}/edit.

The problem is, you can access all of these routes regardless of your session status. So random users can edit any given Page. Which, obviously, is terrible.

Can anyone point me in the direction of what I should read up on, to limit the ability to access my model's controller actions based on whether or not the user is logged in (and if it's the correct user, at all)?

答:
Other answers are good, but I prefer to use middleware on route groups.

So when I have several routes like this:

```<code>Route::get('pages', 'PagesController@index')->name('pages.index');

Route::get('pages/{id}/edit', 'PagesController@edit')->name('pages.edit');
</code>```

I would add them inside Laravel Route group. Like this:

```<code>Route::group(['middleware' => 'auth'], function() {
    Route::get('pages', 'PagesController@index')->name('pages.index');

    Route::get('pages/{id}/edit', 'PagesController@edit')->name('pages.edit');
});
</code>```

Body:
Laravel newbie here (obviously :D ). I've set up a new model & controller for a model named Pages.

Every User has many Pages.

Each Page has a single User.

I've created the following functioning controller actions (& views):

PagesController::index
PagesController::create
PagesController::store
PagesController::show
PagesController::edit
PagesController::delete

So you can edit a Page by going to url.dev/pages/{id}/edit.

The problem is, you can access all of these routes regardless of your session status. So random users can edit any given Page. Which, obviously, is terrible.

Can anyone point me in the direction of what I should read up on, to limit the ability to access my model's controller actions based on whether or not the user is logged in (and if it's the correct user, at all)?

Body:
Other answers are good, but I prefer to use middleware on route groups.

So when I have several routes like this:

Route::get('pages', 'PagesController@index')->name('pages.index');

Route::get('pages/{id}/edit', 'PagesController@edit')->name('pages.edit');

I would add them inside Laravel Route group. Like this:

Route::group(['middleware' => 'auth'], function() {
    Route::get('pages', 'PagesController@index')->name('pages.index');

    Route::get('pages/{id}/edit', 'PagesController@edit')->name('pages.edit');
});


问:
How do i modify Linq generated sql statement?
I have summarized my problem in following code.

```<code>NorthwindDataContext dc = new NorthwindDataContext();
        var query = from c in dc.Customers
                    select c;
</code>```

Above code is generating following sql statement

```
    SELECT [t0].[ID], [t0].[FirstName], [t0].[LastName]
FROM [dbo].[Customer] AS [t0]
```

Now i want to modify the above generated query something like this

```
SELECT [t0].[ID], [t0].[FirstName], [t0].[LastName] FROM [dbo].[Customer]
AS [t0] WITH (nolock)
```

Is it possible in linq to modify the generated query?If yes then how?

答: You will not be able to modify the generated L2S T-SQL code directly, the way you want (unless you modify the transaction isolation level). However, we've dealt with situations like this, fairly simply, by creating a view with lock hints we want in place and querying the view, instead of the table directly.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have summarized my problem in following code.

NorthwindDataContext dc = new NorthwindDataContext();
        var query = from c in dc.Customers
                    select c;

Above code is generating following sql statement

    SELECT [t0].[ID], [t0].[FirstName], [t0].[LastName]
FROM [dbo].[Customer] AS [t0]

Now i want to modify the above generated query something like this

SELECT [t0].[ID], [t0].[FirstName], [t0].[LastName] FROM [dbo].[Customer]
AS [t0] WITH (nolock)

Is it possible in linq to modify the generated query?If yes then how?


问:
How to search wikipedia by date range and around a location?
I am trying to do what this guy says has done using angular on this SO question

His code goes by:

```<code>.controller('WikiQueryCtrl', ['$scope', '$http', function($scope, $http) {
    $http({
            //these geo coordinates and the date ranges will eventually be dynamic.
            url: 'https://wdq.wmflabs.org/api?q=AROUND[625,-25.911389,31.957222,5]%20AND%20BETWEEN[585,1985,1987]&callback=JSON_CALLBACK',
            method: 'jsonp'
        })
        .success(function(response) {
            var items = response.items;
            $scope.jason = items;
            var wikiDataString = 'http://www.wikidata.org/w/api.php?action=wbgetentities&format=json&ids=Q' + items + '&props=sitelinks%7Csitelinks%2Furls&callback=JSON_CALLBACK';
            $http({
                    url: wikiDataString,
                    method: 'jsonp'
                })
                .success(function(response2) {
                    $scope.jason2 = response2;
                    var url = response2.entities["Q" + items].sitelinks.enwiki.url;
                    var wikipediaTitle = url.substr(24, url.length);
                    var wikipediaURL = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=' + wikipediaTitle + '&format=json&explaintext&redirects&inprop=url&indexpageids&format=json&callback=JSON_CALLBACK';
                    $http({
                        url: wikipediaURL,
                        method: 'jsonp'

                    }).success(function(response4) {
                        var query = response4.query;
                        var pageID = response4.query.pageids;
                        var title = response4.query.pages[pageID].title;
                        var fullurl = response4.query.pages[pageID].fullurl;
                        var content = response4.query.pages[pageID].extract;
                        $scope.title = title;
                        $scope.content = content;
                        $scope.fullurl = fullurl;
                        $scope.jason = query;
                    });
                });
        });
}]);
</code>```

I know wikipedia has a geosearch but not a date range, I tried to look at wikidata as the guy has done and to convert it into jQuery but with no positive results, here it is a code pen:

https://codepen.io/anon/pen/PjywjR

How would I achieve in jQuery what the guy has said to have achieved using Angular, to search wikipedia content by coordinates and date range.

答:
I haven't worked with the Wikipedia API and the URL https://wdq.wmflabs.org gives me a 502 code both in the browser and in an AJAX request. So first question would be: are you sure that's a valid API endpoint?

Next, I would simplify your AJAX request while you test and debug:

```<code>var url = "https://wdq.wmflabs.org/api";
var data = {
  q: "AROUND[625,-25.911389,31.957222,5]%20AND%20BETWEEN[585,1985,1987]",
  callback: "JSON_CALLBACK"
};

$.ajax({
  dataType: "jsonp",
  url: url,
  data: data,
  success: function(data) {
    console.log(data);
  }
});
</code>```

As noted above, this request receives a 502 Bad Gateway response at present.

Body:
I am trying to do what this guy says has done using angular on this SO question

His code goes by:

.controller('WikiQueryCtrl', ['$scope', '$http', function($scope, $http) {
    $http({
            //these geo coordinates and the date ranges will eventually be dynamic.
            url: 'https://wdq.wmflabs.org/api?q=AROUND[625,-25.911389,31.957222,5]%20AND%20BETWEEN[585,1985,1987]&callback=JSON_CALLBACK',
            method: 'jsonp'
        })
        .success(function(response) {
            var items = response.items;
            $scope.jason = items;
            var wikiDataString = 'http://www.wikidata.org/w/api.php?action=wbgetentities&format=json&ids=Q' + items + '&props=sitelinks%7Csitelinks%2Furls&callback=JSON_CALLBACK';
            $http({
                    url: wikiDataString,
                    method: 'jsonp'
                })
                .success(function(response2) {
                    $scope.jason2 = response2;
                    var url = response2.entities["Q" + items].sitelinks.enwiki.url;
                    var wikipediaTitle = url.substr(24, url.length);
                    var wikipediaURL = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=' + wikipediaTitle + '&format=json&explaintext&redirects&inprop=url&indexpageids&format=json&callback=JSON_CALLBACK';
                    $http({
                        url: wikipediaURL,
                        method: 'jsonp'

                    }).success(function(response4) {
                        var query = response4.query;
                        var pageID = response4.query.pageids;
                        var title = response4.query.pages[pageID].title;
                        var fullurl = response4.query.pages[pageID].fullurl;
                        var content = response4.query.pages[pageID].extract;
                        $scope.title = title;
                        $scope.content = content;
                        $scope.fullurl = fullurl;
                        $scope.jason = query;
                    });
                });
        });
}]);

I know wikipedia has a geosearch but not a date range, I tried to look at wikidata as the guy has done and to convert it into jQuery but with no positive results, here it is a code pen:

https://codepen.io/anon/pen/PjywjR

How would I achieve in jQuery what the guy has said to have achieved using Angular, to search wikipedia content by coordinates and date range.

Body:
I haven't worked with the Wikipedia API and the URL https://wdq.wmflabs.org gives me a 502 code both in the browser and in an AJAX request. So first question would be: are you sure that's a valid API endpoint?

Next, I would simplify your AJAX request while you test and debug:

var url = "https://wdq.wmflabs.org/api";
var data = {
  q: "AROUND[625,-25.911389,31.957222,5]%20AND%20BETWEEN[585,1985,1987]",
  callback: "JSON_CALLBACK"
};

$.ajax({
  dataType: "jsonp",
  url: url,
  data: data,
  success: function(data) {
    console.log(data);
  }
});

As noted above, this request receives a 502 Bad Gateway response at present.


问:
Adding required to HTML input when checkbox is checked
I have an hidden div which will contain some HTML inputs which some are needed to be required as part of a form. the div is visible by checking the checkbox and the code looks like this:

$(function() {
  var checkbox = $("#checkbox01");
  var hidden = $("#div01");
  hidden.hide();
  checkbox.change(function() {
    if (checkbox.is(':checked')) {
      hidden.show();
    } else {
      hidden.hide();
      $("#username").val("");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label><input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label>
<div id="div01">
  <input name="username" type="text" required>
</div></code>```

You can see the code in action on JSfiddle
As you can see the div is hidden when the checkbox is unchecked and also the username is cleaned when the div is hidden (checkbox unchecked).

How can I make the required be added to HTML only if checkbox is checked, so user won't get prompt to enter value when the div is hidden by Jquery... ?

答:
You could just toggle the type to hidden, that way it's no longer required

```<code>$("#checkbox01").on('change', function() {
    $("#div01").toggle(this.checked)
               .find('input').prop('type', this.checked ? 'text' : 'hidden')
               .val('');
    }).trigger('change');
</code>```

$(function() {
  $("#checkbox01").on('change', function() {
    $("#div01").toggle(this.checked).find('input').prop('type', this.checked ? 'text' : 'hidden').val('');
  }).trigger('change');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label>
    <input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label>
  <div id="div01">
    <input name="username" type="text" required="required">
  </div>
  <input type="submit">
</form></code>```

Body:
I have an hidden div which will contain some HTML inputs which some are needed to be required as part of a form. the div is visible by checking the checkbox and the code looks like this:

$(function() {
  var checkbox = $("#checkbox01");
  var hidden = $("#div01");
  hidden.hide();
  checkbox.change(function() {
    if (checkbox.is(':checked')) {
      hidden.show();
    } else {
      hidden.hide();
      $("#username").val("");
    }
  });
});

<input id="checkbox01" name="checkbox01" type="checkbox">show/hide

  <input name="username" type="text" required>

You can see the code in action on JSfiddle
As you can see the div is hidden when the checkbox is unchecked and also the username is cleaned when the div is hidden (checkbox unchecked).

How can I make the required be added to HTML only if checkbox is checked, so user won't get prompt to enter value when the div is hidden by Jquery... ?

Body:
You could just toggle the type to hidden, that way it's no longer required

$("#checkbox01").on('change', function() {
    $("#div01").toggle(this.checked)
               .find('input').prop('type', this.checked ? 'text' : 'hidden')
               .val('');
    }).trigger('change');

$(function() {
  $("#checkbox01").on('change', function() {
    $("#div01").toggle(this.checked).find('input').prop('type', this.checked ? 'text' : 'hidden').val('');
  }).trigger('change');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label>
    <input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label>
  <div id="div01">
    <input name="username" type="text" required="required">
  </div>
  <input type="submit">
</form>


答:
I suggest you use  hashmap, rather than arraylist of strings. The basic format of a hashmap is as follows:

```<code>HashMap h <String, String> = new Hashmap<String, String>();
h.put("riddle", "answer");
h.put("riddle", "answer");
h.put("riddle", "answer");
h.put("riddle", "answer");
h.put("riddle", "answer");
</code>```

To get the answer from the randomly generated hashmap, you would simply do:

```<code>String answer = h.get("riddle")
</code>```

There you have it.  To get the random hashmap maybe do something like this:

```<code>String randomValue = (String) values[(new Random).nextInt(value.length)];
</code>```

This gets you a random value within the range of your hashmap:

```<code>String randomRiddle=h[randomValue]
</code>```

Do this, get back to me, tell me how it went.

Title: How to match correct answers in a randomly generated array in Android?

Body:
So I'm creating a riddle app that when you swipe up on the screen it will come up with a riddle that is randomly generated using an array. Now I have no idea which riddle will pop up because of course, it's random but I want the user to be able to click and hold on the randomly generated riddle and the answer will then pop up replacing the riddle. So far I have the array done to where it will randomly generate a riddle but I'm having a problem getting the answer to match up with riddles. How would I go about matching correct answers to a random array on a long press of the text view?

I did see two other questions (one,two) and similar to this one but it did not answer the question that I have and it really wasn't specific.

final TextView answerTxt = (TextView) findViewById(R.id.answerTxt);

    //List with the riddles and its values
    HashMap<String, String> h = new Hashmap<String, String>();
    h.put("a", "v");
    h.put("b", "w");
    h.put("c", "x");
    h.put("d", "y");
    h.put("e", "z");

    //rand generator for array
    String[] yourKeyList = h.keySet().toArray(new String[]{});

    String[] yourValueList = h.values().toArray(new String[]{});

    String randomKey = yourKeyList[new Random().nextInt(yourKeyList.length)];

    final String keyValue = yourValueList[yourValueList.length];

    answerTxt.setText(randomKey);

    answerTxt.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            answerTxt.setText(keyValue);
            return true;
        }
    });

Body:
I suggest you use  hashmap, rather than arraylist of strings. The basic format of a hashmap is as follows:

HashMap h <String, String> = new Hashmap<String, String>();
h.put("riddle", "answer");
h.put("riddle", "answer");
h.put("riddle", "answer");
h.put("riddle", "answer");
h.put("riddle", "answer");

To get the answer from the randomly generated hashmap, you would simply do:

String answer = h.get("riddle")

There you have it.  To get the random hashmap maybe do something like this:

String randomValue = (String) values[(new Random).nextInt(value.length)];

This gets you a random value within the range of your hashmap:

String randomRiddle=h[randomValue]

Do this, get back to me, tell me how it went.


问:
Regex match for Pivotal Tracker
Pivotal Tracker can parse git commits and change ticket status accordingly. I am writing a PHP script that executes post-commit. It searches the commit message and if it finds the right Pivotal Ticket reference it posts it to the PT api. I'm going a bit nuts trying to figure out the regex.

Currently I have:

```<code>preg_match('/^\[#([0-9]{1,16})\]/', $commit['message'], $matches);
</code>```

So the simplest example of a commit passes:

```<code>[#12345678] Made a commit
</code>```

But what I need to pass are the following:

```<code>1: [finished #12345678] Made a commit //'fixed', 'complete', or 'finished' changes the status
2: I made a commit [#12345678] to a story //Can occur anywhere in the commit
</code>```

答:
```<code>$string = '2: I made a commit [#12345678] to a story
1: [finished #12345678] Made a commit
3: [fixed #12345678] Made a commit
4: [complete #12345678] Made a commit';

$m = [];
$regex = '/.*\[(finished|fixed|complete)?\s*#(\d+)\]/';

preg_match_all($regex,$string,$m);

echo '```';
print_r($m);
echo '```';
</code>```

Should give you

```<code>Array
(
[0] => Array
    (
        [0] => 2: I made a commit [#12345678]
        [1] => 1: [finished #12345678]
        [2] => 3: [fixed #12345678]
        [3] => 4: [complete #12345678]
    )

[1] => Array
    (
        [0] =>
        [1] => finished
        [2] => fixed
        [3] => complete
    )

[2] => Array
    (
        [0] => 12345678
        [1] => 12345678
        [2] => 12345678
        [3] => 12345678
    )

)
</code>```

As you can see the () in the regex expression act as groups which stores the results in an array $m

```<code>$m[0] -> stores complete match
$m[1] -> stores first group ()
$m[2] -> stores second group ()
</code>```

I think safest way to do this is to process one commit at a time, but this example is just showing you the use cases in the question.

Title: Regex match for Pivotal Tracker

Body:
Pivotal Tracker can parse git commits and change ticket status accordingly. I am writing a PHP script that executes post-commit. It searches the commit message and if it finds the right Pivotal Ticket reference it posts it to the PT api. I'm going a bit nuts trying to figure out the regex.

Currently I have:

preg_match('/^\[#([0-9]{1,16})\]/', $commit['message'], $matches);

So the simplest example of a commit passes:

[#12345678] Made a commit

But what I need to pass are the following:

1: [finished #12345678] Made a commit //'fixed', 'complete', or 'finished' changes the status
2: I made a commit [#12345678] to a story //Can occur anywhere in the commit

Body:
$string = '2: I made a commit [#12345678] to a story
1: [finished #12345678] Made a commit
3: [fixed #12345678] Made a commit
4: [complete #12345678] Made a commit';

$m = [];
$regex = '/.*\[(finished|fixed|complete)?\s*#(\d+)\]/';

preg_match_all($regex,$string,$m);

echo '<pre>';
print_r($m);
echo '</pre>';

Should give you

Array
(
[0] => Array
    (
        [0] => 2: I made a commit [#12345678]
        [1] => 1: [finished #12345678]
        [2] => 3: [fixed #12345678]
        [3] => 4: [complete #12345678]
    )

[1] => Array
    (
        [0] =>
        [1] => finished
        [2] => fixed
        [3] => complete
    )

[2] => Array
    (
        [0] => 12345678
        [1] => 12345678
        [2] => 12345678
        [3] => 12345678
    )

)

As you can see the () in the regex expression act as groups which stores the results in an array $m

$m[0] -> stores complete match
$m[1] -> stores first group ()
$m[2] -> stores second group ()

I think safest way to do this is to process one commit at a time, but this example is just showing you the use cases in the question.


问:
Implementing interface function - claims to incorrectly implement interface

Goal

I'm optimally trying to just enforce the typing in the project so that anyone that implements an Animal must provide this function and ensure that the function can only take either a Woof or a Meow as the sole parameter and must return only either a Woof or Meow.

Initial Attempt

Here's some sample code that's similar (except in names) to the code I've got in VSCode (using TypeScript 2.4.1):

```<code>class Woof {
    constructor(private a: boolean = true) {}
}

class Meow {
    constructor(private b: string = "abc") {}
}

class Dog implements Animal  {
    doSomething(sound: Woof): Woof {
        return new Woof();
    }
}

class Cat implements Animal {
    doSomething(sound: Meow): Meow {
        return new Meow();
    }
}

interface Animal {
    doSomething: <T extends Woof | Meow>(input: T) => T;
}
</code>```

If I drop it in the TypeScript playground, it yields the JavaScript I'd expect without error.

However, within VSCode, I've got a red squiggly line under both the Dog and Cat classes and the mouseover reads all of the following:

Class 'Dog' incorrectly implements interface 'Animal'.

Types of property 'doSomething' are incompatible.

Type '(sound: Woof) => Woof' is not assignable to a type '(input: T) => T'.

Types of parameters 'sound' and 'sound' are incompatible.

Type 'T' is not assignable to type 'Woof'.

Type 'Woof | Meow' is not assignable to type 'Woof'.

Type 'Meow' is not assignable to type 'Woof'.

Property 'a' is missing in type 'Meow'

Each of the errors is nested, so it's difficult to display the formatting accurately here, but it appears to indicate that I can't just specify either a Woof or Meow type when extending the generic because the private properties aren't implemented across both types (which looks similar to another question here). This is despite not seeing anything in the documentation that would indicate that this is illegal (and again, in the playground, this appears to work without issue). But, unlike that question, I don't want the generic to extend both types, but rather be constrained to one or the other.

Reading the description in a post about intersection types, it reads "A union type A | B represents an entity that is either of type A or type B, whereas an intersection type A & B represents an entity that is both type A and type B". Reading that, I definitely want a union type, but that's what I appear to have above, and it isn't appearing to take.

The types are flipped in the squigglies under the alternate class, but the message is the same.

I also get this error when I actually build my project with 'tsc' in the output.

Alternate attempt - Replacing the types with an interface each implements

I've also tried implementing the following in hopes that it would eliminate that bizarre need for the private properties to match between the Woof and Meow classes (in case something unexpected was just not working when specifying each):

```<code>interface Sound {
}

class Woof implements Sound {
    constructor(private a: boolean = true) {}
}

class Meow implements Sound {
    constructor(private b: string = "abc") {}
}

class Dog implements Animal  {
    doSomething(sound: Woof): Woof {
        return new Woof();
    }
}

class Cat implements Animal {
    doSomething(sound: Meow): Meow {
        return new Meow();
    }
}

interface Animal {
    doSomething: <T extends Sound>(input: T) => T;
}
</code>```

I get exactly the same error as before for each of the classes.

Semi-working Version

Now, if I just eliminate the generics altogether and use only the interface from the alternative above, it solves part of the goal in that I can restrict the parameter and the result to a class implementing the interface, but that's not exactly ideal since it doesn't prevent another developer from passing in one interface implementation and attempting to return another.

```<code>interface Sound {
}

class Woof implements Sound {
    constructor(private a: boolean = true) {}
}

class Meow implements Sound {
    constructor(private b: string = "abc") {}
}

class Dog implements Animal  {
    doSomething(sound: Woof): Woof {
        return new Woof();
    }
}

class Cat implements Animal {
    doSomething(sound: Meow): Meow {
        return new Meow();
    }
}

interface Animal {
    doSomething: (input: Sound) => Sound;
}
</code>```

I'd prefer the type safety of using generics and limiting T to one implementation. Any ideas about how I can go about this using generics with a syntax that Typescript would actually work with outside of the playground?

答:
Would this work for you?</p>

```<code>class Woof {
  constructor(private a: boolean = true) { }
}

class Meow {
  constructor(private b: string = "abc") { }
}

class Dog implements Animal<Woof> {
  doSomething(sound: Woof): Woof {
    return new Woof();
  }
}

class Cat implements Animal<Meow> {
  doSomething(sound: Meow): Meow {
    return new Meow();
  }
}

interface Animal<T extends Meow | Woof> {
  doSomething(input: T): T;
}
</code>```

Body:
Goal

I'm optimally trying to just enforce the typing in the project so that anyone that implements an Animal must provide this function and ensure that the function can only take either a Woof or a Meow as the sole parameter and must return only either a Woof or Meow.

Initial Attempt

Here's some sample code that's similar (except in names) to the code I've got in VSCode (using TypeScript 2.4.1):

class Woof {
    constructor(private a: boolean = true) {}
}

class Meow {
    constructor(private b: string = "abc") {}
}

class Dog implements Animal  {
    doSomething(sound: Woof): Woof {
        return new Woof();
    }
}

class Cat implements Animal {
    doSomething(sound: Meow): Meow {
        return new Meow();
    }
}

interface Animal {
    doSomething: <T extends Woof | Meow>(input: T) => T;
}

If I drop it in the TypeScript playground, it yields the JavaScript I'd expect without error.

However, within VSCode, I've got a red squiggly line under both the Dog and Cat classes and the mouseover reads all of the following:

Class 'Dog' incorrectly implements interface 'Animal'.

Types of property 'doSomething' are incompatible.

Type '(sound: Woof) => Woof' is not assignable to a type '(input: T) => T'.

Types of parameters 'sound' and 'sound' are incompatible.

Type 'T' is not assignable to type 'Woof'.

Type 'Woof | Meow' is not assignable to type 'Woof'.

Type 'Meow' is not assignable to type 'Woof'.

Property 'a' is missing in type 'Meow'

Each of the errors is nested, so it's difficult to display the formatting accurately here, but it appears to indicate that I can't just specify either a Woof or Meow type when extending the generic because the private properties aren't implemented across both types (which looks similar to another question here). This is despite not seeing anything in the documentation that would indicate that this is illegal (and again, in the playground, this appears to work without issue). But, unlike that question, I don't want the generic to extend both types, but rather be constrained to one or the other.

Reading the description in a post about intersection types, it reads "A union type A | B represents an entity that is either of type A or type B, whereas an intersection type A & B represents an entity that is both type A and type B". Reading that, I definitely want a union type, but that's what I appear to have above, and it isn't appearing to take.

The types are flipped in the squigglies under the alternate class, but the message is the same.

I also get this error when I actually build my project with 'tsc' in the output.

Alternate attempt - Replacing the types with an interface each implements

I've also tried implementing the following in hopes that it would eliminate that bizarre need for the private properties to match between the Woof and Meow classes (in case something unexpected was just not working when specifying each):

interface Sound {
}

class Woof implements Sound {
    constructor(private a: boolean = true) {}
}

class Meow implements Sound {
    constructor(private b: string = "abc") {}
}

class Dog implements Animal  {
    doSomething(sound: Woof): Woof {
        return new Woof();
    }
}

class Cat implements Animal {
    doSomething(sound: Meow): Meow {
        return new Meow();
    }
}

interface Animal {
    doSomething: <T extends Sound>(input: T) => T;
}

I get exactly the same error as before for each of the classes.

Semi-working Version

Now, if I just eliminate the generics altogether and use only the interface from the alternative above, it solves part of the goal in that I can restrict the parameter and the result to a class implementing the interface, but that's not exactly ideal since it doesn't prevent another developer from passing in one interface implementation and attempting to return another.

interface Sound {
}

class Woof implements Sound {
    constructor(private a: boolean = true) {}
}

class Meow implements Sound {
    constructor(private b: string = "abc") {}
}

class Dog implements Animal  {
    doSomething(sound: Woof): Woof {
        return new Woof();
    }
}

class Cat implements Animal {
    doSomething(sound: Meow): Meow {
        return new Meow();
    }
}

interface Animal {
    doSomething: (input: Sound) => Sound;
}

I'd prefer the type safety of using generics and limiting T to one implementation. Any ideas about how I can go about this using generics with a syntax that Typescript would actually work with outside of the playground?

Body:
Would this work for you?

class Woof {
  constructor(private a: boolean = true) { }
}

class Meow {
  constructor(private b: string = "abc") { }
}

class Dog implements Animal<Woof> {
  doSomething(sound: Woof): Woof {
    return new Woof();
  }
}

class Cat implements Animal<Meow> {
  doSomething(sound: Meow): Meow {
    return new Meow();
  }
}

interface Animal<T extends Meow | Woof> {
  doSomething(input: T): T;
}


问:
Bootstrap Alert - show then hide - cannot show again
I have a simple hidden dismissible bootstrap alert:

  <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

<button type="button" id="getSelectedAssets" class="btn btn-primary">Show Selected Assets</button>```
</div>
</div>
</p>

<p>A button is set to run a script that displays the hidden alert:</p>

```$("#selectedAssetsDetails").html('Selected Assets: '+values);
$("#selectedAssets").show();
```

<p>This works successfully the first time to show the alert, but if the user closes the alert it won't display the alert again by clicking the button to show the alert. I assumed:</p>

```$("#selectedAssets").show();
```

would always show the alert?

答:
data-dismiss remove Div from HTML , you must set your action for Close Button like this

$('#getSelectedAssets').click(function() {
  $('#selectedAssets').show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="selectedAssets" class="alert alert-info text-center alert-dismissible" role="alert" style="display:none">
  <button type="button" class="close" onclick="$('#selectedAssets').hide()" aria-label="Close"><span aria-hidden="true">×</span></button>
  <div id="selectedAssetsDetails">Alert </div>
</div>

<button type="button" id="getSelectedAssets" class="btn btn-primary">Show Selected Assets</button></code>```

Body:
I have a simple hidden dismissible bootstrap alert:

  <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

<button type="button" id="getSelectedAssets" class="btn btn-primary">Show Selected Assets</button>

A button is set to run a script that displays the hidden alert:

$("#selectedAssetsDetails").html('Selected Assets: '+values);
$("#selectedAssets").show();

This works successfully the first time to show the alert, but if the user closes the alert it won't display the alert again by clicking the button to show the alert. I assumed:

$("#selectedAssets").show();

would always show the alert?

Body:
data-dismiss remove Div from HTML , you must set your action for Close Button like this

$('#getSelectedAssets').click(function() {
  $('#selectedAssets').show();
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="selectedAssets" class="alert alert-info text-center alert-dismissible" role="alert" style="display:none">
  <button type="button" class="close" onclick="$('#selectedAssets').hide()" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  <div id="selectedAssetsDetails">Alert </div>
</div>

<button type="button" id="getSelectedAssets" class="btn btn-primary">Show Selected Assets</button>


问:
images does not display in chrome and firefox
Images does not display in firefox and in chrome. Safari works fine. I code the image as a background image in CSS and coded the image in HTML. When I preview the page, the image can only be seen in safari. Why? This occurred when I bought a new computer.

```<code><!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<img src="img/background.png" alt="">
</body>
</html>
</code>```

答: I found out why the image was not showing in firefox and chrome. The image itself was getting errors. I found out when I tried importing the image into photoshop, photoshopped has an error message saying "Could not place “background.png” because the file-format module cannot parse the file." So I made a new image in the html, and the image displayed on the browsers. </p>

Body:
Images does not display in firefox and in chrome. Safari works fine. I code the image as a background image in CSS and coded the image in HTML. When I preview the page, the image can only be seen in safari. Why? This occurred when I bought a new computer.

<!doctype html>

<meta charset="UTF-8">
<title>Untitled Document</title>


问:
C# ArgumentOutOfRangeException when closing forms
I am writing a WinForms C# Program.

I am trying to close all forms except my main form, FrmMain.

I must hide my main form.

I produced this by having two forms open. One with my main form, and one with another form shown with the ShowDialog() method.

When this code is executed on my machine, it appears that it should close all of the forms properly. For some reason, when I am not setting breakpoints and running this particular piece of code, I get an ArgumentOutOfRangeException because the variable i gets to the point where it is -1. When I do set breakpoints, and slowly step through each piece of code it works fine.

It doesn't make sense for the for loop to continue all the way for i to get to -1 because I have the i >= 0 condition.

Can someone explain to me why the index of i gets to -1 when I am not using breakpoints but gets to 0 when I am using breakpoints and stepping through each line of the loop individually?

What can be done to fix this?

Thanks in advance.

```<code>            for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
            {
                if (Application.OpenForms[i] is FrmMain)
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i]?.Hide();
                    });
                }
                else
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i]?.Dispose();
                    });
                }
            }
</code>```

EDIT:

The way I prevented getting the ArgumentOutOfRangeException is by adding another variable inside the for loop.
This is the code that I changed.

```<code>            for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
            {
                int i1 = i;
                if (Application.OpenForms[i] is FrmMain)
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i1]?.Hide();
                    });
                }
                else
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i1]?.Dispose();
                    });
                }
            }
</code>```

答:
Essentially, the for loop only terminates when the condition is false, meaning i has to get to -1 before it will stop. See
When does iteration variable in for loop increment should provides a good explanation.

Combined with the facts that you're using BeginInvoke, which essentially moves the execution to a separate thread (meaning it's execution could be delayed), and i is a captured variable it's entirely possible for i to be -1 when Dispose() is called.

When you've got breakpoints in place, you're probably slowing down the main thread execution enough that all the separate threads run in the expected order, so you won't see the problem.

You can find out about captured variables here: What are 'closures' in .NET?

Body:
I am writing a WinForms C# Program.

I am trying to close all forms except my main form, FrmMain.

I must hide my main form.

I produced this by having two forms open. One with my main form, and one with another form shown with the ShowDialog() method.

When this code is executed on my machine, it appears that it should close all of the forms properly. For some reason, when I am not setting breakpoints and running this particular piece of code, I get an ArgumentOutOfRangeException because the variable i gets to the point where it is -1. When I do set breakpoints, and slowly step through each piece of code it works fine.

It doesn't make sense for the for loop to continue all the way for i to get to -1 because I have the i >= 0 condition.

Can someone explain to me why the index of i gets to -1 when I am not using breakpoints but gets to 0 when I am using breakpoints and stepping through each line of the loop individually?

What can be done to fix this?

Thanks in advance.

            for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
            {
                if (Application.OpenForms[i] is FrmMain)
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i]?.Hide();
                    });
                }
                else
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i]?.Dispose();
                    });
                }
            }

EDIT:

The way I prevented getting the ArgumentOutOfRangeException is by adding another variable inside the for loop.
This is the code that I changed.

            for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
            {
                int i1 = i;
                if (Application.OpenForms[i] is FrmMain)
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i1]?.Hide();
                    });
                }
                else
                {
                    Application.OpenForms[i]?.BeginInvoke((MethodInvoker)delegate
                    {
                        Application.OpenForms[i1]?.Dispose();
                    });
                }
            }


答:
Please check this function, I added two lines in it

```<code>s1 = s1.replaceAll(s1.charAt(i) + "", "");
          i--;
</code>```

in you existing function

```<code>public static void printDups(String s1) {
    int count = 0;
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s1.length(); j++) {
            if (s1.charAt(i) == s1.charAt(j)) {
                count++;
            }

        }

        System.out.println(s1.charAt(i) + " --> " + count);
        s1 = s1.replaceAll(s1.charAt(i) + "", "");
      i--;
        count = 0;
    }

}
</code>```

Title: Print only each character and number once

Body:
I want to not use HashMap or Set when printing Duplicate characters in a String. But in solution I'm using I'm printing all the characters even if they are duplicates. I want to print each character once and with number of times it occurs in the string. Here's my example:

  public static void printDups(String s1) {
    int count = 0;
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s1.length(); j++) {
            if (s1.charAt(i) == s1.charAt(j)) {
                count++;
            }
        }

        System.out.println(s1.charAt(i) + " --> " + count);

        count = 0;
    }
}

public static void main(String[] args) {
    printDups("AABBCCDDD){}
}

And this is the output:

A --> 2
A --> 2
B --> 2
B --> 2
C --> 2
C --> 2
D --> 3
D --> 3

I want to print it like that:

A --> 2
B --> 2
C --> 2
D --> 3

I know I can add this: if (s1.charAt(i) != s1.charAt(i+1))         System.out.println(s1.charAt(i) + " --> " + count);
But then I'll have StringIndexOutOfBoundsException:

If I change my loop to this for (int i = 0; i < s1.length()-1; i++)

It'll skip the last character in the string.

How can I achieve this?

Body:
Please check this function, I added two lines in it

s1 = s1.replaceAll(s1.charAt(i) + "", "");
          i--;

in you existing function

public static void printDups(String s1) {
    int count = 0;
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s1.length(); j++) {
            if (s1.charAt(i) == s1.charAt(j)) {
                count++;
            }

        }

        System.out.println(s1.charAt(i) + " --> " + count);
        s1 = s1.replaceAll(s1.charAt(i) + "", "");
      i--;
        count = 0;
    }

}


问:
notification does not appear
The code bellow is supposed to show a heads up notification, but it is not appearing. However, the MessageActivity is starting without the notification shows up. This activity was supposed to start just when clicking the notification.

This problem does not occurs in API 23 (M). It only occurs in API 16 (JELLY_BEAN). Why the heads up notification appears in android M and is not appearing on android JellyBean?

Thank you in advance.

```<code>public class RunAlarm extends BroadcastReceiver{

    public static final String ACTION = "br.com.irms.randomalarm.RUN_ALARM_ACTION";
    private static final int ID_NOTIFICATION = 1;

    @Override
    public void onReceive(Context context, Intent intent) {
        String source = intent.getStringExtra("source");

        if(source.equals("scheduled_alarm")) {
            Intent showNotificationIntent = new Intent(context, MessageActivity.class);
            String contentTitle = context.getString(R.string.alarm);
            String contentText = intent.getStringExtra("hour");
            createHeadsUpNotificationWithAction(context, showNotificationIntent, contentTitle, contentText, ID_NOTIFICATION);
        } else if(source.equals("dismiss_alarm")) {
            Toast.makeText(context,"Alarm dismiss",Toast.LENGTH_SHORT).show();
            NotificationManagerCompat nm = NotificationManagerCompat.from(context);
            nm.cancel(ID_NOTIFICATION);
        } else if(source.equals("snooze_alarm")) {
            Toast.makeText(context,"Alarm snooze",Toast.LENGTH_SHORT).show();
            NotificationManagerCompat nm = NotificationManagerCompat.from(context);
            nm.cancel(ID_NOTIFICATION);
        }
    }

    public void createHeadsUpNotificationWithAction((Context context, Intent intent, String contentTitle, String contentText, int id) {
        PendingIntent p = getPendingIntent(context, intent, id);

        NotificationCompat.Builder b = new NotificationCompat.Builder(context);
        b.setDefaults(NotificationCompat.DEFAULT_ALL);
        b.setSmallIcon(R.drawable.ic_alarm_black_24dp);
        b.setContentTitle(contentTitle);
        b.setContentText(contentText);
        b.setContentIntent(p);
        b.setAutoCancel(true);
        b.setPriority(Notification.PRIORITY_MAX);
        b.setFullScreenIntent(p,false);

        try {
            Intent dismissAlarmIntent = new Intent();
            dismissAlarmIntent.setAction(ACTION);
            dismissAlarmIntent.putExtra("source","dismiss_alarm");
            PendingIntent actionDismissAlarmIntent = null;
            actionDismissAlarmIntent = PendingIntent.getBroadcast(
                    context, IdService.getUniqueId(context), dismissAlarmIntent, 0);

            Intent snoozeAlarmIntent = new Intent();
            snoozeAlarmIntent.setAction(ACTION);
            snoozeAlarmIntent.putExtra("source","snooze_alarm");
            PendingIntent actionSnoozeAlarmIntent = null;
            actionSnoozeAlarmIntent = PendingIntent.getBroadcast(
                    context, IdService.getUniqueId(context), snoozeAlarmIntent, 0);

            b.addAction(R.drawable.ic_delete_black_24dp, "Pause", actionDismissAlarmIntent);
            b.addAction(R.drawable.ic_calendar_black_24dp, "Play", actionSnoozeAlarmIntent);
        } catch (IOException e) {
            e.printStackTrace();
        }

        NotificationManagerCompat nm = NotificationManagerCompat.from(context);
        nm.notify(id, b.build());

    }

    private static PendingIntent getPendingIntent(Context context, Intent intent, int id) {
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(intent.getComponent());
        stackBuilder.addNextIntent(intent);
        PendingIntent p = stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
        return p;
    }
}
</code>```

This is my androidManifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.com.irms.layouttab">
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="br.com.irms.randomalarm.MainActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="br.com.irms.randomalarm.RunAlarm">
            <intent-filter>
                <action android:name="br.com.irms.randomalarm.RUN_ALARM_ACTION" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

        <activity
            android:name="br.com.irms.randomalarm.MessageActivity"
            android:label="@string/title_activity_message"
            android:parentActivityName="br.com.irms.randomalarm.MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="br.com.irms.randomalarm.MainActivity" />
        </activity>
    </application>

</manifest>
</code>```

答:
After some time looking for the answer I found it on the question bellow

HeadsUp Notification not displayed on KitKat

In short the heads up notification was only added in android 5.0. So, it was  just appearing in status bar and I did not realize that.

Title: notification does not appear

Body:
The code bellow is supposed to show a heads up notification, but it is not appearing. However, the MessageActivity is starting without the notification shows up. This activity was supposed to start just when clicking the notification.

This problem does not occurs in API 23 (M). It only occurs in API 16 (JELLY_BEAN). Why the heads up notification appears in android M and is not appearing on android JellyBean?

Thank you in advance.

public class RunAlarm extends BroadcastReceiver{

    public static final String ACTION = "br.com.irms.randomalarm.RUN_ALARM_ACTION";
    private static final int ID_NOTIFICATION = 1;

    @Override
    public void onReceive(Context context, Intent intent) {
        String source = intent.getStringExtra("source");

        if(source.equals("scheduled_alarm")) {
            Intent showNotificationIntent = new Intent(context, MessageActivity.class);
            String contentTitle = context.getString(R.string.alarm);
            String contentText = intent.getStringExtra("hour");
            createHeadsUpNotificationWithAction(context, showNotificationIntent, contentTitle, contentText, ID_NOTIFICATION);
        } else if(source.equals("dismiss_alarm")) {
            Toast.makeText(context,"Alarm dismiss",Toast.LENGTH_SHORT).show();
            NotificationManagerCompat nm = NotificationManagerCompat.from(context);
            nm.cancel(ID_NOTIFICATION);
        } else if(source.equals("snooze_alarm")) {
            Toast.makeText(context,"Alarm snooze",Toast.LENGTH_SHORT).show();
            NotificationManagerCompat nm = NotificationManagerCompat.from(context);
            nm.cancel(ID_NOTIFICATION);
        }
    }

    public void createHeadsUpNotificationWithAction((Context context, Intent intent, String contentTitle, String contentText, int id) {
        PendingIntent p = getPendingIntent(context, intent, id);

        NotificationCompat.Builder b = new NotificationCompat.Builder(context);
        b.setDefaults(NotificationCompat.DEFAULT_ALL);
        b.setSmallIcon(R.drawable.ic_alarm_black_24dp);
        b.setContentTitle(contentTitle);
        b.setContentText(contentText);
        b.setContentIntent(p);
        b.setAutoCancel(true);
        b.setPriority(Notification.PRIORITY_MAX);
        b.setFullScreenIntent(p,false);

        try {
            Intent dismissAlarmIntent = new Intent();
            dismissAlarmIntent.setAction(ACTION);
            dismissAlarmIntent.putExtra("source","dismiss_alarm");
            PendingIntent actionDismissAlarmIntent = null;
            actionDismissAlarmIntent = PendingIntent.getBroadcast(
                    context, IdService.getUniqueId(context), dismissAlarmIntent, 0);

            Intent snoozeAlarmIntent = new Intent();
            snoozeAlarmIntent.setAction(ACTION);
            snoozeAlarmIntent.putExtra("source","snooze_alarm");
            PendingIntent actionSnoozeAlarmIntent = null;
            actionSnoozeAlarmIntent = PendingIntent.getBroadcast(
                    context, IdService.getUniqueId(context), snoozeAlarmIntent, 0);

            b.addAction(R.drawable.ic_delete_black_24dp, "Pause", actionDismissAlarmIntent);
            b.addAction(R.drawable.ic_calendar_black_24dp, "Play", actionSnoozeAlarmIntent);
        } catch (IOException e) {
            e.printStackTrace();
        }

        NotificationManagerCompat nm = NotificationManagerCompat.from(context);
        nm.notify(id, b.build());

    }

    private static PendingIntent getPendingIntent(Context context, Intent intent, int id) {
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(intent.getComponent());
        stackBuilder.addNextIntent(intent);
        PendingIntent p = stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
        return p;
    }
}

This is my androidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.com.irms.layouttab">
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="br.com.irms.randomalarm.MainActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="br.com.irms.randomalarm.RunAlarm">
            <intent-filter>
                <action android:name="br.com.irms.randomalarm.RUN_ALARM_ACTION" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

        <activity
            android:name="br.com.irms.randomalarm.MessageActivity"
            android:label="@string/title_activity_message"
            android:parentActivityName="br.com.irms.randomalarm.MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="br.com.irms.randomalarm.MainActivity" />
        </activity>
    </application>

</manifest>


问:
Is it possible to parameterize a query inside pl sql?
The stored procedures being written here currently concats the parameters to the queries:

```<code>   SELECT *
     FROM Names
    WHERE Name = ' || prmName || '
 ORDER BY ' || prmSortField
</code>```

Is it possible to parameterize this query inside the stored procedure? Possibly like:

```<code>query = 'select * From Names Where Name = @name Order By ' || prmSortField
call(query, prmName)
</code>```

Note:
In case you wonder why we do so, there are two common parameters for our sp's: sortFieldIndex and sortDirection. Since we cannot directly parameterize these, the query is dynamically generated. But other parameters make the queries open for injection. So I am looking a way to parameterize some of the parameters.

答:
Absolutely.  Use cursors.</p>

```<code>DECLARE
  CURSOR c1 (job VARCHAR2, max_wage NUMBER) IS
    SELECT * FROM employees WHERE job_id = job AND salary > max_wage;
BEGIN
  FOR person IN c1('CLERK', 3000)
  LOOP
     -- process data record
    DBMS_OUTPUT.PUT_LINE('Name = ' || person.last_name || ', salary = ' ||
                         person.salary || ', Job Id = ' || person.job_id );
  END LOOP;
END;
</code>```

OwnerDisplayName: buyutec

Body:
The stored procedures being written here currently concats the parameters to the queries:

   SELECT *
     FROM Names
    WHERE Name = ' || prmName || '
 ORDER BY ' || prmSortField

Is it possible to parameterize this query inside the stored procedure? Possibly like:

query = 'select * From Names Where Name = @name Order By ' || prmSortField
call(query, prmName)

Note:
In case you wonder why we do so, there are two common parameters for our sp's: sortFieldIndex and sortDirection. Since we cannot directly parameterize these, the query is dynamically generated. But other parameters make the queries open for injection. So I am looking a way to parameterize some of the parameters.

LastEditorDisplayName: coldice

Body:
Absolutely.  Use cursors.

DECLARE
  CURSOR c1 (job VARCHAR2, max_wage NUMBER) IS
    SELECT * FROM employees WHERE job_id = job AND salary > max_wage;
BEGIN
  FOR person IN c1('CLERK', 3000)
  LOOP
     -- process data record
    DBMS_OUTPUT.PUT_LINE('Name = ' || person.last_name || ', salary = ' ||
                         person.salary || ', Job Id = ' || person.job_id );
  END LOOP;
END;

OwnerDisplayName: cletus


问:
Help with strange memory behavior. Looking for leaks both in my brain and in my code
I spent the last few days trying to find memory leaks in a program we are developing.

First of all, I tried using some leak detectors. After fixing a few issues, they do not find any leaks any more. However, I am also monitoring my application using perfmon.exe. Performance Monitor reports that 'Private Bytes' and 'Working Set - Private' are steadily rising when the app is used. To me, this suggests that the program is using more and more memory the longer it runs. Internal resources seem to be stable however, so this sounds like leaking to me.

The program is loading a DLL at runtime. I suspect that these leaks or whatever they are occur in that library and get purged when the library is unloaded, hence they won't get picked up by the leak detectors. I used both DevPartner BoundsChecker and Virtual Leak Detector to look for memory leaks. Both supposedly catch leaks in DLLs.

Also, the memory consumption is increasing in steps and those steps roughly, but not exactly, coincide with certain GUI actions I perform in the application. If these were errors in our code, they should get triggered every single time the actions are performed and not just most of the time.

Whenever I am confronted with so much strangeness, I begin to question my basic assumptions. So I turn to you, who know everything, for suggestions. Is there a flaw in my assumptions? Do you have an idea of how to go about troubleshooting a problem like this?

Edit:

I am currently using Microsoft Visual C++ (x86) on Windows 7 64.

Edit2:

I just used IBM Purify to hunt for leaks. First of all, it lists a full 30% of the program as leaked memory. This can not be true. I guess it is identifying the whole DLL as leaked or something like that. However, if I search for new leaks every few actions, it reports leaks that correspond with the size increase reported by Performance Monitor. This could be a lead to a leak. Sadly, I am only using the trial version of Purify, so it won't show me the actual location of those leaks. (These leaks only show up at runtime. When the program exits, there are no leaks whatsoever reported by any tool.)

答:
It's difficult to know without seeing your code, but there are less obvious ways that "leaks" can occur in a C++ program, e.g.

memory fragmentation - if you are allocating different size objects all the time, then sometimes there won't be a large enough contiguous area of free memory and more will have to be allocated from the OS. Allocations like this will not be freed back to OS until all the memory in the allocation is freed, so long running programs will tend to grow (in terms of address space used) over time.

forgetting to have a virtual in a base case which has virtual functions - a very common gotcha which leads to leaks.

using smart pointers, such as shared_ptr, and have an object hold on to a shared_ptr to an object - memory leak tools won't usually spot this kind of thing.

using smart pointers and getting circular references - you need to use e.g. a weak_ptr somewhere to break the cycle.

As to tools, there is purify which is good but expensive.


问:
how can i find the sum of all integers given in the string by using JavaScript?
How do I calculate the sum of all the numbers in a string by using the JavaScript ? In the example below, the expected result would be 2+0+1+5. My attempt is below. </p>

```<code>var a = "weare20boysand15girls";
    var i;
    for(i=0; i<a.length; i++){
        var b = Number(a[i]);
        var c=0;
        c += b;
        console.log(c);
</code>```

答:
You can try : </p>

```<code>var a = "weare20boysand15girls";
var b = a.match(/(\d)/g).map((a) => parseInt(a)).reduce((a,b) => a + b);
</code>```

Body:
How do I calculate the sum of all the numbers in a string by using the JavaScript ? In the example below, the expected result would be 2+0+1+5. My attempt is below.

var a = "weare20boysand15girls";
    var i;
    for(i=0; i<a.length; i++){
        var b = Number(a[i]);
        var c=0;
        c += b;
        console.log(c);

Body:
You can try :

var a = "weare20boysand15girls";
var b = a.match(/(\d)/g).map((a) => parseInt(a)).reduce((a,b) => a + b);


答:
Use regular expression to find all the integers. and use reduce function to compute sum

var a = "weare20boysand15girls";

var res = a.replace(/\D+/g, '').split('').reduce((a, b) => {
  return parseInt(a) + parseInt(b);
});
console.log(res)```

Title: how can i find the sum of all integers given in the string by using JavaScript?


问:
Numpy - load csv with first row as names immediately to a structured array?
Is there a way to avoid having to predefine the names of column headers in numpy/pandas to create a structured array, and instead have numpy/pandas read in the first row as the header names, and load the rest of the data to a structured array? E.g. for this data,

```<code>#        Date     low    open   close
#  2015-08-08  266.00  280.04  266.82
#  2015-07-08  233.00  280.04  266.82
</code>```

I would want to call some function like a = pd.read_csv() and be able to access the columns immediately as a['Date'], without predefining names = [Date, low, open, close] and having to pass that into read_csv(). Is this possible?

答:
If no parameter names in read_csv then first row data create columns of df.

So work:

```<code>df = pd.read_csv('file.csv')
#if necessary change default parameter sep=','
df = pd.read_csv('file.csv', sep=';')
print (df)
         Date    low    open   close
0  2015-08-08  266.0  280.04  266.82
1  2015-07-08  233.0  280.04  266.82

print (df.columns)
Index(['Date', 'low', 'open', 'close'], dtype='object')
</code>```

Body:
Is there a way to avoid having to predefine the names of column headers in numpy/pandas to create a structured array, and instead have numpy/pandas read in the first row as the header names, and load the rest of the data to a structured array? E.g. for this data,

#        Date     low    open   close
#  2015-08-08  266.00  280.04  266.82
#  2015-07-08  233.00  280.04  266.82

I would want to call some function like a = pd.read_csv() and be able to access the columns immediately as a['Date'], without predefining names = [Date, low, open, close] and having to pass that into read_csv(). Is this possible?

Body:
If no parameter names in read_csv then first row data create columns of df.

So work:

df = pd.read_csv('file.csv')
#if necessary change default parameter sep=','
df = pd.read_csv('file.csv', sep=';')
print (df)
         Date    low    open   close
0  2015-08-08  266.0  280.04  266.82
1  2015-07-08  233.0  280.04  266.82

print (df.columns)
Index(['Date', 'low', 'open', 'close'], dtype='object')


问:
All declarations of 'WeakMap' must have identical type parameters
I'm building Ionic App and everything is going fine, but when I cloned my source code to another machine, I get an error as shown in the image.

although the app is compiling without errors at the first machine I checked Ionic, npm, typescript and node versions and they are identical for the two machines.

what I'm missing here!?

答:
Just to document this in case anyone has the same issue I was able to fix this by deleting global node_module folder in path

C:\Users\{user_name}\AppData\Roaming\npm\node_modules

and in my case, there was another folder at C:\node_modules as indicated at the very end of the error message


问:
Crashlytics Beta Can't Find Testers UDID
I've scoured the internet for the last few days trying to figure out why Crashlytics can't find my testers device.

In my developer account, I added the testers device in the devices tab, included that device in a provisioning profile, and then downloaded and double clicked the profile to install it on my computer.

It looks like the provisioning profile has been installed successfully in my ~Library/mobiledevice/provisioningprofiles folder.

In Xcode I've tried deleting my developer account and adding it again. I've tried restarting xcode. I've tried deleting the profiles from my ~Library/mobiledevice/provisioningprofiles folder and reinstalling them.

I originally couldn't get it to install on my own phone either and I was getting the dreaded "The app could not be installed at this time" but I fixed that under build settings by selecting my "personal team" as the development team.

I also changed this in the general tab to match. I don't know why I have multiple "team" options to choose from in the first place or if this could be related to my problem.

I don't know what else to check or try or do, and I keep looking at the same things over and over again online so if anyone has some fresh insight for me it would be much appreciated.

答:
What kind of distribution method are you looking into using? If Ad Hoc, do you have an Ad Hoc distribution profile, with the devices you want to test on, set up?

Edit: It seems to me you dont, you need both a development AND a distribution profile.


问:
node.js express, a very strange behaviour
I have an Express server running.

What i do is upload an Excel File from HTML and then Express parse that file and do some calculating.

In the Excel file, each row has information about address of a User.

For each Address, our Express server will use google map geocoding API to calculate the latitude & longitude.

But, because Google doesn't accept more than 50 request per second to their geocoding API, so i have to use settimeout to delay the calculating.

For example if the Excel file has 50 addresses, so i have to use settimeout on each address to avoid that rate limit.

Here is my code to use settimeout and calculate latitude, longitude

createFromFile(req, res) {
    var form = new formidable.IncomingForm();
    return form.parse(req, function (err, fields, files) {
      if (err)
        return res.status(500).json({error: err.message})

      var workbook = new exceljs.Workbook();
      return workbook.xlsx.readFile(files.excelfile.path).then(function() {
        // use workbook
        var worksheet = workbook.getWorksheet(1)
        var data = []
        for (var i=2; i<=worksheet.rowCount; i++) {
          data.push({
            from_name: worksheet.getCell('A'+i).value + '',
            from_address: worksheet.getCell('B'+i).value + '',
            from_phone: worksheet.getCell('C'+i).value + '',
            receiver_name: worksheet.getCell('D'+i).value + '',
            receiver_address: worksheet.getCell('E'+i).value + '',
            receiver_phone: worksheet.getCell('F'+i).value + '',
            note: worksheet.getCell('H'+i).value + ''
          })
        }

        var delay = function(t) {
          return new Promise(function(resolve)           {
            setTimeout(resolve, t)
          })
        }

        return Promise.all(data.map(function(item, i) {
          return function() {
            return delay(750*i).then(function() {
              winston.log('debug', 'process for item '+i)
              return geocoder.geocode(item.from_address).then(function(geo_data) {
                data[i].from_coord = {
                  lat: geo_data[0].latitude,
                  lng: geo_data[0].longitude
                }
                return geocoder.geocode(item.receiver_address).then(function(geo_data) {
                  data[i].receiver_coord = {
                    lat: geo_data[0].latitude,
                    lng: geo_data[0].longitude
                  }
                })
              })
              .catch(function(geo_error) {
                winston.log('error', 'geo_error', {error: geo_error})
                throw new Error('Address in line ' + i + ' is not valid')
              })
            })
          }()
        }))
        .then(function() {
          winston.log('debug', 'we are done calculating location')
          return res.status(201).json(data)
        })
      })
      .catch(function(e) {
        winston.log('error', 'an error occurred')
        return res.status(500).json({error: e.message})
      })
    })
  }```
</div>
</div>
</p>

<p>And below is my codes to call that Express API, i used React to do frontend job & used javascript fetch api to request to server.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>startUploadFile() {
  this.props.showLoader()
  let data = new FormData()
  data.append('excelfile', this.state.selectedFile)
  data.append('name', 'excelfile')
  var me = this
  fetch(Const.restServer + '/create-from-file', {
    headers: {
      'Access-Token': this.props.access_token,
    },
    method: 'POST',
    body: data
  })
  .then(function(r) {
    return r.json()
  })
  .then(function(r) {
    if (r.hasOwnProperty('error'))
      throw new Error(r.error)

    me.props.hideLoader()
    me.props.showDialog('success', 'Process Complete')
  })
  .catch(function(e) {
    console.log(e)
    me.props.hideLoader()
    me.props.showDialog('error', e.message)
  })
}</code>```

My problem is when i used above codes to uploading a file on browser, i see two request in express log file. Something like this:

I will provide my codes to log info of every request here too

app.use(function(req, res, next) {
  winston.log('debug', 'call api:', {
    api: req.url, requestMethod: req.method
  })
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Access-Token, Web-Admin-Request"
  );
  next()
});

function isAuthenticated(req, res, next) {
  /**
  ** Rest API Middleware check if access_token is valid
  */
  let accessToken = req.body.accessToken || req.get('Access-Token')

  // bunch of codes to check accessToken
  next()
}

app.post('/order/create-from-file', isAuthenticated, orderController.createFromFile);```

I don't understand why this happen. If I use Postman & select a File & upload, it works fine - just only One Request in logs.

Can anyone tell me what is the reason. I feel like this is a Bug of Express. My Express version is 4.15.2

答:
Well, finally i can fix this problem by passing 'Access-Token' into request body instead of request header (now, my server always receive only one request). Thank to @sideshowbarker because your comment trigger me to do this method.

I still think this Problem is a bug in Express, but because it didn't occur on my local development environment, so i will not send a report to them.

Body:
I have an Express server running.

What i do is upload an Excel File from HTML and then Express parse that file and do some calculating.

In the Excel file, each row has information about address of a User.

For each Address, our Express server will use google map geocoding API to calculate the latitude & longitude.

But, because Google doesn't accept more than 50 request per second to their geocoding API, so i have to use settimeout to delay the calculating.

For example if the Excel file has 50 addresses, so i have to use settimeout on each address to avoid that rate limit.

Here is my code to use settimeout and calculate latitude, longitude

createFromFile(req, res) {
    var form = new formidable.IncomingForm();
    return form.parse(req, function (err, fields, files) {
      if (err)
        return res.status(500).json({error: err.message})

      var workbook = new exceljs.Workbook();
      return workbook.xlsx.readFile(files.excelfile.path).then(function() {
        // use workbook
        var worksheet = workbook.getWorksheet(1)
        var data = []
        for (var i=2; i<=worksheet.rowCount; i++) {
          data.push({
            from_name: worksheet.getCell('A'+i).value + '',
            from_address: worksheet.getCell('B'+i).value + '',
            from_phone: worksheet.getCell('C'+i).value + '',
            receiver_name: worksheet.getCell('D'+i).value + '',
            receiver_address: worksheet.getCell('E'+i).value + '',
            receiver_phone: worksheet.getCell('F'+i).value + '',
            note: worksheet.getCell('H'+i).value + ''
          })
        }

        var delay = function(t) {
          return new Promise(function(resolve)           {
            setTimeout(resolve, t)
          })
        }

        return Promise.all(data.map(function(item, i) {
          return function() {
            return delay(750*i).then(function() {
              winston.log('debug', 'process for item '+i)
              return geocoder.geocode(item.from_address).then(function(geo_data) {
                data[i].from_coord = {
                  lat: geo_data[0].latitude,
                  lng: geo_data[0].longitude
                }
                return geocoder.geocode(item.receiver_address).then(function(geo_data) {
                  data[i].receiver_coord = {
                    lat: geo_data[0].latitude,
                    lng: geo_data[0].longitude
                  }
                })
              })
              .catch(function(geo_error) {
                winston.log('error', 'geo_error', {error: geo_error})
                throw new Error('Address in line ' + i + ' is not valid')
              })
            })
          }()
        }))
        .then(function() {
          winston.log('debug', 'we are done calculating location')
          return res.status(201).json(data)
        })
      })
      .catch(function(e) {
        winston.log('error', 'an error occurred')
        return res.status(500).json({error: e.message})
      })
    })
  }

And below is my codes to call that Express API, i used React to do frontend job & used javascript fetch api to request to server.

startUploadFile() {
  this.props.showLoader()
  let data = new FormData()
  data.append('excelfile', this.state.selectedFile)
  data.append('name', 'excelfile')
  var me = this
  fetch(Const.restServer + '/create-from-file', {
    headers: {
      'Access-Token': this.props.access_token,
    },
    method: 'POST',
    body: data
  })
  .then(function(r) {
    return r.json()
  })
  .then(function(r) {
    if (r.hasOwnProperty('error'))
      throw new Error(r.error)

    me.props.hideLoader()
    me.props.showDialog('success', 'Process Complete')
  })
  .catch(function(e) {
    console.log(e)
    me.props.hideLoader()
    me.props.showDialog('error', e.message)
  })
}

My problem is when i used above codes to uploading a file on browser, i see two request in express log file. Something like this:

I will provide my codes to log info of every request here too

app.use(function(req, res, next) {
  winston.log('debug', 'call api:', {
    api: req.url, requestMethod: req.method
  })
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Access-Token, Web-Admin-Request"
  );
  next()
});

function isAuthenticated(req, res, next) {
  /**
  ** Rest API Middleware check if access_token is valid
  */
  let accessToken = req.body.accessToken || req.get('Access-Token')

  // bunch of codes to check accessToken
  next()
}

app.post('/order/create-from-file', isAuthenticated, orderController.createFromFile);

I don't understand why this happen. If I use Postman & select a File & upload, it works fine - just only One Request in logs.

Can anyone tell me what is the reason. I feel like this is a Bug of Express. My Express version is 4.15.2


答:
check the ascii value to identify numerical characters, and then sum it

var sum = 0;
var a = "weare20boysand15girls";
for (var i; i = 48 && a.charCodeAt(i) <= 57) {
    sum += a.charCodeAt(i) - 48;
  }
}
console.log(sum);```

Body:
check the ascii value to identify numerical characters, and then sum it

var sum = 0;
var a = "weare20boysand15girls";
for (var i; i < a.length; i++) {
  if (a.charCodeAt(i) >= 48 && a.charCodeAt(i) <= 57) {
    sum += a.charCodeAt(i) - 48;
  }
}
console.log(sum);