答:
Well it's obviously because of the order in which you perform these operations and also because findAny explicitly says : throws NullPointerException if the element selected is null

When you do map(Foo::getAttr) you have effectively mapped that to null, so your Stream now contains a null; thus findAny breaks with an Exception (since findAny is applied on that null)

The other operation first finds the Foo object, then maps it to Foo::getAttr (thus mapping it to Optional.empty()), thus orElse is called.

Also, this would make more sense (for me at least):

```<code> list.stream()
     .findAny()
     .flatMap(f -> Optional.ofNullable(f.getAttr()))
     .orElse(null);
</code>```

flatMap would map to Optional<Integer> (attributes), in case this one is empty get the orElse result.

Title: java 8 findFirst vs map on optional

Body:
Well it's obviously because of the order in which you perform these operations and also because findAny explicitly says : throws NullPointerException if the element selected is null

When you do map(Foo::getAttr) you have effectively mapped that to null, so your Stream now contains a null; thus findAny breaks with an Exception (since findAny is applied on that null)

The other operation first finds the Foo object, then maps it to Foo::getAttr (thus mapping it to Optional.empty()), thus orElse is called.

Also, this would make more sense (for me at least):

 list.stream()
     .findAny()
     .flatMap(f -> Optional.ofNullable(f.getAttr()))
     .orElse(null);

flatMap would map to Optional<Integer> (attributes), in case this one is empty get the orElse result.


来源: stackexchange

问:
Angular 2 - Check If Any Default Values Have Changed
I am extremely new to Angular 2 and am struggling to find a way to check if any value in my md-input's have changed.

HTML

```<code><md-card>
    <h3>Contact details</h3>
        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="Telephone number" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.contact.telephoneNumber">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="Email address" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.contact.email">
        </md-input-container>
        <div>
            <h3 class="headingWithButtonBeside">Address details</h3>
            <button *ngIf="!this.personalDetailsDisable" class="floatingButtonBesideHeading" md-button color="accent" title="Click to find your new address using your new postcode.">Use postcode lookup</button>
        </div>
        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="Flat name" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.flatName">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="Flat number" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.flatNumber">
        </md-input-container>
        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="House name" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.houseName">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="House number" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.houseNumber">
        </md-input-container>
        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="Street" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.street">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="District" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.district">
        </md-input-container>
        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="City" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.city">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="County" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.county">
        </md-input-container>
        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="Country" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.country">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="Postcode" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.postCode">
        </md-input-container>
</md-card>
</code>```

I have no idea how to check i can check all fields in one.  Reason for this is that unless any field value changes from the default value that is returned from my service, then i want a 'Save' button to display other wise i don't want the save button to be displayed.

I know this has to be done in my component and i have seen examples of SimpleChange etc but i cant get it work at all

答:
If you could share your component source code we could see more. But so far it should be done like this. Link to Angular docs.</p>

```<code>@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
  @Input()
  prop: number;

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am extremely new to Angular 2 and am struggling to find a way to check if any value in my md-input's have changed.

HTML

<md-card>

Contact details

        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="Telephone number" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.contact.telephoneNumber">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="Email address" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.contact.email">
        </md-input-container>

Address details

            <button *ngIf="!this.personalDetailsDisable" class="floatingButtonBesideHeading" md-button color="accent" title="Click to find your new address using your new postcode.">Use postcode lookup</button>

        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="Flat name" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.flatName">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="Flat number" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.flatNumber">
        </md-input-container>
        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="House name" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.houseName">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="House number" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.houseNumber">
        </md-input-container>
        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="Street" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.street">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="District" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.district">
        </md-input-container>
        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="City" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.city">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="County" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.county">
        </md-input-container>
        <md-input-container class="containerRightMargin">
            <input mdInput placeholder="Country" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.country">
        </md-input-container>
        <md-input-container>
            <input mdInput placeholder="Postcode" [disabled]="this.personalDetailsDisable" [(ngModel)]="accountService.client?.address.postCode">
        </md-input-container>
</md-card>

I have no idea how to check i can check all fields in one.  Reason for this is that unless any field value changes from the default value that is returned from my service, then i want a 'Save' button to display other wise i don't want the save button to be displayed.

I know this has to be done in my component and i have seen examples of SimpleChange etc but i cant get it work at all

Body:
If you could share your component source code we could see more. But so far it should be done like this. Link to Angular docs.

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
  @Input()
  prop: number;

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
  }
}


问:
Do MySql connections closed from Jdbc stay opened for some time?
I get the following error accessing to a MySql Database from Jdbc:

```<code>java.sql.SQLNonTransientConnectionException: Too many connections
</code>```

At the same time I am monitoring my connections. I added a counter that counts any opening and closing. The error ouccurs when I get to 380 opened and closed connections within 3 minutes.
Is it possible that it takes some time for MySql to acutally close the connection so that there are still too many opened even though I have send a command to close them?

答:
I am just assuming certain points that might be the reason.

MySql Connections are maintained by MySql Connection Manager so once connection is released Manager will decide to kill that thread or return it back to pool.

In some cases if MySql Resultset is not closed after retrieving data and connection has been close on that time sending it back to pool might have some latency issue.

These two are points that i think might cause that, but i am not sure if these are correct or not.
There could be other reasons that i am not knowing about.
Hope it gives you some idea.

Body:
I get the following error accessing to a MySql Database from Jdbc:

java.sql.SQLNonTransientConnectionException: Too many connections

At the same time I am monitoring my connections. I added a counter that counts any opening and closing. The error ouccurs when I get to 380 opened and closed connections within 3 minutes.
Is it possible that it takes some time for MySql to acutally close the connection so that there are still too many opened even though I have send a command to close them?


问:
How to fetch 4 characters from a string in oracle?
By using following query i am able to fetch a particular string.Now this output string contains alphanumeric characters.e.g.abcd123,pqrs542356.
Now i want to fetch only first 4 characters of this string which will be always alpha bates.

Query::

```<code>(SELECT SUBSTR(in_msg, INSTR( in_msg,'?', 1, 10 )+ 1, INSTR(in_msg,'?', 1, 11 ) - INSTR( in_msg,'?', 1, 10 )- 1)
 FROM emp_message
WHERE emp_no IN (SELECT emp_no
                   FROM main_table
                  WHERE name like '%abcd%')
</code>```

This query returns output as e.g.abcd1234,pqrs145423.
Again i want to fetch only first 4 characters from this query output.
Can somebody help me in this.

答:
```<code>select substr(x, 1, 4) from
   ( select x from .....  )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
By using following query i am able to fetch a particular string.Now this output string contains alphanumeric characters.e.g.abcd123,pqrs542356.
Now i want to fetch only first 4 characters of this string which will be always alpha bates.

Query::

(SELECT SUBSTR(in_msg, INSTR( in_msg,'?', 1, 10 )+ 1, INSTR(in_msg,'?', 1, 11 ) - INSTR( in_msg,'?', 1, 10 )- 1)
 FROM emp_message
WHERE emp_no IN (SELECT emp_no
                   FROM main_table
                  WHERE name like '%abcd%')

This query returns output as e.g.abcd1234,pqrs145423.
Again i want to fetch only first 4 characters from this query output.
Can somebody help me in this.


问:
Error while loading coverage session (code 5001)
I got the following error when I am trying to check coverage using EclEmma, please help me out:

Error while loading coverage session (code 5001). Error while
  analyzing package fragment root java at
  F/solo-repository/target/test-classes (code 5007). File not found:
  D:\RDM
  Services\solo-repository\target\test-classes\com\charter\solo\account\repository\AccountBillInformationRepositoryTest.class.
  D:\RDM
  Services\solo-repository\target\test-classes\com\charter\solo\account\repository\AccountBillInformationRepositoryTest.class
  (The system cannot find the path specified)

答:
I had similar problem. This is what I did.

Refreshed the project.

Updated the maven project.

Configured the Coverage. You may want to include some additional jars if you are trying to get the coverage over some dependencies.

It worked for me.

ContentLicense: CC BY-SA 4.0


问:
Using lookup transformation for 2 columns at the same time
I want to use lookup transformation for 2 columns at the same time in SSIS. For example, if there are 3 columns ProductID,CreatedDate,Pname I need to compare 2 columns say ProductID and CreatedDate at the same time so that only if a row has same ProductID but different Created Date it should go in no match output. Currently my transformation is just using productid and if its already exists, it is putting in matched rows even after having a different CreatedDate.

As per above example, both ProductID with 1 should be there in no match output.

How can we implement this in SSIS?

答:
It's very simple. Currently I believe you have only source.ProducID mapped to destination.ProductID in lookup.

All you need to do is map source.CreatedDate to destination.CreatedDate.

You need to do something like this :


问:
Automating H2O Flow: run flow from CLI
I’ve been an h2o user for a little over a year and a half now, but my work has been limited to the R api; h2o flow is relatively new to me. If it's new to you as well, it's basically 0xdata's version of iPython, however iPython let's you export your notebook to a script. I can't find a similar option in flow...

I’m at the point of moving a model (built in flow) to production, and I'm wondering how to automate it. With the R api, after the model was built and saved, I could easily load it in R and make predictions on the new data simply by running a nohup Rscript <the_file> & from CLI, but I’m not sure how I can do something similar with flow, especially since it’s running on Hadoop.

As it currently stands, every run is broken into three pieces with the flow creating a relatively clunky process in the middle:

preprocess data, move it to hdfs

start h2o on hadoop, nslookup the IP address h2o is running on, manually run the flow cell-by-cell

run the post-prediction clean-up and final steps

This is a terribly intrusive production process, and I want to tie all the ends up, however flow is making it rather difficult.  To distill the question: is there a way to compress the flow into a hadoop jar and then later just run the jar like hadoop jar <my_flow_jar.jar> ...?

Edit:

Here's the h2o R package documentation. The R API allows you to load an H2O model, so I tried loading the flow (as if it were an H2O model), and unsurprisingly it did not work (failed with a water.api.FSIOException) as it's not technically an h2o model.

答:
This is really late, but (now) h2o flow models have auto-generated java code that represents the trained model (called a POJO) that can be cut and pasted (say from your remote hadoop session to a local java file). See here for a quickstart tutorial on how to use the java object (https://h2o-release.s3.amazonaws.com/h2o/rel-turing/1/docs-website/h2o-docs/pojo-quick-start.html). You'll have to refer to the h2o java api (https://h2o-release.s3.amazonaws.com/h2o/rel-turing/8/docs-website/h2o-genmodel/javadoc/hex/genmodel/easy/EasyPredictModelWrapper.html) to start customizing how you want to use the POJO, but you essentially use it as a black box that makes predictions on properly formated inputs.

Assuming you hadoop session is remote, replace "localhost" in the example with the IP address of your (remote) flow session.

Title: Automating H2O Flow: run flow from CLI


问:
pthread condition loop
The typical pattern I've seen for using pthread_cond_wait is:

```<code>pthread_mutex_lock(&lock);
  while (!test)
    pthread_cond_wait(&condition, &lock);
pthread_mutex_unlock(&lock);
</code>```

Why can't an if statement be used instead of a while loop.

```<code>pthread_mutex_lock(&lock);
  if (!test)
    pthread_cond_wait(&condition, &lock);
pthread_mutex_unlock(&lock);
</code>```

答:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html

When using condition variables there is always a Boolean predicate involving shared variables associated with each condition wait that is true if the thread should proceed. Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.

The while loop is a very standard way of re-evaluating the predicate, as required by POSIX.

Title: pthread condition loop

Body:
The typical pattern I've seen for using pthread_cond_wait is:

pthread_mutex_lock(&lock);
  while (!test)
    pthread_cond_wait(&condition, &lock);
pthread_mutex_unlock(&lock);

Why can't an if statement be used instead of a while loop.

pthread_mutex_lock(&lock);
  if (!test)
    pthread_cond_wait(&condition, &lock);
pthread_mutex_unlock(&lock);


问:
How do I call a Form's class function or access its property from a conditional formatting expression
Having the following code on a Form class in Access 2003:

Public currentId As Integer

Private Sub Form_Current()
  Me.currentId = Me.id
  ' The following works fine
  Debug.Print Forms!my_form_name.currentId
End Sub
```

<p>...and an unbound textbox in the same continuous form (created in design view), how do I access the <code>.currentId</code> property from a conditional formatting expression?</p>

<p>I want to use the unbound textbox to highlight the record that is currently selected by comparing the form's <code>.currentId</code> value with the actual <code>[id]</code> of its own record.</p>

<p>Some expressions I've tried:</p>

<pre class="lang-vb prettyprint-override"><code>[id] = Me.currentId
[id] = Me!currentId
[id] = Me.Form.currentId
[id] = Forms!my_form_name.currentId
[id] = Forms!my_form_name!currentId
[id] = Forms!my_form_name!Form.[currentId]
[id] = Forms!my_form_name!Form!currentId
[id] = Forms!my_form_name!Form[currentId]
[id] = Forms!my_form_name![currentId]
[id] = Forms![my_form_name].[currentId]
[id] = Forms![my_form_name]![currentId]
</code>```

...etc., etc., etc. Any variant I could think of, basically.

I've tried creating a Public Function getCurrentId() as well, but that didn't get me anywhere either. It even complained when I added parentheses in the expression, like this:

```<code>[id] = Forms!my_form_name.getCurrentId()
</code>```

...which I should perhaps take as a hint that these more complex expressions are probably not allowed for conditional formatting expressions.

So, am I missing something? Or is it indeed simply not possible to reference anything other than current record fields in these conditional formatting expressions?

One other detail that might be important to mention, is that Access 2003 localizes the Forms part to Formulieren in the conditional formatting expression dialog, in the Dutch version I am using.

答:
If you have an hidden unbound text box called say txtCurrRec on your detail line, set using the on current event by </p>

```<code>Me.txtCurrRec = Me.Id
</code>```

<p>Then all you need in the conditional formatting is </p>

```<code>Expression is [txtCurrRec] = [YourIDField]
</code>```

Body:
Having the following code on a Form class in Access 2003:

Public currentId As Integer

Private Sub Form_Current()
  Me.currentId = Me.id
  ' The following works fine
  Debug.Print Forms!my_form_name.currentId
End Sub

...and an unbound textbox in the same continuous form (created in design view), how do I access the .currentId property from a conditional formatting expression?

I want to use the unbound textbox to highlight the record that is currently selected by comparing the form's .currentId value with the actual [id] of its own record.

Some expressions I've tried:

[id] = Me.currentId
[id] = Me!currentId
[id] = Me.Form.currentId
[id] = Forms!my_form_name.currentId
[id] = Forms!my_form_name!currentId
[id] = Forms!my_form_name!Form.[currentId]
[id] = Forms!my_form_name!Form!currentId
[id] = Forms!my_form_name!Form[currentId]
[id] = Forms!my_form_name![currentId]
[id] = Forms![my_form_name].[currentId]
[id] = Forms![my_form_name]![currentId]

...etc., etc., etc. Any variant I could think of, basically.

I've tried creating a Public Function getCurrentId() as well, but that didn't get me anywhere either. It even complained when I added parentheses in the expression, like this:

[id] = Forms!my_form_name.getCurrentId()

...which I should perhaps take as a hint that these more complex expressions are probably not allowed for conditional formatting expressions.

So, am I missing something? Or is it indeed simply not possible to reference anything other than current record fields in these conditional formatting expressions?

One other detail that might be important to mention, is that Access 2003 localizes the Forms part to Formulieren in the conditional formatting expression dialog, in the Dutch version I am using.

Body:
If you have an hidden unbound text box called say txtCurrRec on your detail line, set using the on current event by

Me.txtCurrRec = Me.Id

Then all you need in the conditional formatting is

Expression is [txtCurrRec] = [YourIDField]


问:
How to split string in ruby
I have a string:

```<code>"1 chocolate bar at 25"
</code>```

and I want to split this string into:

```<code> [1, "chocolate bar", 25]
</code>```

I don't know how to write a regex for this split. And I wanted to know whether there are any other functions to accomplish it.

答:
You can also do something like this:

```<code>"1 chocolate bar at 25"
  .split()
  .reject {|string| string == "at" }
  .map {|string| string.scan(/^\D+$/).empty? ? string.to_i : string }
</code>```

Code Example: http://ideone.com/s8OvlC

Title: How to split string in ruby

Body:
I have a string:

"1 chocolate bar at 25"

and I want to split this string into:

 [1, "chocolate bar", 25]

I don't know how to write a regex for this split. And I wanted to know whether there are any other functions to accomplish it.

Body:
You can also do something like this:

"1 chocolate bar at 25"
  .split()
  .reject {|string| string == "at" }
  .map {|string| string.scan(/^\D+$/).empty? ? string.to_i : string }

Code Example: http://ideone.com/s8OvlC


问:
SQL Insert sent to server from entity framework does not create any record
I have a asp.net core web application with entity framework core. When I add a record to in EF and save changes, I don't see any record being created in SQL table.

So I open SQL Profiler to SQL profiler to debug and I can clearly see below insert statement in RPC:Starting and RPC:Completed event. There was no entity framework related exception thrown from my application. There was not SQL exception also. however, the record does not appear in AbpUsers table. But if I manually copy below statement and run in SSMS, the record can be created.

```<code>    exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [AbpUsers] ([AccessFailedCount], [AuthenticationSource], [ConcurrencyStamp], [CreationTime], [CreatorUserId], [DeleterUserId], [DeletionTime], [EmailAddress], [EmailConfirmationCode], [IsActive], [IsDeleted], [IsEmailConfirmed], [IsLockoutEnabled], [IsPhoneNumberConfirmed], [IsTwoFactorEnabled], [LastLoginTime], [LastModificationTime], [LastModifierUserId], [LockoutEndDateUtc], [Name], [NormalizedEmailAddress], [NormalizedUserName], [Password], [PasswordResetCode], [PhoneNumber], [SecurityStamp], [Surname], [TenantId], [UserName])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15, @p16, @p17, @p18, @p19, @p20, @p21, @p22, @p23, @p24, @p25, @p26, @p27, @p28);
SELECT [Id]
FROM [AbpUsers]
WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity();

',N'@p0 int,@p1 nvarchar(64),@p2 nvarchar(4000),@p3 datetime2(7),@p4 bigint,@p5 bigint,@p6 datetime2(7),@p7 nvarchar(256),@p8 nvarchar(328),@p9 bit,@p10 bit,@p11 bit,@p12 bit,@p13 bit,@p14 bit,@p15 datetime2(7),@p16 datetime2(7),@p17 bigint,@p18 datetime2(7),@p19 nvarchar(32),@p20 nvarchar(256),@p21 nvarchar(32),@p22 nvarchar(128),@p23 nvarchar(328),@p24 nvarchar(4000),@p25 nvarchar(4000),@p26 nvarchar(32),@p27 int,@p28 nvarchar(32)',@p0=0,@p1=N'LDAP',@p2=N'215f3645-7546-4808-a1ec-141bf634f818',@p3='2017-07-06 16:54:41.5659350',@p4=NULL,@p5=NULL,@p6=NULL,@p7=N'some email address',@p8=NULL,@p9=1,@p10=0,@p11=1,@p12=1,@p13=0,@p14=0,@p15=NULL,@p16=NULL,@p17=NULL,@p18=NULL,@p19=N'first name',@p20=N'some email address',@p21=N'SESA405265',@p22=N'AQAAAAEAACcQAAAAENF58O2EZ7lsnJuBuoW4hHI9D5dKdf37Hgzcc/VH9eZ5J4x2966Qp2e464o7gfs8KQ==',@p23=NULL,@p24=NULL,@p25=N'34dc38d9-64df-2795-f645-39e029489a9d',@p26=N'last name',@p27=NULL,@p28=N'some id'
</code>```

Below is the code where the record was inserted in entity framework. Full source code can be found here: https://github.com/aspnetboilerplate/module-zero/blob/dev/src/Abp.ZeroCore/Authorization/AbpLoginManager.cs

```<code>using (UnitOfWorkManager.Current.SetTenantId(tenantId))
                    {
                        var user = await UserManager.AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress);
                        if (user == null)
                        {
                            user = await source.Object.CreateUserAsync(userNameOrEmailAddress, tenant);

                            user.TenantId = tenantId;
                            user.AuthenticationSource = source.Object.Name;
                            user.Password = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString("N").Left(16)); //Setting a random password since it will not be used
                            user.NormalizedEmailAddress = user.EmailAddress;
                            user.NormalizedUserName = user.UserName;
                            if (user.Roles == null)
                            {
                                user.Roles = new List<UserRole>();
                                foreach (var defaultRole in RoleManager.Roles.Where(r => r.TenantId == tenantId && r.IsDefault).ToList())
                                {
                                    user.Roles.Add(new UserRole(tenantId, user.Id, defaultRole.Id));
                                }
                            }

                            await UserManager.AbpStore.CreateAsync(user);
                        }
                        else
                        {
                            await source.Object.UpdateUserAsync(user, tenant);

                            user.AuthenticationSource = source.Object.Name;

                            await UserManager.AbpStore.UpdateAsync(user);
                        }

                        await UnitOfWorkManager.Current.SaveChangesAsync();

                        return true;
                    }
</code>```

答:
Thanks to Dan Guzman's suggestions, I started to look for places where rollback could have happened in my code.

So here is what happened. The TryLoginFromExternalAuthenticationSources method created a user with the userName (e.g. Tom). but on the next line of the code, the user was searched using 'domain\Tom' format, which results in the null result. therefore the login result was considered failed and an exception was thrown somewhere very far from this place, causing the transaction being rolledback.

```<code>                var loggedInFromExternalSource = await TryLoginFromExternalAuthenticationSources(userNameOrEmailAddress, plainPassword, tenant);

            var user = await UserManager.AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress);
            if (user == null)
            {
                return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.InvalidUserNameOrEmailAddress, tenant);
            }
</code>```

Body:
I have a asp.net core web application with entity framework core. When I add a record to in EF and save changes, I don't see any record being created in SQL table.

So I open SQL Profiler to SQL profiler to debug and I can clearly see below insert statement in RPC:Starting and RPC:Completed event. There was no entity framework related exception thrown from my application. There was not SQL exception also. however, the record does not appear in AbpUsers table. But if I manually copy below statement and run in SSMS, the record can be created.

    exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [AbpUsers] ([AccessFailedCount], [AuthenticationSource], [ConcurrencyStamp], [CreationTime], [CreatorUserId], [DeleterUserId], [DeletionTime], [EmailAddress], [EmailConfirmationCode], [IsActive], [IsDeleted], [IsEmailConfirmed], [IsLockoutEnabled], [IsPhoneNumberConfirmed], [IsTwoFactorEnabled], [LastLoginTime], [LastModificationTime], [LastModifierUserId], [LockoutEndDateUtc], [Name], [NormalizedEmailAddress], [NormalizedUserName], [Password], [PasswordResetCode], [PhoneNumber], [SecurityStamp], [Surname], [TenantId], [UserName])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15, @p16, @p17, @p18, @p19, @p20, @p21, @p22, @p23, @p24, @p25, @p26, @p27, @p28);
SELECT [Id]
FROM [AbpUsers]
WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity();

',N'@p0 int,@p1 nvarchar(64),@p2 nvarchar(4000),@p3 datetime2(7),@p4 bigint,@p5 bigint,@p6 datetime2(7),@p7 nvarchar(256),@p8 nvarchar(328),@p9 bit,@p10 bit,@p11 bit,@p12 bit,@p13 bit,@p14 bit,@p15 datetime2(7),@p16 datetime2(7),@p17 bigint,@p18 datetime2(7),@p19 nvarchar(32),@p20 nvarchar(256),@p21 nvarchar(32),@p22 nvarchar(128),@p23 nvarchar(328),@p24 nvarchar(4000),@p25 nvarchar(4000),@p26 nvarchar(32),@p27 int,@p28 nvarchar(32)',@p0=0,@p1=N'LDAP',@p2=N'215f3645-7546-4808-a1ec-141bf634f818',@p3='2017-07-06 16:54:41.5659350',@p4=NULL,@p5=NULL,@p6=NULL,@p7=N'some email address',@p8=NULL,@p9=1,@p10=0,@p11=1,@p12=1,@p13=0,@p14=0,@p15=NULL,@p16=NULL,@p17=NULL,@p18=NULL,@p19=N'first name',@p20=N'some email address',@p21=N'SESA405265',@p22=N'AQAAAAEAACcQAAAAENF58O2EZ7lsnJuBuoW4hHI9D5dKdf37Hgzcc/VH9eZ5J4x2966Qp2e464o7gfs8KQ==',@p23=NULL,@p24=NULL,@p25=N'34dc38d9-64df-2795-f645-39e029489a9d',@p26=N'last name',@p27=NULL,@p28=N'some id'

Below is the code where the record was inserted in entity framework. Full source code can be found here: https://github.com/aspnetboilerplate/module-zero/blob/dev/src/Abp.ZeroCore/Authorization/AbpLoginManager.cs

using (UnitOfWorkManager.Current.SetTenantId(tenantId))
                    {
                        var user = await UserManager.AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress);
                        if (user == null)
                        {
                            user = await source.Object.CreateUserAsync(userNameOrEmailAddress, tenant);

                            user.TenantId = tenantId;
                            user.AuthenticationSource = source.Object.Name;
                            user.Password = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString("N").Left(16)); //Setting a random password since it will not be used
                            user.NormalizedEmailAddress = user.EmailAddress;
                            user.NormalizedUserName = user.UserName;
                            if (user.Roles == null)
                            {
                                user.Roles = new List<UserRole>();
                                foreach (var defaultRole in RoleManager.Roles.Where(r => r.TenantId == tenantId && r.IsDefault).ToList())
                                {
                                    user.Roles.Add(new UserRole(tenantId, user.Id, defaultRole.Id));
                                }
                            }

                            await UserManager.AbpStore.CreateAsync(user);
                        }
                        else
                        {
                            await source.Object.UpdateUserAsync(user, tenant);

                            user.AuthenticationSource = source.Object.Name;

                            await UserManager.AbpStore.UpdateAsync(user);
                        }

                        await UnitOfWorkManager.Current.SaveChangesAsync();

                        return true;
                    }

Body:
Thanks to Dan Guzman's suggestions, I started to look for places where rollback could have happened in my code.

So here is what happened. The TryLoginFromExternalAuthenticationSources method created a user with the userName (e.g. Tom). but on the next line of the code, the user was searched using 'domain\Tom' format, which results in the null result. therefore the login result was considered failed and an exception was thrown somewhere very far from this place, causing the transaction being rolledback.

                var loggedInFromExternalSource = await TryLoginFromExternalAuthenticationSources(userNameOrEmailAddress, plainPassword, tenant);

            var user = await UserManager.AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress);
            if (user == null)
            {
                return new AbpLoginResult<TTenant, TUser>(AbpLoginResultType.InvalidUserNameOrEmailAddress, tenant);
            }


问:
Use ClassTag and TypeTag to get type of the elements of Seq[AnyRef]
With the following test case, I would check the type of the elements of a Seq[AnyRef],

```<code>  @Test
  def testClassTagAndTypeTag(): Unit = {
    import scala.reflect.runtime.universe._
    def getTypeTag[T: TypeTag](data: T): TypeTag[T] = typeTag[T]
    def getClassTag[T: ClassTag](data: T): ClassTag[T] = implicitly[ClassTag[T]]
    val data = Seq(List(1), "Hello", new Box(1))
    data.foreach(x => {
      println(s"TypeTag: ${getTypeTag(x)}, tpe: ${getTypeTag(x).tpe}")
    })
    data.foreach(x => {
      println(s"ClassTag: ${getClassTag(x)}")
    })
  }
</code>```

The output of the above code is:

```<code>TypeTag: TypeTag[java.lang.Object], tpe: java.lang.Object
TypeTag: TypeTag[java.lang.Object], tpe: java.lang.Object
TypeTag: TypeTag[java.lang.Object], tpe: java.lang.Object
ClassTag: Object
ClassTag: Object
ClassTag: Object
</code>```

I thought that the type tag should output the real type of Seq's elements, which should be

```<code>List[Int]
String
Box[Int]
</code>```

答:
By the time you have a Seq[AnyRef], it's too late. The type of x in data.foreach(x => ...) is just AnyRef, so getTypeTag(x) and getClassTag(x) give corresponding results.

Instead, you can store type tag together with value, e.g.

```<code>case class WithTypeTag[A](x: A)(implicit val tag: TypeTag[A])

val data = Seq(WithTypeTag(List(1)), WithTypeTag("Hello"), WithTypeTag(new Box(1)))
data.foreach(x => println(x.tag))
</code>```

Body:
With the following test case, I would check the type of the elements of a Seq[AnyRef],

  @Test
  def testClassTagAndTypeTag(): Unit = {
    import scala.reflect.runtime.universe._
    def getTypeTag[T: TypeTag](data: T): TypeTag[T] = typeTag[T]
    def getClassTag[T: ClassTag](data: T): ClassTag[T] = implicitly[ClassTag[T]]
    val data = Seq(List(1), "Hello", new Box(1))
    data.foreach(x => {
      println(s"TypeTag: ${getTypeTag(x)}, tpe: ${getTypeTag(x).tpe}")
    })
    data.foreach(x => {
      println(s"ClassTag: ${getClassTag(x)}")
    })
  }

The output of the above code is:

TypeTag: TypeTag[java.lang.Object], tpe: java.lang.Object
TypeTag: TypeTag[java.lang.Object], tpe: java.lang.Object
TypeTag: TypeTag[java.lang.Object], tpe: java.lang.Object
ClassTag: Object
ClassTag: Object
ClassTag: Object

I thought that the type tag should output the real type of Seq's elements, which should be

List[Int]
String
Box[Int]

Body:
By the time you have a Seq[AnyRef], it's too late. The type of x in data.foreach(x => ...) is just AnyRef, so getTypeTag(x) and getClassTag(x) give corresponding results.

Instead, you can store type tag together with value, e.g.

case class WithTypeTag[A](x: A)(implicit val tag: TypeTag[A])

val data = Seq(WithTypeTag(List(1)), WithTypeTag("Hello"), WithTypeTag(new Box(1)))
data.foreach(x => println(x.tag))


问:
Adding new data to one table and delete count from other table
I have 2 table ,  ( tableProducts , tableSpent)
I want to do " When I add new spent products at tableSpent , NumberofTotal = NumberofTotal - SpentProductnumber)

For example 3 products on Total Products

SEQDSD-PENCIL-15

QWEWQD-BOOK-10

ASGAGG-SHARPENER-45

I will add these infos at SpentProduct Table

ASGAGG - SHARPENER -20 - FOR SCHOOL

I want to delete this number ( 20 ) from TotalProducts
so Total Products must look like

SEQDSD-PENCIL-15

QWEWQD-BOOK-10

ASGAGG-SHARPENER-25

This is my code for adding spent products at Spent table
but Idk how can I delete this count number from total Products table
When I clicked button1 , It must add 4 textboxes's data at SpentTable
and It must delete that number from TotalProducts name

How can I do that?

This is my code for adding.// Names  and number of rows are different cause of translation :)

```<code>        if (conn.State == ConnectionState.Closed)
            conn.Open();

        string kayit = "insert into projeSarfBase(urunKodu,urunAdi,sarfAdet,projeKodu,projeAdi) values (@urunKodu,@urunAdi,@sarfAdet,@projeKodu,@projeAdi)";

        SqlCommand komut = new SqlCommand(kayit, conn);

        komut.Parameters.AddWithValue("@urunKodu", textBox1.Text);
        komut.Parameters.AddWithValue("@urunAdi", textBox2.Text);

        komut.Parameters.AddWithValue("@sarfAdet", textBox3.Text);
        komut.Parameters.AddWithValue("@projeKodu", textBox4.Text);
        komut.Parameters.AddWithValue("@projeAdi", textBox5.Text);

        komut.ExecuteNonQuery();

        conn.Close();
</code>```

答:
The way that commercial products will handle this is as follows.

Create a 'Transactions' table. As follows

```<code>Create Table InventTransactions (
ID int IDENTITY(1,1) PRIMARY KEY,
ProductID NVarChar(25),
Reference NVarchar(25),
TransactionDate datetime,
Quantity int)
</code>```

When you want to record the purchase of products, you set the quantity to a positive value

```<code>insert into InventTransactions (ProductID,Reference,TransactionDate,Quantity)
Values ('SHARPENER','Purchase Order #1',getDate(),45);
</code>```

And when you 'Spend' the products, you post a negative quantity

```<code>insert into InventTransactions (ProductID,Reference,TransactionDate,Quantity)
Values ('SHARPENER','ForSchool',getDate(),-20);
</code>```

At any point, you simply add up all of the quantities to get your result

Total Products:

```<code>Select ProductID, sum(quantity) from InventTransactions group by ProductID
Having SUM(Quantity)>0
</code>```

This approach improves performance (you only have to stamp one entry per transaction) and gives you a permanent record of where the inventory came from, and where it went.  It also allows you ask more interesting questions of the data like "What was the inventory at X date" or 'How much of this item do I use every week" (by filtering on date).

Body:
I have 2 table ,  ( tableProducts , tableSpent)
I want to do " When I add new spent products at tableSpent , NumberofTotal = NumberofTotal - SpentProductnumber)

For example 3 products on Total Products

SEQDSD-PENCIL-15

QWEWQD-BOOK-10

ASGAGG-SHARPENER-45

I will add these infos at SpentProduct Table

ASGAGG - SHARPENER -20 - FOR SCHOOL

I want to delete this number ( 20 ) from TotalProducts
so Total Products must look like

SEQDSD-PENCIL-15

QWEWQD-BOOK-10

ASGAGG-SHARPENER-25

This is my code for adding spent products at Spent table
but Idk how can I delete this count number from total Products table
When I clicked button1 , It must add 4 textboxes's data at SpentTable
and It must delete that number from TotalProducts name

How can I do that?

This is my code for adding.// Names  and number of rows are different cause of translation :)

        if (conn.State == ConnectionState.Closed)
            conn.Open();

        string kayit = "insert into projeSarfBase(urunKodu,urunAdi,sarfAdet,projeKodu,projeAdi) values (@urunKodu,@urunAdi,@sarfAdet,@projeKodu,@projeAdi)";

        SqlCommand komut = new SqlCommand(kayit, conn);

        komut.Parameters.AddWithValue("@urunKodu", textBox1.Text);
        komut.Parameters.AddWithValue("@urunAdi", textBox2.Text);

        komut.Parameters.AddWithValue("@sarfAdet", textBox3.Text);
        komut.Parameters.AddWithValue("@projeKodu", textBox4.Text);
        komut.Parameters.AddWithValue("@projeAdi", textBox5.Text);

        komut.ExecuteNonQuery();

        conn.Close();

Body:
The way that commercial products will handle this is as follows.

Create a 'Transactions' table. As follows

Create Table InventTransactions (
ID int IDENTITY(1,1) PRIMARY KEY,
ProductID NVarChar(25),
Reference NVarchar(25),
TransactionDate datetime,
Quantity int)

When you want to record the purchase of products, you set the quantity to a positive value

insert into InventTransactions (ProductID,Reference,TransactionDate,Quantity)
Values ('SHARPENER','Purchase Order #1',getDate(),45);

And when you 'Spend' the products, you post a negative quantity

insert into InventTransactions (ProductID,Reference,TransactionDate,Quantity)
Values ('SHARPENER','ForSchool',getDate(),-20);

At any point, you simply add up all of the quantities to get your result

Total Products:

Select ProductID, sum(quantity) from InventTransactions group by ProductID
Having SUM(Quantity)>0

This approach improves performance (you only have to stamp one entry per transaction) and gives you a permanent record of where the inventory came from, and where it went.  It also allows you ask more interesting questions of the data like "What was the inventory at X date" or 'How much of this item do I use every week" (by filtering on date).


问:
Showing and disposing tooltip .NET
I am working with yFiles.Net component which I use for representing dependencies between objects in some SQL database (graph representation).

I need to create tooltip which will appear when I point cursors on some object. That tooltip not contains just text, it contains images also. I know how to make custom class which extends default Tooltip class and then to override methods for drawing custom tooltips.

What i do not know is how to show tooltip when I point on some object on graph, and how to dispose it when I move cursor from object on graph? Can someone help me with this please?

答:
```<code> private CustomTooltip m_tooltip;
 private MouseHoverInputMode m_mouseHoverMode;

 private void SetupToolTips(GraphEditorInputMode mode)
    {

        m_tooltip = new CustomTooltip(m_model.TooltipImages);

        ItemHoverInputMode itemHoverMode = new ItemHoverInputMode();
        itemHoverMode.HoverItems = GraphItemTypes.Node | GraphItemTypes.Edge;
        mode.ItemHoverInputMode = itemHoverMode;

        m_mouseHoverMode = new MouseHoverInputMode(m_tooltip, textProvider);
        mode.MouseHoverInputMode = m_mouseHoverMode;
        mode.ItemHoverInputMode.HoveredItemChanged += new EventHandler<HoveredItemChangedEventArgs>(ToolTipEvent);
    }

    private void ToolTipEvent(object sender, HoveredItemChangedEventArgs e)
    {
        m_tooltip.Item = e.Item;
    }

    private void textProvider(object sender, ToolTipQueryEventArgs e)
    {
        if (m_tooltip.Item is INode || m_tooltip.Item is IEdge)
        {
            e.ToolTip = " ";
        }
    }

 public class CustomTooltip : ToolTip
  {
    private void OnPopup(object sender, PopupEventArgs e)
     {
     }
    private void OnDraw(object sender, DrawToolTipEventArgs e)
     {
     }
  }
</code>```

Title: Showing and disposing tooltip .NET


问:
How to receive an array of 16-bit integer tuples from a socket, in Python?
My Python app needs to receive an array of 16-bit integer tuples from a C++ application.

The data consists of an array of 32-bit unsigned integers, where each integer represents an IQ complex number. I and Q are each signed 16-bit numbers.

The array size is constant (6000).

The apps run on similar architectures so I don’t need to worry about endianness.

Please suggest a Python code snippet to read the data from a socket into a list of IQ tuples.  (I know how to create and connect a socket).

Best regards

David

答:
You can use struct library in python is you have incoming data as hexadecimal bytes.

Or if they are simple hexadecimal numbers then conversion is direct.

It would be really helpful if you can tell the data type you receive from C++ and the required format in python.


问:
logic in prolog language
I have a question in prolog here is the code:

```<code>sound(time1).
sound(time2).

sun(time3).

relax(X):-
    not(sound(X)),
    !,
    sun(X).
relax(_):-
    sun(_).
</code>```

now I an running - relax(T). I get true when I run relax(F) I get true also. Why does it happen?

and one more question, why relax(time4). also gets false? I think I am missing something.
thanks a lot!

答:
The fact that relax(T) and relax(F) both give the same result, is normal: uppercase identifiers are variables. So the two queries are semantically the same: you query with an ungrounded variable.

Now why do we get true.? If you query relax(T), Prolog will first call the first clause of relax(X).

The first clause has a body that starts with not(sound(X)). So we actually query not(sound(T)). Not is satisfied by the negation as finite failure principle: Prolog will aim to "prove" sound(T), and if that fails (it cannot find a way to satisfy that query).

So now Prolog queries sound(T), and this query is satisfied: indeed, sound(time1) satisfies this query, since Prolog reasons that now T = time1. As a result not(sound(T)) is false, and thus Prolog backtracks.

Now Prolog will try the next clause: relax(_) :- sun(_). The _ is a "wildcard" or "don't care" variable. Furthermore if you use multiple _s in the same clause, those are not related. So you basically say: everything is relax/1, given there is at least one sun/1. So now Prolog will query for a sun(_). This query succeeds: sun(time3) is a valid candidate, since _ = time3. So that means that relax(_) succeeds. We did not alter the variable T (or F), so Prolog can only say that the query is true.

Now if we query relax(time4), that's a different story. Again Prolog will first try to satisfy the first clause of relax/1. This is again done by calling not(sound(time4)). But note that time4 is a constant. And in Prolog all constants are different: so time1 and time4 cannot unify.

So now Prolog first aims to unify sound(time1) (first clause for sound/1) with sound(time4), but since time1 and time4 are different, that fails. Next it aims to unify sound(time2) (second clause of sound/1) with sound(time4), but again no luck. Now there are no clauses of sound/1 anymore. So Prolog gives up and considers not(sound(time4)) to be true.

That means that Prolog will continu in the body of the first clause of relax/1. The next statement is a !, that is a "cut" in Prolog. It means that Prolog should, for this branching point - no longer consider the remaining clauses. So it will from now on, ignore the second clause of relax/1. Next it encounters sun(X). So now Prolog will call sun(time4) and aim to satisfy this. It will aim to unify with the first (and only) clause of sun/1: sun(time3). But as said before, time3 and time4 do not unify. So as a result, that fails. Since Prolog cannot take the second clause of relax/1 (due to the cut (!)), it thus has exhausted all the options, and decides that the query relax(time4) is false.

Title: logic in prolog language

Body:
I have a question in prolog here is the code:

sound(time1).
sound(time2).

sun(time3).

relax(X):-
    not(sound(X)),
    !,
    sun(X).
relax(_):-
    sun(_).

now I an running - relax(T). I get true when I run relax(F) I get true also. Why does it happen?

and one more question, why relax(time4). also gets false? I think I am missing something.
thanks a lot!


问:
How do I preserve flags/width in a printf-formatted NSString used as a key for NSLocalizedString?
I use genstrings to generate .strings files from source code files in my project. Though the project is technically a Cappuccino app, this question should apply equally to any project that uses .strings files.

I have a format string that I'd like to be localized: @"%d:%02d %@". It is for displaying time values. If this were a OSX/iOS app, I'd use the built-in datetime formatting, but since it's Cappuccino I have to roll my own. When I run genstrings it produces this value for that key: "%1$d:%2$d %3$@".

This is as it appears in the Localizable.strings file:

```
/* ShortLocalTimeFormat */
"%d:%02d %@" = "%1$d:%2$d %3$@";
```

by running this command: genstrings -o Resources/en.lproj -s CPLocalizedString *.j */*.j

Again, ignore that I'm using CPLocalizedString instead of NSLocalizedStrings and *.j instead of *.m, as these values are appropriate for Cappuccino. Notice that the 02 in %02d is discarded in the resulting format string. If I run it again with the -noPositionalParameters option, it just leaves the string as is: genstrings -o Resources/en.lproj -noPositionalParameters -s CPLocalizedString *.j */*.j.

```
/* ShortLocalTimeFormat */
"%d:%02d %@" = "%d:%02d %@";
```

Is this a bug in genstrings, or is it not possible to use flags/width in format strings while keeping positional parameters?

答: If this were an Objective-C project, I would shorten the format strings to "%1$@ %2$@" and use an NSDateFormatter to generate the time string. If the class is not available, I would generate the intermediate time string myself and use the string as a parameter for the localized format string rather than passing hours/minutes to the localized format string directly.

Body:
I use genstrings to generate .strings files from source code files in my project. Though the project is technically a Cappuccino app, this question should apply equally to any project that uses .strings files.

I have a format string that I'd like to be localized: @"%d:%02d %@". It is for displaying time values. If this were a OSX/iOS app, I'd use the built-in datetime formatting, but since it's Cappuccino I have to roll my own. When I run genstrings it produces this value for that key: "%1$d:%2$d %3$@".

This is as it appears in the Localizable.strings file:

/* ShortLocalTimeFormat */
"%d:%02d %@" = "%1$d:%2$d %3$@";

by running this command: genstrings -o Resources/en.lproj -s CPLocalizedString *.j */*.j

Again, ignore that I'm using CPLocalizedString instead of NSLocalizedStrings and *.j instead of *.m, as these values are appropriate for Cappuccino. Notice that the 02 in %02d is discarded in the resulting format string. If I run it again with the -noPositionalParameters option, it just leaves the string as is: genstrings -o Resources/en.lproj -noPositionalParameters -s CPLocalizedString *.j */*.j.

/* ShortLocalTimeFormat */
"%d:%02d %@" = "%d:%02d %@";

Is this a bug in genstrings, or is it not possible to use flags/width in format strings while keeping positional parameters?


问:
How to write NUNit test cases when data is read from some database?
I want to test a functionality which includes a call to web service to get the data from database. The methods then operate on that data.

Now I want to write NUnit test cases for those methods. How can I assert results or values when I cannot know (at the time of writing cases) which data would be fetched at the run time?

答:
An excellent way of doing this is by inserting data (do it in the negative index range (assuming the negatives are not in use for production data)) run your tests with that dataset, and then roll back your transaction once you are done.

Another option that would help you test your datalayer better down the road, it to make a wrapping interface for your database layer.  You can then mock that interface when you are running tests that need it.

Normally you might have your IDataReader object and call IdataReader.GetMeData and it would return the result set from the DB.  In this case you would mock it (I use Rhino Mocks) and tell it to return your set of test data when GetMeData is called.
p.s. Don't forget to use dependency injection to pass in the mock database access object.


问:
Realm Swift: Can't get an object from realm
Im getting a JSON file from the api with versions of different api links so that i will know which information to download again if it is outdated.

I have a Version class which looks like this:

```<code>class Version : Object {

dynamic var myKey = NSUUID().uuidString
dynamic var banks_v = 0
dynamic var atms_v = 0

override static func primaryKey() -> String? {
    return "myKey"
}
</code>```

My idea is to take an old version from realm and to download the new version from api and if the versions dont match I should download the JSON file that I need and update my realm. Im doing it like this:

```<code>let newVersion = Version()
for item in json {
     newVersion.banks_v = item.1["banks_v"].intValue
     newVersion.atms_v = item.1["atms_v"].intValue
}

// ---- NEED HELP HERE START
let oldVersion = self.realm.object(ofType: Version.self, forPrimaryKey: newVersion.myKey)
// NEED HELP HERE END ----

var rewriteVersion = false
if newVersion.banks_v != oldVersion?.banks_v {
     print(newVersion.banks_v) // prints 3 (correct)
     print(oldVersion?.banks_v) // prints nil (???)
     self.getBanks()
     rewriteVersion = true
}
if newVersion.atms_v != oldVersion?.atms_v {
     self.getAtms()
     rewriteVersion = true
}

if rewriteVersion {
     try! self.realm.write {
          self.realm.add(newVersion, update: true)
     }
}
</code>```

The problem is that I don't know how to properly get the object from realm. I think this part is wrong:

```<code>forPrimaryKey: newVersion.myKey
</code>```

I also tried putting "myKey" there but it is still nil. Any ideas on this?

Thanks in advance!

答:
I fixed it!

In my model class I replaced my id like this:

```<code>dynamic var id = 0
</code>```

and here:

```<code>let oldVersion = self.realm.object(ofType: Version.self, forPrimaryKey: 0)
</code>```

Body:
Im getting a JSON file from the api with versions of different api links so that i will know which information to download again if it is outdated.

I have a Version class which looks like this:

class Version : Object {

dynamic var myKey = NSUUID().uuidString
dynamic var banks_v = 0
dynamic var atms_v = 0

override static func primaryKey() -> String? {
    return "myKey"
}

My idea is to take an old version from realm and to download the new version from api and if the versions dont match I should download the JSON file that I need and update my realm. Im doing it like this:

let newVersion = Version()
for item in json {
     newVersion.banks_v = item.1["banks_v"].intValue
     newVersion.atms_v = item.1["atms_v"].intValue
}

// ---- NEED HELP HERE START
let oldVersion = self.realm.object(ofType: Version.self, forPrimaryKey: newVersion.myKey)
// NEED HELP HERE END ----

var rewriteVersion = false
if newVersion.banks_v != oldVersion?.banks_v {
     print(newVersion.banks_v) // prints 3 (correct)
     print(oldVersion?.banks_v) // prints nil (???)
     self.getBanks()
     rewriteVersion = true
}
if newVersion.atms_v != oldVersion?.atms_v {
     self.getAtms()
     rewriteVersion = true
}

if rewriteVersion {
     try! self.realm.write {
          self.realm.add(newVersion, update: true)
     }
}

The problem is that I don't know how to properly get the object from realm. I think this part is wrong:

forPrimaryKey: newVersion.myKey

I also tried putting "myKey" there but it is still nil. Any ideas on this?

Thanks in advance!

Body:
I fixed it!

In my model class I replaced my id like this:

dynamic var id = 0

and here:

let oldVersion = self.realm.object(ofType: Version.self, forPrimaryKey: 0)


问:
Foundation Framework and React - reInit accordion not working

Problem

I call setState to add a new recipe to my recipe list

The recipe is a new panel in a Foundation accordion

The accordion title pops up immediately

There is no functionality until page refresh

I have tried everything i can think of including Foundation's reInit, their manual toggle, up, and down methods for accordions, and re constructing the whole accordion

nothing works

答:
This is the solution I came up with.

i was able to call $("#element").foundation("toggle",$target,true) from the console and programmatically open and shut the accordion tab.

element is the accordion wrapper and target the specific tab, true is a param to indicate reflow needed

implementing that function into my app was more trouble than it was worth, for a number of reasons.

i ended up just calling location.reload() and which essentially is like pressing the refresh button.  with a modal animation running at the same time it is barely noticeable

so when all else fails manual over-ride could be a viable solution depending on what your individual page is

There is a real answer

in my research i came across quite a few similar github issues that had to do with Foundation plus some sort of dynamic rendering and/or third party framework/library.  every situation is a bit different so there isn't one answer

if someone has specific knowledge of what why Foundation or React(possibly), wouldn't let me reInit,reflow,$(document).foundation or do any of the various supposed solutions: I would love to know.

perhaps I could have done something different but if you look at my code I keep state to one component, I init my js plugins in componentDidMount - as far as i know this is what i am supposed to do. thanks


问:
html-xml-utils Get a specific
 value
I am using Xubuntu 16.04.2 with html-xml-utils

I tried this command

```<code>hxnormalize -x site/sciz.html | hxselect 'table.vitals-table:first-child'
</code>```

but it doesn't work, it outputs nothing. There are about 3-5 of these tables in the html.

Doing this outputs all the tables

```<code>hxnormalize -x site/sciz.html | hxselect 'table.vitals-table'
</code>```

But I need to only get the first-child or nth-child(n) and it doesn't seem to work correctly.

I tried getting the second
 in the table with this

```<code>hxnormalize -x site/sciz.html | hxselect 'table.vitals-table tbody tr:nth-child(2)'
</code>```

which deletes everything before the second
 but also prints everything after it.

I'm not sure what I'm not understanding about using :first/nth-child(n). Can someone please help? thanks

答: Could you try to use :nth-of-type(2) instead?

Title: html-xml-utils Get a specific <tr> value

Body:
I am using Xubuntu 16.04.2 with html-xml-utils

I tried this command

hxnormalize -x site/sciz.html | hxselect 'table.vitals-table:first-child'

but it doesn't work, it outputs nothing. There are about 3-5 of these tables in the html.

Doing this outputs all the tables

hxnormalize -x site/sciz.html | hxselect 'table.vitals-table'

But I need to only get the first-child or nth-child(n) and it doesn't seem to work correctly.

I tried getting the second
 in the table with this

hxnormalize -x site/sciz.html | hxselect 'table.vitals-table tbody tr:nth-child(2)'

which deletes everything before the second
 but also prints everything after it.

I'm not sure what I'm not understanding about using :first/nth-child(n). Can someone please help? thanks


答: The if is possible but rarely used. You just would have to be sure that the state of your application is as you come out of the wait. Usually you would have to ensure that you'd only use pthread_cond_signal at the other end (and not broadcast), e.g.

Title: pthread condition loop


问:
Access Enum value using EL with JSTL
I have an Enum called Status defined as such:

```<code>public enum Status {

    VALID("valid"), OLD("old");

    private final String val;

    Status(String val) {
        this.val = val;
    }

    public String getStatus() {
        return val;
    }

}
</code>```

I would like to access the value of VALID from a JSTL tag. Specifically the test attribute of the <c:when> tag. E.g.

```<code><c:when test="${dp.status eq Status.VALID">
</code>```

I'm not sure if this is possible.

答:
Here are two more possibilities:

JSP EL 3.0 Constants

As long as you are using at least version 3.0 of EL, then you can import constants into your page as follows:

```<code><%@ page import="org.example.Status" %>
<c:when test="${dp.status eq Status.VALID}">
</code>```

However, some IDEs don't understand this yet (e.g. IntelliJ) so you won't get any warnings if you make a typo, until runtime.

This would be my preferred method once it gets proper IDE support.

Helper Methods

You could just add getters to your enum.

```<code>public enum Status {
  VALID("valid"), OLD("old");

  private final String val;

  Status(String val) {
    this.val = val;
  }

  public String getStatus() {
    return val;
  }

  public boolean isValid() {
    return this == VALID;
  }

  public boolean isOld() {
    return this == OLD;
  }
}
</code>```

Then in your JSP:

```<code><c:when test="${dp.status.valid}">
</code>```

This is supported in all IDEs and will also work if you can't use EL 3.0 yet. This is what I do at the moment because it keeps all the logic wrapped up into my enum.

Also be careful if it is possible for the variable storing the enum to be null. You would need to check for that first if your code doesn't guarantee that it is not null:

```<code><c:when test="${not empty db.status and dp.status.valid}">
</code>```

I think this method is superior to those where you set an intermediary value in the JSP because you have to do that on each page where you need to use the enum. However, with this solution you only need to declare the getter once.

Title: Access Enum value using EL with JSTL

Body:
I have an Enum called Status defined as such:

public enum Status {

    VALID("valid"), OLD("old");

    private final String val;

    Status(String val) {
        this.val = val;
    }

    public String getStatus() {
        return val;
    }

}

I would like to access the value of VALID from a JSTL tag. Specifically the test attribute of the <c:when> tag. E.g.

<c:when test="${dp.status eq Status.VALID">

I'm not sure if this is possible.

Body:
Here are two more possibilities:

JSP EL 3.0 Constants

As long as you are using at least version 3.0 of EL, then you can import constants into your page as follows:

<%@ page import="org.example.Status" %>
<c:when test="${dp.status eq Status.VALID}">

However, some IDEs don't understand this yet (e.g. IntelliJ) so you won't get any warnings if you make a typo, until runtime.

This would be my preferred method once it gets proper IDE support.

Helper Methods

You could just add getters to your enum.

public enum Status {
  VALID("valid"), OLD("old");

  private final String val;

  Status(String val) {
    this.val = val;
  }

  public String getStatus() {
    return val;
  }

  public boolean isValid() {
    return this == VALID;
  }

  public boolean isOld() {
    return this == OLD;
  }
}

Then in your JSP:

<c:when test="${dp.status.valid}">

This is supported in all IDEs and will also work if you can't use EL 3.0 yet. This is what I do at the moment because it keeps all the logic wrapped up into my enum.

Also be careful if it is possible for the variable storing the enum to be null. You would need to check for that first if your code doesn't guarantee that it is not null:

<c:when test="${not empty db.status and dp.status.valid}">

I think this method is superior to those where you set an intermediary value in the JSP because you have to do that on each page where you need to use the enum. However, with this solution you only need to declare the getter once.


问:
How to change object property in a function with onclick in JavaScript
I am new to programming and I am trying to do something that is a bit overchallenging for me, so any help is appreciated.

I would like to use the Canvas Chess PGN viewer on a website which displays chessgames and make it possible for the users to go through the games. I want to use only one chessboard for different games, so I am trying to create onclick events that change the source property value in the chessboard script and make the script run again, but I cannot figure out how to do that.

It is the "pgn_uri" property that should be changed by clicking on the buttons, e.g. when the user clicks on "Round2" than it changes to "pgn_uri: secondGame", and so on. The script with the CHESS.PgnViewer() function should also run again so the chessboard gets updated.

```<code><button type="button" name="button" id="round1">Round1</button>
<button type="button" name="button" id="round2">Round2</button>
<button type="button" name="button" id="round3">Round3</button>

<script src="canvaschess\canvaschess-0.1.0.min.js"></script>
<script src="canvaschess\pgnviewer-0.1.0.min.js"></script>

<script type="text/javascript">
var firstGame = 'canvaschess/pgns/round1.pgn';
var secondGame = 'canvaschess/pgns/round2.pgn';
var thirdGame = 'canvaschess/pgns/round3.pgn';
</script>

<script>
var viewer = new CHESS.PgnViewer({
pgn_uri: firstGame,
square_color_dark: '#000',
square_color_light: '#fff',
square_uri_dark: 'canvaschess/img/themes/wood/square_dark.jpg',
square_uri_light: 'canvaschess/img/themes/wood/square_light.jpg',
show_labels: false,
show_tags: true
});
</script>
</code>```

答:
try adding onclick events
eg

keep variable say chessGame as "global" and  change its value onclick of buttons

```<code>$('#round2').onclick(function()
{
chessGame ='secondGame';
});
</code>```

and pass "chessGame" instead of "firstGame" in  new CHESS.PgnViewer

Body:
I am new to programming and I am trying to do something that is a bit overchallenging for me, so any help is appreciated.

I would like to use the Canvas Chess PGN viewer on a website which displays chessgames and make it possible for the users to go through the games. I want to use only one chessboard for different games, so I am trying to create onclick events that change the source property value in the chessboard script and make the script run again, but I cannot figure out how to do that.

It is the "pgn_uri" property that should be changed by clicking on the buttons, e.g. when the user clicks on "Round2" than it changes to "pgn_uri: secondGame", and so on. The script with the CHESS.PgnViewer() function should also run again so the chessboard gets updated.

<button type="button" name="button" id="round1">Round1</button>
<button type="button" name="button" id="round2">Round2</button>
<button type="button" name="button" id="round3">Round3</button>

Body:
try adding onclick events
eg

keep variable say chessGame as "global" and  change its value onclick of buttons

$('#round2').onclick(function()
{
chessGame ='secondGame';
});

and pass "chessGame" instead of "firstGame" in  new CHESS.PgnViewer


问:
React Prop-Types not detected ESLint
I have this on my react page:

```<code>import PropTypes from 'prop-types';
</code>```

...then

```<code>  componentWillMount() {
    this.props.myfunction();
  }
</code>```

...and finally:

```<code>MyComponent.PropTypes = {
  myfunction: PropTypes.func,
};
</code>```

Why does ESLine still complain with:

"ESLint: 'myfunction' is missing in props validation" ?

答:
Try using lower-case for your propTypes declaration:

```<code>MyComponent.propTypes = {
  myfunction: PropTypes.func,
};
</code>```

The difference here is that PropTypes (captial "P") is your node package, but propTypes (lowercase) is the name of the object inside your component.

Demo

class MyApp extends React.Component {
  componentWillMount() {
    this.props.myFunction();
  }
  render() {
    return (
hello
);
  }
}

MyApp.propTypes = {
  myfunction: PropTypes.func,
};

ReactDOM.render(<MyApp myFunction={() => {console.log("foo bar")}} />, document.getElementById("myApp"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/prop-types/prop-types.min.js"></script>
<div id="myApp"></div></code>```

Title: React Prop-Types not detected ESLint

Body:
I have this on my react page:

import PropTypes from 'prop-types';

...then

  componentWillMount() {
    this.props.myfunction();
  }

...and finally:

MyComponent.PropTypes = {
  myfunction: PropTypes.func,
};

Why does ESLine still complain with:

"ESLint: 'myfunction' is missing in props validation" ?

Body:
Try using lower-case for your propTypes declaration:

MyComponent.propTypes = {
  myfunction: PropTypes.func,
};

The difference here is that PropTypes (captial "P") is your node package, but propTypes (lowercase) is the name of the object inside your component.

Demo

class MyApp extends React.Component {
  componentWillMount() {
    this.props.myFunction();
  }
  render() {
    return (<p>hello</p>);
  }
}

MyApp.propTypes = {
  myfunction: PropTypes.func,
};

ReactDOM.render(<MyApp myFunction={() => {console.log("foo bar")}} />, document.getElementById("myApp"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/prop-types/prop-types.min.js"></script>
<div id="myApp"></div>


问:
VSCode jsconfig.json not working to provide intellisense
I have a very simple 'jsconfig.json' to provide intellisense to my *.js and *.html (

答: External file intellisense in html script blocks is not supported in VSCode 1.14. We are tracking the feature request here: https://github.com/Microsoft/vscode/issues/26338 </p>


问:
How to delete few files from zip in bash?
In my zip archive I have many txt files. Some of them have names ending on _temp_file.txt.
I know I can delete files from my zip archive with zip -d command, but how do I remove all files that have that ending? Is that even possible?

答:
Try using the command:

```<code>zip -d archive.zip "*_temp_file.txt"
</code>```

that should remove anything ending with _temp_file.txt from the archive.

Body:
Try using the command:

zip -d archive.zip "*_temp_file.txt"

that should remove anything ending with _temp_file.txt from the archive.


问:
Error in preview a container in tagmanager in android
I integrated the tagmanager in android for adwords conversion tracking. I want to test the container in preview mode. So I did all the things described on the google's developer page here.

I included the complete code needed for preview the container. But when I tried to launch the app from QR scanner or the link provided by tagmanager for preview.

It says:

sorry we cannot open this link. there is not any apps installed which can handle it.

Is anything I have to do except the above mentioned things.

答:
Stumbled upon similar problem. Solved by correctly reading the manual. Steps I did:

Add this to your android manifest file and replace your information:

```<code> <activity
        android:name="com.google.android.gms.tagmanager.PreviewActivity"
        android:label="@string/app_name"
        android:noHistory="true">  <!-- optional, removes the previewActivity from the activity stack. -->
        <intent-filter>
            <data android:scheme="YOUR WHOLE APP PACKAGE NAME" />
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE"/>
        </intent-filter>
    </activity>
</code>```

then go to GTM administration website -> container versions -> your current version -> actions -> preview and enter your WHOLE package name into the box. "eg. com.example.mygtm"

then proceed to open the link, copy adb command or scan QR code.

Hope this helps !

Body:
Stumbled upon similar problem. Solved by correctly reading the manual. Steps I did:

Add this to your android manifest file and replace your information:

 <activity
        android:name="com.google.android.gms.tagmanager.PreviewActivity"
        android:label="@string/app_name"
        android:noHistory="true">  <!-- optional, removes the previewActivity from the activity stack. -->
        <intent-filter>
            <data android:scheme="YOUR WHOLE APP PACKAGE NAME" />
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE"/>
        </intent-filter>
    </activity>

then go to GTM administration website -> container versions -> your current version -> actions -> preview and enter your WHOLE package name into the box. "eg. com.example.mygtm"

then proceed to open the link, copy adb command or scan QR code.

Hope this helps !


问:
How to rank transactions in custom order in redshift?
I have some transactions in database. I need to rank the transaction in a custom order. The transactions are

Transactions needs to be given rank in descending order of csave column and transactions with same tx number will get the same rank. So i execute below query:

```<code>SELECT * , DENSE_RANK() over (ORDER BY csave desc, tx) AS rank
FROM noma_d.setu_test.report_result
</code>```

And the result:

In the above transactions, for same tx, the value of csave column is same. Let's consider below transactions where for tx =1, csave values are different.

Now if i execute the same above query, then the result i got:

Here, one transaction of tx = 1 has rank = 2 and another transaction of tx = 1 has rank = 5. But i want to give all the transactions of tx = 1 to rank = 2 as one transaction of the tx = 1 got rank 2 so the rest of the transactions with tx = 1 will also have to be given rank 2.

The expected output will be like below:

How will i achieve this by modifying my above query?

答:
You need to group by the tx before ranking, so I've put this in a subquery:</p>

```<code>select t1.*, t2.rank
from noma_d.setu_test.report_result
inner join
(
    select a2.*, row_number() over (order by csave desc) as rank
    from
    (
        select tx, max(csave) as csave
        from noma_d.setu_test.report_result
        group by tx
    ) a2
) t2
    on t1.tx = t2.tx
</code>```

Body:
I have some transactions in database. I need to rank the transaction in a custom order. The transactions are

Transactions needs to be given rank in descending order of csave column and transactions with same tx number will get the same rank. So i execute below query:

SELECT * , DENSE_RANK() over (ORDER BY csave desc, tx) AS rank
FROM noma_d.setu_test.report_result

And the result:

In the above transactions, for same tx, the value of csave column is same. Let's consider below transactions where for tx =1, csave values are different.

Now if i execute the same above query, then the result i got:

Here, one transaction of tx = 1 has rank = 2 and another transaction of tx = 1 has rank = 5. But i want to give all the transactions of tx = 1 to rank = 2 as one transaction of the tx = 1 got rank 2 so the rest of the transactions with tx = 1 will also have to be given rank 2.

The expected output will be like below:

How will i achieve this by modifying my above query?

Body:
You need to group by the tx before ranking, so I've put this in a subquery:

select t1.*, t2.rank
from noma_d.setu_test.report_result
inner join
(
    select a2.*, row_number() over (order by csave desc) as rank
    from
    (
        select tx, max(csave) as csave
        from noma_d.setu_test.report_result
        group by tx
    ) a2
) t2
    on t1.tx = t2.tx


问:
Make text hyperlink in <textarea>
I have a textarea which post plane text to  mysql db table. Now I want to add some hyper references in that text.
how can I do this?
And I don't want to use any editor.</p>

答:
Use html_entities of php

```<code>    $textarea_code = htmlentities($_REQUEST['text_area_name']);
            $b = html_entity_decode($textarea_code);
            $textarea = mysql_real_escape_string($b);
echo $textarea;
</code>```

Title: Make text hyperlink in <textarea>

Body:
Use html_entities of php

    $textarea_code = htmlentities($_REQUEST['text_area_name']);
            $b = html_entity_decode($textarea_code);
            $textarea = mysql_real_escape_string($b);
echo $textarea;


问:
Performance of memmove compared to memcpy twice?
I have seen the difference pointed in the accepted answer in What is the difference between memmove and memcpy? and it said memmove might be very slightly slower than memcpy.

We can implement an alternative for memmove by doing as follows: allocate a temporary buffer, then memcpy twice (src -> tmp, tmp -> dest). My question is: which way is faster, memmove or the alternative?

答:
From http://en.cppreference.com/w/cpp/string/byte/memmove

Despite being specified "as if" a temporary buffer is used, actual implementations of this function do not incur the overhead of double copying or extra memory. For small count, it may load up and write out registers; for larger blocks, a common approach (glibc and bsd libc) is to copy bytes forwards from the beginning of the buffer if the destination starts before the source, and backwards from the end otherwise, with a fall back to std::memcpy when there is no overlap at all.

Therefore the overhead in all likelihood is a couple of conditional branches. Hardly worth worrying about for large blocks.

However, it is worth remembering that std::memcpy is a 'magic' function, being the only legal way to cast between two dissimilar types.

In c++, this is illegal (undefined behaviour):

```<code>union {
  float a;
  int b;
} u;

u.a = 10.0;
int x = u.b;
</code>```

This is legal:

```<code>float a = 10.0;
int b;
std::memcpy(std::addressof(b), std::addressof(a), size(b));
</code>```

and does what you'd expect the union to do if you were a C programmer.

Body:
From http://en.cppreference.com/w/cpp/string/byte/memmove

Despite being specified "as if" a temporary buffer is used, actual implementations of this function do not incur the overhead of double copying or extra memory. For small count, it may load up and write out registers; for larger blocks, a common approach (glibc and bsd libc) is to copy bytes forwards from the beginning of the buffer if the destination starts before the source, and backwards from the end otherwise, with a fall back to std::memcpy when there is no overlap at all.

Therefore the overhead in all likelihood is a couple of conditional branches. Hardly worth worrying about for large blocks.

However, it is worth remembering that std::memcpy is a 'magic' function, being the only legal way to cast between two dissimilar types.

In c++, this is illegal (undefined behaviour):

union {
  float a;
  int b;
} u;

u.a = 10.0;
int x = u.b;

This is legal:

float a = 10.0;
int b;
std::memcpy(std::addressof(b), std::addressof(a), size(b));

and does what you'd expect the union to do if you were a C programmer.


问:
How to achieve this font appearance?
How can I acheive a font like this?

It's the name below icons on the iOS platform.  Is it Helvetica, and how can I achieve the soft shadow that it has in code?  Thanks in advance!

答:
EDIT

BoltClock answered it already in a comment. Follow his link.

(I just discovered he said the same thing, but I want to draw attention to it so I'll leave this answer -- just don't check it, or BoltClock, add it as answer.)

This answer to a previous similar question explains how to do it. Turns out it's pretty simple.

Title: How to achieve this font appearance?


问:
Cannot read property 'get' of undefined in Node.js
I know some JS but I'm new to Node.js. I know this is a very common error but I couldn't find the source of the error since I lack debugging skills in Node.js.
Here is my app.js :

```<code>var index = require('./routes/index');
var users = require('./routes/userlist');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/userlist', users);
</code>```

Here is my userlist.js :

```<code>var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;
</code>```

Here is my index.js:

```<code>var express = require('express');
var router = express.Router();

router.get('/userlist', function(req, res) {
    var db = req.db;
    var collection = db.get('usercollection');
    console.log(collection);
    collection.find({},{},function(e,docs){
        res.render('userlist', {
            "userlist" : docs
        });
    });
});
</code>```

Here is userlist view :

```<code>extends layout

block content
    h1.
        User List
    ul
        each user, i in userlist
            li
                a(href="mailto:#{user.email}")= user.username
</code>```

I appreciate if you tell me where the problem is or tell me how I can detect the problem. Thanks in advance.

EDIT:

In console I get this :

```<code>GET /userlist 500 296.280 ms - 1501
</code>```

EDIT 2:
It gives me the error at this line :

```<code>var collection = db.get('usercollection');
</code>```

EDIT 3:
In index.js, I see that

```<code>router.get('/userlist', function(req, res) {
    var db = req.db;
</code>```

req.db is undefined. Why is it undefined? Do you have any idea?

答:
Changing code to this worked: </p>

```<code>app.use(function(req,res,next){
    req.db = db;
    next();
});
app.use('/', index);
app.use('/userlist', users);
</code>```

Body:
I know some JS but I'm new to Node.js. I know this is a very common error but I couldn't find the source of the error since I lack debugging skills in Node.js.
Here is my app.js :

var index = require('./routes/index');
var users = require('./routes/userlist');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/userlist', users);

Here is my userlist.js :

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

Here is my index.js:

var express = require('express');
var router = express.Router();

router.get('/userlist', function(req, res) {
    var db = req.db;
    var collection = db.get('usercollection');
    console.log(collection);
    collection.find({},{},function(e,docs){
        res.render('userlist', {
            "userlist" : docs
        });
    });
});

Here is userlist view :

extends layout

block content
    h1.
        User List
    ul
        each user, i in userlist
            li
                a(href="mailto:#{user.email}")= user.username

I appreciate if you tell me where the problem is or tell me how I can detect the problem. Thanks in advance.

EDIT:

In console I get this :

GET /userlist 500 296.280 ms - 1501

EDIT 2:
It gives me the error at this line :

var collection = db.get('usercollection');

EDIT 3:
In index.js, I see that

router.get('/userlist', function(req, res) {
    var db = req.db;

req.db is undefined. Why is it undefined? Do you have any idea?

Body:
Changing code to this worked:

app.use(function(req,res,next){
    req.db = db;
    next();
});
app.use('/', index);
app.use('/userlist', users);


问:
Store different templated classes in one container without losing information about it's type
I'm currently working on a project where a client part of my application has to be able to create custom templated classes on the server. The server part has to keep track of these created classes and has to remember the types with which the classes has been instantiated. The problem is, that there are around 36 different class-template-combinations that are valid in my application. I'm currently struggling to keep track of these different types in a collection without losing information about my instances.

I'm currently using something like this:

```<code>#include <memory>
#include <type_traits>
#include <vector>

enum class data_type : std::uint8_t {
    type_int = 1,
    type_float,
    type_double
};

enum class class_type : std:: uint8_t {
    type_A = 1,
    type_B
};

struct X {
    virtual data_type get_data_type() = 0;
    virtual class_type get_class_type() = 0;
};

template <typename T>
struct A : X {
    data_type get_data_type() override
    {
        if (std::is_same<T, int>::value) {
            return data_type::type_int;
        } else if (std::is_same<T, float>::value) {
            return data_type::type_float;
        } else if (std::is_same<T, double>::value) {
            return data_type::type_double;
        } else {
            /* ... */
        }
    }

    class_type get_class_type() override
    {
        return class_type::type_A;
    }
};

template <typename T>
struct B : X {
    data_type get_data_type() override
    {
        if (std::is_same<T, int>::value) {
            return data_type::type_int;
        } else if (std::is_same<T, float>::value) {
            return data_type::type_float;
        } else if (std::is_same<T, double>::value) {
            return data_type::type_double;
        } else {
            /* ... */
        }
    }

    class_type get_class_type() override
    {
        return class_type::type_B;
    }
};

struct Storage {

    template <typename T, template <typename> class Class>
    void create() {
        Class<T>* t = new Class<T>();
        _classes.push_back(std::unique_ptr<X>(t));
    }

    std::vector<std::unique_ptr<X>> _classes;
};
</code>```

but I'm wondering if this is the way to go or if there is a more elegant way. Here I would have to always switch through the enums to get the full type out of my Storage class, something like:

```<code>switch(_classes.front()->get_class_type()) {
case class_type::type_A:
{
    switch(_classes.front()->get_data_type()) {
    case data_type::type_int:
    {
         /* I finally know that it is A<int> */
    }
/* ... */
</code>```

Thanks in advance.

答:
As mentioned in the comments to the question, this is a viable approach that could help:

```<code>#include<vector>
#include<memory>

struct Counter {
    static int next() {
        static int v = 0;
        return v++;
    }
};

template<typename>
struct Type: Counter {
    static int value() {
        static const int v = Counter::next();
        return v;
    }
};

struct X {
    virtual int get_data_type() = 0;
    virtual int get_class_type() = 0;
};

template <typename T>
struct A : X {
    int get_data_type() override {
        return Type<T>::value();
    }

    int get_class_type() override {
        return Type<A<T>>::value();
    }
};

template <typename T>
struct B : X {
    int get_data_type() override {
        return Type<T>::value();
    }

    int get_class_type() override {
        return Type<B<T>>::value();
    }
};

struct Storage {
    template <typename T, template <typename> class Class>
    void create() {
        Class<T>* t = new Class<T>();
        _classes.push_back(std::unique_ptr<X>(t));
    }

    std::vector<std::unique_ptr<X>> _classes;
};

int main() {
    Storage s;
    s.create<int, A>();

    if(Type<int>::value() == s._classes.front()->get_class_type()) {
        //...
    };
}
</code>```

See it running on wandbox.

Body:
I'm currently working on a project where a client part of my application has to be able to create custom templated classes on the server. The server part has to keep track of these created classes and has to remember the types with which the classes has been instantiated. The problem is, that there are around 36 different class-template-combinations that are valid in my application. I'm currently struggling to keep track of these different types in a collection without losing information about my instances.

I'm currently using something like this:

#include <memory>
#include <type_traits>
#include <vector>

enum class data_type : std::uint8_t {
    type_int = 1,
    type_float,
    type_double
};

enum class class_type : std:: uint8_t {
    type_A = 1,
    type_B
};

struct X {
    virtual data_type get_data_type() = 0;
    virtual class_type get_class_type() = 0;
};

template <typename T>
struct A : X {
    data_type get_data_type() override
    {
        if (std::is_same<T, int>::value) {
            return data_type::type_int;
        } else if (std::is_same<T, float>::value) {
            return data_type::type_float;
        } else if (std::is_same<T, double>::value) {
            return data_type::type_double;
        } else {
            /* ... */
        }
    }

    class_type get_class_type() override
    {
        return class_type::type_A;
    }
};

template <typename T>
struct B : X {
    data_type get_data_type() override
    {
        if (std::is_same<T, int>::value) {
            return data_type::type_int;
        } else if (std::is_same<T, float>::value) {
            return data_type::type_float;
        } else if (std::is_same<T, double>::value) {
            return data_type::type_double;
        } else {
            /* ... */
        }
    }

    class_type get_class_type() override
    {
        return class_type::type_B;
    }
};

struct Storage {

    template <typename T, template <typename> class Class>
    void create() {
        Class<T>* t = new Class<T>();
        _classes.push_back(std::unique_ptr<X>(t));
    }

    std::vector<std::unique_ptr<X>> _classes;
};

but I'm wondering if this is the way to go or if there is a more elegant way. Here I would have to always switch through the enums to get the full type out of my Storage class, something like:

switch(_classes.front()->get_class_type()) {
case class_type::type_A:
{
    switch(_classes.front()->get_data_type()) {
    case data_type::type_int:
    {
         /* I finally know that it is A<int> */
    }
/* ... */

Thanks in advance.

Body:
As mentioned in the comments to the question, this is a viable approach that could help:

#include<vector>
#include<memory>

struct Counter {
    static int next() {
        static int v = 0;
        return v++;
    }
};

template<typename>
struct Type: Counter {
    static int value() {
        static const int v = Counter::next();
        return v;
    }
};

struct X {
    virtual int get_data_type() = 0;
    virtual int get_class_type() = 0;
};

template <typename T>
struct A : X {
    int get_data_type() override {
        return Type<T>::value();
    }

    int get_class_type() override {
        return Type<A<T>>::value();
    }
};

template <typename T>
struct B : X {
    int get_data_type() override {
        return Type<T>::value();
    }

    int get_class_type() override {
        return Type<B<T>>::value();
    }
};

struct Storage {
    template <typename T, template <typename> class Class>
    void create() {
        Class<T>* t = new Class<T>();
        _classes.push_back(std::unique_ptr<X>(t));
    }

    std::vector<std::unique_ptr<X>> _classes;
};

int main() {
    Storage s;
    s.create<int, A>();

    if(Type<int>::value() == s._classes.front()->get_class_type()) {
        //...
    };
}

See it running on wandbox.


问:
Firebase Phone Authentication credentials linking with Google login in firebase
I have implemented two step authentication in my app using firebase authentication in which I have used gmail, facebook or simple email login for authenticating. As digits phone verification has migrated to firebase i have implemented firebase phone authentication by linking the existing logged in account (facebook, gmail, or email) with phone authentication credentials. It works fine when used with facebook and email account. When user is logged in through google and tries to verify mobile through phone authentication this logs are printed :

signInWithCredential:failure

com.google.firebase.auth.FirebaseAuthUserCollisionException: An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.

Read this article. Is it the same issue as mentioned in the article?? Is there any solution for the same..

答:
After research over internet and in firebase documentation itself I found solution to this two step authentication in app using firebase auth.

```<code>firebaseAuth.getCurrentUser().updatePhoneNumber(credential).addOnCompleteListener(this, new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d(TAG, "signInWithCredential:success");

                Snackbar.make(findViewById(android.R.id.content), "Mobile Verified Successfully.",
                        Snackbar.LENGTH_SHORT).show();

            } else {
                Log.w(TAG, "signInWithCredential:failure", task.getException());
                if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                    //mVerificationField.setError("Invalid code.");
                    Snackbar.make(findViewById(android.R.id.content), "Invalid Code.",
                            Snackbar.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context,"signInWithCredential:failure"+task.getException(),
                            Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });
</code>```

Just pass the PhoneAuthCredential to above method and it will verify the phone assigns to your existing account. Make sure it is not used by any other account.

```<code>PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
</code>```

Body:
After research over internet and in firebase documentation itself I found solution to this two step authentication in app using firebase auth.

firebaseAuth.getCurrentUser().updatePhoneNumber(credential).addOnCompleteListener(this, new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d(TAG, "signInWithCredential:success");

                Snackbar.make(findViewById(android.R.id.content), "Mobile Verified Successfully.",
                        Snackbar.LENGTH_SHORT).show();

            } else {
                Log.w(TAG, "signInWithCredential:failure", task.getException());
                if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                    //mVerificationField.setError("Invalid code.");
                    Snackbar.make(findViewById(android.R.id.content), "Invalid Code.",
                            Snackbar.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context,"signInWithCredential:failure"+task.getException(),
                            Snackbar.LENGTH_LONG).show();
                }
            }
        }
    });

Just pass the PhoneAuthCredential to above method and it will verify the phone assigns to your existing account. Make sure it is not used by any other account.

PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);


问:
Best Practices for Integrating Hibernate 3.6 and Spring Framework 3?
Let me try this again since the first post got mangled... I've seen a few different methods for integrating Spring and Hibernate... What are the best practices for integrating the latest versions of Hibernate and Spring? What are the pros and cons to using the Spring Hibernate template? Any examples would be cool. Thx!</p>

答:
Are you looking more documentation than the one provided here from spring reference?

Here are the pros and cons of using a hibernate template: Spring hibernate template when to use and why?

Here you can get more examples with explanations.