答:
You can just subtract the two and compare the difference to 20.</p>

```<code>// if var2 is 20 or more greater than var1
if (var2 - var1 >= 20) {
     // do something here
} else {
     // something else here
}
</code>```

Title: How to execute code if the difference in the value of a variable is over 20

Body:
I'm trying to see if var1 is not equal to var2, but has top be greater than it by 20 or more to execute the code.

I currently have:

if (var1 != var2) {
    // need to put what happens if var2 is 20 or more greater than var1
}
else {

}

Body:
You can just subtract the two and compare the difference to 20.

// if var2 is 20 or more greater than var1
if (var2 - var1 >= 20) {
     // do something here
} else {
     // something else here
}


来源: stackexchange

问:
How to use split_part of postgresql inside laravel?
I want to use split_part inside laravel. My code is like,

```<code>$results = DB::table('zaiko')
               ->where('soukobango',$souko_bango_for_joining)
               ->join('syouhin1','zaiko.syouhinbango','=','syouhin1.bango')
               ->where('syouhin1.isphoto','is distinct from','1')
               ->select('syouhin1.bango',
                    'syouhin1.kokyakusyouhinbango',
                    'syouhin1.jouhou',
                    'syouhin1.tokuchou',
                    "SPLIT_PART('zaiko.datachar02', '|', 1) as test1")
              ->get();
</code>```

However, it is giving me the following error.

Undefined table: 7 ERROR: missing FROM-clause entry for table
  "SPLIT_PART('zaiko" LINE 1: ...ngo", "syouhin1"."jouhou",
  "syouhin1"."tokuchou", "SPLIT_PAR... ^ (SQL: select
  "syouhin1"."bango", "syouhin1"."kokyakusyouhinbango",
  "syouhin1"."jouhou", "syouhin1"."tokuchou",
  "SPLIT_PART('zaiko"."datachar02', '|', 1)" as "test1" from "zaiko"
  inner join "syouhin1" on "zaiko"."syouhinbango" = "syouhin1"."bango"
  where "soukobango" = 1 and "syouhin1"."isphoto" is distinct from 1)

But if I remove the line with SPLIT_PART then it works as expected.

答:
Try using a raw select:</p>

```<code>->select(DB::raw("syouhin1.bango,
                  syouhin1.kokyakusyouhinbango,
                  syouhin1.jouhou,
                  syouhin1.tokuchou,
                  SPLIT_PART(zaiko.datachar02, '|', 1) AS test1"))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to use split_part inside laravel. My code is like,

$results = DB::table('zaiko')
               ->where('soukobango',$souko_bango_for_joining)
               ->join('syouhin1','zaiko.syouhinbango','=','syouhin1.bango')
               ->where('syouhin1.isphoto','is distinct from','1')
               ->select('syouhin1.bango',
                    'syouhin1.kokyakusyouhinbango',
                    'syouhin1.jouhou',
                    'syouhin1.tokuchou',
                    "SPLIT_PART('zaiko.datachar02', '|', 1) as test1")
              ->get();

However, it is giving me the following error.

Undefined table: 7 ERROR: missing FROM-clause entry for table
  "SPLIT_PART('zaiko" LINE 1: ...ngo", "syouhin1"."jouhou",
  "syouhin1"."tokuchou", "SPLIT_PAR... ^ (SQL: select
  "syouhin1"."bango", "syouhin1"."kokyakusyouhinbango",
  "syouhin1"."jouhou", "syouhin1"."tokuchou",
  "SPLIT_PART('zaiko"."datachar02', '|', 1)" as "test1" from "zaiko"
  inner join "syouhin1" on "zaiko"."syouhinbango" = "syouhin1"."bango"
  where "soukobango" = 1 and "syouhin1"."isphoto" is distinct from 1)

But if I remove the line with SPLIT_PART then it works as expected.

Body:
Try using a raw select:

->select(DB::raw("syouhin1.bango,
                  syouhin1.kokyakusyouhinbango,
                  syouhin1.jouhou,
                  syouhin1.tokuchou,
                  SPLIT_PART(zaiko.datachar02, '|', 1) AS test1"))


问:
UWP System.Reflection.TargetInvocationException when including a view in a page?
I have 2 pages. One page contains another, where the Grid looks like the following:

```<code>        <Grid>
            <views:MapViewPage/>
        </Grid>
</code>```

I've included the views namespace correctly and everything runs fine but the designer seems to be having a bit of an issue with this.

It underlines the views:MapViewPage line and says object reference not set to an instance of an object, and complains about the constructor. I don't understand why, I've done this in WPF where I've included views in another page or window so I don't understand why the XAML designer complains in UWP. I've restarted visual studio and deleted the bin and obj directories but i still see the error - builds fine and runs fine tho... and includes the view as expected...

答: You are on the right path but sometimes designer picks up wrong metadata. Please delete your obj and bin directories and rebuild your project. It should work</p>

Body:
I have 2 pages. One page contains another, where the Grid looks like the following:

        <Grid>
            <views:MapViewPage/>
        </Grid>

I've included the views namespace correctly and everything runs fine but the designer seems to be having a bit of an issue with this.

It underlines the views:MapViewPage line and says object reference not set to an instance of an object, and complains about the constructor. I don't understand why, I've done this in WPF where I've included views in another page or window so I don't understand why the XAML designer complains in UWP. I've restarted visual studio and deleted the bin and obj directories but i still see the error - builds fine and runs fine tho... and includes the view as expected...


问:
Many-to-many relationship between Django User, Permissions, and another entity
Consider a Django web app for CompanyXYZ that provides goods and services to many organizations.  Users of the app will be affiliated with one or more of those organizations, and have different roles (and be permitted access to different data) within each.  So, imagine a schema like this:

```<code>Users>---UserOrg----<Org
             V
             |
          UserOrgPermissions
             |
             ^
           Permissions

</code>```

Permissions relate to services provided by the company, and in general look like:  “Can order X”, “Can view X orders”, “Can order Y”, “Can view Y orders”, “Can order Z”...etc.  Users should be able to log on to CompanyXYZ’s site once, and then choose from among his/her affiliated organizations to view summary data and/or place orders, depending on his/her permissions at a given organization.

From an admin perspective, I need to be able to create organizations, create users, assign users to organizations, and assign permissions to users for each of his/her organizations.

I’m fairly new to Django, so I'm not sure if this is even doable. How would I start?

答:
That would be something like this:

class Permission(models.Model):
    pass

class Org(models.Model):
    pass

class UserOrg(models.Model):
    org = models.Foreignkey('Org')
    user = models.Foreignkey('User')
    permissions = models.ManyToManyField(Permission)

class User(models.Model):
    orgs = models.ManyToManyField(Org, through=UserOrg)
```

I suggest you to either read the docs or start with their tutorial for beginners.

Body:
Consider a Django web app for CompanyXYZ that provides goods and services to many organizations.  Users of the app will be affiliated with one or more of those organizations, and have different roles (and be permitted access to different data) within each.  So, imagine a schema like this:

Users>---UserOrg----<Org
             V
             |
          UserOrgPermissions
             |
             ^
           Permissions

Permissions relate to services provided by the company, and in general look like:  “Can order X”, “Can view X orders”, “Can order Y”, “Can view Y orders”, “Can order Z”...etc.  Users should be able to log on to CompanyXYZ’s site once, and then choose from among his/her affiliated organizations to view summary data and/or place orders, depending on his/her permissions at a given organization.

From an admin perspective, I need to be able to create organizations, create users, assign users to organizations, and assign permissions to users for each of his/her organizations.

I’m fairly new to Django, so I'm not sure if this is even doable. How would I start?

Body:
That would be something like this:

class Permission(models.Model):
    pass

class Org(models.Model):
    pass

class UserOrg(models.Model):
    org = models.Foreignkey('Org')
    user = models.Foreignkey('User')
    permissions = models.ManyToManyField(Permission)

class User(models.Model):
    orgs = models.ManyToManyField(Org, through=UserOrg)

I suggest you to either read the docs or start with their tutorial for beginners.


问:
Help with silverlight
I have some methods which are not compiled with Silverlight framework but are very essential for execution of SL workflow(by workflow, I mean to process my application completely). What is the best/quickest way to do so?
I was thinking of publishing a web-service(for non-sl compiled methods) and make SL call into my WS.. but I am unable to see/create webservice instance even after registering one in my SL project. (I am using VS 2010)
any help?</p>

答:
Esentially, you have three ways to run code.

native built-in methods in your application--this would be the easiest way

methods that live in an external silverlight assembly, like a class library

use a webservice

if you use a webservice, you have to either host the website yourself or use a 3rd party website, then add a reference to said service. if the service is not hosted on the same website as your silverlight app, there must be a cross-domain policy file in place otherwise silverlight will not use the service.

if you use an external assembly, it MUST be a silverlight assembly. you can not use a windows class library, etc.

ContentLicense: CC BY-SA 3.0

Title: Help with silverlight


问:
Visual studio 2019: Enabling "Use Managed Compatibility Mode" leads to `Access Denied` in remote debugging
I started to use remote debugging for checking my web-service behavior which developed in ASP.NET (not MVC not .net core) but during debug process value of variables what not shown and watch was not working.

Many answers such as [1],[2] suggested to enable Use Managed Compatibility Mode. I did this but after this change I cannot connect to remote process anymore due to error: Unable to attach to the process. Access is denied.
I should disable Use Managed Compatibility Mode to be able to attach to remote process again.

I don't know how to fix this although there are many suggestions such as Running as administrator and etc but they did not work.
Details:
MY IDE: VS 2019 Version 16.2.0 in windows 10x64
IIS Server runs on Windows 7x64
Both VS2019 and Remote Debugger ran as administrator.

答:
Do you choose “DefaultAppPool” while adding Web Site to IIS or others like “ASP .NET 4.0”? I notice that the type of w3wp.exe is “x86”, not sure if this matters, as I test on my side and it is x64(since MS stops support for Windows7, I use two machines with Windows 10 x64 and test on my side but the remote debugging works well).

Also, please make sure when you publish, you have set the configuration to “Debug”(not “release”). And note “debugging between two computers connected through a proxy is not supported.”, not sure if you missed something/steps, you could check this document: Remote Debug ASP.NET on a Remote IIS Computer to confirm it.

In addition, please check the “Permissions for Remote Debugging”(VS 2019 Remote Debugger(Administrator)=>Tools=>Permissions..) and make sure the administrator/user has been added to “Group or user names” and check the “Allow” checkbox under “Permissions for Administrators” for “Debug”.

Hope this could help you a little.


Title: Construct restriction matrix such that the odd rows are zero

Body:
I have two arrays: A is of shape (m,n) and B is of shape (2*m,n). Furthermore, the even rows of B are the rows of A. Let a = numpy.reshape(A,(A.size,1)) and b = numpy.reshape(B,(B.size,1)). My aim is to construct a diagonal matrix R such that R*b = a. The arrays look like this:

[[13865.995  14020.785  14020.788 ]
 [ 6885.634   6784.8813  6837.428 ]
 [14510.425  14712.554  14657.217 ]
 [ 7688.0923  7817.8457  7792.413 ]
 [10473.903  10417.55   10469.508 ]
 [10485.661  10348.152  10632.414 ]]
[[14662.705  14869.951  15166.294 ]
 [13865.995  14020.785  14020.788 ]
 [ 9780.559  10038.395  10202.31  ]
 [ 6885.634   6784.8813  6837.428 ]
 [ 7167.9575  7357.9062  7287.3003]
 [14510.425  14712.554  14657.217 ]
 [12825.017  12680.751  12823.563 ]
 [ 7688.0923  7817.8457  7792.413 ]
 [ 6861.9443  6826.6245  6758.8965]
 [10473.903  10417.55   10469.508 ]
 [ 8498.976   8637.245   8718.052 ]
 [10485.661  10348.152  10632.414 ]]

I am sure that I can construct an array x with values 0 and 1 at the correct indices and then set R = np.diag(x) but I'm not sure how can I make this work and if this is the best solution. Any help is appreciated

Body:
It takes a bit of creative array indexing, but hopefully this is what you're after. Note: R isn't actually a diagonal matrix in this case.

import numpy

A = numpy.array([[13865.995,  14020.785,  14020.788 ],
    [ 6885.634,   6784.8813,  6837.428 ],
    [14510.425,  14712.554,  14657.217 ],
    [ 7688.0923,  7817.8457,  7792.413 ],
    [10473.903,  10417.55,   10469.508 ],
    [10485.661,  10348.152,  10632.414 ]])
B = numpy.array([[14662.705,  14869.951,  15166.294 ],
    [13865.995,  14020.785,  14020.788 ],
    [ 9780.559,  10038.395,  10202.31  ],
    [ 6885.634,   6784.8813,  6837.428 ],
    [ 7167.9575,  7357.9062,  7287.3003],
    [14510.425,  14712.554,  14657.217 ],
    [12825.017,  12680.751,  12823.563 ],
    [ 7688.0923,  7817.8457,  7792.413 ],
    [ 6861.9443,  6826.6245,  6758.8965],
    [10473.903,  10417.55,   10469.508 ],
    [ 8498.976,   8637.245,   8718.052 ],
    [10485.661,  10348.152,  10632.414 ]])
a = numpy.reshape(A,(A.size,1))
b = numpy.reshape(B,(B.size,1))
R = numpy.zeros((A.size,B.size))
R[[a for a in range(A.size)],[a for a in range(B.size) if (a // 3) % 2]] = 1
print( numpy.all(numpy.dot(R, b) == a) )
# True


问:
Using array for `ls --ignore`
I'm working on a bash script for my server backup.
Based on my web root(/home), I wanna filter my web directories excludes something generals.
I found --ignore option for it. Here's my code for returng what I want.

```<code>DIR_LIST=`ls -al $WWW_ROOT --ignore={.,..,ubuntu,test} | grep "^d" | awk '{ print $9 }'`
echo $DIR_LIST;
</code>```

But when I tried with array, it's not worked as well.

```<code>EXCLUDED=(. .. test ubuntu)
STR=$(IFS=,; echo "${EXCLUDED[*]}")
DIR_LIST=`ls -al $WWW_ROOT --ignore={$STR} | grep "^d" | awk '{ print $9 }'`
echo $DIR_LIST;
</code>```

echo $STR works well but echo $DIR_LIST is not.
I think brace is not worked properly.

How can I do this as I expected?

答:
Your idea is mostly right, but it has a few issues. Firstly the ls command uses the shell globbing style to expand your --ignore pattern. It works fine when you specified it explicitly.

But when you define it in a variable to expand the glob, the shell doesn't like it. Because when the shell expands the command line, it does the glob expansion first before expanding the variable. Since you have the glob within the variable, by the time it expands the variable, it has crossed a point where it can expand the glob, so your --ignore pattern is never really formed with the way you expect it to be.

Also, the way you are populating the array, its not recommended to take that approach, because it is fragile ( Why you shouldn't parse the output of ls(1) ), when it comes to dealing with names involving spaces/newline or any other shell metacharacters.

See How to exclude a directory in find . command to exclude directories when searching over a file system.

Title: Using array for `ls --ignore`

Body:
I'm working on a bash script for my server backup.
Based on my web root(/home), I wanna filter my web directories excludes something generals.
I found --ignore option for it. Here's my code for returng what I want.

DIR_LIST=`ls -al $WWW_ROOT --ignore={.,..,ubuntu,test} | grep "^d" | awk '{ print $9 }'`
echo $DIR_LIST;

But when I tried with array, it's not worked as well.

EXCLUDED=(. .. test ubuntu)
STR=$(IFS=,; echo "${EXCLUDED[*]}")
DIR_LIST=`ls -al $WWW_ROOT --ignore={$STR} | grep "^d" | awk '{ print $9 }'`
echo $DIR_LIST;

echo $STR works well but echo $DIR_LIST is not.
I think brace is not worked properly.

How can I do this as I expected?


问:
Perl, @array in perl constructor
I write perl classes, but I don't know how to have a array or a hash in my $this variable ?

I have a pack.pm :

```<code>#!/usr/bin/perl -w
use strict;
use Parallel::ForkManager;
package Pack;

our $cgi = new CGI;

sub new {
    my ($classe, $nom, $nbports, $gio) = @_;

    my $this = {
    "nom"    => $nom,
    "nbports" => $nbports,
    "gio"   => $gio
    };

    bless($this, $classe);
    return $this;
}
    ...
1;
</code>```

I would like to have a @tab, I can access via $this->tab, but I don't want to give it in arg to the instance.

How does it work in Perl ?

Thanks.

答:
Consider using Moose for your OO Perl needs.

I've created a Moose version of your object that includes an attribute with an attribute featuring Array trait delegation, inlcuding currying of delegated methods.  Moose offers easy ways to generate powerful, encapsulated classes without writing reams of boilerplate.

I created a class Pack with attributes: nom, nbports, gio, and tab.

nom is a read-only string and is required when the object is created.
nbports is a read-only integer value and defaults to 32 when not provided.
gio is an optional, read-write boolean value.
tab is an array of strings.  All sorts of behavior has been defined for tab:

all_tabs   returns a list of the contents of tabs

add_tab    pushes values onto the end of tabs

tab_count  returns a count of the elements in tabs

alpha_tabs returns a list of the members of tabs alphabetical order

turn_tabs  returns a list of the strings in tabs, but with the letters in reverse

Any attempts to set an attribute with be checked for type correctness.

Moose creates all the required methods to support these complex behaviors with the following code:

```<code>package Pack;
use Moose;

has 'nom' => (
   is => 'ro',
   isa => 'Str',
   required => 1,
);

has 'nbports' => (
   is      => 'ro',
   isa     => 'Int',
   default => 32,
);

has 'gio' => (
   is  => 'rw',
   isa => 'Bool',
   predicate => 'has_gio',
);

has 'tab' => (
   traits  => ['Array'],
   is      => 'ro',
   isa     => 'ArrayRef[Str]',
   default => sub {[]},
   handles => {
      all_tabs    => 'elements',
      add_tab     => 'push',
      turn_tabs   => [ 'map', sub { reverse } ],
      tab_count   => 'count',
      alpha_tabs  => [ 'sort', sub { lc($a) cmp lc($b) } ],
  },
);

__PACKAGE__->meta->make_immutable;
no Moose;
1;
</code>```

Usable like so:

```<code> my $p = Pack->new( nom => 'Roger', tab => [qw( fee fie foe fum )] );

 my $gio_state = 'UNSET';
 if( $p->has_gio ) {
      $gio_state = $p->gio ? 'TRUE' : 'FALSE';
 }

 print  "GIO is $gio_state\n";

 my @turned = $p->turn_tabs; # eef eif eof muf
 $p->add_tabs( 'faa', 'fim' );
 my @sorted = $p->alpha_tabls; # faa fee fie fim foe fum

 my $count = $p->tab_count;  # 6

 my $ports = $p->nbports; # 32
</code>```

Title: Perl, @array in perl constructor

Body:
I write perl classes, but I don't know how to have a array or a hash in my $this variable ?

I have a pack.pm :

#!/usr/bin/perl -w
use strict;
use Parallel::ForkManager;
package Pack;

our $cgi = new CGI;

sub new {
    my ($classe, $nom, $nbports, $gio) = @_;

    my $this = {
    "nom"    => $nom,
    "nbports" => $nbports,
    "gio"   => $gio
    };

    bless($this, $classe);
    return $this;
}
    ...
1;

I would like to have a @tab, I can access via $this->tab, but I don't want to give it in arg to the instance.

How does it work in Perl ?

Thanks.

Body:
Consider using Moose for your OO Perl needs.

I've created a Moose version of your object that includes an attribute with an attribute featuring Array trait delegation, inlcuding currying of delegated methods.  Moose offers easy ways to generate powerful, encapsulated classes without writing reams of boilerplate.

I created a class Pack with attributes: nom, nbports, gio, and tab.

nom is a read-only string and is required when the object is created.
nbports is a read-only integer value and defaults to 32 when not provided.
gio is an optional, read-write boolean value.
tab is an array of strings.  All sorts of behavior has been defined for tab:

all_tabs   returns a list of the contents of tabs

add_tab    pushes values onto the end of tabs

tab_count  returns a count of the elements in tabs

alpha_tabs returns a list of the members of tabs alphabetical order

turn_tabs  returns a list of the strings in tabs, but with the letters in reverse

Any attempts to set an attribute with be checked for type correctness.

Moose creates all the required methods to support these complex behaviors with the following code:

package Pack;
use Moose;

has 'nom' => (
   is => 'ro',
   isa => 'Str',
   required => 1,
);

has 'nbports' => (
   is      => 'ro',
   isa     => 'Int',
   default => 32,
);

has 'gio' => (
   is  => 'rw',
   isa => 'Bool',
   predicate => 'has_gio',
);

has 'tab' => (
   traits  => ['Array'],
   is      => 'ro',
   isa     => 'ArrayRef[Str]',
   default => sub {[]},
   handles => {
      all_tabs    => 'elements',
      add_tab     => 'push',
      turn_tabs   => [ 'map', sub { reverse } ],
      tab_count   => 'count',
      alpha_tabs  => [ 'sort', sub { lc($a) cmp lc($b) } ],
  },
);

__PACKAGE__->meta->make_immutable;
no Moose;
1;

Usable like so:

 my $p = Pack->new( nom => 'Roger', tab => [qw( fee fie foe fum )] );

 my $gio_state = 'UNSET';
 if( $p->has_gio ) {
      $gio_state = $p->gio ? 'TRUE' : 'FALSE';
 }

 print  "GIO is $gio_state\n";

 my @turned = $p->turn_tabs; # eef eif eof muf
 $p->add_tabs( 'faa', 'fim' );
 my @sorted = $p->alpha_tabls; # faa fee fie fim foe fum

 my $count = $p->tab_count;  # 6

 my $ports = $p->nbports; # 32


问:
Kibana server is not ready yet
I have just installed Kibana 7.3 on RHEL 8. The Kibana service is active (running).

I receive Kibana server is not ready yet message when i curl to http://localhost:5601.
My Elasticsearch instance is on another server and it is responding with succes to my requests. I have updated the kibana.yml with that

elasticsearch.hosts:["http://EXTERNAL-IP-ADDRESS-OF-ES:9200"]

i can reach to elasticsearch from the internet with response:

```<code>{
  "name" : "ip-172-31-21-240.ec2.internal",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "y4UjlddiQimGRh29TVZoeA",
  "version" : {
    "number" : "7.3.1",
    "build_flavor" : "default",
    "build_type" : "rpm",
    "build_hash" : "4749ba6",
    "build_date" : "2019-08-19T20:19:25.651794Z",
    "build_snapshot" : false,
    "lucene_version" : "8.1.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}
</code>```

The result of the sudo systemctl status kibana:

```<code>● kibana.service - Kibana
   Loaded: loaded (/etc/systemd/system/kibana.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2019-09-19 12:22:34 UTC; 24min ago
 Main PID: 4912 (node)
    Tasks: 21 (limit: 4998)
   Memory: 368.8M
   CGroup: /system.slice/kibana.service
           └─4912 /usr/share/kibana/bin/../node/bin/node --no-warnings --max-http-header-size>

Sep 19 12:46:42 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0>
Sep 19 12:46:42 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0>
Sep 19 12:46:43 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0>
Sep 19 12:46:43 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0>
Sep 19 12:46:43 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0>
Sep 19 12:46:44 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0
</code>```

the result of "sudo journalctl --unit kibana"

```<code>Sep 19 06:03:53 ip-172-31-88-39.ec2.internal kibana[1356]: {"type":"log","@timestamp":"2019-09-19T06:03:53Z","tags":["warning","elasticsearch","admin"],"pid":1356,"message":"Unable to revive >
Sep 19 06:03:53 ip-172-31-88-39.ec2.internal kibana[1356]: {"type":"log","@timestamp":"2019-09-19T06:03:53Z","tags":["warning","elasticsearch","admin"],"pid":1356,"message":"No living connect>
Sep 19 06:03:53 ip-172-31-88-39.ec2.internal kibana[1356]: {"type":"log","@timestamp":"2019-09-19T06:03:53Z","tags":["warning","task_manager"],"pid":1356,"message":"PollError No Living connec>
Sep 19 06:03:53 ip-172-31-88-39.ec2.internal kibana[1356]: {"type":"log","@timestamp":"2019-09-19T06:03:53Z","tags":["warning","elasticsearch","admin"],"pid":1356,"message":"Unable to revive >
Sep 19 06:03:53 ip-172-31-88-39.ec2.internal kibana[1356]: {"type":"log","@timestamp":"2019-09-19T06:03:53Z","tags":["warning","elasticsearch","admin"],"pid":1356,"message":"No living connect>
</code>```

Do you have any idea where the problem is?

答:
Probably not the solution for this question

In my case the version from kibana and elasticsearch were not compatible

How i was using docker, i just recreated both but using the same version (7.5.1)

https://www.elastic.co/support/matrix#matrix_compatibility

Title: Kibana server is not ready yet

Body:
I have just installed Kibana 7.3 on RHEL 8. The Kibana service is active (running).

I receive Kibana server is not ready yet message when i curl to http://localhost:5601.
My Elasticsearch instance is on another server and it is responding with succes to my requests. I have updated the kibana.yml with that

elasticsearch.hosts:["http://EXTERNAL-IP-ADDRESS-OF-ES:9200"]

i can reach to elasticsearch from the internet with response:

{
  "name" : "ip-172-31-21-240.ec2.internal",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "y4UjlddiQimGRh29TVZoeA",
  "version" : {
    "number" : "7.3.1",
    "build_flavor" : "default",
    "build_type" : "rpm",
    "build_hash" : "4749ba6",
    "build_date" : "2019-08-19T20:19:25.651794Z",
    "build_snapshot" : false,
    "lucene_version" : "8.1.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

The result of the sudo systemctl status kibana:

● kibana.service - Kibana
   Loaded: loaded (/etc/systemd/system/kibana.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2019-09-19 12:22:34 UTC; 24min ago
 Main PID: 4912 (node)
    Tasks: 21 (limit: 4998)
   Memory: 368.8M
   CGroup: /system.slice/kibana.service
           └─4912 /usr/share/kibana/bin/../node/bin/node --no-warnings --max-http-header-size>

Sep 19 12:46:42 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0>
Sep 19 12:46:42 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0>
Sep 19 12:46:43 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0>
Sep 19 12:46:43 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0>
Sep 19 12:46:43 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0>
Sep 19 12:46:44 ip-172-31-88-39.ec2.internal kibana[4912]: {"type":"log","@timestamp":"2019-0

the result of "sudo journalctl --unit kibana"

Sep 19 06:03:53 ip-172-31-88-39.ec2.internal kibana[1356]: {"type":"log","@timestamp":"2019-09-19T06:03:53Z","tags":["warning","elasticsearch","admin"],"pid":1356,"message":"Unable to revive >
Sep 19 06:03:53 ip-172-31-88-39.ec2.internal kibana[1356]: {"type":"log","@timestamp":"2019-09-19T06:03:53Z","tags":["warning","elasticsearch","admin"],"pid":1356,"message":"No living connect>
Sep 19 06:03:53 ip-172-31-88-39.ec2.internal kibana[1356]: {"type":"log","@timestamp":"2019-09-19T06:03:53Z","tags":["warning","task_manager"],"pid":1356,"message":"PollError No Living connec>
Sep 19 06:03:53 ip-172-31-88-39.ec2.internal kibana[1356]: {"type":"log","@timestamp":"2019-09-19T06:03:53Z","tags":["warning","elasticsearch","admin"],"pid":1356,"message":"Unable to revive >
Sep 19 06:03:53 ip-172-31-88-39.ec2.internal kibana[1356]: {"type":"log","@timestamp":"2019-09-19T06:03:53Z","tags":["warning","elasticsearch","admin"],"pid":1356,"message":"No living connect>

Do you have any idea where the problem is?


问:
Using JAMon with Spring 5 and log4j2
I'm in the middle of a upgrade for an application currently moving Spring core  from 4.3 to 5.2 (yeah, trying the milestone expecting the LTS release) and it requires us to move to log4j2.

The problem we have so far is that I cannot seem to find anything on how to make JAMon work with this new configuration. The appender fail with this message:

```<code>java.lang.NoSuchMethodException: org.apache.log4j.api.LoggingEvent.<init>(Ljava/lang/String;Lorg/apache/log4j/Category;Jorg/apache/log4j/Priority...)
</code>```

And, in the project, the last we heard from maintainer was this (looks like the current version does not support changing appenders to log4j2).

E.g. in log4j.jsp, it imports

```<code><%@ page import="com.jamonapi.MonitorFactory, org.apache.log4j.Logger, org.apache.log4j.PropertyConfigurator, java.util.Properties" %>
</code>```

and the JAMonAppender class in the source code says

```<code>public class JAMonAppender extends AppenderSkeleton {
    /* Prefix for this classes jamon monitor labels */
    private final String PREFIX = "com.jamonapi.log4j.JAMonAppender.";

    // any of these poperties can be overridden via log4j configurators.
    private int bufferSize = 100;

    private String units = "log4j"; // units in jamon montiors
</code>```

So it seems to be hardwired to ye olde log4j. Has anyone managed to make it work?

答:
Note, I am the creator of jamonapi. Although, I haven't made updates in a while it is still supported and we could add a log4j 2 appender if anyone would want it.  I know this is an old post, but let me know what you think....

EDIT: as of jamon 2.82 JAMonAppender has been updated to work with log4j 2. For log4j It gives the ability to see how many times each level was called (ERROR, INFO) as well as allows you to 'tail' the log via a web app. It monitors many other aspects of your application too.  Here is a link for log4j2 - http://jamonapi.sourceforge.net/log4j_jamonappender.html

Title: Using JAMon with Spring 5 and log4j2

Body:
I'm in the middle of a upgrade for an application currently moving Spring core  from 4.3 to 5.2 (yeah, trying the milestone expecting the LTS release) and it requires us to move to log4j2.

The problem we have so far is that I cannot seem to find anything on how to make JAMon work with this new configuration. The appender fail with this message:

java.lang.NoSuchMethodException: org.apache.log4j.api.LoggingEvent.<init>(Ljava/lang/String;Lorg/apache/log4j/Category;Jorg/apache/log4j/Priority...)

And, in the project, the last we heard from maintainer was this (looks like the current version does not support changing appenders to log4j2).

E.g. in log4j.jsp, it imports

<%@ page import="com.jamonapi.MonitorFactory, org.apache.log4j.Logger, org.apache.log4j.PropertyConfigurator, java.util.Properties" %>

and the JAMonAppender class in the source code says

public class JAMonAppender extends AppenderSkeleton {
    /* Prefix for this classes jamon monitor labels */
    private final String PREFIX = "com.jamonapi.log4j.JAMonAppender.";

    // any of these poperties can be overridden via log4j configurators.
    private int bufferSize = 100;

    private String units = "log4j"; // units in jamon montiors

So it seems to be hardwired to ye olde log4j. Has anyone managed to make it work?


问:
How to execute code if the difference in the value of a variable is over 20
I'm trying to see if var1 is not equal to var2, but has top be greater than it by 20 or more to execute the code.

I currently have:

```<code>if (var1 != var2) {
    // need to put what happens if var2 is 20 or more greater than var1
}
else {

}
</code>```

答:
I believe this should do what you wanted.</p>

```<code>//Check if the difference between var2 and var1 is greater than or equal to 20
if(var2 - var1 >= 20){
    //Insert Code here
}
</code>```

Body:
I believe this should do what you wanted.

//Check if the difference between var2 and var1 is greater than or equal to 20
if(var2 - var1 >= 20){
    //Insert Code here
}


问:
Scroll only a part of a page
I have a fixed Toolbar in the top. The scrollbar of the page is for the whole page. The toolbar wont move from the top and is always visible and i have no problem with that. But i want only the content of the page to be scrollable instead of the whole page

Example i have a div called  content inside the body and i want only that to be scrollable instead of the whole body

Code

```<code><body>
  <div>
     <div class="Top">
        <?php $var = 1; include('PHP/ToolBar.php') ?>
     </div>

     <div class="content">
        <h5>Page Content</h5>
     </div>
  </div>
</body>
</code>```

The whole page scrolls but i want only the content to be scrollable.

Using webkit for customised scrollbar

```<code>::-webkit-scrollbar {
  width: 10px;
}
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 5px;
}
::-webkit-scrollbar-thumb {
  background: #333333;
  border-radius: 5px;
}
::-webkit-scrollbar-thumb:hover {
  background: #555555;
}
</code>```

答:
Hope this help you.

::-webkit-scrollbar {
  width: 10px;
}

::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 5px;
}

::-webkit-scrollbar-thumb {
  background: #333333;
  border-radius: 5px;
}

::-webkit-scrollbar-thumb:hover {
  background: #555555;
}

.Top {
  height: 10vh;
  float: left;
  width: 100%;
}

.content {
  height: 90vh;
  float: left;
  width: 100%;
  overflow-y: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="Top">
    Header
  </div>

  <div class="content">
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  </div>
</div></code>```

Title: Scroll only a part of a page

Body:
I have a fixed Toolbar in the top. The scrollbar of the page is for the whole page. The toolbar wont move from the top and is always visible and i have no problem with that. But i want only the content of the page to be scrollable instead of the whole page

Example i have a div called  content inside the body and i want only that to be scrollable instead of the whole body

Code

        <?php $var = 1; include('PHP/ToolBar.php') ?>

Page Content

The whole page scrolls but i want only the content to be scrollable.

Using webkit for customised scrollbar

::-webkit-scrollbar {
  width: 10px;
}
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 5px;
}
::-webkit-scrollbar-thumb {
  background: #333333;
  border-radius: 5px;
}
::-webkit-scrollbar-thumb:hover {
  background: #555555;
}

Body:
Hope this help you.

::-webkit-scrollbar {
  width: 10px;
}

::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 5px;
}

::-webkit-scrollbar-thumb {
  background: #333333;
  border-radius: 5px;
}

::-webkit-scrollbar-thumb:hover {
  background: #555555;
}

.Top {
  height: 10vh;
  float: left;
  width: 100%;
}

.content {
  height: 90vh;
  float: left;
  width: 100%;
  overflow-y: scroll;
}

<div>
  <div class="Top">
    Header
  </div>

  <div class="content">
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  </div>
</div>


答:
You could do:</p>

```<code>if(Math.Abs(var1 +- var2) >= 20){
//do code
}
</code>```

Body:
I'm trying to see if var1 is not equal to var2, but has top be greater than it by 20 or more to execute the code.

I currently have:

if (var1 != var2) {
    // need to put what happens if var2 is 20 or more greater than var1
}
else {

}

Body:
You could do:

if(Math.Abs(var1 +- var2) >= 20){
//do code
}


问:
When I'm using map local it maps several requests
My path is /api/query without any Query Parameters, but Charles maps all requests that have path /api/query.

In other words:

Charles maps /api/query?some=1, /api/query?another=1 and /api/query requests, but I need just /api/query. I need to be mapped clear request without query parameters.

version: 3.12.3

答:
Not sure if you have figured out but there is an alternative tool that works the same as Charles named Proxyman. Basically, just right click your URL --> select Tools --> Map Local

If you check "Include all subpaths of this domain" --> Proxyman will map all requests including subpaths such as /api/query?some=1, /api/query?another=1 and /api/query

If you uncheck the box --> Proxyman will map /api/query only

Hope it helps :)


问:
What is the blue circle in python dash app?
I am new to dash and I don't know what exactly the blue circle is in the app does.

Attached is the same for reference.

https://i.stack.imgur.com/hVcsY.png

答: That is only visible when running in debug mode. Use app.run_server(debug=False) to hide it. It allows you to view or hide errors in the browser, and view the callback structure of your app.


问:
bitbake do_package_qa issue contains bad RPATH
I am clueless about an issue which i am facing.
During cross compiling one of the app, i am getting following error which is making no sense.
If someone can help me debug the issue, it would be really helpful.

```<code>ERROR: lib32-audiod-1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00 do_package_qa: QA Issue: package lib32-audiod-ptest contains bad RPATH /home/work/ashutosh.tripathi/o20_build/build-starfish/BUILD/work/o20-starfishmllib32-linux-gnueabi/lib32-audiod/1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00/audiod-1.0.0-161.jcl4tv.85 in file /home/work/ashutosh.tripathi/o20_build/build-starfish/BUILD/work/o20-starfishmllib32-linux-gnueabi/lib32-audiod/1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00/packages-split/lib32-audiod-ptest/opt/webos/tests/audiod/gtest_audiod
package lib32-audiod-ptest contains bad RPATH /home/work/ashutosh.tripathi/o20_build/build-starfish/BUILD/work/o20-starfishmllib32-linux-gnueabi/lib32-audiod/1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00/audiod-1.0.0-161.jcl4tv.85 in file /home/work/ashutosh.tripathi/o20_build/build-starfish/BUILD/work/o20-starfishmllib32-linux-gnueabi/lib32-audiod/1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00/packages-split/lib32-audiod-ptest/opt/webos/tests/audiod/gtest_audiod [rpaths]
ERROR: lib32-audiod-1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00 do_package_qa: QA run found fatal errors. Please consider fixing them.
ERROR: lib32-audiod-1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00 do_package_qa: Function failed: do_package_qa
ERROR: Logfile of failure stored in: /home/work/ashutosh.tripathi/o20_build/build-starfish/BUILD/work/o20-starfishmllib32-linux-gnueabi/lib32-audiod/1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00/temp/log.do_package_qa.4873
ERROR: Task (virtual:multilib:lib32:/home/work/ashutosh.tripathi/o20_build/build-starfish/meta-lg-webos/meta-webos/recipes-multimedia/audiod/audiod.bb:do_package_qa) failed with exit code '1'
NOTE: Tasks Summary: Attempted 2622 tasks of which 2608 didn't need to be rerun and 1 failed.

</code>```

Here is the audiod recipe file:

```<code>DEPENDS = "glib-2.0 libpbnjson luna-service2 pmloglib luna-prefs boost pulseaudio"
RDEPENDS_${PN} = "\
    libasound \
    libasound-module-pcm-pulse \
    libpulsecore \
    pulseaudio \
    pulseaudio-lib-cli \
    pulseaudio-lib-protocol-cli \
    pulseaudio-misc \
    pulseaudio-module-cli-protocol-tcp \
    pulseaudio-module-cli-protocol-unix \
    pulseaudio-server \
"

WEBOS_VERSION = "1.0.0-161.open.12_49f981e4e5a599b75d893520b30393914657a4ae"
PR = "r26"

inherit webos_component
inherit webos_enhanced_submissions
inherit webos_cmake
inherit webos_library
inherit webos_daemon
inherit webos_system_bus
inherit webos_machine_dep
inherit gettext
inherit webos_lttng
inherit webos_public_repo
inherit webos_test_provider

# TODO: move to WEBOS_GIT_REPO_COMPLETE
WEBOS_REPO_NAME = "audiod-pro"
SRC_URI = "${WEBOS_PRO_GIT_REPO_COMPLETE}"
S = "${WORKDIR}/git"

EXTRA_OECMAKE += "${@bb.utils.contains('WEBOS_LTTNG_ENABLED', '1', '-DWEBOS_LTTNG_ENABLED:BOOLEAN=True', '', d)}"

EXTRA_OECMAKE += "-DAUDIOD_PALM_LEGACY:BOOLEAN=True"
EXTRA_OECMAKE += "-DAUDIOD_TEST_API:BOOLEAN=True"

FILES_${PN} += "${datadir}/alsa/"
FILES_${PN} += "/data"
FILES_${PN} += "${webos_mediadir}/internal"

</code>```

答:
I would like to thank the stackoverflow community for the help offered.
Adding the following flags helped resolve the issue.
Posting it here, so that others may get some benefit from it, if they ever face similar problem

```<code>set(CMAKE_INSTALL_RPATH "$ORIGIN")
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
</code>```

Or, skipping RPATH also does the job:

```<code>SET(CMAKE_SKIP_BUILD_RPATH  TRUE)
SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
</code>```

Body:
I am clueless about an issue which i am facing.
During cross compiling one of the app, i am getting following error which is making no sense.
If someone can help me debug the issue, it would be really helpful.

ERROR: lib32-audiod-1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00 do_package_qa: QA Issue: package lib32-audiod-ptest contains bad RPATH /home/work/ashutosh.tripathi/o20_build/build-starfish/BUILD/work/o20-starfishmllib32-linux-gnueabi/lib32-audiod/1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00/audiod-1.0.0-161.jcl4tv.85 in file /home/work/ashutosh.tripathi/o20_build/build-starfish/BUILD/work/o20-starfishmllib32-linux-gnueabi/lib32-audiod/1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00/packages-split/lib32-audiod-ptest/opt/webos/tests/audiod/gtest_audiod
package lib32-audiod-ptest contains bad RPATH /home/work/ashutosh.tripathi/o20_build/build-starfish/BUILD/work/o20-starfishmllib32-linux-gnueabi/lib32-audiod/1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00/audiod-1.0.0-161.jcl4tv.85 in file /home/work/ashutosh.tripathi/o20_build/build-starfish/BUILD/work/o20-starfishmllib32-linux-gnueabi/lib32-audiod/1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00/packages-split/lib32-audiod-ptest/opt/webos/tests/audiod/gtest_audiod [rpaths]
ERROR: lib32-audiod-1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00 do_package_qa: QA run found fatal errors. Please consider fixing them.
ERROR: lib32-audiod-1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00 do_package_qa: Function failed: do_package_qa
ERROR: Logfile of failure stored in: /home/work/ashutosh.tripathi/o20_build/build-starfish/BUILD/work/o20-starfishmllib32-linux-gnueabi/lib32-audiod/1.0.0-161.jcl4tv.85-r26audiod-automation-10Feb_00/temp/log.do_package_qa.4873
ERROR: Task (virtual:multilib:lib32:/home/work/ashutosh.tripathi/o20_build/build-starfish/meta-lg-webos/meta-webos/recipes-multimedia/audiod/audiod.bb:do_package_qa) failed with exit code '1'
NOTE: Tasks Summary: Attempted 2622 tasks of which 2608 didn't need to be rerun and 1 failed.

Here is the audiod recipe file:

DEPENDS = "glib-2.0 libpbnjson luna-service2 pmloglib luna-prefs boost pulseaudio"
RDEPENDS_${PN} = "\
    libasound \
    libasound-module-pcm-pulse \
    libpulsecore \
    pulseaudio \
    pulseaudio-lib-cli \
    pulseaudio-lib-protocol-cli \
    pulseaudio-misc \
    pulseaudio-module-cli-protocol-tcp \
    pulseaudio-module-cli-protocol-unix \
    pulseaudio-server \
"

WEBOS_VERSION = "1.0.0-161.open.12_49f981e4e5a599b75d893520b30393914657a4ae"
PR = "r26"

inherit webos_component
inherit webos_enhanced_submissions
inherit webos_cmake
inherit webos_library
inherit webos_daemon
inherit webos_system_bus
inherit webos_machine_dep
inherit gettext
inherit webos_lttng
inherit webos_public_repo
inherit webos_test_provider

# TODO: move to WEBOS_GIT_REPO_COMPLETE
WEBOS_REPO_NAME = "audiod-pro"
SRC_URI = "${WEBOS_PRO_GIT_REPO_COMPLETE}"
S = "${WORKDIR}/git"

EXTRA_OECMAKE += "${@bb.utils.contains('WEBOS_LTTNG_ENABLED', '1', '-DWEBOS_LTTNG_ENABLED:BOOLEAN=True', '', d)}"

EXTRA_OECMAKE += "-DAUDIOD_PALM_LEGACY:BOOLEAN=True"
EXTRA_OECMAKE += "-DAUDIOD_TEST_API:BOOLEAN=True"

FILES_${PN} += "${datadir}/alsa/"
FILES_${PN} += "/data"
FILES_${PN} += "${webos_mediadir}/internal"

Body:
I would like to thank the stackoverflow community for the help offered.
Adding the following flags helped resolve the issue.
Posting it here, so that others may get some benefit from it, if they ever face similar problem

set(CMAKE_INSTALL_RPATH "$ORIGIN")
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)

Or, skipping RPATH also does the job:

SET(CMAKE_SKIP_BUILD_RPATH  TRUE)
SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)


问:
mongod command creating error when entered into command line
Command line error image

This is the error I get from trying to run mongod command, there are similar errors on the forum and none of the solution have worked.

Please help

答:
data directory path data/db

do these directories not exist?

the error code is complaining about them - so check it out...


问:
How to calculate pairwise cosine distance of matrix using broadcasting in python
I have a matrix like this where each row is a vector and need to calculate pairwise cosine distance between the vectors (in this example, as a 2x2 matrix) without using loops? I understand for cartesian distance one can pad up a dimension but don't know the best method here.</p>

```<code>m = np.array([[1, 3, 5],[2,6,10]])
</code>```

答:
This type of question will get you berated with "Stack isn't for homework" but I guess you could just do this...

```<code>from numpy import linalg as LA
import numpy as np
m = np.array([[1, 3, 5],[2,6,10]])
cos = float(sum(m[0]*m[1]))/float(LA.norm(m[0])*LA.norm(m[1]))
</code>```

of course if you wanted to avoid using linlag

```<code>float(sum(m[0]*m[1]))/(float(sum(m[0]*m[0]))**0.5*float(sum(m[1]*m[1]))**0.5)
</code>```

See link -> https://en.wikipedia.org/wiki/Cosine_similarity

Body:
I have a matrix like this where each row is a vector and need to calculate pairwise cosine distance between the vectors (in this example, as a 2x2 matrix) without using loops? I understand for cartesian distance one can pad up a dimension but don't know the best method here.

m = np.array([[1, 3, 5],[2,6,10]])

Body:
This type of question will get you berated with "Stack isn't for homework" but I guess you could just do this...

from numpy import linalg as LA
import numpy as np
m = np.array([[1, 3, 5],[2,6,10]])
cos = float(sum(m[0]*m[1]))/float(LA.norm(m[0])*LA.norm(m[1]))

of course if you wanted to avoid using linlag

float(sum(m[0]*m[1]))/(float(sum(m[0]*m[0]))**0.5*float(sum(m[1]*m[1]))**0.5)

See link -> https://en.wikipedia.org/wiki/Cosine_similarity


问:
Kotlin how to make multiple requests in a queue
I have multiple requests, each request return 10 items. Something like this:

```<code>        var startIndex = 0
        var batchSize = 10
        var totoalCount = 50
        var requestTimes = totoalCount/batchSize
        for (index in 1..reqeustTimes) {
           client.request(url, "POST", startIndex) {
               completion(result.map {
                  //store in an array and append the returned items
               })
            startIndex += batchSize
        }
</code>```

But I want to control the order, like put the request in a queue, one finished the start the next one.

How should I do that?

Thanks!

EDIT

```<code>completion: ((Result<JsonObject>) -> Unit)?
</code>```

is an lambda.

EDIT:

I can make the request one by one, but the problem right now is the request isn't in order.

```<code>launch {
          (1..parameter.totalSize/parameter.batchSize).asFlow()
                    .map { _ -> fetchItem(parameter)}.collect()
}
</code>```

答:
You could use coroutine for this purpose,

As an example:

```<code>// suspend fun main() = withContext(Dispatchers.Default) { // for production
fun main() = runBlocking { // for testing (single threaded)
    var startIndex = 0
    val batchSize = 10
    val totoalCount = 50
    var requestTimes = totoalCount / batchSize
    for (index in 1..requestTimes) {
        val result = request(startIndex)
        // do result.onSuccess{} here
        startIndex += batchSize
    }
}

suspend fun request(startIndex: Int) = suspendCoroutine<Result<JsonObject>> {cont ->
    client.fetchItems(startIndex) { cont.resume (it) }
}
</code>```

NOTE: Since i don't know about what is type of fetchItems{it} in request function, i used suspendCoroutine<Result<JsonObject>> change it to what your fetchItems{it} return

The thread will be suspended till the coroutine is completed and another coroutine could easily occupy that thread till the request has the continuation resumed. So its not like blocking the thread or anything (stupid) :).

EDIT: see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/suspend-coroutine.html and https://discuss.kotlinlang.org/t/where-is-suspendcoroutine-supposed-to-be-used/11190/2

Body:
I have multiple requests, each request return 10 items. Something like this:

        var startIndex = 0
        var batchSize = 10
        var totoalCount = 50
        var requestTimes = totoalCount/batchSize
        for (index in 1..reqeustTimes) {
           client.request(url, "POST", startIndex) {
               completion(result.map {
                  //store in an array and append the returned items
               })
            startIndex += batchSize
        }

But I want to control the order, like put the request in a queue, one finished the start the next one.

How should I do that?

Thanks!

EDIT

completion: ((Result<JsonObject>) -> Unit)?

is an lambda.

EDIT:

I can make the request one by one, but the problem right now is the request isn't in order.

launch {
          (1..parameter.totalSize/parameter.batchSize).asFlow()
                    .map { _ -> fetchItem(parameter)}.collect()
}

Body:
You could use coroutine for this purpose,

As an example:

// suspend fun main() = withContext(Dispatchers.Default) { // for production
fun main() = runBlocking { // for testing (single threaded)
    var startIndex = 0
    val batchSize = 10
    val totoalCount = 50
    var requestTimes = totoalCount / batchSize
    for (index in 1..requestTimes) {
        val result = request(startIndex)
        // do result.onSuccess{} here
        startIndex += batchSize
    }
}

suspend fun request(startIndex: Int) = suspendCoroutine<Result<JsonObject>> {cont ->
    client.fetchItems(startIndex) { cont.resume (it) }
}

NOTE: Since i don't know about what is type of fetchItems{it} in request function, i used suspendCoroutine<Result<JsonObject>> change it to what your fetchItems{it} return

The thread will be suspended till the coroutine is completed and another coroutine could easily occupy that thread till the request has the continuation resumed. So its not like blocking the thread or anything (stupid) :).

EDIT: see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/suspend-coroutine.html and https://discuss.kotlinlang.org/t/where-is-suspendcoroutine-supposed-to-be-used/11190/2


答:
I won't provide a specific solution, since there are a few different ways of doing that depending on how exactly you want things to scroll or not scroll, so I suggest you start by reading about positioning and then layout in CSS:

https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout

https://developer.mozilla.org/en-US/docs/Web/CSS/position

https://css-tricks.com/almanac/properties/p/position/

Have fun!

Title: Scroll only a part of a page


问:
read c++ bytes bitfields in java
I have some legacy system that produces bytes[] array using bitfields in C++ that will sent over the network

```<code>struct date_compressed {
    unsigned int d:5;  //2 bytes
    unsigned int m:4; //1 bytes
    unsigned int y;   //4 bytes
};

This produces a hex string of 9fd3d46fde070000
</code>```

I need to able to read these bytes in Java and read the proper value , how do i do that?

I am looking at few ByteBuf library like netty etc but i cant find any good example how do we do this.

Thanks

答:
Use a ByteBuffer, and make sure to set the endianness correctly.

Example

```<code>byte[] data = new byte[7];
// fill data here

ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
int d = buf.getShort() & 0x1f; // 2 bytes, 5 bits, unsigned
int m = buf.get() & 0xf;       // 1 byte, 4 bits, unsigned
int y = buf.getInt();          // 4 bytes, 32 bits, signed
</code>```

Sure, the year value is signed, not unsigned like the C++ code specified, but you won't have year values that big.

Title: read c++ bytes bitfields in java

Body:
I have some legacy system that produces bytes[] array using bitfields in C++ that will sent over the network

struct date_compressed {
    unsigned int d:5;  //2 bytes
    unsigned int m:4; //1 bytes
    unsigned int y;   //4 bytes
};

This produces a hex string of 9fd3d46fde070000

I need to able to read these bytes in Java and read the proper value , how do i do that?

I am looking at few ByteBuf library like netty etc but i cant find any good example how do we do this.

Thanks

Body:
Use a ByteBuffer, and make sure to set the endianness correctly.

Example

byte[] data = new byte[7];
// fill data here

ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
int d = buf.getShort() & 0x1f; // 2 bytes, 5 bits, unsigned
int m = buf.get() & 0xf;       // 1 byte, 4 bits, unsigned
int y = buf.getInt();          // 4 bytes, 32 bits, signed

Sure, the year value is signed, not unsigned like the C++ code specified, but you won't have year values that big.


问:
Try to connect onos contrller in remote sever's container
I try to connect onos contrller in remote sever's container. But it shows Unable to contact the remote controller at 129.00.09.82:8190
The mininet command is sudo mn --topo=linear,3 --controller=remote,ip= 129.00.09.82:8190
The Ip I used is floating Ip
Then I use the command sudo ovs-vsctl set-controller s1 tcp:129.00.09.82:8190:6653 to set controller. It failed.

But if I run mininet on the same sever as docker container
I use the command sudo mn --topo=linear,3 --controller=remote,ip=127.0.0.1:8190
and set use this command sudo ovs-vsctl set-controller s1 tcp:172.17.0.2:6653
I succeed.
I know the success from karaf@root > when I type devices, it shows connected.

答:
Make sure the ping 129.00.09.82is responding.

If you can ping successfully but cannot connect.

Check that Onos contrller application Openflow Provide suite is started.


问:
How can i manipulate an master table so i can add an calender to it when using splitview in Swift
So I am new to programming in swift and I am stuck. I am trying to add an calender to the left hand side by using splitview so that for each date I can save a sketch to it. How would I use the splitview function to write code for a calender? Or do I need to do it another way? Please view the picture below to get a better idea of it. All I need help with is if there is a way to manipulate splitview into using it more than just a table or is it another way to complete this project?

答:
Yeah, so there's totally a way to do that. I'm just assuming you want to show a calendar for the current month.

```<code>let calendar = Calendar.current
// If you wanted, you could easily change the 0 below to any number to get months in the future.
let targetDate = calendar.date(byAdding: .month, value: 0, to: Date(), wrappingComponents: false)!
let targetMonth = calendar.component(.month, from: targetDate)
let targetYear = calendar.component(.year, from: targetDate)
var targetMonthComponents = DateComponents()
targetMonthComponents.year = targetYear
targetMonthComponents.month = targetMonth
let targetMonthDate = calendar.date(from: targetMonthComponents)!
let numberOfDays = calendar.range(of: .day, in: .month, for: targetMonthDate)!.count
</code>```

Simply use a UITableViewDataSource to finish this.

Body:
Yeah, so there's totally a way to do that. I'm just assuming you want to show a calendar for the current month.

let calendar = Calendar.current
// If you wanted, you could easily change the 0 below to any number to get months in the future.
let targetDate = calendar.date(byAdding: .month, value: 0, to: Date(), wrappingComponents: false)!
let targetMonth = calendar.component(.month, from: targetDate)
let targetYear = calendar.component(.year, from: targetDate)
var targetMonthComponents = DateComponents()
targetMonthComponents.year = targetYear
targetMonthComponents.month = targetMonth
let targetMonthDate = calendar.date(from: targetMonthComponents)!
let numberOfDays = calendar.range(of: .day, in: .month, for: targetMonthDate)!.count

Simply use a UITableViewDataSource to finish this.


问:
Angular - LazyLoading child-route starting with :id catches everything
I have the following routing-modules:

app-routing.modules.ts

```<code>...
const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./startpage/startpage.module').then(m => m.StartpageModule)
  },
  {
    path: 'user',
    loadChildren: () => import('./user/user.module').then(m => m.UserModule),
    canActivate: [AuthGuard]
  },
  {
    path: 'shop',
    loadChildren: () => import('./shop/shop.module').then(m => m.ShopModule),
    canActivate: [AuthGuard]
  },
  {
    path: '**',
    redirectTo: '',
    pathMatch: 'full'
  }
];
...
</code>```

and shop-routing.modules.ts

```<code>const routes: Routes = [
  {
    path: '',
    redirectTo: 'user',
    pathMatch: 'full',
  },
  {
    path: ':id',
    component: ShopPageComponent
  }
];
</code>```

The problem is, since I'm starting the child route of 'shop' with ':id', it acts as a 'catch-everything' route. If i call 'localhost:4200/user' now, it loads the shopcomponent. Why is that like that? I thought 'shop' was the main route and the ':id' child is only called, when the link has 'shop/' as prefix. If I put 'shop/:id' before, it works fine, but then the route is also callable via 'localhost:4200/shop/shop/something' which is ugly and also my authGuard isn't working anymore.

答:
App-routing.module.ts

```<code>const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./startpage/startpage.module').then(m => m.StartpageModule),
    pathMatch: 'prefix'
  },
  {
    path: 'user',
    loadChildren: () => import('./user/user.module').then(m => m.UserModule),
    canActivate: [AuthGuard],
    pathMatch: 'prefix'
  },
  {
    path: 'shop',
    loadChildren: () => import('./shop/shop.module').then(m => m.ShopModule),
    canActivate: [AuthGuard],
    pathMatch: 'prefix'
  },
  {
    path: '**',
    redirectTo: '',
    pathMatch: 'full'
  }
</code>```

pathMatch: 'prefix' will check for prefix path only and checks for child path for the rest of the path.

Body:
I have the following routing-modules:

app-routing.modules.ts

...
const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./startpage/startpage.module').then(m => m.StartpageModule)
  },
  {
    path: 'user',
    loadChildren: () => import('./user/user.module').then(m => m.UserModule),
    canActivate: [AuthGuard]
  },
  {
    path: 'shop',
    loadChildren: () => import('./shop/shop.module').then(m => m.ShopModule),
    canActivate: [AuthGuard]
  },
  {
    path: '**',
    redirectTo: '',
    pathMatch: 'full'
  }
];
...

and shop-routing.modules.ts

const routes: Routes = [
  {
    path: '',
    redirectTo: 'user',
    pathMatch: 'full',
  },
  {
    path: ':id',
    component: ShopPageComponent
  }
];

The problem is, since I'm starting the child route of 'shop' with ':id', it acts as a 'catch-everything' route. If i call 'localhost:4200/user' now, it loads the shopcomponent. Why is that like that? I thought 'shop' was the main route and the ':id' child is only called, when the link has 'shop/' as prefix. If I put 'shop/:id' before, it works fine, but then the route is also callable via 'localhost:4200/shop/shop/something' which is ugly and also my authGuard isn't working anymore.

Body:
App-routing.module.ts

const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('./startpage/startpage.module').then(m => m.StartpageModule),
    pathMatch: 'prefix'
  },
  {
    path: 'user',
    loadChildren: () => import('./user/user.module').then(m => m.UserModule),
    canActivate: [AuthGuard],
    pathMatch: 'prefix'
  },
  {
    path: 'shop',
    loadChildren: () => import('./shop/shop.module').then(m => m.ShopModule),
    canActivate: [AuthGuard],
    pathMatch: 'prefix'
  },
  {
    path: '**',
    redirectTo: '',
    pathMatch: 'full'
  }

pathMatch: 'prefix' will check for prefix path only and checks for child path for the rest of the path.


问:
Django Models and Admin interface question
I am preparing a Examination website for my students. Simple website, with use of Django's admin interface to create the Question paper.

I have following models:

```<code>class Paper(models.Model):
    name = models.CharField(max_length=2000, unique=False)
    short_desc = models.TextField(unique=False)

class Question(models.Model):
    text = models.TextField(unique=False)
    order = models.IntegerField(unique=True)
    paper = models.ForeignKey(Paper, unique=False)
</code>```

While adding questions to the paper, I want that I should be able to add the question from the Paper's admin interface itself, by clicking a "+" sign or some kind of "add more questions" etc.

In my current setup, I have to first create the paper and then go into Question interface and add them one by one (and heaven's forbid) if I lose their order number.

Remember, each Question belongs to a Paper and it is not a ManyToMany thing here.

Do I have to modify the admin in any way or am I doing it wrong?

Thanks.

答: InlineModelAdmin is what you're after. See http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects for the details</p>

Body:
I am preparing a Examination website for my students. Simple website, with use of Django's admin interface to create the Question paper.

I have following models:

class Paper(models.Model):
    name = models.CharField(max_length=2000, unique=False)
    short_desc = models.TextField(unique=False)

class Question(models.Model):
    text = models.TextField(unique=False)
    order = models.IntegerField(unique=True)
    paper = models.ForeignKey(Paper, unique=False)

While adding questions to the paper, I want that I should be able to add the question from the Paper's admin interface itself, by clicking a "+" sign or some kind of "add more questions" etc.

In my current setup, I have to first create the paper and then go into Question interface and add them one by one (and heaven's forbid) if I lose their order number.

Remember, each Question belongs to a Paper and it is not a ManyToMany thing here.

Do I have to modify the admin in any way or am I doing it wrong?

Thanks.


问:
How to create CoreApplicationView (C++/CX)?
Im trying to create a second window on UWP, but nothing works out for me. Unfortunately, I`m not well in UWP and there are few guides for C++/CX.
My IFrameworkViewSource:

```<code>IFrameworkView^ ApplicationSource::CreateView()
{
    return ref new test();
}
</code>```

maximally simple implementation of IFrameworkView:

```<code>test::test()
{
}

void test::Initialize(CoreApplicationView^ applicationView)
{
    applicationView->Activated +=
        ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &test::OnActivated);
}

void test::SetWindow(Windows::UI::Core::CoreWindow^ window) {

}

void test::Load(Platform::String^ entryPoint)
{
}

void test::Run()
{
}

void test::Uninitialize()
{
}

void test::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
    CoreWindow::GetForCurrentThread()->Activate();
}
</code>```

The trying to create a view:

```<code>auto applicationSource = ref new ApplicationSource();
CoreApplication::CreateNewView(applicationSource);
</code>```

Sometimes application is running, sometimes it return HR 0x8000000e .
I`m using a classic template in microsoft visual studio 2019 "Application DirectX11(UWP - C++/CX)

答:
You can first call CoreApplication.CreateNewView to create a new window and thread for the view content. Then Track the Id of the new view. You use this to show the view later. After that, active window and show the new view. You could try to use the following code and about more details, you can refer to this document  which is using c #.

```<code>auto newView = CoreApplication::CreateNewView(ref new ApplicationSource());
newView->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
{
    auto viewId = Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->Id;
    CoreWindow::GetForCurrentThread()->Activate();
    CoreApplication::MainView->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([viewId]()
    {
        auto asyncAction = Windows::UI::ViewManagement::ApplicationViewSwitcher::SwitchAsync(viewId, Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->Id);
    }));
}));
</code>```

Body:
Im trying to create a second window on UWP, but nothing works out for me. Unfortunately, I`m not well in UWP and there are few guides for C++/CX.
My IFrameworkViewSource:

IFrameworkView^ ApplicationSource::CreateView()
{
    return ref new test();
}

maximally simple implementation of IFrameworkView:

test::test()
{
}

void test::Initialize(CoreApplicationView^ applicationView)
{
    applicationView->Activated +=
        ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &test::OnActivated);
}

void test::SetWindow(Windows::UI::Core::CoreWindow^ window) {

}

void test::Load(Platform::String^ entryPoint)
{
}

void test::Run()
{
}

void test::Uninitialize()
{
}

void test::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
    CoreWindow::GetForCurrentThread()->Activate();
}

The trying to create a view:

auto applicationSource = ref new ApplicationSource();
CoreApplication::CreateNewView(applicationSource);

Sometimes application is running, sometimes it return HR 0x8000000e .
I`m using a classic template in microsoft visual studio 2019 "Application DirectX11(UWP - C++/CX)

Body:
You can first call CoreApplication.CreateNewView to create a new window and thread for the view content. Then Track the Id of the new view. You use this to show the view later. After that, active window and show the new view. You could try to use the following code and about more details, you can refer to this document  which is using c #.

auto newView = CoreApplication::CreateNewView(ref new ApplicationSource());
newView->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
{
    auto viewId = Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->Id;
    CoreWindow::GetForCurrentThread()->Activate();
    CoreApplication::MainView->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([viewId]()
    {
        auto asyncAction = Windows::UI::ViewManagement::ApplicationViewSwitcher::SwitchAsync(viewId, Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->Id);
    }));
}));


问:
`elementFormDefault` sometimes doesn't work
Introduction

elementFormDefault="unqualified" on the <schema> element sets a default form="unqualified" for the elements defined in that schema.

The following valid XML segment used a schema defined with elementFormDefault="unqualified"

```<code><asnx:module xmlns:asnx="urn:ietf:params:xml:ns:asnx">
   <sequence/>
</asnx:module>
</code>```

The <sequence> element doesn't have namespace qualification because the schema was defined like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns="urn:ietf:params:xml:ns:asnx"
       targetNamespace="urn:ietf:params:xml:ns:asnx"
       elementFormDefault="unqualified">
....
</code>```

Abnormality

In a specific system I'm working with, modularised XHTML was used in the descriptive part of XML data, like this:

```<code><product:description>
 <xhtml:div>
  <xhtml:p>This product is discontinued</xhtml:p>
 </xhtml:div>
</product:description>
</code>```

Due to the way the software application I'm working on was assembled, it won't work unless it's written in this form:

```<code><product:description>
  <xhtml:div>
    <p>This product is discontinued</p>
  </xhtml:div>
</product:description>
</code>```

That is, the software application fails to process the embedded XHTML if elements are qualified.

I thought a quick fix is to modify the schema for XHTML namespace to make validator accept embeded XHTML elements unqualified. That is, to change XHTML's schema xhtml1-strict.xsd (only locally - the system won't reach out to w3.org website to get the official xsd file), by changing the root <schema> element from elementFormDefault="qualified" to elementFormDefault="unqualified".

To my surprise, the change has no effects. The validator (xmllint) still demand
 to be qualified:

element p: Schemas validity error : Element 'p': This element is not expected. Expected is one of ( {http://www.w3.org/1999/xhtml}p, {http://www.w3.org/1999/xhtml}div, {http://www.w3.org/1999/xhtml}fieldset, {http://www.w3.org/1999/xhtml}table, {http://www.w3.org/1999/xhtml}noscript, {http://www.w3.org/1999/xhtml}h1, {http://www.w3.org/1999/xhtml}h2, {http://www.w3.org/1999/xhtml}h3, {http://www.w3.org/1999/xhtml}h4, {http://www.w3.org/1999/xhtml}h5 )

Ruled-out probable causes

I thought maybe I was editing a xhtml1-strict.xsd not used by the system, so I edited parts of it like changing "div" to "vid" and observe the resulting error. That way I verified that the file I edit is the file used by the validator.

I also tried to change the other schemas imported in the product namespace and verified that changing elementFormDefault in any imported schema does have the anticipated effect on the way validator requires the children element to be qualified/unqualified, and that effect is clearly missing when I do the same to xhtml1-strict.xsd, so there is something magical about xhtml schema.

答:
I don't have a solution but I have an "answer" now.

First, elementFormDefault doesn't work on elements directly defined in the schema, but only in sub-elements defined in an element. In XHTML, elements like
 are not defined as sub-elements of , but rather instead, a standalone element on its own.

Second, even for sub-elements, only those not referring to the standalone elements can have form attribute, which are affected by elementFormDefault.

I reached that conclusion with a lot of experiments. I spent a lot of time trying to search in the defining documents in vain.

The author of xhtml chose to define elements standalone and refer to them, hence XHTML in its entirty is not affected by elementFormDefault.

Body:
Introduction

elementFormDefault="unqualified" on the <schema> element sets a default form="unqualified" for the elements defined in that schema.

The following valid XML segment used a schema defined with elementFormDefault="unqualified"

<asnx:module xmlns:asnx="urn:ietf:params:xml:ns:asnx">
   <sequence/>
</asnx:module>

The <sequence> element doesn't have namespace qualification because the schema was defined like this:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns="urn:ietf:params:xml:ns:asnx"
       targetNamespace="urn:ietf:params:xml:ns:asnx"
       elementFormDefault="unqualified">
....

Abnormality

In a specific system I'm working with, modularised XHTML was used in the descriptive part of XML data, like this:

<product:description>
 <xhtml:div>
  <xhtml:p>This product is discontinued</xhtml:p>
 </xhtml:div>
</product:description>

Due to the way the software application I'm working on was assembled, it won't work unless it's written in this form:

<product:description>
  <xhtml:div>

This product is discontinued

  </xhtml:div>
</product:description>

That is, the software application fails to process the embedded XHTML if elements are qualified.

I thought a quick fix is to modify the schema for XHTML namespace to make validator accept embeded XHTML elements unqualified. That is, to change XHTML's schema xhtml1-strict.xsd (only locally - the system won't reach out to w3.org website to get the official xsd file), by changing the root <schema> element from elementFormDefault="qualified" to elementFormDefault="unqualified".

To my surprise, the change has no effects. The validator (xmllint) still demand
 to be qualified:

element p: Schemas validity error : Element 'p': This element is not expected. Expected is one of ( {http://www.w3.org/1999/xhtml}p, {http://www.w3.org/1999/xhtml}div, {http://www.w3.org/1999/xhtml}fieldset, {http://www.w3.org/1999/xhtml}table, {http://www.w3.org/1999/xhtml}noscript, {http://www.w3.org/1999/xhtml}h1, {http://www.w3.org/1999/xhtml}h2, {http://www.w3.org/1999/xhtml}h3, {http://www.w3.org/1999/xhtml}h4, {http://www.w3.org/1999/xhtml}h5 )

Ruled-out probable causes

I thought maybe I was editing a xhtml1-strict.xsd not used by the system, so I edited parts of it like changing "div" to "vid" and observe the resulting error. That way I verified that the file I edit is the file used by the validator.

I also tried to change the other schemas imported in the product namespace and verified that changing elementFormDefault in any imported schema does have the anticipated effect on the way validator requires the children element to be qualified/unqualified, and that effect is clearly missing when I do the same to xhtml1-strict.xsd, so there is something magical about xhtml schema.

Body:
I don't have a solution but I have an "answer" now.

First, elementFormDefault doesn't work on elements directly defined in the schema, but only in sub-elements defined in an element. In XHTML, elements like <p> are not defined as sub-elements of <body>, but rather instead, a standalone element on its own.

Second, even for sub-elements, only those not referring to the standalone elements can have form attribute, which are affected by elementFormDefault.

I reached that conclusion with a lot of experiments. I spent a lot of time trying to search in the defining documents in vain.

The author of xhtml chose to define elements standalone and refer to them, hence XHTML in its entirty is not affected by elementFormDefault.


问:
My second scanf is not working - what can I do?
My second scanf in this code is not working, the computer doesn't wait for me to enter the second value.

I know when it happens with %c it is just need to put a space before the %
But can't make it work with %f

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

main()
{
    float a, p;
    printf("Insira seu peso: "); scanf("%.1f", &p);
    printf("Insira sua altura: "); scanf("%.2f", &a);
}
</code>```

答:
The dot . is not a valid format flag character in the scanf() family of functions.  The formats are related to the printf() family of formats (and that's not accidental) but they are far from identical.

Each conversion specification is introduced by the character '%' … after which the following appear in sequence:

An optional assignment-suppressing character '*'.

An optional non-zero decimal integer that specifies the maximum field width.

[CX] ⌦ An optional assignment-allocation character 'm'. ⌫

An option length modifier that specifies the size of the receiving object.

A conversion specifier character that specifies the type of conversion to be applied. The valid conversion specifiers are described below.

No mention of . in there.

Body:
My second scanf in this code is not working, the computer doesn't wait for me to enter the second value.

I know when it happens with %c it is just need to put a space before the %
But can't make it work with %f

#include <stdlib.h>
#include <stdio.h>

main()
{
    float a, p;
    printf("Insira seu peso: "); scanf("%.1f", &p);
    printf("Insira sua altura: "); scanf("%.2f", &a);
}