问:
How to configure monopolistic FIFO application queue in YARN?
I need to disable parallel execution of YARN applications in hadoop cluster. Now, YARN has default settings, so several jobs can run in parallel. I see no advantages of this, because both jobs run slower.

I found this setting yarn.scheduler.capacity.maximum-applications which limits maximum number of applications, but it affects both submitted and running apps (as stated in docs). I'd like to keep submitted apps in queue until current running application is not finished. How can this be done?

答:
As per my understanding about your question. I see, the above code line/setting only may not help you. Can you check below code with your existing setup, it may give you some solution.</p>

```<code><allocations>
  <defaultQueueSchedulingPolicy>fair</defaultQueueSchedulingPolicy>

  <queue name="<<Your Queue Name>>"
    <weight>40</weight>
    <schedulingPolicy>fifo</schedulingPolicy>
  </queue>

  <queue name=<<Your Queue Name>>>
    <weight>60</weight>
    <queue name=<<Your Queue Name>> />
    <queue name=<<Your Queue Name>> />
  </queue>

  <queuePlacementPolicy>
    <rule name="specified" create="false" />
    <rule name="primaryGroup" create="false" />
    <rule name="default" queue=<<Your Queue Name>> />
  </queuePlacementPolicy>
</allocations>
</code>```

Body:
As per my understanding about your question. I see, the above code line/setting only may not help you. Can you check below code with your existing setup, it may give you some solution.

<allocations>
  <defaultQueueSchedulingPolicy>fair</defaultQueueSchedulingPolicy>

  <queue name="<<Your Queue Name>>"
    <weight>40</weight>
    <schedulingPolicy>fifo</schedulingPolicy>
  </queue>

  <queue name=<<Your Queue Name>>>
    <weight>60</weight>
    <queue name=<<Your Queue Name>> />
    <queue name=<<Your Queue Name>> />
  </queue>

  <queuePlacementPolicy>
    <rule name="specified" create="false" />
    <rule name="primaryGroup" create="false" />
    <rule name="default" queue=<<Your Queue Name>> />
  </queuePlacementPolicy>
</allocations>


来源: stackexchange

问:
GCC -O2 and __attribute__((weak))
It looks like GCC with -O2 and __attribute__((weak)) produces different results depending on how you reference your weak symbols. Consider this:

$ cat weak.c

```<code>#include <stdio.h>

extern const int weaksym1;
const int weaksym1 __attribute__(( weak )) = 0;

extern const int weaksym2;
const int weaksym2 __attribute__(( weak )) = 0;

extern int weaksym3;
int weaksym3 __attribute__(( weak )) = 0;

void testweak(void)
{
    if ( weaksym1 == 0 )
    {
        printf( "0\n" );
    }
    else
    {
        printf( "1\n" );
    }

    printf( "%d\n", weaksym2 );

    if ( weaksym3 == 0 )
    {
        printf( "0\n" );
    }
    else
    {
        printf( "1\n" );
    }
}
</code>```

$ cat test.c

```<code>extern const int weaksym1;
const int weaksym1 = 1;

extern const int weaksym2;
const int weaksym2 = 1;

extern int weaksym3;
int weaksym3 = 1;

extern void testweak(void);

void main(void)
{
    testweak();
}
</code>```

$ make

```<code>gcc  -c weak.c
gcc  -c test.c
gcc  -o test test.o weak.o
</code>```

$ ./test

```<code>1
1
1
</code>```

$ make ADD_FLAGS="-O2"

```<code>gcc -O2 -c weak.c
gcc -O2 -c test.c
gcc -O2 -o test test.o weak.o
</code>```

$ ./test

```<code>0
1
1
</code>```

The question is, why the last "./test" produces "0 1 1", not "1 1 1"?

gcc version 5.4.0 (GCC)

答:
Looks like when doing optimizations, the compiler is having trouble with symbols declared const and having the weak definition within the same compilation unit.

You can create a separate c file and move the const weak definitions there, it will work around the problem:

weak_def.c

```<code>const int weaksym1 __attribute__(( weak )) = 0;
const int weaksym2 __attribute__(( weak )) = 0;
</code>```

Same issue described in this question: GCC weak attribute on constant variables

ContentLicense: CC BY-SA 3.0

Title: GCC -O2 and __attribute__((weak))

Body:
It looks like GCC with -O2 and __attribute__((weak)) produces different results depending on how you reference your weak symbols. Consider this:

$ cat weak.c

#include <stdio.h>

extern const int weaksym1;
const int weaksym1 __attribute__(( weak )) = 0;

extern const int weaksym2;
const int weaksym2 __attribute__(( weak )) = 0;

extern int weaksym3;
int weaksym3 __attribute__(( weak )) = 0;

void testweak(void)
{
    if ( weaksym1 == 0 )
    {
        printf( "0\n" );
    }
    else
    {
        printf( "1\n" );
    }

    printf( "%d\n", weaksym2 );

    if ( weaksym3 == 0 )
    {
        printf( "0\n" );
    }
    else
    {
        printf( "1\n" );
    }
}

$ cat test.c

extern const int weaksym1;
const int weaksym1 = 1;

extern const int weaksym2;
const int weaksym2 = 1;

extern int weaksym3;
int weaksym3 = 1;

extern void testweak(void);

void main(void)
{
    testweak();
}

$ make

gcc  -c weak.c
gcc  -c test.c
gcc  -o test test.o weak.o

$ ./test

1
1
1

$ make ADD_FLAGS="-O2"

gcc -O2 -c weak.c
gcc -O2 -c test.c
gcc -O2 -o test test.o weak.o

$ ./test

0
1
1

The question is, why the last "./test" produces "0 1 1", not "1 1 1"?

gcc version 5.4.0 (GCC)

Body:
Looks like when doing optimizations, the compiler is having trouble with symbols declared const and having the weak definition within the same compilation unit.

You can create a separate c file and move the const weak definitions there, it will work around the problem:

weak_def.c

const int weaksym1 __attribute__(( weak )) = 0;
const int weaksym2 __attribute__(( weak )) = 0;

Same issue described in this question: GCC weak attribute on constant variables

ContentLicense: CC BY-SA 4.0


问:
How do I access this variable in react js?
Parent Component:

```<code>render(){
    console.log("here2");
    var temp = [];
    this.props.datarows.forEach((data, key) => {
            temp = this.props.datarows[key]  })
    return(
            <tr>
                <ListColumn col = { this.temp } />
            </tr>
        )
}
</code>```

ListColumn.py

```<code>import React, { Component } from 'react';
import _ from 'lodash';

export default class ListColumn extends Component{

    render(){
        var columns = [];
        console.log("here3")
        console.log(this.props.col);
        // for (var key in this.props.col)
        // {
        //  columns.push(<td>this.props.col[key]</td>)
        // }
        // console.log(columns);
        // return(
        //  columns
        // )
        return(
                <td>a</td>
            )
    }
}
</code>```

When I tried printing the value of this.props.col, it returns undefined, How do I access the variable temp? Thanks in advance.

答:
The problem is,temp decalared as var temp = []; but you passing this.temp
change:  <ListColumn col = { this.temp } />

to

```<code><ListColumn col ={temp } />
</code>```

So,

```<code>render(){
    console.log("here2");
    var temp = [];
    this.props.datarows.forEach((data, key) => {
            temp = this.props.datarows[key]  })//it should be temp.push(data) if you want to pass all datarows as props
    return(
            <tr>
                <ListColumn col = {temp } />
            </tr>
        )
}
</code>```

2.

```<code> for (var key in this.props.col)
    {
      columns.push(<td>this.props.col[key]</td>)
     }
</code>```

Should be

```<code> for (var key in this.props.col)
     {
        columns.push(<td key={key}>{this.props.col[key]}</td>)
     }
</code>```

Body:
Parent Component:

render(){
    console.log("here2");
    var temp = [];
    this.props.datarows.forEach((data, key) => {
            temp = this.props.datarows[key]  })
    return(

                <ListColumn col = { this.temp } />

        )
}

ListColumn.py

import React, { Component } from 'react';
import _ from 'lodash';

export default class ListColumn extends Component{

    render(){
        var columns = [];
        console.log("here3")
        console.log(this.props.col);
        // for (var key in this.props.col)
        // {
        //  columns.push(this.props.col[key]	)
        // }
        // console.log(columns);
        // return(
        //  columns
        // )
        return(
                a
            )
    }
}

When I tried printing the value of this.props.col, it returns undefined, How do I access the variable temp? Thanks in advance.

Body:
The problem is,temp decalared as var temp = []; but you passing this.temp
change:  <ListColumn col = { this.temp } />

to

<ListColumn col ={temp } />

So,

render(){
    console.log("here2");
    var temp = [];
    this.props.datarows.forEach((data, key) => {
            temp = this.props.datarows[key]  })//it should be temp.push(data) if you want to pass all datarows as props
    return(
            <tr>
                <ListColumn col = {temp } />
            </tr>
        )
}

2.

 for (var key in this.props.col)
    {
      columns.push(<td>this.props.col[key]</td>)
     }

Should be

 for (var key in this.props.col)
     {
        columns.push(<td key={key}>{this.props.col[key]}</td>)
     }


问:
Convert a hash into another hash in Ruby
I have a hash of strings

```<code>navigable_objects = { 'Dashboard' => root_path,
                      'Timesheets' => timesheets_path,
                      'Clients' => clients_path,
                      'Projects' => projects_path,
                    }
</code>```

I want to convert them into another hash where the key is again the key, but the value is either the string 'active' or empty string depending on whether the current controller name contains the key.

For example, lets say that the current controller name is "ClientsController".  The result I should get is:

```<code>{ 'Dashboard' => '',
  'Timesheets' => '',
  'Clients' => 'active',
  'Projects' => ''
}
</code>```

Here is how I am currently doing it:

```<code>active = {}

navigable_objects.each do |name, path|
  active[name] = (controller.controller_name.include?(name)) ? 'active' : '')
end
</code>```

I feel that while this works, there is a better way to do this in Ruby, possibly using inject or each_with_objects?

答:
Since Ruby 2.0, there is to_h:

```<code>navigable_objects.map do |name, path|
  [name, controller.controller_name.include?(name)) ? 'active' : '']
end.to_h
</code>```

I don't think it's very efficient, but for small Hashes it's an elegant way.

Body:
I have a hash of strings

navigable_objects = { 'Dashboard' => root_path,
                      'Timesheets' => timesheets_path,
                      'Clients' => clients_path,
                      'Projects' => projects_path,
                    }

I want to convert them into another hash where the key is again the key, but the value is either the string 'active' or empty string depending on whether the current controller name contains the key.

For example, lets say that the current controller name is "ClientsController".  The result I should get is:

{ 'Dashboard' => '',
  'Timesheets' => '',
  'Clients' => 'active',
  'Projects' => ''
}

Here is how I am currently doing it:

active = {}

navigable_objects.each do |name, path|
  active[name] = (controller.controller_name.include?(name)) ? 'active' : '')
end

I feel that while this works, there is a better way to do this in Ruby, possibly using inject or each_with_objects?

Body:
Since Ruby 2.0, there is to_h:

navigable_objects.map do |name, path|
  [name, controller.controller_name.include?(name)) ? 'active' : '']
end.to_h

I don't think it's very efficient, but for small Hashes it's an elegant way.


问:
How setup Node.js error handling?
I have node 7.8.0 and I have read Node.js Best Practice Exception Handling

Still I can't seem to understand error handling in node.js.

For my http I have

```<code>server.on('error', () => console.log('Here I should be replacing
the Error console.'));
</code>```

For 404 I have this code

```<code>app.use((req, res, next) => {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});
app.use((err, req, res) => {
  res.status(err.status);
  res.render('error');
});
</code>```

404 is being caught, it creates the Error object and then it's handled by rendering the error view correctly as I want. But it also throws error log to my console and I have no idea where that is coming from and how to stop it.

I would like to use my own error handling and never actually write errors like 404 into the console.

Codes that I tried and don't seem to work.

```<code>var server = http.createServer(app);
const onError = () => console.log('Here I should be replacing the Error console.');
server.on('error', onError);
server.on('uncaughtException', onError);
process.on('uncaughtException', onError);
</code>```

答:
This is due to expressjs. Expressjs if the env is not equal to the test, the all errors writes to the console.

```<code>function logerror(err) {
  if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}
</code>```

Also http.Server does not have an event named error.

Title: How setup Node.js error handling?

Body:
I have node 7.8.0 and I have read Node.js Best Practice Exception Handling

Still I can't seem to understand error handling in node.js.

For my http I have

server.on('error', () => console.log('Here I should be replacing
the Error console.'));

For 404 I have this code

app.use((req, res, next) => {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});
app.use((err, req, res) => {
  res.status(err.status);
  res.render('error');
});

404 is being caught, it creates the Error object and then it's handled by rendering the error view correctly as I want. But it also throws error log to my console and I have no idea where that is coming from and how to stop it.

I would like to use my own error handling and never actually write errors like 404 into the console.

Codes that I tried and don't seem to work.

var server = http.createServer(app);
const onError = () => console.log('Here I should be replacing the Error console.');
server.on('error', onError);
server.on('uncaughtException', onError);
process.on('uncaughtException', onError);

Body:
This is due to expressjs. Expressjs if the env is not equal to the test, the all errors writes to the console.

function logerror(err) {
  if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}

Also http.Server does not have an event named error.


问:
Bitwise NOT of Java BigInteger is Negative
I am trying to perform a bitwise not on a 128 bit BigInteger in Java. I have a 128 bit number which has the first 64 bits set to 1 and the last 64 bits set to 0 (I am playing with IPv6 masks).

```<code>BigInteger b = new BigInteger(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(b.toString(2));
</code>```

This results in the following, if I output it using base 2:

11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

I am trying to flip/reverse all the bits using a bitwise not.

```<code>System.out.println(b.not().toString(2));
</code>```

From my understanding of a bitwise not, I was expecting all the 1's to change to 0's and all the 0's to change to 1's, but I get the following instead:

-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

This also seems to match the documentation of the not() function:

This method returns a negative value if and only if this BigInteger is non-negative

Is it a case of looping through all 128 bits and performing a bitwise not on each separate bit instead?

UPDATE
It probably helps if I try and explain what I was trying to achieve to give some context. I am manipulating IPv6 addresses and was trying to determine if a given IPv6 address was within a subnet or not based on an IPv6 mask.

Based on the responses, I think the following should work:

E.g.
Is 2001:db8:0:0:8:800:200c:417b within 2001:db8::/64?

```<code>BigInteger n = new BigInteger(1, InetAddress.getByName("2001:db8::").getAddress());
BigInteger b = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(64);

// First Address in Subnet
BigInteger first = n.and(b);

// Last Address in Subnet (this is where I was having a problem as it was returning a negative number)
BigInteger MASK_128 = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
BigInteger last = first.add(b.xor(MASK_128));

// Convert our test IP into BigInteger
BigInteger ip = new BigInteger(1, InetAddress.getByName("2001:db8:0:0:8:800:200c:417b").getAddress());

// Check if IP is >= first and <= last
if ((first.compareTo(ip) <= 0) && (last.compareTo(ip) >= 0)) {
  // in subnet
}
</code>```

答:
As others have pointed out, it's the sign bit that is giving you the result that you don't want.

There are a couple of ways that you can get the inverted bits.  For both of them you will need a 128 bit mask value:

```<code>private static final BigInteger MASK_128 =
    BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
</code>```

Then you can either mask the sign bit:

```<code>BigInteger b = BigInteger.valueOf(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(MASK_128.andNot(b).toString(2));
</code>```

Or invert directly using xor:

```<code>System.out.println(b.xor(MASK_128).toString(2));
</code>```

I expect the mask value will be useful elsewhere once you start fleshing things out also.

Body:
I am trying to perform a bitwise not on a 128 bit BigInteger in Java. I have a 128 bit number which has the first 64 bits set to 1 and the last 64 bits set to 0 (I am playing with IPv6 masks).

BigInteger b = new BigInteger(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(b.toString(2));

This results in the following, if I output it using base 2:

11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

I am trying to flip/reverse all the bits using a bitwise not.

System.out.println(b.not().toString(2));

From my understanding of a bitwise not, I was expecting all the 1's to change to 0's and all the 0's to change to 1's, but I get the following instead:

-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

This also seems to match the documentation of the not() function:

This method returns a negative value if and only if this BigInteger is non-negative

Is it a case of looping through all 128 bits and performing a bitwise not on each separate bit instead?

UPDATE
It probably helps if I try and explain what I was trying to achieve to give some context. I am manipulating IPv6 addresses and was trying to determine if a given IPv6 address was within a subnet or not based on an IPv6 mask.

Based on the responses, I think the following should work:

E.g.
Is 2001:db8:0:0:8:800:200c:417b within 2001:db8::/64?

BigInteger n = new BigInteger(1, InetAddress.getByName("2001:db8::").getAddress());
BigInteger b = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(64);

// First Address in Subnet
BigInteger first = n.and(b);

// Last Address in Subnet (this is where I was having a problem as it was returning a negative number)
BigInteger MASK_128 = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
BigInteger last = first.add(b.xor(MASK_128));

// Convert our test IP into BigInteger
BigInteger ip = new BigInteger(1, InetAddress.getByName("2001:db8:0:0:8:800:200c:417b").getAddress());

// Check if IP is >= first and <= last
if ((first.compareTo(ip) <= 0) && (last.compareTo(ip) >= 0)) {
  // in subnet
}

Body:
As others have pointed out, it's the sign bit that is giving you the result that you don't want.

There are a couple of ways that you can get the inverted bits.  For both of them you will need a 128 bit mask value:

private static final BigInteger MASK_128 =
    BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);

Then you can either mask the sign bit:

BigInteger b = BigInteger.valueOf(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(MASK_128.andNot(b).toString(2));

Or invert directly using xor:

System.out.println(b.xor(MASK_128).toString(2));

I expect the mask value will be useful elsewhere once you start fleshing things out also.


问:
Trying to get property of non-object Laravel 5.4
Hi Guy's Im always getting an error from laravel 5.4.
Im creating a list of members... but when i use @foreach it says

```<code>ErrorException in 6163a8b030c7474bc8eaad359ab99eb61ebdb127.php line 38:
Trying to get property of non-object (View: E:\wamp64\www\gplspring2017\resources\views\admin\memberlist.blade.php)
</code>```

Here's my controller

```<code>public function listmember(Request $request, $idteam)
{
    $teams = DB::table('gpl_team')->where('gpl_team_id', $idteam)->first();
    $count = count($teams);

    if (!$count) {
        return redirect('404');
    } else {
        return view('/admin/memberlist', ['team' => $teams]);
    }
}
</code>```

and here's my view code:

```<code><table class="table table-striped">
    <tr>
        <td style="width:15%;"></td>
        <td style="width:25%;">Summoners Name</td>
        <td style="width:25%;">Name</td>
        <td style="width:25%;">Role</td>
        <td style="width:10%;"></td>
    </tr>
    <?php
    $qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();

    $counting = count($qmember);

    ?>
    @if (! $counting)
    <tr>
        <td colspan="4"> No Recored! </td>
    </tr>
    @else
    @foreach($qmember as $get_member)
    <tr>
        <td><img src="{{ $get_member->member_pic }}" /></td>
        <td></td>
        <td></td>
        <td></td>
        <td>
            <a href="" data-toggle="tooltip" title="Edit Team"><div class="glyphicon glyphicon-pencil"></div></a> |
            <a href="" data-toggle="tooltip" title="Delete Team"><div class="glyphicon glyphicon-trash"></div></a>
        </td>
    </tr>
    @endforeach
    @endif
</table>
</code>```

When i remove the foreach the code is working.. but i try to add the @foreach($qmember as $get_member) it not working anymore...

答:
Using first() method you are fetching only one record from DB that match with the ID (First one matched). You need to use get().

Controller:

```<code>public function listmember(Request $request, $idteam)
    {

        $teams = DB::table('gpl_team')->where('gpl_team_id', $idteam)->get(); //Use get() if you expect more than one result not first()
        $count = count($teams);

        if(! $count)
        {
            return redirect('404');
        }
        else
        {
            return view('/admin/memberlist', ['teams' => $teams]);// this team variable must be used in the blade
        }
    }
</code>```

View:

```<code><table class="table table-striped">
    <tr>
        <td style="width:15%;"></td>
        <td style="width:25%;">Summoners Name</td>
        <td style="width:25%;">Name</td>
        <td style="width:25%;">Role</td>
        <td style="width:10%;"></td>
    </tr>
    <?php

        $qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();

        $counting = count($qmember);
    ?>
    @if (! $counting)
    <tr>
        <td colspan="4"> No Recored! </td>
    </tr>
    @else
       @foreach($teams as $team)
            <tr>
                <td><img src="{{ $team['member_pic'] }}" /></td>
                <td></td>
                <td></td>
                <td></td>
                <td>
                    <a href="" data-toggle="tooltip" title="Edit Team"><div class="glyphicon glyphicon-pencil"></div></a> |
                    <a href="" data-toggle="tooltip" title="Delete Team"><div class="glyphicon glyphicon-trash"></div></a>
                </td>
            </tr>
        @endforeach
    @endif
</table>
</code>```

Body:
Hi Guy's Im always getting an error from laravel 5.4.
Im creating a list of members... but when i use @foreach it says

ErrorException in 6163a8b030c7474bc8eaad359ab99eb61ebdb127.php line 38:
Trying to get property of non-object (View: E:\wamp64\www\gplspring2017\resources\views\admin\memberlist.blade.php)

Here's my controller

public function listmember(Request $request, $idteam)
{
    $teams = DB::table('gpl_team')->where('gpl_team_id', $idteam)->first();
    $count = count($teams);

    if (!$count) {
        return redirect('404');
    } else {
        return view('/admin/memberlist', ['team' => $teams]);
    }
}

and here's my view code:

        Summoners Name
        Name
        Role

    <?php
    $qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();

    $counting = count($qmember);

    ?>
    @if (! $counting)

         No Recored!

    @else
    @foreach($qmember as $get_member)

        member_pic }}" />

 |

    @endforeach
    @endif

When i remove the foreach the code is working.. but i try to add the @foreach($qmember as $get_member) it not working anymore...

Body:
Using first() method you are fetching only one record from DB that match with the ID (First one matched). You need to use get().

Controller:

public function listmember(Request $request, $idteam)
    {

        $teams = DB::table('gpl_team')->where('gpl_team_id', $idteam)->get(); //Use get() if you expect more than one result not first()
        $count = count($teams);

        if(! $count)
        {
            return redirect('404');
        }
        else
        {
            return view('/admin/memberlist', ['teams' => $teams]);// this team variable must be used in the blade
        }
    }

View:

<table class="table table-striped">
    <tr>
        <td style="width:15%;"></td>
        <td style="width:25%;">Summoners Name</td>
        <td style="width:25%;">Name</td>
        <td style="width:25%;">Role</td>
        <td style="width:10%;"></td>
    </tr>
    <?php

        $qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();

        $counting = count($qmember);
    ?>
    @if (! $counting)
    <tr>
        <td colspan="4"> No Recored! </td>
    </tr>
    @else
       @foreach($teams as $team)
            <tr>
                <td><img src="{{ $team['member_pic'] }}" /></td>
                <td></td>
                <td></td>
                <td></td>
                <td>
                    <a href="" data-toggle="tooltip" title="Edit Team"><div class="glyphicon glyphicon-pencil"></div></a> |
                    <a href="" data-toggle="tooltip" title="Delete Team"><div class="glyphicon glyphicon-trash"></div></a>
                </td>
            </tr>
        @endforeach
    @endif
</table>


问:
Does Spring Data JPA ignore @Fetch annotations?
I have the following JPA Mapping (getters and setters out for brevity purposes, the DDL also gets generated from the code which may/may not play a role):

Expense

```<code>@Entity
public class Expense {

@Id
@GeneratedValue
private Long id;

private String name;
private Long amount;
private Boolean monthly;

@OneToOne
@JoinColumn(name = "category")
@Fetch(FetchMode.JOIN)
private Category category;

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<Label> labels = new ArrayList<>();
//constructor, getters and setters...
}
</code>```

Category

```<code>@Entity
public class Category {

@Id
private String name;

//constructor, getters and setters...
}
</code>```

Label

```<code>@Entity
public class Label {

@Id
private String name;
//constructor, getters and setters...

}
</code>```

Usage with JpaRepository

So I am using a JpaRepository that looks like this:

```<code>public interface ExpensesRepository extends JpaRepository<Expense, Long> {

    @Query("SELECT e FROM Expense e LEFT JOIN FETCH e.category")
    List<Expense> findAllExpensesExploded();
}
</code>```

When I use the default findAll() method of the JpaRepository, I get a n+1 select problem:

```<code>2017-01-03 19:35:22.665 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL                        : select expense0_.id as id1_1_, expense0_.amount as amount2_1_, expense0_.category_name as category5_1_, expense0_.monthly as monthly3_1_, expense0_.name as name4_1_ from expense expense0_
2017-01-03 19:35:22.673 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL                        : select category0_.name as name1_0_0_ from category category0_ where category0_.name=?
2017-01-03 19:35:22.674 TRACE 26040 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [Rent]
2017-01-03 19:35:22.682 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL                        : select category0_.name as name1_0_0_ from category category0_ where category0_.name=?
2017-01-03 19:35:22.683 TRACE 26040 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [Insurance]
</code>```

However, when I use my own findAllExpensesExploded() method I get a single SQL query:

```<code>2017-01-03 19:35:22.691 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL                        : select expense0_.id as id1_1_0_, category1_.name as name1_0_1_, expense0_.amount as amount2_1_0_, expense0_.category_name as category5_1_0_, expense0_.monthly as monthly3_1_0_, expense0_.name as name4_1_0_ from expense expense0_ left outer join category category1_ on expense0_.category_name=category1_.name
</code>```

My expectation was for both findAll() and findAllExpensesExploded() to be executed with a single SQL query.

My query worked because I seemed to have constructed it correctly

But why does the findAll() not work with the given mapping annotations? Is it possible that Spring Data is ignoring the @Fetch annotation?

An additional question that seems reasonable to ask is whether the default findAll() should only be used for simple entities? (where simple is defined as no associations).

答:
The Default fetch mode is lazy. It's always a good practice to use @NamedEntityGraph and @EntityGraph annotations when working with Spring Data JPA.You can go through this

```<code>whether the default findAll() should only be used for simple entities? (where simple is defined as no associations).
</code>```

Fetch Mode - LAZY will only fire for primary table. If in the code you call any other method that has a parent table dependency then it will fire Fetch Mode - SELECT.

Body:
I have the following JPA Mapping (getters and setters out for brevity purposes, the DDL also gets generated from the code which may/may not play a role):

Expense

@Entity
public class Expense {

@Id
@GeneratedValue
private Long id;

private String name;
private Long amount;
private Boolean monthly;

@OneToOne
@JoinColumn(name = "category")
@Fetch(FetchMode.JOIN)
private Category category;

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List labels = new ArrayList<>();
//constructor, getters and setters...
}

Category

@Entity
public class Category {

@Id
private String name;

//constructor, getters and setters...
}

Label

@Entity
public class Label {

@Id
private String name;
//constructor, getters and setters...

}

Usage with JpaRepository

So I am using a JpaRepository that looks like this:

public interface ExpensesRepository extends JpaRepository<Expense, Long> {

    @Query("SELECT e FROM Expense e LEFT JOIN FETCH e.category")
    List<Expense> findAllExpensesExploded();
}

When I use the default findAll() method of the JpaRepository, I get a n+1 select problem:

2017-01-03 19:35:22.665 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL                        : select expense0_.id as id1_1_, expense0_.amount as amount2_1_, expense0_.category_name as category5_1_, expense0_.monthly as monthly3_1_, expense0_.name as name4_1_ from expense expense0_
2017-01-03 19:35:22.673 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL                        : select category0_.name as name1_0_0_ from category category0_ where category0_.name=?
2017-01-03 19:35:22.674 TRACE 26040 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [Rent]
2017-01-03 19:35:22.682 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL                        : select category0_.name as name1_0_0_ from category category0_ where category0_.name=?
2017-01-03 19:35:22.683 TRACE 26040 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [Insurance]

However, when I use my own findAllExpensesExploded() method I get a single SQL query:

2017-01-03 19:35:22.691 DEBUG 26040 --- [nio-8080-exec-1] org.hibernate.SQL                        : select expense0_.id as id1_1_0_, category1_.name as name1_0_1_, expense0_.amount as amount2_1_0_, expense0_.category_name as category5_1_0_, expense0_.monthly as monthly3_1_0_, expense0_.name as name4_1_0_ from expense expense0_ left outer join category category1_ on expense0_.category_name=category1_.name

My expectation was for both findAll() and findAllExpensesExploded() to be executed with a single SQL query.

My query worked because I seemed to have constructed it correctly

But why does the findAll() not work with the given mapping annotations? Is it possible that Spring Data is ignoring the @Fetch annotation?

An additional question that seems reasonable to ask is whether the default findAll() should only be used for simple entities? (where simple is defined as no associations).

Body:
The Default fetch mode is lazy. It's always a good practice to use @NamedEntityGraph and @EntityGraph annotations when working with Spring Data JPA.You can go through this

whether the default findAll() should only be used for simple entities? (where simple is defined as no associations).

Fetch Mode - LAZY will only fire for primary table. If in the code you call any other method that has a parent table dependency then it will fire Fetch Mode - SELECT.


问:
C# Do I need TRY/CATCH in order to throw?
If all I want to do is throw the exception up a level when it occurs?

```<code>private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}
</code>```

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

答: These two methods are essentially the same. In this case ReSharper was correct with its suggestion.</p>

OwnerDisplayName: Petrolios

LastEditorDisplayName: Jon Skeet

ContentLicense: CC BY-SA 2.5

Body:
If all I want to do is throw the exception up a level when it occurs?

private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.


问:
Sorting a table breaks the TableRowListener?
I have a sortable default table model with ListSelectionListener that listens for a doubleclick and then opens a details view of a particular column. This works fine, however, when I sort a column the listener no longer functions.</p>

```<code>JTable foosTable = new JTable(model);
TableRowSorter<TableModel> fooSorter = new TableRowSorter<TableModel>(model);
foosTable.setRowSorter(fooSorter);
ListSelectionModel listMod = foosTable.getSelectionModel();
listMod.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionListener barListener = new ListSelectionListener(foosTable);
listMod.addListSelectionListener(barListener);
</code>```

答:
I have never used TableRowListener which seems to only have an itemChanged event. I usually stick to standard swing. Add a mouse listener to the table, grab the location of a click event and then handle it.

```<code> jTable.addMouseListener(new java.awt.event.MouseAdapter() {
     public void mouseClicked(java.awt.event.MouseEvent evt) {
         Point p = new Point(evt.getX(), evt.getY());
         int col = jTable.columnAtPoint(p);
         int row = jTable.rowAtPoint(p);
         if (evt.getButton() == MouseEvent.BUTTON1)
         {
            if (evt.getClickCount() >= 2)
            {
               ...
               ...
            }
        });
</code>```

Edit
Setup a TableRowSorter:

```<code>  TableRowSorter<YourJTableModel> sorter =
        new TableRowSorter<YourJTableModel>(yourJTableModel);
   jTable.setRowSorter(sorter);
</code>```

Because you are changing the row order, you will need to use convertColumnIndexToModel
to get the correct model data for the view.

For more complex sorting/filtering needs you may want to try glazed lists.

Body:
I have a sortable default table model with ListSelectionListener that listens for a doubleclick and then opens a details view of a particular column. This works fine, however, when I sort a column the listener no longer functions.

JTable foosTable = new JTable(model);
TableRowSorter<TableModel> fooSorter = new TableRowSorter<TableModel>(model);
foosTable.setRowSorter(fooSorter);
ListSelectionModel listMod = foosTable.getSelectionModel();
listMod.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionListener barListener = new ListSelectionListener(foosTable);
listMod.addListSelectionListener(barListener);

Body:
I have never used TableRowListener which seems to only have an itemChanged event. I usually stick to standard swing. Add a mouse listener to the table, grab the location of a click event and then handle it.

 jTable.addMouseListener(new java.awt.event.MouseAdapter() {
     public void mouseClicked(java.awt.event.MouseEvent evt) {
         Point p = new Point(evt.getX(), evt.getY());
         int col = jTable.columnAtPoint(p);
         int row = jTable.rowAtPoint(p);
         if (evt.getButton() == MouseEvent.BUTTON1)
         {
            if (evt.getClickCount() >= 2)
            {
               ...
               ...
            }
        });

Edit
Setup a TableRowSorter:

  TableRowSorter<YourJTableModel> sorter =
        new TableRowSorter<YourJTableModel>(yourJTableModel);
   jTable.setRowSorter(sorter);

Because you are changing the row order, you will need to use convertColumnIndexToModel
to get the correct model data for the view.

For more complex sorting/filtering needs you may want to try glazed lists.


问:
Kendo Grid doesn't show any data despite having data within DataSource
So, I'm trying to make a readyonly grid with kendo that shows data, but whatever I do, the data does not get shown.

The grid looks like this

And here's the code:

```<code>    $("#Materials")
        .kendoGrid({
            dataSource: {
                data: [],
                schema: {
                    model: {
                        id: "ID",
                        fields: {
                            ID: { type: "number", editable: false },
                            Code: { type: "string", editable: false },
                            Name: { type: "string", editable: false },
                            ExtDeviceCode: { type: "string", editable: false , nullable: true },
                            BaseUomLOVString: { type: "string", editable: false }
                        }
                    }
                },
                pageSize: 20
            },
            filterable: {
                extra: true
            },
            pageable: true,
            columns: [
                { field: "Code", title:"Code"},
                { field: "Name", title: "Name"},
                { field: "ExtDeviceCode", title:"External device code"},
                { field: "BaseUomLOVString", title: "UnitsOfMeasure" }
            ],
            editable: false
        });
</code>```

This makes an empty grid with no data, which I later on fill with an Ajax call. As you can see from above picture, the grid contains the data but does not display it. The data inside the dataSource looks like this. or as Json:

```<code>[{
    "ID": 21150,
    "Code": "3",
    "ExtDeviceCode": null,
    "Name": "Avio benzin",
    "BaseUomLOVString": "Kilogram"
}, {
    "ID": 21400,
    "Code": "5003",
    "ExtDeviceCode": null,
    "Name": "Bencin 95",
    "BaseUomLOVString": "Litre"
}]
</code>```

EDIT 1:  I'm filling the data with an Ajax call like this:

```<code>            $.ajax({
                url: '@SimpleUrlHelper.UrlObjectToRoot(Url)/FuelPointMaterialTankMask/LookupMaterials',
                data: {
                    //Send list of IDs
                    'materialIDs': materialList
                },
                type: "POST",
                success: function (response) {

                    var tmp = [];
                    if (typeof response !== "undefined" &&
                    response !== null) {
                        response.forEach(function(item) {
                            tmp.push(item);
                        });
                    }
                    grid = $("#Materials").data("kendoGrid");
                    originalMaterialDataSource = grid.dataSource;
                    originalMaterialDataSource.data(tmp);
                    originalMaterialDataSource._destroyed = [];
                    originalMaterialDataSource.pageSize(pageSize);
                    originalMaterialDataSource.page(1);
                    originalMaterialDataSource._total = tmp.length;
                    grid.pager.refresh();
                }
            });
</code>```

答:
Okay so after days of trying to figure out what was wrong I finally found the answer.

Somewhere along the lines I had:

```<code>var grids = $('.k-grid');
for (var i = 0; i < grids.length; i++) {
        ....
grid.dataSource.filter().filters[0] = {
       logic: "or",
       filters: filters
}
        ....
</code>```

So basically I was putting filters on all grids without excluding this one, which was just a bug from my part.

Body:
So, I'm trying to make a readyonly grid with kendo that shows data, but whatever I do, the data does not get shown.

The grid looks like this

And here's the code:

    $("#Materials")
        .kendoGrid({
            dataSource: {
                data: [],
                schema: {
                    model: {
                        id: "ID",
                        fields: {
                            ID: { type: "number", editable: false },
                            Code: { type: "string", editable: false },
                            Name: { type: "string", editable: false },
                            ExtDeviceCode: { type: "string", editable: false , nullable: true },
                            BaseUomLOVString: { type: "string", editable: false }
                        }
                    }
                },
                pageSize: 20
            },
            filterable: {
                extra: true
            },
            pageable: true,
            columns: [
                { field: "Code", title:"Code"},
                { field: "Name", title: "Name"},
                { field: "ExtDeviceCode", title:"External device code"},
                { field: "BaseUomLOVString", title: "UnitsOfMeasure" }
            ],
            editable: false
        });

This makes an empty grid with no data, which I later on fill with an Ajax call. As you can see from above picture, the grid contains the data but does not display it. The data inside the dataSource looks like this. or as Json:

[{
    "ID": 21150,
    "Code": "3",
    "ExtDeviceCode": null,
    "Name": "Avio benzin",
    "BaseUomLOVString": "Kilogram"
}, {
    "ID": 21400,
    "Code": "5003",
    "ExtDeviceCode": null,
    "Name": "Bencin 95",
    "BaseUomLOVString": "Litre"
}]

EDIT 1:  I'm filling the data with an Ajax call like this:

            $.ajax({
                url: '@SimpleUrlHelper.UrlObjectToRoot(Url)/FuelPointMaterialTankMask/LookupMaterials',
                data: {
                    //Send list of IDs
                    'materialIDs': materialList
                },
                type: "POST",
                success: function (response) {

                    var tmp = [];
                    if (typeof response !== "undefined" &&
                    response !== null) {
                        response.forEach(function(item) {
                            tmp.push(item);
                        });
                    }
                    grid = $("#Materials").data("kendoGrid");
                    originalMaterialDataSource = grid.dataSource;
                    originalMaterialDataSource.data(tmp);
                    originalMaterialDataSource._destroyed = [];
                    originalMaterialDataSource.pageSize(pageSize);
                    originalMaterialDataSource.page(1);
                    originalMaterialDataSource._total = tmp.length;
                    grid.pager.refresh();
                }
            });

Body:
Okay so after days of trying to figure out what was wrong I finally found the answer.

Somewhere along the lines I had:

var grids = $('.k-grid');
for (var i = 0; i < grids.length; i++) {
        ....
grid.dataSource.filter().filters[0] = {
       logic: "or",
       filters: filters
}
        ....

So basically I was putting filters on all grids without excluding this one, which was just a bug from my part.


问:
Memory leak with Eigen sparse matrices multiplication
I have these three sparse matrices, defined in the following way:

```<code>typedef SparseMatrix<double> SpMat;

int m_totSize = 256*256;

SpMat *L = new SpMat(m_totSize, m_totSize);
SpMat *A = new SpMat(m_totSize, m_totSize);
SpMat *W = new SpMat(m_totSize, m_totSize);
</code>```

I am setting L with "setFromTriplets" and set W as the identity matrix.

Now I want to do:

```<code>*A = (*W)*(*L);
</code>```

(Although I know it's going to give me L back).

And then:

```<code>delete L;
delete A;
delete W;
</code>```

Even though I'm deleting the matrices at the end (I've also tried resize(0,0)), I'm experiencing severe memory leaks because of this multiplication.

Any ideas?

Thanks!

答: It seems the memory leak originates from another part of my application, and the multiplication is the final straw (in terms of memory consumption). But it does not originate from there... sorry.</p>

Body:
I have these three sparse matrices, defined in the following way:

typedef SparseMatrix<double> SpMat;

int m_totSize = 256*256;

SpMat *L = new SpMat(m_totSize, m_totSize);
SpMat *A = new SpMat(m_totSize, m_totSize);
SpMat *W = new SpMat(m_totSize, m_totSize);

I am setting L with "setFromTriplets" and set W as the identity matrix.

Now I want to do:

*A = (*W)*(*L);

(Although I know it's going to give me L back).

And then:

delete L;
delete A;
delete W;

Even though I'm deleting the matrices at the end (I've also tried resize(0,0)), I'm experiencing severe memory leaks because of this multiplication.

Any ideas?

Thanks!


问:
asp:LinkButton in gridview to retreive audio file from folder to html audio so that it can play
I have a webform that consist of

```<code><audio controls="controls" id="audio" runat="server"></audio>
</code>```

and

```<code><asp:GridView ID="GridView1" runat="server" GridLines="None" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
    <Columns>
            <asp:TemplateField HeaderText="Name" SortExpression="Name">
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Bind("Name") %>' OnClick="LinkButton1_Click"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConStr %>" SelectCommand="SELECT [Name], [Date] FROM [tablename]"></asp:SqlDataSource>
</code>```

I'm so stuck at code behind. I want to play the audio file from folder by checking the date and path from database. I have something like the code below in vb

```<code>audio.Attributes("src") = "Audio/" 'I am unable to continue from here.
</code>```

答:
You can change the LinkButton from an OnClick to a OnCommand. That way you can send a CommandArgument with it.

```<code><asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("FileName") %>' OnCommand="LinkButton1_Command">LinkButton1</asp:LinkButton>
</code>```

Then in the Command method in code behind you can get the file name from the command argument an use it as the source for the player.

```<code>protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
    string fileName = e.CommandArgument.ToString();
    audio.Attributes.Add("src", Server.MapPath("/Audio/" + fileName));
}
</code>```

UPDATE

If the filename is always going to be the Text of the LinkButton, you can also cast the sender back to one and get the Text property.

```<code>protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
    LinkButton lb = sender as LinkButton;
    audio.Attributes.Add("src", Server.MapPath("/Audio/" + lb.Text));
}
</code>```

Body:
I have a webform that consist of

<audio controls="controls" id="audio" runat="server"></audio>

and

<asp:GridView ID="GridView1" runat="server" GridLines="None" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
    <Columns>
            <asp:TemplateField HeaderText="Name" SortExpression="Name">
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Bind("Name") %>' OnClick="LinkButton1_Click"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConStr %>" SelectCommand="SELECT [Name], [Date] FROM [tablename]"></asp:SqlDataSource>

I'm so stuck at code behind. I want to play the audio file from folder by checking the date and path from database. I have something like the code below in vb

audio.Attributes("src") = "Audio/" 'I am unable to continue from here.

Body:
You can change the LinkButton from an OnClick to a OnCommand. That way you can send a CommandArgument with it.

<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("FileName") %>' OnCommand="LinkButton1_Command">LinkButton1</asp:LinkButton>

Then in the Command method in code behind you can get the file name from the command argument an use it as the source for the player.

protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
    string fileName = e.CommandArgument.ToString();
    audio.Attributes.Add("src", Server.MapPath("/Audio/" + fileName));
}

UPDATE

If the filename is always going to be the Text of the LinkButton, you can also cast the sender back to one and get the Text property.

protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
    LinkButton lb = sender as LinkButton;
    audio.Attributes.Add("src", Server.MapPath("/Audio/" + lb.Text));
}


问:
How to use a recursive function to count the sum of the positive elements of a list?
How to use a recursive function to count the sum of the positive elements of a list?

I'm not sure how to go about it? I know how to do it without using a recursive function:

```<code>sum=0
for i in range(len(List)):
    if List[i]>0:
        sum=sum+List[i]
</code>```

答:
this can be one wy of doing it.

```<code>def fun(l):
    if len(l)==0:
        return 0
    num = l.pop()
    if num > 0:
        return num + fun(l)
    return fun(l)
</code>```

but be careful. this function destroys the list that has benn passed to it. so make a copy of your list before passing it to the function or:

```<code>def fun(l):
    if len(l)==0:
        return 0
    if len(l)==1:
        return l[0]
    num = l[0]
    if num > 0:
        return num + fun(l[1:])
    return fun(l[1:])
</code>```

Body:
How to use a recursive function to count the sum of the positive elements of a list?

I'm not sure how to go about it? I know how to do it without using a recursive function:

sum=0
for i in range(len(List)):
    if List[i]>0:
        sum=sum+List[i]

Body:
this can be one wy of doing it.

def fun(l):
    if len(l)==0:
        return 0
    num = l.pop()
    if num > 0:
        return num + fun(l)
    return fun(l)

but be careful. this function destroys the list that has benn passed to it. so make a copy of your list before passing it to the function or:

def fun(l):
    if len(l)==0:
        return 0
    if len(l)==1:
        return l[0]
    num = l[0]
    if num > 0:
        return num + fun(l[1:])
    return fun(l[1:])


问:
Hide footer view in ListView?
I have a ListView. The data behind it is fetched from the Internet, in sets of 10-30 items whenever the user scrolls all the way to the bottom. In order to indicate that it is loading more items, I used addFooterView() to add a simple view that displays a "Loading..." message and a spinner. Now, when I'm out of data (no more data to fetch), I want to hide that message. I tried to do:

```<code>loadingView.setVisibility(View.GONE);
</code>```

Unfortunately, while that does hide the view, it leaves space for it. I.e. I end up with a big blank space where the "Loading" message used to be. How can I go about properly hiding this view?

I can't use removeFooterView() because I may need to show it again, in which case I can't call addFooterView() again because an adapter has already been set on the ListView, and you can't call addHeaderView() / addFooterView() after setting an adapter.

答: The Droid-Fu library has a class designed for having a loading footer show and hide: ListAdapterWithProgress.</p>

Title: Hide footer view in ListView?

Body:
I have a ListView. The data behind it is fetched from the Internet, in sets of 10-30 items whenever the user scrolls all the way to the bottom. In order to indicate that it is loading more items, I used addFooterView() to add a simple view that displays a "Loading..." message and a spinner. Now, when I'm out of data (no more data to fetch), I want to hide that message. I tried to do:

loadingView.setVisibility(View.GONE);

Unfortunately, while that does hide the view, it leaves space for it. I.e. I end up with a big blank space where the "Loading" message used to be. How can I go about properly hiding this view?

I can't use removeFooterView() because I may need to show it again, in which case I can't call addFooterView() again because an adapter has already been set on the ListView, and you can't call addHeaderView() / addFooterView() after setting an adapter.


问:
Does R perform automatic partial column match in data frame, if the column does not exists in the data frame
R is performing the automatic partial match with existing columns.
This is the code I ran...

```<code>a<-mtcars
## I get the results for this
a$mpg
## Surprisingly I am getting the results for which is same as a$mpg data
a$m
</code>```

May I know why this is happening?

Thanks in advance

答:
We can use [[ or [, to subset without partial matching

```<code>a[["mpg"]]
a[, 'mpg']
</code>```

Body:
R is performing the automatic partial match with existing columns.
This is the code I ran...

a<-mtcars
## I get the results for this
a$mpg
## Surprisingly I am getting the results for which is same as a$mpg data
a$m

May I know why this is happening?

Thanks in advance

Body:
We can use [[ or [, to subset without partial matching

a[["mpg"]]
a[, 'mpg']


问:
Moodle event observer not triggered in local plugin
I have created a plugin at this location moodle/local/redirectafterlogin with the following structure :

```<code>redirectafterlogin/
├── db
│   ├── classes
│   │   └── observer.php
│   └── events
│       └── events.php
└── version.php
</code>```

version.php:

```<code>defined('MOODLE_INTERNAL') || die();

$plugin->version = 20170333;
$plugin->requires = 2015111000;
$plugin->component = 'local_redirectafterlogin';
</code>```

events.php:

```<code>defined('MOODLE_INTERNAL') || die();

    $observers = array(
        array(
            'eventname' => 'core\event\user_loggedin',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
        array(
            'eventname' => 'core\event\user_loggedout',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
    );
</code>```

observer.php:

```<code>class local_redirectafterlogin_observer
{
    public static function user_loggedin(core\event\base $event)
    {
        $event_data = $event->get_data();
        var_dump($event_data);
        die();
    }
}
</code>```

Cached has been cleared a lot of time and version number has been bumped too but the callback is never called!

What's wrong, why does the callback is not triggered?

How can I debug events (is there a way in Moodle to see dispatched events)?

答:
It was a structure mistake! I put the classes folder containing observer.php in the db folder!
After moving the classes folder at the root of the plugin as follow, this is ok, observer is triggered!

Structure that is ok:

```<code>redirectafterlogin/
├── classes
│   └── observer.php
├── db
│   └── events.php
└── version.php
</code>```

Body:
I have created a plugin at this location moodle/local/redirectafterlogin with the following structure :

redirectafterlogin/
├── db
│   ├── classes
│   │   └── observer.php
│   └── events
│       └── events.php
└── version.php

version.php:

defined('MOODLE_INTERNAL') || die();

$plugin->version = 20170333;
$plugin->requires = 2015111000;
$plugin->component = 'local_redirectafterlogin';

events.php:

defined('MOODLE_INTERNAL') || die();

    $observers = array(
        array(
            'eventname' => 'core\event\user_loggedin',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
        array(
            'eventname' => 'core\event\user_loggedout',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
    );

observer.php:

class local_redirectafterlogin_observer
{
    public static function user_loggedin(core\event\base $event)
    {
        $event_data = $event->get_data();
        var_dump($event_data);
        die();
    }
}

Cached has been cleared a lot of time and version number has been bumped too but the callback is never called!

What's wrong, why does the callback is not triggered?

How can I debug events (is there a way in Moodle to see dispatched events)?

Body:
It was a structure mistake! I put the classes folder containing observer.php in the db folder!
After moving the classes folder at the root of the plugin as follow, this is ok, observer is triggered!

Structure that is ok:

redirectafterlogin/
├── classes
│   └── observer.php
├── db
│   └── events.php
└── version.php


问:
CalendarView Android Studio
I am trying to populate my CalendarView with events in android studio. I have already established a connection to my web service.

```<code>What I need my calendar to do is:

1) Turn unavailable dates another color.
2) When a date is clicked on, have some type of textview pop up with events for that particular day.
3) When an available day is clicked on, set that day to a textview.
</code>```

I have never worked with the calendarview widget so if anyone knows where I can get answers please attach a link. Thanks.

答:
You can try this link https://github.com/marcohc/roboto-calendar-view. This link is the library for calendar. I already use it, work awesome.

Need add this in your gradle build file.

```<code> compile 'com.github.marcohc:robotocalendarview:<release>'
</code>```

Hope it will help you.

Title: CalendarView Android Studio

Body:
I am trying to populate my CalendarView with events in android studio. I have already established a connection to my web service.

What I need my calendar to do is:

1) Turn unavailable dates another color.
2) When a date is clicked on, have some type of textview pop up with events for that particular day.
3) When an available day is clicked on, set that day to a textview.

I have never worked with the calendarview widget so if anyone knows where I can get answers please attach a link. Thanks.

Body:
You can try this link https://github.com/marcohc/roboto-calendar-view. This link is the library for calendar. I already use it, work awesome.

Need add this in your gradle build file.

 compile 'com.github.marcohc:robotocalendarview:<release>'

Hope it will help you.


问:
ion-searchbar as a tab component IONIC 2
My Ionic 2 App is having 5 tabs:-

```<code><ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="ios-blicon-home" ></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Categories" tabIcon="ios-blicon-category"></ion-tab>
  <ion-tab tabTitle="Search" tabIcon="ios-blicon-search" (click)="startsearch()"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="Bookmark" tabIcon="ios-blicon-bookmark"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="Me" tabIcon="ios-blicon-me"></ion-tab>
</ion-tabs>
</code>```

I have four component and one is a search tab where I want to pop a seachbar (ion-searchbar) whenever clicked and it can trigger a function on submit.

I am not sure how to do this, please suggest me.

Thank you..!!

答:
In your Tabs component, use ionSelect event instead of click

```<code><ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="ios-blicon-home" ></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Categories" tabIcon="ios-blicon-category"></ion-tab>
  <ion-tab tabTitle="Search" tabIcon="ios-blicon-search" (ionSelect)="startsearch()"></ion-tab><!-- use ionSelect -->
  <ion-tab [root]="tab4Root" tabTitle="Bookmark" tabIcon="ios-blicon-bookmark"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="Me" tabIcon="ios-blicon-me"></ion-tab>
</ion-tabs>
<ion-searchbar *ngIf="showSearch"></ion-searchbar>
</code>```

In the component side have a class variable:

```<code>showSearch:boolean=false;
startsearch(){
 this.showSearch = ! this.showSearch;
}
</code>```

Body:
My Ionic 2 App is having 5 tabs:-

<ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="ios-blicon-home" ></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Categories" tabIcon="ios-blicon-category"></ion-tab>
  <ion-tab tabTitle="Search" tabIcon="ios-blicon-search" (click)="startsearch()"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="Bookmark" tabIcon="ios-blicon-bookmark"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="Me" tabIcon="ios-blicon-me"></ion-tab>
</ion-tabs>

I have four component and one is a search tab where I want to pop a seachbar (ion-searchbar) whenever clicked and it can trigger a function on submit.

I am not sure how to do this, please suggest me.

Thank you..!!

Body:
In your Tabs component, use ionSelect event instead of click

<ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="ios-blicon-home" ></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Categories" tabIcon="ios-blicon-category"></ion-tab>
  <ion-tab tabTitle="Search" tabIcon="ios-blicon-search" (ionSelect)="startsearch()"></ion-tab><!-- use ionSelect -->
  <ion-tab [root]="tab4Root" tabTitle="Bookmark" tabIcon="ios-blicon-bookmark"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="Me" tabIcon="ios-blicon-me"></ion-tab>
</ion-tabs>
<ion-searchbar *ngIf="showSearch"></ion-searchbar>

In the component side have a class variable:

showSearch:boolean=false;
startsearch(){
 this.showSearch = ! this.showSearch;
}


问:
Program won't start through bat file
I have a program called program.exe

It's located in the folder:

```<code>C:\Program Files\Comp\Soft\program.exe
</code>```

I want to start it through a bat file but failed to do so.

Everything works when I do this in cmd:

```<code>cmd> cd C:\Program Files\Comp\Soft\
cmd> program.exe
// program is running
</code>```

I tried to do it in a bat file using these combinations:

```<code>Start "" "C:\Program Files\Comp\Soft\program.exe"
Start /d "" "C:\Program Files\Comp\Soft" "program.exe"
Start /d /w "" "C:\Program Files\Comp\Soft" "program.exe"
</code>```

But failed everytime.

What's wrong with my file?

答:
Yout start syntax is wrong, you need to specify the working directory immediately after the /D option:

```<code>Start "" /D "C:\Program Files\Comp\Soft" "program.exe"
</code>```

Or:

```<code>Start "" /D "C:\Program Files\Comp\Soft" /WAIT "program.exe"
</code>```

Title: Program won't start through bat file

Body:
I have a program called program.exe

It's located in the folder:

C:\Program Files\Comp\Soft\program.exe

I want to start it through a bat file but failed to do so.

Everything works when I do this in cmd:

cmd> cd C:\Program Files\Comp\Soft\
cmd> program.exe
// program is running

I tried to do it in a bat file using these combinations:

Start "" "C:\Program Files\Comp\Soft\program.exe"
Start /d "" "C:\Program Files\Comp\Soft" "program.exe"
Start /d /w "" "C:\Program Files\Comp\Soft" "program.exe"

But failed everytime.

What's wrong with my file?

Body:
Yout start syntax is wrong, you need to specify the working directory immediately after the /D option:

Start "" /D "C:\Program Files\Comp\Soft" "program.exe"

Or:

Start "" /D "C:\Program Files\Comp\Soft" /WAIT "program.exe"


问:
How do I access this variable in react js?
Parent Component:

```<code>render(){
    console.log("here2");
    var temp = [];
    this.props.datarows.forEach((data, key) => {
            temp = this.props.datarows[key]  })
    return(
            <tr>
                <ListColumn col = { this.temp } />
            </tr>
        )
}
</code>```

ListColumn.py

```<code>import React, { Component } from 'react';
import _ from 'lodash';

export default class ListColumn extends Component{

    render(){
        var columns = [];
        console.log("here3")
        console.log(this.props.col);
        // for (var key in this.props.col)
        // {
        //  columns.push(<td>this.props.col[key]</td>)
        // }
        // console.log(columns);
        // return(
        //  columns
        // )
        return(
                <td>a</td>
            )
    }
}
</code>```

When I tried printing the value of this.props.col, it returns undefined, How do I access the variable temp? Thanks in advance.

答:
Instead of

<ListColumn col = { this.temp } />

use

<ListColumn col = {temp } />

Reason: In JS this refers to the object that own the code, inside render method this will refer to the react component. If you use this.temp, it will not take the local variable (defined inside render method), So instead of this.temp use temp (local variable).

One more thing, if you use it like this:

```<code>this.props.datarows.forEach((data, key) => {
         temp = this.props.datarows[key]  })
</code>```

temp will have the last value of this.props.datarows array. I think, you want something like this:

```<code>this.props.datarows.forEach((data, key) => {
      if(/*use some condition to filter out the value that you want to save in temp array*/){
           temp.push(data);
      }
}
</code>```

or if you want to assign the same array to temp variable, looping is not required in that case.

Suggestion: In place of this.props.datarows[key] you can use data also, because data and this.props.datarows[key] will be same.

Body:
Parent Component:

render(){
    console.log("here2");
    var temp = [];
    this.props.datarows.forEach((data, key) => {
            temp = this.props.datarows[key]  })
    return(

                <ListColumn col = { this.temp } />

        )
}

ListColumn.py

import React, { Component } from 'react';
import _ from 'lodash';

export default class ListColumn extends Component{

    render(){
        var columns = [];
        console.log("here3")
        console.log(this.props.col);
        // for (var key in this.props.col)
        // {
        //  columns.push(this.props.col[key]	)
        // }
        // console.log(columns);
        // return(
        //  columns
        // )
        return(
                a
            )
    }
}

When I tried printing the value of this.props.col, it returns undefined, How do I access the variable temp? Thanks in advance.

Body:
Instead of

<ListColumn col = { this.temp } />

use

<ListColumn col = {temp } />

Reason: In JS this refers to the object that own the code, inside render method this will refer to the react component. If you use this.temp, it will not take the local variable (defined inside render method), So instead of this.temp use temp (local variable).

One more thing, if you use it like this:

this.props.datarows.forEach((data, key) => {
         temp = this.props.datarows[key]  })

temp will have the last value of this.props.datarows array. I think, you want something like this:

this.props.datarows.forEach((data, key) => {
      if(/*use some condition to filter out the value that you want to save in temp array*/){
           temp.push(data);
      }
}

or if you want to assign the same array to temp variable, looping is not required in that case.

Suggestion: In place of this.props.datarows[key] you can use data also, because data and this.props.datarows[key] will be same.


问:
Install bash on Alpine/Docker using qemu for ARM host
I am trying to create, at buildtime on an x86 host, a docker container
, for runtime on an ARM host. To do this you need to use qemu for cross compilation. I also want to use alpine linux since the image size is so small.

However I am encountering an unusual error that only happens at build time - a problem
installing bash.

My understanding is when running apk -U add bash, apk updates the package list
from the repositories and then installs the latest version of the package requested.
In then runs post-install scripts. It seems these post install scripts fail.
However, when I built the image without bash and then ran interactively the container
on the ARM host, and did apk fix && apk -U add bash it did the trick. Doing this
command at build time fails however.

How can I add bash at buildtime?

Dockerfile

```<code>FROM armhf/alpine:3.5

ENV CONSUL_PREFIX __CONSUL_PREFIX__
ENV CONSUL_SECRET_PREFIX __CONSUL_SECRET_PREFIX__

ENV QEMU_EXECVE 1

COPY deploy/qemu/qemu-arm-static            /usr/bin/

RUN ["qemu-arm-static","/sbin/apk","fix"]
RUN ["qemu-arm-static","/sbin/apk","add","-U","bash"]

RUN ["qemu-arm-static","/sbin/apk","-U","add", \
                       "postgresql-client",\
                       "curl","vim",\
                       "tzdata","bc"]

RUN ["qemu-arm-static","/bin/cp","usr/share/zoneinfo/America/Los_Angeles","/etc/localtime"]
RUN ["qemu-arm-static","/bin/echo","America/Los_Angeles",">","/etc/timezone"]
RUN ["qemu-arm-static","/bin/rm","-rf","/var/cache/apk/*"]
RUN ["qemu-arm-static","/bin/sh"]

COPY deploy                         /usr/local/deploy
COPY deploy/default/bashrc          /root/.bashrc
COPY deploy/default/vimrc           /root/.vimrc

COPY src                            /src
</code>```

Build log / Error

```<code>@C02NN3NBG3QT:dev-resources $ ./publish-image
+ : router-logs
+ : quay.io
+ : quay.io/skilbjo/router-logs
+ : skilbjo@github.com
++ echo router-logs
++ tr - _
+ : router_logs/config
++ echo router-logs
++ tr - _
+ : router_logs/secrets
+ cat ../deploy/default/Dockerfile
+ sed 's;__CONSUL_PREFIX__;router_logs/config;'
+ sed 's;__CONSUL_SECRET_PREFIX__;router_logs/secrets;'
+ IMAGE_TAG=dev
+ cd ..
++ git rev-parse HEAD
+ echo 0a865e3918d584b4377fad9afe9ba28a1dbe5968
+ docker build --rm -t quay.io/skilbjo/router-logs:dev .
Sending build context to Docker daemon 8.713 MB
Step 1 : FROM armhf/alpine:3.5
 ---> 3ddfeafc01f0
Step 2 : ENV CONSUL_PREFIX router_logs/config
 ---> Using cache
 ---> e2aae782f6d8
Step 3 : ENV CONSUL_SECRET_PREFIX router_logs/secrets
 ---> Using cache
 ---> 71c863da2558
Step 4 : ENV QEMU_EXECVE 1
 ---> Using cache
 ---> a7e80415d0d4
Step 5 : COPY deploy/qemu/qemu-arm-static /usr/bin/
 ---> Using cache
 ---> 265df9b6575f
Step 6 : RUN qemu-arm-static /sbin/apk fix
 ---> Using cache
 ---> def74ac67891
Step 7 : RUN qemu-arm-static /sbin/apk add -U bash
 ---> Running in 6f62d2ecd6b3
fetch http://dl-cdn.alpinelinux.org/alpine/v3.5/main/armhf/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.5/community/armhf/APKINDEX.tar.gz
(1/5) Installing ncurses-terminfo-base (6.0-r7)
(2/5) Installing ncurses-terminfo (6.0-r7)
(3/5) Installing ncurses-libs (6.0-r7)
(4/5) Installing readline (6.3.008-r4)
(5/5) Installing bash (4.3.46-r5)
Executing bash-4.3.46-r5.post-install
ERROR: bash-4.3.46-r5.post-install: script exited with error 1
Executing busybox-1.25.1-r0.trigger
ERROR: busybox-1.25.1-r0.trigger: script exited with error 1
1 errors; 7 MiB in 16 packages
The command 'qemu-arm-static /sbin/apk add -U bash' returned a non-zero code: 1
</code>```

Project repo is here: https://github.com/skilbjo/router-logs

答: It turns out FROM armhf/alpine:3.5 is not good and FROM resin/armhf-alpine:3.5 will do the trick! I'd love to be able to see the commants from scratch that resulted in the armhf image being borked, but for now, this works!

Body:
I am trying to create, at buildtime on an x86 host, a docker container
, for runtime on an ARM host. To do this you need to use qemu for cross compilation. I also want to use alpine linux since the image size is so small.

However I am encountering an unusual error that only happens at build time - a problem
installing bash.

My understanding is when running apk -U add bash, apk updates the package list
from the repositories and then installs the latest version of the package requested.
In then runs post-install scripts. It seems these post install scripts fail.
However, when I built the image without bash and then ran interactively the container
on the ARM host, and did apk fix && apk -U add bash it did the trick. Doing this
command at build time fails however.

How can I add bash at buildtime?

Dockerfile

FROM armhf/alpine:3.5

ENV CONSUL_PREFIX __CONSUL_PREFIX__
ENV CONSUL_SECRET_PREFIX __CONSUL_SECRET_PREFIX__

ENV QEMU_EXECVE 1

COPY deploy/qemu/qemu-arm-static            /usr/bin/

RUN ["qemu-arm-static","/sbin/apk","fix"]
RUN ["qemu-arm-static","/sbin/apk","add","-U","bash"]

RUN ["qemu-arm-static","/sbin/apk","-U","add", \
                       "postgresql-client",\
                       "curl","vim",\
                       "tzdata","bc"]

RUN ["qemu-arm-static","/bin/cp","usr/share/zoneinfo/America/Los_Angeles","/etc/localtime"]
RUN ["qemu-arm-static","/bin/echo","America/Los_Angeles",">","/etc/timezone"]
RUN ["qemu-arm-static","/bin/rm","-rf","/var/cache/apk/*"]
RUN ["qemu-arm-static","/bin/sh"]

COPY deploy                         /usr/local/deploy
COPY deploy/default/bashrc          /root/.bashrc
COPY deploy/default/vimrc           /root/.vimrc

COPY src                            /src

Build log / Error

@C02NN3NBG3QT:dev-resources $ ./publish-image
+ : router-logs
+ : quay.io
+ : quay.io/skilbjo/router-logs
+ : skilbjo@github.com
++ echo router-logs
++ tr - _
+ : router_logs/config
++ echo router-logs
++ tr - _
+ : router_logs/secrets
+ cat ../deploy/default/Dockerfile
+ sed 's;__CONSUL_PREFIX__;router_logs/config;'
+ sed 's;__CONSUL_SECRET_PREFIX__;router_logs/secrets;'
+ IMAGE_TAG=dev
+ cd ..
++ git rev-parse HEAD
+ echo 0a865e3918d584b4377fad9afe9ba28a1dbe5968
+ docker build --rm -t quay.io/skilbjo/router-logs:dev .
Sending build context to Docker daemon 8.713 MB
Step 1 : FROM armhf/alpine:3.5
 ---> 3ddfeafc01f0
Step 2 : ENV CONSUL_PREFIX router_logs/config
 ---> Using cache
 ---> e2aae782f6d8
Step 3 : ENV CONSUL_SECRET_PREFIX router_logs/secrets
 ---> Using cache
 ---> 71c863da2558
Step 4 : ENV QEMU_EXECVE 1
 ---> Using cache
 ---> a7e80415d0d4
Step 5 : COPY deploy/qemu/qemu-arm-static /usr/bin/
 ---> Using cache
 ---> 265df9b6575f
Step 6 : RUN qemu-arm-static /sbin/apk fix
 ---> Using cache
 ---> def74ac67891
Step 7 : RUN qemu-arm-static /sbin/apk add -U bash
 ---> Running in 6f62d2ecd6b3
fetch http://dl-cdn.alpinelinux.org/alpine/v3.5/main/armhf/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.5/community/armhf/APKINDEX.tar.gz
(1/5) Installing ncurses-terminfo-base (6.0-r7)
(2/5) Installing ncurses-terminfo (6.0-r7)
(3/5) Installing ncurses-libs (6.0-r7)
(4/5) Installing readline (6.3.008-r4)
(5/5) Installing bash (4.3.46-r5)
Executing bash-4.3.46-r5.post-install
ERROR: bash-4.3.46-r5.post-install: script exited with error 1
Executing busybox-1.25.1-r0.trigger
ERROR: busybox-1.25.1-r0.trigger: script exited with error 1
1 errors; 7 MiB in 16 packages
The command 'qemu-arm-static /sbin/apk add -U bash' returned a non-zero code: 1

Project repo is here: https://github.com/skilbjo/router-logs


问:
Wildcards in counter specifiers in Azure Diagnostic
What I am trying to achieve is similar to what you can see in mongo-azure repo, specifically, I want to write Azure Diagnostic Configuration File in such a way so that I can get all the instances of performance counters, for example

\Processor(*)\% Processor Time

and it doesn't seem to be working - no data is visible in the table in my storage account.

Is it achievable at all with configuration, and if so, how?

UPD: We were able to get this working for a simple single VM (so it is possible!), but for some reason it still doesn't work for VMs in VMSS where Service Fabric Cluster is running

UPD #2: We did upgrade to VS 2015 tools 1.5 and now it magically works. I am not really sure if that was the root cause problem or we screwed up anywhere else.

答:
This is possible.  We do this in CloudMonix when monitoring VMSS and it is working.

How are you instrumenting Diagnostics and which tables are you looking at?

Specifying \LogicalDisk(*)\Available Megabytes yileds all drives and their free space, for example


问:
My perl comparison script is failing while running on huge txt files can any one help out on performance improvement
Right now the above script is able to compare around 9GB to 10GBfiles. But I wanted to compare with very big files like more than 50GB. While running my script it has been killed automatically. Can anyone help how to improve the performance to compare such big files with my script.

Here is my code.

```<code>use strict;
use warnings;
use Getopt::Std;
use FileHandle;

open STDOUT, ">", "output.txt" or die "$0: open: $!";
my %opts;
my $optstr = "i:o:";
getopts("$optstr", \%opts);
if($opts{i} eq '' || $opts{o} eq '' )
{
        print "usage: perl TextCompare_Fund.pl <-i INPUTFILE> <-o MAPREDUCE OUTPUTFILE>\n";
        die 1;
}
my $inputFilesPath=$opts{i};
my $outputFilesPath=$opts{o};
my @ifiles=`ls $inputFilesPath`;
my @ofiles=`ls $outputFilesPath`;
foreach my $ifile (@ifiles)
{
    my $ifile_substr=substr("$ifile",0,-25);
    foreach my $ofile (@ofiles)
    {
        my $ofile_substr=substr("$ofile",0,-25);
        my $result=$ifile_substr cmp $ofile_substr;
        if($result eq 0)
        {
            #print "$result\n";
            #print "$ifile\n";
            compare($ifile,$ofile)
        }
    }
}
sub compare
{
    my $afile="$_[0]";
    my $bfile="$_[1]";
    my $path1="$inputFilesPath/$afile";
    my $path2="$outputFilesPath/$bfile";
    chomp $path1;
    chomp $path2;
    #open FILE, "<", $path1 or die "$!:$path1";
    open my $infile, "<", $path1 or die "Couldn't open $path1: $!";
    my %a_lines;
    my %b_lines;
    my $count1=0;
    while (my $line = <$infile>)
    {
        chomp $line;
            $a_lines{$line} = undef;
        $count1=$count1+1;
    }
    print"$bfile records count : $count1\n";
    close $infile;
    my $file=substr("$afile",0,-25);
    my $OUTPUT = "/hadoop/user/m6034690/Kishore/CompareResult_Files/$file.comparision_result";
    open my $outfile, "<", $path2 or die "Couldn't open $path2: $!";
    open (OUTPUT, ">$OUTPUT") or die "Cannot open $OUTPUT \n";

    my $count=0;
    my $count2=0;
    while (my $line = <$outfile>)
    {
        chomp $line;
        $b_lines{$line} = undef;
        $count2=$count2+1;
        next if exists $a_lines{$line};
        $count=$count+1;
        print OUTPUT "$line \t===> The Line which is selected from file2/arg2 is mismatching/not available in file1\n";
    }
    print "$bfile records count : $count2\n";
    print "Total mismatching/unavailable records in file1 : $count\n";
    close $outfile;
    close OUTPUT;
}
close (STDOUT);
</code>```

答:
You're loading the entire file into memory. Obviously, that's a no-go.

So you out trying to to identify the lines in file2 that aren't in file1? That can be done with no memory if the files are sorted. So start by sorting the files. The unix sort utility can handle files of arbitrary size, so let's use that.

```<code>diff -u <( sort -u file1 ) <( sort -u file2 ) | tail -n +3 | grep ^+ | cut -c 2-
</code>```

or

```<code>sub compare {
   my ($qfn1, $qfn2) = @_;

   open(my $fh1, '-|', 'sort', '-u', '--', $qfn1) or die $!;
   open(my $fh2, '-|', 'sort', '-u', '--', $qfn2) or die $!;

   my $line1 = <$fh1>;
   my $line2 = <$fh2>;
   while ($line1 && $line2) {
      my $cmp = $line1 cmp $line2;
      print($line2) if $cmp > 0;
      $line1 = <$fh1> if $cmp <= 0;
      $line2 = <$fh2> if $cmp >= 0;
   }

   while ($line2) {
      print($line2);
      $line2 = <$fh2>;
   }
}
</code>```

Body:
Right now the above script is able to compare around 9GB to 10GBfiles. But I wanted to compare with very big files like more than 50GB. While running my script it has been killed automatically. Can anyone help how to improve the performance to compare such big files with my script.

Here is my code.

use strict;
use warnings;
use Getopt::Std;
use FileHandle;

open STDOUT, ">", "output.txt" or die "$0: open: $!";
my %opts;
my $optstr = "i:o:";
getopts("$optstr", \%opts);
if($opts{i} eq '' || $opts{o} eq '' )
{
        print "usage: perl TextCompare_Fund.pl <-i INPUTFILE> <-o MAPREDUCE OUTPUTFILE>\n";
        die 1;
}
my $inputFilesPath=$opts{i};
my $outputFilesPath=$opts{o};
my @ifiles=`ls $inputFilesPath`;
my @ofiles=`ls $outputFilesPath`;
foreach my $ifile (@ifiles)
{
    my $ifile_substr=substr("$ifile",0,-25);
    foreach my $ofile (@ofiles)
    {
        my $ofile_substr=substr("$ofile",0,-25);
        my $result=$ifile_substr cmp $ofile_substr;
        if($result eq 0)
        {
            #print "$result\n";
            #print "$ifile\n";
            compare($ifile,$ofile)
        }
    }
}
sub compare
{
    my $afile="$_[0]";
    my $bfile="$_[1]";
    my $path1="$inputFilesPath/$afile";
    my $path2="$outputFilesPath/$bfile";
    chomp $path1;
    chomp $path2;
    #open FILE, "<", $path1 or die "$!:$path1";
    open my $infile, "<", $path1 or die "Couldn't open $path1: $!";
    my %a_lines;
    my %b_lines;
    my $count1=0;
    while (my $line = <$infile>)
    {
        chomp $line;
            $a_lines{$line} = undef;
        $count1=$count1+1;
    }
    print"$bfile records count : $count1\n";
    close $infile;
    my $file=substr("$afile",0,-25);
    my $OUTPUT = "/hadoop/user/m6034690/Kishore/CompareResult_Files/$file.comparision_result";
    open my $outfile, "<", $path2 or die "Couldn't open $path2: $!";
    open (OUTPUT, ">$OUTPUT") or die "Cannot open $OUTPUT \n";

    my $count=0;
    my $count2=0;
    while (my $line = <$outfile>)
    {
        chomp $line;
        $b_lines{$line} = undef;
        $count2=$count2+1;
        next if exists $a_lines{$line};
        $count=$count+1;
        print OUTPUT "$line \t===> The Line which is selected from file2/arg2 is mismatching/not available in file1\n";
    }
    print "$bfile records count : $count2\n";
    print "Total mismatching/unavailable records in file1 : $count\n";
    close $outfile;
    close OUTPUT;
}
close (STDOUT);

Body:
You're loading the entire file into memory. Obviously, that's a no-go.

So you out trying to to identify the lines in file2 that aren't in file1? That can be done with no memory if the files are sorted. So start by sorting the files. The unix sort utility can handle files of arbitrary size, so let's use that.

diff -u <( sort -u file1 ) <( sort -u file2 ) | tail -n +3 | grep ^+ | cut -c 2-

or

sub compare {
   my ($qfn1, $qfn2) = @_;

   open(my $fh1, '-|', 'sort', '-u', '--', $qfn1) or die $!;
   open(my $fh2, '-|', 'sort', '-u', '--', $qfn2) or die $!;

   my $line1 = <$fh1>;
   my $line2 = <$fh2>;
   while ($line1 && $line2) {
      my $cmp = $line1 cmp $line2;
      print($line2) if $cmp > 0;
      $line1 = <$fh1> if $cmp <= 0;
      $line2 = <$fh2> if $cmp >= 0;
   }

   while ($line2) {
      print($line2);
      $line2 = <$fh2>;
   }
}


问:
How to insert the corresponding image to color swatch using Javascript?
I am trying to insert the corresponding background image for my color swatch in Shopify.
   Right now, I have my icons ready with the proper link to each color, but the icons dont have their corresponding image, like this.
   I am trying to insert the images that I have in my assets file, each image is already named in the same way as the color variation. How do I assign each image to their corresponding icon through Javascript? I know I can do it in Liquid, but it does not work for me as all the html are generated by Javascript.
Here is my html

```<code><ul class="new-variant-swatchs">
  <li class="new-variant-swatch js-new-variant-swatch is-active" data-val="Army Green" data-select="js-option-selector-0"></li>
  <li class="new-variant-swatch js-new-variant-swatch" data-val="Burgundy" data-select="js-option-selector-0"></li>
  <li class="new-variant-swatch js-new-variant-swatch" data-val="Camel Beige" data-select="js-option-selector-0"></li><li class="new-variant-swatch js-new-variant-swatch" data-val="Candy Red" data-select="js-option-selector-0"></li>
  <li class="new-variant-swatch js-new-variant-swatch" data-val="Caramel Brown" data-select="js-option-selector-0"></li><li class="new-variant-swatch js-new-variant-swatch" data-val="Charcoal Grey" data-select="js-option-selector-0"></li>
  <li class="new-variant-swatch js-new-variant-swatch" data-val="Heather Grey" data-select="js-option-selector-0"></li><li class="new-variant-swatch js-new-variant-swatch" data-val="Ivory White" data-select="js-option-selector-0"></li>
  <li class="new-variant-swatch js-new-variant-swatch" data-val="Muted Black" data-select="js-option-selector-0"></li><li class="new-variant-swatch js-new-variant-swatch" data-val="Navy Blue" data-select="js-option-selector-0"></li>
  <li class="new-variant-swatch js-new-variant-swatch" data-val="Rose Pink" data-select="js-option-selector-0"></li>

</ul>
</code>```

I am a total noobie to Javascript, this is what I am trying to write, I know it is wrong, I am just trying to give an idea, thanks!

```<code>$(function() {
    if($(".new-variant-swatchs").length) {

        $(".new-variant-swatchs").each(function(i) {
            var $thisSelect = $(this);
            var $currentOption = $thisSelect.val();

            $thisSelect.find("li").each(function() {
                var $this = $(this);
                var $liText = $this.text();
                var $liVal = $this.val();

                $this.style.backgroundImage = "url({{ $liVal | handle | append: '.' | append: png | asset_url }}"

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

Thank you in advance!

答:
You might need to rename your images to match the data-val attribute value. For instance as of now Camel-Beige.png might need to be renamed to Camel Beige.png.

Next u will need to change your javascript code accordingly as below :

```<code>$(function() {
    if($(".new-variant-swatchs").length) {
        $(".new-variant-swatchs").each(function(i) {
            var $thisSelect = $(this);
            var $currentOption = $thisSelect.data('val');
            $thisSelect.find("li").each(function() {
                var $this = $(this);
                var $liText = $this.text();
                var $liVal = $this.data('val');
                $this.css('background', 'url(/assets/'+$liVal+'.png) no-repeat');
            });
        });
    }
});
</code>```

You may have to put proper asset relative path though.

Body:
I am trying to insert the corresponding background image for my color swatch in Shopify.
   Right now, I have my icons ready with the proper link to each color, but the icons dont have their corresponding image, like this.
   I am trying to insert the images that I have in my assets file, each image is already named in the same way as the color variation. How do I assign each image to their corresponding icon through Javascript? I know I can do it in Liquid, but it does not work for me as all the html are generated by Javascript.
Here is my html

I am a total noobie to Javascript, this is what I am trying to write, I know it is wrong, I am just trying to give an idea, thanks!

$(function() {
    if($(".new-variant-swatchs").length) {

        $(".new-variant-swatchs").each(function(i) {
            var $thisSelect = $(this);
            var $currentOption = $thisSelect.val();

            $thisSelect.find("li").each(function() {
                var $this = $(this);
                var $liText = $this.text();
                var $liVal = $this.val();

                $this.style.backgroundImage = "url({{ $liVal | handle | append: '.' | append: png | asset_url }}"

            }
        });
    }
});

Thank you in advance!

Body:
You might need to rename your images to match the data-val attribute value. For instance as of now Camel-Beige.png might need to be renamed to Camel Beige.png.

Next u will need to change your javascript code accordingly as below :

$(function() {
    if($(".new-variant-swatchs").length) {
        $(".new-variant-swatchs").each(function(i) {
            var $thisSelect = $(this);
            var $currentOption = $thisSelect.data('val');
            $thisSelect.find("li").each(function() {
                var $this = $(this);
                var $liText = $this.text();
                var $liVal = $this.data('val');
                $this.css('background', 'url(/assets/'+$liVal+'.png) no-repeat');
            });
        });
    }
});

You may have to put proper asset relative path though.


问:
Parent Div to Keep the Height of Tallest Child
I've been Googling potential solutions but as yet cannot find one that fits the brief.

```<code><div class="parent">
    <div class="child1">I'm 60px tall and visible; my parent is 100px tall</div>
    <div class="child2">I'm 80px tall and hidden until needed</div>
    <div class="child3">I'm 100px tall and hidden until needed</div>
</div>
</code>```

I need to have a number of child Divs with a parent Div.

Only one child will show at any time.

The parent Div must always remain the same height as the tallest child and never expand or
contract.

I'll use jQuery to change the css of the visible child but I'd prefer a CSS solution to the height if possible.

No IE8/9/10 to support.

Anyone got ideas?

答:
Hope this is what you want:

Use flex display to arrange the child as column display.

Set their opacity as 0 so that the child element still remain in the parent div, this will set the parent height the same as the tallest child.

Created a new class visible to style the visible child, and set default children (which are hidden) width: 0px while visible child will have width: 100%

function show(element) {
  $('.parent div').removeClass('visible');
  $('.' + element).addClass('visible');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
  border: 1px dashed #000;
  display: flex;
}

.child1 {
  height: 60px;
  background: red;
}

.child2 {
  height: 80px;
  background: yellow;
}

.child3 {
  height: 100px;
  background: orange;
}

.parent div {
  opacity: 0;
  width: 0px;
}

.parent div.visible {
  opacity: 1;
  width: 100%;
}</code>```

I'm 60px tall and visible; my parent is 100px tall

I'm 80px tall and hidden until needed

I'm 100px tall and hidden until needed

<button onclick="show('child1')">Child 1</button>
<button onclick="show('child2')">Child 2</button>
<button onclick="show('child3')">Child 3</button>```

Body:
I've been Googling potential solutions but as yet cannot find one that fits the brief.

I'm 60px tall and visible; my parent is 100px tall

I'm 80px tall and hidden until needed

I'm 100px tall and hidden until needed

I need to have a number of child Divs with a parent Div.

Only one child will show at any time.

The parent Div must always remain the same height as the tallest child and never expand or
contract.

I'll use jQuery to change the css of the visible child but I'd prefer a CSS solution to the height if possible.

No IE8/9/10 to support.

Anyone got ideas?

Body:
Hope this is what you want:

Use flex display to arrange the child as column display.

Set their opacity as 0 so that the child element still remain in the parent div, this will set the parent height the same as the tallest child.

Created a new class visible to style the visible child, and set default children (which are hidden) width: 0px while visible child will have width: 100%

function show(element) {
  $('.parent div').removeClass('visible');
  $('.' + element).addClass('visible');
}

.parent {
  border: 1px dashed #000;
  display: flex;
}

.child1 {
  height: 60px;
  background: red;
}

.child2 {
  height: 80px;
  background: yellow;
}

.child3 {
  height: 100px;
  background: orange;
}

.parent div {
  opacity: 0;
  width: 0px;
}

.parent div.visible {
  opacity: 1;
  width: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div class="child1 visible">I'm 60px tall and visible; my parent is 100px tall</div>
  <div class="child2">I'm 80px tall and hidden until needed</div>
  <div class="child3">I'm 100px tall and hidden until needed</div>
</div>

<br/>
<button onclick="show('child1')">Child 1</button>
<button onclick="show('child2')">Child 2</button>
<button onclick="show('child3')">Child 3</button>