问:
Multiple Paths confusion when designing REST API
We have a resources named Games and Players

```<code>/games -> Get all Games available

/games/{game-id} -> Get the game details of specific Game with game-id

/players/me -> Get logged in Player details
</code>```

There will be Games played by the player which can be tagged under Games or Players

Scenario 1

/games/me -> Fetches games played by the current logged in player

This groups the request under Games tag. I'm using Swagger API so this call will be going to GamesAPI controller on the client generated code. I see its fair to be in the Games api rather than player as its related to games.

Problem : It looks too odd to consider "me" as a special id as it looks it is one form of {game-id} which I can't digest.

Scenario 2

```<code>/players/me/games -> Fetches games played by the current logged in player
</code>```

This groups it under Player tag which goes to PlayerAPI after code generation. The path has a meaning which is good but, its more relevant to have it in GamesAPI (by my choice - I could be wrong, please suggest)

Among these two scenarios which is the better way to design this problem?

答: Scenario 1 seems to be better among two because in general your games url will land to GameController and there you can have action function for fetching all games, one game of given id, or the logged in user's games.</p>

Body:
We have a resources named Games and Players

/games -> Get all Games available

/games/{game-id} -> Get the game details of specific Game with game-id

/players/me -> Get logged in Player details

There will be Games played by the player which can be tagged under Games or Players

Scenario 1

/games/me -> Fetches games played by the current logged in player

This groups the request under Games tag. I'm using Swagger API so this call will be going to GamesAPI controller on the client generated code. I see its fair to be in the Games api rather than player as its related to games.

Problem : It looks too odd to consider "me" as a special id as it looks it is one form of {game-id} which I can't digest.

Scenario 2

/players/me/games -> Fetches games played by the current logged in player

This groups it under Player tag which goes to PlayerAPI after code generation. The path has a meaning which is good but, its more relevant to have it in GamesAPI (by my choice - I could be wrong, please suggest)

Among these two scenarios which is the better way to design this problem?


来源: stackexchange

问:
API calls are unresponsive
I tried to use some of the services provided by the Google cloud API, followed the tutorial, and after installing the SDK and authorization files, I started calling. But either way, the program gets stuck after it executes, and then it waits, with no results or any errors. Trying to use Java and python is the same thing. How do you troubleshoot this problem now

I use it in China, but I already use the global proxy model. Otherwise I wouldn't be able to download some of the python packages

```<code>import six
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

text = 'President Kennedy spoke at the White House.'

client = language.LanguageServiceClient()

if isinstance(text, six.binary_type):
    text = text.decode('utf-8')

# Instantiates a plain text document.
document = types.Document(
    content=text,
    type=enums.Document.Type.PLAIN_TEXT)

# Detects syntax in the document. You can also analyze HTML with:
#   document.type == enums.Document.Type.HTML
tokens = client.analyze_syntax(document).tokens

for token in tokens:
    part_of_speech_tag = enums.PartOfSpeech.Tag(token.part_of_speech.tag)
    print(u'{}: {}'.format(part_of_speech_tag.name,
                           token.text.content))
</code>```

No useful information or error messages could be obtained, and the program did not interrupt, waiting for the result to be returned

答:
China blocks many/most Google services (endpoints) from being accessed inside China. If you are doing this at home, this is almost a certainty.

Your best option is to signup with Alibaba Cloud and then use a VM to access Google services. Alibaba's network will "usually" get you thru the great firewall.

ContentLicense: CC BY-SA 4.0

Title: API calls are unresponsive

Body:
I tried to use some of the services provided by the Google cloud API, followed the tutorial, and after installing the SDK and authorization files, I started calling. But either way, the program gets stuck after it executes, and then it waits, with no results or any errors. Trying to use Java and python is the same thing. How do you troubleshoot this problem now

I use it in China, but I already use the global proxy model. Otherwise I wouldn't be able to download some of the python packages

import six
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

text = 'President Kennedy spoke at the White House.'

client = language.LanguageServiceClient()

if isinstance(text, six.binary_type):
    text = text.decode('utf-8')

# Instantiates a plain text document.
document = types.Document(
    content=text,
    type=enums.Document.Type.PLAIN_TEXT)

# Detects syntax in the document. You can also analyze HTML with:
#   document.type == enums.Document.Type.HTML
tokens = client.analyze_syntax(document).tokens

for token in tokens:
    part_of_speech_tag = enums.PartOfSpeech.Tag(token.part_of_speech.tag)
    print(u'{}: {}'.format(part_of_speech_tag.name,
                           token.text.content))

No useful information or error messages could be obtained, and the program did not interrupt, waiting for the result to be returned


问:
Looping through an array based on the first index
I have two arrays and I am wanting to loop through a second array to only return arrays whose first element is equal to an element from another array.

```<code> a = [10, 11, 12, 13, 14]
 b = [[9, 23, 45, 67, 56, 23, 54], [10, 8, 52, 30, 15, 47, 109], [11, 81,
 152, 54, 112, 78, 167], [13, 82, 84, 63, 24, 26, 78], [18, 182, 25, 63, 96,
 104, 74]]
</code>```

I have two different arrays, a and b. I would like to find a way to look through each of the sub-arrays(?) within b in which
the first value is equal to the values in array a to create a new array, c.

The result I am looking for is:

```<code>  c = [[10, 8, 52, 30, 15, 47, 109],[11, 81, 152, 54, 112, 78, 167],[13, 82, 84, 63, 24, 26, 78]]
</code>```

Does Python have a tool to do this in a way Excel has MATCH()?

I tried looping in a manner such as:

```<code> for i in a:
      if i in b:
          print (b)
</code>```

But because there are other elements within the array, this way is not working. Any help would be greatly appreciated.

Further explanation of the problem:

a = [5, 6, 7, 9, 12]

I read in a excel file using XLRD (b_csv_data):

```<code> Start  Count   Error   Constant    Result1 Result2 Result3 Result4
 5       41       0       45             23      54      66       19
 5.4     44       1       21             52      35       6       50
 6       16       1       42             95      39       1       13
 6.9     50       1       22             71      86      59       97
 7       38       1       43             50      47      83       67
  8      26       1       29             100     63      15       40
 9       46       0       28             85       9      27       81
 12      43       0       21             74      78      20       85
</code>```

Next, I created a look to read in a select number of rows. For simplicity, this file above only has a few rows. My current file has about 100 rows.

```<code>for r in range (1, 7): #skipping headers and only wanting first few rows to start

     b_raw = b_csv_data.row_values(r)
     b = np.array(b_raw) # I created this b numpy array from the line of code above
</code>```

答:
Use np.isin -

```<code>In [8]: b[np.isin(b[:,0],a)]
Out[8]:
array([[ 10,   8,  52,  30,  15],
       [ 11,  81, 152,  54, 112],
       [ 13,  82,  84,  63,  24]])
</code>```

With sorted a, we can also use np.searchsorted -

```<code>idx = np.searchsorted(a,b[:,0])
idx[idx==len(a)] = 0
out = b[a[idx] == b[:,0]]
</code>```

If you have an array with different number of elements per row, which is essentially array of lists, you need to modify the slicing part. So, in that case, get the first off elements -

```<code>b0 = [bi[0] for bi in b]
</code>```

Then, use b0 to replace all instances of b[:,0] in earlier posted methods.

Body:
I have two arrays and I am wanting to loop through a second array to only return arrays whose first element is equal to an element from another array.

 a = [10, 11, 12, 13, 14]
 b = [[9, 23, 45, 67, 56, 23, 54], [10, 8, 52, 30, 15, 47, 109], [11, 81,
 152, 54, 112, 78, 167], [13, 82, 84, 63, 24, 26, 78], [18, 182, 25, 63, 96,
 104, 74]]

I have two different arrays, a and b. I would like to find a way to look through each of the sub-arrays(?) within b in which
the first value is equal to the values in array a to create a new array, c.

The result I am looking for is:

  c = [[10, 8, 52, 30, 15, 47, 109],[11, 81, 152, 54, 112, 78, 167],[13, 82, 84, 63, 24, 26, 78]]

Does Python have a tool to do this in a way Excel has MATCH()?

I tried looping in a manner such as:

 for i in a:
      if i in b:
          print (b)

But because there are other elements within the array, this way is not working. Any help would be greatly appreciated.

Further explanation of the problem:

a = [5, 6, 7, 9, 12]

I read in a excel file using XLRD (b_csv_data):

 Start  Count   Error   Constant    Result1 Result2 Result3 Result4
 5       41       0       45             23      54      66       19
 5.4     44       1       21             52      35       6       50
 6       16       1       42             95      39       1       13
 6.9     50       1       22             71      86      59       97
 7       38       1       43             50      47      83       67
  8      26       1       29             100     63      15       40
 9       46       0       28             85       9      27       81
 12      43       0       21             74      78      20       85

Next, I created a look to read in a select number of rows. For simplicity, this file above only has a few rows. My current file has about 100 rows.

for r in range (1, 7): #skipping headers and only wanting first few rows to start

     b_raw = b_csv_data.row_values(r)
     b = np.array(b_raw) # I created this b numpy array from the line of code above

Body:
Use np.isin -

In [8]: b[np.isin(b[:,0],a)]
Out[8]:
array([[ 10,   8,  52,  30,  15],
       [ 11,  81, 152,  54, 112],
       [ 13,  82,  84,  63,  24]])

With sorted a, we can also use np.searchsorted -

idx = np.searchsorted(a,b[:,0])
idx[idx==len(a)] = 0
out = b[a[idx] == b[:,0]]

If you have an array with different number of elements per row, which is essentially array of lists, you need to modify the slicing part. So, in that case, get the first off elements -

b0 = [bi[0] for bi in b]

Then, use b0 to replace all instances of b[:,0] in earlier posted methods.


问:
create multidimensional json array from a json in php
I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.

Here is my data any code. Thanks in advance

My json data

```<code>$val = [
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p1'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p2'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p3'
    },
    {
     'city':'xx',
     'zone':'ww',
     'person_on_zone':'p1'
    },
  ]
</code>```

My expectation is

```<code>[
 {
  'city':'xx',
  'zone':'yy',
  'person_info':{
                  'person_on_zone':'p1',
                  'person_on_zone':'p2',
                  'person_on_zone':'p3',
                }
 },
 {
  'city':'xx',
  'zone':'ww',
  'person_info':{
                  'person_on_zone':'p1'
                }
 },
]
</code>```

Here I tried

```<code>foreach ($val as $v) {
    $new_array['city'] = $v['city'];
    $new_array['zone'] = $v['zone'];
    foreach ($val as $v2) {
        $new_array['person_info'] = $v['person_on_zone'];
    }
}
json_encode($new_array);
</code>```

答:
Try this, use $map to store key city-zone, then transform to array to get the result

```<code><?php

$val = [
    [
        'city' => 'xx',
        'zone' => 'yy',
        'person_on_zone' => 'p1'
    ],
    [
        'city' => 'xx',
        'zone' => 'yy',
        'person_on_zone' => 'p2'
    ],
    [
        'city' => 'xx',
        'zone' => 'yy',
        'person_on_zone' => 'p3'
    ],
    [
        'city' => 'xx',
        'zone' => 'ww',
        'person_on_zone' => 'p1'
    ]
];

$map = [];
foreach ($val as $v) {
    $key = $v['city'] . $v['zone'];
    if (!isset($map[$key])) {
        $map[$key] = [
            'city' => $v['city'],
            'zone' => $v['zone'],
            'person_info' => []
        ];
    }

    $map[$key]['person_info'][] = $v['person_on_zone'];
}

print_r(array_values($map));
</code>```

Body:
I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.

Here is my data any code. Thanks in advance

My json data

$val = [
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p1'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p2'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p3'
    },
    {
     'city':'xx',
     'zone':'ww',
     'person_on_zone':'p1'
    },
  ]

My expectation is

[
 {
  'city':'xx',
  'zone':'yy',
  'person_info':{
                  'person_on_zone':'p1',
                  'person_on_zone':'p2',
                  'person_on_zone':'p3',
                }
 },
 {
  'city':'xx',
  'zone':'ww',
  'person_info':{
                  'person_on_zone':'p1'
                }
 },
]

Here I tried

foreach ($val as $v) {
    $new_array['city'] = $v['city'];
    $new_array['zone'] = $v['zone'];
    foreach ($val as $v2) {
        $new_array['person_info'] = $v['person_on_zone'];
    }
}
json_encode($new_array);

Body:
Try this, use $map to store key city-zone, then transform to array to get the result

<?php

$val = [
    [
        'city' => 'xx',
        'zone' => 'yy',
        'person_on_zone' => 'p1'
    ],
    [
        'city' => 'xx',
        'zone' => 'yy',
        'person_on_zone' => 'p2'
    ],
    [
        'city' => 'xx',
        'zone' => 'yy',
        'person_on_zone' => 'p3'
    ],
    [
        'city' => 'xx',
        'zone' => 'ww',
        'person_on_zone' => 'p1'
    ]
];

$map = [];
foreach ($val as $v) {
    $key = $v['city'] . $v['zone'];
    if (!isset($map[$key])) {
        $map[$key] = [
            'city' => $v['city'],
            'zone' => $v['zone'],
            'person_info' => []
        ];
    }

    $map[$key]['person_info'][] = $v['person_on_zone'];
}

print_r(array_values($map));


问:
Vuetify text field border missing
I'm trying to implement Veutify's text field

This is what it looks like for me right now:

And this is what it looks like when the text field is in focus:

These are my imports in main.js

```<code>import Vue from 'vue';
import Vuetify from 'vuetify';
Vue.use(Vuetify);
</code>```

Am I missing an import or something?

答:
Same issue
But I fixed by this solution.
Please add this link(CDN) to you html file.

```<code><link rel="stylesheet" href="https://unpkg.com/vue-material/dist/vue-material.min.css">
<link rel="stylesheet" href="https://unpkg.com/vue-material/dist/theme/default.css">

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-material"></script>
</code>```

Don't worry
no crashing.

ContentLicense: CC BY-SA 3.0

Title: Vuetify text field border missing

Body:
I'm trying to implement Veutify's text field

This is what it looks like for me right now:

And this is what it looks like when the text field is in focus:

These are my imports in main.js

import Vue from 'vue';
import Vuetify from 'vuetify';
Vue.use(Vuetify);

Am I missing an import or something?

Body:
Same issue
But I fixed by this solution.
Please add this link(CDN) to you html file.

<link rel="stylesheet" href="https://unpkg.com/vue-material/dist/vue-material.min.css">
<link rel="stylesheet" href="https://unpkg.com/vue-material/dist/theme/default.css">

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-material"></script>

Don't worry
no crashing.


问:
javascript woocommerce form validation on add to cart buton before adding to cart
I have a custom page that displays a product with variations, a custom field and add to cart button.
I need to trigger some validation in javascript when the add to cart button is clicked, but if the form doesn't validate, then add to cart can't be performed.

I'd like to know if it's possible to achieve.

First I tried to do as explained here :
WooCommerce add to cart validation: prevent add to cart

It's working great and I'd like to be able to use this code but for me it can't be because :
- I'm using a custom page and not the usual woocommerce product page
- This means that after validation, I'm redirected to the standard woocommerce page which is blank

That's why I really need to use Javascript to perform this:
- javascript or jquery function triggered on the add to cart click
- then the function checks it everything is ok
- if yes, then product can be added to cart
- if no, an alert is displayed and the user remains on the same page, nothing added to cart.

I tried to be as clear as possible.
Hoping I can get some help.

Thanks a lot.

答:
Please try this way:</p>

```<code>function so_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations= '' ) {
<script>
  jQuery(function($){
       jQuery(document).on('click', '.single_add_to_cart_button', function (e) {
            e.preventDefault();
            // your validation here
       });
    });
</script>
}
 add_filter( 'woocommerce_add_to_cart_validation', 'so_validate_add_cart_item', 10, 5 );
</code>```

Body:
Please try this way:

function so_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations= '' ) {
<script>
  jQuery(function($){
       jQuery(document).on('click', '.single_add_to_cart_button', function (e) {
            e.preventDefault();
            // your validation here
       });
    });
</script>
}
 add_filter( 'woocommerce_add_to_cart_validation', 'so_validate_add_cart_item', 10, 5 );


问:
name instead of number to send sms using AT commands
Instead of the sender number to the recipient , i want it be name using the AT commands.

I am successfully send the message through AT commands using GSM Modem. Can somebody provide

the solution to send sms with sender name instead of the mobile number.

答:
Actually,
The sender can not send normal SMS message so that the receiver can read his name.
The receiving terminal can have capacity to search the number from phonebook and replace the number.
When the SMS is sent, then the number of the sender is not coded in to sending sms, because it is the feature of the network:
When the MO SMS (SMS-Submit) is converted into MT- SMS (SMS-Deliver), then the number of the receiver
"is replaced" with the number of the sender.
So you can not send the name instead of the number when you are using SMS.
      The network provider needs to be contacted in case a specific name/number needs to be displayed. AT commands would accept only the phone number as the CMGS parameter.
Hope this answers your question.</p>

ContentLicense: CC BY-SA 2.5


问:
Expand all PrimeNG Accordion panels automatically for Printing
I am currently using the PrimeNG library's accordion component in my angular project. See info here.

The template includes some special css styling for printing the page--something like the following:

```<code> @media print {
  .profile-progress-bar, .top-template-header-content, .header.profile-header{
    display: none !important;
  }
  html, body {
    height: auto;
    font-size: 10px !important;
  }

  p-accordionTab > div {
    display: block !important;
    selected: true !important;
  }

}
</code>```

What I am trying to do, is automatically expand all accordionTab elements when the @media print rendering is processed for the page to be printed.

From the documentation I see that each accordionTab element has a [selected] property which can be bound to and set to "true" in order to expand the tab.

Selected Visibility of the content is specified with the selected
  property that supports one or two-way binding.

However, can this be somehow automatically triggered when the @media print rendering occurs?

Thanks!

答:
This is an interesting one. To keep it inside the realm of Angular, you could use the @angular/cdk/layout library and inject MediaMatcher.  You could also, of course, do almost this exact same thing using JavaScript (see here... the cdk/layout method I'll show you really just wraps this).

The MediaMatcher service has a method called matchMedia, and from there you just add a listener:

```<code>import { MediaMatcher } from '@angular/cdk/layout';

constructor(private readonly mediaMatcher: MediaMatcher ) { }

ngOnInit() {
    mediaMatcher.matchMedia('print').addListener(e => e.matches ?
    console.log('printing!') : null);
}
</code>```

So where I've put the console.log, just perform your logic to get the accordians to expand.

Body:
I am currently using the PrimeNG library's accordion component in my angular project. See info here.

The template includes some special css styling for printing the page--something like the following:

 @media print {
  .profile-progress-bar, .top-template-header-content, .header.profile-header{
    display: none !important;
  }
  html, body {
    height: auto;
    font-size: 10px !important;
  }

  p-accordionTab > div {
    display: block !important;
    selected: true !important;
  }

}

What I am trying to do, is automatically expand all accordionTab elements when the @media print rendering is processed for the page to be printed.

From the documentation I see that each accordionTab element has a [selected] property which can be bound to and set to "true" in order to expand the tab.

Selected Visibility of the content is specified with the selected
  property that supports one or two-way binding.

However, can this be somehow automatically triggered when the @media print rendering occurs?

Thanks!

Body:
This is an interesting one. To keep it inside the realm of Angular, you could use the @angular/cdk/layout library and inject MediaMatcher.  You could also, of course, do almost this exact same thing using JavaScript (see here... the cdk/layout method I'll show you really just wraps this).

The MediaMatcher service has a method called matchMedia, and from there you just add a listener:

import { MediaMatcher } from '@angular/cdk/layout';

constructor(private readonly mediaMatcher: MediaMatcher ) { }

ngOnInit() {
    mediaMatcher.matchMedia('print').addListener(e => e.matches ?
    console.log('printing!') : null);
}

So where I've put the console.log, just perform your logic to get the accordians to expand.


问:
Combining WareHouseModel and Experiments
I am trying to run experiments using the WarehouseRenderer and AgvRenderer from AgvExample.

I get the following exception:

Exception in thread "main" java.lang.IllegalArgumentException: Could not resolve dependency for implementations of interface com.github.rinde.rinsim.core.model.road.CollisionGraphRoadModel, as requested by WarehouseRenderer.builder().
    at com.google.common.base.Preconditions.checkArgument(Preconditions.java:437)
    at com.github.rinde.rinsim.core.model.DependencyResolver.constructDependencyGraph(DependencyResolver.java:90)
    at com.github.rinde.rinsim.core.model.DependencyResolver.resolve(DependencyResolver.java:115)
    at com.github.rinde.rinsim.core.model.ModelManager$Builder.build(ModelManager.java:268)
    at com.github.rinde.rinsim.core.Simulator.<init>(Simulator.java:88)
    at com.github.rinde.rinsim.core.Simulator$Builder.build(Simulator.java:347)
    at com.github.rinde.rinsim.experiment.Experiment.init(Experiment.java:191)
    at com.github.rinde.rinsim.experiment.Experiment.perform(Experiment.java:195)
    at com.github.rinde.rinsim.experiment.LocalComputer$ExperimentRunner.call(LocalComputer.java:202)
    at com.github.rinde.rinsim.experiment.LocalComputer$ExperimentRunner.call(LocalComputer.java:193)
    at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:125)
    at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:57)
    at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:78)
    at com.google.common.util.concurrent.MoreExecutors$DirectExecutorService.execute(MoreExecutors.java:258)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at com.google.common.util.concurrent.AbstractListeningExecutorService.submit(AbstractListeningExecutorService.java:66)
    at com.github.rinde.rinsim.experiment.LocalComputer.compute(LocalComputer.java:81)
    at com.github.rinde.rinsim.experiment.Experiment$Builder.perform(Experiment.java:684)
    at com.github.rinde.rinsim.experiment.Experiment$Builder.perform(Experiment.java:703)
    at agv.ExperimentExample.main(ExperimentExample.java:197)
```

答:
This error indicates that there is a renderer attached to the simulator that expects a model of type CollisionGraphRoadModel. A renderer can only function correctly if there is a corresponding model that contains the data that needs to be rendered.

In AgvExample the following code (see lines 86-90) is used to add the required model:

.addModel(
  RoadModelBuilders.dynamicGraph(GraphCreator.createSimpleGraph())
    .withCollisionAvoidance()
    .withDistanceUnit(SI.METER)
    .withVehicleLength(VEHICLE_LENGTH))
```

You can add similar code if you want to use the WarehouseRenderer in your code.

Body:
This error indicates that there is a renderer attached to the simulator that expects a model of type CollisionGraphRoadModel. A renderer can only function correctly if there is a corresponding model that contains the data that needs to be rendered.

In AgvExample the following code (see lines 86-90) is used to add the required model:

.addModel(
  RoadModelBuilders.dynamicGraph(GraphCreator.createSimpleGraph())
    .withCollisionAvoidance()
    .withDistanceUnit(SI.METER)
    .withVehicleLength(VEHICLE_LENGTH))

You can add similar code if you want to use the WarehouseRenderer in your code.


问:
GraphQL API - any automation tool for testing it?
I want to test a GraphQL API.
For now, I'm using GraphiQL, but I'm looking for any automated tool...
It seems that SOAPUI does not support GraphQL testing.

Any ideas?

Thanks.

答:
I am using SoapUI 5.4.0 (community edition) and have no trouble testing GraphQL requests.
Treat them as a Rest request and add a header, e.g. Content-Type: application/graphql

see image for all details.


问:
How to send serial data (URL) to the sim800l for long strings
I try to send a post request with sim800l but, when I send a long string i have a strange problem

the ouput of my Serial console

```<code>AT+SAPBR=3,1,"APN","free"
OK

AT+SAPBR=1,1
OK

AT+SAPBR=2,1

+SAPBR: 1,1,"10.124.170.82"
OK

AT+HTTPINIT
OK

AT+HTTPPARA="CID",1
OK

AT+HTTPPARA="URL",","http://naviwatt.fr/api/boat/AETFC58003****/*****/time/35"
AT+HTTPPARA="URL",","http://naviwatt.fr/api/boat/AETFC58003****
AT+HTTPACTION=1

ERROR

</code>```

the part where the error may be

```<code>//setup the request
String request = "AT+HTTPPARA=\"URL\",\",\"http://naviwatt.fr/api/boat/" + Id + "/" + Password + "/time/" + counter + "\"";

Serial.println("" + request);

delay(200);
sim.println(request);
sleep();
</code>```

and the sleep(); function

```<code>void sleep(){
  String dump;
  delay(100);
  while(!sim.available()){
    Serial.print("waiting");
    delay(200);
  }
  while(sim.available()){
     dump = sim.readString();
     Serial.println(dump);
   }
}
</code>```

The Serial.println print in the console the correct String to use

But when i send this same string to the sim800l the url seems not full

答:
Your AT+HTTPPATA command is not proper.

It should be

```<code>AT+HTTPPARA="URL","http://naviwatt.fr/api/boat/AETFC58003****/*****/time/35"
</code>```

instead of

```<code>AT+HTTPPARA="URL",","http://naviwatt.fr/api/boat/AETFC58003****/*****/time/35"
</code>```

their is an extra ," in your command.

Similarly you second command should be

```<code>AT+HTTPPARA="URL","http://naviwatt.fr/api/boat/AETFC58003****
</code>```

instead of

```<code>AT+HTTPPARA="URL",","http://naviwatt.fr/api/boat/AETFC58003****
</code>```

Your setup the request should be

```<code>String request = "AT+HTTPPARA=\"URL\",\"http://naviwatt.fr/api/boat/" + Id + "/" + Password + "/time/" + counter + "\"";
</code>```

Body:
I try to send a post request with sim800l but, when I send a long string i have a strange problem

the ouput of my Serial console

AT+SAPBR=3,1,"APN","free"
OK

AT+SAPBR=1,1
OK

AT+SAPBR=2,1

+SAPBR: 1,1,"10.124.170.82"
OK

AT+HTTPINIT
OK

AT+HTTPPARA="CID",1
OK

AT+HTTPPARA="URL",","http://naviwatt.fr/api/boat/AETFC58003****/*****/time/35"
AT+HTTPPARA="URL",","http://naviwatt.fr/api/boat/AETFC58003****
AT+HTTPACTION=1

ERROR

the part where the error may be

//setup the request
String request = "AT+HTTPPARA=\"URL\",\",\"http://naviwatt.fr/api/boat/" + Id + "/" + Password + "/time/" + counter + "\"";

Serial.println("" + request);

delay(200);
sim.println(request);
sleep();

and the sleep(); function

void sleep(){
  String dump;
  delay(100);
  while(!sim.available()){
    Serial.print("waiting");
    delay(200);
  }
  while(sim.available()){
     dump = sim.readString();
     Serial.println(dump);
   }
}

The Serial.println print in the console the correct String to use

But when i send this same string to the sim800l the url seems not full

Body:
Your AT+HTTPPATA command is not proper.

It should be

AT+HTTPPARA="URL","http://naviwatt.fr/api/boat/AETFC58003****/*****/time/35"

instead of

AT+HTTPPARA="URL",","http://naviwatt.fr/api/boat/AETFC58003****/*****/time/35"

their is an extra ," in your command.

Similarly you second command should be

AT+HTTPPARA="URL","http://naviwatt.fr/api/boat/AETFC58003****

instead of

AT+HTTPPARA="URL",","http://naviwatt.fr/api/boat/AETFC58003****

Your setup the request should be

String request = "AT+HTTPPARA=\"URL\",\"http://naviwatt.fr/api/boat/" + Id + "/" + Password + "/time/" + counter + "\"";


问:
Node-config custom-environment-variables not overridding default.json during test
Node-config's custom-environment-variables.json doesn't seem to be overriding values in default.json when NODE_ENV is set to 'test.' Here's an extremely simple config:

config/default.json:

```<code>{
  "jwtPrivateKey": "defaultkey"
}
</code>```

config/custom-environment-variables.json:

```<code>{
 "jwtPrivateKey": "JWTPRIVATEKEY"
}
</code>```

config/test.json:

```<code>{}
</code>```

app.js:

```<code>console.log('NODE_ENV': + process.env.NODE_ENV);
console.log('Env: ' + process.env.JWTPRIVATEKEY);
console.log("Config: " + config.get('jwtPrivateKey'));
</code>```

This works as expected: I get NODE_ENV=undefined (so node-config will default to 'development'), & the next two lines both print the correct value set in the environment variable.  However, if I try to run a simple test with Jest & print the same:

tests/some.test.js:

```<code>test('Some Test', () => {
    console.log('NODE_ENV:' + process.env.NODE_ENV);
    console.log('Env: ' + process.env.JWTPRIVATEKEY);
    console.log("Config: " + config.get('jwtPrivateKey'));
});
</code>```

I get NODE_ENV=test, Env=the correct value set in the environment variable...but Config=defaultKey.

In other words: although it shows that the environment variable is set to the right value, node-config doesn't seem to be pulling it in through custom-environment-variables.json.

Is this a bug?  I've scoured the documentation but been unable to find any reason for this discrepancy.

答:
Do you by chance have a local.json file in your config folder? If so, this is a special file type that overrides everything, so your values may match this config's values exactly. The NODE_ENV var seemingly doesn't affect whether or not local.json is loaded last.

I just ran into this issue and temporarily renaming/removing the local.json solved my problem.

Body:
Node-config's custom-environment-variables.json doesn't seem to be overriding values in default.json when NODE_ENV is set to 'test.' Here's an extremely simple config:

config/default.json:

{
  "jwtPrivateKey": "defaultkey"
}

config/custom-environment-variables.json:

{
 "jwtPrivateKey": "JWTPRIVATEKEY"
}

config/test.json:

{}

app.js:

console.log('NODE_ENV': + process.env.NODE_ENV);
console.log('Env: ' + process.env.JWTPRIVATEKEY);
console.log("Config: " + config.get('jwtPrivateKey'));

This works as expected: I get NODE_ENV=undefined (so node-config will default to 'development'), & the next two lines both print the correct value set in the environment variable.  However, if I try to run a simple test with Jest & print the same:

tests/some.test.js:

test('Some Test', () => {
    console.log('NODE_ENV:' + process.env.NODE_ENV);
    console.log('Env: ' + process.env.JWTPRIVATEKEY);
    console.log("Config: " + config.get('jwtPrivateKey'));
});

I get NODE_ENV=test, Env=the correct value set in the environment variable...but Config=defaultKey.

In other words: although it shows that the environment variable is set to the right value, node-config doesn't seem to be pulling it in through custom-environment-variables.json.

Is this a bug?  I've scoured the documentation but been unable to find any reason for this discrepancy.


问:
loop errors in angular
In angular I've tying to loop my given errors and show them in alert but it doesn't work, I've read and tried different solutions such as using lenght or lenght+1 etc. none of them seem to work.

Data

```<code>{name: Array(1), email: Array(1), password: Array(1)}
email: ["The email field is required."]
name: ["The name field is required."]
password: ["The password field is required."]
__proto__: Object
</code>```

Code

```<code>error => {
        let errors = error.error.errors;
        console.log(errors); //return result above
        for (var i = 0; i < errors.length; i++) {
          this.alertService.presentToast(errors[i]);
        }
      },
</code>```

any idea?

答:
Hi there are two ways to print the error messages. Hope it may help full for you

1.

```<code>for (let [key, value] of Object.entries(errors)) {
    console.log(value[0]);
}
</code>```

2.

```<code>for (let [key, value] of Object.entries(errors)) {
    for(let msg of value) {
        console.log(msg);
    }
}
</code>```

Title: loop errors in angular

Body:
In angular I've tying to loop my given errors and show them in alert but it doesn't work, I've read and tried different solutions such as using lenght or lenght+1 etc. none of them seem to work.

Data

{name: Array(1), email: Array(1), password: Array(1)}
email: ["The email field is required."]
name: ["The name field is required."]
password: ["The password field is required."]
__proto__: Object

Code

error => {
        let errors = error.error.errors;
        console.log(errors); //return result above
        for (var i = 0; i < errors.length; i++) {
          this.alertService.presentToast(errors[i]);
        }
      },

any idea?

Body:
Hi there are two ways to print the error messages. Hope it may help full for you

1.

for (let [key, value] of Object.entries(errors)) {
    console.log(value[0]);
}

2.

for (let [key, value] of Object.entries(errors)) {
    for(let msg of value) {
        console.log(msg);
    }
}


问:
Cloud database architecture for a location-based app
I'm currently planning my database for my location-based Android app (vision for iOS app sometime in future).

I'm wondering if the following structure suits my needs. Quick rundown of what my app involves: finding a user within a 2km radius (geofence) and showing their profile (similar to matching with someone on Tinder).

So how I envision it is each user upload their LatLon location to my database via google maps API - and Android queries the database to find a user within the geofence.

PS: What is the best way to query users within a geofence?

My proposed database is Google Firestore with the following document setup:

```<code>users: {
    2394824972439 (facebook_id): {
      gender: "male"
      currentLat: 37.234234,
      currentLon: 157.192835,
      profileImg1: googlecloudstorage.com/url/to/img1.png,
      profileImg2: googlecloudstorage.com/url/to/img2.png,
      bio: "This is my bio",
      alreadyMatchedWith: [42304823423, 23423423432, 023948230]
  }
    7388824972439: {
      gender: "female"
      currentLat: 34.234234,
      currentLon: 157.132835,
      profileImg1: googlecloudstorage.com/url/to/img1.png,
      profileImg2: googlecloudstorage.com/url/to/img2.png,
      bio: "Another bio",
      alreadyMatchedWith: [82304823423, 33423423432, 923948230]
  }
}
</code>```

So the query will also ensure the other user's facebook ID (i'm using facebook for login) hasn't already been matched with. If it hasn't been matched with then the database will return the document of that user and display their profile info as well as profile images from google cloud. storage.

Are there any red flags about this setup I should be concerned about - or any better alternatives?

答:
Since you haven't mentioned GeoFire, and you pretend to do geo-related queries, GeoFire is probably the best alternative,

GeoFire for Android/Java

https://github.com/firebase/geofire-java

```<code>// creates a new query around [37.7832, -122.4056] with a radius of 2.0 kilometers
GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(37.7832, -122.4056), 2.0);
</code>```

In the case you'll have to implement the same functionality for IOS:

GeoFire for Objective-C

https://github.com/firebase/geofire-objc

Body:
I'm currently planning my database for my location-based Android app (vision for iOS app sometime in future).

I'm wondering if the following structure suits my needs. Quick rundown of what my app involves: finding a user within a 2km radius (geofence) and showing their profile (similar to matching with someone on Tinder).

So how I envision it is each user upload their LatLon location to my database via google maps API - and Android queries the database to find a user within the geofence.

PS: What is the best way to query users within a geofence?

My proposed database is Google Firestore with the following document setup:

users: {
    2394824972439 (facebook_id): {
      gender: "male"
      currentLat: 37.234234,
      currentLon: 157.192835,
      profileImg1: googlecloudstorage.com/url/to/img1.png,
      profileImg2: googlecloudstorage.com/url/to/img2.png,
      bio: "This is my bio",
      alreadyMatchedWith: [42304823423, 23423423432, 023948230]
  }
    7388824972439: {
      gender: "female"
      currentLat: 34.234234,
      currentLon: 157.132835,
      profileImg1: googlecloudstorage.com/url/to/img1.png,
      profileImg2: googlecloudstorage.com/url/to/img2.png,
      bio: "Another bio",
      alreadyMatchedWith: [82304823423, 33423423432, 923948230]
  }
}

So the query will also ensure the other user's facebook ID (i'm using facebook for login) hasn't already been matched with. If it hasn't been matched with then the database will return the document of that user and display their profile info as well as profile images from google cloud. storage.

Are there any red flags about this setup I should be concerned about - or any better alternatives?

Body:
Since you haven't mentioned GeoFire, and you pretend to do geo-related queries, GeoFire is probably the best alternative,

GeoFire for Android/Java

https://github.com/firebase/geofire-java

// creates a new query around [37.7832, -122.4056] with a radius of 2.0 kilometers
GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(37.7832, -122.4056), 2.0);

In the case you'll have to implement the same functionality for IOS:

GeoFire for Objective-C

https://github.com/firebase/geofire-objc


问:
Is there a way to sort the rank in Mpi by ascending and descending order
I am trying to display the Hello World message by ascending and descending order of it rank

I read about the bitonic sort but couldn't understand how to implement it,

```<code>int[] datalist = new int[8];
MPI.Init(args);

int rank = MPI.COMM_WORLD.Rank();
int size = MPI.COMM_WORLD.Size();

System.out.println("Hello World from <"+rank+"> of total "+size+" processes");

MPI.Finalize();
</code>```

I get the output from this coding but didn't how to output it by sorting it, I really need help cause I am still new with the mpi stuff

答:
The question is not very clear. It may be interpreted in two ways:

You would like to see the printed rank in ascending or descending order. Any MPI library, including MPJ Express, follows the Single Program Multiple Data (SPMD) model. This essentially means that multiple copies of your program will be executed. The number of copies depend upon how many parallel processes you specified while executing the program with mpjrun switch (using -np switch). It is not possible for MPJ Express to print this line in any particular order since it has no control over execution order of parallel copies of this program. So the output will always be non-deterministic.

You would like to see the data in datalist array to be sorted in an ascending or descending order. Again, for that you will need Gather() or Reduce() operation. Currently your program is making N copies of datalist array (assuming that you started N parallel processes).

Hope this helps.

Body:
I am trying to display the Hello World message by ascending and descending order of it rank

I read about the bitonic sort but couldn't understand how to implement it,

int[] datalist = new int[8];
MPI.Init(args);

int rank = MPI.COMM_WORLD.Rank();
int size = MPI.COMM_WORLD.Size();

System.out.println("Hello World from <"+rank+"> of total "+size+" processes");

MPI.Finalize();

I get the output from this coding but didn't how to output it by sorting it, I really need help cause I am still new with the mpi stuff


问:
Using a Relative Paths in C#
I'm trying to seed my database with an image. I'm able to do this successfully using an absolute path, however this won't work as a permanent solution.

```<code> Image = File.ReadAllBytes(@"E:\Graded Unit\Implementation\YorkiesVehicleHire\YorkiesVehicleHire\Images\Ferrari488.jpg"),
</code>```

How could I get the same path so resolve. Using something like

```<code>~\Images\Ferrari488.jpg
</code>```

Any help would be appreciated.

答:
For getting only file name from a path you can use Path.GetFileName('path'); which in your case you can get the file name first as:

```<code>var fileName = System.IO.Path.GetFileName(@"E:\Graded Unit\Implementation\YorkiesVehicleHire\YorkiesVehicleHire\Images\Ferrari488.jpg");
//filename will now only contain: Ferrari488.jpg

//Now let's concatenate it with ~/Images/
var storingPath= "~\Images\" + fileName;
</code>```

Now for the absolute path, try using Server.MapPath("~") which returns the physical path to the root of the application.

So in your case if you want to get the absolute path for ~\Images\Ferrari488.jpg then it will look like: Server.MapPath("~\Images\Ferrari488.jpg"); or System.Web.HttpContext.Current.Server.MapPath("~\Images\Ferrari488.jpg");

OR

```<code>var absolutePath = System.Web.HttpContext.Current.Server.MapPath(storingPath);
Image = File.ReadAllBytes(absolutePath);
</code>```

Title: Using a Relative Paths in C#

Body:
I'm trying to seed my database with an image. I'm able to do this successfully using an absolute path, however this won't work as a permanent solution.

 Image = File.ReadAllBytes(@"E:\Graded Unit\Implementation\YorkiesVehicleHire\YorkiesVehicleHire\Images\Ferrari488.jpg"),

How could I get the same path so resolve. Using something like

~\Images\Ferrari488.jpg

Any help would be appreciated.

Body:
For getting only file name from a path you can use Path.GetFileName('path'); which in your case you can get the file name first as:

var fileName = System.IO.Path.GetFileName(@"E:\Graded Unit\Implementation\YorkiesVehicleHire\YorkiesVehicleHire\Images\Ferrari488.jpg");
//filename will now only contain: Ferrari488.jpg

//Now let's concatenate it with ~/Images/
var storingPath= "~\Images\" + fileName;

Now for the absolute path, try using Server.MapPath("~") which returns the physical path to the root of the application.

So in your case if you want to get the absolute path for ~\Images\Ferrari488.jpg then it will look like: Server.MapPath("~\Images\Ferrari488.jpg"); or System.Web.HttpContext.Current.Server.MapPath("~\Images\Ferrari488.jpg");

OR

var absolutePath = System.Web.HttpContext.Current.Server.MapPath(storingPath);
Image = File.ReadAllBytes(absolutePath);


问:
What is the difference between method Sheet1.ShowAll and Sheet1.AutoFilter.ShowAll
I recorded a macro to clear filter and show all row data. Result is Sheet1.ShowAll. I use this method for long time but sometimes I got error that I can fix using Sheet1.AutoFilter.ShowAll. Why is Sheet1.AutoFilter.ShowAll working?

I use and tested on Excel 2010

```<code>Sheet1.ShowAll 'runtime error

Sheet1.AutoFilter.ShowAll 'no error, why?
</code>```

答:
Sheet1.ShowAllData is the code you are looking for to clear the Filter.

But if you use Sheet1.UsedRange.AutoFilter , it will remove the filter or add the filter if no filter is applied.

Body:
I recorded a macro to clear filter and show all row data. Result is Sheet1.ShowAll. I use this method for long time but sometimes I got error that I can fix using Sheet1.AutoFilter.ShowAll. Why is Sheet1.AutoFilter.ShowAll working?

I use and tested on Excel 2010

Sheet1.ShowAll 'runtime error

Sheet1.AutoFilter.ShowAll 'no error, why?


问:
Is using a hash table valid in counting sort (in place of an array)?
The classic counting sort example requires you to build an array of size equal to the greatest integer of your input array.

For example, if your array is [1, 6, 3, 10000, 8] you would need an array 10000 long for the counting sort.

Could this not be done in the same linear time using a hash table on the integers?  Just a simple map?

In python, it'd be something like:

```<code>counting_map = {n: 0 for n in input_array}  # start by mapping all to 0
for num in input_array:
    counting_map[n] += 1
</code>```

I know this really only works well for integers, but in that case is the mapping solution not superior?

Time-complexity wise, you initialize the map in O(n) time, then iterate through the array in O(n) time, then perform hashing functions on input in O(1) time.  (Obviously big-O notation isn't the final determining factor of whether an algorithm is good, I just want to make sure I have the theory correct here).

Is this a good solution, or does the "original" counting sort still do something superior that I don't see?  I'm also curious why a "hashmap-based counting sort" hardly returns any Google search results, making it seem like it's hardly ever used.  Is the overhead of the hashing enough to outweigh its smaller memory footprint?

答: you need not sort the key ,just traverse from min to max as key</p>

Body:
The classic counting sort example requires you to build an array of size equal to the greatest integer of your input array.

For example, if your array is [1, 6, 3, 10000, 8] you would need an array 10000 long for the counting sort.

Could this not be done in the same linear time using a hash table on the integers?  Just a simple map?

In python, it'd be something like:

counting_map = {n: 0 for n in input_array}  # start by mapping all to 0
for num in input_array:
    counting_map[n] += 1

I know this really only works well for integers, but in that case is the mapping solution not superior?

Time-complexity wise, you initialize the map in O(n) time, then iterate through the array in O(n) time, then perform hashing functions on input in O(1) time.  (Obviously big-O notation isn't the final determining factor of whether an algorithm is good, I just want to make sure I have the theory correct here).

Is this a good solution, or does the "original" counting sort still do something superior that I don't see?  I'm also curious why a "hashmap-based counting sort" hardly returns any Google search results, making it seem like it's hardly ever used.  Is the overhead of the hashing enough to outweigh its smaller memory footprint?


问:
A Starting Menu for a simple game
I am making this small and simple game with Java, and when I start it up, it just starts the game without any menus or something. Now, I want to make it so that if I run the game, there comes a game menu, or starting menu, where you can select new game, and exit. But, how would I do this? I need some help with this.

Edit:

The game is in a 800x600 screen, and I want like, a menu that takes over the whole 800x600 screen, with just a "Start Game" and a "Exit" button.

答:
Set a JMenuBar to the JFrame (or JApplet).  Add JMenu(s) to the JMenuBar.  Add JMenuItem(s) to the JMenu(s).  Add ActionListener(s) to the JMenuItem(s).

Google 'java+tutorial+classname' for more details of each.

Title: A Starting Menu for a simple game


问:
Javascript My Array Push is only getting the last value
I have this for loop that I want to increment the year on every cycle, but I'm only getting the last year all repeating multiple times.

```<code>for (let i = 0; i < 2; i++) {
  this.data.year = new Date().getFullYear() + i;
  this.data.noSolar = averageBill * increaseRate;
  this.data.withSolar = (contractAmount * .004) + customerCharge;
  this.data.saving = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12);
  this.data.check = SREC;
  this.data.total = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12) + SREC;

  this.dataSource.push(this.data);
}
</code>```

The Year in this case 2020 is showing twice. I want something like 2019 and 2020. Its like the variable is being reference multiple times.

答:
You may try this:-</p>

```<code>for (let i = 0; i < 2; i++) {
  this.data.year = new Date().getFullYear() + i;
  this.data.noSolar = averageBill * increaseRate;
  this.data.withSolar = (contractAmount * .004) + customerCharge;
  this.data.saving = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12);
  this.data.check = SREC;
  this.data.total = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12) + SREC;

  this.dataSource.push(Object.assign({}, this.data));
}
</code>```

Body:
I have this for loop that I want to increment the year on every cycle, but I'm only getting the last year all repeating multiple times.

for (let i = 0; i < 2; i++) {
  this.data.year = new Date().getFullYear() + i;
  this.data.noSolar = averageBill * increaseRate;
  this.data.withSolar = (contractAmount * .004) + customerCharge;
  this.data.saving = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12);
  this.data.check = SREC;
  this.data.total = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12) + SREC;

  this.dataSource.push(this.data);
}

The Year in this case 2020 is showing twice. I want something like 2019 and 2020. Its like the variable is being reference multiple times.

Body:
You may try this:-

for (let i = 0; i < 2; i++) {
  this.data.year = new Date().getFullYear() + i;
  this.data.noSolar = averageBill * increaseRate;
  this.data.withSolar = (contractAmount * .004) + customerCharge;
  this.data.saving = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12);
  this.data.check = SREC;
  this.data.total = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12) + SREC;

  this.dataSource.push(Object.assign({}, this.data));
}


问:
Constraint on a related table
I have 2 tables (ItemType and Item). ItemType has a boolean hasSize, and the Item table has a size column.

I'd like to enforce that size is only set if the hasSize boolean = true.

I've seen solutions discussed which use triggers for validation. However, that doesn't provide the same robustness as a constraint.

Is this a problem of non-ideal schema design, or are there appropriate solutions for this?

答:
Yes, I'd call this a problem of the design. Normally such problems can be avoided by not storing hassize, since it can be derived when the database is queried.

Sometimes it is necessary to store redundant data to improve performance, but then you have to pay the price of potential inconsistency that you are afraid of.

If you cannot avoid persisting hassize, using a trigger is usually the best solution; try to avoid anomalies by reducing concurrency (e.g. locks or serializable isolation).

Title: Constraint on a related table


问:
How to terminate the script in JavaScript?
How can I exit the JavaScript script much like PHP's exit or die? I know it's not the best programming practice but I need to.

答:
If you use any undefined function in the script then script will stop due to "Uncaught ReferenceError". I have tried by following code and first two lines executed.

I think, this is the best way to stop the script. If there's any other way then please comment me. I also want to know another best and simple way. BTW, I didn't get exit or  die inbuilt function in Javascript like PHP for terminate the script. If anyone know then please let me know.

```<code>alert('Hello');

document.write('Hello User!!!');

die();  //Uncaught ReferenceError: die is not defined

alert('bye');

document.write('Bye User!!!');
</code>```

OwnerDisplayName: Nir

Body:
If you use any undefined function in the script then script will stop due to "Uncaught ReferenceError". I have tried by following code and first two lines executed.

I think, this is the best way to stop the script. If there's any other way then please comment me. I also want to know another best and simple way. BTW, I didn't get exit or  die inbuilt function in Javascript like PHP for terminate the script. If anyone know then please let me know.

alert('Hello');

document.write('Hello User!!!');

die();  //Uncaught ReferenceError: die is not defined

alert('bye');

document.write('Bye User!!!');


问:
How to multiply/divide one function to another ? How to use parameters?
How do I multiply a function to another function? and how do I properly use parameters?

I'm not exactly sure, I am really new to C++ with only about 14 weeks of class time.

Something I've tried would be creating a new function meant to multiply other functions and in the arguments I would put in the functions names.

For example:

```<code>float mealMath(numberOfAdults, mealChoosing){
   //Rest of function
}
</code>```

but I always get an error.Please explain how to fix this, this is a big obstacle in programming for me and I can't seem to grasp how to fix this or go about doing these things. Don't be to harsh on me for this.Thanks!

```<code>int numberOfAdults(){
    int totalAdults;
            cout << "Now how many adults will there be?: ";
            cin >> totalAdults;
                cout << "It seems there will be: " <<                      totalAdults << " Adults." << endl;
                    while(totalAdults < 1){
                        cout << "Sorry there has to be a minimum of 1 adult!" << endl;
                            cout << "How many adults: ";
                                cin >>  totalAdults;
                    }
                    return 0;
}

int numberOfKids(){
    int totalKids;
        cout << "Now how many Kids will there be?: ";
            cin >> totalKids;
                cout << "It seems there will be: " <<   totalKids << " kids." << endl;
                    while(totalKids < 0){
                        cout << "Sorry there has   to be a minimum of 1 Kid!" << endl;
                            cout << "How many   Kids: ";
                            cin >>   totalKids;
                    }
                    return 0;
                  }

float mealChoosing(){
    float cost;
        string mealChoise;
            cout << "   " << endl;
                cout << "Now, What meal will you be    getting(D/S): ";
                    cin >> mealChoise;
                        if(mealChoise == "D"){
                            cout << "It seems you have selected the Deluxe Meal plan for everyone!" << endl;
                                cost = 25.95;
                        }
                                    if(mealChoise == "S"){
                                        cout << "It seems you have selected the Standard Meal plan for everyone!" <<     endl;
                                            cost = 21.75;
                            }
                                                cout << "   " << endl;

                                                return cost;
}
</code>```

One expected result is I want to multiply the input that the user gives in function "numberOfAdults" to the input a user gives for "mealChoosing"

So I want numberOfAdults * mealChoosing but I want that done in a different function so

```<code>"float total(){
   float totalBill;
     totalBill = numberOfAdults * mealChoosing;
       cout << totalBill;"
</code>```

or something along those lines. I can't complete this project because I can't for some reason properly give the functions the proper information needed in parameters.

答:
In this case(and most) you should not declare a function whose parameters are functions. Instead declare mealMath with an integer and a float input:

```<code>float mealMath(int a, float b){/*Your code here*/}
</code>```

And then later call mealMath with the other two functions passed as arguments.

```<code>float x = mealMath(numberOfAdults(), mealChoosing());
</code>```

Alternatively you can have no function parameters for mealMath() and instead call numberOfAdults() and mealChoosing() from inside of the function.

It's important to note that most of the time you'll be calling a function and using its output as an argument, and therefore you'll need to put the () after the function's identifier, instead of just typing the identifier alone.

Body:
How do I multiply a function to another function? and how do I properly use parameters?

I'm not exactly sure, I am really new to C++ with only about 14 weeks of class time.

Something I've tried would be creating a new function meant to multiply other functions and in the arguments I would put in the functions names.

For example:

float mealMath(numberOfAdults, mealChoosing){
   //Rest of function
}

but I always get an error.Please explain how to fix this, this is a big obstacle in programming for me and I can't seem to grasp how to fix this or go about doing these things. Don't be to harsh on me for this.Thanks!

int numberOfAdults(){
    int totalAdults;
            cout << "Now how many adults will there be?: ";
            cin >> totalAdults;
                cout << "It seems there will be: " <<                      totalAdults << " Adults." << endl;
                    while(totalAdults < 1){
                        cout << "Sorry there has to be a minimum of 1 adult!" << endl;
                            cout << "How many adults: ";
                                cin >>  totalAdults;
                    }
                    return 0;
}

int numberOfKids(){
    int totalKids;
        cout << "Now how many Kids will there be?: ";
            cin >> totalKids;
                cout << "It seems there will be: " <<   totalKids << " kids." << endl;
                    while(totalKids < 0){
                        cout << "Sorry there has   to be a minimum of 1 Kid!" << endl;
                            cout << "How many   Kids: ";
                            cin >>   totalKids;
                    }
                    return 0;
                  }

float mealChoosing(){
    float cost;
        string mealChoise;
            cout << "   " << endl;
                cout << "Now, What meal will you be    getting(D/S): ";
                    cin >> mealChoise;
                        if(mealChoise == "D"){
                            cout << "It seems you have selected the Deluxe Meal plan for everyone!" << endl;
                                cost = 25.95;
                        }
                                    if(mealChoise == "S"){
                                        cout << "It seems you have selected the Standard Meal plan for everyone!" <<     endl;
                                            cost = 21.75;
                            }
                                                cout << "   " << endl;

                                                return cost;
}

One expected result is I want to multiply the input that the user gives in function "numberOfAdults" to the input a user gives for "mealChoosing"

So I want numberOfAdults * mealChoosing but I want that done in a different function so

"float total(){
   float totalBill;
     totalBill = numberOfAdults * mealChoosing;
       cout << totalBill;"

or something along those lines. I can't complete this project because I can't for some reason properly give the functions the proper information needed in parameters.

Body:
In this case(and most) you should not declare a function whose parameters are functions. Instead declare mealMath with an integer and a float input:

float mealMath(int a, float b){/*Your code here*/}

And then later call mealMath with the other two functions passed as arguments.

float x = mealMath(numberOfAdults(), mealChoosing());

Alternatively you can have no function parameters for mealMath() and instead call numberOfAdults() and mealChoosing() from inside of the function.

It's important to note that most of the time you'll be calling a function and using its output as an argument, and therefore you'll need to put the () after the function's identifier, instead of just typing the identifier alone.


问:
Docker-compose and .dockerignore
There is small config of docker-compose with Dockerfiles and .dockerignore files I have in subdirectories. I can't understand why my images after build include everything even I have some items to ignore in .dockerignore. Here is what I have

```<code>docker-compose.yml
docker
├── app
│   ├── Dockerfile
│   └── .dockerignore
└── web
    ├── Dockerfile
    ├── nginx.conf
    └── .dockerignore
</code>```

Example of .dockerignore:

```<code>**/.dockerignore
docker-compose.yml
log
**/log
../../log
</code>```

I just run this as follows:

```<code>docker-compose up -d --build --no-cache
</code>```

None of the above ignored.. What am I doing wrong?

```<code>docker-compose version 1.23.2, build 1110ad01
</code>```

Adding Dockerfile for the app service (see docker-compose). Docker-compose packs two images with ROR app and nginx. For both dockerfiles I have dockerignore. So my understanding is that I can say what exactly I want in each. But it is not. How can I ignore some of the files in package? Or should I put my Dockerfile and dockerignore in different paths since build works only inside the context.. I am confused.

```<code>FROM ruby:2.4.1
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs imagemagick
# Configuring main directory
RUN mkdir -p /var/www/example.com
WORKDIR /var/www/example.com
# Setting env up
ENV RAILS_ENV='production'
ENV RACK_ENV='production'

# Adding gems
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN bundle install --jobs 20 --retry 5 --without development test
# Adding project files
COPY . .

EXPOSE 3000
CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]
</code>```

So I thought that COPY . .  checks .dockerignore first.. no?

答: The .dockerignore needs to be in the root directory/context folder as you specified in the docker-compose.yml

Title: Docker-compose and .dockerignore

Body:
There is small config of docker-compose with Dockerfiles and .dockerignore files I have in subdirectories. I can't understand why my images after build include everything even I have some items to ignore in .dockerignore. Here is what I have

docker-compose.yml
docker
├── app
│   ├── Dockerfile
│   └── .dockerignore
└── web
    ├── Dockerfile
    ├── nginx.conf
    └── .dockerignore

Example of .dockerignore:

**/.dockerignore
docker-compose.yml
log
**/log
../../log

I just run this as follows:

docker-compose up -d --build --no-cache

None of the above ignored.. What am I doing wrong?

docker-compose version 1.23.2, build 1110ad01

Adding Dockerfile for the app service (see docker-compose). Docker-compose packs two images with ROR app and nginx. For both dockerfiles I have dockerignore. So my understanding is that I can say what exactly I want in each. But it is not. How can I ignore some of the files in package? Or should I put my Dockerfile and dockerignore in different paths since build works only inside the context.. I am confused.

FROM ruby:2.4.1
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs imagemagick
# Configuring main directory
RUN mkdir -p /var/www/example.com
WORKDIR /var/www/example.com
# Setting env up
ENV RAILS_ENV='production'
ENV RACK_ENV='production'

# Adding gems
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN bundle install --jobs 20 --retry 5 --without development test
# Adding project files
COPY . .

EXPOSE 3000
CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]

So I thought that COPY . .  checks .dockerignore first.. no?


问:
Expand all PrimeNG Accordion panels automatically for Printing
I am currently using the PrimeNG library's accordion component in my angular project. See info here.

The template includes some special css styling for printing the page--something like the following:

```<code> @media print {
  .profile-progress-bar, .top-template-header-content, .header.profile-header{
    display: none !important;
  }
  html, body {
    height: auto;
    font-size: 10px !important;
  }

  p-accordionTab > div {
    display: block !important;
    selected: true !important;
  }

}
</code>```

What I am trying to do, is automatically expand all accordionTab elements when the @media print rendering is processed for the page to be printed.

From the documentation I see that each accordionTab element has a [selected] property which can be bound to and set to "true" in order to expand the tab.

Selected Visibility of the content is specified with the selected
  property that supports one or two-way binding.

However, can this be somehow automatically triggered when the @media print rendering occurs?

Thanks!

答:
media query is the way to go, you can take a css only approach to achieve this; no change in TS or HTML files

relevant css:

```<code>@media print {
  ::ng-deep .ui-accordion-content-wrapper-overflown {
      overflow: visible;
      height: auto !important;
  }
}
</code>```

complete demo on stackblitz here

Body:
I am currently using the PrimeNG library's accordion component in my angular project. See info here.

The template includes some special css styling for printing the page--something like the following:

 @media print {
  .profile-progress-bar, .top-template-header-content, .header.profile-header{
    display: none !important;
  }
  html, body {
    height: auto;
    font-size: 10px !important;
  }

  p-accordionTab > div {
    display: block !important;
    selected: true !important;
  }

}

What I am trying to do, is automatically expand all accordionTab elements when the @media print rendering is processed for the page to be printed.

From the documentation I see that each accordionTab element has a [selected] property which can be bound to and set to "true" in order to expand the tab.

Selected Visibility of the content is specified with the selected
  property that supports one or two-way binding.

However, can this be somehow automatically triggered when the @media print rendering occurs?

Thanks!

Body:
media query is the way to go, you can take a css only approach to achieve this; no change in TS or HTML files

relevant css:

@media print {
  ::ng-deep .ui-accordion-content-wrapper-overflown {
      overflow: visible;
      height: auto !important;
  }
}

complete demo on stackblitz here


问:
How can I use @around spring aop annotation on method declaration?
How can I use @around spring AOP annotation on method declaration? actually there are lots of duplicate code in the java class so I am thinking to optimize it.Only the @around execution values are getting changed every time  and method definition is same for 3-4 methods.Can you please suggest what I can do in this case for code optimization?Here in the given example you can see nicdStatus and nicdPortStatus are only getting changed and rest all the method definition is same.
            Please provide some suggestion for code optimization because I have duplicate code in my java class.

@Around("execution(* dcp.casa.services.nicd.NicdController.**nicdStatus**(..)) && args(*, relationId,..)")
Object handleRunTest(final ProceedingJoinPoint joinPoint, final String relationId) {
    log.info("xyz");
    callAbc();
    return joinPoint.proceed();
}

@Around("execution(* dcp.casa.services.nicd.NicdController.nicdPortStatus(..)) && args(*, relationId,..)")
Object handleRunTest(final ProceedingJoinPoint joinPoint, final String relationId) {
    log.info("xyz");
    callAbc();
    return joinPoint.proceed();
}
```

答:
Your question is a bit unclear. Am I guessing right that you have multiple @Around advice methods with identical method bodies and you want to factor out those method bodies into a helper method in order to avoid code duplication within your aspect(s)?

yes you are correct @kriegaex. you understood my question.

Well, then the answer is simple: Just refactor like you would refactor any other Java class:

package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Aspect
public class LoggingAspect {
  private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);

  private void callAbc() {}

  @Around("execution(* dcp.casa.services.nicd.NicdController.**nicdStatus**(..)) && args(*, relationId, ..)")
  public Object handleRunTestA(ProceedingJoinPoint joinPoint, String relationId) throws Throwable {
    return handleRunHelper(joinPoint);
  }

  @Around("execution(* dcp.casa.services.nicd.NicdController.nicdPortStatus(..)) && args(*, relationId, ..)")
  public Object handleRunTestB(ProceedingJoinPoint joinPoint, String relationId) throws Throwable {
    return handleRunHelper(joinPoint);
  }

  private Object handleRunHelper(ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("xyz");
    callAbc();
    return joinPoint.proceed();
  }
}
```

If the helper method also needs access to String relationId, just add another parameter to it and call it correspondingly.

Body:
Your question is a bit unclear. Am I guessing right that you have multiple @Around advice methods with identical method bodies and you want to factor out those method bodies into a helper method in order to avoid code duplication within your aspect(s)?

yes you are correct @kriegaex. you understood my question.

Well, then the answer is simple: Just refactor like you would refactor any other Java class:

package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Aspect
public class LoggingAspect {
  private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);

  private void callAbc() {}

  @Around("execution(* dcp.casa.services.nicd.NicdController.**nicdStatus**(..)) && args(*, relationId, ..)")
  public Object handleRunTestA(ProceedingJoinPoint joinPoint, String relationId) throws Throwable {
    return handleRunHelper(joinPoint);
  }

  @Around("execution(* dcp.casa.services.nicd.NicdController.nicdPortStatus(..)) && args(*, relationId, ..)")
  public Object handleRunTestB(ProceedingJoinPoint joinPoint, String relationId) throws Throwable {
    return handleRunHelper(joinPoint);
  }

  private Object handleRunHelper(ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("xyz");
    callAbc();
    return joinPoint.proceed();
  }
}

If the helper method also needs access to String relationId, just add another parameter to it and call it correspondingly.


问:
sqlite constraint failed error code
I have two tables albums and songs and each song has reference to alum's id.

Album table :

```<code>CREATE TABLE albums
(id INTEGER PRIMARY KEY ASC,
name TEXT,
additional TEXT)
</code>```

Song table:

```<code>CREATE TABLE songs
(id INTEGER PRIMARY KEY ASC,
album_fk INTEGER NOT NULL,
title TEXT,
url TEXT,
duration BIGINT NOT NULL)
</code>```

and i also have a trigger to check when i delete an album if there are existing songs in it :

```<code>CREATE TRIGGER trigger_on_delete
BEFORE DELETE ON albums
FOR EACH ROW BEGIN
SELECT RAISE(FAIL,'album has songs cannot be deleted')
WHERE (SELECT album_fk FROM songs WHERE album_fk = OLD.id) IS NOT
NULL;)
END
</code>```

all this is working fine but sometimes

```<code>Exception: android.database.sqlite.SQLiteConstraintException: error
code 19: constraint failed
Stack Trace :
android.database.sqlite.SQLiteStatement.native_execute(Native Method)
android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:
66)
</code>```

is thrown when i try to delete an album. My delete method is simply deleting an album by id.The bad thing is that i can't reproduce this so there is no much info i can provide.
I tried different scenarios with deleting an album but i never got this exception.

So any ideas how can investigate this issue. There are not any contraints in album table so what could cause such exception ? Any help will be appreciated.

答:
See also "SQLiteStatement does not propagate error messages defined in SQLite triggers"
 http://code.google.com/p/android/issues/detail?id=3296</p>

Title: sqlite constraint failed error code

Body:
I have two tables albums and songs and each song has reference to alum's id.

Album table :

CREATE TABLE albums
(id INTEGER PRIMARY KEY ASC,
name TEXT,
additional TEXT)

Song table:

CREATE TABLE songs
(id INTEGER PRIMARY KEY ASC,
album_fk INTEGER NOT NULL,
title TEXT,
url TEXT,
duration BIGINT NOT NULL)

and i also have a trigger to check when i delete an album if there are existing songs in it :

CREATE TRIGGER trigger_on_delete
BEFORE DELETE ON albums
FOR EACH ROW BEGIN
SELECT RAISE(FAIL,'album has songs cannot be deleted')
WHERE (SELECT album_fk FROM songs WHERE album_fk = OLD.id) IS NOT
NULL;)
END

all this is working fine but sometimes

Exception: android.database.sqlite.SQLiteConstraintException: error
code 19: constraint failed
Stack Trace :
android.database.sqlite.SQLiteStatement.native_execute(Native Method)
android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:
66)

is thrown when i try to delete an album. My delete method is simply deleting an album by id.The bad thing is that i can't reproduce this so there is no much info i can provide.
I tried different scenarios with deleting an album but i never got this exception.

So any ideas how can investigate this issue. There are not any contraints in album table so what could cause such exception ? Any help will be appreciated.


问:
Serve Images in Next-Gen Formats
My ranking from Google Page Speed insights is being severely penalised because of:

"Serve Images in Next-Gen Formats" more info on Google's help page here.

However, according to this, this and this those formats are supported very few browsers.

What do you do in this scenario? What

答:
WebP is the one that currently has broader support, pretty much all major browser except Safari support it.

As colossalyouth mentioned on one of the answers you can use the picture tag to load webp images and in the case is not supported it will fallback to any other format you choose.

And if you are using background-image you can use something like modernizr to detect feature support by the browser and end up with CSS like the following:

```<code>my-selector {
    background: url('../images/home-bg.webp') no-repeat scroll center center
}

.no-webp my-selector {
    background: url('../images/home-bg.jpg') no-repeat scroll center center
}
</code>```

I have actually done both things on my website and successfully implemented webp formats, I have created a detailed post on how I did it and the performance gains I had you can check it out here: Improve your website speed performance using next-gen formats

Title: Serve Images in Next-Gen Formats

Body:
WebP is the one that currently has broader support, pretty much all major browser except Safari support it.

As colossalyouth mentioned on one of the answers you can use the picture tag to load webp images and in the case is not supported it will fallback to any other format you choose.

And if you are using background-image you can use something like modernizr to detect feature support by the browser and end up with CSS like the following:

my-selector {
    background: url('../images/home-bg.webp') no-repeat scroll center center
}

.no-webp my-selector {
    background: url('../images/home-bg.jpg') no-repeat scroll center center
}

I have actually done both things on my website and successfully implemented webp formats, I have created a detailed post on how I did it and the performance gains I had you can check it out here: Improve your website speed performance using next-gen formats


问:
How to localize default validation message for value-type (ushort) properties if value is out of the type boundaries?
I have some web form where user should enter the port number. Of course the best type for the port number is ushort. I use RangeAttribute to validate the port number and some error message.

[Required(ErrorMessage = "The field is required")]
[Display(Name = "Port")]
[Range(1, ushort.MaxValue, ErrorMessage = "Invalid value")]
public ushort Port { get; set; }
```

The localization works correct only if I enter values from 0 to 65535. So there is only one incorrect case - zero value. But if I try to save empty value, enter negative values or values greater than 65535, I get completely another error message (The value '-1' is not valid for Port.) and I don't know how to localize it.

Could anybody help me with this?

答:
Try to use int and custom validation attribute like

```<code>public class PortPolicy : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if ((int)value >= 1 && (int)value <= 65535)
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult("Invalid value");
        }
    }
}
</code>```

Model:

```<code>[Required(ErrorMessage = "The field is required")]
[Display(Name = "Port")]
[PortPolicy]
public int Port { get; set; }
</code>```

Body:
I have some web form where user should enter the port number. Of course the best type for the port number is ushort. I use RangeAttribute to validate the port number and some error message.

[Required(ErrorMessage = "The field is required")]
[Display(Name = "Port")]
[Range(1, ushort.MaxValue, ErrorMessage = "Invalid value")]
public ushort Port { get; set; }

The localization works correct only if I enter values from 0 to 65535. So there is only one incorrect case - zero value. But if I try to save empty value, enter negative values or values greater than 65535, I get completely another error message (The value '-1' is not valid for Port.) and I don't know how to localize it.

Could anybody help me with this?

Body:
Try to use int and custom validation attribute like

public class PortPolicy : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if ((int)value >= 1 && (int)value <= 65535)
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult("Invalid value");
        }
    }
}

Model:

[Required(ErrorMessage = "The field is required")]
[Display(Name = "Port")]
[PortPolicy]
public int Port { get; set; }


问:
Is it advisable to add to the global window object?
So I'm working a React/Typescript project, where I need to store a value for the number of rows that needs to be accessible globally.

Is it a good idea to define it on the window object?

```<code>window.MySpace = {};
MySpace.rowCount = 10;
</code>```

Are there any issues that could arise as the project grows? Or is there a more elegant way of handling this through Typescript?

Thanks!

edit:

Declare it as a module in a module.ts file

```<code>export module Global {
    export const rowCount = 10;
}
</code>```

Then import it to whichever file requires the value of rowCount.

答:
When You need to store a value that needs to be accessible globally, create a global object with a unique name, with your variables as properties of that object:

```<code>window.MySpace= {};
</code>```

Then use it in whatever way you prefer.
Use it with functions

```<code>MySpace.show();
MySpace.hide();
</code>```

Assign a value to it

```<code>MySpace.value=1;
MySpace.value=2;
</code>```

different ways to handle that

```<code>MySpace.rowCount = 10;
</code>```

and yes it is sometimes a good idea to define it on the window object, some cases require other ways of defining.

You're good to go!!

Body:
So I'm working a React/Typescript project, where I need to store a value for the number of rows that needs to be accessible globally.

Is it a good idea to define it on the window object?

window.MySpace = {};
MySpace.rowCount = 10;

Are there any issues that could arise as the project grows? Or is there a more elegant way of handling this through Typescript?

Thanks!

edit:

Declare it as a module in a module.ts file

export module Global {
    export const rowCount = 10;
}

Then import it to whichever file requires the value of rowCount.

Body:
When You need to store a value that needs to be accessible globally, create a global object with a unique name, with your variables as properties of that object:

window.MySpace= {};

Then use it in whatever way you prefer.
Use it with functions

MySpace.show();
MySpace.hide();

Assign a value to it

MySpace.value=1;
MySpace.value=2;

different ways to handle that

MySpace.rowCount = 10;

and yes it is sometimes a good idea to define it on the window object, some cases require other ways of defining.

You're good to go!!


问:
Are explicit specializations templates?
According to [temp.spec] p4, a specialization is a class/function/[...] that is instantiated, or explicitly specialized. [temp.expl.spec] p19 states that some explicit specializations are templates, which leads me to believe that explicit specializations are specialization (in the "entity generated from a template" sense), and not templates (sometimes).

My question is, are explicit specializations actual concrete entities (class/function/[...]), or are they templates. If not, what exactly are they of they aren't templates or specializations (following the definition provided by [temp.spec] p4)

答:
Your question assumes a binary status that need not exist, that an explicit specialization is either a template or a "concrete entity".

An explicit specialization may or may not be a template. A non-template explicit specialization is a specialization. As stated in the very text you quote:

A specialization is a class, variable, function, or class member that is either instantiated or explicitly specialized.

Thus, explicit specializations behave like specializations. Template instantiation (implicit or explicit) creates specializations, unless the parameters match an explicit specialization. So instead, that is what gets used. But whether generated by an instantiation or by explicit specialization, specializations are treated as specializations.

So for example, different explicit specializations of the same function template are handled, not through overload resolution rules, but through template argument deduction. This is no different from any other case of specialization of that template.

Title: Are explicit specializations templates?


问:
Search for pattern and add sequential number to end of each line where pattern occurs
I want to search for a pattern and add sequential number to end of line.
For example, I have following text file.

```<code>Male
John  #
Tom   #
Jack  #

Female
Mary  #
Jenny #
</code>```

I want to search pattern "#" and add sequential number end of line.

```<code>Male
John  #0
Tom   #1
Jack  #2

Female
Mary  #3
Jenny #4
</code>```

答:
You could substitute with ascending numbers, as explained in this tip from the Vim Wiki:</p>

```<code>:let i=1 | g/#$/s//\='#'.i/ | let i=i+1
</code>```

Body:
I want to search for a pattern and add sequential number to end of line.
For example, I have following text file.

Male
John  #
Tom   #
Jack  #

Female
Mary  #
Jenny #

I want to search pattern "#" and add sequential number end of line.

Male
John  #0
Tom   #1
Jack  #2

Female
Mary  #3
Jenny #4

Body:
You could substitute with ascending numbers, as explained in this tip from the Vim Wiki:

:let i=1 | g/#$/s//\='#'.i/ | let i=i+1


问:
JestJS - show all uncovered lines in coverage report
When I run the Jest coverage report, it prints out each type of coverage and the percentage by file. The last column that shows the uncovered lines gets truncated when there are more than ~4-5 lines. Is there a way to print all of the uncovered lines?

```<code>-------------------------------|----------|----------|----------|----------|----------------|
File                           |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
-------------------------------|----------|----------|----------|----------|----------------|
All files                      |    75.57 |    69.18 |    74.21 |    75.83 |                |
 js/components/catalyst        |    80.74 |    72.97 |    80.16 |    81.85 |                |
  JobGroup.jsx                 |    57.14 |       50 |    44.44 |       60 |... 33,34,38,73 |
...etc
</code>```

This shows me that JobGroup.jsx has lines 33,34,38, and 73, but there are more, and I'd like to see them all at once.

答:
Is there a way to print all of the uncovered lines?

I'm using React + TypeScript + Jest. In my project, I run npm test -- --coverage, and the file with the remaining uncovered lines is under the coverage directory:

```<code><project name>\<directory>\<directory>\coverage\lcov-report\index.html
</code>```

(Your file path may have a variation on the coverage part. :-))

Then I navigate to the file of interest:

All lines highlighted in pink are uncovered:

Body:
When I run the Jest coverage report, it prints out each type of coverage and the percentage by file. The last column that shows the uncovered lines gets truncated when there are more than ~4-5 lines. Is there a way to print all of the uncovered lines?

-------------------------------|----------|----------|----------|----------|----------------|
File                           |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
-------------------------------|----------|----------|----------|----------|----------------|
All files                      |    75.57 |    69.18 |    74.21 |    75.83 |                |
 js/components/catalyst        |    80.74 |    72.97 |    80.16 |    81.85 |                |
  JobGroup.jsx                 |    57.14 |       50 |    44.44 |       60 |... 33,34,38,73 |
...etc

This shows me that JobGroup.jsx has lines 33,34,38, and 73, but there are more, and I'd like to see them all at once.

Body:
Is there a way to print all of the uncovered lines?

I'm using React + TypeScript + Jest. In my project, I run npm test -- --coverage, and the file with the remaining uncovered lines is under the coverage directory:

<project name>\<directory>\<directory>\coverage\lcov-report\index.html

(Your file path may have a variation on the coverage part. :-))

Then I navigate to the file of interest:

All lines highlighted in pink are uncovered:


问:
Enum.each loses variable when looping over an ExUnit test
When running the following code I get the warning:

```<code>warning: variable "char" does not exist and is being expanded to "char()", please use parentheses to remove the ambiguity or change the variable name
  test/my_module_test.exs:7
</code>```

Followed by a failed test:

```<code>== Compilation error in file test/my_module_test.exs ==
** (CompileError) test/my_module_test.exs:7: undefined function char/0
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/code.ex:767: Code.require_file/2
    (elixir) lib/kernel/parallel_compiler.ex:209: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6
</code>```

defmodule MyModule do
  use ExUnit.Case, async: true
  doctest MyModule

  Enum.each ~w(a b c), fn char ->
    test "test involving #{char}" do
      assert char == char
    end
  end
end
```

It seems that within the Enum.each block the value of char is defined for the line test "... #{char}" do but becomes undefined within the assertions.

Why is this happening?

答:
ExUnit.test/3 is a macro that defines a function for you.

Every time you define a new function in Elixir, it starts a new scope. This means any variable defined outside of the function won't be available inside the function. For example, you can't do this:

```<code>foo = 1
def some_function() do
  foo
end
</code>```

There are some ways you can bypass this mechanism. One is to use unquote to inject some values as AST. However, in this case, the simplest approach is to put the value in a module attribute, so you can read it inside the function:

```<code>@foo 1
def some_function() do
  @foo
end
</code>```

Whether you want to run the same test with different inputs (although it likely means there are issues with the test structure design,) you might use ExUnit.Callbacks.setup_all/2 to setup tests context, or use module attributes as shown in the documentation for ExUnit.Case.test/3

```<code>Enum.each ~w(a b c), fn char ->
  @char char
  test "test involving #{char}", ctx do
    assert @char == @char
  end
end
</code>```

Module attributes are obviously visible from anywhere in a module after they are defined.

Body:
When running the following code I get the warning:

warning: variable "char" does not exist and is being expanded to "char()", please use parentheses to remove the ambiguity or change the variable name
  test/my_module_test.exs:7

Followed by a failed test:

== Compilation error in file test/my_module_test.exs ==
** (CompileError) test/my_module_test.exs:7: undefined function char/0
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/code.ex:767: Code.require_file/2
    (elixir) lib/kernel/parallel_compiler.ex:209: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6

defmodule MyModule do
  use ExUnit.Case, async: true
  doctest MyModule

  Enum.each ~w(a b c), fn char ->
    test "test involving #{char}" do
      assert char == char
    end
  end
end

It seems that within the Enum.each block the value of char is defined for the line test "... #{char}" do but becomes undefined within the assertions.

Why is this happening?

Body:
ExUnit.test/3 is a macro that defines a function for you.

Every time you define a new function in Elixir, it starts a new scope. This means any variable defined outside of the function won't be available inside the function. For example, you can't do this:

foo = 1
def some_function() do
  foo
end

There are some ways you can bypass this mechanism. One is to use unquote to inject some values as AST. However, in this case, the simplest approach is to put the value in a module attribute, so you can read it inside the function:

@foo 1
def some_function() do
  @foo
end

Whether you want to run the same test with different inputs (although it likely means there are issues with the test structure design,) you might use ExUnit.Callbacks.setup_all/2 to setup tests context, or use module attributes as shown in the documentation for ExUnit.Case.test/3

Enum.each ~w(a b c), fn char ->
  @char char
  test "test involving #{char}", ctx do
    assert @char == @char
  end
end

Module attributes are obviously visible from anywhere in a module after they are defined.


问:
unknow system variable: "new.id" is not recognized
Let's say 6,7,8 are all taken, and l tried to insert data with id = 6. The purpose of the trigger is to find the next available number. However, MySQL does not recognize new.id
Or, can l alter auto_increment's value?
Why am l doing this? Because in OracleDB, the sequence generator will increment(and eventually find that available number) whereas MySQL's sequence generator won't increment if a duplicate primary key is generated somehow.

tried to replace "new.id = @valid" with "alter table wooster_brush_employee auto_increment = @valid" in trigger, but it did not work.

create table wooster_brush_employee(
    id int primary key auto_increment,
    first_name varchar(15),
    last_name varchar(20),
    username varchar(10),
    password varchar(15),
    email varchar(30)
);
delimiter //
create trigger validate_id before insert on wooster_brush_employee
    for each row
    set @old = last_insert_id();
    set @valid = last_insert_id();
    call wooster_brush_employee_id_validator(@old, @valid);
    set NEW.id = @valid;
    end;
delimiter;

答:
I believe that your whole approach here is off kilter, and you don't even need to use this trigger.  The point of an auto increment column, in either MySQL or Oracle, is that the database handles the problem of finding the next available number in the sequence.  While the auto increment contract does not guarantee that the next value found will be greater than every value already in the column, it does guarantee that the next value will be unique.

So, if you want to make use of MySQL's auto increment functionality, then next time you insert, simply omit id from the column list:

```<code>INSERT INTO wooster_brush_employee (first_name, last_name, username, password, email)
VALUES
    ('Jon', 'Skeet', 'jonskeet', '*****", 'jon.skeet@google.com');
</code>```

Since id was omitted, MySQL will automatically generate the next value in the sequence behind the scenes.

Body:
I believe that your whole approach here is off kilter, and you don't even need to use this trigger.  The point of an auto increment column, in either MySQL or Oracle, is that the database handles the problem of finding the next available number in the sequence.  While the auto increment contract does not guarantee that the next value found will be greater than every value already in the column, it does guarantee that the next value will be unique.

So, if you want to make use of MySQL's auto increment functionality, then next time you insert, simply omit id from the column list:

INSERT INTO wooster_brush_employee (first_name, last_name, username, password, email)
VALUES
    ('Jon', 'Skeet', 'jonskeet', '*****", 'jon.skeet@google.com');

Since id was omitted, MySQL will automatically generate the next value in the sequence behind the scenes.


问:
PermGen Out of Memory reasons
I constantly detect OOM in PermGen for my environment:

java 6

jboss-4.2.3

Not a big web-application

I know about String.intern() problem - but I don't have enough valuable usage of it.
Increasing of MaxPermGen size didn't take a force (from 128 Mb to 256 Mb).

What other reasons could invoke OOM for PermGen?
What scenario of investigation is the best in such situation (strategy, tools and etc.)?

Thanks for any help

答:
You typically get this error when redeploying an application while having a classloader leak, because it means all your classes are loaded again while the old versions stay around.

There are two solutions:

Restart the app server instead of redeploying the application - easy, but annoying

Investigate and fix the leak using a profiler. Unfortunately, classloader leaks can be very hard to pinpoint.

Title: PermGen Out of Memory reasons