问:
How do I add variable number of months to a date in Ruby (avoid using loop)
Is there something similar to the code below in Ruby where X stands for the number of months to add to today's date but is coming from a variable

Time.zone.today + X.month ## X comes from a variable
```

<p><strong>Preferably without using a loop as 'm' can be large number in the example below</strong></p>

<pre class="lang-rb prettyprint-override"><code>def add_months_to_today(m)
  number_of_months_to_add = m.to_i
  return_date = Time.zone.today
  if m.to_i > 0
    (1..number_of_months_to_add).each do |i|
      return_date = return_date + 1.month
    end
  end

  return_date
end
</code>```

答:
Your code works perfectly fine:

```<code>x = 4
Time.zone.today + x.month
#=> Sun, 29 Sep 2019
</code>```

month is a method defined on Integer. It doesn't matter if the integer is given as a literal or as a variable. The receiver just has to be an Integer.

Instead of Time.zone.today you could also call Date.current:

```<code>Date.current + 4.month  #=> Sun, 29 Sep 2019
</code>```

Rails also adds a variety of other methods to Date: (also via DateAndTime::Calculations)

```<code>Date.current.advance(months: 4) #=> Sun, 29 Sep 2019
Date.current.months_since(4)    #=> Sun, 29 Sep 2019
4.months.since(Date.current)    #=> Sun, 29 Sep 2019
</code>```

The above also work for instances of Time:

```<code>Time.current.advance(months: 4) #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
Time.current.months_since(4)    #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
4.months.since                  #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
</code>```

When only dealing with dates, Ruby's built-in >> or next_month might be used as well:

```<code>Date.current >> 4
#=> Sun, 29 Sep 2019

Date.current.next_month(4)
#=> Sun, 29 Sep 2019
</code>```

Note that you can use 4 and x interchangeably in all of the above examples.

Body:
Is there something similar to the code below in Ruby where X stands for the number of months to add to today's date but is coming from a variable

Time.zone.today + X.month ## X comes from a variable

Preferably without using a loop as 'm' can be large number in the example below

def add_months_to_today(m)
  number_of_months_to_add = m.to_i
  return_date = Time.zone.today
  if m.to_i > 0
    (1..number_of_months_to_add).each do |i|
      return_date = return_date + 1.month
    end
  end

  return_date
end

Body:
Your code works perfectly fine:

x = 4
Time.zone.today + x.month
#=> Sun, 29 Sep 2019

month is a method defined on Integer. It doesn't matter if the integer is given as a literal or as a variable. The receiver just has to be an Integer.

Instead of Time.zone.today you could also call Date.current:

Date.current + 4.month  #=> Sun, 29 Sep 2019

Rails also adds a variety of other methods to Date: (also via DateAndTime::Calculations)

Date.current.advance(months: 4) #=> Sun, 29 Sep 2019
Date.current.months_since(4)    #=> Sun, 29 Sep 2019
4.months.since(Date.current)    #=> Sun, 29 Sep 2019

The above also work for instances of Time:

Time.current.advance(months: 4) #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
Time.current.months_since(4)    #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00
4.months.since                  #=> Sun, 29 Sep 2019 10:11:52 CEST +02:00

When only dealing with dates, Ruby's built-in >> or next_month might be used as well:

Date.current >> 4
#=> Sun, 29 Sep 2019

Date.current.next_month(4)
#=> Sun, 29 Sep 2019

Note that you can use 4 and x interchangeably in all of the above examples.


来源: stackexchange

问:
Drupal 6 batch not executing
Anyone able to offer some ideas on this? Basically the module I'm building has a form (as per function_email_solicitors_compose), and on submission we obviously route to form_emails_solicitors_compose_submit. Here I define a batch in $batch, and batch_set the aforementioned batch. The drupal documentation says I don't need to run batch_process() if it's called from within a form_submit, which this is, but I've tried with and without. All tests have shown that it gets as far as defining the batch but never goes any further than that. email_solicitors_batch_iteration never runs. Any ideas?

As an additional bit of info, batch_get then returns the following:

```<code>Array
(
    [sets] => Array
        (
            [0] => Array
                (
                    [sandbox] => Array
                        (
                        )

                    [results] => Array
                        (
                        )

                    [success] =>
                    [title] => Emailing.
                    [operations] => Array
                        (
                            [0] => Array
                                (
                                    [0] =>
</code>```

email_solicitors_batch_iteration
                                          [1] => Array
                                              (
                                                  [0] =>
                                                  [1] =>
                                              )

```<code>                                )

                        )

                    [finished] => my_finished_callback
                    [init_message] => Initializing.<br/>
                    [progress_message] => Remaining
</code>```

@remaining of @total.
                          [error_message] => An error has
  occurred.
                          [total] => 1
                      )

```<code>        )

)
</code>```

The code:

```<code>function email_solicitors_compose(){
    $form['email_solicitors_subject'] = array(
        '#type' => 'textfield',
        '#title' => t('Subject'),
        '#description' => t('Enter the subject of your email'),
        '#default_value' => 'Subject',
        '#size' => 30
    );
    $form['email_solicitors_message'] = array(
        '#type' => 'textarea',
        '#title' => t('Message'),
        '#description' => t('Write your message here. <strong>Please note that we will automatically add "Dear #name", which will be personalised to the solicitor.</strong>'),
        '#default_value' => '',
    );
    $form['email_solicitors_submit'] = array(
        '#type' => 'submit',
        '#title' => t('Submit'),
        '#description' => t('Sumbit this form.'),
        '#default_value' => 'Submit',
    );
    return $form;
}//function email_solicitors_compose

function email_solicitors_compose_submit($form_state)
{
    $batch = array(
        'title' => t('Sending emails to solicitors'),
        'operations' => array(
            array('email_solicitors_batch_iteration', array())
        ),
        'finished' => 'email_solicitors_batch_finished', //run this when we're finished
        'init_message' => t('Preparing to send emails'), //initialisation message
        'progress_message' => t('Sent @current out of @total messages.'),
        'error_message' => t('Sorry, something went wrong when sending emails.'),
    );// create batch array
    $info=print_r($batch,TRUE);
    drupal_set_message($info);
    batch_set($batch);
    batch_process();
}//function email_solicitors_compose_submit

function email_solicitors_batch_iteration(&$context)
{
    // Initialize sandbox the first time through.
    if (!isset($context['sandbox']['progress'])) {
        $context['sandbox']['progress'] = 0;
        $context['sandbox']['current_user_id'] = 0;
        $context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT field_solicitor_email_value) FROM content_type_solicitor'));
    }
    $comment="On item ".$context['sandbox']['progress'];
    drupal_set_message ($comment);
}//function email_solicitors_batch_iteration

function email_solicitors_batch_finished (&$context)
{
    die ('woohoo we finished');
}
</code>```

答:
Are you having a start of sign that the batch is beginning or just nothing happens?
You are missing two information in your batch operation callback: the increase of the progress and most importantly a statement to determine when the batch should over.</p>

```<code>  // Update our progress information.
  $context['sandbox']['progress']++;
  $context['sandbox']['current_node'] = $row['nid'];
  $context['message'] = t('Calcul des votes pour %node', array('%node' => $row['title']));

  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Drupal 6 batch not executing

Body:
Anyone able to offer some ideas on this? Basically the module I'm building has a form (as per function_email_solicitors_compose), and on submission we obviously route to form_emails_solicitors_compose_submit. Here I define a batch in $batch, and batch_set the aforementioned batch. The drupal documentation says I don't need to run batch_process() if it's called from within a form_submit, which this is, but I've tried with and without. All tests have shown that it gets as far as defining the batch but never goes any further than that. email_solicitors_batch_iteration never runs. Any ideas?

As an additional bit of info, batch_get then returns the following:

Array
(
    [sets] => Array
        (
            [0] => Array
                (
                    [sandbox] => Array
                        (
                        )

                    [results] => Array
                        (
                        )

                    [success] =>
                    [title] => Emailing.
                    [operations] => Array
                        (
                            [0] => Array
                                (
                                    [0] =>

email_solicitors_batch_iteration
                                          [1] => Array
                                              (
                                                  [0] =>
                                                  [1] =>
                                              )

                                )

                        )

                    [finished] => my_finished_callback
                    [init_message] => Initializing.

                    [progress_message] => Remaining

@remaining of @total.
                          [error_message] => An error has
  occurred.
                          [total] => 1
                      )

        )

)

The code:

function email_solicitors_compose(){
    $form['email_solicitors_subject'] = array(
        '#type' => 'textfield',
        '#title' => t('Subject'),
        '#description' => t('Enter the subject of your email'),
        '#default_value' => 'Subject',
        '#size' => 30
    );
    $form['email_solicitors_message'] = array(
        '#type' => 'textarea',
        '#title' => t('Message'),
        '#description' => t('Write your message here. Please note that we will automatically add "Dear #name", which will be personalised to the solicitor.'),
        '#default_value' => '',
    );
    $form['email_solicitors_submit'] = array(
        '#type' => 'submit',
        '#title' => t('Submit'),
        '#description' => t('Sumbit this form.'),
        '#default_value' => 'Submit',
    );
    return $form;
}//function email_solicitors_compose

function email_solicitors_compose_submit($form_state)
{
    $batch = array(
        'title' => t('Sending emails to solicitors'),
        'operations' => array(
            array('email_solicitors_batch_iteration', array())
        ),
        'finished' => 'email_solicitors_batch_finished', //run this when we're finished
        'init_message' => t('Preparing to send emails'), //initialisation message
        'progress_message' => t('Sent @current out of @total messages.'),
        'error_message' => t('Sorry, something went wrong when sending emails.'),
    );// create batch array
    $info=print_r($batch,TRUE);
    drupal_set_message($info);
    batch_set($batch);
    batch_process();
}//function email_solicitors_compose_submit

function email_solicitors_batch_iteration(&$context)
{
    // Initialize sandbox the first time through.
    if (!isset($context['sandbox']['progress'])) {
        $context['sandbox']['progress'] = 0;
        $context['sandbox']['current_user_id'] = 0;
        $context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT field_solicitor_email_value) FROM content_type_solicitor'));
    }
    $comment="On item ".$context['sandbox']['progress'];
    drupal_set_message ($comment);
}//function email_solicitors_batch_iteration

function email_solicitors_batch_finished (&$context)
{
    die ('woohoo we finished');
}

Body:
Are you having a start of sign that the batch is beginning or just nothing happens?
You are missing two information in your batch operation callback: the increase of the progress and most importantly a statement to determine when the batch should over.

  // Update our progress information.
  $context['sandbox']['progress']++;
  $context['sandbox']['current_node'] = $row['nid'];
  $context['message'] = t('Calcul des votes pour %node', array('%node' => $row['title']));

  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }


问:
mat snackbar unit test message is null
i have a custom service that uses matSnackbar to show the alerts, and a custom matSnackbar component to use as template for snackBar.
i wrote a unit test for it and want to test the showing my message in it:

```<code>fit('should show my alert message',  () => {
    service.openSnackBarFromComponent('lia lia');
    expect(element.querySelector('.message-container span').innerText).toBe('lia lia');
  });
</code>```

i see in browser that it shows my message "lia lia" but in the test above content of the .message-container span in null. my qusetion is why it shows null and or any another way to test my message?

答:
Following my comment, fixture.detectChanges should resolve your issue.

As for unit testing : as you must have guessed, unit testing means testing a unit.

A unit is a piece of code

that you wrote yourself

that is defined in a given scope (function, class)

that has dependencies (injection, parameters ...)

When you test that unit, you have several steps to respect

Mock the dependencies

Isolate the unit

Test the side effects

The purpose of unit testing is to prevent side effects from modifications.

For instance, you have a component that simply colors a button in green if the HTTP answer is 200.

The unit test purpose is to ensure that the color becomes green if the answer is 200.

This means that if you don't receive 200, the colour should not change, and if you receive 200, the colour should be green only.

Applied to your case, the purpose of your test would be to ensure that the snacker is called with your custom component.

It's not your purpose to test the snackar works. The snackbar is a unit itself, and one you did not code : the unit testing of the snackbar is tested by the Angular Material unit tests, not you.

In fine, your test isn't wrong : it's just a duplicate of another test, so it's "useless" in the sense that it has already been tested.

If you continue to test like that, you will spend 3, 4 times the time you would have spent testing, which isn't productive in the end.

ContentLicense: CC BY-SA 4.0

Title: mat snackbar unit test message is null

Body:
i have a custom service that uses matSnackbar to show the alerts, and a custom matSnackbar component to use as template for snackBar.
i wrote a unit test for it and want to test the showing my message in it:

fit('should show my alert message',  () => {
    service.openSnackBarFromComponent('lia lia');
    expect(element.querySelector('.message-container span').innerText).toBe('lia lia');
  });

i see in browser that it shows my message "lia lia" but in the test above content of the .message-container span in null. my qusetion is why it shows null and or any another way to test my message?


问:
Django query if field has chosen
I have 2 models : ServiceRequest and Quote like this:

```<code>class ServiceRequest(models.Model):
   post_time = models.DateTimeField(default=timezone.now)

class Quote(models.Model):
   service_request = models.ForeignKey(ServiceRequest, on_delete=models.CASCADE)
   status = models.BooleanField(default=False)
</code>```

My question is: how to get queryset from ServiceRequest can know one of Quote has status is True ?

Example : ServiceRequest id = 1 , have 2 Quote. One status is True and one is False.
ServiceRequest id = 2 have 2 Quote, both them status is False.

I want id=1 return True, and id=2 return False

Thank you

答:
I think you can try like this(using related_name):

```<code>class ServiceRequest(models.Model):
   post_time = models.DateTimeField(default=timezone.now)

   def current_quote_status(self):
      return self.quotes.filter(status=True).exists()

class Quote(models.Model):
   service_request = models.ForeignKey(ServiceRequest, on_delete=models.CASCADE, <b>related_name='quotes'</b>)
   status = models.BooleanField(default=False)

# Usage
ServiceRequest.objects.filter(<b>quotes__status</b>=True)

from django.db.models import F

ServiceRequest.objects.annotate(<b>quote_status=F('quotes__status')</b>).values(<b>'pk', 'quote_status'</b>)
# Output
# [{'pk': 1, 'quote_status': True}, {'pk': 1, 'quote_status': False}, {'pk': 2, 'quote_status': False}]]
</code>```

Update

From comments, its better to have a property method to show the quote status:

```<code>class ServiceRequest(models.Model):
   post_time = models.DateTimeField(default=timezone.now)

   @property
   def current_quote_status(self):
      return self.quotes.filter(status=True).exists()

# Usage

services = ServiceRequest.objects.all()
for s in services:
    print(s.current_quote_status)

</code>```

Update 2

Using Subquery and OuterRef:

```<code>from django.db.models import Subquery, Outerref

quotes = Quote.objects.filter(service_request=OuterRef('pk')).order_by('status')
services = ServiceRequest.objects.annotate(quote_status = Subquery(quotes.values('status')[:1]))
services.values('pk', 'quote_status')
</code>```

Title: Django query if field has chosen

Body:
I have 2 models : ServiceRequest and Quote like this:

class ServiceRequest(models.Model):
   post_time = models.DateTimeField(default=timezone.now)

class Quote(models.Model):
   service_request = models.ForeignKey(ServiceRequest, on_delete=models.CASCADE)
   status = models.BooleanField(default=False)

My question is: how to get queryset from ServiceRequest can know one of Quote has status is True ?

Example : ServiceRequest id = 1 , have 2 Quote. One status is True and one is False.
ServiceRequest id = 2 have 2 Quote, both them status is False.

I want id=1 return True, and id=2 return False

Thank you

Body:
I think you can try like this(using related_name):

class ServiceRequest(models.Model):
   post_time = models.DateTimeField(default=timezone.now)

   def current_quote_status(self):
      return self.quotes.filter(status=True).exists()

class Quote(models.Model):
   service_request = models.ForeignKey(ServiceRequest, on_delete=models.CASCADE, related_name='quotes')
   status = models.BooleanField(default=False)

# Usage
ServiceRequest.objects.filter(quotes__status=True)

from django.db.models import F

ServiceRequest.objects.annotate(quote_status=F('quotes__status')).values('pk', 'quote_status')
# Output
# [{'pk': 1, 'quote_status': True}, {'pk': 1, 'quote_status': False}, {'pk': 2, 'quote_status': False}]]

Update

From comments, its better to have a property method to show the quote status:

class ServiceRequest(models.Model):
   post_time = models.DateTimeField(default=timezone.now)

   @property
   def current_quote_status(self):
      return self.quotes.filter(status=True).exists()

# Usage

services = ServiceRequest.objects.all()
for s in services:
    print(s.current_quote_status)

Update 2

Using Subquery and OuterRef:

from django.db.models import Subquery, Outerref

quotes = Quote.objects.filter(service_request=OuterRef('pk')).order_by('status')
services = ServiceRequest.objects.annotate(quote_status = Subquery(quotes.values('status')[:1]))
services.values('pk', 'quote_status')


问:
How to insert/update JSON data into postgreSQL
This is my table schema,

```<code>[column] [type]
tablename json
word  varchar
text  json
</code>```

I implemented using psycopg2 with Python,

```<code>cur.execute("INSERT INTO json (word,text) VALUES (%s,%s);",(word,text))
</code>```

word contains list object type but inside are string,

```<code>['a','b','c']
</code>```

text contains list object type but inside is dict (json),

```<code>[{'a':'b'},{'c':'d'}]
</code>```

When I run the function. I got this error wanring below,

```<code>" can't adapt type 'dict' "
</code>```

The question is, How to insert json into postgreSQL, As you see type of text. It's look like dict, But how to assign text variable is json?. or I'm missing something?

答:
Well,you use execute function to execute a SQL, just construct the right SQL, it would get success.You want insert a json type data, just use "::" to transform a string type into a json type, like below, it works:

```<code>postgres=# insert into json_test(word,text) values('abcd_word','[{"a":"b"},{"c":"d"}]'::json);
INSERT 0 1
postgres=#
postgres=# select * from json_test ;
 tablename |   word    |         text
-----------+-----------+-----------------------
           | abcd_word | [{"a":"b"},{"c":"d"}]
</code>```

Body:
This is my table schema,

[column] [type]
tablename json
word  varchar
text  json

I implemented using psycopg2 with Python,

cur.execute("INSERT INTO json (word,text) VALUES (%s,%s);",(word,text))

word contains list object type but inside are string,

['a','b','c']

text contains list object type but inside is dict (json),

[{'a':'b'},{'c':'d'}]

When I run the function. I got this error wanring below,

" can't adapt type 'dict' "

The question is, How to insert json into postgreSQL, As you see type of text. It's look like dict, But how to assign text variable is json?. or I'm missing something?

Body:
Well,you use execute function to execute a SQL, just construct the right SQL, it would get success.You want insert a json type data, just use "::" to transform a string type into a json type, like below, it works:

postgres=# insert into json_test(word,text) values('abcd_word','[{"a":"b"},{"c":"d"}]'::json);
INSERT 0 1
postgres=#
postgres=# select * from json_test ;
 tablename |   word    |         text
-----------+-----------+-----------------------
           | abcd_word | [{"a":"b"},{"c":"d"}]


问:
NHibernate Multiquery for eager loading without joins
Is it possible to use a multiquery and have two hql queries returning two different sets of entities where one of the sets are used in the other and that the session "fixes" this via the first level cache?

E.g. scenario (a dumb one and it could be solved with joins)

```<code>public class Room
{
  ...
  public virtual ISet<Bookings> Bookings {get;set;}
  public virtual bool IsAvailible {get;set;}
  ...
}

public class Booking
{
  ...
}
</code>```

After executing a multicriteria with two hql's:

returning all rooms where
IsAvailible = true

returning all bookings having a room that has a room that IsAvailible

when accessing a room from the result and its bookings I want them to be resolved from the second resultset via the firstlevel cache of the session and there by avoiding n+1.

答:
Generally speaking, NHibernate can use the cache to "combine" the results from queries executed through Multiquery. However, it should be noted that this usually only applies to cases where lazy collections are loaded with no restrictions whatsoever.

Examples:

```<code>Invoice iAlias = null;
InvoiceDetails idAlias = null;

// Base-Query: get Invoices with certain condition
var invoices = session.QueryOver<Invoice>()
    .Where(i => i.Number == "001")
    .Future<Invoice>();

// Option 1: this will still cause N+1 if we iterate through invoices,
// because it doesn't know better
var invoicedetails = session.QueryOver<InvoiceDetails>()
    .JoinAlias(a => a.Invoice, () => iAlias)
    .Where(() => iAlias.Number == "001")
    .Future<InvoiceDetails>();

// Option 2: this will still cause N+1 if we iterate through invoices,
// because we limited the possible results using a where-condition
var invoices2 = session.QueryOver<Invoice>()
    .Left.JoinAlias(i => i.Details, () => idAlias)
    .Where(i => i.Number == "001")
    .And(() => idAlias.Quantity > 5)
    .Future<Invoice>();

// Option 3: this will work without N+1, because we don't use a filter
// -> NHibernate will use the collection in cache
var invoices3 = session.QueryOver<Invoice>()
    .Left.JoinAlias(i => i.Details, () => idAlias)
    .Where(i => i.Number == "001")
    .Future<Invoice>();

foreach (Invoice i in invoices)
{
    int count = i.Details.Count;
}
</code>```

If we comment out two of the three options and execute the code, we will see that only option 3 will prevent a N+1, the other two will still load the InvoiceDetails for each Invoice in the loop.

Of course this is a very simple example and it is obvious that Option 3 could also be executed without the Base-query and still return the same result, but I hope you get the idea.

In the case where we load two different sets of entities, i.e. the root class is different as in Option 1, this "combining" will most likely not work.

Sorry, if I used QueryOver instead of HQL, but the same rules apply.

Body:
Is it possible to use a multiquery and have two hql queries returning two different sets of entities where one of the sets are used in the other and that the session "fixes" this via the first level cache?

E.g. scenario (a dumb one and it could be solved with joins)

public class Room
{
  ...
  public virtual ISet<Bookings> Bookings {get;set;}
  public virtual bool IsAvailible {get;set;}
  ...
}

public class Booking
{
  ...
}

After executing a multicriteria with two hql's:

returning all rooms where
IsAvailible = true

returning all bookings having a room that has a room that IsAvailible

when accessing a room from the result and its bookings I want them to be resolved from the second resultset via the firstlevel cache of the session and there by avoiding n+1.

Body:
Generally speaking, NHibernate can use the cache to "combine" the results from queries executed through Multiquery. However, it should be noted that this usually only applies to cases where lazy collections are loaded with no restrictions whatsoever.

Examples:

Invoice iAlias = null;
InvoiceDetails idAlias = null;

// Base-Query: get Invoices with certain condition
var invoices = session.QueryOver<Invoice>()
    .Where(i => i.Number == "001")
    .Future<Invoice>();

// Option 1: this will still cause N+1 if we iterate through invoices,
// because it doesn't know better
var invoicedetails = session.QueryOver<InvoiceDetails>()
    .JoinAlias(a => a.Invoice, () => iAlias)
    .Where(() => iAlias.Number == "001")
    .Future<InvoiceDetails>();

// Option 2: this will still cause N+1 if we iterate through invoices,
// because we limited the possible results using a where-condition
var invoices2 = session.QueryOver<Invoice>()
    .Left.JoinAlias(i => i.Details, () => idAlias)
    .Where(i => i.Number == "001")
    .And(() => idAlias.Quantity > 5)
    .Future<Invoice>();

// Option 3: this will work without N+1, because we don't use a filter
// -> NHibernate will use the collection in cache
var invoices3 = session.QueryOver<Invoice>()
    .Left.JoinAlias(i => i.Details, () => idAlias)
    .Where(i => i.Number == "001")
    .Future<Invoice>();

foreach (Invoice i in invoices)
{
    int count = i.Details.Count;
}

If we comment out two of the three options and execute the code, we will see that only option 3 will prevent a N+1, the other two will still load the InvoiceDetails for each Invoice in the loop.

Of course this is a very simple example and it is obvious that Option 3 could also be executed without the Base-query and still return the same result, but I hope you get the idea.

In the case where we load two different sets of entities, i.e. the root class is different as in Option 1, this "combining" will most likely not work.

Sorry, if I used QueryOver instead of HQL, but the same rules apply.


问:
TestNG @BeforeClass initialization code not running before Test
I am writing test codes with Selenium, TestNG. I am trying to set some elements on the @BeforeClass section as I am repeating those actions on the same page. But I am getting null pointer exception. Is there a way to fix this issue?

```<code>public class RunTest {
private static WebElement user;
private static WebElement pass;
private static WebElement login;

@BeforeClass
public static void driveraBaglan() {
    //Driver is declared here. I removed it to give the simple code.
    user = driver.findElement(By.id("user"));
    pass = driver.findElement(By.id("pass"));
    login = driver.findElement(By.xpath("//button[contains(.,'Log In')]"));
    statusMessage = driver.findElement(By.id("login-status-message")).getText();

}
@Test(priority=1)
public void loginNoInfo() {
        user.clear();
        pass.clear();
}
</code>```

I get the null pointer error on user.clear() , pass.clear() and login.click() functions. All tests on the page runs on the same page. I don't want to use repeated "find element by id" tags on each test on the page.

答:
I got this same issue by an accidental change I've done.

You may also get the null pointer exception on objects you are initializing in @BeforeClass or @BeforeTest, when you have a dilemma situation as below (where the class is set to as a disabled test class while having enabled test methods).

```<code>@Test(enabled=false)
public class TestClass{
    A a;

    @BeforeClass
    public void doBeforeClass(){
      a=new A();
      //
    }

    @Test
    public void test1(){
       a.callMethod1();
    }

    @Test
    public void test2(){
       a.callMethod2();
    }

}
</code>```

Here, when you are running full-suite by putting @Test(enabled=false) only for the class, still the suite will run individual tests in the class since @Test annotations are present there. However, since @BeforeClass is not running for whole class, object 'a' is not initialized and will cause null pointer exceptions.

In such cases, the individual @Test annotations too need to be changed to @Test(enabled=false)

Body:
I am writing test codes with Selenium, TestNG. I am trying to set some elements on the @BeforeClass section as I am repeating those actions on the same page. But I am getting null pointer exception. Is there a way to fix this issue?

public class RunTest {
private static WebElement user;
private static WebElement pass;
private static WebElement login;

@BeforeClass
public static void driveraBaglan() {
    //Driver is declared here. I removed it to give the simple code.
    user = driver.findElement(By.id("user"));
    pass = driver.findElement(By.id("pass"));
    login = driver.findElement(By.xpath("//button[contains(.,'Log In')]"));
    statusMessage = driver.findElement(By.id("login-status-message")).getText();

}
@Test(priority=1)
public void loginNoInfo() {
        user.clear();
        pass.clear();
}

I get the null pointer error on user.clear() , pass.clear() and login.click() functions. All tests on the page runs on the same page. I don't want to use repeated "find element by id" tags on each test on the page.

Body:
I got this same issue by an accidental change I've done.

You may also get the null pointer exception on objects you are initializing in @BeforeClass or @BeforeTest, when you have a dilemma situation as below (where the class is set to as a disabled test class while having enabled test methods).

@Test(enabled=false)
public class TestClass{
    A a;

    @BeforeClass
    public void doBeforeClass(){
      a=new A();
      //
    }

    @Test
    public void test1(){
       a.callMethod1();
    }

    @Test
    public void test2(){
       a.callMethod2();
    }

}

Here, when you are running full-suite by putting @Test(enabled=false) only for the class, still the suite will run individual tests in the class since @Test annotations are present there. However, since @BeforeClass is not running for whole class, object 'a' is not initialized and will cause null pointer exceptions.

In such cases, the individual @Test annotations too need to be changed to @Test(enabled=false)


问:
How to fix Execution failed for task ':app:mergeDebugResources'
I updated to Android 3.4 and I'm Working on a TO-DO app and when I wanna run it but it is giving me this error:

```<code>Executing tasks: [:app:assembleDebug]

> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:compileDebugAidl NO-SOURCE
> Task :app:compileDebugRenderscript NO-SOURCE
> Task :app:checkDebugManifest UP-TO-DATE
> Task :app:generateDebugBuildConfig UP-TO-DATE
> Task :app:prepareLintJar UP-TO-DATE
> Task :app:generateDebugSources UP-TO-DATE
> Task :app:javaPreCompileDebug UP-TO-DATE
> Task :app:mainApkListPersistenceDebug UP-TO-DATE
> Task :app:generateDebugResValues UP-TO-DATE
> Task :app:generateDebugResources UP-TO-DATE
> Task :app:mergeDebugResources FAILED

Execution failed for task ':app:mergeDebugResources'
>1 exception was raised by workers:
  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Users\CHARAN\Desktop\Android Development\BPTODO\app\src\main\res\drawable-v24\ic_launcher_foreground.xml:11: error: not well-formed (invalid token).
  C:\Users\CHARAN\Desktop\Android Development\BPTODO\app\src\main\res\drawable-v24\ic_launcher_foreground.xml: error: file failed to compile.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 35s
8 actionable tasks: 1 executed, 7 up-to-date

</code>```

I tried
1. clean and rebuild
2. invalidate caches and Restart
3. changing gradle dependencies
and this what android studio suggested
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
And even tried this

Gradle(project)

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

</code>```

Gradle(app)

```<code>
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.bptodo"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}
</code>```

Activity_main.xml

```<code><LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F4F4F4"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:background="#1eea40"
        android:layout_height="198dp">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_marginLeft="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/titlepage"
                    android:layout_marginTop="20dp"
                    android:textSize="32sp"
                    android:textColor="#FFF"
                    android:text="TO DO's"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

                <TextView
                    android:id="@+id/subtitlepage"
                    android:textSize="18sp"
                    android:textColor="#4A4E6A"
                    android:layout_marginTop="8dp"
                    android:text="Finish Them Quickly Today"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            </LinearLayout>

            <Button
                android:id="@+id/btnAddNew"
                android:layout_width="99dp"
                android:layout_height="52dp"
                android:layout_marginLeft="60dp"
                android:layout_marginTop="35dp"
                android:background="@drawable/bgbtnnew"
                android:text="+"
                android:textAlignment="center"
                android:textColor="#FFF"
                android:textSize="38sp" />

        </LinearLayout>

        <View
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:background="#131E69"
            android:layout_height="1dp" />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/ourdoes"
        android:layout_width="match_parent"
        android:layout_marginTop="-60dp"
        android:layout_marginRight="16dp"
        android:layout_marginLeft="16dp"
        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

    <TextView
        android:id="@+id/endpage"
        android:textSize="16sp"
        android:textColor="#9A9A9A"
        android:layout_marginTop="20dp"
        android:text="No More Does"
        android:textAlignment="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

“I expect the output of smooth run, Please Help"
Thanks in advance

答:
Build > Clean Project

Or

```<code>./gradlew clean build
</code>```

Or

In the individual apps's build.gradle section android {}, insert :

```<code>aaptOptions {
    cruncherEnabled = false
}
</code>```

Body:
I updated to Android 3.4 and I'm Working on a TO-DO app and when I wanna run it but it is giving me this error:

Executing tasks: [:app:assembleDebug]

> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:compileDebugAidl NO-SOURCE
> Task :app:compileDebugRenderscript NO-SOURCE
> Task :app:checkDebugManifest UP-TO-DATE
> Task :app:generateDebugBuildConfig UP-TO-DATE
> Task :app:prepareLintJar UP-TO-DATE
> Task :app:generateDebugSources UP-TO-DATE
> Task :app:javaPreCompileDebug UP-TO-DATE
> Task :app:mainApkListPersistenceDebug UP-TO-DATE
> Task :app:generateDebugResValues UP-TO-DATE
> Task :app:generateDebugResources UP-TO-DATE
> Task :app:mergeDebugResources FAILED

Execution failed for task ':app:mergeDebugResources'
>1 exception was raised by workers:
  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Users\CHARAN\Desktop\Android Development\BPTODO\app\src\main\res\drawable-v24\ic_launcher_foreground.xml:11: error: not well-formed (invalid token).
  C:\Users\CHARAN\Desktop\Android Development\BPTODO\app\src\main\res\drawable-v24\ic_launcher_foreground.xml: error: file failed to compile.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 35s
8 actionable tasks: 1 executed, 7 up-to-date

I tried
1. clean and rebuild
2. invalidate caches and Restart
3. changing gradle dependencies
and this what android studio suggested
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
And even tried this

Gradle(project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Gradle(app)

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.bptodo"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}

Activity_main.xml

<LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F4F4F4"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:background="#1eea40"
        android:layout_height="198dp">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_marginLeft="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/titlepage"
                    android:layout_marginTop="20dp"
                    android:textSize="32sp"
                    android:textColor="#FFF"
                    android:text="TO DO's"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

                <TextView
                    android:id="@+id/subtitlepage"
                    android:textSize="18sp"
                    android:textColor="#4A4E6A"
                    android:layout_marginTop="8dp"
                    android:text="Finish Them Quickly Today"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            </LinearLayout>

            <Button
                android:id="@+id/btnAddNew"
                android:layout_width="99dp"
                android:layout_height="52dp"
                android:layout_marginLeft="60dp"
                android:layout_marginTop="35dp"
                android:background="@drawable/bgbtnnew"
                android:text="+"
                android:textAlignment="center"
                android:textColor="#FFF"
                android:textSize="38sp" />

        </LinearLayout>

        <View
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:background="#131E69"
            android:layout_height="1dp" />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/ourdoes"
        android:layout_width="match_parent"
        android:layout_marginTop="-60dp"
        android:layout_marginRight="16dp"
        android:layout_marginLeft="16dp"
        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

    <TextView
        android:id="@+id/endpage"
        android:textSize="16sp"
        android:textColor="#9A9A9A"
        android:layout_marginTop="20dp"
        android:text="No More Does"
        android:textAlignment="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

“I expect the output of smooth run, Please Help"
Thanks in advance

Body:
Build > Clean Project

Or

./gradlew clean build

Or

In the individual apps's build.gradle section android {}, insert :

aaptOptions {
    cruncherEnabled = false
}


问:
golang unexpected directory layout
So I downloaded minio from github.com/minio/minio

I want to run it from the source,

I create my directory like:

```<code>~/Downloads/minio-RELEASE.2017-06-13T19-01-01Z
|
 src
   |
    all minio directories, including vendor, like the image below
</code>```

I also use godep resolve other dependencies under GOPATH.

Now I run it from Gogland(go IDE)

It shows:

```<code>GOROOT=/usr/local/Cellar/go/1.8.3/libexec
GOPATH=/Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z:/Users/xl/go
/usr/local/Cellar/go/1.8.3/libexec/bin/go build -i -o /private/var/folders/8v/6dg7d6mx2850sv1gp8ts9thm0000gn/T/go_run_main_gogo /Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z/src/main.go
unexpected directory layout:
    import path: github.com/Azure/azure-sdk-for-go/storage
    root: /Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z/src
    dir: /Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z/src/vendor/github.com/Azure/azure-sdk-for-go/storage
    expand root: /Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z/src
    expand dir: /Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z/src/vendor/github.com/Azure/azure-sdk-for-go/storage
    separator: /
</code>```

Now I am confused that, what's the problem? The files are all there and the directories are just like what's it's printing. How do I fix it? Thanks.

答: This can happen if you have duplicate repos under goroot AND gopath. Delete the goroot one.</p>

Title: golang unexpected directory layout

Body:
So I downloaded minio from github.com/minio/minio

I want to run it from the source,

I create my directory like:

~/Downloads/minio-RELEASE.2017-06-13T19-01-01Z
|
 src
   |
    all minio directories, including vendor, like the image below

I also use godep resolve other dependencies under GOPATH.

Now I run it from Gogland(go IDE)

It shows:

GOROOT=/usr/local/Cellar/go/1.8.3/libexec
GOPATH=/Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z:/Users/xl/go
/usr/local/Cellar/go/1.8.3/libexec/bin/go build -i -o /private/var/folders/8v/6dg7d6mx2850sv1gp8ts9thm0000gn/T/go_run_main_gogo /Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z/src/main.go
unexpected directory layout:
    import path: github.com/Azure/azure-sdk-for-go/storage
    root: /Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z/src
    dir: /Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z/src/vendor/github.com/Azure/azure-sdk-for-go/storage
    expand root: /Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z/src
    expand dir: /Users/xl/Downloads/minio-RELEASE.2017-06-13T19-01-01Z/src/vendor/github.com/Azure/azure-sdk-for-go/storage
    separator: /

Now I am confused that, what's the problem? The files are all there and the directories are just like what's it's printing. How do I fix it? Thanks.


问:
how secure is the Ticket.UserData in User.Identity in asp.net
My website uses ASP.NET's forms authentication and i am inserting user specific information into the UserData portion of the authentication ticket/cookie. Since the UserData is inside the authentication ticket it is encrypted like so

```<code>authCookie.Value = FormsAuthentication.Encrypt(newTicket);
</code>```

Now I am not too worried about the data being compromised at this point since it's encrypted. but i noticed that the data is available in unencrypted form like this

```<code>FormsIdentity fid = User.Identity as FormsIdentity;
string plainTextUserData = fid.Ticket.UserData;
</code>```

The data itself is not too important. i am still ok even if other people can see it. but i cannot allow people to hijack this information and start using it as their own. for example, i don't want one user to be logged in pretending to be a different user (based on the userID contained in UserData

Is this something I have to worry about?

Edit 1:

The reason i want to do this is so i can stop using sessions and just use cookies and Ticket.UserData

Edit 2:

The data in Ticket.UserData is not changing. it's constant once the user is logged in.

答:
You probably don't need to worry.

If the data is sensitive (for example, Social Security Number in the United States), then you should probably avoid sending it with the FormsAuth ticket, even though it is encrypted, because evil-doers are always conjuring up new attacks.

However, I have to ask: you already get to store an identifier with each ticket (username), so why wouldn't you keep all other data in the database?

ContentLicense: CC BY-SA 2.5

Body:
My website uses ASP.NET's forms authentication and i am inserting user specific information into the UserData portion of the authentication ticket/cookie. Since the UserData is inside the authentication ticket it is encrypted like so

authCookie.Value = FormsAuthentication.Encrypt(newTicket);

Now I am not too worried about the data being compromised at this point since it's encrypted. but i noticed that the data is available in unencrypted form like this

FormsIdentity fid = User.Identity as FormsIdentity;
string plainTextUserData = fid.Ticket.UserData;

The data itself is not too important. i am still ok even if other people can see it. but i cannot allow people to hijack this information and start using it as their own. for example, i don't want one user to be logged in pretending to be a different user (based on the userID contained in UserData

Is this something I have to worry about?

Edit 1:

The reason i want to do this is so i can stop using sessions and just use cookies and Ticket.UserData

Edit 2:

The data in Ticket.UserData is not changing. it's constant once the user is logged in.

LastEditorDisplayName: Rich B

OwnerDisplayName: Portman


问:
Best way to design soundex based search
I have a table of forum posts, and want to improve the basic search functionality as we get a lot of users from all over the world who are not native English speakers and will have trouble finding results when they spell incorrectly.  The current forum search is exact.

Which of these designs will perform best?  Assume the database has 500,000 records and the search is used frequently.  Ideally I would like it to search every record.

Design One

Along side each forum post, I store soundex_post, which contains all the soundex data.  When a search is run, it soundexes all search terms, and does a LIKE operation on the soundex fields.

Design Two

I normalise it.  Every soundex code is stored in a new table, tblSoundexCodes.  Then there is a table tblForumPostSoundexCodes:

ID | Post_ID | SoundexCode_ID | Count

Then when a soundex is searched for, I simply pull out all the Post_IDs where SoundexCode_ID = n

Am I correct that method two will be considerably faster, but that it will be a lot harder to maintain (IE, when people edit posts).

答:
Design Two is better.

Design two won't be faster.  The data storage will be more compact, and you will have to update or insert a row into tblForumPostSoundexCodes, as well as insert a row into tblSoundexCodes, when someone writes or updates a post.

You'll have to verify that this soundex transaction processing takes place for every change to a post (create, update, delete).

Title: Best way to design soundex based search


问:
How to efficiently syntax
I wrote some code. I realized when I wanted to expand the code below, it would make the syntax wasteful.
how to make it efficient?</p>

```<code>a = ['a', 'b', 'c', 'd', 'e']
b = int(input("Number of digit:\n"))
#This is for 1 digit printed
if b == 1:
   for i in a:
        print(i)
#This is for 2 digit printed
elif b == 2:
    for i in a:
        for j in a:
           print(i,j)

#This is for 3 digit printed
    elif b == 2:
        for i in a:
            for j in a:
                for k in a:
                   print(i,j,k)
</code>```

答:
You can use itertools to generalize this for any b as follows:

```<code>import itertools

a = ['a', 'b', 'c', 'd', 'e']
b = int(input("Number of digit:\n"))

for t in itertools.product(a, repeat=b):
    print(*t)
</code>```

If you instead want to save the tuples in a list, you can do:

```<code>vals = list(itertools.product(a, repeat=b))
</code>```

Title: How to efficiently syntax

Body:
I wrote some code. I realized when I wanted to expand the code below, it would make the syntax wasteful.
how to make it efficient?

a = ['a', 'b', 'c', 'd', 'e']
b = int(input("Number of digit:\n"))
#This is for 1 digit printed
if b == 1:
   for i in a:
        print(i)
#This is for 2 digit printed
elif b == 2:
    for i in a:
        for j in a:
           print(i,j)

#This is for 3 digit printed
    elif b == 2:
        for i in a:
            for j in a:
                for k in a:
                   print(i,j,k)

Body:
You can use itertools to generalize this for any b as follows:

import itertools

a = ['a', 'b', 'c', 'd', 'e']
b = int(input("Number of digit:\n"))

for t in itertools.product(a, repeat=b):
    print(*t)

If you instead want to save the tuples in a list, you can do:

vals = list(itertools.product(a, repeat=b))


问:
A simple pivot but can't get my head around it - please assist..:-)
I try to do a simple pivot in MS SSMS, but can't figure it out.

This is my data set:

```<code>Date        CallerANI      Skills               CallerDNIS
2019-05-27  27315391449    loc-SPD-CSR-OverFlow 47515070001
2019-05-27  27315391449    cc-Loc-Voice         Transfer
</code>```

and statement:

```<code>SELECT [Date],
       CallerANI,
       [47515001101],
       [Transfer]
FROM (SELECT [Date], Skills, CallerANI, CallerDNIS FROM #TempDB) AS p
PIVOT (MAX(Skills)
       FOR CallerDNIS IN ([47515001101], [Transfer])) AS pvt;
</code>```

I want to pivot so that the result looks like this:

```<code>Date            CallerANI              [47515070001]            [Transfer]
2019-05-27      273135391449           loc-SPD-CSR-OverFlow     cc-loc-Voice
</code>```

答:
Personally, I prefer to use a Cross Tab over the inbuilt PIVOT function. I find it far easier to use:

```<code>SELECT [Date],
       CallerANI,
       MAX(CASE WHEN V.CallerDNIS = '47515070001' THEN Skills END) AS [47515070001],
       MAX(CASE WHEN V.CallerDNIS = 'Transfer' THEN Skills END) AS [Transfer]
FROM (VALUES (CONVERT(date,'20190527'),27315391449,'loc-SPD-CSR-OverFlow','47515070001'),
             (CONVERT(date,'20190527'),27315391449,'cc-Loc-Voice','Transfer')) V([Date],CallerANI,Skills,CallerDNIS)
GROUP BY [Date],
         CallerANI;
</code>```

Body:
I try to do a simple pivot in MS SSMS, but can't figure it out.

This is my data set:

Date        CallerANI      Skills               CallerDNIS
2019-05-27  27315391449    loc-SPD-CSR-OverFlow 47515070001
2019-05-27  27315391449    cc-Loc-Voice         Transfer

and statement:

SELECT [Date],
       CallerANI,
       [47515001101],
       [Transfer]
FROM (SELECT [Date], Skills, CallerANI, CallerDNIS FROM #TempDB) AS p
PIVOT (MAX(Skills)
       FOR CallerDNIS IN ([47515001101], [Transfer])) AS pvt;

I want to pivot so that the result looks like this:

Date            CallerANI              [47515070001]            [Transfer]
2019-05-27      273135391449           loc-SPD-CSR-OverFlow     cc-loc-Voice

Body:
Personally, I prefer to use a Cross Tab over the inbuilt PIVOT function. I find it far easier to use:

SELECT [Date],
       CallerANI,
       MAX(CASE WHEN V.CallerDNIS = '47515070001' THEN Skills END) AS [47515070001],
       MAX(CASE WHEN V.CallerDNIS = 'Transfer' THEN Skills END) AS [Transfer]
FROM (VALUES (CONVERT(date,'20190527'),27315391449,'loc-SPD-CSR-OverFlow','47515070001'),
             (CONVERT(date,'20190527'),27315391449,'cc-Loc-Voice','Transfer')) V([Date],CallerANI,Skills,CallerDNIS)
GROUP BY [Date],
         CallerANI;


问:
Definition mx.binding.utils.BindingUtils could not be found similar couple of imports not loading
I got chance to migrate Flex application to Apache Royale, able to run helloworld applications. started migrating Application, getting couple of exceptions. bellow is the one.

we are using the

```<code>AdobeSpelling.swc
AlivePDF.swc
Cairngorm.swc
flexmdi.swc
FlexUnit.swc
spcairngorm.swc
</code>```

these '.swc'  libraries.

how can i import these or is any similar libraries in royale compatible files.
i found asconfig.json file - external-library-path - but i am compiling my application with maven pom.xml.

Please help me, basic migrations

Error Log:

```<code>Warning: Definition com.model.ModelLocator could not be found.
import com.model.ModelLocator;
Warning: Definition com.util.customComponents.CustomMenuBarEvent could
not be found.
import com.util.customComponents.CustomMenuBarEvent;
</code>```

答:
There is two path which you can go in case of migrating.

Emulation Components. However there is a chance that some of
the components wasn't added to emulation so you may get exceptions
and this would be the place where you can add them and make pull
requests to Royale. Those components allows you in best case
successfully build your application without changing drastically UI
part, but you may won't see anything on the screen or it may be
messed, cause there wasn't volunteer who could work on displaying
better them.

Another path is to distinguish your pure ActionScript code (no
dependency to Flash) from UI part - pure AS3 code should ported
without any problem - and rewrite UI from scratch using Basic module
or Jewel

All libraries which you have mention have strong dependencies to Flash, so my recommendation is to find JS replacement for them and use it in your porting. There is also PureMVC which is working pretty good with Royale - it's has been tested in several applications already.

Body:
I got chance to migrate Flex application to Apache Royale, able to run helloworld applications. started migrating Application, getting couple of exceptions. bellow is the one.

we are using the

AdobeSpelling.swc
AlivePDF.swc
Cairngorm.swc
flexmdi.swc
FlexUnit.swc
spcairngorm.swc

these '.swc'  libraries.

how can i import these or is any similar libraries in royale compatible files.
i found asconfig.json file - external-library-path - but i am compiling my application with maven pom.xml.

Please help me, basic migrations

Error Log:

Warning: Definition com.model.ModelLocator could not be found.
import com.model.ModelLocator;
Warning: Definition com.util.customComponents.CustomMenuBarEvent could
not be found.
import com.util.customComponents.CustomMenuBarEvent;


问:
iPhone AVAudioPlayer release EXC_BAD_ACCESS
I play sound making this:

```<code>NSData *data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];
</code>```

In this buffer i have sound with aac format.
Everything is ok, until I want to release it, and sometimes not always i get EXC_BAD_ACCESS

I release it in this way:

```<code>[player release];
free (buffer);
</code>```

I think that player stil wants to do something with this data, but this data not longer exist after I make free (buffer);

But I don't know when make this free (buffer). If i remove this line everything is ok.
But when i remove this free (buffer) i will have memory leaks:(

Best regards
Chudziutki

答:
you can use below line of code,</p>

```<code>NSData *dataToEncode = [NSData dataWithBytesNoCopy:base64buffer length:sizeof(base64buffer) freeWhenDone:YES];
</code>```

Body:
I play sound making this:

NSData *data = [NSData dataWithBytesNoCopy:buffer length:length freeWhenDone:NO];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];

In this buffer i have sound with aac format.
Everything is ok, until I want to release it, and sometimes not always i get EXC_BAD_ACCESS

I release it in this way:

[player release];
free (buffer);

I think that player stil wants to do something with this data, but this data not longer exist after I make free (buffer);

But I don't know when make this free (buffer). If i remove this line everything is ok.
But when i remove this free (buffer) i will have memory leaks:(

Best regards
Chudziutki

Body:
you can use below line of code,

NSData *dataToEncode = [NSData dataWithBytesNoCopy:base64buffer length:sizeof(base64buffer) freeWhenDone:YES];


问:
Is that correct to split the i18n dictionary by translation value instead of business logic?
For example - my application has a different types of entities: person and client.

Application has the dictionary, containing labels and translations for a couple of languages.

```<code>const en = {
  firstName: 'First name',
  lastName: 'Last name',
  address: 'Address'
};

const ru = {
  firstName: 'Имя',
  lastName: 'Фамилия',
  address: 'Адрес'
}

const dictionary = createDictionary({ en, ru });
</code>```

As you can see there is no difference between labels for person or client if they have the same translation.

Should I separate the labels by entity type?

答:
If it's the same word and it translates as the same word, there's no need to differentiate. You probably have many places in your app where you translate the word "Okay" on a button, and you don't need to differentiate every single "Okay" button to end up with 200 separate translations which are all identical.

Having said that, in some languages words do translate differently depending on context, probably especially in the area of people's names, honourifics and pronouns. Therefore it's important that your translators understand the context of the translation. This is a bit hard in the format you chose, but in gettext PO files, this could look something like:

```<code>#: signup-form.html:42 admin/user-details.html:69
msgid "First name"
msgstr "Имя"
</code>```

Now, say, your Japanese translator may come to you and say that "First name" in the context of addressing the user directly, and in the context of an admin view, should really be differentiated for politeness. Again, in PO files you could add context:

```<code>#: signup-form.html:42
msgctxt "Label addressing the user in signup form"
msgid "First name"
msgstr "お客様の名"

#: admin/user-details.html:69
msgctxt "Label for user data in admin view"
msgid "First name"
msgstr "名"
</code>```

Those are now two separate strings that can be translated separately.

So, the important thing here is to have a technical solution to disambiguate if necessary, to provide enough context and awareness to translators, and to have a working feedback mechanism between translators and programmers to add disambiguations where necessary. Programmers shouldn't overzealously disambiguate needlessly, since they often can't anticipate where it's really necessary.

Body:
For example - my application has a different types of entities: person and client.

Application has the dictionary, containing labels and translations for a couple of languages.

const en = {
  firstName: 'First name',
  lastName: 'Last name',
  address: 'Address'
};

const ru = {
  firstName: 'Имя',
  lastName: 'Фамилия',
  address: 'Адрес'
}

const dictionary = createDictionary({ en, ru });

As you can see there is no difference between labels for person or client if they have the same translation.

Should I separate the labels by entity type?

Body:
If it's the same word and it translates as the same word, there's no need to differentiate. You probably have many places in your app where you translate the word "Okay" on a button, and you don't need to differentiate every single "Okay" button to end up with 200 separate translations which are all identical.

Having said that, in some languages words do translate differently depending on context, probably especially in the area of people's names, honourifics and pronouns. Therefore it's important that your translators understand the context of the translation. This is a bit hard in the format you chose, but in gettext PO files, this could look something like:

#: signup-form.html:42 admin/user-details.html:69
msgid "First name"
msgstr "Имя"

Now, say, your Japanese translator may come to you and say that "First name" in the context of addressing the user directly, and in the context of an admin view, should really be differentiated for politeness. Again, in PO files you could add context:

#: signup-form.html:42
msgctxt "Label addressing the user in signup form"
msgid "First name"
msgstr "お客様の名"

#: admin/user-details.html:69
msgctxt "Label for user data in admin view"
msgid "First name"
msgstr "名"

Those are now two separate strings that can be translated separately.

So, the important thing here is to have a technical solution to disambiguate if necessary, to provide enough context and awareness to translators, and to have a working feedback mechanism between translators and programmers to add disambiguations where necessary. Programmers shouldn't overzealously disambiguate needlessly, since they often can't anticipate where it's really necessary.


问:
Gibbs sampling using sklearn package
I'm currently trying to use sklearns package for the bernoulli version of the Restricted Boltzmann Machine [RBM], but I don't understand how it works. The dataset I want to use it on is the MNIST-dataset. The very small amount of code I'm using currently is:

```<code>def rbm():
    #weights = np.zeros((20, 100, 784))
    #for j in range(0, epochs):
    rbm = BernoulliRBM(n_iter= 1, learning_rate = 0.01, n_components = 100, random_state=0, verbose=True)
    rbm.fit(bindigit_trn)
    gibbs(rbm.components_)
    weights = rbm.components_
    return weights
</code>```

The error code I'm getting is: "This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items."

Can someone help a beginner, how do I make this right?

答:
You can try the following with scikit-learn digits dataset:

```<code>from sklearn.neural_network import BernoulliRBM
from sklearn import datasets
import numpy as np
import matplotlib.pylab as plt

def show_digits(im, title):
    plt.figure(figsize=(5,5))
    plt.gray()
    for i in range(im.shape[0]):
        plt.subplot(10,10,i+1)
        plt.imshow(np.reshape(im[i,:], (8,8)))
        plt.axis('off')
    plt.suptitle(title)
    plt.show()

def rbm():
    digits = datasets.load_digits()
    bindigit_trn = np.asarray(digits.data, 'float32')
    for i in range(len(bindigit_trn)):
        bindigit_trn[i,:] = bindigit_trn[i,:] / np.max(bindigit_trn[i,:])
    print(bindigit_trn.shape)
    # (1797, 64) => 1797 8x8 digits images
    digits = bindigit_trn[:100,:]
    print(digits.shape)
    # (100, 64) => 100 images
    show_digits(digits, 'original digits')
    rbm = BernoulliRBM(n_iter= 10, learning_rate = 0.1, n_components = 10, random_state=0, verbose=True)
    rbm.fit(bindigit_trn)
    print(rbm.components_.shape)
    # (10, 64)
    digits_new = digits.copy() # rbm.components_.copy()
    # gibbs sampling here
    for j in range(10000):
        for i in range(100):
            digits_new[i,:] = rbm.gibbs(digits_new[i,:])
    print(digits_new.shape)
    # (100, 64)
    show_digits(digits_new, 'sampled digits')
    weights = rbm.components_
    return weights

weights = rbm()
show_digits(weights, 'weights')
</code>```

```<code>#[BernoulliRBM] Iteration 1, pseudo-likelihood = -25.85, time = 0.02s
#[BernoulliRBM] Iteration 2, pseudo-likelihood = -25.67, time = 0.02s
#[BernoulliRBM] Iteration 3, pseudo-likelihood = -25.45, time = 0.03s
#[BernoulliRBM] Iteration 4, pseudo-likelihood = -24.34, time = 0.02s
#[BernoulliRBM] Iteration 5, pseudo-likelihood = -23.41, time = 0.02s
#[BernoulliRBM] Iteration 6, pseudo-likelihood = -22.33, time = 0.02s
#[BernoulliRBM] Iteration 7, pseudo-likelihood = -21.88, time = 0.02s
#[BernoulliRBM] Iteration 8, pseudo-likelihood = -21.66, time = 0.02s
#[BernoulliRBM] Iteration 9, pseudo-likelihood = -21.74, time = 0.02s
#[BernoulliRBM] Iteration 10, pseudo-likelihood = -21.04, time = 0.02s
</code>```

Title: Gibbs sampling using sklearn package

Body:
I'm currently trying to use sklearns package for the bernoulli version of the Restricted Boltzmann Machine [RBM], but I don't understand how it works. The dataset I want to use it on is the MNIST-dataset. The very small amount of code I'm using currently is:

def rbm():
    #weights = np.zeros((20, 100, 784))
    #for j in range(0, epochs):
    rbm = BernoulliRBM(n_iter= 1, learning_rate = 0.01, n_components = 100, random_state=0, verbose=True)
    rbm.fit(bindigit_trn)
    gibbs(rbm.components_)
    weights = rbm.components_
    return weights

The error code I'm getting is: "This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items."

Can someone help a beginner, how do I make this right?

Body:
You can try the following with scikit-learn digits dataset:

from sklearn.neural_network import BernoulliRBM
from sklearn import datasets
import numpy as np
import matplotlib.pylab as plt

def show_digits(im, title):
    plt.figure(figsize=(5,5))
    plt.gray()
    for i in range(im.shape[0]):
        plt.subplot(10,10,i+1)
        plt.imshow(np.reshape(im[i,:], (8,8)))
        plt.axis('off')
    plt.suptitle(title)
    plt.show()

def rbm():
    digits = datasets.load_digits()
    bindigit_trn = np.asarray(digits.data, 'float32')
    for i in range(len(bindigit_trn)):
        bindigit_trn[i,:] = bindigit_trn[i,:] / np.max(bindigit_trn[i,:])
    print(bindigit_trn.shape)
    # (1797, 64) => 1797 8x8 digits images
    digits = bindigit_trn[:100,:]
    print(digits.shape)
    # (100, 64) => 100 images
    show_digits(digits, 'original digits')
    rbm = BernoulliRBM(n_iter= 10, learning_rate = 0.1, n_components = 10, random_state=0, verbose=True)
    rbm.fit(bindigit_trn)
    print(rbm.components_.shape)
    # (10, 64)
    digits_new = digits.copy() # rbm.components_.copy()
    # gibbs sampling here
    for j in range(10000):
        for i in range(100):
            digits_new[i,:] = rbm.gibbs(digits_new[i,:])
    print(digits_new.shape)
    # (100, 64)
    show_digits(digits_new, 'sampled digits')
    weights = rbm.components_
    return weights

weights = rbm()
show_digits(weights, 'weights')

#[BernoulliRBM] Iteration 1, pseudo-likelihood = -25.85, time = 0.02s
#[BernoulliRBM] Iteration 2, pseudo-likelihood = -25.67, time = 0.02s
#[BernoulliRBM] Iteration 3, pseudo-likelihood = -25.45, time = 0.03s
#[BernoulliRBM] Iteration 4, pseudo-likelihood = -24.34, time = 0.02s
#[BernoulliRBM] Iteration 5, pseudo-likelihood = -23.41, time = 0.02s
#[BernoulliRBM] Iteration 6, pseudo-likelihood = -22.33, time = 0.02s
#[BernoulliRBM] Iteration 7, pseudo-likelihood = -21.88, time = 0.02s
#[BernoulliRBM] Iteration 8, pseudo-likelihood = -21.66, time = 0.02s
#[BernoulliRBM] Iteration 9, pseudo-likelihood = -21.74, time = 0.02s
#[BernoulliRBM] Iteration 10, pseudo-likelihood = -21.04, time = 0.02s


问:
how to check if a file exist and is a text file?
Hi everyone I need to check if a file exist with a shell script. I did some digging and ended up with this syntax but I'm not sure why it isn't working
(please bear in mind that you are talking to beginner)

I've found that you can add -e for example to check if it exist but I didn't get where these shortcuts came form or their names

#! /bin/bash
if [ "$#" = "1" ]
then
    if [ -e $($1) ] && [ -f $($1) ]
        then echo 'the file exists'
    fi

fi
```

答:
```<code>#!/bin/bash
if [ "$#" == 1 ]; then
    if [[ -e "$1" && -f "$1" ]]; then
        echo 'The file exists';
    fi
fi
</code>```

<p>You should put every conditional && between [[ ]] symbols otherwise it will be interpreted as execute if success. </p>

Body:
#!/bin/bash
if [ "$#" == 1 ]; then
    if [[ -e "$1" && -f "$1" ]]; then
        echo 'The file exists';
    fi
fi

You should put every conditional && between [[ ]] symbols otherwise it will be interpreted as execute if success.


问:
How can I get the phone native font size in react native?
I need to get the phone native font size (set in accessibility on ios and screen settings on android). is there a way to get that parameter?

I couldn't find anything online.

I need that because whenever a user changes his phone native font size the font in the app also getting bigger(which is just fine! I want to support that) but the elements that contains it doesn't.
So I need that parameter to handle the container elements.

答: You can use react-native-device-info as it gives you a function getFontScale() for getting device font size in android and ios</p>


答:
```<code>#! /bin/sh

FILE=$1    # get filename from commandline

if [ -f $FILE ]; then
    echo "file $FILE exists"
fi
</code>```

See the fine manual page of test commands, which are built-in in the different shells: man test; man sh; man bash

You will also find many shell primers which explain this very nicely.
Or see bash reference manual: https://www.gnu.org/software/bash/manual/bash.pdf

Title: how to check if a file exist and is a text file?

Body:
Hi everyone I need to check if a file exist with a shell script. I did some digging and ended up with this syntax but I'm not sure why it isn't working
(please bear in mind that you are talking to beginner)

I've found that you can add -e for example to check if it exist but I didn't get where these shortcuts came form or their names

#! /bin/bash
if [ "$#" = "1" ]
then
    if [ -e $($1) ] && [ -f $($1) ]
        then echo 'the file exists'
    fi

fi

Body:
#! /bin/sh

FILE=$1    # get filename from commandline

if [ -f $FILE ]; then
    echo "file $FILE exists"
fi

See the fine manual page of test commands, which are built-in in the different shells: man test; man sh; man bash

You will also find many shell primers which explain this very nicely.
Or see bash reference manual: https://www.gnu.org/software/bash/manual/bash.pdf


问:
Define values for each namespace
values.yaml

```<code>replicas: {
  test: 1,
  stage: 2,
  prod: 3
}
</code>```

Here I am trying to use Helm templates to define number of replicas per namespace but am unsure of the proper syntax and pattern:

deployment.yaml

```<code>replicas: {{ .Values.replicas.{{ .Release.Namespace }} }}
</code>```

So if this were deployed to --namespace=prod, I would expect the template to return:

```<code># .Values.replicas.prod
replicas: 3
</code>```

答:
I don't think that Helm supports evaluating variable in the variable. For this, you're expression would need to be evaluated twice.

What you could do is to write the following code:

```<code>{{ if eq .Release.Namespace "test" }}{{ .Values.replicas.test }}{{ end }}
</code>```

You can then also extract that code to your _helpers.tpl. Then the usage should be clear and pretty.

Title: Define values for each namespace

Body:
values.yaml

replicas: {
  test: 1,
  stage: 2,
  prod: 3
}

Here I am trying to use Helm templates to define number of replicas per namespace but am unsure of the proper syntax and pattern:

deployment.yaml

replicas: {{ .Values.replicas.{{ .Release.Namespace }} }}

So if this were deployed to --namespace=prod, I would expect the template to return:

# .Values.replicas.prod
replicas: 3

Body:
I don't think that Helm supports evaluating variable in the variable. For this, you're expression would need to be evaluated twice.

What you could do is to write the following code:

{{ if eq .Release.Namespace "test" }}{{ .Values.replicas.test }}{{ end }}

You can then also extract that code to your _helpers.tpl. Then the usage should be clear and pretty.