问:
why pcap_setfilter did not take effect
I'm using libpcap as lib to write a C program for catching up coming IPs.
my code snippet as following:

```<code>struct bpf_program filter;
pcap_compile(pcap_handle, &filter, "icmp[icmptype]=0 and '(dst 16.11.26.100 or dst 16.11.27.100)'", 1, 0);
pcap_setfilter(pcap_handle, &filter);
</code>```

But it didn't work, I still could see other dest Ips rather than only the above two Ips.

答: You should always check for errors from library routine calls.  If you'd checked for errors from pcap_compile(), you would have seen that the compile failed (due to the single quotes, although the error message would probably just be "syntax error").

Title: why pcap_setfilter did not take effect

Body:
I'm using libpcap as lib to write a C program for catching up coming IPs.
my code snippet as following:

struct bpf_program filter;
pcap_compile(pcap_handle, &filter, "icmp[icmptype]=0 and '(dst 16.11.26.100 or dst 16.11.27.100)'", 1, 0);
pcap_setfilter(pcap_handle, &filter);

But it didn't work, I still could see other dest Ips rather than only the above two Ips.


来源: stackexchange

问:
Experiencing slow booting times in Laravel
I've taken over a project and have noticed their booting times are outrageous average out 2-3 seconds, but have seen them hit as far as 9-10 second using Laravel Debugbar.

Now, trying to determine the source of this I've created a new application under the same server and using the same MySQL server. I've even got the blades for a basic page recreated and the difference is huge. Booting is down to maybe 3.4 to 5.6ms on average, all while using the same database, same server and same blade templating (at least for an example).

Now my question is, based on these factors, is there something I can do to try and locate where the real issue is for booting time delays in the old one (mind you, it is regularly updated to the most stable version of Laravel, so it's not old in the since of Laravel 4.1 or anything)? I'd hate to have to rebuild the entire thing, but would absolutely prefer that over these slow times for a project that I wouldn't consider simple but definitely not complex either.

I was hoping Laravel Debugbar might give me the hint I needed but the delays definitely don't have anything to do with the database as far as I'm concerned...

I should mention that I’ve gone through the regular caching artisan commands such as route, view, config:cache, etc. Session caching and general caching is handled through Redis.

答:
I would check what service providers and middlewares are executed during lifecycle of a request. But I give you a list of what I would do to debug this stuff.

Check 'providers' in config/app.php and disable everything under the "Application Service Providers" section.

Check middlewares configuration under app/Kernel.php and look if there is something suspicious.

Create a new /test route with a new controller, with no middleware and check access time for that route. If it's fast, then there is some bloatware executing for other routes.

Check responses of artisan commands. When an artisan command is executed, all service providers are loaded (but not middlewares). A simple php artisan that will show all the commands should be instant

Enable query log in MySQL and check all the queries coming for a simple request.

ContentLicense: CC BY-SA 4.0


问:
What to watch out for when converting a std::string to a char* for C function?
I have read many posts asking the question on how to convert a C++ std::string or const std::string& to a char* to pass it to a C function and it seems there is quite a few caveat's in regards to doing this.  One has to beware about the string being contiguous and a lot of other things.  The point is that I've never really understood all the points one needs to be aware of and why?

I wondered if someone could sum up the caveats and downfalls about doing a conversion from a std::string to a char* that is needed to pass to a C function?

This when the std::string is a const reference and when it's just a non-const reference, and when the C function will alter the char* and when it will not alter it.

答:
[I would add a comment, but I don't have enough rep for that, so sorry for adding (yet) another answer.]

While it is true that the current standard does not guarantee the internal buffer of std::string to be contiguous, it appears that practically all implementations use contiguous buffers. Furthermore, the new C++0x standard (which is about to be approved by ISO) requires contiguous internal buffers in std::string, and even the current C++03 standard requires returning a contiguous buffer when you call data() or &str[0] (though it won't be necessarily null-terminated). See here for more details.

That still doesn't make it safe to write to the string though, since the standard doesn't force implementations to actually return their internal buffer when you call data(), c_str() or operator, and neither are they prevented from using optimizations like copy-on-write, which may complicate things further (it appears that the new C++0x will ban ban copy-on-write though). That being said, if you don't care about maximum portability, you can check your target implementation and see what it actually does inside. AFAIK, Visual C++ 2008/2010 always returns the real internal buffer pointer, and doesn't do copy-on-write (it does have the Small String Optimization, but that's probably not a concern).

ContentLicense: CC BY-SA 3.0


问:
502 error on request for static *.js files from a function that wraps an Express application
We are serving static files through a Firebase Function.

```<code>const functions = require('firebase-functions');
const express = require('express');

const app = express();
app.use(express.static('dist'))

exports.staticFiles = functions.https.onRequest(app);
</code>```

Our dist/ directory contains two files:

```<code>dist/
  index.html
  app.js
</code>```

A request to our-project.cloudfunctions.net/staticFiles/index.html serves the expected HTML file. A request to our-project.cloudfunctions.net/staticFiles/app.js returns a 502 error.

How can we serve a simple *.js file from a Firebase Function?

Additional Details

We are on the Blaze plan.

The logs says: Function execution took 922 ms, finished with status: 'response error'.

答:
There is a file size limit:

https://cloud.google.com/functions/quotas#resource_limits

Max uncompressed HTTP response size: 10MB.

Body:
We are serving static files through a Firebase Function.

const functions = require('firebase-functions');
const express = require('express');

const app = express();
app.use(express.static('dist'))

exports.staticFiles = functions.https.onRequest(app);

Our dist/ directory contains two files:

dist/
  index.html
  app.js

A request to our-project.cloudfunctions.net/staticFiles/index.html serves the expected HTML file. A request to our-project.cloudfunctions.net/staticFiles/app.js returns a 502 error.

How can we serve a simple *.js file from a Firebase Function?

Additional Details

We are on the Blaze plan.

The logs says: Function execution took 922 ms, finished with status: 'response error'.


问:
VS Code process "ruby" on MacOS running at 100% CPU: how to fix?
When running Visual Studio Code for my Ruby on Rails development project, there is a 'ruby' process constantly running at almost 100% CPU making my fans spin like crazy. Looking at the Open Files and Ports of that process in the Activity Monitor, it looks like this is being caused by some process (node_modules.asar?) scanning through data directories (my_project/public/system/**):

```<code>cwd
/Users/pascal/projects/RoR/my_project
txt
/Users/pascal/.rbenv/versions/2.4.4/bin/ruby
txt
/usr/local/Cellar/gmp/6.1.2_2/lib/libgmp.10.dylib
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/encdb.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/trans/transdb.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/stringio.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/etc.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/digest/sha1.bundle
txt
/usr/local/Cellar/openssl/1.0.2o_2/lib/libcrypto.1.0.0.dylib
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/digest.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/openssl.bundle
txt
/usr/local/Cellar/openssl/1.0.2o_2/lib/libssl.1.0.0.dylib
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/io/nonblock.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/io/console.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/zlib.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/socket.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/io/wait.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/windows_31j.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/json-2.1.0/lib/json/ext/parser.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/json-2.1.0/lib/json/ext/generator.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/ripper.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/cgi/escape.bundle
txt
/Library/Preferences/Logging/.plist-cache.KjBd2ZgB
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/readline.bundle
txt
/usr/local/Cellar/readline/7.0.3_1/lib/libreadline.7.0.dylib
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/eventmachine-1.2.7/lib/rubyeventmachine.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/date_core.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/psych.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/strscan.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/utf_16le.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/utf_16be.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/racc/cparse.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/trans/single_byte.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/nokogiri-1.8.5/lib/nokogiri/nokogiri.bundle
txt
/usr/local/Cellar/xz/5.2.4/lib/liblzma.5.dylib
txt
/usr/lib/dyld
0
->(none)
1
->(none)
2
->(none)
3
->0xebb30f785d0d6639
4
->0xebb30f785d0d4fb9
5
->0xebb30f785d0d70b9
6
->0xebb30f785d0d7b39
7
/dev/null
8
->0xebb30f785d0d7bf9
9
->0xebb30f785d0d6e79
10
localhost:59701
11
localhost:59701->localhost:59702
12
[ctl com.apple.netsrc id 9 unit 64]
13
->0xebb30f7867f30159
14
192.168.10.31:59810->151.101.0.70:https
15
/Users/pascal/projects/RoR/my_project
16
/Users/pascal/projects/RoR/my_project/public
17
/Users/pascal/projects/RoR/my_project/public/system
18
/Users/pascal/projects/RoR/my_project/public/system/dragonfly
19
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test
20
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images
21
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662
22
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017
23
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017/12
24
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017/12/08
25
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017/12/08/13
26
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017/12/08/13/11
27
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017/12/08/13/11/27
36
/dev/ptmx
38
/private/var/folders/fn/wjmjy_xj1vv2n8lhfcsjb3480000gn/T/com.microsoft.VSCode.ShipIt.3TPnSs1E/Visual Studio Code.app/Contents/Resources/app/node_modules.asar
</code>```

I'm hoping that some exclude folders settings would fix this, but I cannot find any relevant setting. Or is there another solution for this?

答:
This turned out to be caused by the Solargraph gem. According to this explanation of the author, the exclude settings of this gem in the .solargraph.yml file don't work very well. Instead one should use more specific include settings. In my case I was using - **/*.rb as a single include setting. I've now changed this to:

```<code>include:
- app/**/*.rb
- db/migrate/**/*.rb
- db/seeds/**/*.rb
- config/**/*.rb
- lib/**/*.rb
- spec/**/*.rb
</code>```

Since then the ruby process seems to be tamed.

Body:
When running Visual Studio Code for my Ruby on Rails development project, there is a 'ruby' process constantly running at almost 100% CPU making my fans spin like crazy. Looking at the Open Files and Ports of that process in the Activity Monitor, it looks like this is being caused by some process (node_modules.asar?) scanning through data directories (my_project/public/system/**):

cwd
/Users/pascal/projects/RoR/my_project
txt
/Users/pascal/.rbenv/versions/2.4.4/bin/ruby
txt
/usr/local/Cellar/gmp/6.1.2_2/lib/libgmp.10.dylib
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/encdb.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/trans/transdb.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/stringio.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/etc.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/digest/sha1.bundle
txt
/usr/local/Cellar/openssl/1.0.2o_2/lib/libcrypto.1.0.0.dylib
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/digest.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/openssl.bundle
txt
/usr/local/Cellar/openssl/1.0.2o_2/lib/libssl.1.0.0.dylib
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/io/nonblock.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/io/console.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/zlib.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/socket.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/io/wait.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/windows_31j.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/json-2.1.0/lib/json/ext/parser.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/json-2.1.0/lib/json/ext/generator.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/ripper.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/cgi/escape.bundle
txt
/Library/Preferences/Logging/.plist-cache.KjBd2ZgB
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/readline.bundle
txt
/usr/local/Cellar/readline/7.0.3_1/lib/libreadline.7.0.dylib
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/eventmachine-1.2.7/lib/rubyeventmachine.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/date_core.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/psych.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/strscan.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/utf_16le.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/utf_16be.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/racc/cparse.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/2.4.0/x86_64-darwin17/enc/trans/single_byte.bundle
txt
/Users/pascal/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/nokogiri-1.8.5/lib/nokogiri/nokogiri.bundle
txt
/usr/local/Cellar/xz/5.2.4/lib/liblzma.5.dylib
txt
/usr/lib/dyld
0
->(none)
1
->(none)
2
->(none)
3
->0xebb30f785d0d6639
4
->0xebb30f785d0d4fb9
5
->0xebb30f785d0d70b9
6
->0xebb30f785d0d7b39
7
/dev/null
8
->0xebb30f785d0d7bf9
9
->0xebb30f785d0d6e79
10
localhost:59701
11
localhost:59701->localhost:59702
12
[ctl com.apple.netsrc id 9 unit 64]
13
->0xebb30f7867f30159
14
192.168.10.31:59810->151.101.0.70:https
15
/Users/pascal/projects/RoR/my_project
16
/Users/pascal/projects/RoR/my_project/public
17
/Users/pascal/projects/RoR/my_project/public/system
18
/Users/pascal/projects/RoR/my_project/public/system/dragonfly
19
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test
20
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images
21
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662
22
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017
23
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017/12
24
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017/12/08
25
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017/12/08/13
26
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017/12/08/13/11
27
/Users/pascal/projects/RoR/my_project/public/system/dragonfly/test/images/662/2017/12/08/13/11/27
36
/dev/ptmx
38
/private/var/folders/fn/wjmjy_xj1vv2n8lhfcsjb3480000gn/T/com.microsoft.VSCode.ShipIt.3TPnSs1E/Visual Studio Code.app/Contents/Resources/app/node_modules.asar

I'm hoping that some exclude folders settings would fix this, but I cannot find any relevant setting. Or is there another solution for this?

Body:
This turned out to be caused by the Solargraph gem. According to this explanation of the author, the exclude settings of this gem in the .solargraph.yml file don't work very well. Instead one should use more specific include settings. In my case I was using - **/*.rb as a single include setting. I've now changed this to:

include:
- app/**/*.rb
- db/migrate/**/*.rb
- db/seeds/**/*.rb
- config/**/*.rb
- lib/**/*.rb
- spec/**/*.rb

Since then the ruby process seems to be tamed.


问:
If I wrote some code in Android's runtime. What should I do if I want to call this code in the app?
Because of my lack of Android development skills, I don't know how to fix or find relevant information. If I wrote some code in Android's run time. What should I do if I want to call this code in the app?

I've written some code in run time. And push compiled .so to the phone. I dump some logs. It looks like they running well. But now,I don't know how to call this code in the app.Should I write some JNI code in run time? If so, do I still need load lib in the app?

答:
Yes, you have to play with JNI. JNI will serve as a bridge between your Java code and native code C/C++

I suggest to start with something simple (not necessarily inside Android). Just to get the feeling of what to expect, you can start with simple 'Hello World'.

http://jnicookbook.owsiak.org/recipe-No-001/

Basically, what you need, is to have your native code accessible from your Java code via JNI.

There are two options:

you can pack all the stuff (your code and JNI based code) inside one .so

you can also create two libraries: one with your native code and other one with JNI code

http://jnicookbook.owsiak.org/recipe-No-023/


问:
Improve accuracy on convolutional neural network
I'm trying to train a convolutional neural network to classify sentences. I take the code from here

The code works fine in one of my datasets. However, on another dataset, its performance is very poor. Two datasets are comparable in terms of volumes and sentence length. For the dataset with the poor performance, I notice the loss function decreases after steps. Here the blue is for training set and the read is for test set.

And here is the accuracy:

As you can see, the loss values on the test set decrease, but the accuracy values are almost the same.
Can you suggest me how to fix it?
Thank you very much.

答: Try using an exponential decaying learning rate--starts big at first (say 0.1) and then slows down over iterations.</p>


问:
Constraint for a many-to-many relationship table - both the related records need to reference the same dependent record?
There are three entities, Student, Class and  Department. Department and Student have a one-to-many relationship. Department and Class have a one-to-many relationship too. Student and Class have a many-to-many relationship.

```<code>create table Department
(
    Id int primary key,
    -- ...
)

create table Student
(
    Id int primary key,
    DepartmentId int not null references Department(Id),
    -- ....
)

create table Class
(
    Id int primary key,
    DepartmentId int not null references Department(Id),
    ....
)
</code>```

The following table is for the many-to-many relationship between Student and Class. Now user can put a pair of student/class which are from different (which shouldn't be allowed) departments in the table. Is it a way to prevent it besides using a trigger?

```<code>create table StudentAndClass
(
    StudentId int references Student(Id),
    ClassId int references Class(Id),
    -- ....
    primary key (StudentId, ClassId)
)
</code>```

答:
You should use a CHECK CONSTRAINT

```<code>CREATE FUNCTION dbo.CheckDepartment()
RETURNS int
AS BEGIN RETURN (
SELECT count(1)
    FROM StudentAndClass sc
    JOIN Student s on sc.StudentId=s.id
    JOIN Class c on sc.ClassId=c.id
WHERE c.DepartmentId<>s.DepartmentId
) END
go

ALTER TABLE StudentAndClass ADD CONSTRAINT chkDep CHECK (dbo.CheckDepartment() = 0);
</code>```

This will guarantee that the departments will match

Body:
There are three entities, Student, Class and  Department. Department and Student have a one-to-many relationship. Department and Class have a one-to-many relationship too. Student and Class have a many-to-many relationship.

create table Department
(
    Id int primary key,
    -- ...
)

create table Student
(
    Id int primary key,
    DepartmentId int not null references Department(Id),
    -- ....
)

create table Class
(
    Id int primary key,
    DepartmentId int not null references Department(Id),
    ....
)

The following table is for the many-to-many relationship between Student and Class. Now user can put a pair of student/class which are from different (which shouldn't be allowed) departments in the table. Is it a way to prevent it besides using a trigger?

create table StudentAndClass
(
    StudentId int references Student(Id),
    ClassId int references Class(Id),
    -- ....
    primary key (StudentId, ClassId)
)

Body:
You should use a CHECK CONSTRAINT

CREATE FUNCTION dbo.CheckDepartment()
RETURNS int
AS BEGIN RETURN (
SELECT count(1)
    FROM StudentAndClass sc
    JOIN Student s on sc.StudentId=s.id
    JOIN Class c on sc.ClassId=c.id
WHERE c.DepartmentId<>s.DepartmentId
) END
go

ALTER TABLE StudentAndClass ADD CONSTRAINT chkDep CHECK (dbo.CheckDepartment() = 0);

This will guarantee that the departments will match


问:
VB6: CDate(some date) returns runtime error 13
HI,

I have this string: "2010-12-27 23:05:36.0". When I parse it with CDate like this: CDate("2010-12-27 23:05:36.0") it returns error 13.
When I remove the '.0' from the string it is working fine.

The date string comes from a database where there is a mixture of dates formatted like this: 'yyyy-mm-dd' and 'yyyy-mm-dd hh-MM-ss.n' What would be the easy way to get rid of the error 13?

答: You could check the string length -> if it is >19, get rid of the rest and apply then the CDate function</p>


问:
How to return an HTML <div> tag from a javascript function in React?
I am working on a React application where I am trying to render text on the screen when a button is clicked. I have defined a function onButtonClick which gets triggered whenever the button is clicked. However, the HTML that I am returning from the function is not rendered on the screen. I am in the learning stages of React so please excuse me if the question seems silly.</p>

```<code>class App extends Component {

constructor() {
  super();

  this.state = {
    blockno:0

  }
}

OnButtonClick = () => {
  this.setState({blockno: this.state.blockno + 1})
  return(
      <div>
          <h3>Some text</h3>
      </div>
    );

}

render() {
return(
    <div>
        <Button onButtonClick={this.OnButtonClick}/>
    </div>
    );
}

}

</code>```

答:
You have to make a render based on your state. Please check the tutorial at the react docs to learn more about how React works. It's really good

Here is a version of your code that works. Hope it helps

```<code>class App extends Component {
  constructor() {
    super();

    this.state = {
      blockno: 0
    };
  }

  OnButtonClick = () => {
    //updates the states
    this.setState({ blockno: this.state.blockno + 1 });
  };
  //remember: every time there is an update to the state the render functions re-runs
  render() {
    //variable holding the blocks in an array
    let blocks = []
    //if blockno is greater than 0, it checks everytime that there is a state change
    if (this.state.blockno > 0) {
      //for every block added
      for (let index = 0; index < this.state.blockno; index++) {
        //We`re going to add to the array of blocks a new div with the block number
        blocks.push(
          <div>
            <h3>My block number is {index}</h3>
          </div>
        );
      }
    }
    return (
      <div>
        <div>
          {/**button that updates the state on every click */}
          <button onClick={this.OnButtonClick}>
            Click me to add a new div!
          </button>
        </div>
        {/**This render the blocks variable that holds the divs */}
        {blocks}
      </div>
    );
  }
}
</code>```

Body:
I am working on a React application where I am trying to render text on the screen when a button is clicked. I have defined a function onButtonClick which gets triggered whenever the button is clicked. However, the HTML that I am returning from the function is not rendered on the screen. I am in the learning stages of React so please excuse me if the question seems silly.

class App extends Component {

constructor() {
  super();

  this.state = {
    blockno:0

  }
}

OnButtonClick = () => {
  this.setState({blockno: this.state.blockno + 1})
  return(

Some text

    );

}

render() {
return(

        <Button onButtonClick={this.OnButtonClick}/>

    );
}

}

Body:
You have to make a render based on your state. Please check the tutorial at the react docs to learn more about how React works. It's really good

Here is a version of your code that works. Hope it helps

class App extends Component {
  constructor() {
    super();

    this.state = {
      blockno: 0
    };
  }

  OnButtonClick = () => {
    //updates the states
    this.setState({ blockno: this.state.blockno + 1 });
  };
  //remember: every time there is an update to the state the render functions re-runs
  render() {
    //variable holding the blocks in an array
    let blocks = []
    //if blockno is greater than 0, it checks everytime that there is a state change
    if (this.state.blockno > 0) {
      //for every block added
      for (let index = 0; index < this.state.blockno; index++) {
        //We`re going to add to the array of blocks a new div with the block number
        blocks.push(
          <div>
            <h3>My block number is {index}</h3>
          </div>
        );
      }
    }
    return (
      <div>
        <div>
          {/**button that updates the state on every click */}
          <button onClick={this.OnButtonClick}>
            Click me to add a new div!
          </button>
        </div>
        {/**This render the blocks variable that holds the divs */}
        {blocks}
      </div>
    );
  }
}


问:
A substitute OR query for Cassandra
I have a table in my Cassandra DB with columns userid, city1, city2 and city3. What would my query be if I wanted to retrieve  all users that have "Paris" as a city? I understand Cassandra doesn't have OR so I'm not sure how to structure the query.</p>

答:
First - it's heavily depend on the structure of the table - if you have userid as partition key, you can of course use secondary index to search users in cities, but it's not optimal as it's fan-out call - request is sent to all nodes in the cluster. You can re-design to use the materialized view with city as partition key, but you may have problems if you have a lot users in some cities.

In general, if you need to select several values in the same column - you can use IN operator, but it's better not to use it for partition keys (parallel queries are better). If you need OR on different columns - you need to do parallel queries, and collect results on application side.

Title: A substitute OR query for Cassandra


问:
Cannot migrate Oracle database (initially create tables) because of insufficient privileges?
I'm new to Oracle DB and really not sure what kind of privileges I should setup for an user so that he can execute basic commands like create,drop,delete, insert, update, select tables.

And actually I've setup all those privileges for my user account.
But when running migrate, it failed with the following error printed in console window:

2019-05-27 08:29:07.837809 ThreadID:1   (ERROR)   OracleRelationalCommand.Execute() :  Oracle.ManagedDataAccess.Client.OracleException (0x80004005): ORA-01031: insufficient privileges
  ORA-06512: at line 2
     at OracleInternal.ServiceObjects.OracleConnectionImpl.VerifyExecution(Int32& cursorId, Boolean bThrowArrayBindRelatedErrors, SqlStatementType sqlStatementType, Int32 arrayBindCount, OracleException& exceptionForArrayBindDML, Boolean& hasMoreRowsInDB, Boolean bFirstIterationDone)
     at OracleInternal.ServiceObjects.OracleCommandImpl.ExecuteNonQuery(String commandText, OracleParameterCollection paramColl, CommandType commandType, OracleConnectionImpl connectionImpl, Int32 longFetchSize, Int64 clientInitialLOBFS, OracleDependencyImpl orclDependencyImpl, Int64[]& scnFromExecution, OracleParameterCollection& bindByPositionParamColl, Boolean& bBindParamPresent, OracleException& exceptionForArrayBindDML, OracleConnection connection, OracleLogicalTransaction& oracleLogicalTransaction, Boolean isFromEF)
     at Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteNonQuery()
     at Oracle.EntityFrameworkCore.Storage.Internal.OracleRelationalCommandBuilderFactory.OracleRelationalCommandBuilder.OracleRelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues)
  Failed executing DbCommand (292ms) [Parameters=[], CommandType='Text', CommandTimeout='0']
  BEGIN
  EXECUTE IMMEDIATE 'CREATE TABLE
  "CUSTOMER" (
      "Id" NUMBER(10) GENERATED BY DEFAULT ON NULL AS IDENTITY NOT NULL,
      ...
      )';
  END;
  2019-05-27 08:29:07.842817 ThreadID:1   (ERROR)   OracleRelationalCommand.Execute() :  Oracle.ManagedDataAccess.Client.OracleException (0x80004005): ORA-01031: insufficient privileges
  ORA-06512: at line 2
     at OracleInternal.ServiceObjects.OracleConnectionImpl.VerifyExecution(Int32& cursorId, Boolean bThrowArrayBindRelatedErrors, SqlStatementType sqlStatementType, Int32 arrayBindCount, OracleException& exceptionForArrayBindDML, Boolean& hasMoreRowsInDB, Boolean bFirstIterationDone)
     at OracleInternal.ServiceObjects.OracleCommandImpl.ExecuteNonQuery(String commandText, OracleParameterCollection paramColl, CommandType commandType, OracleConnectionImpl connectionImpl, Int32 longFetchSize, Int64 clientInitialLOBFS, OracleDependencyImpl orclDependencyImpl, Int64[]& scnFromExecution, OracleParameterCollection& bindByPositionParamColl, Boolean& bBindParamPresent, OracleException& exceptionForArrayBindDML, OracleConnection connection, OracleLogicalTransaction& oracleLogicalTransaction, Boolean isFromEF)
     at Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteNonQuery()
     at Oracle.EntityFrameworkCore.Storage.Internal.OracleRelationalCommandBuilderFactory.OracleRelationalCommandBuilder.OracleRelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues)
  Oracle.ManagedDataAccess.Client.OracleException (0x80004005): ORA-01031: insufficient privileges
  ORA-06512: at line 2
     at OracleInternal.ServiceObjects.OracleConnectionImpl.VerifyExecution(Int32& cursorId, Boolean bThrowArrayBindRelatedErrors, SqlStatementType sqlStatementType, Int32 arrayBindCount, OracleException& exceptionForArrayBindDML, Boolean& hasMoreRowsInDB, Boolean bFirstIterationDone)
     at OracleInternal.ServiceObjects.OracleCommandImpl.ExecuteNonQuery(String commandText, OracleParameterCollection paramColl, CommandType commandType, OracleConnectionImpl connectionImpl, Int32 longFetchSize, Int64 clientInitialLOBFS, OracleDependencyImpl orclDependencyImpl, Int64[]& scnFromExecution, OracleParameterCollection& bindByPositionParamColl, Boolean& bBindParamPresent, OracleException& exceptionForArrayBindDML, OracleConnection connection, OracleLogicalTransaction& oracleLogicalTransaction, Boolean isFromEF)
     at Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteNonQuery()
     at Oracle.EntityFrameworkCore.Storage.Internal.OracleRelationalCommandBuilderFactory.OracleRelationalCommandBuilder.OracleRelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues)
     at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
     at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
     at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
     at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
  ORA-01031: insufficient privileges
  ORA-06512: at line 2

So looks like the involved sql command here is BEGIN EXECUTE IMMEDIATE …. I'm not so sure what kind of privileges I should setup for that to be executed successfully. Could you please take a look at the error info above to give me some suggestion to setup the privileges correctly for my user account?
 Thanks!

PS: screenshots showing all privileges I've setup:

答:
Well it looks like that the CREATE TABLE privilege is fine only when the table to be created does not contain any auto-incremented primary key?

It's really not enough in my case and I've tried adding 2 more privileges (for sure but not really know if which one does the trick or both do): CREATE CLUSTER and CREATE SEQUENCE.
Looks like when creating my tables, it need to create some sequence first (for identity columns) or create cluster for primary key ...

Actually I just tried looking in the RESOURCE role for any possible privileges that are missing for my specific user and I found the 2 most possible privileges as mentioned above.

It now works fine, all tables can be created fine :) blocking me about 1 day (of course not always focusing on it, but really waiting and thinking about the cause).


问:
Why print_r() still exists?
```<code>print_r(array('name'=> 'bob', 'age' => 20, 'sex' => 'man'));
</code>```

Then :

```<code>Array {
    [name] => bob,
    [age] => 20,
    [sex] => man }

var_dump(array('name' => 'bob', 'age' => 20));
</code>```

will display:

```<code>array(2) {
    ['name'] => string(3) 'bob'
    ['age'] => int(20) }
</code>```

var_dump is perfect to debug  and  much better than print_r. But why print_r still exists? or print_r has some advantage i don't know

答: If you wish to get as much data as you can use var_dump(), however i find that print_r() is more readable by humans.

Title: Why print_r() still exists?

Body:
print_r(array('name'=> 'bob', 'age' => 20, 'sex' => 'man'));

Then :

Array {
    [name] => bob,
    [age] => 20,
    [sex] => man }

var_dump(array('name' => 'bob', 'age' => 20));

will display:

array(2) {
    ['name'] => string(3) 'bob'
    ['age'] => int(20) }

var_dump is perfect to debug  and  much better than print_r. But why print_r still exists? or print_r has some advantage i don't know


问:
Microsoft OLE DB Provider for Visual FoxPro: Invalid path or file name
I'm able to connect to my VFP database when running my classic ASP site locally w/ Visual Studio and IIS Express but when I deploy to a server on IIS it get:

Microsoft OLE DB Provider for Visual FoxPro: Invalid path or file name

From a comment on this post, I see the problem is probably related to permissions but I've got the application pool running under a domain account that has access to the UNC where the DB resides.

答:
I changed my authentication on anonymous access from IUSR to the Application pool identity and it started working.

IIS Manager -> Website -> Authentication -> Anonymous Authentication -> Edit

After changing that, the database access must be using the service account now.  I guess there's a difference between ASP.NET and Classic ASP?

References how I arrived at this answer

I found this post which talked about anonymous access which got me thinking more about "classic asp run under service account".  That Google search lead to me to this SO post:

Classic ASP runs impersonating the user who is authenticated to the server in the HTTP session.


问:
tomcat 8080 behind AWS Application Load Balancer 443
My goal is 443 (ALB)->8080 (TOMCAT)

I am running a EC2 tomcat instance on 8080.

Here is the tomcat apr connector on 8080

```<code><Connector protocol="org.apache.coyote.http11.Http11AprProtocol"
           port="8080" scheme="http"
/>
</code>```

I have an ALB listening on 443 with a certificate and set to pass off to a target group 8080.

So the idea is https://www.website.com/myapp -> www.mywebsite.com:8080/myapp

I know my application is running fine because if I open up public access to 8080 I can fully run the app.

I have something misconfigured because when I go to the site
https://www.website.com/myapp

I seem to get redirected to:
www.website.com/myapp

It seems like I can reach tomcat fine, but then it is redirecting me back to http when it responds.  What am I doing wrong?

Thanks!

答:
What worked for me is:
I added 2 listeners:

To redirect, HTTP(80) -> HTTPS(443)

Then for the second listener, a forward rule, HTTPS(443) -> My Target for the ALB

Body:
My goal is 443 (ALB)->8080 (TOMCAT)

I am running a EC2 tomcat instance on 8080.

Here is the tomcat apr connector on 8080

<Connector protocol="org.apache.coyote.http11.Http11AprProtocol"
           port="8080" scheme="http"
/>

I have an ALB listening on 443 with a certificate and set to pass off to a target group 8080.

So the idea is https://www.website.com/myapp -> www.mywebsite.com:8080/myapp

I know my application is running fine because if I open up public access to 8080 I can fully run the app.

I have something misconfigured because when I go to the site
https://www.website.com/myapp

I seem to get redirected to:
www.website.com/myapp

It seems like I can reach tomcat fine, but then it is redirecting me back to http when it responds.  What am I doing wrong?

Thanks!


问:
How do I assign the output of jq to variables?
I am attempting to parse NOAA NWS json data with jq.  My last computer class was as a senior in high school, '67-68 semester.  Be gentle.

I have figured out how to filter the data I want, but I'd like it assigned to variables so I can use it farther down the road.  Using the original json name and index number as the variable's name is where I'm aimed.  I can't find any documentation that even gives me a clue, but I'm guessing this is something jq is used for all-the-time.

Here are my data and filters:  https://jqplay.org/s/uRhNX-UglJ?fbclid=IwAR3lPxOj1fQcyzEOSrvf5x3WBQWXd0N1kwTc62Agmg1KANwkKL6hI-0vJOE

答:
So not sure if this will help, but I use a JSON prettifier tool to get the arrays & indices info that I need
(the first one is a little more helpful to me)

https://codebeautify.org/jsonviewer

http://jsonviewer.stack.hu/

and from there I wrote a bash script that takes in whatever I'm getting data about as a variable, query it, and then use jq and awk to print whatever I'm after

Here's a line from the script showing the data I'm looking for:

```<code>res=$(curl --silent "https://api.oraclize.it/v1/query/eth_mainnet_${rec}/status" | jq -r ".result.checks[0].results")
        echo "$res"|awk '{print $2}'
</code>```

If I can provide anything further please feel free to reach out but maybe this will get you pointed in the right direction

Body:
So not sure if this will help, but I use a JSON prettifier tool to get the arrays & indices info that I need
(the first one is a little more helpful to me)

https://codebeautify.org/jsonviewer

http://jsonviewer.stack.hu/

and from there I wrote a bash script that takes in whatever I'm getting data about as a variable, query it, and then use jq and awk to print whatever I'm after

Here's a line from the script showing the data I'm looking for:

res=$(curl --silent "https://api.oraclize.it/v1/query/eth_mainnet_${rec}/status" | jq -r ".result.checks[0].results")
        echo "$res"|awk '{print $2}'

If I can provide anything further please feel free to reach out but maybe this will get you pointed in the right direction


问:
Haskell: Modifying value at specific index of array
New to Haskell. I have created an char array and I am trying to figure out the best way to modify data in that array given a specific index.

I already have an array created that I am passing into the below method in my main. That part is working fine. I just cant figure out how to manipulate the data at each index. In this particular case I am trying to override the value if the below condition is met with a space. And I want to return this to my main so i can print out the updated board.

```<code>import System.Random
import Control.Monad
import Data.Array
import Data.List

modifyArray :: Array Int Char -> Int -> IO (Array Int Char)
modifyArray arr i =
    if i > 0 then
        if i `mod` 102 == 1 then do
            (MODIFY ARRAY AT INDEX:i to equal ' ')
        else modifyArray arr (i-1)
    else arr
</code>```

答:
You don't actually need to modify the array. Just make your function create a new array that has the change you want, like this:

```<code>modifyArray :: Array Int Char -> Int -> Array Int Char
modifyArray arr i =
    if i > 0 then
        if i `mod` 102 == 1 then
            arr // [(i, ' ')]
        else modifyArray arr (i-1)
    else arr
</code>```

Data.Array includes the // operator, which means "take the array on the left, apply the changes on the right, and return the result". Also, since this function doesn't do any IO, there's no need to use "do" or have IO in the type signature.

Body:
New to Haskell. I have created an char array and I am trying to figure out the best way to modify data in that array given a specific index.

I already have an array created that I am passing into the below method in my main. That part is working fine. I just cant figure out how to manipulate the data at each index. In this particular case I am trying to override the value if the below condition is met with a space. And I want to return this to my main so i can print out the updated board.

import System.Random
import Control.Monad
import Data.Array
import Data.List

modifyArray :: Array Int Char -> Int -> IO (Array Int Char)
modifyArray arr i =
    if i > 0 then
        if i `mod` 102 == 1 then do
            (MODIFY ARRAY AT INDEX:i to equal ' ')
        else modifyArray arr (i-1)
    else arr

Body:
You don't actually need to modify the array. Just make your function create a new array that has the change you want, like this:

modifyArray :: Array Int Char -> Int -> Array Int Char
modifyArray arr i =
    if i > 0 then
        if i `mod` 102 == 1 then
            arr // [(i, ' ')]
        else modifyArray arr (i-1)
    else arr

Data.Array includes the // operator, which means "take the array on the left, apply the changes on the right, and return the result". Also, since this function doesn't do any IO, there's no need to use "do" or have IO in the type signature.


问:
Default value for user ForeignKey with Django admin
```<code>author = models.ForeignKey(User)
</code>```

Is there any way I can set the default value of this field to automatically select the logged in user? I know you can do this in the save method but my client has requested that it automatically defaults to the logged in user at edit time to avoid confusion.

This article goes into how to update it during save, just not at edit time.

答:
```<code>class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'author':
            kwargs['initial'] = request.user.id
        return super(MyModelAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs
        )
</code>```

Body:
author = models.ForeignKey(User)

Is there any way I can set the default value of this field to automatically select the logged in user? I know you can do this in the save method but my client has requested that it automatically defaults to the logged in user at edit time to avoid confusion.

This article goes into how to update it during save, just not at edit time.


问:
How to find XPath in Firefox Developer Edition?
I have installed Firefox Developer Edition. How to find XPath in this browser? I would like to get XPath and use in Selenium script.</p>

答:
$x(path, [startNode])

$x(path) returns an array of DOM elements that match the given XPath expression.

For example, the following returns all the
 elements on the page:

```<code> $x("//p")
</code>```

The following example returns all the
 elements that contain  elements:

```<code>$x("//p[a]")
</code>```

Similar to the other selector functions, $x(path) has an optional second parameter, startNode, that specifies an element or Node from which to search for elements.

Body:
$x(path, [startNode])

$x(path) returns an array of DOM elements that match the given XPath expression.

For example, the following returns all the <p> elements on the page:

 $x("//p")

The following example returns all the <p> elements that contain <a> elements:

$x("//p[a]")

Similar to the other selector functions, $x(path) has an optional second parameter, startNode, that specifies an element or Node from which to search for elements.


问:
How to trigger Reactjs onClick inside render instead of return?
How can I assign an onClick function if I decide to do a conditional render outside of React return?

Stackoverflow wants me to add even more description than the one I provided but my spent 1 hour writing code into their editor without syntax help or eslint :D

section:hover {
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"/>

<script type="text/babel">

const RotateOnClick = ( {rotated, handleChange} ) => {
  if (rotated) {
    return <section onClick={handleChange}>I'M ROTATED! Click me to rotate again!</section>
  } else {
    return <section onClick={handleChange}>I'm not rotated. Click me to rotate!</section>
  }
}

class Rotator extends React.Component {

  // Change state to true to see that it renders if toggled
  state = {
    isRotated: false
  }

  toggleRotation = () => {
    // Outdated initial code when asking the question
    // console.log("React doesn't like me. It will never call me :( ")

    console.log("Yei, it works! React likes me again")
    const { isRotated } = this.state
    this.setState( {isRotated: !isRotated })
  }

  render() {
    const { isRotated } = this.state

    let conditionalRender;
    if (isRotated) {
      conditionalRender = <RotateOnClick rotated handleChange={this.toggleRotation} />
    } else {
      conditionalRender = <RotateOnClick handleChange={this.toggleRotation} />
    }

    return (
    <div className="hover">
      {conditionalRender}
    </div>
    );
  }
}

ReactDOM.render(
    <Rotator />,
    document.getElementById('root')
);
</script></code>```

答:
<RotateOnClick rotated onClick={this.toggleRotation} />

doesn't mean that component will react to click event. You can't assign event handlers to components!

You should pass handler to component, f.e.

```<code><RotateOnClick rotated clickHandler={this.toggleRotation} />
</code>```

and use this prop in render:

```<code>const RotateOnClick = ( {rotated, clickHandler} ) => {
  if (rotated) {
    return <section onClick={clickHandler}>I'M ROTATED! Click me to rotate again!</section>
  } else {
    return <section onClick={clickHandler}>I'm not rotated. Click me to rotate!</section>
  }
}
</code>```

This way react should be nice again ;)

Body:
<RotateOnClick rotated onClick={this.toggleRotation} />

doesn't mean that component will react to click event. You can't assign event handlers to components!

You should pass handler to component, f.e.

<RotateOnClick rotated clickHandler={this.toggleRotation} />

and use this prop in render:

const RotateOnClick = ( {rotated, clickHandler} ) => {
  if (rotated) {
    return <section onClick={clickHandler}>I'M ROTATED! Click me to rotate again!</section>
  } else {
    return <section onClick={clickHandler}>I'm not rotated. Click me to rotate!</section>
  }
}

This way react should be nice again ;)


问:
Not setting headers for request
I have an Angular 7 app and an API in Java Spring with JTW. The app must at each request in the API send the token, but this is not happening, and so all requests return the 401 error.

app modules

```<code>     ...

        @NgModule

({
      declarations: [
        AppComponent,
        PatientComponent,
        HeaderComponent,
        FooterComponent,
        AlertComponent,
        NotFoundComponent,
        UserRegisterComponent,
        LoginComponent,
        AuthGuardComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        NgSelectModule,
        ReactiveFormsModule,
        HttpClientModule,
        AppRoutingModule,
        NgbModule,
      ],
      providers: [
        {
          provide : HTTP_INTERCEPTORS,
          useClass: AuthInterceptor,
          multi   : true,
        },
      ],
      bootstrap: [AppComponent]
    })

    export class AppModule {

    }
</code>```

AuthInterceptor

```<code>import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GeneralService } from '../_service/general.service';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private generalService: GeneralService) {

    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
            setHeaders: {
                Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJTeXN0ZW0gVXNlciJ9XSwiaXNzIjoiaHR0cHM6Ly9hcGkubmVvZ3JpZC5jb20vIiwiaWF0IjoxNTU4OTgwOTAxLCJleHAiOjE1NTg5OTg5MDF9.vZByXryTI-1wGLYY1bU8DurOF15qlxA7QkdMW5UeM8c')
            }
        });

       console.log(req);
       return next.handle(req);
    }
}
</code>```

Request

```<code>listAll() {
     return this.http.get('http://localhost:8080/api/listAll');
}

async get() {
    let error = null;

    let response = await this.listAll()
    .toPromise()
    .catch(error => error = error);

    console.log(response);
  }
</code>```

Result of console.log(req);

Looks like okay, the authorization and the token is there

The request

Dont pass the token here :c

Erros

OPTIONS 401 Access to XMLHttpRequest
  at'http://localhost:4200' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: It does not have
  HTTP ok status.

I done the  same request with insonmia (passed Authorization and the token) e all is okay, the problem is with the angular request.

答:
First of all, if you haven't done so already you need to provide the interceptor in the root module. Add this to the providers-field:

```<code>{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
</code>```

Second, this could be related to this issue. Make sure you only have one import of HttpClientModule in the entire app.

Also check out this discussion from an issue on the Angular repo. The same behavior can occur if you import some module from a third party package that imports HttpClientModule.

Title: Not setting headers for request

Body:
I have an Angular 7 app and an API in Java Spring with JTW. The app must at each request in the API send the token, but this is not happening, and so all requests return the 401 error.

app modules

     ...

        @NgModule

({
      declarations: [
        AppComponent,
        PatientComponent,
        HeaderComponent,
        FooterComponent,
        AlertComponent,
        NotFoundComponent,
        UserRegisterComponent,
        LoginComponent,
        AuthGuardComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        NgSelectModule,
        ReactiveFormsModule,
        HttpClientModule,
        AppRoutingModule,
        NgbModule,
      ],
      providers: [
        {
          provide : HTTP_INTERCEPTORS,
          useClass: AuthInterceptor,
          multi   : true,
        },
      ],
      bootstrap: [AppComponent]
    })

    export class AppModule {

    }

AuthInterceptor

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GeneralService } from '../_service/general.service';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private generalService: GeneralService) {

    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
            setHeaders: {
                Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJTeXN0ZW0gVXNlciJ9XSwiaXNzIjoiaHR0cHM6Ly9hcGkubmVvZ3JpZC5jb20vIiwiaWF0IjoxNTU4OTgwOTAxLCJleHAiOjE1NTg5OTg5MDF9.vZByXryTI-1wGLYY1bU8DurOF15qlxA7QkdMW5UeM8c')
            }
        });

       console.log(req);
       return next.handle(req);
    }
}

Request

listAll() {
     return this.http.get('http://localhost:8080/api/listAll');
}

async get() {
    let error = null;

    let response = await this.listAll()
    .toPromise()
    .catch(error => error = error);

    console.log(response);
  }

Result of console.log(req);

Looks like okay, the authorization and the token is there

The request

Dont pass the token here :c

Erros

OPTIONS 401 Access to XMLHttpRequest
  at'http://localhost:4200' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: It does not have
  HTTP ok status.

I done the  same request with insonmia (passed Authorization and the token) e all is okay, the problem is with the angular request.

Body:
First of all, if you haven't done so already you need to provide the interceptor in the root module. Add this to the providers-field:

{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }

Second, this could be related to this issue. Make sure you only have one import of HttpClientModule in the entire app.

Also check out this discussion from an issue on the Angular repo. The same behavior can occur if you import some module from a third party package that imports HttpClientModule.


问:
Can I filter a PivotTable's PivotItems with a selection(s) from a listbox in a Userform?
I am creating a dashboard and I'd like the user to select a product group(s) in a listbox of a userform. I'm having trouble getting the selection of the listbox to filter that specific pivottable's pivotitems. I'd like to understand how to filter pivotitems if a user makes one or multiple selections in a listbox.

I've been at this for hours and I can't seem to connect the listbox and pivottable. I've tried different events and tried executing with a cmdbutton to no avail.

```<code>Private Sub lbxProduct_Change()

    Dim PvtTbl As PivotTable
    Dim pvtItm As PivotItem
    Set PvtTbl = PvtPage.PivotTables("pvtYoYChart1")

'   I need the pivottable to change whenever a selection is made in the listbox
'   right now, nothing happens when i make a selection
    For Each pvtItm In PvtTbl.PivotFields("Product Group").PivotItems
        If pvtItm <> Me.lbxProduct.Value Then pvtItm.Visible = False
    Next pvtItm

End Sub
</code>```

I expect the user to click an item in a list box and my pivot table to update instantaneously. Thanks a lot for any advice you guys can provide!!

答:
EDIT: this seems to be more robust</p>

```<code>Dim showMe, pvtItm

showMe = Me.lbxProduct.Value

With ActiveSheet.PivotTables(1).PivotFields("Product Group")
    .PivotItems(showMe).Visible = True '<< first unhide the one we want

    'then hide any others
    For Each pvtItm In .PivotItems
        pvtItm.Visible = (pvtItm.Caption = showMe)
    Next pvtItm
End With
</code>```

Body:
I am creating a dashboard and I'd like the user to select a product group(s) in a listbox of a userform. I'm having trouble getting the selection of the listbox to filter that specific pivottable's pivotitems. I'd like to understand how to filter pivotitems if a user makes one or multiple selections in a listbox.

I've been at this for hours and I can't seem to connect the listbox and pivottable. I've tried different events and tried executing with a cmdbutton to no avail.

Private Sub lbxProduct_Change()

    Dim PvtTbl As PivotTable
    Dim pvtItm As PivotItem
    Set PvtTbl = PvtPage.PivotTables("pvtYoYChart1")

'   I need the pivottable to change whenever a selection is made in the listbox
'   right now, nothing happens when i make a selection
    For Each pvtItm In PvtTbl.PivotFields("Product Group").PivotItems
        If pvtItm <> Me.lbxProduct.Value Then pvtItm.Visible = False
    Next pvtItm

End Sub

I expect the user to click an item in a list box and my pivot table to update instantaneously. Thanks a lot for any advice you guys can provide!!

Body:
EDIT: this seems to be more robust

Dim showMe, pvtItm

showMe = Me.lbxProduct.Value

With ActiveSheet.PivotTables(1).PivotFields("Product Group")
    .PivotItems(showMe).Visible = True '<< first unhide the one we want

    'then hide any others
    For Each pvtItm In .PivotItems
        pvtItm.Visible = (pvtItm.Caption = showMe)
    Next pvtItm
End With


问:
Spark on Yarn IO issues
When scheduling a spark job on yarn is there a possibility to control home any executors are placed on a physical node?

I currently set the spark.executor.cores to 4.

Now when YARN places multiple executors on the same data node it is 4* #numberOfExecutorsOnSameNodethreads trying to read and possibly also swapping as HDFS and the temporary directory of spark reside on the same disks.

So this results in huge issues regarding blocked IO time. Getting SSDs is not an option for now. Are there other things I can try?

答: One quick fix is to increase spark.executor.memory as this might over-allocate memory but prevent too many executors being launched on the same data nodes.

Title: Spark on Yarn IO issues


问:
undefined reference to YAML::LoadFile
I'm trying to use the new version of libyaml-cpp and having linker problems (undefined reference to 'YAML::LoadFile(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)').

I build the library as follows:

```<code>cmake -DBUILD_SHARED_LIBS=ON ..
make
sudo make install
</code>```

Then I include yaml-cpp/yaml.h and call YAML::LoadFile( some_string );. My compilation line is:

```<code>g++ -L/usr/local/lib -I/usr/local/include -lyaml-cpp -std=c++0x -o $@  $^
</code>```

I've tried putting the exact .so file in there as well with no luck. Using nm I can see a LoadFile function in the shared library. I can't figure out now if I'm somehow using the wrong build line or there is something wrong with the library.

答:
Support new yaml-cpp API.</p>

```<code>find_package(PkgConfig)
pkg_check_modules(YAMLCPP REQUIRED yaml-cpp>=0.5)
include_directories(${YAMLCPP_INCLUDE_DIRS})

add_executable(name src/name.cpp)
target_link_libraries(name ${catkin_LIBRARIES}  ${YAMLCPP_LIBRARIES})
</code>```

Title: undefined reference to YAML::LoadFile

Body:
I'm trying to use the new version of libyaml-cpp and having linker problems (undefined reference to 'YAML::LoadFile(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)').

I build the library as follows:

cmake -DBUILD_SHARED_LIBS=ON ..
make
sudo make install

Then I include yaml-cpp/yaml.h and call YAML::LoadFile( some_string );. My compilation line is:

g++ -L/usr/local/lib -I/usr/local/include -lyaml-cpp -std=c++0x -o $@  $^

I've tried putting the exact .so file in there as well with no luck. Using nm I can see a LoadFile function in the shared library. I can't figure out now if I'm somehow using the wrong build line or there is something wrong with the library.

Body:
Support new yaml-cpp API.

find_package(PkgConfig)
pkg_check_modules(YAMLCPP REQUIRED yaml-cpp>=0.5)
include_directories(${YAMLCPP_INCLUDE_DIRS})

add_executable(name src/name.cpp)
target_link_libraries(name ${catkin_LIBRARIES}  ${YAMLCPP_LIBRARIES})


问:
Error importing Google Cloud Bigquery api module in python app
I am trying to import bigquery into my python app from google.cloud import bigqueryand run it locally with dev_appserver.py, but I receive an error:

```<code>File "/Volumes/Budhi/Users/anjas/Projects/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Volumes/Budhi/Users/anjas/Projects/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/Volumes/Budhi/Users/anjas/Projects/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/Volumes/Budhi/Users/anjas/Projects/wordworks/urlworker/main.py", line 9, in <module>
from google.cloud import bigquery
File "/Volumes/Budhi/Users/anjas/Projects/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 999, in load_module
raise ImportError('No module named %s' % fullname)
ImportError: No module named google.cloud.bigquery
</code>```

I have installed bigquery lib with pip:

```<code>pip install --upgrade google-cloud-bigquery
</code>```

Also I've tried installing it as 3d party library into lib directory with no result.

Though it works when I try importing bigquery lib from python shell:

```<code>Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more  information.
>>> from google.cloud import bigquery
>>>
</code>```

Update:

It seems that "google" module installed to project/lib/ folder is clashing with "google" module in google-cloud-sdk/platform/google_appengine.

When trying to do

```<code>from google.cloud import bigquery
</code>```

python looks for the module inside google-cloud-sdk/platform/google_appengine/google not inside project/lib/google/cloud

Any ideas?

答:
I experienced exactly the same error and fixed this by deleting google folder in appengine sdk or you can just try to copy that to your lib folder . This will fix the problem on local development environment but you need to revert this when deploying your service on production.

I could not find a workaround to keep both google-cloud-sdk/platform/google_appengine/google and  project/lib/google/cloud. You need to delete one of them

Body:
I am trying to import bigquery into my python app from google.cloud import bigqueryand run it locally with dev_appserver.py, but I receive an error:

File "/Volumes/Budhi/Users/anjas/Projects/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Volumes/Budhi/Users/anjas/Projects/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/Volumes/Budhi/Users/anjas/Projects/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/Volumes/Budhi/Users/anjas/Projects/wordworks/urlworker/main.py", line 9, in <module>
from google.cloud import bigquery
File "/Volumes/Budhi/Users/anjas/Projects/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 999, in load_module
raise ImportError('No module named %s' % fullname)
ImportError: No module named google.cloud.bigquery

I have installed bigquery lib with pip:

pip install --upgrade google-cloud-bigquery

Also I've tried installing it as 3d party library into lib directory with no result.

Though it works when I try importing bigquery lib from python shell:

Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more  information.
>>> from google.cloud import bigquery
>>>

Update:

It seems that "google" module installed to project/lib/ folder is clashing with "google" module in google-cloud-sdk/platform/google_appengine.

When trying to do

from google.cloud import bigquery

python looks for the module inside google-cloud-sdk/platform/google_appengine/google not inside project/lib/google/cloud

Any ideas?


问:
Blackberry check internet connection on device
How do I check if the Internet connection is ON or OFF on a device?</p>

答:
Call this method, if it returns true then you've got connection. It checks to ensure you have enough battery for internet connection, your 3G or wireless is turned on and then you have enough signal. </p>

```<code>public synchronized static boolean checkConnection() {
        boolean returnVal = true;

    if (DeviceInfo.getBatteryLevel() < 6) {
        returnVal = false;
    }
    else if (RadioInfo.getState() == RadioInfo.STATE_OFF) {
        returnVal = false;
    }
    else if (RadioInfo.getSignalLevel() == RadioInfo.LEVEL_NO_COVERAGE) {
        returnVal = false;
    }

    return returnVal;
}
</code>```

Body:
Call this method, if it returns true then you've got connection. It checks to ensure you have enough battery for internet connection, your 3G or wireless is turned on and then you have enough signal.

public synchronized static boolean checkConnection() {
        boolean returnVal = true;

    if (DeviceInfo.getBatteryLevel() < 6) {
        returnVal = false;
    }
    else if (RadioInfo.getState() == RadioInfo.STATE_OFF) {
        returnVal = false;
    }
    else if (RadioInfo.getSignalLevel() == RadioInfo.LEVEL_NO_COVERAGE) {
        returnVal = false;
    }

    return returnVal;
}


问:
How to use a custom autoloader for a Magento 2 plugin
There is a Magento 2 plugin that need to use few non PSR-4 classes. (It is a code shared with different projects.) It is not possible to use php magento -vvv setup:di:compile because that classes cannot be found. Is there a standard place in Magento 2 to declare custom autoloader for a plugin?

P.S.

I found only possibility to use registration.php, but I am told this is an ugly solution.

答:
The question is too vague to answer specifically, could you elaborate further.

Magento 2 has concept of event observer, may be you can create a custom event observable class


问:
make can't read file written by itself
Makefile:

```<code>SHELL=/bin/bash
.PONY: stamp diff
.DEFAULT_GOAL := all

diff:
    diff <(./stamp.txt) <(docker-compose -f docker-compose.test.yml up)

stamp:
    docker-compose -f docker-compose.test.yml up > stamp.txt

all: stamp diff
</code>```

Output:

```<code>$ make
docker-compose -f docker-compose.test.yml up > stamp.txt
Starting ci-test ... done
diff <(./stamp.txt) <(docker-compose -f docker-compose.test.yml up)
/bin/bash: ./stamp.txt: Permission denied
Starting ci-test ... done
0a1,4
> Attaching to ci-test
> ci-test    | Python 3.7.3
> ci-test exited with code 0
>
\ No newline at end of file
Makefile:26: recipe for target 'diff' failed
make: *** [diff] Error 1

$ ll
total 32
drwxrwxr-x  4 mirror mirror 4096 May 26 07:38 ./
drwxrwxr-x 47 mirror mirror 4096 May 24 15:58 ../
-rw-rw-r--  1 mirror mirror  210 May 26 07:34 docker-compose.test.yml
-rw-rw-r--  1 mirror mirror  103 May 26 07:33 .env
drwxrwxr-x  9 mirror mirror 4096 May 26 07:36 .git/
drwxrwxr-x  3 mirror mirror 4096 May 24 03:29 .idea/
-rw-rw-r--  1 mirror mirror  664 May 26 07:38 Makefile
-rw-rw-r--  1 mirror mirror   92 May 26 07:36 stamp.txt

</code>```

Questions. Why I got /bin/bash: ./stamp.txt: Permission denied and how to fix it?

答:
You have a bug in your makefile. Here is a simplified version

```<code>SHELL=/bin/bash
.PHONY: stamp diff
.DEFAULT_GOAL := all

diff:
        @diff <(./stamp.txt) <(echo "aaa")

stamp:
        @echo > stamp.txt

all: stamp diff
</code>```

This line: @diff <(./stamp.txt) <(echo "aaa") will pass result of execution of ./stamp.txt. I guess, what you are looking for is

```<code>SHELL=/bin/bash
.PHONY: stamp diff
.DEFAULT_GOAL := all

diff:
        @diff <(cat ./stamp.txt) <(echo "aaa")

stamp:
        @echo > stamp.txt

all: stamp diff
</code>```

Title: make can't read file written by itself

Body:
Makefile:

SHELL=/bin/bash
.PONY: stamp diff
.DEFAULT_GOAL := all

diff:
    diff <(./stamp.txt) <(docker-compose -f docker-compose.test.yml up)

stamp:
    docker-compose -f docker-compose.test.yml up > stamp.txt

all: stamp diff

Output:

$ make
docker-compose -f docker-compose.test.yml up > stamp.txt
Starting ci-test ... done
diff <(./stamp.txt) <(docker-compose -f docker-compose.test.yml up)
/bin/bash: ./stamp.txt: Permission denied
Starting ci-test ... done
0a1,4
> Attaching to ci-test
> ci-test    | Python 3.7.3
> ci-test exited with code 0
>
\ No newline at end of file
Makefile:26: recipe for target 'diff' failed
make: *** [diff] Error 1

$ ll
total 32
drwxrwxr-x  4 mirror mirror 4096 May 26 07:38 ./
drwxrwxr-x 47 mirror mirror 4096 May 24 15:58 ../
-rw-rw-r--  1 mirror mirror  210 May 26 07:34 docker-compose.test.yml
-rw-rw-r--  1 mirror mirror  103 May 26 07:33 .env
drwxrwxr-x  9 mirror mirror 4096 May 26 07:36 .git/
drwxrwxr-x  3 mirror mirror 4096 May 24 03:29 .idea/
-rw-rw-r--  1 mirror mirror  664 May 26 07:38 Makefile
-rw-rw-r--  1 mirror mirror   92 May 26 07:36 stamp.txt

Questions. Why I got /bin/bash: ./stamp.txt: Permission denied and how to fix it?

Body:
You have a bug in your makefile. Here is a simplified version

SHELL=/bin/bash
.PHONY: stamp diff
.DEFAULT_GOAL := all

diff:
        @diff <(./stamp.txt) <(echo "aaa")

stamp:
        @echo > stamp.txt

all: stamp diff

This line: @diff <(./stamp.txt) <(echo "aaa") will pass result of execution of ./stamp.txt. I guess, what you are looking for is

SHELL=/bin/bash
.PHONY: stamp diff
.DEFAULT_GOAL := all

diff:
        @diff <(cat ./stamp.txt) <(echo "aaa")

stamp:
        @echo > stamp.txt

all: stamp diff


问:
Retrieve ForeignKey from views before saving in DJANGO
How can i retrieve the foreign key from the form child relationship, save it at the same time that I am saving the parent information on the same page.

I am currently working with two forms, the Parent and the child. The logic of the page is saving the name of a book and the name of the course it contains.

Ex: Book = "Learn data structure and algorithms",
    Language = "Python"

models.py

```<code>class Entity(models.Model):
    entity_name = models.CharField(max_length=250, blank=False)
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')

    class Meta:
        verbose_name_plural = "Entities"

    def __str__(self):
        return self.entity_name

    def get_absolute_url(self):
        return reverse('snippets:password', kwargs={'pk': self.pk})

class Password(models.Model):
    password_name = models.CharField(max_length=12, blank=False)
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name='passwords')

    def __str__(self):
        return self.password_name
</code>```

forms.py

```<code>from django import forms
from snippets.models import Entity, Password

class EntityForm(forms.ModelForm):
    class Meta:
        model = Entity
        fields = ('entity_name',)

class PasswordForm(forms.ModelForm):
    class Meta:
        model = Password
        fields = ('password_name',)
</code>```

views.py

```<code>def password_creation(request):
    if request.method == 'POST':
        form_one = EntityForm(request.POST)
        form_two = PasswordForm(request.POST)
        if form_one.is_valid():
            entity_form = form_one.save(commit=False)
            entity_form.owner = request.user
            entity_form.save()
            password_form = form_two.save(commit=False)
            # HERE : what is the right way to retrieve name from PK
            # owner is not part the Password table field therefore
            # need to be changed to 'password_name'or 'entity'
            # then, how to retrieve the field from the view??
            password_form.owner = request.user
            password_form.save()
            return redirect('snippets:entity')

    else:
        form_one = EntityForm()
        form_two = PasswordForm()

    context = {
        'form_one':form_one,
        'form_two':form_two,
    }

    return render(request, 'snippets/create-password.html', context)
</code>```

I have tried the codes above. The problem is that Django is saving the name of the "Book" but not the name of the "Language" in the database. The system also breaks and return this message : NOT NULL constraint failed: snippets_password.entity_id.

Any help would be much appreciated.

Traceback error

```<code>Traceback (most recent call last):
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/password_change/snippets/views.py", line 67, in password_creation
    password_form.save()
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 729, in save
    force_update=force_update, update_fields=update_fields)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 759, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 842, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 880, in _do_insert
    using=using, raw=raw)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/query.py", line 1125, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1280, in execute_sql
    cursor.execute(sql, params)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: snippets_password.entity_id
</code>```

答:
Your diagnosis is not at all correct. Password doesn't have an owner field, or in fact any relation with User. Its relationship is with Entity, and the error clearly states that it is the entity or that is missing. So you just have to assign the Entity you just created:

```<code>    if form_one.is_valid() and form_two.is_valid():
        entity = form_one.save(commit=False)
        entity.owner = request.user
        entity.save()
        password = form_two.save(commit=False)
        password.entity = entity
        password.save()
</code>```

Note, I added a check that that form_two is valid, and also renamed the objects: the result of calling form.save is not a form, but an instance of the model.

Body:
How can i retrieve the foreign key from the form child relationship, save it at the same time that I am saving the parent information on the same page.

I am currently working with two forms, the Parent and the child. The logic of the page is saving the name of a book and the name of the course it contains.

Ex: Book = "Learn data structure and algorithms",
    Language = "Python"

models.py

class Entity(models.Model):
    entity_name = models.CharField(max_length=250, blank=False)
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')

    class Meta:
        verbose_name_plural = "Entities"

    def __str__(self):
        return self.entity_name

    def get_absolute_url(self):
        return reverse('snippets:password', kwargs={'pk': self.pk})

class Password(models.Model):
    password_name = models.CharField(max_length=12, blank=False)
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name='passwords')

    def __str__(self):
        return self.password_name

forms.py

from django import forms
from snippets.models import Entity, Password

class EntityForm(forms.ModelForm):
    class Meta:
        model = Entity
        fields = ('entity_name',)

class PasswordForm(forms.ModelForm):
    class Meta:
        model = Password
        fields = ('password_name',)

views.py

def password_creation(request):
    if request.method == 'POST':
        form_one = EntityForm(request.POST)
        form_two = PasswordForm(request.POST)
        if form_one.is_valid():
            entity_form = form_one.save(commit=False)
            entity_form.owner = request.user
            entity_form.save()
            password_form = form_two.save(commit=False)
            # HERE : what is the right way to retrieve name from PK
            # owner is not part the Password table field therefore
            # need to be changed to 'password_name'or 'entity'
            # then, how to retrieve the field from the view??
            password_form.owner = request.user
            password_form.save()
            return redirect('snippets:entity')

    else:
        form_one = EntityForm()
        form_two = PasswordForm()

    context = {
        'form_one':form_one,
        'form_two':form_two,
    }

    return render(request, 'snippets/create-password.html', context)

I have tried the codes above. The problem is that Django is saving the name of the "Book" but not the name of the "Language" in the database. The system also breaks and return this message : NOT NULL constraint failed: snippets_password.entity_id.

Any help would be much appreciated.

Traceback error

Traceback (most recent call last):
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/password_change/snippets/views.py", line 67, in password_creation
    password_form.save()
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 729, in save
    force_update=force_update, update_fields=update_fields)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 759, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 842, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 880, in _do_insert
    using=using, raw=raw)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/query.py", line 1125, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1280, in execute_sql
    cursor.execute(sql, params)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: snippets_password.entity_id

Body:
Your diagnosis is not at all correct. Password doesn't have an owner field, or in fact any relation with User. Its relationship is with Entity, and the error clearly states that it is the entity or that is missing. So you just have to assign the Entity you just created:

    if form_one.is_valid() and form_two.is_valid():
        entity = form_one.save(commit=False)
        entity.owner = request.user
        entity.save()
        password = form_two.save(commit=False)
        password.entity = entity
        password.save()

Note, I added a check that that form_two is valid, and also renamed the objects: the result of calling form.save is not a form, but an instance of the model.


问:
Coding Test - allow use of web?
During hiring a .NET web developer I give the candidate a coding test.

I tend to limit the candidate to MSDN installed on the test server - I think it holds everything the candidate needs to complete the task.

I admit, this is not the normal case as I don't expect the candidate to do his work without use of the web.

On the other hand I don't want the candidate to google for a complete example and copy-paste it, i want to evaluate his skills.

The question is do I need to allow free use of the web during the test?

If you think the whole coding test is wrong - I would like to hear alternatives you may have for me.

答:
It all depends what you want out of your successful candidate. I contest the view that knowing how to google makes you a good programmer because the simple fact is that the internet is full of bad examples as well as good ones. You don't really want your codebase to reflect how lucky your googler was on the day he cut and pasted all his code off the web. You want it to demonstrate sound practices, proven methodologies & elegant, efficient solutions that your team understand and are enthusiastic about. Not a jumble of styles that don't resemble each other. There's a wealth of good to be gotten from knowing how to get help from the interweb but real knowledge and ancient wisdom is being lost every day that people who don't really understand what they are doing are given jobs because they appear to solve problems with their ability to "google it".

If you really want to give your candidates access to the web then by all means do, but make the questions hard and scrutinise the results to see if they've picked the first solution they found or if they've picked the best solution to the problem.

OwnerDisplayName: Dror

Title: Coding Test - allow use of web?

OwnerDisplayName: Rob Thijssen

ContentLicense: CC BY-SA 2.5


问:
Imagebutton layout_center_inparent problem
i am having a problem with my imagebutton it does not align right when i specify the centerinparent.

```<code><LinearLayout
        android:layout_width="match_parent" android:layout_marginTop="4dp"
        android:layout_marginLeft="4dp" android:layout_marginRight="4dp"
        android:layout_height="50dp" android:background="#FF0000">

        <RelativeLayout android:layout_height="match_parent"
            android:layout_width="40dp" android:background="#0000FF">
            <ImageView android:id="@+id/imgType"
                android:layout_centerInParent="true" android:layout_width="wrap_content"
                android:src="@drawable/type_text" android:layout_height="wrap_content" />
        </RelativeLayout>

        <RelativeLayout android:layout_height="match_parent"
            android:layout_width="match_parent" android:layout_weight="1">
            <LinearLayout android:orientation="vertical"
                android:layout_height="match_parent" android:layout_width="match_parent">
                <TextView android:layout_width="match_parent"
                    android:textColor="#686a68" android:layout_height="match_parent"
                    android:textSize="15dp" android:text="Manifest : Text"
                    android:ellipsize="end" android:singleLine="true"
                    android:layout_weight="1" />

                <TextView android:layout_width="match_parent"
                    android:textColor="#686a68" android:layout_height="match_parent"
                    android:textSize="15dp" android:id="@+id/txtTitle" android:text="[TEXT NAME]"
                    android:layout_weight="1" android:singleLine="true"
                    android:ellipsize="end" />
            </LinearLayout>
        </RelativeLayout>

        <RelativeLayout android:layout_height="match_parent"
            android:layout_width="60dp" android:background="#00FF00">
            <ImageButton android:src="@drawable/type_text"
                android:layout_height="48dp" android:layout_centerInParent="true"
                android:layout_width="48dp" android:id="@+id/butEdit" />
        </RelativeLayout>

    </LinearLayout>
</code>```

image

As you can see the vertical alignment of the imagebutton is not right.

why is it doing this.

答:
Have you tried running this on the emulator and using the hierarchyviewer tool (in the "tools" folder of the SDK. Click on your app in the list and select "Load View Hierarchy" ) to inspect the elements in question? Have a look at the margins and padding of both the problem control & its container. Also look at the widths of the various components and it may give you a clue as to where the problem is occurring.

Also check that your drawable in @drawable/type_text does not contain any space around it which could be causing a perceived offset (unlikely, I think).

I have occasionally seen odd problems scaling images, so if @drawable/type_text is not 48x48 pixels, try manually scaling the image to the desired size in Photoshop / GIMP / PSP and see if that makes a difference.

Alternatively try using gravity to try to centre your control:

```<code><LinearLayout android:layout_height="match_parent" android:gravity="center"
    android:layout_width="60dp" android:background="#00FF00">
    <ImageButton android:src="@drawable/type_text"
        android:layout_height="48dp"
        android:layout_width="48dp" android:id="@+id/butEdit" />
</LinearLayout>
</code>```

Or maybe:

```<code><LinearLayout android:layout_height="match_parent" android:gravity="center"
    android:layout_width="wrap_content" android:background="#00FF00">
    <ImageButton android:src="@drawable/type_text"
        android:layout_height="48dp" android:layout_width="48dp"
        android:layout_margin="12dp" android:id="@+id/butEdit" />
</LinearLayout>
</code>```

If all else fails, try tweaking the individual android:layout_margin* attributes of the ImageButton to try and force things.

I hope that some of this helps.

Body:
i am having a problem with my imagebutton it does not align right when i specify the centerinparent.

<LinearLayout
        android:layout_width="match_parent" android:layout_marginTop="4dp"
        android:layout_marginLeft="4dp" android:layout_marginRight="4dp"
        android:layout_height="50dp" android:background="#FF0000">

        <RelativeLayout android:layout_height="match_parent"
            android:layout_width="40dp" android:background="#0000FF">
            <ImageView android:id="@+id/imgType"
                android:layout_centerInParent="true" android:layout_width="wrap_content"
                android:src="@drawable/type_text" android:layout_height="wrap_content" />
        </RelativeLayout>

        <RelativeLayout android:layout_height="match_parent"
            android:layout_width="match_parent" android:layout_weight="1">
            <LinearLayout android:orientation="vertical"
                android:layout_height="match_parent" android:layout_width="match_parent">
                <TextView android:layout_width="match_parent"
                    android:textColor="#686a68" android:layout_height="match_parent"
                    android:textSize="15dp" android:text="Manifest : Text"
                    android:ellipsize="end" android:singleLine="true"
                    android:layout_weight="1" />

                <TextView android:layout_width="match_parent"
                    android:textColor="#686a68" android:layout_height="match_parent"
                    android:textSize="15dp" android:id="@+id/txtTitle" android:text="[TEXT NAME]"
                    android:layout_weight="1" android:singleLine="true"
                    android:ellipsize="end" />
            </LinearLayout>
        </RelativeLayout>

        <RelativeLayout android:layout_height="match_parent"
            android:layout_width="60dp" android:background="#00FF00">
            <ImageButton android:src="@drawable/type_text"
                android:layout_height="48dp" android:layout_centerInParent="true"
                android:layout_width="48dp" android:id="@+id/butEdit" />
        </RelativeLayout>

    </LinearLayout>

image

As you can see the vertical alignment of the imagebutton is not right.

why is it doing this.

Body:
Have you tried running this on the emulator and using the hierarchyviewer tool (in the "tools" folder of the SDK. Click on your app in the list and select "Load View Hierarchy" ) to inspect the elements in question? Have a look at the margins and padding of both the problem control & its container. Also look at the widths of the various components and it may give you a clue as to where the problem is occurring.

Also check that your drawable in @drawable/type_text does not contain any space around it which could be causing a perceived offset (unlikely, I think).

I have occasionally seen odd problems scaling images, so if @drawable/type_text is not 48x48 pixels, try manually scaling the image to the desired size in Photoshop / GIMP / PSP and see if that makes a difference.

Alternatively try using gravity to try to centre your control:

<LinearLayout android:layout_height="match_parent" android:gravity="center"
    android:layout_width="60dp" android:background="#00FF00">
    <ImageButton android:src="@drawable/type_text"
        android:layout_height="48dp"
        android:layout_width="48dp" android:id="@+id/butEdit" />
</LinearLayout>

Or maybe:

<LinearLayout android:layout_height="match_parent" android:gravity="center"
    android:layout_width="wrap_content" android:background="#00FF00">
    <ImageButton android:src="@drawable/type_text"
        android:layout_height="48dp" android:layout_width="48dp"
        android:layout_margin="12dp" android:id="@+id/butEdit" />
</LinearLayout>

If all else fails, try tweaking the individual android:layout_margin* attributes of the ImageButton to try and force things.

I hope that some of this helps.


问:
ORA-00926: missing VALUES keyword while using insert into table as select * from in execute immediate
I have two table emp1 and emp2 i want to create emp3 by using emp1 and emp2 all this i need to do plsql to automate code

I tried coding but getting

ORA-00926: missing VALUES keyword ORA-06512: at line 9

```<code>declare
v1  varchar2(2000);
begin
for i in 1..2
loop
v1:='insert into emp3 as select * from emp'||i||'where 1=1;';
execute immediate v1;
end loop;
end;
</code>```

ORA-00926: missing VALUES keyword
ORA-06512: at line 9.
i have a bigger where condition but i just used 'where 1=1' and bigger tables but i need the logic for this thanks!

答:
Dynamic SQL is hard because it turns compilation errors into runtime errors. For instance, in this case you are missed the leading space before the where:

```<code>v1:='insert into emp3 as select * from emp'||i||'where 1=1;';
------------------------------------------------^
</code>```

This means the actual SQL your code attempts to execute is

```<code>insert into emp3 as select * from emp1where 1=1;
</code>```

Which is not valid SQL and that's why you get an error.

The other mistake is we don't need to include the terminating character at the end of the string. So the correct code should be

```<code>v1:='insert into emp3 as select * from emp'||i||' where 1=1';
</code>```

In future you should use include code to display the dynamic statement. You are halfway there by assigning the statement to a variable before executing it. So you just need to log it, which could be as simple as

```<code>dbms_output.put_line(v1);
</code>```

It's a lot easier to spot bloomers in the assembled string than it is to try to interpret the concatenation of boilerplate and variables.

Body:
I have two table emp1 and emp2 i want to create emp3 by using emp1 and emp2 all this i need to do plsql to automate code

I tried coding but getting

ORA-00926: missing VALUES keyword ORA-06512: at line 9

declare
v1  varchar2(2000);
begin
for i in 1..2
loop
v1:='insert into emp3 as select * from emp'||i||'where 1=1;';
execute immediate v1;
end loop;
end;

ORA-00926: missing VALUES keyword
ORA-06512: at line 9.
i have a bigger where condition but i just used 'where 1=1' and bigger tables but i need the logic for this thanks!

Body:
Dynamic SQL is hard because it turns compilation errors into runtime errors. For instance, in this case you are missed the leading space before the where:

v1:='insert into emp3 as select * from emp'||i||'where 1=1;';
------------------------------------------------^

This means the actual SQL your code attempts to execute is

insert into emp3 as select * from emp1where 1=1;

Which is not valid SQL and that's why you get an error.

The other mistake is we don't need to include the terminating character at the end of the string. So the correct code should be

v1:='insert into emp3 as select * from emp'||i||' where 1=1';

In future you should use include code to display the dynamic statement. You are halfway there by assigning the statement to a variable before executing it. So you just need to log it, which could be as simple as

dbms_output.put_line(v1);

It's a lot easier to spot bloomers in the assembled string than it is to try to interpret the concatenation of boilerplate and variables.