问:
SQL - How to make exclude condition
I have the following table. I'm trying to get the rows that met my specific condition.

Table look as follows:

```<code>account|transactiontypecode|
-------|-------------------|
1000058|                  8|
1000067|                  2|
1000067|                  8|
</code>```

The query output would retrieve only the account 1000058, as it applies to the transactiontypecode 8. The other account applies too, but it also has another transactiontypecode that does not applies.

So requirement would be to get the accounts that meet specifics transaction codes, and excludes accounts even though it can also have the code required but has codes unwanted too.

This was my guess over above issue, among others, but I think that other eyes may guide me on a better direction.

```<code>with cte1 as (
select
    gp.account,
    case
        when gp.transactiontypecode in (2,8,17) then TRUE
        else false
    end as txcheck
from
    gp.t2001 gp
group by
    1, 2)

select
    account,
    txcheck
from
    cte1
where
    txcheck is true and txcheck is not false;
</code>```

If anyone can help me achieve above requirement, would be great!

答:
You can use aggregation in a HAVING clause checking the count of codes to be exactly one and the code is 8 -- wrap it in e.g. max(), if there's only one value the maximum is that one value:

```<code>SELECT gp.account
       FROM gp.t2001 gp
       GROUP BY gp.account
       HAVING count(gp.transactiontypecode) = 1
              AND max(gp.transactiontypecode) = 8;
</code>```

Or, if it is allowed that the code of 8 can occur multiple times for an account and you want all of them not having any other code, change it using conditional aggregation to count the codes of 8 and compare it to the overall count of codes. If they match they're all 8:

```<code>       ...
       HAVING count(CASE
                      WHEN gp.transactiontypecode = 8 THEN
                        1
                    END) = count(*);
</code>```

Another option, if the code may occur more than once is to use NOT EXISTS to check for other rows with another code:

```<code>SELECT DISTINCT
       gp1.account
       FROM gp.t2001 gp1
       WHERE gp1.transactiontypecode = 8
             AND NOT EXISTS (SELECT *
                                    FROM gp.t2001 gp2
                                    WHERE gp2.account = gp1.account
                                          AND gp2.transactiontypecode <> 8);
</code>```

Title: SQL - How to make exclude condition

Body:
I have the following table. I'm trying to get the rows that met my specific condition.

Table look as follows:

account|transactiontypecode|
-------|-------------------|
1000058|                  8|
1000067|                  2|
1000067|                  8|

The query output would retrieve only the account 1000058, as it applies to the transactiontypecode 8. The other account applies too, but it also has another transactiontypecode that does not applies.

So requirement would be to get the accounts that meet specifics transaction codes, and excludes accounts even though it can also have the code required but has codes unwanted too.

This was my guess over above issue, among others, but I think that other eyes may guide me on a better direction.

with cte1 as (
select
    gp.account,
    case
        when gp.transactiontypecode in (2,8,17) then TRUE
        else false
    end as txcheck
from
    gp.t2001 gp
group by
    1, 2)

select
    account,
    txcheck
from
    cte1
where
    txcheck is true and txcheck is not false;

If anyone can help me achieve above requirement, would be great!

Body:
You can use aggregation in a HAVING clause checking the count of codes to be exactly one and the code is 8 -- wrap it in e.g. max(), if there's only one value the maximum is that one value:

SELECT gp.account
       FROM gp.t2001 gp
       GROUP BY gp.account
       HAVING count(gp.transactiontypecode) = 1
              AND max(gp.transactiontypecode) = 8;

Or, if it is allowed that the code of 8 can occur multiple times for an account and you want all of them not having any other code, change it using conditional aggregation to count the codes of 8 and compare it to the overall count of codes. If they match they're all 8:

       ...
       HAVING count(CASE
                      WHEN gp.transactiontypecode = 8 THEN
                        1
                    END) = count(*);

Another option, if the code may occur more than once is to use NOT EXISTS to check for other rows with another code:

SELECT DISTINCT
       gp1.account
       FROM gp.t2001 gp1
       WHERE gp1.transactiontypecode = 8
             AND NOT EXISTS (SELECT *
                                    FROM gp.t2001 gp2
                                    WHERE gp2.account = gp1.account
                                          AND gp2.transactiontypecode <> 8);


来源: stackexchange

问:
Convert mysql query to CodeIgniter $query->row
How to convert this query to CodeIgniter?</p>

```<code>$date = '28-05-2019';
$time_start = '10:00';
$time_end = '19:00';

select courtrooms.* from courtrooms
left join reservations
on courtrooms.id = reservations.courtroom_id
and reservations.date = '$date' and reservations.time_start < '$time_start' and reservations.time_end > '$time_end'
where reservations.id is null
</code>```

答:
There are actually several ways to write queries in Codeigniter, the following syntaxis is the most understandable from my point of view if you are just starting to write queries using this framework.

Please see Query Builder Class

```<code>$this->db->select('*');
$this->db->from('courtrooms');
$this->db->join('reservations','courtrooms.id = reservations.courtroom_id','left');
$this->db->where('reservations.id IS NULL', null, false);
$this->db->where('reservations.date', $date);
$this->db->where('reservations.time_start<', $time_start);
$this->db->where('reservations.time_end>', $time_end);
$query = $this->db->get();

$query = $query->result();
</code>```

The above code is the same than this one:

```<code>$query = $this->db->join('reservations','courtrooms.id = reservations.courtroom_id','left')
                  ->where('reservations.id IS NULL', null, false)
                  ->where('reservations.date', $date)
                  ->where('reservations.time_start<', $time_start)
                  ->where('reservations.time_end>', $time_end)
                  ->get('courtrooms');
$query = $query->result();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to convert this query to CodeIgniter?

$date = '28-05-2019';
$time_start = '10:00';
$time_end = '19:00';

select courtrooms.* from courtrooms
left join reservations
on courtrooms.id = reservations.courtroom_id
and reservations.date = '$date' and reservations.time_start < '$time_start' and reservations.time_end > '$time_end'
where reservations.id is null

Body:
There are actually several ways to write queries in Codeigniter, the following syntaxis is the most understandable from my point of view if you are just starting to write queries using this framework.

Please see Query Builder Class

$this->db->select('*');
$this->db->from('courtrooms');
$this->db->join('reservations','courtrooms.id = reservations.courtroom_id','left');
$this->db->where('reservations.id IS NULL', null, false);
$this->db->where('reservations.date', $date);
$this->db->where('reservations.time_start<', $time_start);
$this->db->where('reservations.time_end>', $time_end);
$query = $this->db->get();

$query = $query->result();

The above code is the same than this one:

$query = $this->db->join('reservations','courtrooms.id = reservations.courtroom_id','left')
                  ->where('reservations.id IS NULL', null, false)
                  ->where('reservations.date', $date)
                  ->where('reservations.time_start<', $time_start)
                  ->where('reservations.time_end>', $time_end)
                  ->get('courtrooms');
$query = $query->result();


问:
Besides ? and *, what other wildcards are allowed in conditional formatting?
The google help on conditional formatting of cells in google sheets has a small section on wildcards but only talks about ? and * (and how to escape them).  Are other wildcards allowed?  I have cells that look like:

```<code>some text
1.2.3 more text
4.5.6 even more
another section
7.8.9 stuff
</code>```

I want to have the cells without numbers be bold.  In the conditional formatting, I can choose "text does not contain" and I want to specify "digit" as a wildcard.  Standard regexp doesn't seem to work.  I've tried [0-9], :d, #, \d.

Google help doesn't list anything else so I'm guessing no other wildcards are supported other than ? and *?

答:
you can do it like this too:

```<code>=ARRAYFORMULA(IF(IFERROR(IF(IFERROR(REGEXEXTRACT(A1:A, "\d+")), , "♦"))<>"", 1))
</code>```

Body:
The google help on conditional formatting of cells in google sheets has a small section on wildcards but only talks about ? and * (and how to escape them).  Are other wildcards allowed?  I have cells that look like:

some text
1.2.3 more text
4.5.6 even more
another section
7.8.9 stuff

I want to have the cells without numbers be bold.  In the conditional formatting, I can choose "text does not contain" and I want to specify "digit" as a wildcard.  Standard regexp doesn't seem to work.  I've tried [0-9], :d, #, \d.

Google help doesn't list anything else so I'm guessing no other wildcards are supported other than ? and *?

Body:
you can do it like this too:

=ARRAYFORMULA(IF(IFERROR(IF(IFERROR(REGEXEXTRACT(A1:A, "\d+")), , "♦"))<>"", 1))


问:
Check if a Debian package is installed from Python
Is there an elegant and more Python-like way to check if a package is installed on Debian?

In a bash script, I'd do:

```<code>dpkg -s packagename | grep Status
</code>```

Suggestions to do the same in a Python script?

答:
Inspired by the previous answers, this works nicely for both Python 2 and Python 3 and avoids try/catch for the key error:</p>

```<code>import apt
package = 'foo' # insert your package name here
cache = apt.Cache()
package_installed = False

if package in cache:
    package_installed = cache[package].is_installed
</code>```

Body:
Is there an elegant and more Python-like way to check if a package is installed on Debian?

In a bash script, I'd do:

dpkg -s packagename | grep Status

Suggestions to do the same in a Python script?

Body:
Inspired by the previous answers, this works nicely for both Python 2 and Python 3 and avoids try/catch for the key error:

import apt
package = 'foo' # insert your package name here
cache = apt.Cache()
package_installed = False

if package in cache:
    package_installed = cache[package].is_installed


问:
How to pass variable from controller to javascript?
im working on a laravel project. im trying to do auto-complete search box by retrieving data from the database. not sure how to foreach the collection and get it working in js

```<code>controller

$tag = DB::table('tags')->get(['title']);
</code>```

```<code>view

//get each title for autocomplete
@foreach($tag as $key => $tag)
  <p>{{$tag->title}}</p>
@endforeach

<script>
    //im guessing im passing a tag collection right here??
    //so how do i foreach tag->title variable right here in js to get the title only?
    var tag = {!! json_encode($tag) !!};

    $(function() {

      var content = [
        { title: tag }
        // etc
      ];

      $('.ui.search')
      .search({
        source: content
       });
   });
</script>
</code>```

update:
im using the pluck
update my view

```<code>var tag = {!! json_encode($tag) !!};

    $(function() {

      var content = [
        { title: tag }
        // etc
      ];

      $('.ui.search')
      .search({
        source: content
       });
   });
</code>```

答:
UPDATE FINAL
got it working yay</p>

```<code><script>
        $(document).ready(function(){

            var tag = {!! $tag !!} ;

            console.log(tag); //here I console the tag data, you can use tag data as per your requirement
            var content;
            var final="";

            tag.forEach(function (item, key) {
                //console.log(item);

                var str1= "[";
                var str2= "]";
                var str3= '{ "title": "';
                var str4= '"},';
                var str5= '"}';

                if (key==0) {
                    final = final + str1;
                }

                if (key+1!=tag.length) {
                    final= final+str3+item+str4;
                }
                else{
                    final= final+str3+item+str5+str2;
                }

            });

            var obj = JSON.parse(final);

             console.log(obj);

            $('.ui.search')
            .search({
                source: obj
            })
            ;

        });

    </script>
</code>```

Body:
im working on a laravel project. im trying to do auto-complete search box by retrieving data from the database. not sure how to foreach the collection and get it working in js

controller

$tag = DB::table('tags')->get(['title']);

view

//get each title for autocomplete
@foreach($tag as $key => $tag)

{{$tag->title}}

@endforeach

update:
im using the pluck
update my view

var tag = {!! json_encode($tag) !!};

    $(function() {

      var content = [
        { title: tag }
        // etc
      ];

      $('.ui.search')
      .search({
        source: content
       });
   });

Body:
UPDATE FINAL
got it working yay

<script>
        $(document).ready(function(){

            var tag = {!! $tag !!} ;

            console.log(tag); //here I console the tag data, you can use tag data as per your requirement
            var content;
            var final="";

            tag.forEach(function (item, key) {
                //console.log(item);

                var str1= "[";
                var str2= "]";
                var str3= '{ "title": "';
                var str4= '"},';
                var str5= '"}';

                if (key==0) {
                    final = final + str1;
                }

                if (key+1!=tag.length) {
                    final= final+str3+item+str4;
                }
                else{
                    final= final+str3+item+str5+str2;
                }

            });

            var obj = JSON.parse(final);

             console.log(obj);

            $('.ui.search')
            .search({
                source: obj
            })
            ;

        });

    </script>


问:
PHP Problem with array_count_values
I need to get one time occurence on my array, with my code I get only first result here is my example code:

```<code>$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}
</code>```

Thanks in advance

ciao h

ContentLicense: CC BY-SA 3.0

Title: PHP Problem with array_count_values

Body:
I need to get one time occurence on my array, with my code I get only first result here is my example code:

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}

Thanks in advance

ciao h

Body:
$count = 0;
foreach(array("a","a","b","c","d") as $v){
    if($v == 1){$count++;}
}


问:
Compilation of SCSS file with selector with background-color assigned to result of arithmetic operation on a variable produces an error
In an SCSS file, I've assigned a variable, $bgCol, to a shade of grey and I have six id selectors- each of whose background-color property is assigned to a multiple of the $bgCol. When I compile the SCSS file, I get an error message saying that the arithmetic computation operation (e.g. $bgCol * 1.5) is undefined.

The relevant html is:

```<code><div class="container">
    <div id="d1"></div>
    <div id="d2"></div>
    <div id="d3"></div>
    <div id="d4"></div>
    <div id="d5"></div>
    <div id="d6"></div>
</div>
</code>```

The relevant sass code is (with error-producing line followed by a comment):

```<code>$bgCol: #111;

.container {
    display:flex;
    flex-wrap:wrap;
}

%abox {
    width: 100px;
    height: 100px;
    background-color: $bgCol;
    margin: 20px;
}

#d1 {
    @extend abox;
    background-color: $bgCol * 1.5; //this line produces the error on compilation; i imagine other id selectors with this multiplication computation would produce the same error
}

#d2 {
    @extend abox;
    background-color: $bgCol * 2.5;
}

#d3 {
    @extend abox;
    background-color: $bgCol * 3.5;
}

#d4 {
    @extend abox;
    background-color: $bgCol * 4.5;
}

#d5 {
    @extend abox;
    background-color: $bgCol * 5.5;
}

#d6 {
    @extend abox;
    background-color: $bgCol * 6.5;
}
</code>```

The desired behavior is for each successive inner div to be a lighter shade of grey than the one before (i.e. the div w/ id 'd1' is the darkest, the div w/ id 'd2' is a bit lighter, and the div w/ id 'd6' is the lighest). How can I fix the error I get when compiling the SCSS file and get the desired color scheme?

答:
You cannot simply do arithmetics on colors in SASS.

How about

```<code>@for $i from 1 through 6 {
  #d#{$i} {
    @extend abox;
    background-color: scale-color($bgCol, $lightness: (($i + 0.5) * 10%));
  }
}
</code>```

This will expand into 6 selectors, from #d1 to #d6 each @extending the abox mixin and having a brighter background color as the ID increases.

Please note the differences between lighten and scale-color from the docs.

Body:
In an SCSS file, I've assigned a variable, $bgCol, to a shade of grey and I have six id selectors- each of whose background-color property is assigned to a multiple of the $bgCol. When I compile the SCSS file, I get an error message saying that the arithmetic computation operation (e.g. $bgCol * 1.5) is undefined.

The relevant html is:

The relevant sass code is (with error-producing line followed by a comment):

$bgCol: #111;

.container {
    display:flex;
    flex-wrap:wrap;
}

%abox {
    width: 100px;
    height: 100px;
    background-color: $bgCol;
    margin: 20px;
}

#d1 {
    @extend abox;
    background-color: $bgCol * 1.5; //this line produces the error on compilation; i imagine other id selectors with this multiplication computation would produce the same error
}

#d2 {
    @extend abox;
    background-color: $bgCol * 2.5;
}

#d3 {
    @extend abox;
    background-color: $bgCol * 3.5;
}

#d4 {
    @extend abox;
    background-color: $bgCol * 4.5;
}

#d5 {
    @extend abox;
    background-color: $bgCol * 5.5;
}

#d6 {
    @extend abox;
    background-color: $bgCol * 6.5;
}

The desired behavior is for each successive inner div to be a lighter shade of grey than the one before (i.e. the div w/ id 'd1' is the darkest, the div w/ id 'd2' is a bit lighter, and the div w/ id 'd6' is the lighest). How can I fix the error I get when compiling the SCSS file and get the desired color scheme?

Body:
You cannot simply do arithmetics on colors in SASS.

How about

@for $i from 1 through 6 {
  #d#{$i} {
    @extend abox;
    background-color: scale-color($bgCol, $lightness: (($i + 0.5) * 10%));
  }
}

This will expand into 6 selectors, from #d1 to #d6 each @extending the abox mixin and having a brighter background color as the ID increases.

Please note the differences between lighten and scale-color from the docs.


问:
Understanding the Life cycle of Activity and Service
Suppose I have multiple activities say Screen A(Main Screen) & Screen B.

Screen A opens Screen B and then Screen B starts a service which sends updates to Screen B. Now when the user minimizes the app and the service is running and since Android OS is short of memory then it clears the App.

Now I have two question

1) Does the Android OS clear the memory of the whole app (Screen A & Screen B) or only my Screen B?

2) Will my service also be cleared or will it continue to run? If it is cleared then can a foreground service with a notification help me to overcome this?

Any help would be grateful.

答:
Now when the user minimizes the app and the service is running and since Android OS is short of memory then it clears the App.

When Android is short on memory, it terminates a process.

Does the Android OS clear the memory of the whole app (Screen A & Screen B) or only my Screen B?

By default, your app uses a single process. So, when Android terminates your process, everything of your app goes away.

Will my service also be cleared or will it continue to run?

By default, your app uses a single process. So, when Android terminates your process, your service will also go away. Some developers elect to put their service in a separate process (via the android:process manifest attribute) to help the service stay around longer, but that makes your app a bit more difficult to build.

If it is cleared then can a foreground service with a notification help me to overcome this?

A foreground service makes it far less likely that Android will terminate that service's process to free up system RAM. However, you should only have a service running when it is actively delivering value to the user.


问:
How can I query all products under a category includeing child categories' products using Sequelize
folks. I'm developing e-commerce using nodejs and sequelize. I need some help, my question is:
How can I query all products under a category including child categories' products using sequelize?

I'm using sequelizeV5 and also 'sequelize-hierarchy' npm package

So far I have this:

```<code>async categoryAllProducts(req, res) {
        try {
            let category_id = req.params.id;
            let categories = await models.Category.findAll({
                where: sequelize.literal(`id=${category_id} OR parent_id = ${category_id}`)
            });

            await Promise.all(categories.map(async (category)=> {
                let items = await category.getProducts({
                    offset: req.query.offset || 0,
                    limit: req.query.limit || 10,
                    where: req.query.filter ? sqs.find(req.query.filter) : {},
                    order: req.query.sort ? sqs.sort(req.query.sort) : [['id', 'asc']]
                });
                category.dataValues.products = items;
            }));

            return ReS(res, {data: categories}, 200);
        } catch (error) {
            return ReE(res, error, 400);
        }
    },
</code>```

But on that, I can't use limit and offset as I wanted, and there are duplications of the same products in the different child categories. Also, it is not so efficient. Any recommendations?

答:
I hope I understand your problem. I think you should do it similar to this.</p>

```<code>async categoryAllProducts(req, res) {
    try {
        let category_id = req.params.id;

        const products = await models.Product.findAll({
           include: [{
              model: models.Category,
              // you should use sequelize.Op
              where: sequelize.literal(`id=${category_id} OR parent_id = ${category_id}`)
           }],
           offset: req.query.offset || 0,
           limit: req.query.limit || 10,
           order: req.query.sort ? sqs.sort(req.query.sort) : [['id', 'asc']]
        })

        return ReS(res, {data: products}, 200);
    } catch (error) {
        return ReE(res, error, 400);
    }
},
</code>```

Body:
folks. I'm developing e-commerce using nodejs and sequelize. I need some help, my question is:
How can I query all products under a category including child categories' products using sequelize?

I'm using sequelizeV5 and also 'sequelize-hierarchy' npm package

So far I have this:

async categoryAllProducts(req, res) {
        try {
            let category_id = req.params.id;
            let categories = await models.Category.findAll({
                where: sequelize.literal(`id=${category_id} OR parent_id = ${category_id}`)
            });

            await Promise.all(categories.map(async (category)=> {
                let items = await category.getProducts({
                    offset: req.query.offset || 0,
                    limit: req.query.limit || 10,
                    where: req.query.filter ? sqs.find(req.query.filter) : {},
                    order: req.query.sort ? sqs.sort(req.query.sort) : [['id', 'asc']]
                });
                category.dataValues.products = items;
            }));

            return ReS(res, {data: categories}, 200);
        } catch (error) {
            return ReE(res, error, 400);
        }
    },

But on that, I can't use limit and offset as I wanted, and there are duplications of the same products in the different child categories. Also, it is not so efficient. Any recommendations?

Body:
I hope I understand your problem. I think you should do it similar to this.

async categoryAllProducts(req, res) {
    try {
        let category_id = req.params.id;

        const products = await models.Product.findAll({
           include: [{
              model: models.Category,
              // you should use sequelize.Op
              where: sequelize.literal(`id=${category_id} OR parent_id = ${category_id}`)
           }],
           offset: req.query.offset || 0,
           limit: req.query.limit || 10,
           order: req.query.sort ? sqs.sort(req.query.sort) : [['id', 'asc']]
        })

        return ReS(res, {data: products}, 200);
    } catch (error) {
        return ReE(res, error, 400);
    }
},


问:
Pass object attrbute to spring Mock mvc call
I am using spring rest docs to generate the documentation of an API. My problem is that inside the get I have some objects which are created from other ones, so I need to mock these objects with are the base to create others ones. I'm not pretty sure how can I achieve that. This is what I am doing now:

My Controller looks like this:

```<code>import com.espn.api.platform.model.*
import com.espn.csemobile.espnapp.context.*
import com.espn.csemobile.espnapp.context.common.RequestBasedSWIDContext
import com.espn.csemobile.espnapp.context.common.RequestBasedSeeAllContext
import com.espn.csemobile.espnapp.context.common.RequestBasedUIDContext
import com.espn.csemobile.espnapp.models.browseplayer.BrowsePlayerResponse
import com.espn.csemobile.espnapp.services.browseplayer.BrowsePlayerServiceRepresentable
import com.espn.csemobile.espnapp.services.browseplayer.contexts.RequestBrowsePlayerContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import rx.Single

@Controller
@ProductApi(
        id = "v1_browse_player",
        title = "Browse Player (v1)",
        description = "")
class BrowsePlayerController(private val transaction: Transaction,private val apiRequest: ApiRequest) {

    @Autowired
    lateinit var browsePlayerService: BrowsePlayerServiceRepresentable

    @GetRequest(
            path = "/v1/browse/players",
            timeToLive = 300,
            queries = [
                QueryParameter(name = "swid", required = true),
                QueryParameter(name = "uid"),
                QueryParameter(name = "seeAll", type = java.lang.Boolean::class),
                QueryParameter(name = "lang", required = true),
                QueryParameter(name = "region", required = true),
                QueryParameter(name = "version", required = true, type = Integer::class),
                QueryParameter(name = "appName", required = true),
                QueryParameter(name = "platform", required = true)
            ]
    )
    @GetMapping()
    fun processBrowsePlayerRequest(transaction: Transaction, apiRequest: ApiRequest): Single<BrowsePlayerResponse?> {
        val applicationContext = RequestBasedApplicationContext(apiRequest)
        val standardContext = RequestBasedStandardContext(
                RequestBasedVersionContext(apiRequest),
                applicationContext,
                RequestBasedEditionContext(apiRequest, applicationContext),
                RequestBasedPlatformContext(apiRequest),
                transaction
        )
        val swidContext = RequestBasedSWIDContext(apiRequest)
        val uidContext = if (checkUIDPresent(apiRequest)) RequestBasedUIDContext(apiRequest) else null
        val seeAllContext = RequestBasedSeeAllContext(apiRequest)
        val requestBrowsePlayerContext = RequestBrowsePlayerContext(standardContext, swidContext, uidContext, seeAllContext, apiRequest)
        return browsePlayerService.getEntitiesBrowse(requestBrowsePlayerContext)
    }

    private fun checkUIDPresent(apiRequest: ApiRequest): Boolean =
            apiRequest.parameters["uid"] != null
}
</code>```

The issue is for example when I want to create this object:
val swidContext = RequestBasedSWIDContext(apiRequest) which depends from the apiRequest one.

My test is just like this:

```<code>import com.espn.api.platform.model.ApiRequest
import com.espn.api.platform.model.Transaction
import com.espn.csemobile.espnapp.context.StandardContext
import com.espn.csemobile.espnapp.context.common.SWIDContext
import com.espn.csemobile.espnapp.context.common.SeeAllContext
import com.espn.csemobile.espnapp.context.common.UIDContext
import com.espn.csemobile.espnapp.models.UID
import com.espn.csemobile.espnapp.models.browseplayer.*
import com.espn.csemobile.espnapp.services.browseplayer.BrowsePlayerServiceRepresentable
import com.espn.csemobile.espnapp.services.browseplayer.contexts.RequestBrowsePlayerContext
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.restdocs.JUnitRestDocumentation
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultHandlers.print
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import org.springframework.web.context.WebApplicationContext
import rx.Single

@RunWith(SpringRunner::class)
@WebMvcTest(BrowsePlayerController::class, secure = false)
@AutoConfigureRestDocs(outputDir = "target/snippets")
class BrowsePlayerControllerTest {

    @Autowired
    lateinit var mockMvc: MockMvc
    @MockBean
    private lateinit var browsePlayerServiceRepresentable: BrowsePlayerServiceRepresentable
    @MockBean
    private lateinit var standardContext: StandardContext
    @MockBean
    private lateinit var sWDIContext: SWIDContext
    @MockBean
    private lateinit var uIDContext: UIDContext
    @MockBean
    private lateinit var seeAllContext: SeeAllContext
    @MockBean
    private lateinit var apiRequest: ApiRequest
    @Autowired
    lateinit var context: WebApplicationContext
    @MockBean
    private lateinit var transaction: Transaction
    @get:Rule
    var restDocumentation = JUnitRestDocumentation()

    @Before
    fun init() {
        MockitoAnnotations.initMocks(this)
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply<DefaultMockMvcBuilder>(MockMvcRestDocumentation.documentationConfiguration(this.restDocumentation)
                        .uris()
                        .withScheme("http")
                        .withHost("localhost")
                        .withPort(8080))
                .build()
    }

    @Test
    @Throws(Exception::class)
    fun shouldReturnDefaultMessage() {
        val paramsMock = mapOf("swid" to "asudyasd-asdasd-asdasd")
        `when`(apiRequest.parameters).thenReturn(paramsMock)
        val contextRequest = RequestBrowsePlayerContext(this.standardContext, this.sWDIContext, this.uIDContext, this.seeAllContext, apiRequest)
        //`when`(RequestBrowsePlayerContext.(MockMvc., sWDIContext, uIDContext, seeAllContext, apiRequest)).thenReturn(contextRequest)
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))
        this.mockMvc!!.perform(get("/v1/browse/players/{transaction}{apiRequest}",transaction,apiRequest).param("swid", "asudyasd-asdasd-asdasd")
                .param("uid", "s:20~l:23").param("seeAll", true.toString()).param("lang", "es")
                .param("region", "us").param("version", "23").param("appName", "espn")
                .param("platform", "espn"))
                .andDo(print())
    }

    private fun  presentBrowsePlayers(): BrowsePlayerResponse {
        var sections = arrayListOf<Node>()
        val playersResponse = buildMockSuggestedPlayers()
        val nodePlayers =  Node(null, SectionType.PLAYERS, playersResponse)
        sections.add(nodePlayers)
        val entitiesResponse = buildMockEntitiesBrowse()
        val nodeEntities =  Node(null, SectionType.ENTITIES, entitiesResponse)
        sections.add(nodeEntities)
        return  BrowsePlayerResponse(presentTopHeader(), buildAnalytics(), sections)
    }

    private fun buildMockSuggestedPlayers(): List<SuggestedPlayer> {
        val items = arrayListOf<SuggestedPlayer>()
        items.add(SuggestedPlayer(
                "http://i.espncdn.com/i/players/130x180/45843.jpg",
                "Lionel Messi",
                "SOCCER",
                "dc5f8d51332b0ab2b4b0c97efdc624e0",
                buildAnalyticsPlayer("s:600~t:83", "s:600~l:740", "s:600", SuggestedType.TEAM)
        ))
        items.add(SuggestedPlayer(
                "http://i.espncdn.com/i/players/130x180/22774.jpg",
                "Cristiano Ronaldo",
                "SOCCER",
                "19e162c06bf5d817e9f981bf96001ee2",
                buildAnalyticsPlayer("s:600~t:111", "s:600~l:730", "s:600", SuggestedType.LEAGUE)
        ))
        return items
    }

    private fun  buildAnalyticsPlayer( teamUid:String?,  leagueId :String,  sportUid :String,  suggestedType:SuggestedType):PlayerAnalytics {
        return  PlayerAnalytics(teamUid, leagueId, sportUid, suggestedType)
    }

     private fun presentTopHeader():TopBrowsePlayerHeader {
        val  searchURL = "http://someurl"
        return  TopBrowsePlayerHeader("Player Browse", searchURL)
    }

     private fun buildAnalytics():Analytics {
        return  Analytics(null, null, null, null, null, PageType.ALL_PLAYERS, false)
    }

    private fun buildMockEntitiesBrowse(): List<EntityBrowse> {
        var items = arrayListOf<EntityBrowse>()
        items.add(buildSport("NFL", "s:20~l:28", "http://a.espncdn.com/i/teamlogos/leagues/500/nfl.png"))
        items.add(buildSport("NCAA Football", "s:20~l:23", "http://a.espncdn.com/redesign/assets/img/icons/ESPN-icon-football-college.png"))
        items.add(buildSport("NBA", "s:40~l:46", "http://a.espncdn.com/i/teamlogos/leagues/500/nba.png"))
        items.add(buildSport("NCAA Basketball", "s:40~l:41", "http://a.espncdn.com/redesign/assets/img/icons/ESPN-icon-basketball.png"))
        return items
    }

    private fun buildSport(label: String, uid: String, image: String): EntityBrowse {
        val type = "internalLink"
        val url = "sportscenter://x-callback-url/showPlayerBrowse?uid=$uid"
        val action = BrowsePlayerAction(type, url)
        return  EntityBrowse(label, UID.create(uid), action, image)
    }
</code>```

I'm not really now how can I send the transaction and apiRequest mocked objects to the controller because I am only calling this.mockMvc!!.perform(get("/v1/browse/players/{transaction}{apiRequest}",transaction,apiRequest) without send any param.

Any ideas?

答:
I had used the flash attribute like this:

```<code>@Test
    @Throws(Exception::class)
    fun shouldReturnDefaultMessage() {
        val paramsMock = mapOf("swid" to "asudyasd-asdasd-asdasd","seeAll" to true )
        `when`(apiRequest.parameters).thenReturn(paramsMock)
        val contextRequest = RequestBrowsePlayerContext(this.standardContext, this.sWDIContext, this.uIDContext, this.seeAllContext, apiRequest)
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))
        this.mockMvc!!.perform(get("/v1/browse/players").flashAttr("apiRequest", apiRequest))
                .andDo(print()).andExpect(status().isOk)
    }
</code>```

So I can control what get passes to the model and I can send the mocked apiRequest object.

Body:
I am using spring rest docs to generate the documentation of an API. My problem is that inside the get I have some objects which are created from other ones, so I need to mock these objects with are the base to create others ones. I'm not pretty sure how can I achieve that. This is what I am doing now:

My Controller looks like this:

import com.espn.api.platform.model.*
import com.espn.csemobile.espnapp.context.*
import com.espn.csemobile.espnapp.context.common.RequestBasedSWIDContext
import com.espn.csemobile.espnapp.context.common.RequestBasedSeeAllContext
import com.espn.csemobile.espnapp.context.common.RequestBasedUIDContext
import com.espn.csemobile.espnapp.models.browseplayer.BrowsePlayerResponse
import com.espn.csemobile.espnapp.services.browseplayer.BrowsePlayerServiceRepresentable
import com.espn.csemobile.espnapp.services.browseplayer.contexts.RequestBrowsePlayerContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import rx.Single

@Controller
@ProductApi(
        id = "v1_browse_player",
        title = "Browse Player (v1)",
        description = "")
class BrowsePlayerController(private val transaction: Transaction,private val apiRequest: ApiRequest) {

    @Autowired
    lateinit var browsePlayerService: BrowsePlayerServiceRepresentable

    @GetRequest(
            path = "/v1/browse/players",
            timeToLive = 300,
            queries = [
                QueryParameter(name = "swid", required = true),
                QueryParameter(name = "uid"),
                QueryParameter(name = "seeAll", type = java.lang.Boolean::class),
                QueryParameter(name = "lang", required = true),
                QueryParameter(name = "region", required = true),
                QueryParameter(name = "version", required = true, type = Integer::class),
                QueryParameter(name = "appName", required = true),
                QueryParameter(name = "platform", required = true)
            ]
    )
    @GetMapping()
    fun processBrowsePlayerRequest(transaction: Transaction, apiRequest: ApiRequest): Single<BrowsePlayerResponse?> {
        val applicationContext = RequestBasedApplicationContext(apiRequest)
        val standardContext = RequestBasedStandardContext(
                RequestBasedVersionContext(apiRequest),
                applicationContext,
                RequestBasedEditionContext(apiRequest, applicationContext),
                RequestBasedPlatformContext(apiRequest),
                transaction
        )
        val swidContext = RequestBasedSWIDContext(apiRequest)
        val uidContext = if (checkUIDPresent(apiRequest)) RequestBasedUIDContext(apiRequest) else null
        val seeAllContext = RequestBasedSeeAllContext(apiRequest)
        val requestBrowsePlayerContext = RequestBrowsePlayerContext(standardContext, swidContext, uidContext, seeAllContext, apiRequest)
        return browsePlayerService.getEntitiesBrowse(requestBrowsePlayerContext)
    }

    private fun checkUIDPresent(apiRequest: ApiRequest): Boolean =
            apiRequest.parameters["uid"] != null
}

The issue is for example when I want to create this object:
val swidContext = RequestBasedSWIDContext(apiRequest) which depends from the apiRequest one.

My test is just like this:

import com.espn.api.platform.model.ApiRequest
import com.espn.api.platform.model.Transaction
import com.espn.csemobile.espnapp.context.StandardContext
import com.espn.csemobile.espnapp.context.common.SWIDContext
import com.espn.csemobile.espnapp.context.common.SeeAllContext
import com.espn.csemobile.espnapp.context.common.UIDContext
import com.espn.csemobile.espnapp.models.UID
import com.espn.csemobile.espnapp.models.browseplayer.*
import com.espn.csemobile.espnapp.services.browseplayer.BrowsePlayerServiceRepresentable
import com.espn.csemobile.espnapp.services.browseplayer.contexts.RequestBrowsePlayerContext
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.restdocs.JUnitRestDocumentation
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultHandlers.print
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import org.springframework.web.context.WebApplicationContext
import rx.Single

@RunWith(SpringRunner::class)
@WebMvcTest(BrowsePlayerController::class, secure = false)
@AutoConfigureRestDocs(outputDir = "target/snippets")
class BrowsePlayerControllerTest {

    @Autowired
    lateinit var mockMvc: MockMvc
    @MockBean
    private lateinit var browsePlayerServiceRepresentable: BrowsePlayerServiceRepresentable
    @MockBean
    private lateinit var standardContext: StandardContext
    @MockBean
    private lateinit var sWDIContext: SWIDContext
    @MockBean
    private lateinit var uIDContext: UIDContext
    @MockBean
    private lateinit var seeAllContext: SeeAllContext
    @MockBean
    private lateinit var apiRequest: ApiRequest
    @Autowired
    lateinit var context: WebApplicationContext
    @MockBean
    private lateinit var transaction: Transaction
    @get:Rule
    var restDocumentation = JUnitRestDocumentation()

    @Before
    fun init() {
        MockitoAnnotations.initMocks(this)
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply<DefaultMockMvcBuilder>(MockMvcRestDocumentation.documentationConfiguration(this.restDocumentation)
                        .uris()
                        .withScheme("http")
                        .withHost("localhost")
                        .withPort(8080))
                .build()
    }

    @Test
    @Throws(Exception::class)
    fun shouldReturnDefaultMessage() {
        val paramsMock = mapOf("swid" to "asudyasd-asdasd-asdasd")
        `when`(apiRequest.parameters).thenReturn(paramsMock)
        val contextRequest = RequestBrowsePlayerContext(this.standardContext, this.sWDIContext, this.uIDContext, this.seeAllContext, apiRequest)
        //`when`(RequestBrowsePlayerContext.(MockMvc., sWDIContext, uIDContext, seeAllContext, apiRequest)).thenReturn(contextRequest)
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))
        this.mockMvc!!.perform(get("/v1/browse/players/{transaction}{apiRequest}",transaction,apiRequest).param("swid", "asudyasd-asdasd-asdasd")
                .param("uid", "s:20~l:23").param("seeAll", true.toString()).param("lang", "es")
                .param("region", "us").param("version", "23").param("appName", "espn")
                .param("platform", "espn"))
                .andDo(print())
    }

    private fun  presentBrowsePlayers(): BrowsePlayerResponse {
        var sections = arrayListOf<Node>()
        val playersResponse = buildMockSuggestedPlayers()
        val nodePlayers =  Node(null, SectionType.PLAYERS, playersResponse)
        sections.add(nodePlayers)
        val entitiesResponse = buildMockEntitiesBrowse()
        val nodeEntities =  Node(null, SectionType.ENTITIES, entitiesResponse)
        sections.add(nodeEntities)
        return  BrowsePlayerResponse(presentTopHeader(), buildAnalytics(), sections)
    }

    private fun buildMockSuggestedPlayers(): List<SuggestedPlayer> {
        val items = arrayListOf<SuggestedPlayer>()
        items.add(SuggestedPlayer(
                "http://i.espncdn.com/i/players/130x180/45843.jpg",
                "Lionel Messi",
                "SOCCER",
                "dc5f8d51332b0ab2b4b0c97efdc624e0",
                buildAnalyticsPlayer("s:600~t:83", "s:600~l:740", "s:600", SuggestedType.TEAM)
        ))
        items.add(SuggestedPlayer(
                "http://i.espncdn.com/i/players/130x180/22774.jpg",
                "Cristiano Ronaldo",
                "SOCCER",
                "19e162c06bf5d817e9f981bf96001ee2",
                buildAnalyticsPlayer("s:600~t:111", "s:600~l:730", "s:600", SuggestedType.LEAGUE)
        ))
        return items
    }

    private fun  buildAnalyticsPlayer( teamUid:String?,  leagueId :String,  sportUid :String,  suggestedType:SuggestedType):PlayerAnalytics {
        return  PlayerAnalytics(teamUid, leagueId, sportUid, suggestedType)
    }

     private fun presentTopHeader():TopBrowsePlayerHeader {
        val  searchURL = "http://someurl"
        return  TopBrowsePlayerHeader("Player Browse", searchURL)
    }

     private fun buildAnalytics():Analytics {
        return  Analytics(null, null, null, null, null, PageType.ALL_PLAYERS, false)
    }

    private fun buildMockEntitiesBrowse(): List<EntityBrowse> {
        var items = arrayListOf<EntityBrowse>()
        items.add(buildSport("NFL", "s:20~l:28", "http://a.espncdn.com/i/teamlogos/leagues/500/nfl.png"))
        items.add(buildSport("NCAA Football", "s:20~l:23", "http://a.espncdn.com/redesign/assets/img/icons/ESPN-icon-football-college.png"))
        items.add(buildSport("NBA", "s:40~l:46", "http://a.espncdn.com/i/teamlogos/leagues/500/nba.png"))
        items.add(buildSport("NCAA Basketball", "s:40~l:41", "http://a.espncdn.com/redesign/assets/img/icons/ESPN-icon-basketball.png"))
        return items
    }

    private fun buildSport(label: String, uid: String, image: String): EntityBrowse {
        val type = "internalLink"
        val url = "sportscenter://x-callback-url/showPlayerBrowse?uid=$uid"
        val action = BrowsePlayerAction(type, url)
        return  EntityBrowse(label, UID.create(uid), action, image)
    }

I'm not really now how can I send the transaction and apiRequest mocked objects to the controller because I am only calling this.mockMvc!!.perform(get("/v1/browse/players/{transaction}{apiRequest}",transaction,apiRequest) without send any param.

Any ideas?

Body:
I had used the flash attribute like this:

@Test
    @Throws(Exception::class)
    fun shouldReturnDefaultMessage() {
        val paramsMock = mapOf("swid" to "asudyasd-asdasd-asdasd","seeAll" to true )
        `when`(apiRequest.parameters).thenReturn(paramsMock)
        val contextRequest = RequestBrowsePlayerContext(this.standardContext, this.sWDIContext, this.uIDContext, this.seeAllContext, apiRequest)
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))
        `when`(browsePlayerServiceRepresentable.getEntitiesBrowse(contextRequest)).thenReturn(Single.just(presentBrowsePlayers()))
        this.mockMvc!!.perform(get("/v1/browse/players").flashAttr("apiRequest", apiRequest))
                .andDo(print()).andExpect(status().isOk)
    }

So I can control what get passes to the model and I can send the mocked apiRequest object.


问:
How can I locate a specific value in a collection of objects?
I have a firestore collection which is an object that contains other objects. I want to search this larger object based on an ID. The object looks like this:

```<code>{
  id1: {name: 'a', somethingElse: 'a'},
  id2: {name: 'b', somethingElse: 'b'},
  id3: {name: 'c', somethingElse: 'c'},

}

</code>```

Since it isn't an array, and I am unable to use .find(). How can I search the object using the id, and return the name?

This is what I'm working with so far:

```<code>  function findUser(id, users){
         users.find(function(id{
          return id.name
         })
        }
</code>```

which, of course, doesn't work

答:
You can directly access objects inside another object by id:

```<code>obj[id]
</code>```

let store = {
  id1: {name: 'a', somethingElse: 'a'},
  id2: {name: 'b', somethingElse: 'b'},
  id3: {name: 'c', somethingElse: 'c'},
}

function findUser(id, users){
  return users[id].name;
}

console.log(findUser('id2', store));```

Body:
I have a firestore collection which is an object that contains other objects. I want to search this larger object based on an ID. The object looks like this:

{
  id1: {name: 'a', somethingElse: 'a'},
  id2: {name: 'b', somethingElse: 'b'},
  id3: {name: 'c', somethingElse: 'c'},

}

Since it isn't an array, and I am unable to use .find(). How can I search the object using the id, and return the name?

This is what I'm working with so far:

  function findUser(id, users){
         users.find(function(id{
          return id.name
         })
        }

which, of course, doesn't work

Body:
You can directly access objects inside another object by id:

obj[id]

let store = {
  id1: {name: 'a', somethingElse: 'a'},
  id2: {name: 'b', somethingElse: 'b'},
  id3: {name: 'c', somethingElse: 'c'},
}

function findUser(id, users){
  return users[id].name;
}

console.log(findUser('id2', store));


问:
pgadmin 4, cannot find "edit data"
I read the Q/A "How to insert a row in postgreSQL pgAdmin?" from enter link description here
, but it's for pgAdmin 3.

I just installed postgreSQL 9.6.2 with pgAdmin 4, but could not find the option shown in pgAdmin 3, which you can click to have an excel-like window where you can add and update data in a table without using SQL language (as per @KarelG). Does anyone know whether it stills exist in postgreSQL 9.6.2 with pgAdmin 4? Thanks.

答: I had some trouble finding this too, but found it eventually: Right-click the table, then select "View/Edit Data", and select "Filtered Rows", then enter the condition (format:  field name = ).  Now it will only be showing the row you want to find and edit, and you can double-click the value, change it, then click the save-icon button to save it.</p>

Title: pgadmin 4, cannot find "edit data"


问:
Rails Validation: Limit input to specific values
I'm looking for "the Rails Way" to write a validation that limits acceptable input values to a predetermined list.

In my case, I want to only accept the values "-5", "-2", "+2", "+5", and nil. However, I think this is best as a general question: how do you predefine a list of acceptable entry values in a Rails model?

Thanks!

答:
Rails 3+

The modern way to do this is the following:

```<code>validates :field, inclusion: { in: [ -5, -2, 2, 5 ], allow_blank: true, message: "not an allowable number." }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Rails 3+

The modern way to do this is the following:

validates :field, inclusion: { in: [ -5, -2, 2, 5 ], allow_blank: true, message: "not an allowable number." }


问:
Outsystems - Add another environment
I previously created a personal environment in Outsystems 11, I need to create a new one in Outsytems 10 because it is the version I needed. I searched over the internet and saw how to add another environment in Lifetime cloud but the options in my environment management looks like this only.

How can I add a new environment? Thanks for any help.

答:
In a Personal Environment you can have only one stage/environment. Adding other stages is only available on paid subscriptions.

In any case, it's no longer possible to launch new version 10 infrastructures. Only v11 infras are now available.

Title: Outsystems - Add another environment


问:
How to use external filter with React? (ag-grid)
Ag-grid does not give a react example on how to use external filters with React. I've followed the example anyway and tried to use gridOptions declaratively as I was doing:

```<code><AgGridReact
    rowData={this.state.rowData}
    columnDefs={this.state.columnDefs}
    defaultColDef={this.state.defaultColDef}
    groupDefaultExpanded={this.state.groupDefaultExpanded}
    masterDetail={true}
    detailRowHeight={this.state.detailRowHeight}
    detailCellRendererParams={this.state.detailCellRendererParams}
    onGridReady={this.onGridReady}
    enableRangeSelection={true}
    pagination={true}
    sideBar={this.state.sideBar}
    isExternalFilterPresent={true}
    doesExternalFilterPass={(node) => {
        alert(node);
    }}
/>
</code>```

I trigger the filterChanged manually just like on the example:

```<code><Col xs='3'>
    <Field
        component={renderSelectField}
        name="relatorio-filtro"
        hintText='100'
        variant="outlined"
        selectStyle={relatorioFiltro}
        disable={() => { }}
        onChange={(e) => {
            this.gridApi.onFilterChanged()
        }}
    >
        <div value="15" key="15">{"15"}</div>
        <div value="25" key="25">{"25"}</div>
        <div value="50" key="50">{"50"}</div>
        <div value="100" key="100">{"100"}</div>
        <div value="200" key="200">{"200"}</div>
    </Field>
</Col>
</code>```

But it's no use, that alert never happens. I suspect such feature does not work for React.

答:
from the page you provided:

isExternalFilterPresent is called exactly once every time the grid senses a filter change. It should return true if external filtering is active, otherwise false. If you return true, then doesExternalFilterPass() will be called while filtering, otherwise doesExternalFilterPass() will not be called.

so it seems to me you should try something like this:

```<code>isExternalFilterPresent={()=> {return true;} }
</code>```

Body:
Ag-grid does not give a react example on how to use external filters with React. I've followed the example anyway and tried to use gridOptions declaratively as I was doing:

<AgGridReact
    rowData={this.state.rowData}
    columnDefs={this.state.columnDefs}
    defaultColDef={this.state.defaultColDef}
    groupDefaultExpanded={this.state.groupDefaultExpanded}
    masterDetail={true}
    detailRowHeight={this.state.detailRowHeight}
    detailCellRendererParams={this.state.detailCellRendererParams}
    onGridReady={this.onGridReady}
    enableRangeSelection={true}
    pagination={true}
    sideBar={this.state.sideBar}
    isExternalFilterPresent={true}
    doesExternalFilterPass={(node) => {
        alert(node);
    }}
/>

I trigger the filterChanged manually just like on the example:

<Col xs='3'>
    <Field
        component={renderSelectField}
        name="relatorio-filtro"
        hintText='100'
        variant="outlined"
        selectStyle={relatorioFiltro}
        disable={() => { }}
        onChange={(e) => {
            this.gridApi.onFilterChanged()
        }}
    >

{"15"}

{"25"}

{"50"}

{"100"}

{"200"}

    </Field>
</Col>

But it's no use, that alert never happens. I suspect such feature does not work for React.

Body:
from the page you provided:

isExternalFilterPresent is called exactly once every time the grid senses a filter change. It should return true if external filtering is active, otherwise false. If you return true, then doesExternalFilterPass() will be called while filtering, otherwise doesExternalFilterPass() will not be called.

so it seems to me you should try something like this:

isExternalFilterPresent={()=> {return true;} }


问:
IO redirection with Ruby in GNU/Linux
So, I have written a little application called cowspeak

It does various jobs on a GNU/Linux system. But the problem is while accepting inputs using pipes.

I have already implemented accepting IO redirection with this code:

```<code>#!/usr/bin/ruby -w
require 'timeout'

STDIN.sync = STDOUT.sync = true
pipe = false

begin
    Timeout.timeout(0.000_000_000_001) do pipe = STDIN.gets end
rescue Timeout::Error
end

if pipe
    print pipe
    print pipe while pipe = STDIN.gets
end
</code>```

It's all fine.

So for echo -e "hello\nworld" | ruby cowspeak, I get

```<code>hello
world
</code>```

But the problem is it doesn't work with programs like irb (yes, I don't need to use IRB with this program, but I want to learn how it should work). A working example is the lolcat gem.

So for irb | ruby cowspeak, I get it running forever in the while loop (implemented in loop loop in cowspeak).

Lolcat works fine in that case as well!

Also, apps like cmatrix doesn't work with my program, but they work with lolcat.

Unix programs like cowsay (which is written in Perl) doesn't also work with pipes well - the same behaviour as cowspeak...

Anyways, I see the question is asked before here:
ruby pipes, IO and stderr redirect

But it doesn't answer my question properly.

How can I implement IO redirection with Ruby and overall how the lolcat gem really work with pipes?

答:
To correctly read all data from a pipe, read block by block without timeouts, and to make sure you're able to process any kind of data as it comes in:

```<code>#!/usr/bin/ruby -w

if STDIN.isatty
  STDERR.puts "You are not piping, but I will read from stdin anyways"
  STDERR.puts "because that is the canonical Unix behavior."
end

until STDIN.eof?
  STDOUT.write(STDIN.readpartial(4096))
end
</code>```

This fixes the two issues with your posted code (ignoring all the other programs and combinations you're asking about):

You are using a timeout, so the program fails if input is slow

You are reading line by line, so the program fails if input isn't line based

echo appears to work because this is a shell builtin and is therefore likely to run before ruby finishes loading, but it's still down to chance and scheduling. Here's a race rigged so that echo loses:

```<code>$ ( sleep 1; echo Hello ) | ./yourprogram
./yourprogram:9: warning: constant ::TimeoutError is deprecated
</code>```

You're also waiting for complete lines, but irb only outputs a prompt without linefeeds and cmatrix doesn't output linefeeds at all. This causes a timeout due to the above bug, and would otherwise just read memory until it dies:

```<code>$ while echo -n foo; do true; done | ./yourprogram
./yourprogram:9: warning: constant ::TimeoutError is deprecated
</code>```

The suggestion above has neither of these issues.

Title: IO redirection with Ruby in GNU/Linux

Body:
So, I have written a little application called cowspeak

It does various jobs on a GNU/Linux system. But the problem is while accepting inputs using pipes.

I have already implemented accepting IO redirection with this code:

#!/usr/bin/ruby -w
require 'timeout'

STDIN.sync = STDOUT.sync = true
pipe = false

begin
    Timeout.timeout(0.000_000_000_001) do pipe = STDIN.gets end
rescue Timeout::Error
end

if pipe
    print pipe
    print pipe while pipe = STDIN.gets
end

It's all fine.

So for echo -e "hello\nworld" | ruby cowspeak, I get

hello
world

But the problem is it doesn't work with programs like irb (yes, I don't need to use IRB with this program, but I want to learn how it should work). A working example is the lolcat gem.

So for irb | ruby cowspeak, I get it running forever in the while loop (implemented in loop loop in cowspeak).

Lolcat works fine in that case as well!

Also, apps like cmatrix doesn't work with my program, but they work with lolcat.

Unix programs like cowsay (which is written in Perl) doesn't also work with pipes well - the same behaviour as cowspeak...

Anyways, I see the question is asked before here:
ruby pipes, IO and stderr redirect

But it doesn't answer my question properly.

How can I implement IO redirection with Ruby and overall how the lolcat gem really work with pipes?

Body:
To correctly read all data from a pipe, read block by block without timeouts, and to make sure you're able to process any kind of data as it comes in:

#!/usr/bin/ruby -w

if STDIN.isatty
  STDERR.puts "You are not piping, but I will read from stdin anyways"
  STDERR.puts "because that is the canonical Unix behavior."
end

until STDIN.eof?
  STDOUT.write(STDIN.readpartial(4096))
end

This fixes the two issues with your posted code (ignoring all the other programs and combinations you're asking about):

You are using a timeout, so the program fails if input is slow

You are reading line by line, so the program fails if input isn't line based

echo appears to work because this is a shell builtin and is therefore likely to run before ruby finishes loading, but it's still down to chance and scheduling. Here's a race rigged so that echo loses:

$ ( sleep 1; echo Hello ) | ./yourprogram
./yourprogram:9: warning: constant ::TimeoutError is deprecated

You're also waiting for complete lines, but irb only outputs a prompt without linefeeds and cmatrix doesn't output linefeeds at all. This causes a timeout due to the above bug, and would otherwise just read memory until it dies:

$ while echo -n foo; do true; done | ./yourprogram
./yourprogram:9: warning: constant ::TimeoutError is deprecated

The suggestion above has neither of these issues.


问:
Fatal error: Array index out of range when appending array
I currently have an array which I am appending options to. They are they displayed in a table with 3 sections. The first 2 sections have 1 row each, but the third section has a variable number of rows depending on what is appended to the array. I essentially take the third component of my initial array (allAlbums[0].markscheme) and break it down to create multiple new items in the array.

However, when I am trying to simulate this, I get a fatal array on 'cell.textData?.text = section[indexPath.row] as! String' and I'm not sure why?

```<code>final class CaseViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var titleText: UILabel!
@IBOutlet var tableView: UITableView!

private var allAlbums = [Case]()

let kHeaderSectionTag: Int = 6900;

var expandedSectionHeaderNumber: Int = -1
var expandedSectionHeader: UITableViewHeaderFooterView!
var sectionItems: Array<Any> = []
var sectionNames: Array<Any> = []
var markschemeRows: Array<Any> = []

override func viewDidLoad() {
    super.viewDidLoad()

    allAlbums = LibraryAPI.shared.getCases()

    // Filter the main array to match a single case
    allAlbums = allAlbums.filter { $0.title == title}

    // Get data to fill in to table
    sectionNames = [ "Trainee Information", "Patient Information", "Examiner Information" ];
    sectionItems = [ [allAlbums[0].doctor], [allAlbums[0].patient], [allAlbums[0].markscheme]]

    let text = allAlbums[0].markscheme
    markschemeRows = text.components(separatedBy: " ")

    sectionItems.append(contentsOf: markschemeRows)

    // Autoresize rows
    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 500

    // Remove excess row seperators
    tableView.tableFooterView = UIView()
    tableView.separatorColor = UIColor.clear

    titleText.text = title

}

func numberOfSections(in tableView: UITableView) -> Int {
    return 3
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if (self.expandedSectionHeaderNumber == section) {

        // Header section
        let header = self.sectionNames[section] as! String

        // If markscheme, create the markscheme format
        if (header == "Examiner Information")
        {
            print(self.markschemeRows.count)
            return self.markschemeRows.count
        }
        else
        {
            let arrayOfItems = self.sectionItems[section] as! NSArray
            print(arrayOfItems.count)
            return arrayOfItems.count
        }

    } else {
        return 0;
    }
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if (self.sectionNames.count != 0) {
        return self.sectionNames[section] as? String
    }
    return ""
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44.0;
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
    return 0;
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    //recast your view as a UITableViewHeaderFooterView
    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    header.contentView.backgroundColor = UIColor.darkGray
    header.textLabel?.textColor = UIColor.white

    if let viewWithTag = self.view.viewWithTag(kHeaderSectionTag + section) {
        viewWithTag.removeFromSuperview()
    }
    let headerFrame = self.view.frame.size
    let theImageView = UIImageView(frame: CGRect(x: headerFrame.width - 32, y: 13, width: 18, height: 18));
    theImageView.image = UIImage(named: "Chevron-Dn-Wht")
    theImageView.tag = kHeaderSectionTag + section
    header.addSubview(theImageView)

    // make headers touchable
    header.tag = section
    let headerTapGesture = UITapGestureRecognizer()
    headerTapGesture.addTarget(self, action: #selector(CaseViewController.sectionHeaderWasTouched(_:)))
    header.addGestureRecognizer(headerTapGesture)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
    let section = self.sectionItems[indexPath.section] as! NSArray

    cell.textLabel?.textColor = UIColor.black

    cell.textData?.text = section[indexPath.row] as! String

    return cell
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
}

// MARK: - Expand / Collapse Methods

@objc func sectionHeaderWasTouched(_ sender: UITapGestureRecognizer) {
    let headerView = sender.view as! UITableViewHeaderFooterView
    let section    = headerView.tag
    let eImageView = headerView.viewWithTag(kHeaderSectionTag + section) as? UIImageView

    if (self.expandedSectionHeaderNumber == -1) {
        self.expandedSectionHeaderNumber = section
        tableViewExpandSection(section, imageView: eImageView!)
    } else {
        if (self.expandedSectionHeaderNumber == section) {
            tableViewCollapeSection(section, imageView: eImageView!)
        } else {
            let cImageView = self.view.viewWithTag(kHeaderSectionTag + self.expandedSectionHeaderNumber) as? UIImageView
            tableViewCollapeSection(self.expandedSectionHeaderNumber, imageView: cImageView!)
            tableViewExpandSection(section, imageView: eImageView!)
        }
    }
}

func tableViewCollapeSection(_ section: Int, imageView: UIImageView) {
    let sectionData = self.sectionItems[section] as! NSArray

    self.expandedSectionHeaderNumber = -1;
    if (sectionData.count == 0) {
        return;
    } else {
        UIView.animate(withDuration: 0.4, animations: {
            imageView.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(Double.pi)) / 180.0)
        })
        var indexesPath = [IndexPath]()
        for i in 0 ..< sectionData.count {
            let index = IndexPath(row: i, section: section)
            indexesPath.append(index)
        }
        self.tableView!.beginUpdates()
        self.tableView!.deleteRows(at: indexesPath, with: UITableView.RowAnimation.fade)
        self.tableView!.endUpdates()
    }
}

func tableViewExpandSection(_ section: Int, imageView: UIImageView) {
    let sectionData = self.sectionItems[section] as! NSArray

    if (sectionData.count == 0) {
        self.expandedSectionHeaderNumber = -1;
        return;
    } else {
        UIView.animate(withDuration: 0.4, animations: {
            imageView.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(Double.pi)) / 180.0)
        })
        var indexesPath = [IndexPath]()

        // Header section
        let header = self.sectionNames[section] as! String

        // If markscheme, create the markscheme format
        if (header == "Examiner Information")
        {
            for i in 0 ..< markschemeRows.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }
        else
        {
            for i in 0 ..< sectionData.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }
        self.expandedSectionHeaderNumber = section
        self.tableView!.beginUpdates()
        self.tableView!.insertRows(at: indexesPath, with: UITableView.RowAnimation.fade)
        self.tableView!.endUpdates()
    }
}
</code>```

}

答:
The error is pretty clear.

In numberOfRows you return markschemeRows.count for section 2 which is the number of separated items in this line

```<code>markschemeRows = text.components(separatedBy: " ")
</code>```

Then you must also get the item from markschemeRows rather than from section[indexPath.row] in cellForRow

```<code>var markschemeRows = [String]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
    let section = self.sectionItems[indexPath.section] as! NSArray

    cell.textLabel?.textColor = UIColor.black
    if indexPath.section == 2 {
        cell.textData?.text = markschemeRows[indexPath.row]
    } else {
        cell.textData?.text = section[indexPath.row] as! String
    }

    return cell
}
</code>```

Your code is quite cumbersome. For example sectionNames and markschemeRows are clearly [String].Why do you declare the arrays as [Any]? This is Swift. Take care of the types. And don't use Foundation collection types like NSArray in Swift at all. Again take care of the types.

Body:
I currently have an array which I am appending options to. They are they displayed in a table with 3 sections. The first 2 sections have 1 row each, but the third section has a variable number of rows depending on what is appended to the array. I essentially take the third component of my initial array (allAlbums[0].markscheme) and break it down to create multiple new items in the array.

However, when I am trying to simulate this, I get a fatal array on 'cell.textData?.text = section[indexPath.row] as! String' and I'm not sure why?

final class CaseViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var titleText: UILabel!
@IBOutlet var tableView: UITableView!

private var allAlbums = [Case]()

let kHeaderSectionTag: Int = 6900;

var expandedSectionHeaderNumber: Int = -1
var expandedSectionHeader: UITableViewHeaderFooterView!
var sectionItems: Array<Any> = []
var sectionNames: Array<Any> = []
var markschemeRows: Array<Any> = []

override func viewDidLoad() {
    super.viewDidLoad()

    allAlbums = LibraryAPI.shared.getCases()

    // Filter the main array to match a single case
    allAlbums = allAlbums.filter { $0.title == title}

    // Get data to fill in to table
    sectionNames = [ "Trainee Information", "Patient Information", "Examiner Information" ];
    sectionItems = [ [allAlbums[0].doctor], [allAlbums[0].patient], [allAlbums[0].markscheme]]

    let text = allAlbums[0].markscheme
    markschemeRows = text.components(separatedBy: " ")

    sectionItems.append(contentsOf: markschemeRows)

    // Autoresize rows
    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 500

    // Remove excess row seperators
    tableView.tableFooterView = UIView()
    tableView.separatorColor = UIColor.clear

    titleText.text = title

}

func numberOfSections(in tableView: UITableView) -> Int {
    return 3
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if (self.expandedSectionHeaderNumber == section) {

        // Header section
        let header = self.sectionNames[section] as! String

        // If markscheme, create the markscheme format
        if (header == "Examiner Information")
        {
            print(self.markschemeRows.count)
            return self.markschemeRows.count
        }
        else
        {
            let arrayOfItems = self.sectionItems[section] as! NSArray
            print(arrayOfItems.count)
            return arrayOfItems.count
        }

    } else {
        return 0;
    }
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if (self.sectionNames.count != 0) {
        return self.sectionNames[section] as? String
    }
    return ""
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44.0;
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
    return 0;
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    //recast your view as a UITableViewHeaderFooterView
    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    header.contentView.backgroundColor = UIColor.darkGray
    header.textLabel?.textColor = UIColor.white

    if let viewWithTag = self.view.viewWithTag(kHeaderSectionTag + section) {
        viewWithTag.removeFromSuperview()
    }
    let headerFrame = self.view.frame.size
    let theImageView = UIImageView(frame: CGRect(x: headerFrame.width - 32, y: 13, width: 18, height: 18));
    theImageView.image = UIImage(named: "Chevron-Dn-Wht")
    theImageView.tag = kHeaderSectionTag + section
    header.addSubview(theImageView)

    // make headers touchable
    header.tag = section
    let headerTapGesture = UITapGestureRecognizer()
    headerTapGesture.addTarget(self, action: #selector(CaseViewController.sectionHeaderWasTouched(_:)))
    header.addGestureRecognizer(headerTapGesture)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
    let section = self.sectionItems[indexPath.section] as! NSArray

    cell.textLabel?.textColor = UIColor.black

    cell.textData?.text = section[indexPath.row] as! String

    return cell
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
}

// MARK: - Expand / Collapse Methods

@objc func sectionHeaderWasTouched(_ sender: UITapGestureRecognizer) {
    let headerView = sender.view as! UITableViewHeaderFooterView
    let section    = headerView.tag
    let eImageView = headerView.viewWithTag(kHeaderSectionTag + section) as? UIImageView

    if (self.expandedSectionHeaderNumber == -1) {
        self.expandedSectionHeaderNumber = section
        tableViewExpandSection(section, imageView: eImageView!)
    } else {
        if (self.expandedSectionHeaderNumber == section) {
            tableViewCollapeSection(section, imageView: eImageView!)
        } else {
            let cImageView = self.view.viewWithTag(kHeaderSectionTag + self.expandedSectionHeaderNumber) as? UIImageView
            tableViewCollapeSection(self.expandedSectionHeaderNumber, imageView: cImageView!)
            tableViewExpandSection(section, imageView: eImageView!)
        }
    }
}

func tableViewCollapeSection(_ section: Int, imageView: UIImageView) {
    let sectionData = self.sectionItems[section] as! NSArray

    self.expandedSectionHeaderNumber = -1;
    if (sectionData.count == 0) {
        return;
    } else {
        UIView.animate(withDuration: 0.4, animations: {
            imageView.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(Double.pi)) / 180.0)
        })
        var indexesPath = [IndexPath]()
        for i in 0 ..< sectionData.count {
            let index = IndexPath(row: i, section: section)
            indexesPath.append(index)
        }
        self.tableView!.beginUpdates()
        self.tableView!.deleteRows(at: indexesPath, with: UITableView.RowAnimation.fade)
        self.tableView!.endUpdates()
    }
}

func tableViewExpandSection(_ section: Int, imageView: UIImageView) {
    let sectionData = self.sectionItems[section] as! NSArray

    if (sectionData.count == 0) {
        self.expandedSectionHeaderNumber = -1;
        return;
    } else {
        UIView.animate(withDuration: 0.4, animations: {
            imageView.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(Double.pi)) / 180.0)
        })
        var indexesPath = [IndexPath]()

        // Header section
        let header = self.sectionNames[section] as! String

        // If markscheme, create the markscheme format
        if (header == "Examiner Information")
        {
            for i in 0 ..< markschemeRows.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }
        else
        {
            for i in 0 ..< sectionData.count {
                let index = IndexPath(row: i, section: section)
                indexesPath.append(index)
            }
        }
        self.expandedSectionHeaderNumber = section
        self.tableView!.beginUpdates()
        self.tableView!.insertRows(at: indexesPath, with: UITableView.RowAnimation.fade)
        self.tableView!.endUpdates()
    }
}

}

Body:
The error is pretty clear.

In numberOfRows you return markschemeRows.count for section 2 which is the number of separated items in this line

markschemeRows = text.components(separatedBy: " ")

Then you must also get the item from markschemeRows rather than from section[indexPath.row] in cellForRow

var markschemeRows = [String]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomTableCell
    let section = self.sectionItems[indexPath.section] as! NSArray

    cell.textLabel?.textColor = UIColor.black
    if indexPath.section == 2 {
        cell.textData?.text = markschemeRows[indexPath.row]
    } else {
        cell.textData?.text = section[indexPath.row] as! String
    }

    return cell
}

Your code is quite cumbersome. For example sectionNames and markschemeRows are clearly [String].Why do you declare the arrays as [Any]? This is Swift. Take care of the types. And don't use Foundation collection types like NSArray in Swift at all. Again take care of the types.


问:
Is there a possibility to somehow overcome limitations of using generics in interface? (without boxing/unboxing)
I'm trying to create set of interfaces that will be used in several classes. But I have troubles with setting them properly. I want to keep them generic.

I tried to get around this using dynamic type and object type without success. Maybe this will be clear with attached those interfaces below:

In code below type T is unknown. I cannot specify it because each IDeviceParameter will be different type. And number of parameters is not fixed, so I want to simply add all available IParameters to list. Only solution that came into my mind is to use some sort of boxing/unboxing (for example cast int to object and vice versa) or use dynamic. Or to totally change those interfaces. Thanks you in advance for any advises.

```<code>public interface IDevice : IDisposable
{
    string Name { get; }
    bool Close();
    Guid DeviceGuid { get; }
    IList<IDeviceParameter<T>>AvailableParameters { get; }
    IList<IDeviceCommand> AvailableCommands { get; }
}

public interface IDeviceParameter<T>
{
    event EventHandler<IDeviceParameter<T>> ParameterValueChanged;
    event EventHandler<Exception> ParameterNotSet;
    string ParameterName { get; }
    string ParameterValue { get; }
    string ParameterUnit { get; }
    bool IsReadOnly { get; }
    T Parameter { get; }
    void SetParameter(T value);
}
</code>```

Below is some concrete implementation (not working because of error like "Cannot convert from type Object to type int") :

```<code>public class Device : IDevice
{
    public int _setableParameter1 = 1;
    public string _setableParameter2 = "2";
    private Guid _guid;
    private string _name;
    private List<IDeviceCommand> _cmdList = new List<IDeviceCommand>();
    private List<IDeviceParameter<object>> _paramList = new List<IDeviceParameter<object>>();

   public Device()
   {
        IDeviceParameter<int> setableParameter1 = DeviceParameterFactory.Factory<int>.CreateParameter("SomeParameter1", "V", delegate { throw new DeviceParameterFactory.ParametersNotSetException("SomeParameter1"); },  ref _setableParameter1);
         IDeviceParameter<string> setableParameter2 = DeviceParameterFactory.Factory<string>.CreateParameter("SomeParameter2", "V", delegate { throw new DeviceParameterFactory.ParametersNotSetException("SomeParameter2"); },  ref _setableParameter2);
        _cmdList.Add(setableParameter1);
        _cmdList.Add(setableParameter2);
        _guid = Guid.NewGuid();
        _name = "Device" + DateTime.Now.Millisecond;
    }
</code>```

Some explanation: factory class returns IDeviceParameter, and those types for sure are known at compilation time because they are explictly set.

答:
If you have something of type IDeviceParameter<string> and something of IDeviceParameter<int> then there is no way to make that into an IDeviceParameter<object> without doing new IDeviceParameter<object>() somewhere. This is because they are just entirely different interfaces to the program. For the compiler you might as well have created classes named IIntDeviceParameter and IStringDeviceParameter.

If these classes share a similar interface, then you will need to explicitly state this, i.e. you would need to make an interface IUnknownTypeDeviceParameter, but you cannot put the fields or methods that use T in their type definition in there. So you could do this:

public interface IUnknownTypeDeviceParameter
{
    event EventHandler<Exception> ParameterNotSet;
    string ParameterName { get; }
    string ParameterValue { get; }
    string ParameterUnit { get; }
    bool IsReadOnly { get; }
}

public interface IDeviceParameter<T> : IUnknownTypeDeviceParameter
{
    event EventHandler<IDeviceParameter<T>> ParameterValueChanged;
    event EventHandler<Exception> ParameterNotSet;
    string ParameterName { get; }
    string ParameterValue { get; }
    string ParameterUnit { get; }
    bool IsReadOnly { get; }
    T Parameter { get; }
    void SetParameter(T value);
}
```

If you would like to use one of the functions in IDeviceParameter<T> on an IUnknownTypeDeviceParameter you would need to cast it back to an IDeviceParameter<T>.

Body:
I'm trying to create set of interfaces that will be used in several classes. But I have troubles with setting them properly. I want to keep them generic.

I tried to get around this using dynamic type and object type without success. Maybe this will be clear with attached those interfaces below:

In code below type T is unknown. I cannot specify it because each IDeviceParameter will be different type. And number of parameters is not fixed, so I want to simply add all available IParameters to list. Only solution that came into my mind is to use some sort of boxing/unboxing (for example cast int to object and vice versa) or use dynamic. Or to totally change those interfaces. Thanks you in advance for any advises.

public interface IDevice : IDisposable
{
    string Name { get; }
    bool Close();
    Guid DeviceGuid { get; }
    IList<IDeviceParameter<T>>AvailableParameters { get; }
    IList<IDeviceCommand> AvailableCommands { get; }
}

public interface IDeviceParameter<T>
{
    event EventHandler<IDeviceParameter<T>> ParameterValueChanged;
    event EventHandler<Exception> ParameterNotSet;
    string ParameterName { get; }
    string ParameterValue { get; }
    string ParameterUnit { get; }
    bool IsReadOnly { get; }
    T Parameter { get; }
    void SetParameter(T value);
}

Below is some concrete implementation (not working because of error like "Cannot convert from type Object to type int") :

public class Device : IDevice
{
    public int _setableParameter1 = 1;
    public string _setableParameter2 = "2";
    private Guid _guid;
    private string _name;
    private List<IDeviceCommand> _cmdList = new List<IDeviceCommand>();
    private List<IDeviceParameter<object>> _paramList = new List<IDeviceParameter<object>>();

   public Device()
   {
        IDeviceParameter<int> setableParameter1 = DeviceParameterFactory.Factory<int>.CreateParameter("SomeParameter1", "V", delegate { throw new DeviceParameterFactory.ParametersNotSetException("SomeParameter1"); },  ref _setableParameter1);
         IDeviceParameter<string> setableParameter2 = DeviceParameterFactory.Factory<string>.CreateParameter("SomeParameter2", "V", delegate { throw new DeviceParameterFactory.ParametersNotSetException("SomeParameter2"); },  ref _setableParameter2);
        _cmdList.Add(setableParameter1);
        _cmdList.Add(setableParameter2);
        _guid = Guid.NewGuid();
        _name = "Device" + DateTime.Now.Millisecond;
    }

Some explanation: factory class returns IDeviceParameter, and those types for sure are known at compilation time because they are explictly set.

Body:
If you have something of type IDeviceParameter<string> and something of IDeviceParameter<int> then there is no way to make that into an IDeviceParameter<object> without doing new IDeviceParameter<object>() somewhere. This is because they are just entirely different interfaces to the program. For the compiler you might as well have created classes named IIntDeviceParameter and IStringDeviceParameter.

If these classes share a similar interface, then you will need to explicitly state this, i.e. you would need to make an interface IUnknownTypeDeviceParameter, but you cannot put the fields or methods that use T in their type definition in there. So you could do this:

public interface IUnknownTypeDeviceParameter
{
    event EventHandler<Exception> ParameterNotSet;
    string ParameterName { get; }
    string ParameterValue { get; }
    string ParameterUnit { get; }
    bool IsReadOnly { get; }
}

public interface IDeviceParameter<T> : IUnknownTypeDeviceParameter
{
    event EventHandler<IDeviceParameter<T>> ParameterValueChanged;
    event EventHandler<Exception> ParameterNotSet;
    string ParameterName { get; }
    string ParameterValue { get; }
    string ParameterUnit { get; }
    bool IsReadOnly { get; }
    T Parameter { get; }
    void SetParameter(T value);
}

If you would like to use one of the functions in IDeviceParameter<T> on an IUnknownTypeDeviceParameter you would need to cast it back to an IDeviceParameter<T>.


问:
SQL - How to make exclude condition
I have the following table. I'm trying to get the rows that met my specific condition.

Table look as follows:

```<code>account|transactiontypecode|
-------|-------------------|
1000058|                  8|
1000067|                  2|
1000067|                  8|
</code>```

The query output would retrieve only the account 1000058, as it applies to the transactiontypecode 8. The other account applies too, but it also has another transactiontypecode that does not applies.

So requirement would be to get the accounts that meet specifics transaction codes, and excludes accounts even though it can also have the code required but has codes unwanted too.

This was my guess over above issue, among others, but I think that other eyes may guide me on a better direction.

```<code>with cte1 as (
select
    gp.account,
    case
        when gp.transactiontypecode in (2,8,17) then TRUE
        else false
    end as txcheck
from
    gp.t2001 gp
group by
    1, 2)

select
    account,
    txcheck
from
    cte1
where
    txcheck is true and txcheck is not false;
</code>```

If anyone can help me achieve above requirement, would be great!

答:
Try something like this:

```<code>SELECT account
FROM [Table]
GROUP BY account
HAVING
   COUNT(transactiontypecode) = 1 AND
   transactiontypecode = 8
</code>```

The COUNT inside having clause should give you the accounts with only 1 transaction type code. Then, you can apply any other condition.

Title: SQL - How to make exclude condition

Body:
I have the following table. I'm trying to get the rows that met my specific condition.

Table look as follows:

account|transactiontypecode|
-------|-------------------|
1000058|                  8|
1000067|                  2|
1000067|                  8|

The query output would retrieve only the account 1000058, as it applies to the transactiontypecode 8. The other account applies too, but it also has another transactiontypecode that does not applies.

So requirement would be to get the accounts that meet specifics transaction codes, and excludes accounts even though it can also have the code required but has codes unwanted too.

This was my guess over above issue, among others, but I think that other eyes may guide me on a better direction.

with cte1 as (
select
    gp.account,
    case
        when gp.transactiontypecode in (2,8,17) then TRUE
        else false
    end as txcheck
from
    gp.t2001 gp
group by
    1, 2)

select
    account,
    txcheck
from
    cte1
where
    txcheck is true and txcheck is not false;

If anyone can help me achieve above requirement, would be great!

Body:
Try something like this:

SELECT account
FROM [Table]
GROUP BY account
HAVING
   COUNT(transactiontypecode) = 1 AND
   transactiontypecode = 8

The COUNT inside having clause should give you the accounts with only 1 transaction type code. Then, you can apply any other condition.


问:
NSURLConnection threading problem
i have a big problem and i need your help. Here's what i need to accomplish:

The user select a row from a
TableView

A new view controller is pushed in
the NavigationController, and
displays only a "Loading" message

Meanwhile some data is read from an
XML file (via http)

When the data has been read, an
NSUConnection is used to load an
image from an URL (this URL is part
of the data)

While the image is still loading,
the other data is displayed on the
screen

The image has been downloaded and is
shown, completing the appearance of
the view

The big problem is that i can't use detachNewThreadSelector and NSURLConnection together!

So how can i make a workaround for this? How would you do this?

Thank you VERY much!

答:
I would use a NSTimer to solve the problem using detachNewThreadSelector and NSURLConnection together.

I have similar scenario where there is a downloading Progress UIViewController showing till the file getting complete, here is what i do:

I Draw a loading View contains a Activity Indicator for example.

I initialize a NSTimer to keep checking if the file is complete.

 I call the method that contains the Download Logic.

[1]

```<code> -(void) vManageFileRequest
{
  [self.oFilesManager vGetSingleFileRequest];

   NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self   selector:@selector(vValidateFileRequest) userInfo:nil repeats:NO]];
}
</code>```

[2]

```<code>   [self performSelectorOnMainThread:@selector(vManageFileRequest) withObject:nil waitUntilDone:NO];
</code>```

Title: NSURLConnection threading problem

Body:
I would use a NSTimer to solve the problem using detachNewThreadSelector and NSURLConnection together.

I have similar scenario where there is a downloading Progress UIViewController showing till the file getting complete, here is what i do:

I Draw a loading View contains a Activity Indicator for example.

I initialize a NSTimer to keep checking if the file is complete.

 I call the method that contains the Download Logic.

[1]

 -(void) vManageFileRequest
{
  [self.oFilesManager vGetSingleFileRequest];

   NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self   selector:@selector(vValidateFileRequest) userInfo:nil repeats:NO]];
}

[2]

   [self performSelectorOnMainThread:@selector(vManageFileRequest) withObject:nil waitUntilDone:NO];


问:
BigQuery (BQ) - Drop Partition
I'm using the BQ CLI (https://cloud.google.com/bigquery/bq-command-line-tool).

I didn't find how to Delete DAY Partition data.

For example, i have a DAY PARTITIONED table that holds data for dates 2016-09-01 and until 2016-09-30.

I need to delete the "2016-09-15" partition completely.

Is this possible through CLI command ?

答:
If you do want to delete a partition you can use the bq rm command while specifying a $YYYYMMDD table decorator. For your case the command would look like:

```<code>bq rm -t 'dataset.table$20160915'
</code>```

Be careful to include the single quotes, otherwise the decorator may get expanded to an empty variable and you'll delete the full table.

Title: BigQuery (BQ) - Drop Partition

Body:
If you do want to delete a partition you can use the bq rm command while specifying a $YYYYMMDD table decorator. For your case the command would look like:

bq rm -t 'dataset.table$20160915'

Be careful to include the single quotes, otherwise the decorator may get expanded to an empty variable and you'll delete the full table.


问:
How to get MAC address of a client device in Xamarin.Forms?
In my client-server-solution I need the MAC addresses of frontend devices, running my Xamarin.Forms app. Currently I just have an Entry where a user should type in the mac address of the device where the app is running (main interface).

I already searched for the topic and found that iOS and Android are restrictive on returning the MAC. I also know about the Device plugin from James Montemagno and it's not delivering what I need. Is there still a possibility to get it? Could I atleast make a shortcut to the exact settings page where a user can manually copy the MAC?

Some may wonder: Why do I need the mac address?

My solution is a platform for employees to share their availability and location. Employees can enter device info, so that the backend can find their devices. Then the backend can give you information like: John Doe is currently in the office (because his devices are found in the network) and is on the second floor on the river side (because his devices are connected with the wifi controller on that exact location). Other employees that want to talk to John then know for certain that they can just go to John instead of writing mail or calling him. The solution promotes direct communication and work-life balance with accurate data that can be pulled automatically but is still privacy conform, because employees have to actively share their information to get the automated status. On top the data collected is the same that you get by asking or walking around in the office.

答:
As far as I know, getting Mac address on IOS is not possible but on Android and UWP it is.  Here is what I do

```<code>var ni = NetworkInterface.GetAllNetworkInterfaces()
   .OrderBy(intf => intf.NetworkInterfaceType)
   .FirstOrDefault(intf => intf.OperationalStatus == OperationalStatus.Up
         && (intf.NetworkInterfaceType == NetworkInterfaceType.Wireless80211
             || intf.NetworkInterfaceType == NetworkInterfaceType.Ethernet));
</code>```

then:

```<code>var hw = ni.GetPhysicalAddress();
return string.Join(":", (from ma in hw.GetAddressBytes() select ma.ToString("X2")).ToArray());
</code>```

This will return MAC address like: 63:D5:16:27:DE:95

Body:
As far as I know, getting Mac address on IOS is not possible but on Android and UWP it is.  Here is what I do

var ni = NetworkInterface.GetAllNetworkInterfaces()
   .OrderBy(intf => intf.NetworkInterfaceType)
   .FirstOrDefault(intf => intf.OperationalStatus == OperationalStatus.Up
         && (intf.NetworkInterfaceType == NetworkInterfaceType.Wireless80211
             || intf.NetworkInterfaceType == NetworkInterfaceType.Ethernet));

then:

var hw = ni.GetPhysicalAddress();
return string.Join(":", (from ma in hw.GetAddressBytes() select ma.ToString("X2")).ToArray());

This will return MAC address like: 63:D5:16:27:DE:95


问:
Laravel model create not null violation when value is set
```<code>SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column "title" violates not-null constraint
</code>```

is thrown when executing the create function on the product model. This is the code I am executing:

$title = $csvLine[18];
$description = $csvLine[0];
$link = $csvLine[17];

$productTemp = Product::create([
 'title' => $title,
 'description' => $description,
 'link' => $link,
]);
```

When adding an echo statement inbetween assigning csv values to variable and creating the product, it is not null. But when I create it immediatly throws a null contrains violation.

答: You most likely have not declared title as fillable in the Products model.

Body:
SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column "title" violates not-null constraint

is thrown when executing the create function on the product model. This is the code I am executing:

$title = $csvLine[18];
$description = $csvLine[0];
$link = $csvLine[17];

$productTemp = Product::create([
 'title' => $title,
 'description' => $description,
 'link' => $link,
]);

When adding an echo statement inbetween assigning csv values to variable and creating the product, it is not null. But when I create it immediatly throws a null contrains violation.