问:
What is a lambda (function)?
For a person without a comp-sci background, what is a lambda in the world of Computer Science?</p>

答:
For a person without a comp-sci background, what is a lambda in the world of Computer Science?

I will illustrate it intuitively step by step in simple and readable python codes.

In short, a lambda is just an anonymous and inline function.

Let's start from assignment to understand lambdas as a freshman with background of basic arithmetic.

The blueprint of assignment is 'the name = value', see:

```<code>In [1]: x = 1
   ...: y = 'value'
In [2]: x
Out[2]: 1
In [3]: y
Out[3]: 'value'
</code>```

'x', 'y' are names and 1, 'value' are values.
Try a function in mathematics

```<code>In [4]: m = n**2 + 2*n + 1
NameError: name 'n' is not defined
</code>```

Error reports,

you cannot write a mathematic directly as code,'n' should be defined or be assigned to a value.

```<code>In [8]: n = 3.14
In [9]: m = n**2 + 2*n + 1
In [10]: m
Out[10]: 17.1396
</code>```

It works now,what if you insist on combining the two seperarte lines to one.
There comes lambda

```<code>In [13]: j = lambda i: i**2 + 2*i + 1
In [14]: j
Out[14]: <function __main__.<lambda>>
</code>```

No errors reported.

This is a glance at lambda, it enables you to write a function in a single line as you do in mathematic into the computer directly.

We will see it later.

Let's continue on digging deeper on 'assignment'.

As illustrated above, the equals symbol = works for simple data(1 and 'value') type and simple expression(n**2 + 2*n + 1).

Try this:

```<code>In [15]: x = print('This is a x')
This is a x
In [16]: x
In [17]: x = input('Enter a x: ')
Enter a x: x
</code>```

It works for simple statements,there's 11 types of them in python 7. Simple statements — Python 3.6.3 documentation

How about compound statement,

```<code>In [18]: m = n**2 + 2*n + 1 if n > 0
SyntaxError: invalid syntax
#or
In [19]: m = n**2 + 2*n + 1, if n > 0
SyntaxError: invalid syntax
</code>```

There comes def enable it working

```<code>In [23]: def m(n):
    ...:     if n > 0:
    ...:         return n**2 + 2*n + 1
    ...:
In [24]: m(2)
Out[24]: 9
</code>```

Tada, analyse it, 'm' is name, 'n**2 + 2*n + 1' is value.: is a variant of '='.

Find it, if just for understanding, everything starts from assignment and everything is assignment.

Now return to lambda, we have a function named 'm'

Try:

```<code>In [28]: m = m(3)
In [29]: m
Out[29]: 16
</code>```

There are two names of 'm' here, function m already has a name, duplicated.

It's formatting like:

```<code>In [27]: m = def m(n):
    ...:         if n > 0:
    ...:             return n**2 + 2*n + 1
    SyntaxError: invalid syntax
</code>```

It's not a smart strategy, so error reports

We have to delete one of them,set a function without a name.

```<code>m = lambda n:n**2 + 2*n + 1
</code>```

It's called 'anonymous function'

In conclusion,

lambda in an inline function which enable you to write a function in one straight line as does in mathematics

lambda is anonymous

Hope, this helps.

OwnerDisplayName: Brian Warshaw

Title: What is a lambda (function)?

LastEditorDisplayName: Steve M

Body:
For a person without a comp-sci background, what is a lambda in the world of Computer Science?

I will illustrate it intuitively step by step in simple and readable python codes.

In short, a lambda is just an anonymous and inline function.

Let's start from assignment to understand lambdas as a freshman with background of basic arithmetic.

The blueprint of assignment is 'the name = value', see:

In [1]: x = 1
   ...: y = 'value'
In [2]: x
Out[2]: 1
In [3]: y
Out[3]: 'value'

'x', 'y' are names and 1, 'value' are values.
Try a function in mathematics

In [4]: m = n**2 + 2*n + 1
NameError: name 'n' is not defined

Error reports,

you cannot write a mathematic directly as code,'n' should be defined or be assigned to a value.

In [8]: n = 3.14
In [9]: m = n**2 + 2*n + 1
In [10]: m
Out[10]: 17.1396

It works now,what if you insist on combining the two seperarte lines to one.
There comes lambda

In [13]: j = lambda i: i**2 + 2*i + 1
In [14]: j
Out[14]: <function __main__.<lambda>>

No errors reported.

This is a glance at lambda, it enables you to write a function in a single line as you do in mathematic into the computer directly.

We will see it later.

Let's continue on digging deeper on 'assignment'.

As illustrated above, the equals symbol = works for simple data(1 and 'value') type and simple expression(n**2 + 2*n + 1).

Try this:

In [15]: x = print('This is a x')
This is a x
In [16]: x
In [17]: x = input('Enter a x: ')
Enter a x: x

It works for simple statements,there's 11 types of them in python 7. Simple statements — Python 3.6.3 documentation

How about compound statement,

In [18]: m = n**2 + 2*n + 1 if n > 0
SyntaxError: invalid syntax
#or
In [19]: m = n**2 + 2*n + 1, if n > 0
SyntaxError: invalid syntax

There comes def enable it working

In [23]: def m(n):
    ...:     if n > 0:
    ...:         return n**2 + 2*n + 1
    ...:
In [24]: m(2)
Out[24]: 9

Tada, analyse it, 'm' is name, 'n**2 + 2*n + 1' is value.: is a variant of '='.

Find it, if just for understanding, everything starts from assignment and everything is assignment.

Now return to lambda, we have a function named 'm'

Try:

In [28]: m = m(3)
In [29]: m
Out[29]: 16

There are two names of 'm' here, function m already has a name, duplicated.

It's formatting like:

In [27]: m = def m(n):
    ...:         if n > 0:
    ...:             return n**2 + 2*n + 1
    SyntaxError: invalid syntax

It's not a smart strategy, so error reports

We have to delete one of them,set a function without a name.

m = lambda n:n**2 + 2*n + 1

It's called 'anonymous function'

In conclusion,

lambda in an inline function which enable you to write a function in one straight line as does in mathematics

lambda is anonymous

Hope, this helps.


来源: stackexchange

问:
SQL : Multiple left joins with similar tables
I have the following tables:

```<code>TABLE A
id
info

TABLE B
f_id
question
choices

TABLE C
f_id
question
lines
</code>```

The id from the Table A always match a f_id from either Table B or C, but never both. I want to join Table B and Table C on table A only when it matches so I would get a table with the following columns :

```<code>id |   info   |   question   | choices | lines
</code>```

where all rows are filled in the question column, some are NULL in the column choices and some are NULL in the column lines.

What I tried is to do two consecutive left joins, but the second one overrides the first so all the rows that doesn't match in Table C (second left join) get a NULL value in the question column.

Is there a way to do a query that will not override previously joined data with NULL values? I'm working with Laravel Eloquent, so any of raw SQL or Eloquent Query would help me.

答:
but never both

Good luck with that.

id |   info   |   question   | choices | lines

```<code>SELECT a.id, a.info, b.question, b.choices, '' AS lines
FROM tableA as A
LEFT JOIN tableB AS b
ON a.id=b.f_id
UNION
SELECT a.id, a.info, c.question, '', c.lines
FROM tableA as A
INNER JOIN tableC AS c
ON a.id=c.f_id
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following tables:

TABLE A
id
info

TABLE B
f_id
question
choices

TABLE C
f_id
question
lines

The id from the Table A always match a f_id from either Table B or C, but never both. I want to join Table B and Table C on table A only when it matches so I would get a table with the following columns :

id |   info   |   question   | choices | lines

where all rows are filled in the question column, some are NULL in the column choices and some are NULL in the column lines.

What I tried is to do two consecutive left joins, but the second one overrides the first so all the rows that doesn't match in Table C (second left join) get a NULL value in the question column.

Is there a way to do a query that will not override previously joined data with NULL values? I'm working with Laravel Eloquent, so any of raw SQL or Eloquent Query would help me.

Body:
but never both

Good luck with that.

id |   info   |   question   | choices | lines

SELECT a.id, a.info, b.question, b.choices, '' AS lines
FROM tableA as A
LEFT JOIN tableB AS b
ON a.id=b.f_id
UNION
SELECT a.id, a.info, c.question, '', c.lines
FROM tableA as A
INNER JOIN tableC AS c
ON a.id=c.f_id


问:
Dynamically change datetime format of xAxis Tick Label in highchart
I need to change datetime format of the X Axis Tick Label between MM/dd/yyyy HH:mm:ss and MM/dd/yyyy according to selection by the user.

How can i achieve this using javascript?

答:
I know that I am way too late but if you are looking for a pure JavaScript implementation this might work:

```<code>tooltip:{formatter:function(){
            const selectedFormat = document.getElementById("dateFormat").value;
            const finalDate = Highcharts.dateFormat(selectedFormat, this.x);
            return finalDate;
        }
}
</code>```

http://jsfiddle.net/527moaLs/

You can find the rest of the solution by yourself, I suppose

Body:
I know that I am way too late but if you are looking for a pure JavaScript implementation this might work:

tooltip:{formatter:function(){
            const selectedFormat = document.getElementById("dateFormat").value;
            const finalDate = Highcharts.dateFormat(selectedFormat, this.x);
            return finalDate;
        }
}

http://jsfiddle.net/527moaLs/

You can find the rest of the solution by yourself, I suppose


问:
Reverse DNS lookup to check remote host in MVC 2 C#
I am working on a Portal and want to detect whether the users in on our domain. I have been told that the best way to do this is to do a reverse DNS lookup to check the remote host and whether the user is on our domain and then log them in using their AD credentials.

We want the user to be logged in if they are on our domain:

First we'll do an IP Range check then a reverse DNS lookup...

On another system we use this code in an ASP page

```<code>Dim oIIS
Dim vEnableRevDNS
Dim vDisableRevDNS

vEnableRevDNS = 1
vDisableRevDNS = 0

Set oIIS = GetObject("IIS://localhost/w3svc/1/ROOT")
oIIS.Put "EnableReverseDNS", vEnableRevDNS
oIIS.SetInfo
Set oIIS = Nothing
</code>```

Is there a way to do this in MVC 2:C#?

To clarify:
I will still be using Windows Integrated Authentication - however I want the process to be seamless... if you are our network you get automatically logged in... if you are not you get forwarded to a login page

There will be intranet/ extranet and public user access - each will have a different login process    - I want to use reverse DNS purely as a mechanism to direct to an entry point.

Thanks for any pointers.

答:
Reverse DNS is not a strong authentication mechanism.

Integrated windows authentication is an IIS/ASP.NET option.
You turn it on, and the browser and IIS handles the rest. Users arrive at your application authenticated.  (Make sure you have anonymous access turned off)

Edit: DNS is not an authentication mechanism at all. Whomever wrote your technical spec should go and read up on how Windows Integrated Authentication (NTLM/Kerberos) actually works.

Suffice to say, it doesn't rely on the DNS entry assigned to your machine.

Edit 2:

For Windows Integrated Authentication to be seamless, you need three things on a client machine:

Using a browser that supports NTLM/Kerberos-Auth (Internet Explorer, and with the correct settings: Firefox)

Using a machine that is a member of that Active Directory domain (This may also work for other trusted AD Domains)

Logged into an AD domain account.

With this, then you'll get automatic sign-in. No prompting, you're just there.

If, however you're not meeting those, then in Internet Explorer and Firefox you'll receive a standard password prompt (not in your application, just the standard browser one).
You don't get the option of showing a friendly error message, as this is handled outside of your application context.

If the user is using a browser that doesnt' support NTLM/Kerberos, you'll either recieve endless authentication prompts - or the browser will just display the 'access denied' page.

ContentLicense: CC BY-SA 2.5

Body:
I am working on a Portal and want to detect whether the users in on our domain. I have been told that the best way to do this is to do a reverse DNS lookup to check the remote host and whether the user is on our domain and then log them in using their AD credentials.

We want the user to be logged in if they are on our domain:

First we'll do an IP Range check then a reverse DNS lookup...

On another system we use this code in an ASP page

Dim oIIS
Dim vEnableRevDNS
Dim vDisableRevDNS

vEnableRevDNS = 1
vDisableRevDNS = 0

Set oIIS = GetObject("IIS://localhost/w3svc/1/ROOT")
oIIS.Put "EnableReverseDNS", vEnableRevDNS
oIIS.SetInfo
Set oIIS = Nothing

Is there a way to do this in MVC 2:C#?

To clarify:
I will still be using Windows Integrated Authentication - however I want the process to be seamless... if you are our network you get automatically logged in... if you are not you get forwarded to a login page

There will be intranet/ extranet and public user access - each will have a different login process    - I want to use reverse DNS purely as a mechanism to direct to an entry point.

Thanks for any pointers.


问:
How to Generate Parquet File Using Pure Java (Including Date & Decimal Types) And Upload to S3 [Windows] (No HDFS)
I recently had a requirement where I needed to generate Parquet files that could be read by Apache Spark using only Java (Using no additional software installations such as: Apache Drill, Hive, Spark, etc.). The files needed to be saved to S3 so I will be sharing details on how to do both.

There were no simple to follow guides on how to do this. I'm also not a Java programmer so the concepts of using Maven, Hadoop, etc. were all foreign to me. So it took me nearly two weeks to get this working. I'd like to share my personal guide below on how I achieved this

答:
Disclaimer: The code samples below in no way represent best practices and are only presented as a rough how-to.

Dependencies:

parquet-avro (1.9.0) : https://mvnrepository.com/artifact/org.apache.parquet/parquet-avro/1.9.0 (We use 1.9.0 because this version uses Avro 1.8+ which supports Decimals and Dates)

hadoop-aws (2.8.2) [If you don't plan on writing to S3 you won't need this but you will need to add several other dependencies that normally get added thanks to this. I will not cover that scenario. So even if you're going to generate Parquet files only on your local disk, you can still add this to your project as a dependency]: https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-aws/2.8.2 (We use this because it was the latest version at the time)

Hadoop 2.8.1: https://github.com/steveloughran/winutils/tree/master/hadoop-2.8.1 (We use 2.8.X because it needs to match the hadoop libraries used in the parquet-avro and hadoop-aws dependencies)

I'll be using NetBeans as my IDE.

Some info regarding parquet in Java (For noobs such as me):

In order to serialize your data into parquet, you must choose one of the popular Java data serialization frameworks: Avro, Protocol Buffers or Thrift (I'll be using Avro (1.8.0), as can be seen from our parquet-avro dependency)

You will need to use an IDE that supports Maven. This is because the dependencies above have a lot of dependencies of their own. Maven will automatically download those for you (like NuGet for VisualStudio)

Pre-requisite:

You must have hadoop on the windows machine that will be running the Java code. The good news is you don't need to install the entire hadoop software, rather you need only two files:

hadoop.dll

winutils.exe

These can be downloaded here. You will need version 2.8.1 for this example (due to parquet-avro 1.9.0).

Copy these files to C:\hadoop-2.8.1\bin on the target machine.

Add a new System Variable (not user variable) called: HADOOP_HOME with the value C:\hadoop-2.8.1

Modify the System Path variable (not user variable) and add the following to the end: %HADOOP_HOME%\bin

Restart the machine for changes to take affect.

If this config was not done properly you will get the following error at run-time: java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z

Getting Started with Coding:

First create a new empty Maven Project and add parquet-avro 1.9.0 and hadoop-aws 2.8.2 as dependencies:

Create your main class where you can write some code

First thing is you need to generate a Schema. Now as far as I can tell there is no way you can generate a schema programmatically at run-time. the Schema.Parser class' parse() method only takes a file or a string literal as a parameter and doesn't let you modify the schema once it is created.
To circumvent this I am generating my Schema JSON at run time and parsing that. Below is an example Schema:

```<code>String schema = "{\"namespace\": \"org.myorganization.mynamespace\"," //Not used in Parquet, can put anything
    + "\"type\": \"record\"," //Must be set as record
    + "\"name\": \"myrecordname\"," //Not used in Parquet, can put anything
    + "\"fields\": ["
    + " {\"name\": \"myInteger\", \"type\": \"int\"}," //Required field
    + " {\"name\": \"myString\",  \"type\": [\"string\", \"null\"]},"
    + " {\"name\": \"myDecimal\", \"type\": [{\"type\": \"fixed\", \"size\":16, \"logicalType\": \"decimal\", \"name\": \"mydecimaltype1\", \"precision\": 32, \"scale\": 4}, \"null\"]},"
    + " {\"name\": \"myDate\", \"type\": [{\"type\": \"int\", \"logicalType\" : \"date\"}, \"null\"]}"
    + " ]}";
Parser parser = new Schema.Parser().setValidate(true);
Schema avroSchema = parser.parse(schema);
</code>```

Details on Avro schema can be found here: https://avro.apache.org/docs/1.8.0/spec.html

Next we can start generating records (Avro primitive types are simple):

```<code>GenericData.Record record = new GenericData.Record(avroSchema);
record.put("myInteger", 1);
record.put("myString", "string value 1");
</code>```

In order to generate a decimal logical type a fixed or bytes primitive type must be used as the actual data type for storage. The current Parquet format only supports Fixed length byte arrays (aka: fixed_len_byte_array). So we have to use fixed in our case as well (as can be seen in the schema). In Java we must use BigDecimal in order to truly handle decimals. And I've identified that a Decimal(32,4) will not take more than 16 bytes no matter the value. So we will use a standard byte array size of 16 in our serialization below (and in the schema above):

```<code>BigDecimal myDecimalValue = new BigDecimal("99.9999");

//First we need to make sure the BigDecimal matches our schema scale:
myDecimalValue = myDecimalValue.setScale(4, RoundingMode.HALF_UP);

//Next we get the decimal value as one BigInteger (like there was no decimal point)
BigInteger myUnscaledDecimalValue = myDecimalValue.unscaledValue();

//Finally we serialize the integer
byte[] decimalBytes = myUnscaledDecimalValue.toByteArray();

//We need to create an Avro 'Fixed' type and pass the decimal schema once more here:
GenericData.Fixed fixed = new GenericData.Fixed(new Schema.Parser().parse("{\"type\": \"fixed\", \"size\":16, \"precision\": 32, \"scale\": 4, \"name\":\"mydecimaltype1\"}"));

byte[] myDecimalBuffer = new byte[16];
if (myDecimalBuffer.length >= decimalBytes.length) {
    //Because we set our fixed byte array size as 16 bytes, we need to
    //pad-left our original value's bytes with zeros
    int myDecimalBufferIndex = myDecimalBuffer.length - 1;
    for(int i = decimalBytes.length - 1; i >= 0; i--){
        myDecimalBuffer[myDecimalBufferIndex] = decimalBytes[i];
        myDecimalBufferIndex--;
    }
    //Save result
    fixed.bytes(myDecimalBuffer);
} else {
    throw new IllegalArgumentException(String.format("Decimal size: %d was greater than the allowed max: %d", decimalBytes.length, myDecimalBuffer.length));
}

//We can finally write our decimal to our record
record.put("myDecimal", fixed);
</code>```

For Date values, Avro specifies that we need to save the number of days since EPOCH as an integer. (If you need the time component as well, such as an actual DateTime type, you need to use the Timestamp Avro type, which I will not cover).
The easiest way I found to get the number of days since epoch is using the joda-time library. If you added the hadoop-aws dependency to your project you should already have this library. If not you will need to add it yourself:

```<code>//Get epoch value
MutableDateTime epoch = new MutableDateTime(0l, DateTimeZone.UTC);

DateTime currentDate = new DateTime(); //Can take Java Date in constructor
Days days = Days.daysBetween(epoch, currentDate);

//We can write number of days since epoch into the record
record.put("myDate", days.getDays());
</code>```

We finally can start writing our parquet file as such

```<code>try {
   Configuration conf = new Configuration();
   conf.set("fs.s3a.access.key", "ACCESSKEY");
   conf.set("fs.s3a.secret.key", "SECRETKEY");
   //Below are some other helpful settings
   //conf.set("fs.s3a.endpoint", "s3.amazonaws.com");
   //conf.set("fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider");
   //conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); // Not needed unless you reference the hadoop-hdfs library.
   //conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); // Uncomment if you get "No FileSystem for scheme: file" errors

   Path path = new Path("s3a://your-bucket-name/examplefolder/data.parquet");

   //Use path below to save to local file system instead
   //Path path = new Path("data.parquet");

   try (ParquetWriter writer = AvroParquetWriter.builder(path)
           .withSchema(avroSchema)
           .withCompressionCodec(CompressionCodecName.GZIP)
           .withConf(conf)
           .withPageSize(4 * 1024 * 1024) //For compression
           .withRowGroupSize(16 * 1024 * 1024) //For write buffering (Page size)
           .build()) {
       //We only have one record to write in our example
       writer.write(record);
   }
} catch (Exception ex) { ex.printStackTrace(System.out); }</code>```

Here is the data loaded into Apache Spark (2.2.0):

And for your convenience, the entire source code:

```<code>package com.mycompany.stackoverflow;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.parquet.avro.AvroParquetWriter;
import org.apache.parquet.hadoop.ParquetWriter;
import org.apache.parquet.hadoop.metadata.CompressionCodecName;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.joda.time.MutableDateTime;

public class Main {
    public static void main(String[] args) {
        System.out.println("Start");

        String schema = "{\"namespace\": \"org.myorganization.mynamespace\"," //Not used in Parquet, can put anything
                + "\"type\": \"record\"," //Must be set as record
                + "\"name\": \"myrecordname\"," //Not used in Parquet, can put anything
                + "\"fields\": ["
                + " {\"name\": \"myInteger\", \"type\": \"int\"}," //Required field
                + " {\"name\": \"myString\",  \"type\": [\"string\", \"null\"]},"
                + " {\"name\": \"myDecimal\", \"type\": [{\"type\": \"fixed\", \"size\":16, \"logicalType\": \"decimal\", \"name\": \"mydecimaltype1\", \"precision\": 32, \"scale\": 4}, \"null\"]},"
                + " {\"name\": \"myDate\", \"type\": [{\"type\": \"int\", \"logicalType\" : \"date\"}, \"null\"]}"
                + " ]}";

        Schema.Parser parser = new Schema.Parser().setValidate(true);
        Schema avroSchema = parser.parse(schema);

        GenericData.Record record = new GenericData.Record(avroSchema);
        record.put("myInteger", 1);
        record.put("myString", "string value 1");

        BigDecimal myDecimalValue = new BigDecimal("99.9999");

        //First we need to make sure the huge decimal matches our schema scale:
        myDecimalValue = myDecimalValue.setScale(4, RoundingMode.HALF_UP);

        //Next we get the decimal value as one BigInteger (like there was no decimal point)
        BigInteger myUnscaledDecimalValue = myDecimalValue.unscaledValue();

        //Finally we serialize the integer
        byte[] decimalBytes = myUnscaledDecimalValue.toByteArray();

        //We need to create an Avro 'Fixed' type and pass the decimal schema once more here:
        GenericData.Fixed fixed = new GenericData.Fixed(new Schema.Parser().parse("{\"type\": \"fixed\", \"size\":16, \"precision\": 32, \"scale\": 4, \"name\":\"mydecimaltype1\"}"));

        byte[] myDecimalBuffer = new byte[16];
        if (myDecimalBuffer.length >= decimalBytes.length) {
            //Because we set our fixed byte array size as 16 bytes, we need to
            //pad-left our original value's bytes with zeros
            int myDecimalBufferIndex = myDecimalBuffer.length - 1;
            for(int i = decimalBytes.length - 1; i >= 0; i--){
                myDecimalBuffer[myDecimalBufferIndex] = decimalBytes[i];
                myDecimalBufferIndex--;
            }

            //Save result
            fixed.bytes(myDecimalBuffer);
        } else {
            throw new IllegalArgumentException(String.format("Decimal size: %d was greater than the allowed max: %d", decimalBytes.length, myDecimalBuffer.length));
        }

        //We can finally write our decimal to our record
        record.put("myDecimal", fixed);

        //Get epoch value
        MutableDateTime epoch = new MutableDateTime(0l, DateTimeZone.UTC);

        DateTime currentDate = new DateTime(); //Can take Java Date in constructor
        Days days = Days.daysBetween(epoch, currentDate);

        //We can write number of days since epoch into the record
        record.put("myDate", days.getDays());

        try {
           Configuration conf = new Configuration();
           conf.set("fs.s3a.access.key", "ACCESSKEY");
           conf.set("fs.s3a.secret.key", "SECRETKEY");
           //Below are some other helpful settings
           //conf.set("fs.s3a.endpoint", "s3.amazonaws.com");
           //conf.set("fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider");
           //conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); // Not needed unless you reference the hadoop-hdfs library.
           //conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); // Uncomment if you get "No FileSystem for scheme: file" errors.

           Path path = new Path("s3a://your-bucket-name/examplefolder/data.parquet");

           //Use path below to save to local file system instead
           //Path path = new Path("data.parquet");

           try (ParquetWriter<GenericData.Record> writer = AvroParquetWriter.<GenericData.Record>builder(path)
                   .withSchema(avroSchema)
                   .withCompressionCodec(CompressionCodecName.GZIP)
                   .withConf(conf)
                   .withPageSize(4 * 1024 * 1024) //For compression
                   .withRowGroupSize(16 * 1024 * 1024) //For write buffering (Page size)
                   .build()) {

               //We only have one record to write in our example
               writer.write(record);
           }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Disclaimer: The code samples below in no way represent best practices and are only presented as a rough how-to.

Dependencies:

parquet-avro (1.9.0) : https://mvnrepository.com/artifact/org.apache.parquet/parquet-avro/1.9.0 (We use 1.9.0 because this version uses Avro 1.8+ which supports Decimals and Dates)

hadoop-aws (2.8.2) [If you don't plan on writing to S3 you won't need this but you will need to add several other dependencies that normally get added thanks to this. I will not cover that scenario. So even if you're going to generate Parquet files only on your local disk, you can still add this to your project as a dependency]: https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-aws/2.8.2 (We use this because it was the latest version at the time)

Hadoop 2.8.1: https://github.com/steveloughran/winutils/tree/master/hadoop-2.8.1 (We use 2.8.X because it needs to match the hadoop libraries used in the parquet-avro and hadoop-aws dependencies)

I'll be using NetBeans as my IDE.

Some info regarding parquet in Java (For noobs such as me):

In order to serialize your data into parquet, you must choose one of the popular Java data serialization frameworks: Avro, Protocol Buffers or Thrift (I'll be using Avro (1.8.0), as can be seen from our parquet-avro dependency)

You will need to use an IDE that supports Maven. This is because the dependencies above have a lot of dependencies of their own. Maven will automatically download those for you (like NuGet for VisualStudio)

Pre-requisite:

You must have hadoop on the windows machine that will be running the Java code. The good news is you don't need to install the entire hadoop software, rather you need only two files:

hadoop.dll

winutils.exe

These can be downloaded here. You will need version 2.8.1 for this example (due to parquet-avro 1.9.0).

Copy these files to C:\hadoop-2.8.1\bin on the target machine.

Add a new System Variable (not user variable) called: HADOOP_HOME with the value C:\hadoop-2.8.1

Modify the System Path variable (not user variable) and add the following to the end: %HADOOP_HOME%\bin

Restart the machine for changes to take affect.

If this config was not done properly you will get the following error at run-time: java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z

Getting Started with Coding:

First create a new empty Maven Project and add parquet-avro 1.9.0 and hadoop-aws 2.8.2 as dependencies:

Create your main class where you can write some code

First thing is you need to generate a Schema. Now as far as I can tell there is no way you can generate a schema programmatically at run-time. the Schema.Parser class' parse() method only takes a file or a string literal as a parameter and doesn't let you modify the schema once it is created.
To circumvent this I am generating my Schema JSON at run time and parsing that. Below is an example Schema:

String schema = "{\"namespace\": \"org.myorganization.mynamespace\"," //Not used in Parquet, can put anything
    + "\"type\": \"record\"," //Must be set as record
    + "\"name\": \"myrecordname\"," //Not used in Parquet, can put anything
    + "\"fields\": ["
    + " {\"name\": \"myInteger\", \"type\": \"int\"}," //Required field
    + " {\"name\": \"myString\",  \"type\": [\"string\", \"null\"]},"
    + " {\"name\": \"myDecimal\", \"type\": [{\"type\": \"fixed\", \"size\":16, \"logicalType\": \"decimal\", \"name\": \"mydecimaltype1\", \"precision\": 32, \"scale\": 4}, \"null\"]},"
    + " {\"name\": \"myDate\", \"type\": [{\"type\": \"int\", \"logicalType\" : \"date\"}, \"null\"]}"
    + " ]}";
Parser parser = new Schema.Parser().setValidate(true);
Schema avroSchema = parser.parse(schema);

Details on Avro schema can be found here: https://avro.apache.org/docs/1.8.0/spec.html

Next we can start generating records (Avro primitive types are simple):

GenericData.Record record = new GenericData.Record(avroSchema);
record.put("myInteger", 1);
record.put("myString", "string value 1");

In order to generate a decimal logical type a fixed or bytes primitive type must be used as the actual data type for storage. The current Parquet format only supports Fixed length byte arrays (aka: fixed_len_byte_array). So we have to use fixed in our case as well (as can be seen in the schema). In Java we must use BigDecimal in order to truly handle decimals. And I've identified that a Decimal(32,4) will not take more than 16 bytes no matter the value. So we will use a standard byte array size of 16 in our serialization below (and in the schema above):

BigDecimal myDecimalValue = new BigDecimal("99.9999");

//First we need to make sure the BigDecimal matches our schema scale:
myDecimalValue = myDecimalValue.setScale(4, RoundingMode.HALF_UP);

//Next we get the decimal value as one BigInteger (like there was no decimal point)
BigInteger myUnscaledDecimalValue = myDecimalValue.unscaledValue();

//Finally we serialize the integer
byte[] decimalBytes = myUnscaledDecimalValue.toByteArray();

//We need to create an Avro 'Fixed' type and pass the decimal schema once more here:
GenericData.Fixed fixed = new GenericData.Fixed(new Schema.Parser().parse("{\"type\": \"fixed\", \"size\":16, \"precision\": 32, \"scale\": 4, \"name\":\"mydecimaltype1\"}"));

byte[] myDecimalBuffer = new byte[16];
if (myDecimalBuffer.length >= decimalBytes.length) {
    //Because we set our fixed byte array size as 16 bytes, we need to
    //pad-left our original value's bytes with zeros
    int myDecimalBufferIndex = myDecimalBuffer.length - 1;
    for(int i = decimalBytes.length - 1; i >= 0; i--){
        myDecimalBuffer[myDecimalBufferIndex] = decimalBytes[i];
        myDecimalBufferIndex--;
    }
    //Save result
    fixed.bytes(myDecimalBuffer);
} else {
    throw new IllegalArgumentException(String.format("Decimal size: %d was greater than the allowed max: %d", decimalBytes.length, myDecimalBuffer.length));
}

//We can finally write our decimal to our record
record.put("myDecimal", fixed);

For Date values, Avro specifies that we need to save the number of days since EPOCH as an integer. (If you need the time component as well, such as an actual DateTime type, you need to use the Timestamp Avro type, which I will not cover).
The easiest way I found to get the number of days since epoch is using the joda-time library. If you added the hadoop-aws dependency to your project you should already have this library. If not you will need to add it yourself:

//Get epoch value
MutableDateTime epoch = new MutableDateTime(0l, DateTimeZone.UTC);

DateTime currentDate = new DateTime(); //Can take Java Date in constructor
Days days = Days.daysBetween(epoch, currentDate);

//We can write number of days since epoch into the record
record.put("myDate", days.getDays());

We finally can start writing our parquet file as such

try {
   Configuration conf = new Configuration();
   conf.set("fs.s3a.access.key", "ACCESSKEY");
   conf.set("fs.s3a.secret.key", "SECRETKEY");
   //Below are some other helpful settings
   //conf.set("fs.s3a.endpoint", "s3.amazonaws.com");
   //conf.set("fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider");
   //conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); // Not needed unless you reference the hadoop-hdfs library.
   //conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); // Uncomment if you get "No FileSystem for scheme: file" errors

   Path path = new Path("s3a://your-bucket-name/examplefolder/data.parquet");

   //Use path below to save to local file system instead
   //Path path = new Path("data.parquet");

   try (ParquetWriter writer = AvroParquetWriter.builder(path)
           .withSchema(avroSchema)
           .withCompressionCodec(CompressionCodecName.GZIP)
           .withConf(conf)
           .withPageSize(4 * 1024 * 1024) //For compression
           .withRowGroupSize(16 * 1024 * 1024) //For write buffering (Page size)
           .build()) {
       //We only have one record to write in our example
       writer.write(record);
   }
} catch (Exception ex) { ex.printStackTrace(System.out); }

Here is the data loaded into Apache Spark (2.2.0):

And for your convenience, the entire source code:

package com.mycompany.stackoverflow;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.parquet.avro.AvroParquetWriter;
import org.apache.parquet.hadoop.ParquetWriter;
import org.apache.parquet.hadoop.metadata.CompressionCodecName;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.joda.time.MutableDateTime;

public class Main {
    public static void main(String[] args) {
        System.out.println("Start");

        String schema = "{\"namespace\": \"org.myorganization.mynamespace\"," //Not used in Parquet, can put anything
                + "\"type\": \"record\"," //Must be set as record
                + "\"name\": \"myrecordname\"," //Not used in Parquet, can put anything
                + "\"fields\": ["
                + " {\"name\": \"myInteger\", \"type\": \"int\"}," //Required field
                + " {\"name\": \"myString\",  \"type\": [\"string\", \"null\"]},"
                + " {\"name\": \"myDecimal\", \"type\": [{\"type\": \"fixed\", \"size\":16, \"logicalType\": \"decimal\", \"name\": \"mydecimaltype1\", \"precision\": 32, \"scale\": 4}, \"null\"]},"
                + " {\"name\": \"myDate\", \"type\": [{\"type\": \"int\", \"logicalType\" : \"date\"}, \"null\"]}"
                + " ]}";

        Schema.Parser parser = new Schema.Parser().setValidate(true);
        Schema avroSchema = parser.parse(schema);

        GenericData.Record record = new GenericData.Record(avroSchema);
        record.put("myInteger", 1);
        record.put("myString", "string value 1");

        BigDecimal myDecimalValue = new BigDecimal("99.9999");

        //First we need to make sure the huge decimal matches our schema scale:
        myDecimalValue = myDecimalValue.setScale(4, RoundingMode.HALF_UP);

        //Next we get the decimal value as one BigInteger (like there was no decimal point)
        BigInteger myUnscaledDecimalValue = myDecimalValue.unscaledValue();

        //Finally we serialize the integer
        byte[] decimalBytes = myUnscaledDecimalValue.toByteArray();

        //We need to create an Avro 'Fixed' type and pass the decimal schema once more here:
        GenericData.Fixed fixed = new GenericData.Fixed(new Schema.Parser().parse("{\"type\": \"fixed\", \"size\":16, \"precision\": 32, \"scale\": 4, \"name\":\"mydecimaltype1\"}"));

        byte[] myDecimalBuffer = new byte[16];
        if (myDecimalBuffer.length >= decimalBytes.length) {
            //Because we set our fixed byte array size as 16 bytes, we need to
            //pad-left our original value's bytes with zeros
            int myDecimalBufferIndex = myDecimalBuffer.length - 1;
            for(int i = decimalBytes.length - 1; i >= 0; i--){
                myDecimalBuffer[myDecimalBufferIndex] = decimalBytes[i];
                myDecimalBufferIndex--;
            }

            //Save result
            fixed.bytes(myDecimalBuffer);
        } else {
            throw new IllegalArgumentException(String.format("Decimal size: %d was greater than the allowed max: %d", decimalBytes.length, myDecimalBuffer.length));
        }

        //We can finally write our decimal to our record
        record.put("myDecimal", fixed);

        //Get epoch value
        MutableDateTime epoch = new MutableDateTime(0l, DateTimeZone.UTC);

        DateTime currentDate = new DateTime(); //Can take Java Date in constructor
        Days days = Days.daysBetween(epoch, currentDate);

        //We can write number of days since epoch into the record
        record.put("myDate", days.getDays());

        try {
           Configuration conf = new Configuration();
           conf.set("fs.s3a.access.key", "ACCESSKEY");
           conf.set("fs.s3a.secret.key", "SECRETKEY");
           //Below are some other helpful settings
           //conf.set("fs.s3a.endpoint", "s3.amazonaws.com");
           //conf.set("fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider");
           //conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); // Not needed unless you reference the hadoop-hdfs library.
           //conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); // Uncomment if you get "No FileSystem for scheme: file" errors.

           Path path = new Path("s3a://your-bucket-name/examplefolder/data.parquet");

           //Use path below to save to local file system instead
           //Path path = new Path("data.parquet");

           try (ParquetWriter<GenericData.Record> writer = AvroParquetWriter.<GenericData.Record>builder(path)
                   .withSchema(avroSchema)
                   .withCompressionCodec(CompressionCodecName.GZIP)
                   .withConf(conf)
                   .withPageSize(4 * 1024 * 1024) //For compression
                   .withRowGroupSize(16 * 1024 * 1024) //For write buffering (Page size)
                   .build()) {

               //We only have one record to write in our example
               writer.write(record);
           }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }
}


问:
Can't read incoming SMS messages with AT+CMGL=ALL
I am using a PHP's Digital_IO to connect with a usb connected modem, I have been using a Digi Xbee LTE. I have it working great to send SMS messages, but can't find how to pull up the list of incoming messages.

This seems like a no-brainer, I have read a dozen tutorials like this one: http://www.developershome.com/sms/howToReceiveSMSUsingPC.asp#11.1 and they all point me back to AT+CMGL, which doesn't seem to be doing anything. Here is a console log. Near the end you can see a MSG (+CMT: "4805554667") I sent from my phone to the device show up unsolicited as it was received, but then it didn't seem to be stored anywhere.

The only thing I ever get back when I do the AT+CMGL is "OK". I tried pulling up individual ones using AT+CMGR=1-100 and got nothing back but "OK" I also tried changing where the "preferred storage" was using AT+CPMS, but couldn't make any headway.

```<code>AT
OK

at+CMGF=1
OK

OK
at+cmgs="4805554667"
> Outbound Test
>
+CMGS: 193

OK

at+cmgl
OK

AT+COPS?
+COPS: 0,0,"Verizon",7

OK
AT+CMGR="193"
ERROR

AT+CMGR=193
+CMS ERROR: 321

AT+CMGR=1
OK
AT+CMGR=2
OK
AT+CMGR=3
OK

AT+CPMS?
+CPMS: "ME",0,100,"ME",0,100,"ME",0,100
OK

AT+CPMS=?
+CPMS: ("SM","ME"),("SM","ME"),("SM","ME")
OK

AT+CPMS=SM,SM,SM
+CPMS: 0,0,0,0,0,0
OK

AT+CPMS?
+CPMS: "SM",0,0,"SM",0,0,"SM",0,0
OK

at+CMGF=1
OK
AT+CMGL="ALL"
OK

at+CMGF=0
OK

AT+CMGL="ALL"
ERROR

AT+CMGL
OK

AT+CMGL=?
+CMGL: (0-4)
OK

AT+CMGL=0
OK

AT+CMGL
OK

at+CMGF=1
OK
AT+CMGL
OK

AT+CMGL=?
+CMGL: ("REC UNREAD","REC READ","STO UNSENT","STO SENT","ALL")
OK

AT+CMGL=ALL
OK
AT+CMGL="ALL"
OK

AT+CMGL="REC UNREAD"
OK

AT+CPMS=me
+CPMS: "ME",0,100,"ME",0,100,"ME",0,100
OK

+CMT: "4805554027","","17/11/15,18:42:11+00"
Incoming Test

AT+CSCS=?
+CSCS: ("GSM","IRA","8859-1","PCCP437","UCS2")
OK

AT+CSCS?
+CSCS: "IRA"
OK

AT+CSCS="GSM"
OK

AT+CMGL=ALL
OK

AT+CPMS?
+CPMS: "ME",0,100,"ME",0,100,"ME",0,100
OK
</code>```

答:
So it turns out the Telit firmware version that is on the Digi Xbee LTE Cat1 doesn't support storing incoming messages. Here is the response I got from Digi.

The Telit LE866-SV1 modem running firmware version 23.00.002, does not
  support SMS Storage within the modem. This is a known limitation of
  that version of the Telit firmware which has been addressed in Telit
  firmware version 23.00.004 for which Digi has not implemented yet.

  When using the current version of the XBee Code installed with bypass
  mode, you must configure the AT+CNMI to generate a +CMT notification
  and handle the incoming message immediately as they arrive.

So yes, with Telit firmware version 23.00.002, the AT+CMGL="ALL" will
  be empty. At lest until we release a new version that includes the
  updated Telit code.

Body:
I am using a PHP's Digital_IO to connect with a usb connected modem, I have been using a Digi Xbee LTE. I have it working great to send SMS messages, but can't find how to pull up the list of incoming messages.

This seems like a no-brainer, I have read a dozen tutorials like this one: http://www.developershome.com/sms/howToReceiveSMSUsingPC.asp#11.1 and they all point me back to AT+CMGL, which doesn't seem to be doing anything. Here is a console log. Near the end you can see a MSG (+CMT: "4805554667") I sent from my phone to the device show up unsolicited as it was received, but then it didn't seem to be stored anywhere.

The only thing I ever get back when I do the AT+CMGL is "OK". I tried pulling up individual ones using AT+CMGR=1-100 and got nothing back but "OK" I also tried changing where the "preferred storage" was using AT+CPMS, but couldn't make any headway.

AT
OK

at+CMGF=1
OK

OK
at+cmgs="4805554667"
> Outbound Test
>
+CMGS: 193

OK

at+cmgl
OK

AT+COPS?
+COPS: 0,0,"Verizon",7

OK
AT+CMGR="193"
ERROR

AT+CMGR=193
+CMS ERROR: 321

AT+CMGR=1
OK
AT+CMGR=2
OK
AT+CMGR=3
OK

AT+CPMS?
+CPMS: "ME",0,100,"ME",0,100,"ME",0,100
OK

AT+CPMS=?
+CPMS: ("SM","ME"),("SM","ME"),("SM","ME")
OK

AT+CPMS=SM,SM,SM
+CPMS: 0,0,0,0,0,0
OK

AT+CPMS?
+CPMS: "SM",0,0,"SM",0,0,"SM",0,0
OK

at+CMGF=1
OK
AT+CMGL="ALL"
OK

at+CMGF=0
OK

AT+CMGL="ALL"
ERROR

AT+CMGL
OK

AT+CMGL=?
+CMGL: (0-4)
OK

AT+CMGL=0
OK

AT+CMGL
OK

at+CMGF=1
OK
AT+CMGL
OK

AT+CMGL=?
+CMGL: ("REC UNREAD","REC READ","STO UNSENT","STO SENT","ALL")
OK

AT+CMGL=ALL
OK
AT+CMGL="ALL"
OK

AT+CMGL="REC UNREAD"
OK

AT+CPMS=me
+CPMS: "ME",0,100,"ME",0,100,"ME",0,100
OK

+CMT: "4805554027","","17/11/15,18:42:11+00"
Incoming Test

AT+CSCS=?
+CSCS: ("GSM","IRA","8859-1","PCCP437","UCS2")
OK

AT+CSCS?
+CSCS: "IRA"
OK

AT+CSCS="GSM"
OK

AT+CMGL=ALL
OK

AT+CPMS?
+CPMS: "ME",0,100,"ME",0,100,"ME",0,100
OK


问:
What is the most simple way to remove a row in a CSV using Python CSV?
I'm having trouble finding clear and concise methods of removing a select row from a CSV using the CSV module (not the Panda since it's required to be installed). I would also like to remove a range of rows separately. Every article and every question I've seen either or abroad are not clear at all and tend to include specific logic people are asking about. I just want a clear cut answer that is very simple. </p>

<p>I would like to use argv to provide a filename, beginning row number, and end row numbers. So something like python Script.py /CSVfile.csv 1 5, meaning the file name and remove rows 1 through 5 (beginning and ending). I'm new to Python scripting and I get halfway there, but there is always some logic people include that isn't relevant to what I need to do. I just keep getting blocked (as I typically do when trying to code), any help is appreciated. </p>

```<code>import csv
import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

with open (var1, 'w') as file1:
   reader = csv.reader(file1)
   for line in reader:
      file1.writer()
</code>```

答:
similar question here

```<code>with open("foo.txt", "r+") as f:
     old = f.read() # read everything in the file
     f.seek(0) # rewind
     f.write("new line\n" + old) # write the new line before
</code>```

go to line number using seek and add '\n' or whatever.

Body:
I'm having trouble finding clear and concise methods of removing a select row from a CSV using the CSV module (not the Panda since it's required to be installed). I would also like to remove a range of rows separately. Every article and every question I've seen either or abroad are not clear at all and tend to include specific logic people are asking about. I just want a clear cut answer that is very simple.

I would like to use argv to provide a filename, beginning row number, and end row numbers. So something like python Script.py /CSVfile.csv 1 5, meaning the file name and remove rows 1 through 5 (beginning and ending). I'm new to Python scripting and I get halfway there, but there is always some logic people include that isn't relevant to what I need to do. I just keep getting blocked (as I typically do when trying to code), any help is appreciated.

import csv
import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

with open (var1, 'w') as file1:
   reader = csv.reader(file1)
   for line in reader:
      file1.writer()

Body:
similar question here

with open("foo.txt", "r+") as f:
     old = f.read() # read everything in the file
     f.seek(0) # rewind
     f.write("new line\n" + old) # write the new line before

go to line number using seek and add '\n' or whatever.


问:
Unable to select a row in gridview in Asp.net c# WebForms application
I have a gridview in an Asp.net c# web application that I populate using a sqldatasource in the code behind.  The gridview ma

<telerik:RadGrid ID="rgAssnmtList" runat="server" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" AllowFilteringByColumn="True" ShowGroupPanel="True" Skin="Default" OnSelectedIndexChanged="rgAssnmtList_SelectedIndexChanged" OnPreRender="rgAssnmtList_PreRender" OnItemCommand="rgAssnmtList_ItemCommand">
                <ClientSettings AllowDragToGroup="True" AllowColumnsReorder="True" ReorderColumnsOnClient="True"></ClientSettings>
                <MasterTableView DataKeyNames="assnmtIdPk">
                    <Columns>
                        <telerik:GridButtonColumn ButtonType="LinkButton" CommandName="Select" Text="Select" HeaderStyle-Font-Bold="true" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"></telerik:GridButtonColumn>
                        <telerik:GridBoundColumn DataField="assnmtIdPk" ReadOnly="True" HeaderText="assnmtIdPk" SortExpression="assnmtIdPk" UniqueName="assnmtIdPk" DataType="System.Int32" FilterControlAltText="Filter assnmtIdPk column"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Id" ReadOnly="true" HeaderText="Id" SortExpression="Id" UniqueName="Id" FilterControlAltText="Filter Id column"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="clientIdPk" ReadOnly="true" HeaderText="clientIdPk" SortExpression="clientIdPk" UniqueName="clientIdPk" DataType="System.Int32" FilterControlAltText="Filter clientIdPk column"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="clientNm" ReadOnly="true" HeaderText="Client" SortExpression="clientNm" UniqueName="clientNm" FilterControlAltText="clientNm" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="assnmtClmNo" ReadOnly="true" HeaderText="Claim" SortExpression="assnmtClmNo" UniqueName="assnmtClmNo" FilterControlAltText="assnmtClmNo" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="invNo" ReadOnly="true" HeaderText="Invoice" SortExpression="invNo" UniqueName="invNo" FilterControlAltText="invNo" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="assnmtCrtdDt" ReadOnly="true" HeaderText="Rcd. Date" SortExpression="assnmtCrtdDt" UniqueName="assnmtCrtdDt" FilterControlAltText="assnmtCrtdDt" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="inspDt" ReadOnly="true" HeaderText="Inspection Date/Time" SortExpression="inspDt" UniqueName="inspDt" FilterControlAltText="inspDt" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="stat" ReadOnly="true" HeaderText="Status" SortExpression="stat" UniqueName="stat" FilterControlAltText="stat" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="FirstName" ReadOnly="true" HeaderText="First Name" SortExpression="FirstName" UniqueName="FirstName" FilterControlAltText="FirstName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="LastName" ReadOnly="true" HeaderText="Last Name" SortExpression="LastName" UniqueName="LastName" FilterControlAltText="LastName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>```
</div>
</div>
</p>

<p>The sqldatasource is:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>protected void Page_Load(object sender, EventArgs e)
        {
            //Identify the current user
            crntUserId.Value = HttpContext.Current.User.Identity.GetUserId();
            //crntUserIdLbl.Text = HttpContext.Current.User.Identity.GetUserId();

            //populate a hidden control with the current user's ID
            hdnCrntUsr.Value = HttpContext.Current.User.Identity.GetUserId();
            string currentUserId = hdnCrntUsr.Value;

            //populate a hidden control with the current user's company Id and another with the company name
            SqlDataSource sdsAssnmtList = new SqlDataSource();
            sdsAssnmtList.ID = "sdsAssnmtList";
            this.Page.Controls.Add(sdsAssnmtList);
            sdsAssnmtList.DataSourceMode = SqlDataSourceMode.DataSet;
            sdsAssnmtList.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            sdsAssnmtList.SelectCommand = "SELECT anu.Id, anu.FirstName, anu.LastName, uc.clientIdFk, c.clientNm FROM AspNetUsers anu INNER JOIN AspNetUserComps uc ON anu.Id = uc.anuIdFk INNER JOIN clients c ON c.clientIdPk = uc.clientIdFk WHERE Id = @Id";
            sdsAssnmtList.SelectParameters.Clear();
            sdsAssnmtList.SelectParameters.Add("Id", currentUserId);

            System.Data.DataView assnmtListDV = (DataView)sdsAssnmtList.Select(DataSourceSelectArguments.Empty);
            DataTable assnmtListDT = assnmtListDV.ToTable();
            DataSet assnmtListDS = new DataSet();
            assnmtListDS.Tables.Add(assnmtListDT);

            DataRow row = assnmtListDT.Rows[0];
            hdnCompId.Value = row["clientIdFk"].ToString();
            hdnCompNm.Value = row["clientNm"].ToString();

            //populate the grid based on the role and company of the current user
            //can see all of the assignments in the system
            if (HttpContext.Current.User.IsInRole("AKOB") || (HttpContext.Current.User.IsInRole("aQA") || (HttpContext.Current.User.IsInRole("aMgr"))))
            {
                SqlDataSource sdsAkobAssnmtList = new SqlDataSource();
                sdsAkobAssnmtList.ID = "sdsAkobAssnmtList";
                this.Page.Controls.Add(sdsAkobAssnmtList);
                sdsAkobAssnmtList.DataSourceMode = SqlDataSourceMode.DataSet;
                sdsAkobAssnmtList.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                sdsAkobAssnmtList.SelectCommand = "SELECT a.assnmtIdPk, c.clientIdPk, c.clientNm, a.assnmtClmNo, a.assnmtCrtdDt, invs.invNo, " +
                                                   "i.inspDt, s.stat, anu.FirstName, anu.LastName " +
                                                   "FROM assnmts a " +
                                                   "INNER JOIN clients c " +
                                                   "    ON a.assnmtClientId = c.clientIdPk " +
                                                   "LEFT JOIN insps i " +
                                                   "    ON a.assnmtIdPk = i.assntIdFk " +
                                                   "LEFT JOIN invoices invs " +
                                                   "    ON a.assnmtIdPk = invs.assnmtIdFk " +
                                                   "INNER JOIN assnmtStats aStats " +
                                                   "    ON a.assnmtIdPk = aStats.assnmtIdFk " +
                                                   "INNER JOIN statuses s " +
                                                   "    ON aStats.assnmtStat = s.statIdPk " +
                                                   "INNER JOIN( " +
                                                   "            SELECT a2.assnmtIdPk, MAX(aStats2.assnmtStatDtSet) AS MaxDate " +
                                                   "            FROM assnmts a2 " +
                                                   "            INNER JOIN assnmtStats aStats2 " +
                                                   "                ON a2.assnmtIdPk = aStats2.assnmtIdFk " +
                                                   "            GROUP BY a2.assnmtIdPk " +
                                                   "           ) mdt " +
                                                   "    ON a.assnmtIdPk = mdt.assnmtIdPk AND aStats.assnmtStatDtSet = mdt.MaxDate " +
                                                   "INNER JOIN repAssnmts ra " +
                                                   "    ON a.assnmtIdPk = ra.assnmtIdFk " +
                                                   "LEFT JOIN AspNetUsers anu " +
                                                   "    ON anu.Id = ra.repAssnmtRep " +
                                                   "INNER JOIN( " +
                                                   "            SELECT a3.assnmtIdPk, Max(ra2.repAssnmtCrtdDt) AS MaxDate2 " +
                                                   "            FROM assnmts a3 " +
                                                   "INNER JOIN repAssnmts ra2 " +
                                                   "    ON a3.assnmtIdPk = ra2.assnmtIdFk " +
                                                   "GROUP BY a3.assnmtIdPk " +
                                                   ") mdt2 " +
                                                   "    ON a.assnmtIdPk = mdt2.assnmtIdPk AND ra.repAssnmtCrtdDt = mdt2.MaxDate2";
                sdsAkobAssnmtList.SelectParameters.Clear();

                rgAssnmtList.DataSource = sdsAkobAssnmtList;
                rgAssnmtList.DataBind();

                assnmtMgrTabStrip.Visible = true;

                rgAssnmtList.MasterTableView.GetColumn("assnmtIdPk").Display = false;
                rgAssnmtList.MasterTableView.GetColumn("Id").Display = false;
                rgAssnmtList.MasterTableView.GetColumn("clientIdPk").Display = false;
            }}</code>```

The gridview is populated just fine.  I get the correct records.  When I click on the "Select" LinkButton the row is selected and another gridview is populated with it's data based on the primary key (assnmtIdPk) in rgAssnmtList.  This works as well.

The new gridview is:

<telerik:RadGrid ID="rgJournals" runat="server" DataSourceID="sdsRgJourns" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" AllowFilteringByColumn="True" ShowGroupPanel="True" Skin="Default">
                        <ClientSettings AllowDragToGroup="True" AllowColumnsReorder="True" ReorderColumnsOnClient="True"></ClientSettings>
                        <MasterTableView DataKeyNames="journalIdPk" DataSourceID="sdsRgJourns">
                            <Columns>
                                <telerik:GridButtonColumn ButtonType="LinkButton" CommandName="Select" Text="Select"></telerik:GridButtonColumn>
                                <telerik:GridBoundColumn DataField="journalIdPk" ReadOnly="True" HeaderText="journalIdPk" SortExpression="journalIdPk" UniqueName="journalIdPk" DataType="System.Int32" FilterControlAltText="Filter journalIdPk column"></telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="assnmtIdFk" HeaderText="assnmtIdFk" SortExpression="assnmtIdFk" UniqueName="assnmtIdFk" DataType="System.Int32" FilterControlAltText="Filter assnmtIdFk column"></telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="journEntCrtdBy" HeaderText="journEntCrtdBy" SortExpression="journEntCrtdBy" UniqueName="journEntCrtdBy" FilterControlAltText="Filter journEntCrtdBy column"></telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="journEntCrtdDt" HeaderText="journEntCrtdDt" SortExpression="journEntCrtdDt" UniqueName="journEntCrtdDt" DataType="System.DateTime" FilterControlAltText="Filter journEntCrtdDt column"></telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="journTitle" HeaderText="journTitle" SortExpression="journTitle" UniqueName="journTitle" FilterControlAltText="Filter journTitle column"></telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="journEntry" HeaderText="journEntry" SortExpression="journEntry" UniqueName="journEntry" FilterControlAltText="Filter journEntry column"></telerik:GridBoundColumn>
                            </Columns>
                        </MasterTableView>
                    </telerik:RadGrid>```
</div>
</div>
</p>

<p>And it's sqldatasource is:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><asp:SqlDataSource ID="sdsRgJourns" runat="server" ConnectionString='<%$ ConnectionStrings:DefaultConnection %>'
                SelectCommand="SELECT [journalIdPk], [assnmtIdFk], [journEntCrtdBy], [journEntCrtdDt], [journTitle], [journEntry] FROM [journals] WHERE ([assnmtIdFk] = @assnmtIdFk) ORDER BY [journEntCrtdDt] DESC">
                <SelectParameters>
                    <asp:ControlParameter ControlID="rgAssnmtList" PropertyName="SelectedValue" Name="assnmtIdFk" Type="Int32"></asp:ControlParameter>
                </SelectParameters>
            </asp:SqlDataSource></code>```

At this point I expect to be able to click the "Select" button in the new gridview (rgJournals).  But I am unable to select a row, and I don't get an error.

Am I missing something in the sqldatasource for rgAssnmtList?  Maybe some select parameter?

答: This issue is specific to the Telerik RadGrid.  When I switched to using just the asp:GridView it worked as expected.  I just won't be able to use their product for this specific project.  This comment is being left just-in-case anybody else runs into this same issue in the future with this product.</p>

Body:
I have a gridview in an Asp.net c# web application that I populate using a sqldatasource in the code behind.  The gridview ma

<telerik:RadGrid ID="rgAssnmtList" runat="server" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" AllowFilteringByColumn="True" ShowGroupPanel="True" Skin="Default" OnSelectedIndexChanged="rgAssnmtList_SelectedIndexChanged" OnPreRender="rgAssnmtList_PreRender" OnItemCommand="rgAssnmtList_ItemCommand">
                <ClientSettings AllowDragToGroup="True" AllowColumnsReorder="True" ReorderColumnsOnClient="True"></ClientSettings>
                <MasterTableView DataKeyNames="assnmtIdPk">
                    <Columns>
                        <telerik:GridButtonColumn ButtonType="LinkButton" CommandName="Select" Text="Select" HeaderStyle-Font-Bold="true" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"></telerik:GridButtonColumn>
                        <telerik:GridBoundColumn DataField="assnmtIdPk" ReadOnly="True" HeaderText="assnmtIdPk" SortExpression="assnmtIdPk" UniqueName="assnmtIdPk" DataType="System.Int32" FilterControlAltText="Filter assnmtIdPk column"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Id" ReadOnly="true" HeaderText="Id" SortExpression="Id" UniqueName="Id" FilterControlAltText="Filter Id column"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="clientIdPk" ReadOnly="true" HeaderText="clientIdPk" SortExpression="clientIdPk" UniqueName="clientIdPk" DataType="System.Int32" FilterControlAltText="Filter clientIdPk column"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="clientNm" ReadOnly="true" HeaderText="Client" SortExpression="clientNm" UniqueName="clientNm" FilterControlAltText="clientNm" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="assnmtClmNo" ReadOnly="true" HeaderText="Claim" SortExpression="assnmtClmNo" UniqueName="assnmtClmNo" FilterControlAltText="assnmtClmNo" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="invNo" ReadOnly="true" HeaderText="Invoice" SortExpression="invNo" UniqueName="invNo" FilterControlAltText="invNo" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="assnmtCrtdDt" ReadOnly="true" HeaderText="Rcd. Date" SortExpression="assnmtCrtdDt" UniqueName="assnmtCrtdDt" FilterControlAltText="assnmtCrtdDt" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="inspDt" ReadOnly="true" HeaderText="Inspection Date/Time" SortExpression="inspDt" UniqueName="inspDt" FilterControlAltText="inspDt" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="stat" ReadOnly="true" HeaderText="Status" SortExpression="stat" UniqueName="stat" FilterControlAltText="stat" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="FirstName" ReadOnly="true" HeaderText="First Name" SortExpression="FirstName" UniqueName="FirstName" FilterControlAltText="FirstName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="LastName" ReadOnly="true" HeaderText="Last Name" SortExpression="LastName" UniqueName="LastName" FilterControlAltText="LastName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="true"></telerik:GridBoundColumn>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>

The sqldatasource is:

protected void Page_Load(object sender, EventArgs e)
        {
            //Identify the current user
            crntUserId.Value = HttpContext.Current.User.Identity.GetUserId();
            //crntUserIdLbl.Text = HttpContext.Current.User.Identity.GetUserId();

            //populate a hidden control with the current user's ID
            hdnCrntUsr.Value = HttpContext.Current.User.Identity.GetUserId();
            string currentUserId = hdnCrntUsr.Value;

            //populate a hidden control with the current user's company Id and another with the company name
            SqlDataSource sdsAssnmtList = new SqlDataSource();
            sdsAssnmtList.ID = "sdsAssnmtList";
            this.Page.Controls.Add(sdsAssnmtList);
            sdsAssnmtList.DataSourceMode = SqlDataSourceMode.DataSet;
            sdsAssnmtList.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            sdsAssnmtList.SelectCommand = "SELECT anu.Id, anu.FirstName, anu.LastName, uc.clientIdFk, c.clientNm FROM AspNetUsers anu INNER JOIN AspNetUserComps uc ON anu.Id = uc.anuIdFk INNER JOIN clients c ON c.clientIdPk = uc.clientIdFk WHERE Id = @Id";
            sdsAssnmtList.SelectParameters.Clear();
            sdsAssnmtList.SelectParameters.Add("Id", currentUserId);

            System.Data.DataView assnmtListDV = (DataView)sdsAssnmtList.Select(DataSourceSelectArguments.Empty);
            DataTable assnmtListDT = assnmtListDV.ToTable();
            DataSet assnmtListDS = new DataSet();
            assnmtListDS.Tables.Add(assnmtListDT);

            DataRow row = assnmtListDT.Rows[0];
            hdnCompId.Value = row["clientIdFk"].ToString();
            hdnCompNm.Value = row["clientNm"].ToString();

            //populate the grid based on the role and company of the current user
            //can see all of the assignments in the system
            if (HttpContext.Current.User.IsInRole("AKOB") || (HttpContext.Current.User.IsInRole("aQA") || (HttpContext.Current.User.IsInRole("aMgr"))))
            {
                SqlDataSource sdsAkobAssnmtList = new SqlDataSource();
                sdsAkobAssnmtList.ID = "sdsAkobAssnmtList";
                this.Page.Controls.Add(sdsAkobAssnmtList);
                sdsAkobAssnmtList.DataSourceMode = SqlDataSourceMode.DataSet;
                sdsAkobAssnmtList.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                sdsAkobAssnmtList.SelectCommand = "SELECT a.assnmtIdPk, c.clientIdPk, c.clientNm, a.assnmtClmNo, a.assnmtCrtdDt, invs.invNo, " +
                                                   "i.inspDt, s.stat, anu.FirstName, anu.LastName " +
                                                   "FROM assnmts a " +
                                                   "INNER JOIN clients c " +
                                                   "    ON a.assnmtClientId = c.clientIdPk " +
                                                   "LEFT JOIN insps i " +
                                                   "    ON a.assnmtIdPk = i.assntIdFk " +
                                                   "LEFT JOIN invoices invs " +
                                                   "    ON a.assnmtIdPk = invs.assnmtIdFk " +
                                                   "INNER JOIN assnmtStats aStats " +
                                                   "    ON a.assnmtIdPk = aStats.assnmtIdFk " +
                                                   "INNER JOIN statuses s " +
                                                   "    ON aStats.assnmtStat = s.statIdPk " +
                                                   "INNER JOIN( " +
                                                   "            SELECT a2.assnmtIdPk, MAX(aStats2.assnmtStatDtSet) AS MaxDate " +
                                                   "            FROM assnmts a2 " +
                                                   "            INNER JOIN assnmtStats aStats2 " +
                                                   "                ON a2.assnmtIdPk = aStats2.assnmtIdFk " +
                                                   "            GROUP BY a2.assnmtIdPk " +
                                                   "           ) mdt " +
                                                   "    ON a.assnmtIdPk = mdt.assnmtIdPk AND aStats.assnmtStatDtSet = mdt.MaxDate " +
                                                   "INNER JOIN repAssnmts ra " +
                                                   "    ON a.assnmtIdPk = ra.assnmtIdFk " +
                                                   "LEFT JOIN AspNetUsers anu " +
                                                   "    ON anu.Id = ra.repAssnmtRep " +
                                                   "INNER JOIN( " +
                                                   "            SELECT a3.assnmtIdPk, Max(ra2.repAssnmtCrtdDt) AS MaxDate2 " +
                                                   "            FROM assnmts a3 " +
                                                   "INNER JOIN repAssnmts ra2 " +
                                                   "    ON a3.assnmtIdPk = ra2.assnmtIdFk " +
                                                   "GROUP BY a3.assnmtIdPk " +
                                                   ") mdt2 " +
                                                   "    ON a.assnmtIdPk = mdt2.assnmtIdPk AND ra.repAssnmtCrtdDt = mdt2.MaxDate2";
                sdsAkobAssnmtList.SelectParameters.Clear();

                rgAssnmtList.DataSource = sdsAkobAssnmtList;
                rgAssnmtList.DataBind();

                assnmtMgrTabStrip.Visible = true;

                rgAssnmtList.MasterTableView.GetColumn("assnmtIdPk").Display = false;
                rgAssnmtList.MasterTableView.GetColumn("Id").Display = false;
                rgAssnmtList.MasterTableView.GetColumn("clientIdPk").Display = false;
            }}

The gridview is populated just fine.  I get the correct records.  When I click on the "Select" LinkButton the row is selected and another gridview is populated with it's data based on the primary key (assnmtIdPk) in rgAssnmtList.  This works as well.

The new gridview is:

<telerik:RadGrid ID="rgJournals" runat="server" DataSourceID="sdsRgJourns" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" AllowFilteringByColumn="True" ShowGroupPanel="True" Skin="Default">
                        <ClientSettings AllowDragToGroup="True" AllowColumnsReorder="True" ReorderColumnsOnClient="True"></ClientSettings>
                        <MasterTableView DataKeyNames="journalIdPk" DataSourceID="sdsRgJourns">
                            <Columns>
                                <telerik:GridButtonColumn ButtonType="LinkButton" CommandName="Select" Text="Select"></telerik:GridButtonColumn>
                                <telerik:GridBoundColumn DataField="journalIdPk" ReadOnly="True" HeaderText="journalIdPk" SortExpression="journalIdPk" UniqueName="journalIdPk" DataType="System.Int32" FilterControlAltText="Filter journalIdPk column"></telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="assnmtIdFk" HeaderText="assnmtIdFk" SortExpression="assnmtIdFk" UniqueName="assnmtIdFk" DataType="System.Int32" FilterControlAltText="Filter assnmtIdFk column"></telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="journEntCrtdBy" HeaderText="journEntCrtdBy" SortExpression="journEntCrtdBy" UniqueName="journEntCrtdBy" FilterControlAltText="Filter journEntCrtdBy column"></telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="journEntCrtdDt" HeaderText="journEntCrtdDt" SortExpression="journEntCrtdDt" UniqueName="journEntCrtdDt" DataType="System.DateTime" FilterControlAltText="Filter journEntCrtdDt column"></telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="journTitle" HeaderText="journTitle" SortExpression="journTitle" UniqueName="journTitle" FilterControlAltText="Filter journTitle column"></telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="journEntry" HeaderText="journEntry" SortExpression="journEntry" UniqueName="journEntry" FilterControlAltText="Filter journEntry column"></telerik:GridBoundColumn>
                            </Columns>
                        </MasterTableView>
                    </telerik:RadGrid>

And it's sqldatasource is:

<asp:SqlDataSource ID="sdsRgJourns" runat="server" ConnectionString='<%$ ConnectionStrings:DefaultConnection %>'
                SelectCommand="SELECT [journalIdPk], [assnmtIdFk], [journEntCrtdBy], [journEntCrtdDt], [journTitle], [journEntry] FROM [journals] WHERE ([assnmtIdFk] = @assnmtIdFk) ORDER BY [journEntCrtdDt] DESC">
                <SelectParameters>
                    <asp:ControlParameter ControlID="rgAssnmtList" PropertyName="SelectedValue" Name="assnmtIdFk" Type="Int32"></asp:ControlParameter>
                </SelectParameters>
            </asp:SqlDataSource>

At this point I expect to be able to click the "Select" button in the new gridview (rgJournals).  But I am unable to select a row, and I don't get an error.

Am I missing something in the sqldatasource for rgAssnmtList?  Maybe some select parameter?


问:
UIAlertView show when app loads, open
How show a alertview just when the app open, load...

Like everytime that the user open the app, he see the alert ....

答:
@Rafeel put this UIAlertView in your didFinishLaunchingWithOptions method of your AppDelegate and you will always get the UIAlertView when your app launches

```<code>UIAlertView *confirmAlertView=[[UIAlertView alloc]initWithTitle:@"Saved" message:@"Want to save!!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel",nil];
    [confirmAlertView show];
    [confirmAlertView release];
</code>```

Hope it Will Help u!

Title: UIAlertView show when app loads, open

Body:
@Rafeel put this UIAlertView in your didFinishLaunchingWithOptions method of your AppDelegate and you will always get the UIAlertView when your app launches

UIAlertView *confirmAlertView=[[UIAlertView alloc]initWithTitle:@"Saved" message:@"Want to save!!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel",nil];
    [confirmAlertView show];
    [confirmAlertView release];

Hope it Will Help u!


问:
img src relative path in angular 4 returned undefined error
I am trying to display images on my site using this logic:
Upon component initialization, angular will get img links from a web server(google firebase).
The images are hosted in a image host server like imgur.
then the component will update and display the images.

but right now it returned an undefined error.
Detail code is shown below.

from home.component.ts

```<code>import { Component, OnInit, OnChanges } from '@angular/core';
import {HttpResponse, HttpEvent} from '@angular/common/http';
import {DbService} from '../db.service';
import {LEDProduct} from '../LED-product.model';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  sampleLEDLinks: LEDProduct[];

  constructor(private dbService: DbService) { }

  ngOnInit() {
    this.dbService.getHomePageImgs().subscribe(
      (returnedLinks: LEDProduct[]) => {
        this.sampleLEDLinks = returnedLinks;
      }
    );

  }

}
</code>```

from view template

```<code><div class="row" *ngFor="let link of sampleLEDLinks">
  <img  [src]="'//' + link.imgLink" alt="{{link.imgLink}}" width="100">
</div>
</code>```

LED product model template:

```<code>export class LEDProduct {
  public imgLink: string;

  constructor(imgLink: string) {
    this.imgLink = imgLink;
  }

}
</code>```

now, i also logged the returned url to make sure the links are indeed returned to the app.
and this is the console logged returned obj from chrome

```<code>(2) [{…}, {…}]
0
:
{link: "i.imgur.com/hy9aFEq.png"}
1
:
{link: "i.imgur.com/JRITacY.gif"}
length
:
2
__proto__
:
Array(0)
</code>```

but the view is still empty with an error as follow

is it because of the returned type not matched? I am really confused

答:
Try

EDIT:

or put a full absolute url with the hostname

Body:
I am trying to display images on my site using this logic:
Upon component initialization, angular will get img links from a web server(google firebase).
The images are hosted in a image host server like imgur.
then the component will update and display the images.

but right now it returned an undefined error.
Detail code is shown below.

from home.component.ts

import { Component, OnInit, OnChanges } from '@angular/core';
import {HttpResponse, HttpEvent} from '@angular/common/http';
import {DbService} from '../db.service';
import {LEDProduct} from '../LED-product.model';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  sampleLEDLinks: LEDProduct[];

  constructor(private dbService: DbService) { }

  ngOnInit() {
    this.dbService.getHomePageImgs().subscribe(
      (returnedLinks: LEDProduct[]) => {
        this.sampleLEDLinks = returnedLinks;
      }
    );

  }

}

from view template

LED product model template:

export class LEDProduct {
  public imgLink: string;

  constructor(imgLink: string) {
    this.imgLink = imgLink;
  }

}

now, i also logged the returned url to make sure the links are indeed returned to the app.
and this is the console logged returned obj from chrome

(2) [{…}, {…}]
0
:
{link: "i.imgur.com/hy9aFEq.png"}
1
:
{link: "i.imgur.com/JRITacY.gif"}
length
:
2
__proto__
:
Array(0)

but the view is still empty with an error as follow

is it because of the returned type not matched? I am really confused

Body:
Try <img *ngIf="link"  [src]="'//' + link.imgLink" alt="{{link.imgLink}}" width="100">

EDIT:
<img *ngIf="link"  [src]="'/' + link.imgLink" alt="{{link.imgLink}}" width="100">

or put a full absolute url with the hostname


问:
Expire cache fragment not working
I'm trying to cache a side_bar. Into it, there is two list of groups (1: favorite groups, 2: others_groups)

My caching aproach:

1.caching the two lists of groups into my model User

```<code> def cached_groups
    Rails.cache.fetch([self, "groups"]) {groups.to_a}
  end

  def cached_favgroups
    Rails.cache.fetch([self, "fav_groups"]) {fav_groups.to_a}
  end
</code>```

2.caching the entire list and below each of the group

```<code>  <% cache 'cache_all_groups_fav' do %>
    <% current_user.cached_favgroups.each do |group| %>
      <% cache group do %>
        <%= render 'groups/group', group: group %>
      <% end %>
    <% end %>
  <% end %>

  <% cache 'cache_all_groups' do %>
    <% current_user.cached_groups.each do |group| %>
      <% cache group do %>
        <%= render 'groups/group', group: group %>
      <% end %>
    <% end %>
  <% end %>
</code>```

3.Expire the cache into my Groups/Controller

```<code>def favorit
  FavoritGroup.where(group_id: @group.id).where(user_id: current_user.id).first_or_create
  Group.where(group_id: @group.id).where(user_id: current_user.id).delete_all
  expire_fragment('cache_all_groups_fav')
  expire_fragment('cache_all_groups')
  expire_fragment('cached_favgroups')
  expire_fragment('cached_groups')
  expire_fragment('group')
  respond_to do |format|
    format.html { redirect_back }
    format.js { render 'groups/js/favorit' }
  end
end

def unfavorit
  FavoritGroup.where(group_id: @group.id).where(user_id: current_user.id).delete_all
  Group.where(group_id: @group.id).where(user_id: current_user.id).first_or_create
  expire_fragment('cache_all_groups_fav')
  expire_fragment('cache_all_groups')
  expire_fragment('cached_favgroups')
  expire_fragment('cached_groups')
  expire_fragment('group')
  respond_to do |format|
    format.html { redirect_back }
    format.js { render 'groups/js/unfavorit' }
  end
end
</code>```

Note : To do that, I'm store_cache 'dally' Ruby2.4 (Rails 5.1.4)

Problem :  The expire_fragment method is not working

Do you have any idea of what problem can append here ?

Do you do the same for you cache strategy ?

答:
You should really be doing this caching in the front-end, with russian doll caching.

The cache will expire automatically when any of your group records are updated.

Title: Expire cache fragment not working

Body:
I'm trying to cache a side_bar. Into it, there is two list of groups (1: favorite groups, 2: others_groups)

My caching aproach:

1.caching the two lists of groups into my model User

 def cached_groups
    Rails.cache.fetch([self, "groups"]) {groups.to_a}
  end

  def cached_favgroups
    Rails.cache.fetch([self, "fav_groups"]) {fav_groups.to_a}
  end

2.caching the entire list and below each of the group

  <% cache 'cache_all_groups_fav' do %>
    <% current_user.cached_favgroups.each do |group| %>
      <% cache group do %>
        <%= render 'groups/group', group: group %>
      <% end %>
    <% end %>
  <% end %>

  <% cache 'cache_all_groups' do %>
    <% current_user.cached_groups.each do |group| %>
      <% cache group do %>
        <%= render 'groups/group', group: group %>
      <% end %>
    <% end %>
  <% end %>

3.Expire the cache into my Groups/Controller

def favorit
  FavoritGroup.where(group_id: @group.id).where(user_id: current_user.id).first_or_create
  Group.where(group_id: @group.id).where(user_id: current_user.id).delete_all
  expire_fragment('cache_all_groups_fav')
  expire_fragment('cache_all_groups')
  expire_fragment('cached_favgroups')
  expire_fragment('cached_groups')
  expire_fragment('group')
  respond_to do |format|
    format.html { redirect_back }
    format.js { render 'groups/js/favorit' }
  end
end

def unfavorit
  FavoritGroup.where(group_id: @group.id).where(user_id: current_user.id).delete_all
  Group.where(group_id: @group.id).where(user_id: current_user.id).first_or_create
  expire_fragment('cache_all_groups_fav')
  expire_fragment('cache_all_groups')
  expire_fragment('cached_favgroups')
  expire_fragment('cached_groups')
  expire_fragment('group')
  respond_to do |format|
    format.html { redirect_back }
    format.js { render 'groups/js/unfavorit' }
  end
end

Note : To do that, I'm store_cache 'dally' Ruby2.4 (Rails 5.1.4)

Problem :  The expire_fragment method is not working

Do you have any idea of what problem can append here ?

Do you do the same for you cache strategy ?