问:
Usage of Oracle virtual column to increment value
This is an attempt to the test the usage of the VIRTUAL column with a function to increment the value in a column.

I am using a function which would return the last two digits of the current year, concatenated with a hyphen followed by the next max value from the table column which is defined as a virtual column.

When I insert records into the table, it does insert successfully. However, when I am querying records, I am getting the below error

ORA-00036: maximum number of recursive SQL levels (50) exceeded

My question is, does it possible to achieve to increment the values (custom increment with the using a VIRTUAL column or this attempt is trivial?

The below function is compiled first by uncommenting the commented part and upon the creation of the table, the first SQL block is commented and I use the second SQL block

Function

```<code>CREATE OR REPLACE FUNCTION test_func (
   p_empl_id    NUMBER,
   empl_nm      VARCHAR2)
   RETURN VARCHAR2
   DETERMINISTIC
IS
   return_value  VARCHAR2(32);
BEGIN
   return_value := NULL;

--    SELECT    TO_CHAR (SYSDATE, 'YY')
--          || '-'
--          || LPAD (
--                TO_CHAR (NVL (MAX (TO_NUMBER (SUBSTR (001, 5))), 0) + 1),
--                5,
--                '0') into return_value
--     FROM dual;

   SELECT    TO_CHAR (SYSDATE, 'YY')
          || '-'
          || LPAD (
                TO_CHAR (NVL (MAX (TO_NUMBER (SUBSTR (test_col, 5))), 0) + 1),
                5,
                '0')
     INTO return_value
     FROM test_table
    WHERE SUBSTR (test_col, 1, 2) = TO_CHAR (SYSDATE, 'YY');

   RETURN return_value;
END;
/
</code>```

Table Structure

```<code>CREATE TABLE test_table
(
   empl_id       NUMBER,
   empl_nm       VARCHAR2 (50),
   monthly_sal   NUMBER (10, 2),
   bonus         NUMBER (10, 2),
   test_col      AS (test_func (empl_id, empl_nm)) VIRTUAL
);
</code>```

Insert Statement

```<code>INSERT INTO test_table (empl_id,
                        empl_nm,
                        monthly_sal,
                        bonus)
   WITH data
        AS (SELECT 100 empl_id,
                   'AAA' empl_nm,
                   20000 monthly_sal,
                   3000 bonus
              FROM DUAL)
   SELECT *
     FROM data;
</code>```

I have tried using the below SQL using a sequence, however, the sequence value is getting inserted every time I execute a SQL statement from the table

```<code>SELECT    TO_CHAR (SYSDATE, 'YY')
       || '-'
       || '000'
       || test_virtual_sequence.NEXTVAL
  FROM DUAL;
</code>```

答:
"ORA-00036: maximum number of recursive SQL levels (50) exceeded"

Part of the reason you get that error is because your function is not deterministic. Deterministic means that the same inputs will produce the same output. But this is not true of your function: it makes no use of the input parameters whatsoever. Instead the output is governed my how many records have already been inserted.

But worse than that, your function is manipulating the virtual column. This is similar to the mutating table error on Triggers which query their owning Table.

"this is a certainly a test case to know the usages of virtual column"

Virtual columns are a way to implement a certain amount of denormalization without risking different views of the same data. For instance, on a ORDER_LINE Table we might have columns for ITEM_COST and LINE_QTY. But we need a column for LINE_TOTAL  (say to support a business rules on approvals). Before 11g we would have had to add a real column, and had the burden of maintaining it (probably in triggers or other procedural code). But now we can define it thus:

```<code>, line_qty as (item_cost * line_qty) virtual.
</code>```

Another example is the sort of key in your case. It is a smart key, which users love, but data modellers hate: there are multiple components, in this case the year the record was created and a serial number. These should properly be modelled as separate columns, so the components can be manipulated cleanly in SQL without the need for substr() etc. Also we need to enforce the smart key's format with check constraints.

But, our users love smart keys, because they've been using these identifiers for years. So how can we give them the familiar key yet have proper data integrity? With a virtual column:

```<code>SQL> create table t23 (
  2     created date not null
  3     , serial_no number not null
  4     , ref_no as (to_char(created, 'YYYY')||'-'||lpad(serial_no, 5, '0')) virtual
  5 );

Table created.

SQL> insert into t23 (created, serial_no) values (sysdate, s23.nextval);

1 row created.

SQL> insert into t23 (created, serial_no) values (sysdate, s23.nextval);

1 row created.

SQL> select * from t23
  2  /

CREATED    SERIAL_NO REF_NO
--------- ---------- ----------
04-JUN-17          3 2017-00003
04-JUN-17          4 2017-00004

SQL>
</code>```

One benefit of the virtual column is that it synchronizes automatically if we change a value it depends on:

```<code>SQL> update t23
  2  set created = add_months(created, -12)
  3  where serial_no = 3
  4  /

1 row updated.

SQL> select * from t23
  2  /

CREATED    SERIAL_NO REF_NO
--------- ---------- ----------
04-JUN-16          3 2016-00003
04-JUN-17          4 2017-00004

SQL>
</code>```

This much we could implement with a view over the table. But virtual columns have the benefit that we can build indexes and constraints on them:

```<code>SQL> alter table t23
  2      add constraint t23_ref_no unique (ref_no)
  3  /

Table altered.

SQL> insert into t23 (created, serial_no) values (sysdate, s23.nextval)
  2  /

1 row created.

SQL> insert into t23 (created, serial_no) values (sysdate, s23.currval);
insert into t23 (created, serial_no) values (sysdate, s23.currval)
*
ERROR at line 1:
ORA-00001: unique constraint (C.T23_REF_NO) violated

SQL>
</code>```

The other part of your question relates to incrementing a serial number with a fixed grouping (such as year). If you need to do this you can implement a code control table, such as I show in my answer to this other SO question.

Body:
This is an attempt to the test the usage of the VIRTUAL column with a function to increment the value in a column.

I am using a function which would return the last two digits of the current year, concatenated with a hyphen followed by the next max value from the table column which is defined as a virtual column.

When I insert records into the table, it does insert successfully. However, when I am querying records, I am getting the below error

ORA-00036: maximum number of recursive SQL levels (50) exceeded

My question is, does it possible to achieve to increment the values (custom increment with the using a VIRTUAL column or this attempt is trivial?

The below function is compiled first by uncommenting the commented part and upon the creation of the table, the first SQL block is commented and I use the second SQL block

Function

CREATE OR REPLACE FUNCTION test_func (
   p_empl_id    NUMBER,
   empl_nm      VARCHAR2)
   RETURN VARCHAR2
   DETERMINISTIC
IS
   return_value  VARCHAR2(32);
BEGIN
   return_value := NULL;

--    SELECT    TO_CHAR (SYSDATE, 'YY')
--          || '-'
--          || LPAD (
--                TO_CHAR (NVL (MAX (TO_NUMBER (SUBSTR (001, 5))), 0) + 1),
--                5,
--                '0') into return_value
--     FROM dual;

   SELECT    TO_CHAR (SYSDATE, 'YY')
          || '-'
          || LPAD (
                TO_CHAR (NVL (MAX (TO_NUMBER (SUBSTR (test_col, 5))), 0) + 1),
                5,
                '0')
     INTO return_value
     FROM test_table
    WHERE SUBSTR (test_col, 1, 2) = TO_CHAR (SYSDATE, 'YY');

   RETURN return_value;
END;
/

Table Structure

CREATE TABLE test_table
(
   empl_id       NUMBER,
   empl_nm       VARCHAR2 (50),
   monthly_sal   NUMBER (10, 2),
   bonus         NUMBER (10, 2),
   test_col      AS (test_func (empl_id, empl_nm)) VIRTUAL
);

Insert Statement

INSERT INTO test_table (empl_id,
                        empl_nm,
                        monthly_sal,
                        bonus)
   WITH data
        AS (SELECT 100 empl_id,
                   'AAA' empl_nm,
                   20000 monthly_sal,
                   3000 bonus
              FROM DUAL)
   SELECT *
     FROM data;

I have tried using the below SQL using a sequence, however, the sequence value is getting inserted every time I execute a SQL statement from the table

SELECT    TO_CHAR (SYSDATE, 'YY')
       || '-'
       || '000'
       || test_virtual_sequence.NEXTVAL
  FROM DUAL;

Body:
"ORA-00036: maximum number of recursive SQL levels (50) exceeded"

Part of the reason you get that error is because your function is not deterministic. Deterministic means that the same inputs will produce the same output. But this is not true of your function: it makes no use of the input parameters whatsoever. Instead the output is governed my how many records have already been inserted.

But worse than that, your function is manipulating the virtual column. This is similar to the mutating table error on Triggers which query their owning Table.

"this is a certainly a test case to know the usages of virtual column"

Virtual columns are a way to implement a certain amount of denormalization without risking different views of the same data. For instance, on a ORDER_LINE Table we might have columns for ITEM_COST and LINE_QTY. But we need a column for LINE_TOTAL  (say to support a business rules on approvals). Before 11g we would have had to add a real column, and had the burden of maintaining it (probably in triggers or other procedural code). But now we can define it thus:

, line_qty as (item_cost * line_qty) virtual.

Another example is the sort of key in your case. It is a smart key, which users love, but data modellers hate: there are multiple components, in this case the year the record was created and a serial number. These should properly be modelled as separate columns, so the components can be manipulated cleanly in SQL without the need for substr() etc. Also we need to enforce the smart key's format with check constraints.

But, our users love smart keys, because they've been using these identifiers for years. So how can we give them the familiar key yet have proper data integrity? With a virtual column:

SQL> create table t23 (
  2     created date not null
  3     , serial_no number not null
  4     , ref_no as (to_char(created, 'YYYY')||'-'||lpad(serial_no, 5, '0')) virtual
  5 );

Table created.

SQL> insert into t23 (created, serial_no) values (sysdate, s23.nextval);

1 row created.

SQL> insert into t23 (created, serial_no) values (sysdate, s23.nextval);

1 row created.

SQL> select * from t23
  2  /

CREATED    SERIAL_NO REF_NO
--------- ---------- ----------
04-JUN-17          3 2017-00003
04-JUN-17          4 2017-00004

SQL>

One benefit of the virtual column is that it synchronizes automatically if we change a value it depends on:

SQL> update t23
  2  set created = add_months(created, -12)
  3  where serial_no = 3
  4  /

1 row updated.

SQL> select * from t23
  2  /

CREATED    SERIAL_NO REF_NO
--------- ---------- ----------
04-JUN-16          3 2016-00003
04-JUN-17          4 2017-00004

SQL>

This much we could implement with a view over the table. But virtual columns have the benefit that we can build indexes and constraints on them:

SQL> alter table t23
  2      add constraint t23_ref_no unique (ref_no)
  3  /

Table altered.

SQL> insert into t23 (created, serial_no) values (sysdate, s23.nextval)
  2  /

1 row created.

SQL> insert into t23 (created, serial_no) values (sysdate, s23.currval);
insert into t23 (created, serial_no) values (sysdate, s23.currval)
*
ERROR at line 1:
ORA-00001: unique constraint (C.T23_REF_NO) violated

SQL>

The other part of your question relates to incrementing a serial number with a fixed grouping (such as year). If you need to do this you can implement a code control table, such as I show in my answer to this other SO question.


来源: stackexchange

问:
date convert from yyyy-mm-dd to yyy-mm-dd converting year to day
I have migrated data from old DB to new DB where date was taken as varchar, I have migrated data successfully but problem in date . In old DB the format of date is 25-01-02 where 25 is day 01 is month and 02 is year. But my script converted it to 2025-01-02. How can I fix it in my SQL?

```<code>TEST case:
DATE                  OUTPUT
2025-05-01            2001-05-25
2002-08-16            2016-08-02
2031-01-01            2001-01-31
2028-08-16            2016-08-28
2001-05-01            2001-05-01
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have migrated data from old DB to new DB where date was taken as varchar, I have migrated data successfully but problem in date . In old DB the format of date is 25-01-02 where 25 is day 01 is month and 02 is year. But my script converted it to 2025-01-02. How can I fix it in my SQL?

TEST case:
DATE                  OUTPUT
2025-05-01            2001-05-25
2002-08-16            2016-08-02
2031-01-01            2001-01-31
2028-08-16            2016-08-28
2001-05-01            2001-05-01

Body:
You can it easy convert with STR_TO_DATE like this:

SELECT STR_TO_DATE('25-01-02', '%d-%m-%y');

sample

mysql> SELECT STR_TO_DATE('25-01-02', '%d-%m-%y');
+-------------------------------------+
| STR_TO_DATE('25-01-02', '%d-%m-%y') |
+-------------------------------------+
| 2002-01-25                          |
+-------------------------------------+
1 row in set (0,00 sec)

mysql>

See the Manual: https://mariadb.com/kb/en/mariadb/str_to_date/


问:
Datagridview custom vscrollbar
I would like disable vertical scroll bar in datagridview and managing the scrolling using separate vscroll control. I am using c# 2.0. Any one can help....????</p>

答: You can set DataGridView.ScrollBars property to ScrollBars.None or ScrollBars.Horizontal (to have just horizontal scrollbar). This way the vertical scrollbar will not be displayed and you can use yours</p>

OwnerDisplayName: Anoop

ContentLicense: CC BY-SA 2.5

Title: Datagridview custom vscrollbar

LastEditorDisplayName: brendan


问:
Localhost email for e2e email test
I need to test that an email has been received and preferably have the ablity to access the mailbox by a rest api. Im looking for an open source solution that i can install which will give me a local email address then i will get the application to send the email to the address where i can validate that it was received. Any ideas on solutions that can be used for the full end to end testing of emails would be appreciated. I know there are some internet based solutions out there but being a test environment the preference would be for a local solution.

Thanks

答:
There is smtp4dev to emulate received email. It listens port 25 but you can setup another port number.

Alternatively, you can use papercut.

Title: Localhost email for e2e email test

ContentLicense: CC BY-SA 4.0


问:
Unusually high rate of corrupt JSON responses from web server, causes and solutions?
I'm building a REST based web service which will serve a couple hundreds clients that will upload/request little bursts of information throughout the day and make one larger cache update (about 100-200kb) once a day.

While testing the large update on the production machine (a linux virtual machine in the cloud running Apache/PHP) I discovered to my utter dismay that data gets to client corrupted (i.e. with one or more wrong character) literally MOST of the times.

Example of corrupted JSON, parser says SyntaxError: JSON.parse: expected ':' after property name in object at line 1 column 81998 of the JSON data:

```<code>"nascita":"1940-12-17","attiva":true,","cognome":"MILANI"
</code>```

should be

```<code>"nascita":"1940-12-17","attiva":"true","cognome":"MILANI"
</code>```

This is the HTTP Header of the answer

```<code>Connection  Keep-Alive
Content-Type    application/json
Date    Fri, 02 Jun 2017 16:59:39 GMT
Keep-Alive  timeout=5, max=100
Server  Apache/2.4.18 (Ubuntu)
Transfer-Encoding   chunked
</code>```

I am certainly not an expert when it comes to networking but I used to think that such occurrences, failures of both IP and TCP error detection, were extremely rare. (I found this post interesting:
 Can a TCP checksum produce a false positive? If yes, how is this dealt with?)

So... what's going here? Am I missing something?

I started to think of possible solutions.

The quickest I could think of was using HTTP compression: if the client is unable to decompress the content (which is very likely in case of data corruption) then I can ask for the content again.
I enabled that on Apache and, to my surprise, all responses completed with valid data.
Could it be that web browsers (I'm using good old Firefox for testing the web service) have some built-in mechanism for re-requesting corrupt compressed data? Or MAYBE the smaller, less regular nature of compressed data makes TCP/IP mistakes less likely??

The other quick solution that came to my mind was to calculate a checksum of the content, something I could do for smaller requests that don't really benefit from compression.
I am trying to figure out if and how the Content-MD5 field in HTTP could help me... Web browser seems to ignore it, so I guess i will have to compute and compare it explicitely on my client...

Using TLS may be another good idea, possibly the best.

Or again.... am I missing something HUGE?
Like, I don't know, for some reason my Apache is using UDP??

答:
All these errors didn't make any sense.

So I got Wireshark to capture all TCP segments incoming from the web server and see what could be wrong with them. Again, Firefox showed a mistake at a random column but.... it turned out that there was no such error in the corresponding TCP segment!

I then tried Chrome (which doesn't come with a built in parser), installed JSONView extension and everything there was fine! Did the the same with Firefox, installed JSONView, and.. no errors!

Turns out there's some kind of bug with the latest Firefox built-in JSON viewer. I'm running 53.0.3 right now.

Body:
I'm building a REST based web service which will serve a couple hundreds clients that will upload/request little bursts of information throughout the day and make one larger cache update (about 100-200kb) once a day.

While testing the large update on the production machine (a linux virtual machine in the cloud running Apache/PHP) I discovered to my utter dismay that data gets to client corrupted (i.e. with one or more wrong character) literally MOST of the times.

Example of corrupted JSON, parser says SyntaxError: JSON.parse: expected ':' after property name in object at line 1 column 81998 of the JSON data:

"nascita":"1940-12-17","attiva":true,","cognome":"MILANI"

should be

"nascita":"1940-12-17","attiva":"true","cognome":"MILANI"

This is the HTTP Header of the answer

Connection  Keep-Alive
Content-Type    application/json
Date    Fri, 02 Jun 2017 16:59:39 GMT
Keep-Alive  timeout=5, max=100
Server  Apache/2.4.18 (Ubuntu)
Transfer-Encoding   chunked

I am certainly not an expert when it comes to networking but I used to think that such occurrences, failures of both IP and TCP error detection, were extremely rare. (I found this post interesting:
 Can a TCP checksum produce a false positive? If yes, how is this dealt with?)

So... what's going here? Am I missing something?

I started to think of possible solutions.

The quickest I could think of was using HTTP compression: if the client is unable to decompress the content (which is very likely in case of data corruption) then I can ask for the content again.
I enabled that on Apache and, to my surprise, all responses completed with valid data.
Could it be that web browsers (I'm using good old Firefox for testing the web service) have some built-in mechanism for re-requesting corrupt compressed data? Or MAYBE the smaller, less regular nature of compressed data makes TCP/IP mistakes less likely??

The other quick solution that came to my mind was to calculate a checksum of the content, something I could do for smaller requests that don't really benefit from compression.
I am trying to figure out if and how the Content-MD5 field in HTTP could help me... Web browser seems to ignore it, so I guess i will have to compute and compare it explicitely on my client...

Using TLS may be another good idea, possibly the best.

Or again.... am I missing something HUGE?
Like, I don't know, for some reason my Apache is using UDP??


问:
version code not found in android studio canary -2

when instant run apply i am getting following in android studio 3.0 canary-2

```<code>Error:E:\PublicServer_Share\Extra\app\build\intermediates\instant-run
support\debug\slice_2\AndroidManifest.xml:2 attribute 'android:versionCode'
not found
Error:failed processing manifest
Error:E:\PublicServer_Share\Extra\app\build\intermediates\instant-run-
support\debug\slice_9\AndroidManifest.xml:2 attribute 'android:versionCode'
not found
Error:failed processing manifest
Error:Execution failed for task
':app:transformDexWithInstantRunSlicesApkForDebug'.
com.android.ide.common.process.ProcessException: Failed to execute aapt
</code>```

答: Run Gradle->Clean and try again

Body:
when instant run apply i am getting following in android studio 3.0 canary-2

Error:E:\PublicServer_Share\Extra\app\build\intermediates\instant-run
support\debug\slice_2\AndroidManifest.xml:2 attribute 'android:versionCode'
not found
Error:failed processing manifest
Error:E:\PublicServer_Share\Extra\app\build\intermediates\instant-run-
support\debug\slice_9\AndroidManifest.xml:2 attribute 'android:versionCode'
not found
Error:failed processing manifest
Error:Execution failed for task
':app:transformDexWithInstantRunSlicesApkForDebug'.
com.android.ide.common.process.ProcessException: Failed to execute aapt

Body: Run Gradle->Clean and try again


问:
How to start and stop application pool in IIS using powershell script
I want to start and stop application pool in IIS using powershell script. I had try to write the script but i didn't get this.</p>

答:
You can use this

if your use (PowerShell 2.0) import WebAdministration module

```<code>import-module WebAdministration
</code>```

Please check the state of the application pool before.
If the application pool is already stopped you get an exception.

Stop application pool:

```<code>$applicationPoolName = 'DefaultAppPool'

if((Get-WebAppPoolState -Name $applicationPoolName).Value -ne 'Stopped'){
    Write-Output ('Stopping Application Pool: {0}' -f $applicationPoolName)
    Stop-WebAppPool -Name $applicationPoolName
}
</code>```

Start application pool:

```<code>if((Get-WebAppPoolState -Name $applicationPoolName).Value -ne 'Started'){
    Write-Output ('Starting Application Pool: {0}' -f $applicationPoolName)
    Start-WebAppPool -Name $applicationPoolName
}
</code>```

Permissions: You have to be a member of the "IIS Admins" group.

Body:
You can use this

if your use (PowerShell 2.0) import WebAdministration module

import-module WebAdministration

Please check the state of the application pool before.
If the application pool is already stopped you get an exception.

Stop application pool:

$applicationPoolName = 'DefaultAppPool'

if((Get-WebAppPoolState -Name $applicationPoolName).Value -ne 'Stopped'){
    Write-Output ('Stopping Application Pool: {0}' -f $applicationPoolName)
    Stop-WebAppPool -Name $applicationPoolName
}

Start application pool:

if((Get-WebAppPoolState -Name $applicationPoolName).Value -ne 'Started'){
    Write-Output ('Starting Application Pool: {0}' -f $applicationPoolName)
    Start-WebAppPool -Name $applicationPoolName
}

Permissions: You have to be a member of the "IIS Admins" group.


问:
Execute Azure Automation Runbooks Across Tenants
I am able to execute Runbooks within my Azure tenant/subscription, but would like to use a single Azure Automation Account in my tenant to execute Runbooks against other tenants and their subscriptions.

I have found this article for running against multiple subscriptions, but is it possible to have a centralized Azure Automation Account in one tenant that can connect and execute against other tenants and their subscriptions?

https://blogs.technet.microsoft.com/knightly/2017/05/26/using-azure-automation-with-multiple-subscriptions/

答:
So i stumbled upon this article which offers a guidance how to do what you want:

https://blogs.technet.microsoft.com/knightly/2017/05/26/using-azure-automation-with-multiple-subscriptions/

basically what I said, get appId and grant it permissions to perform actions on other subs


问:
Error in arff module
I am working in Python 2.7.12 in linux. I have installed the liac-arff and arff modules for the machine. The following line throws an error.

```<code>arff_frame = arff.load(
        open(filename, 'r'), encode_nominal=encode_nominal, return_type=arff.DENSE)
</code>```

The error is, AttributeError: 'module' object has no attribute 'DENSE'
Any suggestions about how to address this error?

答:
The documentation for liac-arff at https://pythonhosted.org/liac-arff/ gives the signature of the function as

```<code>arff.load(fp, encode_nominal=False, return_type=0)
</code>```

It looks like you have this version in your Python 2 environment. That is the version you get if you do pip install arff.

Title: Error in arff module

Body:
I am working in Python 2.7.12 in linux. I have installed the liac-arff and arff modules for the machine. The following line throws an error.

arff_frame = arff.load(
        open(filename, 'r'), encode_nominal=encode_nominal, return_type=arff.DENSE)

The error is, AttributeError: 'module' object has no attribute 'DENSE'
Any suggestions about how to address this error?

Body:
The documentation for liac-arff at https://pythonhosted.org/liac-arff/ gives the signature of the function as

arff.load(fp, encode_nominal=False, return_type=0)

It looks like you have this version in your Python 2 environment. That is the version you get if you do pip install arff.


问:
How to connect to a SSL encrypted OData Feed
I try to add a connected Service in Visual Studio (UWP-App) to read from my Odata feed. The problem is that the odata service is SSL encrypted and visual studio tells me that he cannot access the feed for some reason.

答:
For now it doesn't seem to be possible to connect to a SSL-encrypted OData-feed in an UWP-App.

So i created my own WCF-Service, which I host on an IIS, to gather my informations directly from an SQL-server

Here are some useful link collections about  creating a WCF Service, hosting that on an IIS and a UWP sample project:

How to build a WCF

host WCF on IIS

UWP sample project


问:
How can I build expression c=>c.workers.any(o=>o.code=='XXX' || c.name=='XXX') dynamically
I learn how to build simple expression which like

```<code>c=>c.code=='XXX';
</code>```

I create these expression by method below:

```<code>public static Expression<Func<T, bool>> BuildStringEqualLambda(string propertyName, string propertyValue)
{
    ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");
    Expression propertyExp = parameterExp;
    foreach (var property in propertyName.Split('.'))
    {
        propertyExp = Expression.PropertyOrField(propertyExp, property);
    }
    Expression right = Expression.Constant(propertyValue);
    Expression e1 = Expression.Equal(propertyExp, right);
    return Expression.Lambda<Func<T, bool>>(e1, new ParameterExpression[] { parameterExp });
}
</code>```

I think I can build expression

```<code>o=>o.code=='XXX' || c.name=='XXX'
</code>```

But I don't know how can I build method Any.

Thanks

答:
It should be something like:

```<code>public static Expression<Func<T, bool>> BuildStringEqualLambda<T>(params Tuple<string, string>[] propertyNameValues)
{
    if (propertyNameValues == null || propertyNameValues.Length == 0)
    {
        throw new ArgumentException(nameof(propertyNameValues));
    }

    ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");

    Expression body = null;

    foreach (var propertyNameValue in propertyNameValues)
    {
        Expression propertyExp = parameterExp;

        foreach (var property in propertyNameValue.Item1.Split('.'))
        {
            propertyExp = Expression.PropertyOrField(propertyExp, property);
        }

        Expression right = Expression.Constant(propertyNameValue.Item2);
        Expression eq = Expression.Equal(propertyExp, right);

        body = body == null ? eq : Expression.OrElse(body, eq);
    }

    return Expression.Lambda<Func<T, bool>>(body, new ParameterExpression[] { parameterExp });
}
</code>```

You can probably use some funny LINQ with Aggregate to reduce the number of lines, but it would be undebuggable.

In the end you use the Expression.OrElse (not the Expression.Or that is |!) and you handle the first element case.

Use it like:

```<code>var exp = BuildStringEqualLambda(
    Tuple.Create("prop1", "value1"),
    Tuple.Create("prop2", "value2"),
    Tuple.Create("prop3", "value3")
);
</code>```

Using some LINQ and Aggregate (for those who can't live without LINQing everything) (note that while I wouldn't ever use the LINQed version of the code... It is quite unreadable... Enumerable.Aggregate is "terrible" ):

```<code>public static Expression<Func<T, bool>> BuildStringEqualLambda<T>(params Tuple<string, string>[] propertyNameValues)
{
    if (propertyNameValues == null || propertyNameValues.Length == 0)
    {
        throw new ArgumentException(nameof(propertyNameValues));
    }

    ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");

    Expression body = propertyNameValues
        .Select(x => BuildEqualityExpression<T>(parameterExp, x.Item1, x.Item2))
        .Aggregate((acc, x) => Expression.OrElse(acc, x));

    return Expression.Lambda<Func<T, bool>>(body, new ParameterExpression[] { parameterExp });
}

private static Expression BuildEqualityExpression<T>(ParameterExpression parameterExp, string propertyName, string propertyValue)
{
    Expression propertyExp = propertyName
        .Split('.')
        .Aggregate((Expression)parameterExp, (acc, x) => Expression.PropertyOrField(acc, x));

    Expression right = Expression.Constant(propertyValue);
    Expression eq = Expression.Equal(propertyExp, right);
    return eq;
}
</code>```

Body:
I learn how to build simple expression which like

c=>c.code=='XXX';

I create these expression by method below:

public static Expression<Func<T, bool>> BuildStringEqualLambda(string propertyName, string propertyValue)
{
    ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");
    Expression propertyExp = parameterExp;
    foreach (var property in propertyName.Split('.'))
    {
        propertyExp = Expression.PropertyOrField(propertyExp, property);
    }
    Expression right = Expression.Constant(propertyValue);
    Expression e1 = Expression.Equal(propertyExp, right);
    return Expression.Lambda<Func<T, bool>>(e1, new ParameterExpression[] { parameterExp });
}

I think I can build expression

o=>o.code=='XXX' || c.name=='XXX'

But I don't know how can I build method Any.

Thanks

Body:
It should be something like:

public static Expression<Func<T, bool>> BuildStringEqualLambda<T>(params Tuple<string, string>[] propertyNameValues)
{
    if (propertyNameValues == null || propertyNameValues.Length == 0)
    {
        throw new ArgumentException(nameof(propertyNameValues));
    }

    ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");

    Expression body = null;

    foreach (var propertyNameValue in propertyNameValues)
    {
        Expression propertyExp = parameterExp;

        foreach (var property in propertyNameValue.Item1.Split('.'))
        {
            propertyExp = Expression.PropertyOrField(propertyExp, property);
        }

        Expression right = Expression.Constant(propertyNameValue.Item2);
        Expression eq = Expression.Equal(propertyExp, right);

        body = body == null ? eq : Expression.OrElse(body, eq);
    }

    return Expression.Lambda<Func<T, bool>>(body, new ParameterExpression[] { parameterExp });
}

You can probably use some funny LINQ with Aggregate to reduce the number of lines, but it would be undebuggable.

In the end you use the Expression.OrElse (not the Expression.Or that is |!) and you handle the first element case.

Use it like:

var exp = BuildStringEqualLambda(
    Tuple.Create("prop1", "value1"),
    Tuple.Create("prop2", "value2"),
    Tuple.Create("prop3", "value3")
);

Using some LINQ and Aggregate (for those who can't live without LINQing everything) (note that while I wouldn't ever use the LINQed version of the code... It is quite unreadable... Enumerable.Aggregate is "terrible" ):

public static Expression<Func<T, bool>> BuildStringEqualLambda<T>(params Tuple<string, string>[] propertyNameValues)
{
    if (propertyNameValues == null || propertyNameValues.Length == 0)
    {
        throw new ArgumentException(nameof(propertyNameValues));
    }

    ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");

    Expression body = propertyNameValues
        .Select(x => BuildEqualityExpression<T>(parameterExp, x.Item1, x.Item2))
        .Aggregate((acc, x) => Expression.OrElse(acc, x));

    return Expression.Lambda<Func<T, bool>>(body, new ParameterExpression[] { parameterExp });
}

private static Expression BuildEqualityExpression<T>(ParameterExpression parameterExp, string propertyName, string propertyValue)
{
    Expression propertyExp = propertyName
        .Split('.')
        .Aggregate((Expression)parameterExp, (acc, x) => Expression.PropertyOrField(acc, x));

    Expression right = Expression.Constant(propertyValue);
    Expression eq = Expression.Equal(propertyExp, right);
    return eq;
}


问:
Sending mail using Gmail - exception "The SMTP server requires a secure connection"
Aim: send mail with random number if user need to reset or forgot password

Till now what i have done is

View

```<code>    <form id="form1" runat="server">
Email Address:
<asp:TextBox ID="txtEmail" runat="server" Width="250" />
<br />
<asp:Label ID="lblMessage" runat="server" />
<br />
<asp:Button Text="Send" runat="server" OnClick="Button1_Click" />
</form>
</code>```

Source code

```<code>    protected void Button1_Click(object sender, EventArgs e)
            {
                string username = string.Empty;
                string password = string.Empty;
                string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT Name, [Password] FROM tbl_Detailstbl WHERE Email_Id = @Email"))
                    {
                        cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                        cmd.Connection = con;
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            if (sdr.Read())
                            {
                                username = sdr["Name"].ToString();
                                password = sdr["Password"].ToString();
                            }
                        }
                        con.Close();
                    }
                }
                if (!string.IsNullOrEmpty(password))
                {
                    MailMessage mm = new MailMessage("xxxxxxxxx@gmail.com", txtEmail.Text.Trim());
                    mm.Subject = "Password Recovery";
                    mm.Body = string.Format("Hi {0},<br /><br />Your password is {1}.<br /><br />Thank You.", username, password);
                    mm.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    NetworkCredential NetworkCred = new NetworkCredential();
                    NetworkCred.UserName = "xxxxxx@gmail.com";
                    NetworkCred.Password = "asfsdfg";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = NetworkCred;
                    smtp.Port = 587;
                    smtp.Send(mm);
                    lblMessage.ForeColor = Color.Green;
                    lblMessage.Text = "Password has been sent to your email address.";
                }
                else
                {
                    lblMessage.ForeColor = Color.Red;
                    lblMessage.Text = "This email address does not match our records.";
                }

   }
</code>```

An exception of type 'System.Net.Mail.SmtpException' occurred in
  System.dll but was not handled in user code  Additional information:
  The SMTP server requires a secure connection or the client was not
  authenticated. The server response was: 5.5.1 Authentication Required.

Please give me a fine solution for this error

答:
Goto
https://google.com/settings/security/lesssecureapps

And Turn On "Allow less secure apps: ON"

Body:
Aim: send mail with random number if user need to reset or forgot password

Till now what i have done is

View

    <form id="form1" runat="server">
Email Address:
<asp:TextBox ID="txtEmail" runat="server" Width="250" />

<asp:Label ID="lblMessage" runat="server" />

<asp:Button Text="Send" runat="server" OnClick="Button1_Click" />
</form>

Source code

    protected void Button1_Click(object sender, EventArgs e)
            {
                string username = string.Empty;
                string password = string.Empty;
                string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT Name, [Password] FROM tbl_Detailstbl WHERE Email_Id = @Email"))
                    {
                        cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                        cmd.Connection = con;
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            if (sdr.Read())
                            {
                                username = sdr["Name"].ToString();
                                password = sdr["Password"].ToString();
                            }
                        }
                        con.Close();
                    }
                }
                if (!string.IsNullOrEmpty(password))
                {
                    MailMessage mm = new MailMessage("xxxxxxxxx@gmail.com", txtEmail.Text.Trim());
                    mm.Subject = "Password Recovery";
                    mm.Body = string.Format("Hi {0},

Your password is {1}.

Thank You.", username, password);
                    mm.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    NetworkCredential NetworkCred = new NetworkCredential();
                    NetworkCred.UserName = "xxxxxx@gmail.com";
                    NetworkCred.Password = "asfsdfg";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = NetworkCred;
                    smtp.Port = 587;
                    smtp.Send(mm);
                    lblMessage.ForeColor = Color.Green;
                    lblMessage.Text = "Password has been sent to your email address.";
                }
                else
                {
                    lblMessage.ForeColor = Color.Red;
                    lblMessage.Text = "This email address does not match our records.";
                }

   }

An exception of type 'System.Net.Mail.SmtpException' occurred in
  System.dll but was not handled in user code  Additional information:
  The SMTP server requires a secure connection or the client was not
  authenticated. The server response was: 5.5.1 Authentication Required.

Please give me a fine solution for this error


问:
React AddItem to list in another component
I would like to use AddItem to add items to a list in another component. However, I keep getting undefined.

How do I correctly add an item to a list?

I've put it inside a CodeSandbox too: https://codesandbox.io/s/Mjjrm3zrO

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      movies: [x.movies],
    };
  }
  render() {
    return (
      <div>
        <CreateNew addItem={item => this.setState({ movie: [item].concat(this.state.movie) })} />
          {x.movies.map(movie => (
            <Result key={movie.id} result={movie} addItem={item => this.setState({ genres: [item].concat(this.state.genres) })} />
          ))}
      </div>
    );
  }
}

class CreateNew extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      genres: '',
    };
  }
  handleSubmit1 = (e, value) => {
    e.preventDefault();
    this.props.addItem(this.state.value)
    console.log(this.props.item);
  };
  onChange = e => {
    this.setState({ value: {'name': e.target.value}, genres: [{ name: 'Test', type: 1 }, { name: 'Foo', type: 10 }] });
    console.log(this.state.value);
  };
  render() {
    const { value, genres } = this.props;
    return (
      <form onSubmit={this.handleSubmit1}>
        Add a new movie
        <input onChange={this.onChange} type="text" />
        <button type="submit">Save</button>
      </form>
    );
  }
}

class Result extends React.Component {
  render() {
    const { result } = this.props;

    return (
      <div>
        <li>
          {result.name} {' '}
          ({result.genres.map(x => x.name).join(', ')}){' '}
        </li>

      </div>
    );
  }
}
</code>```

答:
Changes:

1. Instead of sending only name from child component send the whole state variable that will contain name and genres.

```<code>handleSubmit1 = (e, value) => {
    e.preventDefault();
    this.props.addItem(this.state)
};
</code>```

2. You are storing the initial value movies from json to state variable so use that state variable to create the ui, because you are updating the state variable once you adding any new item, so if you use initial json to create ui then new item will not reflect in ui.

```<code>{this.state.movies.map(movie => (
    <Result key={movie.id} result={movie} />
))}
</code>```

3. Update the state variable movies like this:

```<code><CreateNew addItem={item => this.setState({ movies: [{name: item.value.name, genres: item.genres}].concat(this.state.movies) })} />
</code>```

Check the working solution: https://codesandbox.io/s/3nD0RgRp

Body:
I would like to use AddItem to add items to a list in another component. However, I keep getting undefined.

How do I correctly add an item to a list?

I've put it inside a CodeSandbox too: https://codesandbox.io/s/Mjjrm3zrO

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      movies: [x.movies],
    };
  }
  render() {
    return (

        <CreateNew addItem={item => this.setState({ movie: [item].concat(this.state.movie) })} />
          {x.movies.map(movie => (
            <Result key={movie.id} result={movie} addItem={item => this.setState({ genres: [item].concat(this.state.genres) })} />
          ))}

    );
  }
}

class CreateNew extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      genres: '',
    };
  }
  handleSubmit1 = (e, value) => {
    e.preventDefault();
    this.props.addItem(this.state.value)
    console.log(this.props.item);
  };
  onChange = e => {
    this.setState({ value: {'name': e.target.value}, genres: [{ name: 'Test', type: 1 }, { name: 'Foo', type: 10 }] });
    console.log(this.state.value);
  };
  render() {
    const { value, genres } = this.props;
    return (
      <form onSubmit={this.handleSubmit1}>
        Add a new movie
        <input onChange={this.onChange} type="text" />
        <button type="submit">Save</button>
      </form>
    );
  }
}

class Result extends React.Component {
  render() {
    const { result } = this.props;

    return (

          {result.name} {' '}
          ({result.genres.map(x => x.name).join(', ')}){' '}

    );
  }
}

Body:
Changes:

1. Instead of sending only name from child component send the whole state variable that will contain name and genres.

handleSubmit1 = (e, value) => {
    e.preventDefault();
    this.props.addItem(this.state)
};

2. You are storing the initial value movies from json to state variable so use that state variable to create the ui, because you are updating the state variable once you adding any new item, so if you use initial json to create ui then new item will not reflect in ui.

{this.state.movies.map(movie => (
    <Result key={movie.id} result={movie} />
))}

3. Update the state variable movies like this:

<CreateNew addItem={item => this.setState({ movies: [{name: item.value.name, genres: item.genres}].concat(this.state.movies) })} />

Check the working solution: https://codesandbox.io/s/3nD0RgRp


问:
JavaFx Table View hidden the String value
My TableView doesn't show any String, but it has Clickable (Exist, but shows no words).

Database used: MySQL.

Full Controller:

```<code>package application.BookList;

import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

import java.net.URL;
import java.sql.*;
import java.util.Observable;
import java.util.ResourceBundle;

public class Controller implements Initializable{
    String theConnectionDriver = "com.mysql.jdbc.Driver";
    private String theConnectionString = "jdbc:mysql://localhost/libraryassistant";
    private String theServerUsername = "root";
    private String theServerPassword = "";

    @FXML TableView<Book> TableView_BookList;
    @FXML TableColumn<Book, String> TableColumn_Title;
    @FXML TableColumn<Book, String> TableColumn_Author;
    @FXML TableColumn<Book, String> TableColumn_Publisher;
    @FXML TableColumn<Book, Boolean> TableColumn_Available;

    ObservableList<Book> thisObservableList = FXCollections.observableArrayList();

    @Override public void initialize(URL thisURL, ResourceBundle thisResourceBundle) {
        TableColumn_Title.setCellValueFactory(new PropertyValueFactory<>("Title"));
        try {
            System.out.println("Retrieving data from database...");
            Class.forName(theConnectionDriver);
            Connection thisConnection;
            thisConnection = DriverManager.getConnection(theConnectionString, theServerUsername, theServerPassword);
            Statement thisStatement;
            thisStatement = thisConnection.createStatement();
            ResultSet thisResultSet;
            thisResultSet = thisStatement.executeQuery("SELECT * FROM `Book`");
            while(thisResultSet.next()) {
                String BookTitle =  thisResultSet.getString("Title");
                String BookAuthor =  thisResultSet.getString("Author");
                String BookPublisher =  thisResultSet.getString("Publisher");
                Boolean BookAvailable =  thisResultSet.getBoolean("Available");
                thisObservableList.add(new Book(BookTitle, BookAuthor, BookPublisher, BookAvailable));
                System.out.println(BookTitle);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        TableView_BookList.getItems().setAll(thisObservableList);
    }

    public static class Book {
        private final SimpleStringProperty BookTitle;
        private final SimpleStringProperty BookAuthor;
        private final SimpleStringProperty BookPublisher;
        private final SimpleBooleanProperty BookAvailable;

        private Book(String BookTitle, String BookAuthor, String BookPublisher, Boolean BookAvailable) {
            this.BookTitle = new SimpleStringProperty(BookTitle);
            this.BookAuthor = new SimpleStringProperty(BookAuthor);
            this.BookPublisher = new SimpleStringProperty(BookPublisher);
            this.BookAvailable = new SimpleBooleanProperty(BookAvailable);
        }

        public String getBookTitle() {
            return BookTitle.get();
        }

        public String getBookAuthor() {
            return BookAuthor.get();
        }

        public String getBookPublisher() {
            return BookPublisher.get();
        }

        public Boolean getBookAvailable() {
            return BookAvailable.get();
        }
    }
}
</code>```

Full FXML:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="512.0" prefWidth="768.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.BookList.Controller">
   <children>
      <TableView fx:id="TableView_BookList" layoutX="14.0" layoutY="256.0" prefHeight="237.0" prefWidth="479.0" AnchorPane.bottomAnchor="16.0" AnchorPane.leftAnchor="16.0" AnchorPane.rightAnchor="16.0" AnchorPane.topAnchor="128.0">
        <columns>
          <TableColumn fx:id="TableColumn_Title" maxWidth="256.0" minWidth="256.0" prefWidth="-1.0" resizable="false" text="Title" />
          <TableColumn fx:id="TableColumn_Author" maxWidth="256.0" minWidth="256.0" prefWidth="-1.0" resizable="false" text="Author" />
            <TableColumn fx:id="TableColumn_Publisher" maxWidth="128.0" minWidth="128.0" prefWidth="-1.0" resizable="false" text="Publisher" />
            <TableColumn fx:id="TableColumn_Available" maxWidth="64.0" minWidth="64.0" prefWidth="-1.0" resizable="false" text="Available" />
        </columns>
         <columnResizePolicy>
            <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
         </columnResizePolicy>
      </TableView>
   </children>
</AnchorPane>
</code>```

System.out.println Debug Message:

As you can see, "Legend of None, My, Ada" is the Book Title, it does show the value in console yet I have clickable rows, but it doesn't show anything (words).

Clickable rows has the same amount as the data in database.

答: As the code is incomplete, can't find the issue. Try debugging it whether the String values BookTitle , BookAuthor, BookPublisher  and BookAvailable  are getting retrieved from the database else print those values and check.

Body:
My TableView doesn't show any String, but it has Clickable (Exist, but shows no words).

Database used: MySQL.

Full Controller:

package application.BookList;

import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

import java.net.URL;
import java.sql.*;
import java.util.Observable;
import java.util.ResourceBundle;

public class Controller implements Initializable{
    String theConnectionDriver = "com.mysql.jdbc.Driver";
    private String theConnectionString = "jdbc:mysql://localhost/libraryassistant";
    private String theServerUsername = "root";
    private String theServerPassword = "";

    @FXML TableView<Book> TableView_BookList;
    @FXML TableColumn<Book, String> TableColumn_Title;
    @FXML TableColumn<Book, String> TableColumn_Author;
    @FXML TableColumn<Book, String> TableColumn_Publisher;
    @FXML TableColumn<Book, Boolean> TableColumn_Available;

    ObservableList<Book> thisObservableList = FXCollections.observableArrayList();

    @Override public void initialize(URL thisURL, ResourceBundle thisResourceBundle) {
        TableColumn_Title.setCellValueFactory(new PropertyValueFactory<>("Title"));
        try {
            System.out.println("Retrieving data from database...");
            Class.forName(theConnectionDriver);
            Connection thisConnection;
            thisConnection = DriverManager.getConnection(theConnectionString, theServerUsername, theServerPassword);
            Statement thisStatement;
            thisStatement = thisConnection.createStatement();
            ResultSet thisResultSet;
            thisResultSet = thisStatement.executeQuery("SELECT * FROM `Book`");
            while(thisResultSet.next()) {
                String BookTitle =  thisResultSet.getString("Title");
                String BookAuthor =  thisResultSet.getString("Author");
                String BookPublisher =  thisResultSet.getString("Publisher");
                Boolean BookAvailable =  thisResultSet.getBoolean("Available");
                thisObservableList.add(new Book(BookTitle, BookAuthor, BookPublisher, BookAvailable));
                System.out.println(BookTitle);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        TableView_BookList.getItems().setAll(thisObservableList);
    }

    public static class Book {
        private final SimpleStringProperty BookTitle;
        private final SimpleStringProperty BookAuthor;
        private final SimpleStringProperty BookPublisher;
        private final SimpleBooleanProperty BookAvailable;

        private Book(String BookTitle, String BookAuthor, String BookPublisher, Boolean BookAvailable) {
            this.BookTitle = new SimpleStringProperty(BookTitle);
            this.BookAuthor = new SimpleStringProperty(BookAuthor);
            this.BookPublisher = new SimpleStringProperty(BookPublisher);
            this.BookAvailable = new SimpleBooleanProperty(BookAvailable);
        }

        public String getBookTitle() {
            return BookTitle.get();
        }

        public String getBookAuthor() {
            return BookAuthor.get();
        }

        public String getBookPublisher() {
            return BookPublisher.get();
        }

        public Boolean getBookAvailable() {
            return BookAvailable.get();
        }
    }
}

Full FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="512.0" prefWidth="768.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.BookList.Controller">
   <children>
      <TableView fx:id="TableView_BookList" layoutX="14.0" layoutY="256.0" prefHeight="237.0" prefWidth="479.0" AnchorPane.bottomAnchor="16.0" AnchorPane.leftAnchor="16.0" AnchorPane.rightAnchor="16.0" AnchorPane.topAnchor="128.0">
        <columns>
          <TableColumn fx:id="TableColumn_Title" maxWidth="256.0" minWidth="256.0" prefWidth="-1.0" resizable="false" text="Title" />
          <TableColumn fx:id="TableColumn_Author" maxWidth="256.0" minWidth="256.0" prefWidth="-1.0" resizable="false" text="Author" />
            <TableColumn fx:id="TableColumn_Publisher" maxWidth="128.0" minWidth="128.0" prefWidth="-1.0" resizable="false" text="Publisher" />
            <TableColumn fx:id="TableColumn_Available" maxWidth="64.0" minWidth="64.0" prefWidth="-1.0" resizable="false" text="Available" />
        </columns>
         <columnResizePolicy>
            <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
         </columnResizePolicy>
      </TableView>
   </children>
</AnchorPane>

System.out.println Debug Message:

As you can see, "Legend of None, My, Ada" is the Book Title, it does show the value in console yet I have clickable rows, but it doesn't show anything (words).

Clickable rows has the same amount as the data in database.


问:
Is there a better way to do with_options in Rails 3 routes?
Here are my Rails 2 routes:

```<code>map.with_options :controller => 'foo', :conditions => { :method => :post } do |foo|
  foo.one 'one', :action => 'one'
  foo.two 'two', :action => 'two'

  foo.with_options :special_flag => 'true', :path_prefix => 'special_prefix',
    :conditions => { :method => :get } do |bar|
    bar.three '',        :action => 'for_blank'
    bar.four  'another', :action => 'for_another'
  end
end
</code>```

How do I convert this sort of thing to Rails 3? Just keep using with_options in the same way? It becomes wordier in some cases because instead of doing

```<code>match '' => 'foo#for_blank'
</code>```

I'm doing

```<code>match '', :action => 'for_blank'
</code>```

答:
Yeah, with_options still works in Rails 3. Try this out:

```<code>map.with_options :controller => 'foo', :via => :post do
  match 'one', :action => 'one' #automatically generates one_* helpers
  match 'two', :action => 'two' #automatically generates two_* helpers

  foo.with_options :special_flag => 'true', :path => 'special_prefix', :via => :get do
    match '',        :action => 'for_blank'
    match  'another', :action => 'for_another', :as => "four" # as will change the helper methods names
  end
end
</code>```

The :via option replaces your ugly conditions hash with a much nicer syntax.

Body:
Here are my Rails 2 routes:

map.with_options :controller => 'foo', :conditions => { :method => :post } do |foo|
  foo.one 'one', :action => 'one'
  foo.two 'two', :action => 'two'

  foo.with_options :special_flag => 'true', :path_prefix => 'special_prefix',
    :conditions => { :method => :get } do |bar|
    bar.three '',        :action => 'for_blank'
    bar.four  'another', :action => 'for_another'
  end
end

How do I convert this sort of thing to Rails 3? Just keep using with_options in the same way? It becomes wordier in some cases because instead of doing

match '' => 'foo#for_blank'

I'm doing

match '', :action => 'for_blank'

Body:
Yeah, with_options still works in Rails 3. Try this out:

map.with_options :controller => 'foo', :via => :post do
  match 'one', :action => 'one' #automatically generates one_* helpers
  match 'two', :action => 'two' #automatically generates two_* helpers

  foo.with_options :special_flag => 'true', :path => 'special_prefix', :via => :get do
    match '',        :action => 'for_blank'
    match  'another', :action => 'for_another', :as => "four" # as will change the helper methods names
  end
end

The :via option replaces your ugly conditions hash with a much nicer syntax.


问:
Javascript - read text file line with multiple lines and report out array
first of all I wanted to thank the ones whom have already helped me get here. My code works and I can output some numbers that are being extracted from a text file. Now I'm facing a challenge where the text file has multiple lines that need to be extracted but all lines start with "Numbers:". ie. below:

Numbers: (23.000,12.000),(12.000,11.000),

Numbers: (13.000,32.000),(42.000,21.000),

Numbers: (33.000,52.000),(22.000,31.000),

I can extract the numbers when my text file has only one line "Numbers:" Can you please help me extract multiple lines? P.S. I would not want to change my code too much is possible. Thanks.

```<code><script type="text/javascript">

    var reader = new FileReader();

    function readText(that){

        if(that.files && that.files[0]){
            var reader = new FileReader();
            reader.onload = function (e) {
                var output1=e.target.result;
                var output2=e.target.result;
                var output3=e.target.result;
                var output4=e.target.result;

//Reads a text file with a line Starting in "Numbers:" that is formated as
following "Numbers: (23.000,12.000),(11.000,22.000),
//multiple numbers read by 2
                output1=(output1.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[1]).join("\n")* 2).toFixed(3);
                output2=(output2.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[2]).join("\n")* 2).toFixed(3);
                output3=(output3.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[3]).join("\n")* 2).toFixed(3);
                output4=(output4.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[4]).join("\n")* 2).toFixed(3);

var n1 = parseFloat(output1),
n2 = parseFloat(output2),
n3 = parseFloat(output3),
n4 = parseFloat(output4),

 //I dont want to print if NaN or 0, that's the reason for list.push and string below

if (n1) {
list.push(n1);
}

if (n2) {
list.push(n2);
}
if (n3) {
list.push(n3);
}

if (n4) {
list.push(n4);
}
//print my numbers "single line" only. Ideally I want to print multiple lines

document.getElementById('inputTextToSave').innerHTML = list.toString().replace(/[^,]+,[^,]+,/g, '$&\n');

//prints the output as the following
//(23.000,12.000)
//(11.000,22.000)

            };//end onload()
            reader.readAsText(that.files[0]);
        }//end if html5 filelist support
    }
</code>```

答:
Try this code.
I have made following changes in above code :-

Wrapped your code into a for loop to execute it for multiple lines

List array is outside the loop to store all the lines.

I have tested this code on my machine :-

Input :-
Numbers: (23.000,12.000),(12.000,11.000),
Numbers: (13.000,32.000),(42.000,21.000),

Output :-
46,24, 24,22, 26,64, 84,42

I hope it helps.

JAVASCRIPT :-

```<code>    var reader = new FileReader();

    function readText(that){

        if(that.files && that.files[0]){
            var reader = new FileReader();
            reader.onload = function (e) {
                // By lines
                var lines = e.target.result.split('\n');
                var list = [];
                for(var Fileline = 0; Fileline < lines.length; Fileline++){
                  var output1 = lines[Fileline];
                  var output2 = lines[Fileline];
                  var output3 = lines[Fileline];
                  var output4 = lines[Fileline];
                  output1=(output1.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[1]).join("\n")* 2).toFixed(3);
                  output2=(output2.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[2]).join("\n")* 2).toFixed(3);
                  output3=(output3.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[3]).join("\n")* 2).toFixed(3);
                  output4=(output4.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[4]).join("\n")* 2).toFixed(3);

                  var n1 = parseFloat(output1),
                    n2 = parseFloat(output2),
                    n3 = parseFloat(output3),
                    n4 = parseFloat(output4);

                    if (n1) {
                    list.push(n1);
                    }

                    if (n2) {
                    list.push(n2);
                    }
                    if (n3) {
                    list.push(n3);
                    }

                    if (n4) {
                    list.push(n4);
                    }
                }

//print my numbers "single line" only. Ideally I want to print multiple lines
console.log(list);
document.getElementById('inputTextToSave').innerHTML = list.toString().replace(/[^,]+,[^,]+,/g, '$&\n');

//prints the output as the following
//(23.000,12.000)
//(11.000,22.000)

            };//end onload()
            reader.readAsText(that.files[0]);
        }//end if html5 filelist support
    }
</code>```

Body:
Try this code.
I have made following changes in above code :-

Wrapped your code into a for loop to execute it for multiple lines

List array is outside the loop to store all the lines.

I have tested this code on my machine :-

Input :-
Numbers: (23.000,12.000),(12.000,11.000),
Numbers: (13.000,32.000),(42.000,21.000),

Output :-
46,24, 24,22, 26,64, 84,42

I hope it helps.

JAVASCRIPT :-

    var reader = new FileReader();

    function readText(that){

        if(that.files && that.files[0]){
            var reader = new FileReader();
            reader.onload = function (e) {
                // By lines
                var lines = e.target.result.split('\n');
                var list = [];
                for(var Fileline = 0; Fileline < lines.length; Fileline++){
                  var output1 = lines[Fileline];
                  var output2 = lines[Fileline];
                  var output3 = lines[Fileline];
                  var output4 = lines[Fileline];
                  output1=(output1.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[1]).join("\n")* 2).toFixed(3);
                  output2=(output2.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[2]).join("\n")* 2).toFixed(3);
                  output3=(output3.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[3]).join("\n")* 2).toFixed(3);
                  output4=(output4.split("\n").filter(/./.test, /Numbers:/).map(line => line.split(/,|\(|\)/).filter(number => number != "")[4]).join("\n")* 2).toFixed(3);

                  var n1 = parseFloat(output1),
                    n2 = parseFloat(output2),
                    n3 = parseFloat(output3),
                    n4 = parseFloat(output4);

                    if (n1) {
                    list.push(n1);
                    }

                    if (n2) {
                    list.push(n2);
                    }
                    if (n3) {
                    list.push(n3);
                    }

                    if (n4) {
                    list.push(n4);
                    }
                }

//print my numbers "single line" only. Ideally I want to print multiple lines
console.log(list);
document.getElementById('inputTextToSave').innerHTML = list.toString().replace(/[^,]+,[^,]+,/g, '$&\n');

//prints the output as the following
//(23.000,12.000)
//(11.000,22.000)

            };//end onload()
            reader.readAsText(that.files[0]);
        }//end if html5 filelist support
    }


问:
Is there any basic gc generation size and ratios for application in production
How much should be the initial size of the young generation?
How much should be -XX:+NewRatio?
-XX:+SurvivourRatio?
What should be the ratio between perm and old generation.?</p>

答:
Every application is different. Your best bet is to measure it yourself!

Create an automated test case which runs through a typical use case for your application. Call this from a shell script which creates random permutations of generation sizes, making sure to keep track of how long it runs for with time. Hold on to the fastest 10 and output them when ctrl+c is pressed.

Leave the script running overnight.

You'll have your answer in the morning =)


问:
save data like session and cache in asp mvc
as you all know we simply use

```<code>Session["kurd"]="";
</code>```

or

Cahce.Insert(...)

and its save data in memory;
its save data without serialize or any thing like that so we can simply save everything

but its not reliable way to save data;

so may you guys say you can save on database or file but in my case
  it  cant be done, because my data its not serializable,  and i can
  only save it in cache , session , viewdata,viewbage
  ,... because it dos not need to be serialize data first ; and because
  of not reliability in session , cache ,... i want way that can save
  data just like cache and session ,... without serialize data

anyone knows how we can do such thing (save data) in disk
i mean save data on hard drive just like session did on memory?

update :

the data type is instance of that class in picture that contain httpclient , httpclienthandeler,deviceinfo,...

update :

how wonderful it is that no one knows
how can i save data in hard drive just like what session did in memory
no question no serialize no bs, just save it very easy

答:
i solved this problem
HttpClient cant be serialize but
i found out that the only thing in HttpClient that we should save in this thread
is "CookieContainer"
so serlize and deserilze like this

```<code>var formatter = new SoapFormatter();
string file = "..\cookies.dat";
//
using (Stream s = File.Create (file))
    formatter.Serialize(s, cookies);
//
CookieContainer retrievedCookies = null;
using (Stream s = File.OpenRead (file))
    retrievedCookies = (CookieContainer) formatter.Deserialize(s);
</code>```

so i serialize it and save it and then for new use i create new HttpClient and assign that CookieContainer to HttpClent.CookieContainer

this problem was for Instasharper

Body:
as you all know we simply use

Session["kurd"]="";

or

Cahce.Insert(...)

and its save data in memory;
its save data without serialize or any thing like that so we can simply save everything

but its not reliable way to save data;

so may you guys say you can save on database or file but in my case
  it  cant be done, because my data its not serializable,  and i can
  only save it in cache , session , viewdata,viewbage
  ,... because it dos not need to be serialize data first ; and because
  of not reliability in session , cache ,... i want way that can save
  data just like cache and session ,... without serialize data

anyone knows how we can do such thing (save data) in disk
i mean save data on hard drive just like session did on memory?

update :

the data type is instance of that class in picture that contain httpclient , httpclienthandeler,deviceinfo,...

update :

how wonderful it is that no one knows
how can i save data in hard drive just like what session did in memory
no question no serialize no bs, just save it very easy

Body:
i solved this problem
HttpClient cant be serialize but
i found out that the only thing in HttpClient that we should save in this thread
is "CookieContainer"
so serlize and deserilze like this

var formatter = new SoapFormatter();
string file = "..\cookies.dat";
//
using (Stream s = File.Create (file))
    formatter.Serialize(s, cookies);
//
CookieContainer retrievedCookies = null;
using (Stream s = File.OpenRead (file))
    retrievedCookies = (CookieContainer) formatter.Deserialize(s);

so i serialize it and save it and then for new use i create new HttpClient and assign that CookieContainer to HttpClent.CookieContainer

this problem was for Instasharper


问:
login failed for user 'sa'.
I try to connect to sql-server by calling this class:

```<code>class DataCon
{
    public static SqlConnection Connection { get; private set; }

    public static void connectDB(string ip, string dbName, string user, string pw)
    {
        string connectionSt = "Server="+ip+";Database="+dbName+";User Id="+user+";Password="+pw+";";
        ConnectToSql(connectionSt);
    }

    private static void ConnectToSql(string connectionSt) {
        Connection = new SqlConnection(connectionSt);
        Connection.Open();
    }

    public static void connectDB(string ip, string dbName)
    {
        string connectionSt = "Server="+ip+";Database="+dbName+";Trusted_Connection=True;";
        ConnectToSql(connectionSt);
    }
}
</code>```

It work when using Windows Authentication but the Server Authentication that give login failed for user 'sa'.

On Sql server management studio I could login successfully with both Windows and Server Authentication with 'sa'.

This is the form I work with:

```<code>        private void btnConfirm_Click(object sender, EventArgs e)
    {
        try
        {
            string dbsName = "dbsStudent";
            string ip = "localhost";
            string user = txtUser.Text;
            string pw = txtUser.Text;

            if (cbAuthentication.SelectedIndex == 0)
                DataCon.connectDB(ip,dbsName);
            else
                DataCon.connectDB(ip,dbsName,user,pw);
            this.Hide();
            new ViewSt().Show();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
</code>```

答:
If your password contains special chars like ';', your connection string will be incorrect.

Consider using SqlConnectionStringBuilder class to build connection string as described on MSDN.

Title: login failed for user 'sa'.

Body:
I try to connect to sql-server by calling this class:

class DataCon
{
    public static SqlConnection Connection { get; private set; }

    public static void connectDB(string ip, string dbName, string user, string pw)
    {
        string connectionSt = "Server="+ip+";Database="+dbName+";User Id="+user+";Password="+pw+";";
        ConnectToSql(connectionSt);
    }

    private static void ConnectToSql(string connectionSt) {
        Connection = new SqlConnection(connectionSt);
        Connection.Open();
    }

    public static void connectDB(string ip, string dbName)
    {
        string connectionSt = "Server="+ip+";Database="+dbName+";Trusted_Connection=True;";
        ConnectToSql(connectionSt);
    }
}

It work when using Windows Authentication but the Server Authentication that give login failed for user 'sa'.

On Sql server management studio I could login successfully with both Windows and Server Authentication with 'sa'.

This is the form I work with:

        private void btnConfirm_Click(object sender, EventArgs e)
    {
        try
        {
            string dbsName = "dbsStudent";
            string ip = "localhost";
            string user = txtUser.Text;
            string pw = txtUser.Text;

            if (cbAuthentication.SelectedIndex == 0)
                DataCon.connectDB(ip,dbsName);
            else
                DataCon.connectDB(ip,dbsName,user,pw);
            this.Hide();
            new ViewSt().Show();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


问:
How do you add items to .dockerignore?
I'm not able to find many examples of what a .dockerignore file should look like.

Using puppet to install a few packages on a docker container causes the image to explode from 600MB to 3GB. I'm trying to use a .dockerignore file to keep the size to a minumum

```<code>$ cat Dockerfile
FROM centos:centos6

#Work around selinux problem on cent images
RUN yum install -y --enablerepo=centosplus libselinux-devel

RUN yum install -y wget git tar openssh-server; yum -y clean all

Add Puppetfile /
RUN librarian-puppet install
RUN puppet apply --modulepath=/modules -e "class { 'buildslave': jenkins_slave => true,}"
RUN librarian-puppet clean
</code>```

If I run docker images --tree I can see that the image instantlly grows by several GB

```<code>$ docker images --tree
                ├─e289570b5555 Virtual Size: 387.7 MB
                │ └─a7646acf90d0 Virtual Size: 442.5 MB
                │   └─d7bc6e1fbe43 Virtual Size: 442.5 MB
                │     └─772e6b204e3b Virtual Size: 627.5 MB
                │       └─599a7b5226f4 Virtual Size: 627.5 MB
                │         └─9fbffccda8bd Virtual Size: 2.943 GB
                │           └─ee46af013f6b Virtual Size: 2.943 GB
                │             └─3e4fe065fd07 Virtual Size: 2.943 GB
                │               └─de9ec3eba39e Virtual Size: 2.943 GB
                │                 └─31cba2716a12 Virtual Size: 2.943 GB
                │                   └─52cbc742d3c4 Virtual Size: 2.943 GB
                │                     └─9a857380258c Virtual Size: 2.943 GB
                │                       └─c6d87a343807 Virtual Size: 2.964 GB
                │                         └─f664124e0080 Virtual Size: 2.964 GB
                │                           └─e6cc212038b9 Virtual Size: 2.964 GB Tags: foo/jenkins-centos6-buildslave:latest
</code>```

I believe the reason that the image grows so large, is because librarian-puppet clones a puppet module to /modules which breaks the build cache

I've tried the following .dockerignore files with no luck.

```<code>$ cat .dockerignore
/modules
/modules/
/modules/*
</code>```

Is this the correct syntax for a .dockerignore file?

Are there any other ways to prevent these containers from growing so large?

Additional information:

http://kartar.net/2013/12/building-puppet-apps-inside-docker/

http://danielmartins.ninja/posts/a-week-of-docker.html

答:
Optimizing container image size is the main goal behind the .dockerignore as it serve a purpose similar to your .gitignore as it reduces the latency and response time while providing services. It is true for deployment automation such as Puppet, SaltStack or Ansible. Timestamp defined for service execution deployment may be failed because of larger image size and low network bandwidth. So .dockerignore helps to make the size of image as small as possible.

You could place it into the build context directory which we specify at the end of a docker build command. The file follows glob pattern for files and directories to exclude those from the final build image.

Suppose I have a directory .img/ into my build context, and I want to exclude it while building image, I'll simply add the following line into .dockerignore file,

```<code>.img
</code>```

And, if I want to exclude all files starts with . then simply, add the line,

```<code>.*
</code>```

(Note: Don't confuse the Unix glob pattern is different than Regular expressions)

In addition, I'll exclude few more of my files from my build context,

```<code>.*
docs
my-stack.dab
docker-compose.overrride.yml
test*
*.md
!README.md
</code>```

Here, *.md line excludes all markdown files(I have many markdown files into my project). But, I want to include README.md and no other markdown files. As our last line in above, we have added README.md with ! or exclude it while excluding all other markdown files.

So, with this we can reduce the overhead of your build image with the help of .dockerignore and leverage to make image size smaller.

Title: How do you add items to .dockerignore?

Body:
I'm not able to find many examples of what a .dockerignore file should look like.

Using puppet to install a few packages on a docker container causes the image to explode from 600MB to 3GB. I'm trying to use a .dockerignore file to keep the size to a minumum

$ cat Dockerfile
FROM centos:centos6

#Work around selinux problem on cent images
RUN yum install -y --enablerepo=centosplus libselinux-devel

RUN yum install -y wget git tar openssh-server; yum -y clean all

Add Puppetfile /
RUN librarian-puppet install
RUN puppet apply --modulepath=/modules -e "class { 'buildslave': jenkins_slave => true,}"
RUN librarian-puppet clean

If I run docker images --tree I can see that the image instantlly grows by several GB

$ docker images --tree
                ├─e289570b5555 Virtual Size: 387.7 MB
                │ └─a7646acf90d0 Virtual Size: 442.5 MB
                │   └─d7bc6e1fbe43 Virtual Size: 442.5 MB
                │     └─772e6b204e3b Virtual Size: 627.5 MB
                │       └─599a7b5226f4 Virtual Size: 627.5 MB
                │         └─9fbffccda8bd Virtual Size: 2.943 GB
                │           └─ee46af013f6b Virtual Size: 2.943 GB
                │             └─3e4fe065fd07 Virtual Size: 2.943 GB
                │               └─de9ec3eba39e Virtual Size: 2.943 GB
                │                 └─31cba2716a12 Virtual Size: 2.943 GB
                │                   └─52cbc742d3c4 Virtual Size: 2.943 GB
                │                     └─9a857380258c Virtual Size: 2.943 GB
                │                       └─c6d87a343807 Virtual Size: 2.964 GB
                │                         └─f664124e0080 Virtual Size: 2.964 GB
                │                           └─e6cc212038b9 Virtual Size: 2.964 GB Tags: foo/jenkins-centos6-buildslave:latest

I believe the reason that the image grows so large, is because librarian-puppet clones a puppet module to /modules which breaks the build cache

I've tried the following .dockerignore files with no luck.

$ cat .dockerignore
/modules
/modules/
/modules/*

Is this the correct syntax for a .dockerignore file?

Are there any other ways to prevent these containers from growing so large?

Additional information:

http://kartar.net/2013/12/building-puppet-apps-inside-docker/

http://danielmartins.ninja/posts/a-week-of-docker.html

Body:
Optimizing container image size is the main goal behind the .dockerignore as it serve a purpose similar to your .gitignore as it reduces the latency and response time while providing services. It is true for deployment automation such as Puppet, SaltStack or Ansible. Timestamp defined for service execution deployment may be failed because of larger image size and low network bandwidth. So .dockerignore helps to make the size of image as small as possible.

You could place it into the build context directory which we specify at the end of a docker build command. The file follows glob pattern for files and directories to exclude those from the final build image.

Suppose I have a directory .img/ into my build context, and I want to exclude it while building image, I'll simply add the following line into .dockerignore file,

.img

And, if I want to exclude all files starts with . then simply, add the line,

.*

(Note: Don't confuse the Unix glob pattern is different than Regular expressions)

In addition, I'll exclude few more of my files from my build context,

.*
docs
my-stack.dab
docker-compose.overrride.yml
test*
*.md
!README.md

Here, *.md line excludes all markdown files(I have many markdown files into my project). But, I want to include README.md and no other markdown files. As our last line in above, we have added README.md with ! or exclude it while excluding all other markdown files.

So, with this we can reduce the overhead of your build image with the help of .dockerignore and leverage to make image size smaller.


答:
First, you need the combinations of 'MarketID' and 'SelectionID' in order of occurrence, so lets sort on the time.
Then, for each 'MarketID' get the unique 'SelectionID's and number them in order of occurrence (already ordered, because df is ordered on column time). Secondly, the combination of number 'MarketID' and 'SelectionID' together with the order will be used later to set the numbers.

I'll give you two solution to the first part:

```<code>dfnewindex = df.sort_values('Time').set_index('MarketID')
valuesetter = {}
for indx in dfnewindex.index.unique():
    selectionid_per_marketid  = dfnewindex.loc[indx].sort_values('Time')['SelectionID'].drop_duplicates().values
    valuesetter.update(dict(zip(zip(len(selectionid_per_marketid)*[indx], selectionid_per_marketid), range(1, 1+len(selectionid_per_marketid)))))
</code>```

100 loops, best of 3: 3.22 ms per loop

```<code>df_sorted = df.sort_values('Time')
valuesetter = {}
for mrktid in df_sorted['MarketID'].unique():
    sltnids = df_sorted[df_sorted['MarketID']==mrktid]['SelectionID'].drop_duplicates(keep='first').values
    valuesetter.update(dict(zip(zip(len(sltnids)*[mrktid], sltnids), range(1, 1+len(sltnids)))))
</code>```

100 loops, best of 3: 2.59 ms per loop

The boolean slicing solution is slightly faster in this case

The output:

```<code>valuesetter

{(112337406, 3819251.0): 4,
 (112337406, 4979206.0): 1,
 (112337406, 5117439.0): 3,
 (112337406, 5696467.0): 2,
 (112337407, 3819254.0): 4,
 (112337407, 4979206.0): 1,
 (112337407, 5117441.0): 3,
 (112337407, 5696485.0): 2}
</code>```

For the second part, this dict is used to generate a column, i.e. SelectNumber. Again two solutions, the first uses multiindex, the second groupby:

```<code>map(lambda x: valuesetter[x], df.set_index(['MarketID', 'SelectionID']).index.values)
</code>```

1000 loops, best of 3: 1.23 ms per loop

```<code>map(lambda x: valuesetter[x], df.groupby(['MarketID', 'SelectionID']).count().index.values)
</code>```

1000 loops, best of 3: 1.59 ms per loop

the multiindex seems to be the fastest solution.

The final, up to this point, fastest answer:

```<code>df_sorted = df.sort_values('Time')
valuesetter2 = {}
for mrktid in df_sorted['MarketID'].unique():
    sltnids = df_sorted[df_sorted['MarketID']==mrktid]['SelectionID'].drop_duplicates(keep='first').values
    valuesetter2.update(dict(zip(zip(len(sltnids)*[mrktid], sltnids), range(1, 1+len(sltnids)))))
df_sorted['SelectNumber'] = list(map(lambda x: valuesetter[x], df.set_index(['MarketID', 'SelectionID']).index.values))
</code>```

Title: Grouping and numbering items in a pandas dataframe

Body:
I want to add a column to a dataframe in python/pandas as follows:

| MarketID  | SelectionID |   Time   | SelectNumber |

| 112337406 | 3819251.0   | 13:38:32 |            4 |

| 112337406 | 3819251.0   | 13:39:03 |            4 |

| 112337406 | 4979206.0   | 11:29:34 |            1 |

| 112337406 | 4979206.0   | 11:37:34 |            1 |

| 112337406 | 5117439.0   | 13:36:32 |            3 |

| 112337406 | 5117439.0   | 13:37:03 |            3 |

| 112337406 | 5696467.0   | 13:23:03 |            2 |

| 112337406 | 5696467.0   | 13:23:33 |            2 |

| 112337407 | 3819254.0   | 13:39:12 |            4 |

| 112337407 | 4979206.0   | 11:29:56 |            1 |

| 112337407 | 4979206.0   | 16:27:34 |            1 |

| 112337407 | 5117441.0   | 13:36:54 |            3 |

| 112337407 | 5117441.0   | 17:47:11 |            3 |

| 112337407 | 5696485.0   | 13:23:04 |            2 |

| 112337407 | 5696485.0   | 18:23:59 |            2 |

I currently have the market ID, Selection ID and Time, I want to generate the SelectNumber column, which represents the time order in which the particular selectionID appears within a particular MarketID. Once numbered all other iterations of the same selection ID within that MarketID need to be numbered the same. The MarketID will always be unique, but the same selectionID can appear in more than 1 MarketID.

This has got me stumped, any ideas?

Body:
First, you need the combinations of 'MarketID' and 'SelectionID' in order of occurrence, so lets sort on the time.
Then, for each 'MarketID' get the unique 'SelectionID's and number them in order of occurrence (already ordered, because df is ordered on column time). Secondly, the combination of number 'MarketID' and 'SelectionID' together with the order will be used later to set the numbers.

I'll give you two solution to the first part:

dfnewindex = df.sort_values('Time').set_index('MarketID')
valuesetter = {}
for indx in dfnewindex.index.unique():
    selectionid_per_marketid  = dfnewindex.loc[indx].sort_values('Time')['SelectionID'].drop_duplicates().values
    valuesetter.update(dict(zip(zip(len(selectionid_per_marketid)*[indx], selectionid_per_marketid), range(1, 1+len(selectionid_per_marketid)))))

100 loops, best of 3: 3.22 ms per loop

df_sorted = df.sort_values('Time')
valuesetter = {}
for mrktid in df_sorted['MarketID'].unique():
    sltnids = df_sorted[df_sorted['MarketID']==mrktid]['SelectionID'].drop_duplicates(keep='first').values
    valuesetter.update(dict(zip(zip(len(sltnids)*[mrktid], sltnids), range(1, 1+len(sltnids)))))

100 loops, best of 3: 2.59 ms per loop

The boolean slicing solution is slightly faster in this case

The output:

valuesetter

{(112337406, 3819251.0): 4,
 (112337406, 4979206.0): 1,
 (112337406, 5117439.0): 3,
 (112337406, 5696467.0): 2,
 (112337407, 3819254.0): 4,
 (112337407, 4979206.0): 1,
 (112337407, 5117441.0): 3,
 (112337407, 5696485.0): 2}

For the second part, this dict is used to generate a column, i.e. SelectNumber. Again two solutions, the first uses multiindex, the second groupby:

map(lambda x: valuesetter[x], df.set_index(['MarketID', 'SelectionID']).index.values)

1000 loops, best of 3: 1.23 ms per loop

map(lambda x: valuesetter[x], df.groupby(['MarketID', 'SelectionID']).count().index.values)

1000 loops, best of 3: 1.59 ms per loop

the multiindex seems to be the fastest solution.

The final, up to this point, fastest answer:

df_sorted = df.sort_values('Time')
valuesetter2 = {}
for mrktid in df_sorted['MarketID'].unique():
    sltnids = df_sorted[df_sorted['MarketID']==mrktid]['SelectionID'].drop_duplicates(keep='first').values
    valuesetter2.update(dict(zip(zip(len(sltnids)*[mrktid], sltnids), range(1, 1+len(sltnids)))))
df_sorted['SelectNumber'] = list(map(lambda x: valuesetter[x], df.set_index(['MarketID', 'SelectionID']).index.values))


答:
No, because pointer arithmetic is scaled depending on the thing you're pointing to. In this case, you're pointing to a three-element array of integers, each four bytes long, for a total of twelve bytes. But that's scaled back to one "element" in your arithmetic.

It's the same reason that you get 0029FAC0 rather than 0029FAB5 (0029FAB4 + 1 when it's not scaled) when printing out a+1.

If you change your output line to:

```<code>cout << a+1                 << " "
     << a                   << " "
     << (a+1) - a           << " "
     << (int)(a+1)-(int)(a) << endl;
</code>```

you'll see the scaling disappear in the final term because it's no longer a subtraction of pointers:

```<code>0xbfaa0ad4 0xbfaa0ac8 1 12
</code>```

Keep in mind that the a+1 in (int)(a+1) is still scaled since a is still a pointer there. It's only the subtraction that's not scaled because, at that point, both values have been converted to integers (and the usual caveats apply to converting between pointers and integers, it's safe for my particular implementation but C99 doesn't mandate that).

Title: How to understand the output?

Body:
int a[2][3];
cout << a+1 << " " << a << " " << (a+1) - a << endl;

Output:

0029FAC0 0029FAB4 1

Shouldn't (a+1)-a be 0029FAC0-0029FAB4=12 ?

Body:
No, because pointer arithmetic is scaled depending on the thing you're pointing to. In this case, you're pointing to a three-element array of integers, each four bytes long, for a total of twelve bytes. But that's scaled back to one "element" in your arithmetic.

It's the same reason that you get 0029FAC0 rather than 0029FAB5 (0029FAB4 + 1 when it's not scaled) when printing out a+1.

If you change your output line to:

cout << a+1                 << " "
     << a                   << " "
     << (a+1) - a           << " "
     << (int)(a+1)-(int)(a) << endl;

you'll see the scaling disappear in the final term because it's no longer a subtraction of pointers:

0xbfaa0ad4 0xbfaa0ac8 1 12

Keep in mind that the a+1 in (int)(a+1) is still scaled since a is still a pointer there. It's only the subtraction that's not scaled because, at that point, both values have been converted to integers (and the usual caveats apply to converting between pointers and integers, it's safe for my particular implementation but C99 doesn't mandate that).


问:
What is the difference between reactjs vs nextjs
I have just started learning Reactjs and I am a little bit confused between Reactjs and next.js. what is the difference between them? Both are component oriented processes.

答:
React is s library for building user interfaces.

Next.js uses React. It's a framework for server-rendered React applications.


问:
clean up the header of csv files with awk
I have a bunch of csv files that look like this:

```<code>Time,Channel A
(s),(V)

0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560
</code>```

And I want to transform it to:

```<code>Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560
</code>```

The units are not necessarily identical across files (i.e. there might be (ms),(µV) etc.)

I got as far as removing the blank line (which is always line no. 3) with awk 'FNR!=3' but cutting the 2nd row arguments and pasting them behind the first row fields is beyond my capacity ;(

Please help me out!
Motivation: there are lots of these files. Doing it by hand is not feasible…

EDIT:
First of all: thanks for helping me out. As there seems to be the same issue with 2 of your answers, there might be a problem in my file potentially? I suspect the empty line to somehow cause trouble?

the shell-script gives me the error 'xpected empty line, read '

the perl-script and the awk-script give me a faulty first line:

```<code> (V) (s),Channel A
0.00000000,0.58058560
</code>```

If it helps, I uploaded a sample infile.

答:
```<code>awk -F , -v RS='\r\n' 'FNR == 1 { x = $1; y = $2 } FNR == 2 { print x " " $1 "," y " " $2 } FNR > 3'
</code>```

A brief explanation: awk accepts logical expressions as range patterns (anything in scope can be used,) hence FNR == n means simply that the pattern applies to line number n in the current file; the last pattern applies to everything after line #3; omitting the action means to simply print the input as read.  Thus, lines #1 and #2 are treated specially, each according to its own meaning, and line #3 is ignored, as there's no matching pattern for it.

UPDATE: Edited to set RS (record separator) as per @123's suggestion.  An alternative way would be to include it in the script itself, possibly along with FS (field separator,) like this:

```<code>awk 'BEGIN { FS=","; RS="\r\n" } FNR == 1 { x = $1; y = $2 } FNR == 2 { print x " " $1 "," y " " $2 } FNR > 3'
</code>```

Body:
I have a bunch of csv files that look like this:

Time,Channel A
(s),(V)

0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560

And I want to transform it to:

Time (s),Channel A (V)
0.00000000,0.58058560
0.00666667,0.58913630
0.01333334,0.58058560

The units are not necessarily identical across files (i.e. there might be (ms),(µV) etc.)

I got as far as removing the blank line (which is always line no. 3) with awk 'FNR!=3' but cutting the 2nd row arguments and pasting them behind the first row fields is beyond my capacity ;(

Please help me out!
Motivation: there are lots of these files. Doing it by hand is not feasible…

EDIT:
First of all: thanks for helping me out. As there seems to be the same issue with 2 of your answers, there might be a problem in my file potentially? I suspect the empty line to somehow cause trouble?

the shell-script gives me the error 'xpected empty line, read '

the perl-script and the awk-script give me a faulty first line:

 (V) (s),Channel A
0.00000000,0.58058560

If it helps, I uploaded a sample infile.

Body:
awk -F , -v RS='\r\n' 'FNR == 1 { x = $1; y = $2 } FNR == 2 { print x " " $1 "," y " " $2 } FNR > 3'

A brief explanation: awk accepts logical expressions as range patterns (anything in scope can be used,) hence FNR == n means simply that the pattern applies to line number n in the current file; the last pattern applies to everything after line #3; omitting the action means to simply print the input as read.  Thus, lines #1 and #2 are treated specially, each according to its own meaning, and line #3 is ignored, as there's no matching pattern for it.

UPDATE: Edited to set RS (record separator) as per @123's suggestion.  An alternative way would be to include it in the script itself, possibly along with FS (field separator,) like this:

awk 'BEGIN { FS=","; RS="\r\n" } FNR == 1 { x = $1; y = $2 } FNR == 2 { print x " " $1 "," y " " $2 } FNR > 3'