How to force Keras VGG16 model show and include detailed layers when being used in new customized models

Question: Summary: How to force keras.applications.VGG16 layers, rather than the vgg model, to show and be included as layers in the new customized models.
Details:

I was building customized models (denoted as model) on top of keras.applications.VGG16 (denoted as conv_base). Specifically, I replace the last dense layers with my own layers.
conv_base = VGG16(weights='imagenet',  # pre-train with ImageNet
          include_top=False,  # exclude the three top layers
          input_shape=(64, 64, 3),
          pooling = 'max')
model = models.Sequential()
model.add(conv_base)
model.add(layers.BatchNormalization())
model.add(layers.Dropout(0.2))
model.add(layers.Dense(256, activation='linear'))
model.add(layers.BatchNormalization())
model.add(layers.Dropout(0.2))
model.add(layers.Dense(1, activation='linear'))

While I can see the layers in conv_base when conv_base.summary(), the new customized model only see the vgg16 layer (type Model), rather than every layer inside vgg16 when model.summary() (shown in the Figure)
conv_base.summary()

    model.summary()

Associated Issues

Although the vgg layers could be accessible by model.get_layer('vgg16').layers, it still occasionally causes other issues, including:
(1) loading weights: it sometimes messes up the weight loading process.
    model.load_weights('~path/weights.hdf5')

(2) building new model: it also causes errors when calling model layers to build new models.
    model2 = Model(inputs=model.inputs, outputs=model.get_layer('vgg16').layers[1].output, name='Vis_Model')

Thoughts:
I could imagine to partially fix this by copy keras.application.VGG layers one by one into a new model. But how to use the pre-trained weights might be a problem. Any other idea would be appreciated.
Answer: EDIT: Based on your comments, here is an updated solution.
You can flatten the nested model by iterating over the layers and appending them to a sequential model. Here is a great solution that I have used for the code below.
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications import VGG16
from tensorflow.keras import layers, Model, utils

#Instantiating the VGG model
conv_base = VGG16(weights='imagenet',  # pre-train with ImageNet
                  include_top=False,  # exclude the three top layers
                  input_shape=(64, 64, 3),
                  pooling = 'max')

#Defining secondary nested model
inp = layers.Input((64,64,3))
cnn = conv_base(inp)
x = layers.BatchNormalization()(cnn)
x = layers.Dropout(0.2)(x)
x = layers.Dense(256, activation='linear')(x)
x = layers.BatchNormalization()(x)
x = layers.Dropout(0.2)(x)
out = layers.Dense(1, activation='linear')(x)

model = Model(inp, out)

#Flattening nested model
def flatten_model(model_nested):
    layers_flat = []
    for layer in model_nested.layers:
        try:
            layers_flat.extend(layer.layers)
        except AttributeError:
            layers_flat.append(layer)
    model_flat = tf.keras.models.Sequential(layers_flat)
    return model_flat

model_flat = flatten_model(model)

model_flat.summary()

Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_10 (InputLayer)        multiple                  0
_________________________________________________________________
block1_conv1 (Conv2D)        (None, 64, 64, 64)        1792
_________________________________________________________________
block1_conv2 (Conv2D)        (None, 64, 64, 64)        36928
_________________________________________________________________
block1_pool (MaxPooling2D)   (None, 32, 32, 64)        0
_________________________________________________________________
block2_conv1 (Conv2D)        (None, 32, 32, 128)       73856
_________________________________________________________________
block2_conv2 (Conv2D)        (None, 32, 32, 128)       147584
_________________________________________________________________
block2_pool (MaxPooling2D)   (None, 16, 16, 128)       0
_________________________________________________________________
block3_conv1 (Conv2D)        (None, 16, 16, 256)       295168
_________________________________________________________________
block3_conv2 (Conv2D)        (None, 16, 16, 256)       590080
_________________________________________________________________
block3_conv3 (Conv2D)        (None, 16, 16, 256)       590080
_________________________________________________________________
block3_pool (MaxPooling2D)   (None, 8, 8, 256)         0
_________________________________________________________________
block4_conv1 (Conv2D)        (None, 8, 8, 512)         1180160
_________________________________________________________________
block4_conv2 (Conv2D)        (None, 8, 8, 512)         2359808
_________________________________________________________________
block4_conv3 (Conv2D)        (None, 8, 8, 512)         2359808
_________________________________________________________________
block4_pool (MaxPooling2D)   (None, 4, 4, 512)         0
_________________________________________________________________
block5_conv1 (Conv2D)        (None, 4, 4, 512)         2359808
_________________________________________________________________
block5_conv2 (Conv2D)        (None, 4, 4, 512)         2359808
_________________________________________________________________
block5_conv3 (Conv2D)        (None, 4, 4, 512)         2359808
_________________________________________________________________
block5_pool (MaxPooling2D)   (None, 2, 2, 512)         0
_________________________________________________________________
global_max_pooling2d_3 (Glob (None, 512)               0
_________________________________________________________________
batch_normalization_4 (Batch (None, 512)               2048
_________________________________________________________________
dropout_4 (Dropout)          (None, 512)               0
_________________________________________________________________
dense_4 (Dense)              (None, 256)               131328
_________________________________________________________________
batch_normalization_5 (Batch (None, 256)               1024
_________________________________________________________________
dropout_5 (Dropout)          (None, 256)               0
_________________________________________________________________
dense_5 (Dense)              (None, 1)                 257
=================================================================
Total params: 14,849,345
Trainable params: 14,847,809
Non-trainable params: 1,536
_________________________________________________________________

I would recommend utilizing an alternate way of summarizing the model.
You can use the utils.plot_model with expand_nested=True for this purpose.
tf.keras.utils.plot_model(model, show_shapes=True, show_layer_names=True, expand_nested=True)

Comment: Thanks for pointing that out. But as described in the question, showing the detailed information is not the only reason to force model layers being included in new models.
Comment: hmm, so as i understand, you have your pretrained model, whose layers you are trying to add into a meta model? would those layers remain non-trainable?
Comment: Please see the associated issue (2). I want to use the layer (inside vgg) in the `model` to build a new model to visualize the feature maps.
Comment: Do help me understand a bit further. Associated issue (2) basically is you trying to use same inputs, but just the first layer of the nested VGG model as a new model?
Comment: do check my updated solution, and let me know if that helps.
Comment: Thanks, Akshay. I think it solves my question for now. I'm just a bit surprised that expand nested is not a function included in keras or tf themselves.But I need to train my model and load weights to build a new model to test. To answer your question: yes, the issue (2) is when I use the same inputs and the first layer of the nested VGG Model to build a new model. I will accept this answer once I do the check.
Comment: @JoeyFueng, glad that worked for you. The reason there is no need for a flatten model, is because keras is itself a very high level framework and the nested model approach is actually quite well executed for finetuning models. In your specific case, the goal is a bit more advance than standard finetuning task, therefore the need for the same.


Rewrite one-line if - "?:" as "??" - to avoid StyleCop warning

Question: How to write a oneliner "if" using "??"
example: How to write the following using "??" instead of "?:"
        SiteSettings = (sitessettings == null)
            ? UnityManager.Instance.Resolve<ISiteSettingsFactory>().Get(100)
            : sitessettings;

Comment: It's always easier when using the correct terms - see [Conditional (`?:`) Operator](http://msdn.microsoft.com/en-us/library/ty67wk28.aspx), and the links to `??` or "null-coalescing operator".
Comment: @user3311522 I didn't vote it down.  I gave all the answers +1 and noticed they were all answered within a minute of each other.  I didn't mean that the question shouldn't have been asked.
Comment: Was this a speed typing test?
Comment: @Kevin, no it is just a question that I couldn't figure out. How did it not meet the question cafeterias that you voted it down?
Answer: Your conditional statement is equivalent to:
SiteSettings = sitessettings
            ?? UnityManager.Instance.Resolve<ISiteSettingsFactory>().Get(100);

Answer: Maybe
SiteSettings = sitessettings ?? UnityManager.Instance.Resolve<ISiteSettingsFactory>().Get(100)

Answer: Try this?
SiteSettings = sitessettings ?? UnityManager.Instance.Resolve<ISiteSettingsFactory>().Get(100)

Answer: SiteSettings  = sitessettings ?? UnityManager.Instance.Resolve<ISiteSettingsFactory>().Get(100);


HDF5 attributes written in C++ are always arrays in python

Question: I am exporting some attributes for an HDF5 file using the C++ API. To simplify some stuff, I have created a writeAttribute function like this:
template <typename AttributeT>
void writeAttribute(const std::string &attrName, const AttributeT &attrValue, H5::Group &group)
{
    std::array<hsize_t, 1> attributeDataSpace{1};
    auto attributeType = H5AttributeType<AttributeT>::predType();
    auto frameAttribute = group.createAttribute(attrName, attributeType, H5::DataSpace{1, attributeDataSpace.data()});
    frameAttribute.write(attributeType, reinterpret_cast<const void *>(&attrValue));
}

The AttributeT is just used to set the size of the datatype
If I now import a file created using this functions with h5py in python, the attributes are always stored in a numpy array of size 1. This is weird, I would have expected to values be stored directly as numbers.
Is this common or am I doing something wrong in the export?
Comment: When I write a scalar to an attribute with `h5py`, the reloaded value is `numpy scalar`, e.g. `np.float64` or `np.int64`.  That's half way between a python scalar and a 0d numpy array.  I don't know what the C++ is doing.
Answer: A scalar attribute uses an empty DataSpace, not one of size 1.
H5::DataSpace attrspace;
H5::Attribute attr = parent.createAttribute(name, attributeType, attrspace);
attr.write(attributeType, &value);


Using Vectors on image xcasset Xcode and Render as Template

Question: someone can give an example to use Vector image (.pdf) on Xcode with option Render: "as template" in the image.xcasset?
Can I programatically set color of the vector image? if yes how?
Thanks,
Omar.
Answer: Yes, you can. When using "as template", the system ignores the image's color information and creates an image stencil based on the alpha values in the image (parts of the image with an alpha value of less than 1.0 get treated as completely transparent). This stencil can then be recolored using tintColor to match the rest of your user interface.
See Apple documentation about template images in UIKitUICatalog.
Comment: Thank you @Ludovic it's work in iOS8.
A little bit tricky to work in iOS7 for images and buttons.


Language settings in Justboil.me

Question: I've set up the Justboil.me plugin to TinyMCE 4. It works great, but I can't make the language files work correctly.
TinyMCE is set to Hungarian.
I've created *hu_HU_dlg.js* and *hu_HU.js*. No luck so far.
Any help is much appreciated.
Answer: It seems like this plugin's language functions are designed for TinyMCE 3.x.
I managed to solve the problem by adding the translation to TinyMCE's language file instead of the plugin's language file. Now it works perfectly.

Language settings in Justboil.me


How to find out where arguments come from to the specific parameter in Java?

Question: I've come to wonder if there is a way to find out which method arguments are returned from.
If you have a few methods in a few classes, perhaps it's easier to figure out where the values come from to the parameter by looking at the method signature.
What if we have very complicated structure of classes? how can we efficiently figure it out? (other than using debugger)
I would appreciate your advice!
For example,
public class Recursion_fig18_9 {
//recursive declaration of method factorial
public static long factorial(long number){
    long result = 1;

    //iterative declaration of method factorial
    for (long i = number; i >=1; i--){
        result *= i;
    }
    return result;
}

//output factorials for values of 0 to 10
public static void main(String[] args) {

    //calculate the factorials from 0 to 10
    for (int counter =0; counter <= 10; counter ++){
        System.out.printf("%d! = %d%n", counter, factorial(counter));
    }
}

(Although this example is quite small structure of class,)
How can I figure out where "number" is returned from in the factorial method?
Comment: this is a very confusingly worded question. What exactly are you looking to do? know where a method's parameters came from before the method call? Know the values of the parameters? please reword to get better answers.
Comment: "which method arguments are returned from"? What does that mean? Could you give an example?
Comment: In general, in your code?  You can't.
Comment: I cannot understand what you are asking here. Your question does not contain grammatically correct english sentences.
Answer: Using your debugger you can set a break point within the method.  When that method breaks, you'll see a stack frame indicating where the call to the method came from and this will help you to trace back the method call to figure out how it was constructed.
Within your code example, place the breakpoint on the return statement so that you can examine the return value before it is returned.
Alternatively, you could use a logger to generate a log file and see how your code steps through it.  You'd be able to back off the logging level after the fact so that you don't have to change code constantly.  More on logging here
Comment: Id say this is a great attempt at deciphering the question lol
Comment: You could use a logger as well.  Lots of logging statements and then view the logs.  The debugger is just one way to do it, but it works.. thanks @RichardBarker :) years of tech support work and a babbelfish do wonders
Comment: @In-youngChoung I really would look into learning to use your IDE's built in debugger -- that will make life a million times easier and your code will look and feel cleaner.
Comment: @OYRM a babbelfish definitely helps. I have to get mine back from Ford but I have not seen nor heard a thing from him in years... I think he got stuck somewhere...
Answer: I am looking back at my old question and I am answering to my own question.
You can figure out easily without using debug which method calls the current method and passes the parameters by

selecting the current method
right mouse click
click Open Call Hierarchy (or Ctrl + Alt + H).


SyntaxError: UNexpected token n

Question: I'm learning how to use the MEAN stack and to practice I'm doing a web that ask you for your name, your email and a course you've done recently. Then it stores the information to a DB. I can't find the error and maybe is an easy one.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var port = process.env.PORT || 8080;
var Schema = mongoose.Schema;
var User = require('./user');

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost');

app.use(morgan('dev'));

var apiRouter = express.Router();
apiRouter.route('/')
.post(function(req, res) {
    var user = new User();
    user.name = req.body.name;
    user.course = req.body.course;
    user.mail = req.res.mail;
    user.save(function(err) {
        console.log(user.name);
        res.json({ message: 'Thank you!'});
    });
}).get(function(req, res) {
    User.find(function(err, users) {
        if (err) res.send(err);
        res.json(users);
    });
    res.json({ message: 'YEAAAAHHHH!'});
});

app.use('/', apiRouter);

app.listen(port);
console.log('Magic happens on port' + port);

And this is the user.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    name: {type: String, required: true},
    course: {type: String, required: true},
    mail: {type: String, required: true}
});

module.exports = mongoose.model('User', UserSchema);

Thank you! :D
EDIT: sorry I forgot to put the error :
SyntaxError: Unexpected token n
at parse (/Users/pingu/Documents/mean_project/node_modules/body-parser /lib/types/json.js:83:15)
at /Users/pingu/Documents/mean_project/node_modules/body-parser/lib/read.js:116:18
at invokeCallback (/Users/pingu/Documents/mean_project/node_modules/raw-body/index.js:262:16)
at done (/Users/pingu/Documents/mean_project/node_modules/raw-body/index.js:251:7)
at IncomingMessage.onEnd (/Users/pingu/Documents/mean_project/node_modules/raw-body/index.js:308:7)
at emitNone (events.js:67:13)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at nextTickCallbackWith2Args (node.js:474:9)
at process._tickCallback (node.js:388:17)

Comment: Could you also post your error?
Comment: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve).
Comment: Yeah sorry  cc/ @The
Answer: Unexpected token is an error message produced by JSON.parse, so you are

telling your server to expect JSON, and
not supplying valid JSON.

This is because you supply a Content-type: application/json header in your request, but you're supplying form-type urlencoded data in your body like name=foobar&course=baz&...
Simply remove the JSON Content-type so your server will parse the body correctly as form data.
Comment: I see. I'm using Postman and this is what I do:
https://gyazo.com/20074774913ddf445538e62c562dcc2b
So should I put "name" instead of name? Because I'm getting an error too.
Comment: @xampla Ah, in that case, your problem is that you are sending `x-www-form-urlencoded` data formatted like `name=foobar&course=....` but for some reason your app is trying to parse it as JSON. You aren't setting the header `Content-Type: application/json` in your request, are you?
Comment: @xampla Yes, don't do that, because you're not sending JSON. If you were doing that, that was causing your problem.
Comment: ok but now when I try to get the users I get this error https://gyazo.com/f03ed9db86a422e7ffa5b63b9bc12fbc related with headers
Comment: @xampla That's because you're calling `res.json` twice, but `res.json` finalizes the HTTP response (so you can't call it twice, because on the second call, the response is already finished.) that's a completely separate issue and is fixed by simply not calling `res.json` more than once per execution of your `.get` handler.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/104321/discussion-between-xampla-and-apsillers).
Comment: @apsillers I have the same problem - when I removed the header - parser don`t see any content (I use multipart/form-data) - request.body is empty.

SyntaxError: UNexpected token n


Inductive proof on r

Question: Let $r, n ∈ N$ and let $r ≤ n$. Give an inductive proof for:
$$ {n+1 \choose r + 1} =  ∑_{k=r}^n {k \choose r} $$
Step 1: We will prove this using induction on n.
n = 1
Step 2: n = k, prove for n = 1.
Am I on the right track? Not sure where to go from there though
Comment: No, in Step 2 you have to assume that your expession for $n$ is correct. In Step 3 you have to show it for $n+1$. In the last step you have to use your result from Step 2.
Answer: The identity you are trying to prove is known as the "Hockey Stick Identity".
The base case should be n = r and not n = 1.
Base Case: n = r
$$\sum^{n}_{k=r}\binom{k}{r}= \sum^{r}_{k=r}\binom{k}{r}= \binom{r}{r}=1=\binom{r+1}{r+1}$$
Inductive Hypothesis:
Assume $$\sum^{n}_{k=r}\binom{k}{r}=\binom{n+1}{r+1}$$ is true for some $n \ge r$.
Inductive Step: n + 1
$$\sum^{n+1}_{k=r}\binom{k}{r}= \sum^{n}_{k=r}\binom{k}{r} + \binom{n+1}{r} $$
$$=\binom{n+1}{r+1} + \binom{n+1}{r}\quad\quad$$
$$=\binom{n+2}{r+1}$$

Inductive proof on r


Cannot write with dir permission 666, but can write with 777

Question: I am using Kali as root user. I did setup an atftp server in a folder (created and owned by root) and gave 666 permission on that folder. But I noticed users get permission denied error while uploading into atftp. Same was happening with FTP server. So to perform some tests, I created a temporary directory, assigned it 666 permission, tried to create a file using unpriviledged user and I got 'Permission denied'. Then I changed the permission to 777 and repeated the same process. This time file got created.
Case 1: 666 permission
root@kali:~/temp# chmod 666 .
root@kali:~/temp# ls -la
total 8
drw-rw-rw-  2 root root 4096 May  7 00:32 .
drwxr-xr-x 21 root root 4096 May  7 00:32 ..
root@kali:~/temp# su temp
$ touch a
touch: cannot touch 'a': Permission denied

Case 2: 777 permission
root@kali:~/temp# chmod 777 .
root@kali:~/temp# ls -la
total 8
drwxrwxrwx  2 root root 4096 May  7 00:32 .
drwxr-xr-x 21 root root 4096 May  7 00:32 ..
root@kali:~/temp# su temp
$ touch a
$ ls -la
total 8
drwxrwxrwx  2 root root 4096 May  7 00:32 .
drwxr-xr-x 21 root root 4096 May  7 00:32 ..
-rw-r--r--  1 temp temp    0 May  7 00:32 a
$

How come adding additional x permission is helping with writing files even when folder had w in both cases?
Comment: What do you really mean 'not suitable'? How do you decide one? And how does it matter in regards to the asked question?
Comment: Kali is not really suitable for general Linux use.
Answer: Execute bit on directories grant permission to enter into it, see this answer

The execute bit (x) allows the affected user to enter the directory, and access files and directories inside

666 has no execute bit whereas 777 does.
Comment: Ah! Completely forgot there's a unix stackexchange too. Thanks for the clarification and links! :)


Memcache on MAMP 1.9

Question: I am trying to make memcache work on MAMP 1.9. In the process I have successfully installed memcached and tested it. But I can't find a way to install memcache.so on my MAMP. Any suggestions.
Thanks
Answer: I had this same problem today. I tried installing the memcache module using PECL and it turns out that PECL is compiling the module to a 64bit architecture. You can check the architecture by:
<code>file /Applications/MAMP/bin/php5.3/lib/php/extensions/no-debug-non-zts-20090626/memcache.so
</code>
My result (working) is now this:
<code>/Applications/MAMP/bin/php5.3/lib/php/extensions/no-debug-non-zts-20090626/memcache.so: Mach-O universal binary with 2 architectures
/Applications/MAMP/bin/php5.3/lib/php/extensions/no-debug-non-zts-20090626/memcache.so (for architecture i386): Mach-O bundle i386
/Applications/MAMP/bin/php5.3/lib/php/extensions/no-debug-non-zts-20090626/memcache.so (for architecture x86_64):       Mach-O 64-bit bundle x86_64
</code>
Previously it was just:
<code>/Applications/MAMP/bin/php5.3/lib/php/extensions/no-debug-non-zts-20090626/memcache.so (for architecture x86_64):       Mach-O 64-bit bundle x86_64
</code>
I followed the steps in Matthias Schmidt's blog. The tutorial is for XAMPP but it should be the same (more or less) with MAMP.
Comment: Thanks. Can't give you 1 up, I don;t have enough points. But your solution worked perfectly.

Memcache on MAMP 1.9


Applescript Xcode to clean, build and install on iPhone device

Question: I'm trying to applescript XCode into building and launching on device. My script is as follows:
tell application "Xcode"
    open "tmp:iphone:myproject:Project.xcodeproj"
    tell project "Project"
        clean
        build
        launch
    end tell
end tell

My project consists of two targets, MainTarget and a SideTarget, the SideTarget is added as a direct dependency of MainTarget. I noticed that when my applescript runs on a pre-cleaned project (removing the build folder) only 65 files are compiled compared to when I press the "Build & Run" button in XCode 130 files are compiled.
The "launch" command in the script seems to be ignored when running the applescript - it simply does not launch on the device. The status in the bottom bar when the script is complete is "Build succeeded". What is the difference between "build" followed by "launch" compared to pressing the "Build & Run" button in the XCode top bar?
The project launches fine on device when building and running through XCode.
My main issue is that I can't get the applescript to launch on device. I do not know where things go wrong. Has anyone successfully scripted XCode to launch on device?
Comment: So I decided to quick fix this by first doing a commandline xcodebuild with the proper options for a device build and then running a applescript like above but without the clean and build commands. The app then nicely launches on device. I'd still like to know the difference between the build command issued via applescript and the build command issued in XCode though.
It appears to me now that one might also just do a GUI script that executes the "Build & Run" in the menubar instead of xcodebuild and launch script that I did.
Answer: I've had this same problem. launch just does not work. You'll have to use debug instead.
Also, debug blocks forever, so invoke it with timeout and catch the timeout error and ignore it.
Answer: build and build and run are two separate commands within Xcode's GUI  (v3.1.4 with build and go (run) and build and debug being the remainder). But the Dictionary for Xcode only shows build as being supported via Applescript. I would say both of these commands are the same as they are in the GUI, and in a perfect AS world we would see build and run in the Dictionary to make it more clear.
My question is whether launch is really building the app or just launching the previously built executable.
Comment: launch only launches the built executable if there is one. If the project is cleaned before launch is executed, it does nothing except exits with a "Could not launch executable" error.


Dual NICs - Dual LANs

Question: Summary: I need to setup a single PC with two NICs - to access a service on LAN 2
NIC 1 - Data network, web access.
Range: 192.168.1.x
Sub: 255.255.255.0
Gateway: 192.168.1.1
NIC 2 - No Web access
Range: 192.168.1.x
Sub: 255.255.255.0
Gateway: 192.168.1.1
What im trying to do:
I need the primary NIC to run as is, with all traffic running through it for LAN and WAN. NIC2 is purely used to telnet into 192.168.1.2 for a data stream.
Problems and question:

Cannot merge the LANs as LAN 1 is for data and LAN 2 is purely for the voice system with a voice switch.
would not like to change address ranges, far too much work involved and business runs 24/7

Q: If I leave NIC 1 as is, working fine and well. If I plug in NIC 2 to LAN 2, can i setup a route so that if 192.168.1.2 is telnetted etc, the PC will select NIC 2 and probe the IP appropriately. Obviously I will ensure that 192.168.1.2 is not used on LAN 1
Comment: possible duplicate of [Configure routing between same network address](http://serverfault.com/questions/286813/configure-routing-between-same-network-address)
Comment: Mike, many thanks for that, exactly what I was looking for and makes complete sense - I would like to accept that answer but I couldn't log into my registered account from work!
Comment: Are you really going to bridge the two networks?
Answer: You should be able to do what you want.
You will need to assign different IP Addresses to NIC1 and NIC2, and ensure that the NIC2 address does not exist on LAN1 and vice-versa, also ensuring that LAN2-HOST1 (192.168.1.2) does not exist on LAN1.
You then need to set the default route to 192.168.1.1 via NIC1, and add a static route for LAN2-HOST1 via NIC2.
You don't say what operating system is on your PC, on windows you can do:
netsh interface ipv4 add route 192.168.1.2/32 "LAN2_INTERFACE_NAME" LAN2_INTERFACE_IP

If you add the keyword
persistent

To the end of that command, the change will be effective across reboots.
You can achieve similar on Linux if required ...

Dual NICs - Dual LANs


Alternativa ao Overlapping de Sprites

Question: Provavelmente, você já viu/jogou algum jogo aonde era possível mudar equipamento/roupa/aparência do seu personagem.
Estou construindo um pequeno joguinho para Android que disponibiliza essa função, e atualmente consigo isso usando a técnica de Overlapping de sprites, que é basicamente ter o personagem, e ter os equipamentos desenhados em uma camada acima. Porém, isso faz com que eu, toda vez que tenha uma ideia nova de equipamento (equipamentos únicos, com características diferentes), eu tenha que desenhar essa peça de equipamento em todas as posições existentes (caminhando, usando magia, pulando..). Também estou começando a suspeitar que isso consome uma enorme quantidade de RAM (que pode ser um problema real em celulares menos potentes).
Dando uma pesquisada, vi um usuário do Reddit sugerindo fazer os modelos em 3d, renderizar e depois usar como se fosse 2d, mas não tenho ideia por onde começar a fazer isso, e gostaria de ver se existem outras alternativas antes de tentar isso.
Gostaria de saber se poderiam me indicar alguma alternativa ao Overlapping, que também me permita criar uma customização eficiente de personagens.
Lembrando que estou em um ambiente 2D
Comment: Para um modelo 3d, não seria apenas trocar a textura do objeto? Ao invés de usar o Overlapping?
Comment: @Matheus Acho que sim, mas meu jogo corre em um ambiente 2D, vou colocar isso mais claramente na pergunta
Comment: Umas das técnicas que uso pra tentar otimizar o desempenho é criar sprites separados para cada situação. No seu caso seria 1 sprite pra cada armadura e suas sequencias de movimentos. Também existe uma outra forma demostrada nesse tutorial: https://www.youtube.com/watch?v=4qE8cuHI93c
Comment: @Matheus sim, eu tenho sprites separadas pra cada peça de armadura/roupa e suas situações. Mas por exemplo, se o jogador equipar  um capacete de um conjunto, um peitoral de outro, uma perneira de outro e uma luva de outro, serão várias sprites em memória :(
Answer: Acredito que há duas possibilidades, uma delas semelhante à que disseste.

Utilizar um plugin gratuito disponibilizado pela Unity Technologies: https://www.assetstore.unity3d.com/en/#!/content/79840
Imitar o que o plugin citado acima faz: criar um modelo 3D de sprites, com as partes do personagem e animar em 3D. Depois colocar as partes de armadura fixada aos respectivos bones(ossos). Podes fazer ossos específicos para movimento de armadura pra ficar mais bonito.

Na Unity só terá que esconder as armaduras conforme a necessidade.
Comment: Muito obrigado, vou dar uma olhada

Alternativa ao Overlapping de Sprites


Programmatically using values from a loaded entity inside a message

Question: I am using Firebase module to send push notifications to a specific mobile user when a webform is submitted.
Below is my custom webform handler:
<?php

namespace Drupal\my_custom_module\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Send Push Notification when a webform submission is submitted.
 *
 * @WebformHandler(
 *   id = "Send Push Notification when a webform submission is submitted",
 *   label = @Translation("Send Push Notification when a webform submission is submitted"),
 *   category = @Translation("Push Notification"),
 *   description = @Translation("Send Push Notification when a webform submission is submitted"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */
class PushNotificationWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get (NID) from text element available on the webform.
    $nidvalue = $values["attached_node"];

    // Load the node.
    $node = \Drupal\node\Entity\Node::load($nidvalue);

    // Get (selected_node_owner) value from the User Entity reference element available on the webform.
    $nodeowner = $values["selected_node_owner"];

    // Get (token) value from the loaded node through the 'field_node_owner' Entity field.
    $usertoken = $node->field_node_owner->entity->field_user_push_token->value;

    // Send the Push Notification.
    // Token is generated by app. You'll have to send the token to Drupal.
    $messageService = \Drupal::service('firebase.message');
    $messageService->setRecipients($usertoken);
    $messageService->setNotification([
        'title' => 'Hello',
        'body' => 'Hello $nodeowner this is your body message',
        'badge' => 1,
        'icon' => 'optional-icon',
        'sound' => 'optional-sound',
        'click_action' => 'optional-action',
    ]);
    $messageService->setData([
        'score' => '3x1',
        'date' => '2019-04-05',
        'optional' => 'Data is used to send silent pushes. Otherwise, optional.',
    ]);
    $messageService->setOptions(['priority' => 'normal']);
    $messageService->send();
    }
}

Everything is working as expected but the 'Variables' are not rendering any values and printed as they are.
Example:
I am expecting the body of the notification message to be something like below (Say the selected_node_owner name is "Elie Masaad"):
Hello Elie Masaad this is your body message

but instead I am getting the below:
Hello $nodeowner this is your body message

Module maintainer gave the below hint:
You should use a Token or simple str_replace for replacing something in string.
Can anyone guide me on how to pragmatically use tokens for my above requirement ?
Comment: I might be misunderstanding but it looks like you're just using single quotes when you mean to be using double quotes? `'body' => "Hello $nodeowner this is your body message"`
Comment: If it returns UID then you should load the user entity to get the name https://drupal.stackexchange.com/questions/187142/how-do-i-get-the-username-from-the-user-id
Comment: Mmmm I just copied the code related to the "Push Notification" from the firebase project page.
Comment: @Clive It was because of using the single quote (') so now it is working but the `$nodeowner = $values["selected_node_owner"];` is returning the **uid** instead of the username. Any idea ?
Answer: As Clive also mentioned use double quotes instead of single quotes to allow the variables to get replaced inside the string
'body' => "Hello $nodeowner this is your body message"

if $values["selected_node_owner"] gives you the UID here is how to get the username
$account = \Drupal\user\Entity\User::load($values["selected_node_owner"]);
$nodeowner = $account->getUsername();


Py.Test : Reporting and HTML output

Question: This is not a technical question at all really. However, I can not locate my .HTML report that is supposed to be generated using:

py.test --cov-report html pytest/01_smoke.py

I thought for sure it would place it in the parent location, or the test script location. Does neither and I have not been able to locate. So I am thinking it is not being generated at all?
Comment: Yes, I had. I'll post here to show it gives no more info than I have already.     `--cov-report=type   type of report to generate: term, term-missing,
                        annotate, html, xml (multi-allowed)`
Comment: Have you tried `py.test --help`?
Answer: I think you also need to specify the directory/file you want coverage for like py.test --cov=MYPKG --cov-report=html after which a html/index.html is generated.
Comment: looks like you need to easy_install the pytest-cov project separately.
Comment: Thanks, hpk42. That did work. The output .html is basically a printout of the script, but. It's a step forward.
Answer: if you do not specify --cov=/path/to/code then it will not generate the html at all.
$ py.test --cov-report html test_smoke.py
== test session starts ==
platform linux2 -- Python 2.7.12, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 rootdir: /home/someuser/somedir, inifile: plugins: xdist-1.22.0, forked-0.2, cov-2.5.1 collected 3 items

test_smoke.py ...                                             [100%]

== 3 passed in 0.67 seconds ==

We can see that there is no message that output was created... However if we specify --cov=...
$ py.test --cov-report html test_smoke.py --cov=/path/to/code
== test session starts ==
platform linux2 -- Python 2.7.12, pytest-3.4.0, py-1.5.2, pluggy-0.6.0
rootdir: /home/someuser/somedir, inifile:
plugins: xdist-1.22.0, forked-0.2, cov-2.5.1
collected 3 items

test_smoke.py ...                                            [100%]

---------- coverage: platform linux2, python 2.7.12-final-0 ----------
Coverage HTML written to dir htmlcov

We now see that there are no stats for tests that passed, instead we see that coverage was written to HTML and sent to the default directory: ./htmlcov
NOTE: if you want a different directory, then affix :/path/to/directory to the output style html -> py.test --cov-report html:/path/to/htmldir test_smoke.py --cov=/path/to/code
If you see a plain html file, this is an indication that your problem is the --cov=/path/to/my/pkg perhaps... are you sure that the code you are testing lives here?
Answer: If you want to generate report in html, give full file path of the test file.
py.test --cov-report html test_file_name.py --cov=/home/ubuntu/venv/python3/lib/python3.7/site-packages/test/

Then start a python server
python -m http.server

Navigate to the html file in htmlcov directory
http://0.0.0.0:8000/venv/python3/lib/python3.7/site-packages/htmlcov/

You will see the report

Py.Test : Reporting and HTML output


Solving the following integral (rational function, cubic over linear)

Question: I'm trying to solve the following integral:
$$
\int\frac{x^3}{(x+2)}\mathrm{d}x
$$
It would seem to me to be a classic integration-by-parts problem, but trying to do that (with $u=x^3$ and $dv=1/(x+2)$ I find myself stuck with the integral:
$$
\int 3x^2\ln(x+2)\mathrm{d}x
$$
which I don't find a way to solve. How should I proceed? Or maybe I got it all wrong from the beginning?
Comment: Do the division first.
Comment: For a rational function, if the degree of the numerator is larger than the degree of the denominator, **Polynomial Division** is the way forward.
Answer: $$\frac{x^3}{x+2}=x^2-2x+4-\frac8{x+2}$$
Thus... in some situations, integration by parts is not the solution. :-)
Answer: If you are trying to compute:
$$\int{\frac{x^3}{x+2}}dx,$$
then you can easily divide $x^3$ by $x + 2$, which yields $x^3 = (x + 2)(x^2 - 2x + 4) - 8$, that is,
$$\frac{x^3}{x+2} = x^2 - 2x + 4 - \frac{8}{x+2};$$
so:
$$\int\frac{x^3}{x+2}dx = \int{(x^2 - 2x + 4)}dx - \int{\frac{8}{x+2}}dx.$$
You solve these integrals and you obtain the solution.
Comment: @mathlove You're right, sorry. Edited :)
Comment: Thank you very much! But I guess I skipped something very basic... How did you do that division?
Comment: @user159527 I did it through the algorithm of polynomial long division: it's very similar to the algorithm used to divide numbers, that long division kids learn in school. It would be odd that you've never heard about that way of dividing polynomials, but anyway, you can check it on Wikipedia if you want :)
Answer: You can always use simple substitution i.e.
$$
u = x+2, du = dx
$$
so
$$
\int \frac{x^3}{x+2} \, d x = \int \frac{(u-2)^3}{u} \, du = \int u^2 - 6 u + 12 - \frac{8}{u}
$$
Comment: A clean solution that you made look extra messy.  This option would look a lot more inviting if you just wrote out the trinomial rather than using the sigma notation.
Comment: @Mike fair point, I personally think the sigma notation is clean but I can see where you're (and the people who upvoted your comment) are coming from.
Answer: In general, an integral has three parts: a polynomial part, a rational part, and a logarithmic part. Depending on the integral, some of these parts may be zero (and hence omitted).
Taking rational functions as our example, consider:
$$\int \frac{x^3}{(x+2)^2} dx = \frac{1}{2} x^2 - 4 x + \frac{8}{x+2} + 12 \log (x+2) + C$$
The logarithmic part is $12 \log (x+2)$, the rational part is $\frac{8}{x+2}$, and the polynomial part is $\frac{1}{2} x^2 - 4x + C$.
In the specific case of rational functions:

The polynomial part is nonzero if and only if the degree of the numerator is greater than or equal to the degree of the denominator. You can find it by doing the polynomial division. The quotient corresponds to the polynomial part and the remainder corresponds to the rest.
The rational part is nonzero if and only if the denominator is not squarefree. You can determine if a polynomial $p(x)$ is squarefree by calculating $\gcd(p(x), p'(x))$. How to actually calculate this is beyond the scope of this answer; ask your favourite search engine about the Hermite reduction as one example.
Anything left over is the logarithmic part, and it can be found by partial fraction expansion on the squarefree part of the denominator. (The Rothstein-Trager method is another option.)

Interestingly, it's not just rational functions that this applies to; integrals over fields which involve more interesting functions can be understood along the same lines, except that there's often a "nonelementary" part left over, where the nonelementary part is typically a standard integral or a simple function for which no elementary integral exists. For example, for some constants $\alpha_{p}$, $\alpha_{r}$, $\alpha_{l}$, $A$ and $B$:
$$\int \frac{\tan^4 x}{(\tan x + 2)^2} dx = \alpha_{p} \tan x + \alpha_{r} \frac{\tan x}{\tan x + 2} + \alpha_{l} \log (\tan x + 2) + \int A \tan x + B\,dx$$
(Don't believe me? Take the derivative of both sides and see for yourself. Use the fact that $\frac{d}{dx}\tan x = 1 + \tan^2 x$.)
If you understand this as a polynomial in $\tan x$ (as opposed to $x$ in the first example), there's a clear "polynomial part", "rational part", "logarithmic part" and "nonelementary part" here.
Comment: "three parts: a polynomial part, a rational part, and a logarithmic part" Actually every polynomial is a rational function hence the tripartition you suggest needs qualifications. "rational polynomials" You probably mean *rational fraction*.
Comment: I just checked on MathWorld. My use of the term "rational polynomial" was semi-standard but apparently discouraged; I changed it to "rational function" as per Did's suggestion.


Proving $-\text{Li}_2(x^{-1}-1)+\text{Li}_2(1-x^{-1})-\text{Li}_2(2 x)+\text{Li}_2(2-2 x)+\text{Li}_2(2) = i \pi \log(x)$ for $x>1/2$.

Question: While working on a physics problem, I have stumbled upon the following identity. For $x>\frac{1}{2}$ note
$$
-\text{Li}_2\left(\frac{1}{x}-1\right)+\text{Li}_2\left(1-\frac{1}{x}\right)-\text{Li}_2(2 x)+\text{Li}_2(2-2 x)+\text{Li}_2(2) \ = \ i \pi \log(x)
$$
where $\mathrm{Li}_2$ is the polylogarithm of order 2.
My physics problem suggests LHS = RHS in the above (and I have confirmed numerically this is true).
How does one prove this? I have not been able to figure out how to use standard polylog identities to show this.
Comment: It would probably become simpler after a differentiation. Then check $x=1$.
Answer: Let
$$f(x)=-\text{Li}_2\left(\frac{1}{x}-1\right)+\text{Li}_2\left(1-\frac{1}{x}\right)-\text{Li}_2(2 x)+\text{Li}_2(2-2 x)+\text{Li}_2(2),$$
$$f(x)=\int \mathrm{d} f(x)=\int\left(\frac{\ln\left(\frac{2x-1}{x}\right)}{x(x-1)}+\frac{\ln(x)}{x(x-1)}+\frac{\ln(1-2x)}{x}+\frac{\ln(2x-1)}{1-x}\right)\mathrm{d}x$$
$$=\int \left(\frac{\ln(2x-1)}{x(x-1)}+\frac{\ln(1-2x)}{x}+\frac{\ln(2x-1)}{1-x}\right)\mathrm{d}x$$
$$=\int\left(-\frac{\ln(2x-1)}{x}-\frac{\ln(2x-1)}{1-x}+\frac{\ln(1-2x)}{x}+\frac{\ln(2x-1)}{1-x}\right)\mathrm{d}x$$
$$=\int\frac{\ln\left(\frac{1-2x}{2x-1}\right)}{x}\mathrm{d}x=\ln(-1)\ln(x)=i\pi\ln(x)+c.$$
Setting $x=1$, we have $c=0$ and the proof is finalized.


How to show associated options with the "Entity select element" when using Webform + Webform Node

Question: I have a webform with an Entity select element. The referenced item is a content type (for example: product). This Product content type has 5 nodes (product 1, product 2 etc.). When viewing the webform it shows a select list with the 5 options (expected).
Now I would like to make use of a node with the webform associated. This content type has the fields Product (entity reference) and webform (to associate the form to the node). When I add 2 products to this node, I would like the webform to only show those 2 products (instead of all) in the Entity select element.
I know there is an option to use a view and tried to use a relationship with contextual filters, but I can't seem to find the right options. Any suggestions?
Answer: Found out how to create this relation. In views I had to add the following settings:

Add relation for desired field.
Add another relation that is referenced by that content.
Add contextual filter NID with a relation to the field selected in step 1.


Reboot Encrypted System Remotely Without Password Query

Question: Are there any standard solutions to rebooting an encrypted system remotely without requiring a password on the next boot?
The system in question is an Ubuntu encrypted with LUKS root partition and an unencrypted boot partition.
The only way I can imagine is to add a randomly generated second key that is based on a file resting on the boot partition and removing it with a start script on system boot.
Would the above approach work?
Or is there a default option that does not require a manual approach?
The only security implication I can think of is that in case the system does fail the boot before starting the first services.
Answer: You could setup an initrd with a minimal sshd in it (dropbear comes to mind), and then connect to it and input the password manually. Or you could look into Mandos. Keep in mind that if someone has physical access to your server, and can replace the boot code without you noticing, then you are game over no matter what
Comment: I like the SSH solution, although that probably requires a lot of tinkering. Mandos is not an option for my setup, since I just have one machine at home. However, I'm not home most of the time and updates, etc. (i.e. me screwing things up =) require a restart at those times as well.
Comment: Ah, look here, adding ssh to my queries I'm getting results of people having the same problem: http://www.howtoforge.com/unlock-a-luks-encrypted-root-partition-via-ssh-on-ubuntu
Comment: That howto also kindly explains the two main possible attacks. Looking at the comments it looks like Ubuntu does something like that by default since 10.04?
Comment: Yes, Ubuntu 11 + 12 has most of the stuff integrated, I just tried it successfully with the following instructions: http://www.thomas-krenn.com/de/wiki/Voll-verschl%C3%BCsseltes-System_via_SSH_freischalten They are in German but should be understandable with Google Translate or sth. like that. The described problems and bugs in the scripts also apply to the newest (12) Ubuntu version.


JNA does not support C++11?

Question: The following code will terminate during calling c_func() on Java. It does not occur if tuple is not used. I guess JNA does not support C++11 because tuple type is introduced on it. Is my guess correct?
C++ code
#include <tuple>
#include <map>

int c_func(){
    static std::map< std::tuple<float, float, float>, float> mapOfTuple;
    return 1;
}

Java code
...
public interface CLibrary extends Library {
    public static final String JNA_LIBRARY_NAME = "test";

...
}

public static void main(String[] args) {
    c_func();
}

Comment: Totally unrelated to your question, but you should seriously consider whether a map keyed by floating-point numbers will behave as you want it to (given the inherent inaccuracy of floating point math).
Comment: @ak79 : It's unreliable bordering incorrect in any language.
Comment: @Angew The differences between my tests and yours: 1) I used a literal 1.0 assigned to a variable, rather than the input routines, and 2) I assigned the results to a variable, rather than just using a cast.  Still, I don't think it matters much, because I agree with you in principle: if the values are the results of floating point calculations, and no particular precautions have been taken to ensure that they line up well, then two expressions which result in the same value if done over the reals may result in different values in floating point arithmetic.
Comment: Thank you @Angew. Is using a map with float key commonly recognized as a bad practice in C++?
Comment: That's language-independent, really. It depends on your application - do you mind `1.f / 10.f` and `0.1f` being [distinct keys?](http://ideone.com/qs9HgM)
Comment: @Angew On any reasonable implementation, those two will be the same, once they are coerced to an actual `float` (which they will be as a key to a `std::map`).  The issue can occur in more complex expressions, however; you can even get differences between debug and optimize builds for the same expression.  (But you need intermediate results for the issue to occur; thus, at least three terms.)
Comment: @JamesKanze Added a cast, it [still differs](http://ideone.com/XnWFot).
Comment: @Angew I assigned them to floating point variables (as would happen if they were keys), and they come out the same.  More to the point, if they don't come out the same, there's a serious issue with regards to the quality of the implementation.  It's when you get more complicated expressions that things can happen (because C++ allows the calculations to be done with greater precision than float).
Comment: @JamesKanze I wanted to avoid potential constant folding, that's why I used the input routine. But I believe our results differing has actually wonderfully demonstrated that imprecisions are likely :-)
Comment: @Angew If they differ with the cast, I'd say that this was due to an error in your implementation.  (Do avoid constant folding, I just assigned the values to non-const variables, and didn't optimize.)  My reasoning: `1.0f` and `10.0f` can be represented exactly.  A quality input routine (or compiler converting string literals) will create the closest possible representation of `0.1f`.  Since `1.0f` and `10.0f` are exact, the results of `1.0f / 10.0f` should be the closest possible representation of `0.1f` _once coerced to a `float`_.  And the key of a map will be coerced.
Comment: @Angew Just out of curiousity: what implementation are you using?  I've tried with 32 bit Visual Studios and 64 bit g++ (both on Intel, under Windows), and `f1 / f2 == f3` returns true, even without the cast (which sort of surprises me, because Intel normally uses extended precision in the expressions, so the results of `f1 / f2` would have greater precision than `f3`).
Comment: @JamesKanze I just used whatever's on Ideone, I believe that's g++ 4.8.2
Answer: JNA works at the interface level, not the implementation level. It doesn't even know that you used C++11 in c_func. However, your C++ function probably has a dependency on a C++11 runtime library, which may be the problem.

JNA does not support C++11?


Try and catch method not working java

Question: I have been trying to get my try/catch set up to work but it doesn't seem to run either the try section or the catch section and just returns the default value of the variable.
I had it working before and cant remember what it was that i changed because I haven't touched it for a while
i can include the data file if requested
Any ideas?
package firsttry;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class csv{
    public double speed(int tool , int block){
    double blockbreak = 0;
    //Define file variable thing

    //runs through file
    try {
        String filename = "data.csv";
        File file = new File(filename);
        Scanner inputStream = new Scanner(file);
        //runs through each line as long as there is something next
        while (inputStream.hasNext()){
            String data = inputStream.next();//gets a whole line
            String[] values = data.split(",");
            if (values[1].equals(block)){
                blockbreak = Double.parseDouble(values[tool + 2]);
                System.out.println(blockbreak);
                blockbreak = 4;
            }
        }

    }catch (Exception e) {
        System.out.println("ERROR");
        blockbreak = 4;
    }
    return blockbreak;

}

public String name(int block){
    String filename = "data.csv";
    File file = new File(filename);

    //runs through file
    try {
        Scanner inputStream = new Scanner(file);
        //runs through each line as long as there is something next
        while (inputStream.hasNext()){
            String data = inputStream.next();//gets a whole line
            String[] values = data.split(",");
            if (values[1].equals(block)){
                //int speed = Integer.parseInt(values[tool]);
                String blockname = values[0];
                return blockname;
            }
        }
    } catch (FileNotFoundException e) {
    }
    return filename;
}

}

Comment: which method? which default value is it returning? Imagine you didn't know the code, would the question be easy to answer? Have you stepped though the code using a debugger? What does it do?
Comment: Is there data in `data.csv`?
Comment: Also the code is very improperly indented, so I'm less inclined to take you seriously since you haven't taken the simplest steps to solve the problem on your own.  Edit your question to Include the exact error you receive below the code.
Comment: This calls for breakpoints.  You can see what the value is and how many times it loops etc.  Perhaps your conditions are not working...
Comment: Yes there is data in there about 25 lines
Comment: Anyone offer any solutions? I have fixed all the problems that you have highlighted in the question
Comment: We could try contacting James Gosling and informing him that his try/catch is broken, as you say in the title.  Use e.printStackTrace() in your catch block, and then include the error message you get below your code.
Comment: I see that you have an Sysout statement inside the if case, that is the only place where the value of `blockbreak` is changed. Is that sysout statement printed?

If not, use the Eclipse or IntelliJ debugger and go through the code line by line, check the values of variables at each step and may be you will see what the problem is.
Answer: Don't have enough reputation to comment, so writing here.
You should modify your if condition in each function() written above,
if (values[1].equals(block)){
}

It will not give you an output you are expecting.
Comparing string with int is incorrect, for example
 System.out.println("1".equals(1));  -> will print false

Answer: You are observing that the default value is being returned.
Does this mean that your function returns 0? (As initialized here? double blockbreak = 0;)
If that is the case, you should look into what happens in your loop.
This if statement looks dodgy.
if (values[1].equals(block))
What do you expect to happen?
Also, please post a line that matches the if statement and a line that doesn't, and the expected output from the function.
Answer: Possible reasons why you only get the default value:

data.csv is an empty file.
values[1].equals(block) returns false. (Which will always be the case since you're comparing a String to an int.)
catch (FileNotFoundException e) doesn't do anything, so you wouldn't know if the file was not found.

To elaborate on point 2, consider values[1].equals(String.valueOf(block))
Answer: Let me suggest some troubleshooting tips.
Write a unit test so you can easily run this repeatedly.
Put a System.out.println into the code in a few places to see which places it hits and when (On small problems this is often easier than debugging if you don't typically debug, I often have it print out a letter at the beginning of any code that comes after a decision point like if, loop and try/catch constructs.)
Print out the value of each line as you read it.
Print the value of blockbreak
I would guess your loop or the if statement aren't executing.  Printing some values will tell you this quickly.
Also, if you truly intend Blockbreak to be assigned a value, try NOT assigning a default value of 0 in the beginning.  This will stop you from compiling until you have assigned a value in every possible program flow path--a very handy feature (May not help in your case because of the way your while loop is structured, but it's a useful habit not to assign initial values until you need to in Java).

Try and catch method not working java


Does $\sum_{i\neq j} \text{Cov}(X_i, X_j) = 0$ imply $\text{Cov}(X_i, X_j) = 0, \,\forall\,i \neq j$

Question: Let $X_1, \dots, X_n$ be random variables, for some integer $n > 2$.  Then, $$\text{Var}\left(\sum_{i=1}^nX_i\right) = \sum_{i=1}^n \text{Var}(X_i) + \sum_{i \neq j} \text{Cov}(X_i, X_j) $$
There is a natural interest in the special case when the $X_i$ are such that $$\sum_{i \neq j} \text{Cov}(X_i, X_j) = 0 \quad \Leftrightarrow \quad \text{Var}\left(\sum_{i=1}^nX_i\right) = \sum_{i=1}^n \text{Var}(X_i)$$
Now, the condition $$\text{Cov}(X_i, X_j) = 0, \,\forall\,i \neq j\tag{1}$$ clearly implies the condition $$\sum_{i\neq j} \text{Cov}(X_i, X_j) = 0 \;.\tag{2}$$
Is the converse true?
Alternatively, can someone give me an example where $(2)$ holds but $(1)$ fails?
(My guess is that $(2)$ does not imply $(1)$, since I realize that, in general, $\sum_1^{n>1} a_i = 0$ does not imply that all the $a_i$ are zero, but I can't readily come up with an example of this general fact when the summands are the terms $\text{Cov}(X_i, X_j),\;(i\neq j)$.)
(My remaining questions are moot if, contrary to what I suspect, $(2)$ does imply, and is therefore equivalent to, $(1)$.)
When the random variables $X_1, \dots, X_n$ are described as being "uncorrelated", does this mean that they satisfy $(1)$, or just that they satisfy $(2)$?
Lastly, I've often seen the term "pairwise uncorrelated", which clearly means that $(1)$ holds, is there a name for the condition in $(2)$ (when $(1)$ is not assumed)?
Answer: Consider three random variables with covariance matrix
$$\left[\begin{matrix}1 & a & 0\\a & 1 & -a\\ 0 & -a & 1\end{matrix}\right]$$
which has leading principal minors $1$, $1-a^2$, and $1-2a^2$ and thus is positive definite
(as all covariance matrices must be) provided that $\vert a\vert < \frac{1}{\sqrt{2}}$.
Obviously this satisfies
$$\sum_{i\neq j} \text{Cov}(X_i, X_j) = 0 \tag{2}$$ but not
$$\text{Cov}(X_i, X_j) = 0, \,\forall\,i \neq j.\tag{1}$$
As noted in my (now-deleted) comment, correlation is a pairwise property and so $n$ random variables are uncorrelated means that $(1)$ holds: every pair of distinct random variables is uncorrelated. As far as I know, there is no name for random variables for which $(2)$
holds but $(1)$ does not. In the example provided, the random variables are not
significantly correlated in the sense that $Y$ "fails to explain" more than half
the variance of either $X$ or $Z$.
Comment: +1. Generally, such covariance matrices can be derived from matrices $\mathbb{\Sigma}$ having these properties: (1) they are positive semi-definite symmetric Real matrices and (2) the kernel of $\mathbb{\Sigma}^*$ is nontrivial, where $\mathbb{\Sigma}^*$ is obtained by zeroing out the diagonal elements of $\mathbb{\Sigma}$. For correlation matrices like yours, which have unit diagonals, this means $\mathbb{\Sigma}$ has $1$ for an eigenvalue. Sure enough, your matrix--with eigenvalues $1$ and $1\pm a\sqrt{2}$--qualifies.


Yii CGridView Not Updating With JS Call

Question: What I'm trying to accomplish with the following code is when the 'roleSelector' dropdown is changed, it fires a ajax request to the 'admin/permissions/assign' url which in turn, sets a state for the role selected.  I need it as a state so I can use it in the CLinkColumn column within the CGridView.  However, when the success javascript fires and the grid view reloads the content of the cgridview does not update, while the summary does (it shows the number of results that should be in the grid view).
I'm not sure why either but this seems to be the only CGridView that I've had to use the 'ajaxUrl' property in order for the $.fn.yiiGridView.update() call to work.  If I omit the url property it returns an error stating it could not find the url which I don't recall having to set in the past.
The Action:
class AssignAction extends CAction {

    // Used in the url to determine if we are assigning or revoking permissions
    const FLAG_APPLY = 'apply';
    const FLAG_REVOKE = 'revoke';

    // Identifier to the user saved state of the role selected
    const STATE_ROLE = 'roleSelected';

    public function run($name='', $action='') {

        // Get the role the user selected
        if (isset($_POST['roleSelector'])) {
            $roleSelected = $_POST['roleSelector'];
            Yii::app()->user->setState(self::STATE_ROLE, $roleSelected);
            Yii::app()->end();
        }

        // Get all of the roles from the system
        $roleSelected = Yii::app()->user->getState(self::STATE_ROLE);
        $roles = AuthItem::model()->byTypes(array(CAuthItem::TYPE_ROLE))->findAll();
        $authItemProvider = new CActiveDataProvider('AuthItem', array(
            'criteria' => array(
                'condition' => (!$roleSelected) ? '1=0' : '',
            ),
            'pagination' => array(
                'pageSize' => 30,
            )
        ));

        $this->getController()->render('assign', array(
            'roles' => $roles,
            'roleSelected' => $roleSelected,
            'authItemProvider' => $authItemProvider,
        ));
    }
}

The View:

Assign Permissions

        <?php
            $roleList = CHtml::listData($roles, 'name', 'label');
            echo CHtml::dropDownList('roleSelector', $roleSelected, $roleList, $htmlOptions=array(
                'empty' => 'Select a Role',
                'ajax' => array(
                    'type' => 'POST',
                    'url' => $this->createUrl('/admin/permissions/assign'),
                    'data' => array('roleSelector' => 'js: $(this).val()'),
                    'success' => 'js: function() { $.fn.yiiGridView.update("GridView-AuthItem") }',
                ),
            ));
        ?>

        <?php
            $this->widget('zii.widgets.grid.CGridView', array(
                'id' => 'GridView-AuthItem',
                'dataProvider' => $authItemProvider,
                'columns' => array(
                    'label:properCase',
                    'typeName:properCase',
                    'description',
                    'bizrule',
                    array(
                        'class' => 'CLinkColumn',
                        'label' => 'Assign',
                        'urlExpression' => 'array("/admin/permissions/assign",
                        "name" => $data->name,
                        "action" => (AuthItemChild::model()->byParentAndChild(Yii::app()->user->getState(AssignAction::STATE_ROLE), $data->name)->find()
                            ? AssignAction::FLAG_REVOKE : AssignAction::FLAG_APPLY),
                        )',
                        'htmlOptions' => array(
                            'style' => 'text-align: center',
                        ),
                        'linkHtmlOptions' => array(
                            'class' => 'button gray icon i_stm_edit',
                        ),
                    ),
                ),
            ));
        ?>

Answer: I forgot I left the table tags in there since it originally was a CListView.  Removing those tags seems to have fixed my problem.

Yii CGridView Not Updating With JS Call


Which type of wood for an electric guitar should one choose for rock/metal music?

Question: I know that the type of wood affects the sound of an electric guitar, but I don't understand in what way (or which type of wood has what effect).
Which wood(s) should I choose if I want to play rock or metal music? Do I have to use different woods for the body and the fretboard of an electric guitar?
Comment: I could go on writing a very long answer explaining the differences but in the end there's only one answer. *Choose the configuration you like.* My tip would be to start with a mahogany body (popular choice) and explore from there.
Comment: Maybe re-wording to something along the lines of "What are the most popular wood types for electric guitar in rock/metal music and why?" would help keep this open. I'd say start with mahogany but you also should find what's right for *you*.
Comment: Mahogany is really popular, perhaps most famously with Gibson's solid body guitars, and is known for its 'warm' tone. Adler is also fairly common and has a more 'balanced' tone (descriptive words are pretty subjective). Lower end woods like poplar and basswood are pretty common in Chinese and Korean-built instruments, and can work just as well, but I believe both are soft and relatively easy to damage. Maple might be the most common neck wood across the industry and tends to be pretty bright, which can be offset by rosewood fingerboards.
Comment: Also, **great** info from Warmoth on the subject: http://www.warmoth.com/guitar/bodies/options/bodywoodoptions.aspx
Comment: Focus on the tone that you want, then go from there. And when you do finally get there, get the grade of wood and type of wood that will get you that tone. All said and done, with enough GAS syndrome, you can get just about any tone out of any wood, only depend$ on how far you are willing (or capable) to go.
Answer: There is no specific combination of wood types that make a guitar more or less appropriate for rock/metal music.
Essentially all combinations can and have been used to good effect by various artists in these genres.
Other features besides the type wood are likely to have a more significant effect on the the behaviour of the guitar; at most you could argue that "this scale length and neck + these pickups + this amp configuration" could be marginally modified by selecting "this wood combination".  This also leaves aside the idea that high-quality vs. low-quality wood of a given type can have an effect as large as shifting from one wood type to another.
Answer: Electric guitar sound is affected, among other things, by the way the wood absorbs the vibrations of the strings. The sustain and the brightness of the sound comes, in part, from the wood used. Availability, workability and visual properties are also important.
The most popular rock guitars are Fender Stratocaster and Gibson Les Paul. Strat bodies are usually made of ash, alder or poplar and Les Paul bodies are mostly made of mahogany with a maple top. Strat necks are made of maple while Les Paul necks may use mahogany or maple. Frets can be pressed directly on a maple neck or the neck may be laminated with a harder wood like rosewood or ebony.
As you can see, the woods used on these two guitars are quite different, yet they're both very popular choices for rock music. So, it's about what sound you want to obtain.
Custom guitar parts supplier Warmoth has some good information on so called tonewoods and neck woods.


Specification of nested random effects in glmer

Question: I have a doubt about nesting random effects. I'm using R with the lme4 package and, in particular, the glmer function with binary family. I will describe the data first --
In this experiment, people answer sentences related to some verbs with a binary answer. They are given a prompt to formulate their answer, and this prompt is one of the variables. Each sentence appears with one different prompts (of two) to different participants in a randomised manner.
Two more binary variables are present and they're bound to the verb: verbs can be divided in two different ways: two classes, A and B, and two types, Y and X. But a verb cannot appear in both A and B forms depending on the context, so each item/verb in the experiment only appears in one of the two variants. That means that verb1 is always A and X, verb2 is always B and X and so on.
My doubt is how to define the random effect for verb/item, knowing that the data does not allow for each item to appear in both conditions of class and type. I thought nesting would solve it in this way:
Answer ~ Prompt + Class + Type +
         (Prompt + Class + Type | participant) +
         (Prompt | verb:class) + (Prompt | verb:type)

But I'm not totally sure if it makes sense. My questions are:

Is it okay to include verb as a random effect nesting it twice (within class and withing type), as in the formula above?
Is it possible that this definition of the random effects would "absorb" the fixed effects, reducing their estimates or significance?
Does it make sense to include verb as a random effect at all, given that each verb can only appear in one class and one type?
Answer: Class and Type are fixed effects. They should not be grouping variables for random intercepts. participant and verb are crossed, so I would start with the model:
Answer ~ Prompt + Class + Type + (1 | participant) + (1 | verb)

and then consider adding random slopes, if supported by the underlying theory and the data.


What do the laws of cricket say about declaring an inning in a limited overs cricket match?

Question: I know that there is no need of declaring a match with limited overs format.
Even the world record total has been chased on that day itself.
But, my question is, what do the laws of cricket say about declaring an inning in a limited overs cricket match?
Comment: I'm trying to think why you would want to. Two possible reasons: 1. Heavy rain is forecast and you don't want to give the opposition the chance to win on Duckworth-Lewis; 2. The competition ladder uses run rate as a tie-breaker and you only have slow scoring batsmen to come in. Any others?
Comment: This has actually happened.  I can't find the article at the moment, but an English county side declared their one-day innings after one over, losing the match but preserving their run rate.  The rules were changed shortly thereafter.
Comment: @PeterEisentraut The incident you are very likely thinking of is the [1979 Benson & Hedges Cup match](http://www.espncricinfo.com/ci/engine/current/match/142289.html) in which Somerset declared at 1 for 0 after 1 over, thus allowing Worcestershire an easy win but denying them the chance to surpass Somerset's already superior net run rate. Somerset were [disqualified from the competition](http://www.espncricinfo.com/magazine/content/story/405598.html) as a result.
Comment: @chimp I don't think reason 1 is very likely; giving up overs (and hence scoring fewer runs) will only give the opposition a lower score to chase, and hence give them a lower D/L par score. However, a related reason could be that with heavy rain forecast, the captain is concerned that insufficient overs will be played to constitute a game under the competition's regulations, and so declares. Reason 2 is quite possible (see my previous comment). Note that all reasons are a result of external factors (such as the competition rules) rather than the game itself as defined by the Laws.
Answer: The Laws of Cricket say that you can declare any innings, no matter what the agreed length is.
ODIs and Twenty20 Internationals, however, are playing under the ICC Playing Conditions, which modify the Laws of Cricket. Both the ODI and the T20I playing conditions say "Law 14 shall not apply." (Law 14 is Declaration and Forfeiture.) The analogous domestic limited-overs competitions are usually playing under very similar rules.
So no, in practice, you cannot declare in a limited-overs game.
If you really wanted to stop batting, all the batsmen could retire or time out, but that would go down differently in their personal statistics.
Answer: I can't think of the specifics, but I seem to remember this scenario from many years ago.  In the old Gillette cup it was 60 overs a side and there was a reserve day if the match could not be completed in one day due to the weather or bad light.  In the first round the first class counties usually played minor counties and won handsomely most of the time.  In this match the 1st class county batted first and knocked up a very substantial score.  The minor county, in reply, struggled and by the time play was halted for the day needed something like 160 to win off 5 overs with 2 wickets in hand.  Theoretically this could be done, but the minor county, being in a hopeless position, declared to effectively concede the match.
Comment: It also came about in England after a declaration during a Benson and Hedges group game by Somerset to ensure they progressed to the knock out stages. See no 1 in [this article](https://sports.stackexchange.com/questions/7465/in-which-game-was-a-limited-overs-innings-declared-to-prevent-an-opponent-from-q/7467#7467)
Comment: This also happened in a 1975 South African Gillette cup [match](https://www.espncricinfo.com/series/8767/scorecard/544580/natal-vs-south-africa-african-xi-1st-round) between Natal and SA-XI where Alan Barrow reached 202 on debut, after which Natal promptly declared (and won).


viewWillAppear is not called when add child controller to table view cell

Question: When I add child view controller to table view cell, it looks like viewWillAppear for child view controller is not called, only viewDidAppear.
Table View Controller method:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCellWithIdentifier("ShopInfoTableViewCell", forIndexPath: indexPath) as! ShopInfoTableViewCell
    self.addChildViewController(self.shopInfoViewController, toView: cell.containerView)
    return cell
}

View Controller category method:
- (void)addChildViewController:(UIViewController *)childController toView:(UIView *)view
{
    [self addChildViewController:childController];
    [view addSubview:childController.view];
    [childController didMoveToParentViewController:self];

    [childController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top);
        make.bottom.equalTo(view.mas_bottom);
        make.left.equalTo(view.mas_left);
        make.right.equalTo(view.mas_right);
    }];
}

Any ideas why it happen?
Answer: - (void)addChildViewController:(UIViewController *)childController toView:(UIView *)view
{
    [self addChildViewController:childController];

    //add this
    [childController beginAppearanceTransition:YES animated:YES];
    [view addSubview:childController.view];
    [childController endAppearanceTransition];

    [childController didMoveToParentViewController:self];

    [childController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top);
        make.bottom.equalTo(view.mas_bottom);
        make.left.equalTo(view.mas_left);
        make.right.equalTo(view.mas_right);
    }];
}

Likewise, you should call this when you want to disappear
    [childController beginAppearanceTransition:NO animated:YES];
    [childController.view removeFromSuperview];
    [childController endAppearanceTransition];

Answer: To @adali answer I would change:
[childController beginAppearanceTransition:YES animated:YES];
by:
[childController willMoveToParentViewController:self];
So at the end it would be:
[self addChildViewController:childController]; //add the child on childViewControllers array
[childController willMoveToParentViewController:self]; //viewWillAppear on childViewController
[self.containerView addSubview:childController.view]; //add childView whenever you want
[childController didMoveToParentViewController:self]; //viewDidAppear on childViewController

And very important, all this must be called once the viewController that contains the children has already executed its viewWillAppear life cicle function
Comment: Apple's documentation on `willMoveToParentViewController:` states:  "addChildViewController: will call [child willMoveToParentViewController:self] before adding the
  child". So, this should not be needed.


Why choose a Dirichlet distribution in Latent Dirichlet Allocation (LDA)?

Question: I am studying Latent Dirichlet Allocation (LDA), but I don't have much knowledge of stochastic processes.
From Wikipedia:

LDA assumes the following generative process for a corpus $D$
consisting of $M$ documents each of length $N_{i}$:

Choose $\theta _{i}\sim \operatorname {Dir} (\alpha )$, where $i\in \{1,\dots ,M\}$ and $\mathrm {Dir} (\alpha )$ is a Dirichlet distribution with a symmetric parameter $\alpha$

My question is this: why Dirichlet distribution? Are there any particular properties of this distribution that make it suitable for this model?
Answer: Two properties that make the Dirichlet distribution a suitable default choice are:

Flexibility: it has full support on the parameter space which is the set possible values of the K-dimensional vector of probabilities, which must sum to 1 (i.e., the K-1 dimensional simplex)

Computational tractability: the Dirichlet distribution is the conjugate prior for the multinomial likelihood and can be analytically integrated out to obtain tractable marginal likelihood and Pólya urn schemes (see Dirichlet multinomial) this allows to have tractable algorithms to perform Bayesian inference (e.g., it gives tractable full conditional distribution in a Gibbs-sampler).

Point 2. is explained with more technical details in the Wikipedia page linked in your question in the Section Aspects of computational details or in the paper: Blei, David M., Ng, Andrew Y. and Jordan, Michael I. "Latent Dirichlet Allocation". Journal of Machine Learning Research (2003)


Spring Data REST Joined Inheritance Issue

Question: I have a Spring Data Repository over a single JPA entity.  This entity is subclassed via joined inheritance.
Spring Data REST seems to have a problem interpreting this structure, at least automatically.  Or maybe I'm misunderstanding the usage of Inheritance.JOINED
Any request for any entity with an Event returns the following:
{
    cause: null,
    message: "Cannot create self link for class com.foo.event.SubEvent! No persistent entity found!"
}

Maybe I'm asking too much for this project to know how to handle this, but is there a workaround that would group all of my Events under the same /events? Maybe even allowing me to filter on type?
I've left the basics of the application structure below.
Event.java
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({
  @Type(value = SubEvent.class),
  ...
})
...
public class Event {
    @Id
    private long id;
    ...
}

SubEvent.java
@Entity
public class SubEvent extends Event {
    private String code;
    ...
}

EventRepository.java
@RepositoryRestResource(path = "events")
public interface EventRepository extends PagingAndSortingRepository<Event, Long> {
    ...
}

Comment: The issue isn't only with `JOINED` inheritance type. The same issue is found when using `SINGLE_TABLE`.
Answer: I think you're missing using Discriminator to let JPA understand what subclass to use for a given object (how does it know otherwise?).
I tend to use abstract classes for table-per-subclass hireachies, so here's an example adapted to that for you:
Event.java
@Entity
@DiscriminatorColumn(name = "type")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Event {
    @Id
    @GeneratedValue
    public Long id;

    public String type;
}

SubEvent.java
@Entity
@DiscriminatorValue("subevent")
@PrimaryKeyJoinColumn(name = "event_id")
public class PeeringService extends Service {
    private String code;
}

With the above code, you'll notice something odd however - when generating the resource path for one of these objects, it assumes you have a Repository for each subclass, and generates something like this:
{
  "type" : "subevent",
  "code" : "bacon",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8081/subEvents/1"
    },
    "peeringService" : {
      "href" : "http://localhost:8081/subEvents/1"
    }
  }
}

This is pretty easy to fix though, you just need to add the following annotation to your base class:
@RestResource(path = "events")

And it will generate the resource paths you'd expect!
Hope this helps :)
Comment: this solution with spring-data-rest 2.5.1 doesn't work
Comment: Thanks for the heads up, I'm running `2.4.4.RELEASE` (the version recommended by the current `spring-boot`).

I'll give it a shot on the newer version next week :)
Comment: in my case seems that only one (non-deterministic) of the repositories (with the same path) handled the request, this resulted in a rest controller delivering only part of the rows (only the ones the repository was responsible for). Let me know how your test goes, I'm keen to know the solution.
Answer: I tried you classes out in a simple spring boot project nd they didn't give me any problems and I couldn't reproduce the issue you are having. However,  search on the error message you describe gives a couple of posts that suggest that you need to create a SubEvent repository even f you don't use it, and that the problem arises in more complicated projects, such as using REST.
Reference: Cannot create self link for class X. No persistent entity found.
How to choose MappingContext in spring-data-jpa (2x) + spring-rest-webmvc?
So, try adding a SubEvent repository:
interface SubEventRepository extends CrudRepository<SubEvent, Long> {
}

Answer: I think the problem has nothing to do with JPA, but it is rather a circular serialization problem. As you haven't shown your entity, I can only suppose that the Subevent entity has a relationship to another (Sub)Event and that one Subevent references itself, which leads to the problem. Of course it is also possible that the relationship is not a direct one, but rather through some other entity classes, like SubEvent -> EntityG -> Event.
To solve it, simply use a DTO in which you map only all the fields of the SubEvent except those that produce the circular dependency.
Comment: Hey Andrei.  The entities are probably just named poorly for this exercise, as I just scrubbed them for the sake of the question.  There are in fact no circular references in this model :-/
Comment: In order to find the cause and eventually to make sure there is no circular reference begin to comment out JPA-mapped property one-by-one, till you find what is causing the problem.
Answer: I tried out quite a few options and none worked as expected, and always had problem on one point (links generation, repository mapping, url mapping and so on).
Even for separated repositories (one for each subtype) I had no success. My "dirty as hell but working" solution was to post-process links for all subtypes using an implementation of ResourceProcessor. This implementation basically replaced the subtype name with the type name on each link present on the resource.
Additionally a RelProvider was introduced to handle properties names of different types.


Are Neural Networks with a softmax output layer considered Probabilistic Classifiers?

Question: For example, is ResNet for image classification a type of Probabilistic Classifier when we take into account the softmax at the end of the network as part of the network? My intuition points in that direction, given that it estimates the probability of an image belonging to each possible class, and then takes the class with the highest probability.
Comment: What is your definition of a probabilistic classifier?
Comment: I would define as: A probabilistic classifier is a type of classifier that, in order to determine the class of a given sample, calculates the probability of the sample belonging to each  possible class and then assigns the sample to that class with the highest probability.
Answer: The softmax output of a neural network classifier can be considered a probabilistic classification, however the probabilities will often not be well calibrated. Well calibrated means that the estimated probability matches our confidence in the prediction - in other words, the classifier is well calibrated it makes the correct prediction 80% of the time it predicts class A with 80% probability (and similarly for all other probabilities).
If calibrated probabilities are required then a post-classification calibration step can be used. This essentially rescales the softmax output to adjust the probabilities to more closely match the expected distribution.
Reference: How and When to Use a Calibrated Classification Model with scikit-learn by Jason Brownlee.


SCOM agent install fails with error 0x80070002

Question: When trying to install Windows agents in SCOM 2012 R2, the task fails with error 0x80070002. Looking in the agent install log at C:\Program Files\Microsoft System Center 2012 R2\Operations Manager\Server\AgentManagement\AgentLogs I see "OmAgentFunctions::InstallOmAgentMsi : MsiInstallProductW() failed. HResult: 80070643".
Answer: Instead of trying to push the agent from the SCOM server, try running the agent installer manually from the target server. The installer GUI may give you a better idea of why the install failed.
In my case the problem was that the System Center Advisor Agent was installed, which can not co-exist with the SCOM agent.


Host Header DNS Problem - Requires FlushDNS

Question: I've inherited a DNS server setup and I'm trying to configure our local intranet properly.
Forgive me if this is simple, but I'm missing something in our configuration.
We're hosting trying to host 2 separate intranet sites on 1 IIS 6 Server (Server 2003).
Site 1: http:// servername (ipaddress:80)
Site 2: http:// production (ipaddress:8080) - host header value of 'production' in IIS and DNS A Record set up points to the correct server.
Everything works properly for a while, but unexpectedly we lose the ability to type in 'production' - and get a DNS resolver error.
If we cmd > ipconfig /flushDNS, everything works perfect back to normal.
Why would each of the clients be losing the reference and then not allowing us to connect for a period of time? (nslookup always finds the correct server, then it works fine again)
Is there any way to create a "static" reference without changing the HOSTS file on each PC (not practical).
Thanks in advance for your help!
Comment: Also, I noticed that our "secondary dns" entry is a 126.96.36.199 (because we're only running one DNS server). Though nslookups are all going through our local server, could the PC be requesting the record from Verizon, and because its local not getting a response, then storing an incorrect record?

Any ideas? Thanks again for the help.
Answer: An A record is a static reference unless you're allowing dynamic updates. The fact that a /flushdns seems to fix the problem is a bit of a puzzler, as all that command does is clear the cache. Clearing the cache as a fix doesn't really make any sense unless the records themselves are changing (which is usually why one would want to flush the cache).
If this is a Windows DNS server, do you by chance have scavenging turned on? Failing that, are you running more than one DNS server and the zone is expiring?
You might experiment by turning off the dns cache on a couple of workstations to see if they then fail at the same time as the caching workstations.
"net stop dnscache" will deactivate caching until the next reboot.
edit:
internally, we used to run about a 100 different A records all pointing to essentially the same resource which was an absolute nightmare if you ever had to change the resolution unless you were 100% sure of your sed/awk skills. Now I insist that they either utilize the standards that I've built, or a CNAME that points to the standards based A record. An example:
<code>$ORIGIN mydomain.com.
socketalpha             CNAME   alpha.socket
socketbeta              CNAME   beta.socket
socketdvlp              CNAME   dvlp.socket
socketsystems           CNAME   systems.socket
alpha                   A       192.168.125.12
alphasecure             CNAME   alpha.secure
alphasecured            CNAME   alpha.secured
$ORIGIN secure.mydomain.com.
alpha                   A       192.168.125.32
beta                    A       192.168.125.33
dvlp                    A       192.168.125.31
systems                 A       192.168.125.30
</code>
The standard I push is ... You could probably find a more efficient method for your own setup, but using this means that if, for example, the server/virtual for alpha.socket.mydomain.com changes, I don't have to change multiple A records.
Comment: I'm going to try stopping the DNS Cache for a while on a few of the pcs, see if that isolates the problem. I'll let you know what I come up with.
Comment: Disabling the DNS Cache worked. Any suggestions on troubleshooting from there? Can't imagine that best practice would be to permanently disable DNS Cache... Thanks again.
Comment: are dynamic updates allowed to that zone? turn cache back on and then make sure you know what the records are resolving to when it breaks with nslookup or dig. We had what might have been a similar situation cause a 12 hour outage one day when the (at the time) backup Windows Oracle servers got restarted and refreshed the name that we were using to hit the production boxes. We now have a service level DNS zone where ALL "service" names are placed that is specifically a primary/secondary zone, not ADI.
Comment: also, is "production" a CNAME to "servername"? your OP indicates that it is an A record, but if they're pointing to the same box, I would suggest switching that to a CNAME
Comment: Thanks for your help! Interesting that you mentioned switching to CNAME, never occurred to me but might have done the trick. I've updated as such and haven't run into problems for a while (though I'm only switching DNS Cache back on now).

I'll keep you posted but my assumption is that is the fix.
Thanks again.
Answer: Are you running WINS?  That may help resolve NetBIOS names.
You also might look at setting your search domain on clients, which I believe will automatically append your domain name to your server name in order to create a FQDN which your DNS server might resolve more easily.
Answer: If your using Host Headers isn't the idea to use the same port i.e port 80
Comment: Yes, actually, my mis-communication. I'm using the Host Header on port 80, and also binding 8080 so I can get there directly (since host header is only working half the time)


How many points does the surface $\mathbb{H}$ defined with the stated expression contain in $\mathbb{F}^5_{p^2}$?

Question:
How many points does the surface $$\mathbb{H} = \{(z_1,z_2,z_3,z_4,z_5)\in \mathbb{F}_{p^2}: z_1 - z_1^p - z_2z_3^p + z_2^pz_3 - z_4z_5^p + z_4^pz_5 = 0\}$$  contain in $\mathbb{F}^5_{p^2}$? Furthermore, is it possible to determine how many lines does that surface contain?

What might be of a help is that if we have $\Phi(a) = a^p$, then for $\mathbb{F}_{p^2}$ the map $\Phi$ is an involution, e.g. $\Phi^2(a) = a$.
Comment: Yes, Marcus, thank you, $\mathbb{F}$ was a typo.
Comment: I'm still thinking about the lines... :-) Did you figure that part out?
Comment: Not yet, but I figured out why $tr(x^p) = tr(x)$. It is just that $x^{p(p^{n-1})}=x^{p^n}=x$. On the problem about lines, I am thinking of looking at specific equations for lines and see whether they lie in that surface. I cannot think of a better approach for now. I do not have sufficient background, however.
Comment: I asked the follow-up question about the lines in a separate question : http://math.stackexchange.com/questions/1360933/how-do-we-define-how-many-lines-lie-on-a-given-hypersurface-in-mathbbf-qn
Answer: Counting the number of points is simple.  I need the trace function
$$
tr:\Bbb{F}_{p^n}\to\Bbb{F}_p, x\mapsto x+x^p+x^{p^2}+\cdots+x^{p^{n-1}}
$$
and its properties
$$
\begin{aligned}
tr(x+y)&=tr(x)+tr(y)\\
tr(x^p)&=tr(x)
\end{aligned}
$$
that hold for all $n$ and all $x,y\in\Bbb{F}_{p^n}.$
Point count follows from the following standard fact.
Proposition. The equation
$$
z^p-z=u
$$
has $p$ solutions $z\in\Bbb{F}_{p^n}$ if $tr(u)=0$, and no solutions otherwise. Furthermore, if $z=\xi$ is one solutions, all the solutions are
of the form $z=\xi+a, a\in\Bbb{F}_p$.
Let us rewrite your equation in the form
$$z_1^p - z_1 =- z_2z_3^p + z_2^pz_3 - z_4z_5^p + z_4^pz_5.\qquad(*)$$
Consider the right hand side. For any choices of $z_2,z_3\in \Bbb{F}_{p^2}$ we have
$$
\begin{aligned}
tr(-z_2z_3^p+z_2^pz_3)&=-tr(z_2z_3^p)+tr(z_2^pz_3)\\
&=-tr(z_2z_3^p)+tr(z_2^{p^2}z_3^p)\\
&=-tr(z_2z_3^p)+tr(z_2z_3^p)=0,
\end{aligned}
$$
because, as you pointed out, $z_2^{p^2}=z_2$.
Similarly
$$
tr(- z_4z_5^p + z_4^pz_5)=0
$$
for all $z_4,z_5\in \Bbb{F}_{p^2}$. So for all values of $z_2,z_3,z_4,z_5$ ($p^8$ choices) the trace of the right hand side of $(*)$ vanishes. Therefore the Proposition implies that the equation has exactly $p^9$ solutions $(z_1,z_2,z_3,z_4,z_5)\in\Bbb{F}_{p^2}^5.$


How to force rebase before each delivery?

Question: We set policy to force rebase before delivery if any baseline is recommended.
But we would not recommend baseline everyday. We will do it once in 2 weeks like that.
In between recommend baseline duration, people are often facing issues in functionality as they have not taken latest code base.
Is there any way to force to rebase before each delivery? [irrespective of baseline is recommended or not].
Is it recommended practice to rebase before each delivery?
Answer: It is recommended to rebase before delivering, and it usually is based on the "recommended baseline" mechanism.
So even if you said "irrespective of baseline is recommended or not", I would still suggest you look at "this deliver policy: 'Rebase before delivery'".

This policy (Require development stream to be based on the project's recommended baseline(s) prior to delivery) requires developers to rebase their source streams to the target stream current recommended baselines before they deliver work to the target stream.
  The policy can be set per project or per stream, for interproject and intraproject deliver operations.
The goal of this policy is to have developers build and test their work in their development work areas against the work included in the most recent stable baselines before they deliver to the target stream. This practice minimizes the amount of merging that developers must do when they perform deliver operations.

From UCM policies:

If you don't recommend baselines on the parent stream, then you need to define a preop deliver trigger (as in this thread):
cleartool mktrtype -ucm -preop deliver_start -execwin ccperl "\\share\path\to\script.pl" -c "Check if rebase activity exists before delivering" rebase_before_delivery@\pvob

With script.pl a script which would list all activities of the current stream, checking if the latest activity is a rebase.xxx one.
http://www.ibm.com/developerworks/forums/message.jspa?messageID=14116547

Comment: @Samselvaprabu: the "recommend baseline" is the native mechanism allowing you to force developers to rebase before delivering. You can recommend as often as you like, but you shouldn't create and recommend baselines every 5 minutes. If they are recommended, they should pass a certain level of quality (at least compile).
Comment: So only way to force rebase before delivery is to recommend baseline and set the policy.Isn't it? How frequent we can recommend baseline? we should recommend only stable deliverable, isn't it?