问:
An alternative to List.Contains for custom classes
I'm trying to do a pathfinding with A* and made a class "Node".

The point is that i have a list of Nodes and i need to know if a Node is already in the list, but List.Contains doesn't work.

Btw, i need to compare the world position which is in a variable inside Node and i don't know how to override the List.Contains to compare with that variable.

Edit: Added the Node class trying to implement Equals and HashSet

```<code>using System.Collections;
using UnityEngine;
using System.Collections.Generic;

public class Node {

public Node parentNode;

public int nodeX;
public int nodeY;
public Vector2 nodePosition;

public bool state;

public int gCost;
public int hCost;
public int fCost;

public Node(int x, int y){
    nodeX = Mathf.RoundToInt(x);
    nodeY = Mathf.RoundToInt(y);
    nodePosition = new Vector2(nodeX, nodeY);
}

public void SetCost(Node end){
    if(parentNode != null){
        gCost =(int) parentNode.gCost + 10;
    }
    else{
        gCost = 10;
    }

    hCost =(int) (Mathf.Abs(nodeX - end.nodeX) + Mathf.Abs(nodeY-end.nodeY));
    fCost =(int) gCost + hCost;
}

public bool Equals (Node other){
    if(other == null){return false;}
    if(this.nodePosition == other.nodePosition){return true;}
    else{return false;}

}

public override bool Equals(Object other){
    if(other == null){return false;}
    if(other is Node){
        return this.Equals(other);
    }
    else{
        return false;
    }
}

public override int GetHashCode(){
    return nodeX ^ nodeY;
}
</code>```

答: For the open set, you should be using a priority queue.  For the closed set, just add a property HasBeenVisited to every node.  You don't need a List for A*.

Body:
I'm trying to do a pathfinding with A* and made a class "Node".

The point is that i have a list of Nodes and i need to know if a Node is already in the list, but List.Contains doesn't work.

Btw, i need to compare the world position which is in a variable inside Node and i don't know how to override the List.Contains to compare with that variable.

Edit: Added the Node class trying to implement Equals and HashSet

using System.Collections;
using UnityEngine;
using System.Collections.Generic;

public class Node {

public Node parentNode;

public int nodeX;
public int nodeY;
public Vector2 nodePosition;

public bool state;

public int gCost;
public int hCost;
public int fCost;

public Node(int x, int y){
    nodeX = Mathf.RoundToInt(x);
    nodeY = Mathf.RoundToInt(y);
    nodePosition = new Vector2(nodeX, nodeY);
}

public void SetCost(Node end){
    if(parentNode != null){
        gCost =(int) parentNode.gCost + 10;
    }
    else{
        gCost = 10;
    }

    hCost =(int) (Mathf.Abs(nodeX - end.nodeX) + Mathf.Abs(nodeY-end.nodeY));
    fCost =(int) gCost + hCost;
}

public bool Equals (Node other){
    if(other == null){return false;}
    if(this.nodePosition == other.nodePosition){return true;}
    else{return false;}

}

public override bool Equals(Object other){
    if(other == null){return false;}
    if(other is Node){
        return this.Equals(other);
    }
    else{
        return false;
    }
}

public override int GetHashCode(){
    return nodeX ^ nodeY;
}


来源: stackexchange

问:
R tidyr::spread duplicate error
I have the following data:

```<code>ID        AGE SEX   RACE    COUNTRY VISITNUM    VSDTC   VSTESTCD    VSORRES
32320058    58  M   WHITE   UKRAINE 2   2016-04-28       DIABP          74
32320058    58  M   WHITE   UKRAINE 1   2016-04-21       HEIGHT        183
32320058    58  M   WHITE   UKRAINE 1   2016-04-21       SYSBP         116
32320058    58  M   WHITE   UKRAINE 2   2016-04-28       SYSBP         116
32320058    58  M   WHITE   UKRAINE 1   2016-04-21       WEIGHT        109
22080090    75  M   WHITE   MEXICO  1   2016-05-17       DIABP          81
22080090    75  M   WHITE   MEXICO  1   2016-05-17       HEIGHT        176
22080090    75  M   WHITE   MEXICO  1   2016-05-17       SYSBP         151
</code>```

I would like to reshape the data using tidyr::spread to get the following output:

```<code>ID AGE SEX  RACE    COUNTRY VISITNUM    VSDTC    DIABP SYSBP WEIGHT HEIGHT
32320058    58  M   WHITE   UKRAINE 2   2016-04-28   74   116   NA   NA
32320058    58  M   WHITE   UKRAINE 1   2016-04-21   NA   116   109   183
22080090    75  M   WHITE   MEXICO  1   2016-05-17   81   151   NA   176
</code>```

I receive duplicate errors, although I don't have duplicates in my data!

```<code>df1=spread(df,VSTESTCD,VSORRES)
</code>```

Error: Duplicate identifiers for rows (36282, 36283), (59176, 59177), (59179, 59180)

答:
I assume that I understand your question</p>

```<code># As many rows are identical, we should create a unique identifier column

# Let's take iris dataset as an example

# install caret package if you don't have it

install.packages("caret")

# require library
library(tidyverse)
library(caret)

# check the dataset (iris)
head(iris)

# assume that I gather all columns in iris dataset, except Species variable

# Create an unique identifier column and transform wide data to long data as follow

iris_gather<- iris %>% dplyr::mutate(ID=row_number(Species)) %>% tidyr::gather(key=Type,value=my_value,1:4)

# check first six rows

head(iris_gather)
# using *spread* to spread out the data

iris_spread<- iris_gather %>% dplyr::group_by(ID) %>% tidyr::spread(key=Type,value=my_value) %>% dplyr::ungroup() %>% dplyr::select(-ID)

# Check first six rows of iris_spread

head(iris_spread)
</code>```

ContentLicense: CC BY-SA 3.0

Title: R tidyr::spread duplicate error

Body:
I have the following data:

ID        AGE SEX   RACE    COUNTRY VISITNUM    VSDTC   VSTESTCD    VSORRES
32320058    58  M   WHITE   UKRAINE 2   2016-04-28       DIABP          74
32320058    58  M   WHITE   UKRAINE 1   2016-04-21       HEIGHT        183
32320058    58  M   WHITE   UKRAINE 1   2016-04-21       SYSBP         116
32320058    58  M   WHITE   UKRAINE 2   2016-04-28       SYSBP         116
32320058    58  M   WHITE   UKRAINE 1   2016-04-21       WEIGHT        109
22080090    75  M   WHITE   MEXICO  1   2016-05-17       DIABP          81
22080090    75  M   WHITE   MEXICO  1   2016-05-17       HEIGHT        176
22080090    75  M   WHITE   MEXICO  1   2016-05-17       SYSBP         151

I would like to reshape the data using tidyr::spread to get the following output:

ID AGE SEX  RACE    COUNTRY VISITNUM    VSDTC    DIABP SYSBP WEIGHT HEIGHT
32320058    58  M   WHITE   UKRAINE 2   2016-04-28   74   116   NA   NA
32320058    58  M   WHITE   UKRAINE 1   2016-04-21   NA   116   109   183
22080090    75  M   WHITE   MEXICO  1   2016-05-17   81   151   NA   176

I receive duplicate errors, although I don't have duplicates in my data!

df1=spread(df,VSTESTCD,VSORRES)

Error: Duplicate identifiers for rows (36282, 36283), (59176, 59177), (59179, 59180)

Body:
I assume that I understand your question

# As many rows are identical, we should create a unique identifier column

# Let's take iris dataset as an example

# install caret package if you don't have it

install.packages("caret")

# require library
library(tidyverse)
library(caret)

# check the dataset (iris)
head(iris)

# assume that I gather all columns in iris dataset, except Species variable

# Create an unique identifier column and transform wide data to long data as follow

iris_gather<- iris %>% dplyr::mutate(ID=row_number(Species)) %>% tidyr::gather(key=Type,value=my_value,1:4)

# check first six rows

head(iris_gather)
# using *spread* to spread out the data

iris_spread<- iris_gather %>% dplyr::group_by(ID) %>% tidyr::spread(key=Type,value=my_value) %>% dplyr::ungroup() %>% dplyr::select(-ID)

# Check first six rows of iris_spread

head(iris_spread)


问:
Angular Animation. Updating animation state after an event
Say I have the following in my components html

```<code><div *ngFor='let box of boxes' [@fade_out]='off'>
 <h1> Author: {{ box.author }} </h1>
 <button (click)='delete(box)'>Delete box</button>
</div>
</code>```

and in the controller:

```<code>delete(box: any){
//opens an mddialog that confirms deletion
dialog.open(...).afterClosed().subscribe( response => {
 //do something
}
</code>```

I want to be able to dynamically update the [@fade_out] state for (and only for) the particular div that the user clicked on AFTER receiving a response from the dialog box.

If I bind [@fade_out] to a boolean in the controller, all of the other boxes will trigger the same animation and therefore all fade out.

If I bind [@fade_out] to a function, I'm lost as to how to trigger that specific function for that specific div after I get the response.

Can anyone suggest a way for me to make this work?

答:
So the answer was right there and I failed to see it. As per the docs, I simply linked the animation to a property of the object.

```<code><div *ngFor='let box of boxes' [@fade_out]='box.state'>
 <h1> Author: {{ box.author }} </h1>
 <button (click)='delete(box)'>Delete box</button>
</div>
</code>```

I then pass the data to the dialog and then in the subscription to afterClosed() I can update the specific box state

```<code>dialog.open(...).afterClosed().subscribe( response => {
 box.state = response
}
</code>```

Body:
Say I have the following in my components html

 Author: {{ box.author }}

 <button (click)='delete(box)'>Delete box</button>

and in the controller:

delete(box: any){
//opens an mddialog that confirms deletion
dialog.open(...).afterClosed().subscribe( response => {
 //do something
}

I want to be able to dynamically update the [@fade_out] state for (and only for) the particular div that the user clicked on AFTER receiving a response from the dialog box.

If I bind [@fade_out] to a boolean in the controller, all of the other boxes will trigger the same animation and therefore all fade out.

If I bind [@fade_out] to a function, I'm lost as to how to trigger that specific function for that specific div after I get the response.

Can anyone suggest a way for me to make this work?

Body:
So the answer was right there and I failed to see it. As per the docs, I simply linked the animation to a property of the object.

<div *ngFor='let box of boxes' [@fade_out]='box.state'>
 <h1> Author: {{ box.author }} </h1>
 <button (click)='delete(box)'>Delete box</button>
</div>

I then pass the data to the dialog and then in the subscription to afterClosed() I can update the specific box state

dialog.open(...).afterClosed().subscribe( response => {
 box.state = response
}


问:
Troubleshooting Python YouTube-download script
I have been using youtube-dl for a while now with no issues, but now I keep getting an error saying

ERROR: unable to download video (format may not be available) for all videos.

What may the issue be?

答:
Works with the most current version of yt-dl, which can be found here:

http://rg3.github.com/youtube-dl/download.html

ContentLicense: CC BY-SA 2.5


问:
How to override `--prefix` option in NASM per symbol?
I'm compiling C code with GCC and assembling some x86 code with NASM on Windows.

Now, GCC by default (and I haven't been able to find an option to change this) prepends an underscore _ to all external symbol names (and expected names).

I need this assembly code to work with GCC on both Windows and Linux and would like to avoid hacks as much as possible (and code duplication; I had separate .s files for Windows/Linux at first).

I found out about (and used) the --prefix flag in NASM. Now for some symbols I'd like NASM to treat them as without the leading underscore (exact situation right now is that I need to reference the entry point in a linker script without the leading underscore). Hence the question here on how to override, per symbol, the --prefix/--postfix flags of NASM.

Feel free to treat this as an XY problem. If there's a way to set the mangling scheme of GCC for C that'd be great, for example.

答:
I stumbled upon the same problem. I've created an include file with a lot of defines like

```<code>%define printf  _printf
%define puts    _puts
%define scanf   _scanf
</code>```

and some other stuff.

That file (libc_win32.in) is included by a "master" include file (libc.inc):

```<code>%ifndef LIBC_INC
%define LIBC_INC

%ifdef win32
    %include 'libc_win32.inc'
%elifdef win64
    %include 'libc_win64.inc'
%elifdef elf32
    %include 'libc_elf32.inc'
%elifdef elf64
    %include 'libc_elf64.inc'
%else
;   %error "libc.inc"
%endif

%endif
</code>```

I set the symbols and include the files at the command line:

```<code>nasm -fwin32 -dwin32 -plibc.inc ...
</code>```

or

```<code>nasm -felf32 -delf32 -plibc.inc ...
</code>```

There is a predefined macro called __OUTPUT_FORMAT__, but it works only inside of a macro, not at program start.

Body:
I stumbled upon the same problem. I've created an include file with a lot of defines like

%define printf  _printf
%define puts    _puts
%define scanf   _scanf

and some other stuff.

That file (libc_win32.in) is included by a "master" include file (libc.inc):

%ifndef LIBC_INC
%define LIBC_INC

%ifdef win32
    %include 'libc_win32.inc'
%elifdef win64
    %include 'libc_win64.inc'
%elifdef elf32
    %include 'libc_elf32.inc'
%elifdef elf64
    %include 'libc_elf64.inc'
%else
;   %error "libc.inc"
%endif

%endif

I set the symbols and include the files at the command line:

nasm -fwin32 -dwin32 -plibc.inc ...

or

nasm -felf32 -delf32 -plibc.inc ...

There is a predefined macro called __OUTPUT_FORMAT__, but it works only inside of a macro, not at program start.


问:
Cancel previous asynchronous .load() requests
I have some javascript code that works as follows:

```<code>function updateResults() {
    var user_input = $('input:text').val();

    user_input = encodeURIComponent(user_input);

    div1.html('').load(cog_url); // Just displays a spinning cog while results load
    div2.html('').load(cog_url); // Just displays a spinning cog while results load
    div3.html('').load(cog_url); // Just displays a spinning cog while results load

    $.when(
        div1.html('').load("api/method1?input=" + user_input),
        div2.html('').load("api/method2?input=" + user_input),
        div3.html('').load("api/method3?input=" + user_input)
    ).done(function () {
        return true;
    });
}
</code>```

The API methods just return HTML which contains the desired results to be rendered in the target divs. This all works relatively well, but when I submit multiple times to the system the previous requests don't get canceled so I get a string of responses and the divs keep getting reloaded with all the requests that were sent in order. I'd like to have it so that just the latest request is returned if the previous one(s) hasn't finished. Any suggestions as to how to do this? I'd like to keep the asynchronous aspect of this.

答:
You cannot do it with .load. You will have to use the .ajax or one of the shorthand methods (in this case .get should do).

So you need to add the Promises to an array and use for the when and also iterate over it and abort when re-calling the function.

something like this

```<code>var calls = [];
function updateResults() {
    var user_input = $('input:text').val(),
        apiQuery = {input: user_input};

    div1.empty().load(cog_url); // Just displays a spinning cog while results load
    div2.empty().load(cog_url); // Just displays a spinning cog while results load
    div3.empty().load(cog_url); // Just displays a spinning cog while results load

    calls.forEach(function(call){call.abort();});
    calls = [];
    calls.push( $.get('api/method1',apiQuery) );
    calls.push( $.get('api/method2',apiQuery) );
    calls.push( $.get('api/method3',apiQuery) );

    $.when.apply($, calls).done(function (result1, result2, result3) {
        div1.html(result1);
        div2.html(result2);
        div3.html(result3);

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

Additionally do not use .html(''), there is a .empty() method that does that. Also, if you pass an object as the parameters to the ajax calls it gets encoded by default (no need to manually encode the input)

Body:
I have some javascript code that works as follows:

function updateResults() {
    var user_input = $('input:text').val();

    user_input = encodeURIComponent(user_input);

    div1.html('').load(cog_url); // Just displays a spinning cog while results load
    div2.html('').load(cog_url); // Just displays a spinning cog while results load
    div3.html('').load(cog_url); // Just displays a spinning cog while results load

    $.when(
        div1.html('').load("api/method1?input=" + user_input),
        div2.html('').load("api/method2?input=" + user_input),
        div3.html('').load("api/method3?input=" + user_input)
    ).done(function () {
        return true;
    });
}

The API methods just return HTML which contains the desired results to be rendered in the target divs. This all works relatively well, but when I submit multiple times to the system the previous requests don't get canceled so I get a string of responses and the divs keep getting reloaded with all the requests that were sent in order. I'd like to have it so that just the latest request is returned if the previous one(s) hasn't finished. Any suggestions as to how to do this? I'd like to keep the asynchronous aspect of this.

Body:
You cannot do it with .load. You will have to use the .ajax or one of the shorthand methods (in this case .get should do).

So you need to add the Promises to an array and use for the when and also iterate over it and abort when re-calling the function.

something like this

var calls = [];
function updateResults() {
    var user_input = $('input:text').val(),
        apiQuery = {input: user_input};

    div1.empty().load(cog_url); // Just displays a spinning cog while results load
    div2.empty().load(cog_url); // Just displays a spinning cog while results load
    div3.empty().load(cog_url); // Just displays a spinning cog while results load

    calls.forEach(function(call){call.abort();});
    calls = [];
    calls.push( $.get('api/method1',apiQuery) );
    calls.push( $.get('api/method2',apiQuery) );
    calls.push( $.get('api/method3',apiQuery) );

    $.when.apply($, calls).done(function (result1, result2, result3) {
        div1.html(result1);
        div2.html(result2);
        div3.html(result3);

        return true;
    });
}

Additionally do not use .html(''), there is a .empty() method that does that. Also, if you pass an object as the parameters to the ajax calls it gets encoded by default (no need to manually encode the input)


问:
Code works in JavaSE, but crashes in Wildfly with NullPointerException
I'm generating graphs with gephi-toolkit (0.9.1), wrote a javaSE application fine, tested it and so on.

While copy-pasting this code to my EJB (tried all three types) the code starts producing:

java.lang.RuntimeException: java.lang.NullPointerException

on exporting graph to SVG (and PNG also).

I explicitly check my objects - they are not null. So, something deep inside of gephi-toolkit is compatible with JavaSE and not with JavaEE.

Any hints or recommendations how to find and fix problem?

I tried to export to File (File.createTempFile())
then to stream - StringWriter and OutputStream.
All three failed.

```<code>ExportController ec = Lookup.getDefault().lookup(ExportController.class);
SVGExporter exp = (SVGExporter) ec.getExporter("svg");
StringWriter sw = new StringWriter();
exp.setWriter(sw);
exp.setWorkspace(workspace);
System.out.println(" exec: " + exp.execute());
</code>```

ec, exp and sw are not null, but I get NPE on exp.execute()

Update:

java.lang.RuntimeException: java.lang.NullPointerException
      at org.gephi.io.exporter.preview.SVGExporter.execute(SVGExporter.java:113)
      at model.GraphBuilder.generateGraph(GraphBuilder.java:155)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
      at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:82)
      at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:93)
      at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
      at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
      at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:83)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ee.concurrent.ConcurrentContextInterceptor.processInvocation(ConcurrentContextInterceptor.java:45)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
      at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:52)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(PooledInstanceInterceptor.java:51)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:275)
      at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:327)
      at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:239)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.invocationmetrics.WaitTimeInterceptor.processInvocation(WaitTimeInterceptor.java:47)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.security.SecurityContextInterceptor.processInvocation(SecurityContextInterceptor.java:100)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.deployment.processors.StartupAwaitInterceptor.processInvocation(StartupAwaitInterceptor.java:22)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory$1.processInvocation(ShutDownInterceptorFactory.java:64)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:67)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:54)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.ContextClassLoaderInterceptor.processInvocation(ContextClassLoaderInterceptor.java:64)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:356)
      at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:636)
      at org.jboss.invocation.AccessCheckingInterceptor.processInvocation(AccessCheckingInterceptor.java:61)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:356)
      at org.jboss.invocation.PrivilegedWithCombinerInterceptor.processInvocation(PrivilegedWithCombinerInterceptor.java:80)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
      at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:198)
      at org.jboss.as.ee.component.ViewDescription$1.processInvocation(ViewDescription.java:185)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
      at org.jboss.as.ee.component.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:73)
      at model.GraphBuilder$$$view20.generateGraph(Unknown Source)
      at beans.Controller.submit3(Controller.java:193)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:181)
      at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
      at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
      at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
      at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
      at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
      at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
      at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
      at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
      at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
      at javax.faces.component.UICommand.broadcast(UICommand.java:315)
      at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
      at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
      at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
      at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
      at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
      at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
      at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
      at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
      at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
      at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
      at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
      at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
      at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
      at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
      at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
      at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
      at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
      at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
      at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
      at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
      at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
      at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
      at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
      at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
      at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
      at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
      at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
      at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
      at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
      at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
      at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
      at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
      at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
      at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
      at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at java.lang.Thread.run(Thread.java:748)
      ERROR [stderr] (default task-11) Caused by: java.lang.NullPointerException
      at org.gephi.preview.plugin.renderers.NodeLabelRenderer.renderSVG(NodeLabelRenderer.java:277)
      at org.gephi.preview.plugin.renderers.NodeLabelRenderer.render(NodeLabelRenderer.java:198)
      at org.gephi.preview.PreviewControllerImpl.render(PreviewControllerImpl.java:251)
      at org.gephi.preview.PreviewControllerImpl.render(PreviewControllerImpl.java:208)
      at org.gephi.io.exporter.preview.SVGExporter.execute(SVGExporter.java:95)

答:
Executive summary: code works on desktop but fails on server because server is in headless mode, and code uses some functionality (here getBBox()) within Batik that requires a GUI.

A major difference between your code running in a simple Java SE program, and the same code running in a server environment, is that the latter is most likely headless.

Gephi delegates to Batik for SVG generation, and in turn Batik uses java.awt for some rendering details, and rendering is (likely) necessary for bounding box computation (getBBox()), which unfortunately gephi relies on.

Old versions of Batik used to crash on headless environments. Now it mostly works. See this example in Batik source code:

```<code>/**
 * Returns the active screen resolution. If Batik is run in a headless environment, this
 * method will return the default "96" unlike {@link Toolkit#getScreenResolution()} which
 * will throw a {@link HeadlessException}.
 * @return the screen resolution in dpi
 */
public static int getScreenResolution() {
    if (GraphicsEnvironment.isHeadless()) {
        return 96;
    } else {
        return Toolkit.getDefaultToolkit().getScreenResolution();
    }
}
</code>```

But it seems still limited when trying to compute a bounding box.

So, one suggestion worth trying, if possible (depending in your situation, it might be very easy, or very complicated): start your server in a non-headless environment.

Wildfly (and most servers) by default runs with -Djava.awt.headless=true in the command line. It should be possible to change that by editing standalone.conf.

For this to work you'll need a display. For example on Linux, give it a valid $DISPLAY to use, that would point to a virtual display, like a VNC server, or better with Virtual Framebuffer, which is a 'fake' X server (avoids X-windows on server, CentOS package is xorg-x11-server-xvfb, Debian's is xvfb).

Maybe that is not a satisfactory solution for production, but if it works, it will at least be a good clue to help determine where to look next: how to get getBBox() work in headless environment, or have gephi work without needing getBBox().

ContentLicense: CC BY-SA 4.0

Body:
I'm generating graphs with gephi-toolkit (0.9.1), wrote a javaSE application fine, tested it and so on.

While copy-pasting this code to my EJB (tried all three types) the code starts producing:

java.lang.RuntimeException: java.lang.NullPointerException

on exporting graph to SVG (and PNG also).

I explicitly check my objects - they are not null. So, something deep inside of gephi-toolkit is compatible with JavaSE and not with JavaEE.

Any hints or recommendations how to find and fix problem?

I tried to export to File (File.createTempFile())
then to stream - StringWriter and OutputStream.
All three failed.

ExportController ec = Lookup.getDefault().lookup(ExportController.class);
SVGExporter exp = (SVGExporter) ec.getExporter("svg");
StringWriter sw = new StringWriter();
exp.setWriter(sw);
exp.setWorkspace(workspace);
System.out.println(" exec: " + exp.execute());

ec, exp and sw are not null, but I get NPE on exp.execute()

Update:

java.lang.RuntimeException: java.lang.NullPointerException
      at org.gephi.io.exporter.preview.SVGExporter.execute(SVGExporter.java:113)
      at model.GraphBuilder.generateGraph(GraphBuilder.java:155)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
      at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:82)
      at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:93)
      at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
      at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
      at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:83)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ee.concurrent.ConcurrentContextInterceptor.processInvocation(ConcurrentContextInterceptor.java:45)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
      at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:52)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(PooledInstanceInterceptor.java:51)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:275)
      at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:327)
      at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:239)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.invocationmetrics.WaitTimeInterceptor.processInvocation(WaitTimeInterceptor.java:47)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.security.SecurityContextInterceptor.processInvocation(SecurityContextInterceptor.java:100)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.deployment.processors.StartupAwaitInterceptor.processInvocation(StartupAwaitInterceptor.java:22)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory$1.processInvocation(ShutDownInterceptorFactory.java:64)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:67)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:54)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.ContextClassLoaderInterceptor.processInvocation(ContextClassLoaderInterceptor.java:64)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:356)
      at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:636)
      at org.jboss.invocation.AccessCheckingInterceptor.processInvocation(AccessCheckingInterceptor.java:61)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:356)
      at org.jboss.invocation.PrivilegedWithCombinerInterceptor.processInvocation(PrivilegedWithCombinerInterceptor.java:80)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
      at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:198)
      at org.jboss.as.ee.component.ViewDescription$1.processInvocation(ViewDescription.java:185)
      at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
      at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
      at org.jboss.as.ee.component.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:73)
      at model.GraphBuilder$$$view20.generateGraph(Unknown Source)
      at beans.Controller.submit3(Controller.java:193)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:181)
      at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
      at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
      at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
      at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
      at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
      at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
      at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
      at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
      at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
      at javax.faces.component.UICommand.broadcast(UICommand.java:315)
      at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
      at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
      at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
      at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
      at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
      at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
      at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
      at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
      at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
      at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
      at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
      at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
      at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
      at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
      at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
      at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
      at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
      at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
      at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
      at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
      at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
      at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
      at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
      at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
      at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
      at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
      at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
      at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
      at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
      at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
      at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
      at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
      at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
      at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
      at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
      at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      at java.lang.Thread.run(Thread.java:748)
      ERROR [stderr] (default task-11) Caused by: java.lang.NullPointerException
      at org.gephi.preview.plugin.renderers.NodeLabelRenderer.renderSVG(NodeLabelRenderer.java:277)
      at org.gephi.preview.plugin.renderers.NodeLabelRenderer.render(NodeLabelRenderer.java:198)
      at org.gephi.preview.PreviewControllerImpl.render(PreviewControllerImpl.java:251)
      at org.gephi.preview.PreviewControllerImpl.render(PreviewControllerImpl.java:208)
      at org.gephi.io.exporter.preview.SVGExporter.execute(SVGExporter.java:95)

Body:
Executive summary: code works on desktop but fails on server because server is in headless mode, and code uses some functionality (here getBBox()) within Batik that requires a GUI.

A major difference between your code running in a simple Java SE program, and the same code running in a server environment, is that the latter is most likely headless.

Gephi delegates to Batik for SVG generation, and in turn Batik uses java.awt for some rendering details, and rendering is (likely) necessary for bounding box computation (getBBox()), which unfortunately gephi relies on.

Old versions of Batik used to crash on headless environments. Now it mostly works. See this example in Batik source code:

/**
 * Returns the active screen resolution. If Batik is run in a headless environment, this
 * method will return the default "96" unlike {@link Toolkit#getScreenResolution()} which
 * will throw a {@link HeadlessException}.
 * @return the screen resolution in dpi
 */
public static int getScreenResolution() {
    if (GraphicsEnvironment.isHeadless()) {
        return 96;
    } else {
        return Toolkit.getDefaultToolkit().getScreenResolution();
    }
}

But it seems still limited when trying to compute a bounding box.

So, one suggestion worth trying, if possible (depending in your situation, it might be very easy, or very complicated): start your server in a non-headless environment.

Wildfly (and most servers) by default runs with -Djava.awt.headless=true in the command line. It should be possible to change that by editing standalone.conf.

For this to work you'll need a display. For example on Linux, give it a valid $DISPLAY to use, that would point to a virtual display, like a VNC server, or better with Virtual Framebuffer, which is a 'fake' X server (avoids X-windows on server, CentOS package is xorg-x11-server-xvfb, Debian's is xvfb).

Maybe that is not a satisfactory solution for production, but if it works, it will at least be a good clue to help determine where to look next: how to get getBBox() work in headless environment, or have gephi work without needing getBBox().


问:
REST only use get and post
Since not all client browsers support put and delete, is it good practice to only use 'get' and 'post' for all crud operations?</p>

答: Yes.  However, your framework should still support proper PUT and DELETE requests that come in.  Ruby on Rails emulates these requests by using a special parameter to POST requests -- the framework then routes the request to a PUT/DELETE handler as appropriate.</p>

Title: REST only use get and post


问:
css structural selector :first-child
If i apply following style on the given html below, why it is applying the style on everything inside the body element. I was assuming since the body is NOT the first child of html it should not apply this style onto anything inside body element.

:first-child { color: blue;}

HTML

```<code><html>
    <head>
      <title>Test Page</title>
    </head>
    <style>
        :first-child { color: blue;}
    </style>
    <body>
      <div>
            <h1>This is a H6</h1>
            <p>Carz wtf noice pour uh saiz hoi.</p>
            <p>Oh winz lol wuv donutz yu. Herrow not wut carz pwety oh hornz. </p>
            <p>Bere noze dum cheezeburger oh. Notise hai mikrosoft foots. Dum oh iz nuthing gravy haz nozbody finking. Funnae hai nom winz noze r. </p>
      </div>
      <div>
        <h1>This is an H1</h1>
        <p>Sheeze dum can compewters flowerz. Loike choosday noice nom samez do hornz mac n. Funnae pour hoi dided gravy samez ghoast I.</p>
        <p> U pwety oh haz cat ghoast hai. Taytoes hornz hunnae hai meeeow ghoast.
        </p>

        <h2>This is an h2</h2>
        <p>Sheeze meeeow dum uh dided cat nom hornz wuv. </p>
        <p>Donutz scratchin mac n dum rong ded gravy.</p>
        <p>Thx chz can hoi wtf. Evrybody yu u ded choosday evrybody hai neether. Iz hai dided sheeze bukket noice nozzing chz watzzup?. </p>
        <h2>this is another h2</h2>
        <p>Graet samez iz iz nozbody saiz sheeze oh carz. Jest kitteh not scratchin herrow. Nom scratchin rong saiz ya kitteh haz chz nom. </p>
        <p>Graet gravy gravy mikrosoft. Dided winz cheezeburger finking samez wtf foots. Gravy wut mac n partay noice noze foots. </p>
        <p>Can sink nom compewter ur ded how herrow cat. </p>
      </div>
    </body>
    </html>
</code>```

答:
Primarily because html is the :first-child, so it's essentially the same as saying html { color: blue; }, and because CSS cascades, other elements inherit it, too. So it essentially applies it to all elements on your page that don't have another color specified because the color is first set on html. For example, if you added an a tag that was not the first child of a parent, that wouldn't inherit this color because a link has it's own color and would overwrite the color on html. Here's an example https://codepen.io/mcoker/pen/WObbbb

But beyond the style on html, every single "first child" of any parent element in your document will be targeted just using :first-child, so a lot of your elements are getting color: blue applied directly as well as indirectly from inheriting the color from parent elements that are first children.

It's also worth noting this is based on the fact that color is an inheritable property in CSS, meaning if you set color on a parent element, the color will be inherited to children elements that do not have an explicit color set in CSS or one that is applied via the agent/browser stylesheet. An example of a non-inheritable property is border - if there is a border on a parent element, the children will not inherit the border property. https://codepen.io/mcoker/pen/OgPPNK

Title: css structural selector :first-child

Body:
If i apply following style on the given html below, why it is applying the style on everything inside the body element. I was assuming since the body is NOT the first child of html it should not apply this style onto anything inside body element.

:first-child { color: blue;}

HTML

      <title>Test Page</title>

This is a H6

Carz wtf noice pour uh saiz hoi.

Oh winz lol wuv donutz yu. Herrow not wut carz pwety oh hornz.

Bere noze dum cheezeburger oh. Notise hai mikrosoft foots. Dum oh iz nuthing gravy haz nozbody finking. Funnae hai nom winz noze r.

This is an H1

Sheeze dum can compewters flowerz. Loike choosday noice nom samez do hornz mac n. Funnae pour hoi dided gravy samez ghoast I.

 U pwety oh haz cat ghoast hai. Taytoes hornz hunnae hai meeeow ghoast.

This is an h2

Sheeze meeeow dum uh dided cat nom hornz wuv.

Donutz scratchin mac n dum rong ded gravy.

Thx chz can hoi wtf. Evrybody yu u ded choosday evrybody hai neether. Iz hai dided sheeze bukket noice nozzing chz watzzup?.

this is another h2

Graet samez iz iz nozbody saiz sheeze oh carz. Jest kitteh not scratchin herrow. Nom scratchin rong saiz ya kitteh haz chz nom.

Graet gravy gravy mikrosoft. Dided winz cheezeburger finking samez wtf foots. Gravy wut mac n partay noice noze foots.

Can sink nom compewter ur ded how herrow cat.


问:
Integer partitioning in Java
I'm trying to implement a program that returns the number of existing partitions of an integer n as part of an assignment. I wrote the code below, but it returns the wrong number (Partitions n returns the result of Partitions n-1). I don't get why this happens. I've tried many things and still don't know how to fix it, can anyone please help me?

```<code>[edited code out to avoid plagiarism from my colleagues :p]
</code>```

m stands for the biggest number allowed in a partition, so partition(4,4) would be 5 = 4, 3+1, 2+2, 2+1+1, 1+1+1+1, but partition (4,1) would be 1 = 1+1+1+1.
Execution: java Partitions n

答:
Suppose you're calling partitions(4,4,memo).  As you said, the answer should be 5 because there are 5 ways to partition the integer:

```<code>4
3 + 1           <== counted by partition(1,3,memo)
2 + 2           <== counted by partition(2,2,memo)
2 + 1 + 1       <== counted by partition(2,2,memo)
1 + 1 + 1 + 1   <== counted by partition(3,1,memo)
</code>```

So it looks like your algorithm tries to count the partitions in the way shown above... but is there one partition you're forgetting to count?

Title: Integer partitioning in Java

Body:
I'm trying to implement a program that returns the number of existing partitions of an integer n as part of an assignment. I wrote the code below, but it returns the wrong number (Partitions n returns the result of Partitions n-1). I don't get why this happens. I've tried many things and still don't know how to fix it, can anyone please help me?

[edited code out to avoid plagiarism from my colleagues :p]

m stands for the biggest number allowed in a partition, so partition(4,4) would be 5 = 4, 3+1, 2+2, 2+1+1, 1+1+1+1, but partition (4,1) would be 1 = 1+1+1+1.
Execution: java Partitions n

Body:
Suppose you're calling partitions(4,4,memo).  As you said, the answer should be 5 because there are 5 ways to partition the integer:

4
3 + 1           <== counted by partition(1,3,memo)
2 + 2           <== counted by partition(2,2,memo)
2 + 1 + 1       <== counted by partition(2,2,memo)
1 + 1 + 1 + 1   <== counted by partition(3,1,memo)

So it looks like your algorithm tries to count the partitions in the way shown above... but is there one partition you're forgetting to count?


问:
Build filters on entities based on ASP.NET MVC 5 Identity User
I have a survey's platform with all the score of a list of stores.

I need to make available to each user, the stores based in his location's area (region).

I use Microsoft Identity in my MVC project and I found only two aproaches for this:

1- Build a profile for each region, so I can filter based on the logged user's profile name - dbContext.Where(location == profileName)

2- Extend the ApplicationUser to include the region, so I can filter using dbContext.Where(location == User.Identity.GetLocation())

Or any other option?

I have been able to implement the second option:

Stores Model:

```<code>public enum PTLocationDistrict
{
    [Display(Name = "Aveiro")]
    Aveiro = 1,
    [Display(Name = "Beja")]
    Beja = 2,
    [Display(Name = "Braga")]
    Braga = 3
}

[Table("Stores")]
public class Store
{
    [Key]
    public int Id { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public PTLocationDistrict District { get; set; }
}
</code>```

Identity ApplicationUser:

```<code>public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        // Add custom user claims here
        userIdentity.AddClaim(new Claim("PTLocationDistrict", this.PTLocationDistrict.ToString()));

        return userIdentity;
    }

    // Additional properties for the Application User
    public PTLocationDistrict? PTLocationDistrict { get; set; }
}
</code>```

Identity Services:

```<code>   public static PTLocationDistrict? GetPTLocationDistrict(this IIdentity identity)
    {
        Claim claim = ((ClaimsIdentity)identity).FindFirst("PTLocationDistrict");

        PTLocationDistrict value;

        if (claim == null)
        {
            return null;
        }
        else if (Enum.TryParse(claim.Value, out value))
        {
            return value;
        }
        else
        {

            return null;
        }
    }
</code>```

Dashboard Report Count Service:

```<code>public int GetCountToday(PTLocationDistrict? ptLocationDistrict)
{
    try
    {
        var today = DateTime.Today;

        IQueryable<SurveySession> surveySessions = _dbContext.SurveySessions.AsNoTracking().AsQueryable();

        if (ptLocationDistrict != null)
        {
            surveySessions = surveySessions.Where(ss => ss.Location.District == ptLocationDistrict.Value);
        }

        int count = surveySessions
                            .Where(p => p.DateCreated >= today)
                            .Count();

        return count;
    }
    catch (Exception error)
    {
        _logger.Error("[Error in SurveyService.GetCountToday" - Error: " + error + "]");

        return 0;
    }
}
</code>```

Controller Action:

```<code>public virtual ActionResult Index()
{
    IndexViewModel model = new IndexViewModel();
    PTLocationDistrict? ptLocationDistrict = User.Identity.GetPTLocationDistrict();

    // Realizados Hoje
    model.SurveyCountToday = _surveyService.GetCountToday(ptLocationDistrict);

}
</code>```

答:
It seems that the information is not used for Identity (denying access based on location). So in case you have a 'Person' table, you can store the location there, outside the Identity Model, and use this table in a join on the location field.

If not, I would simply add a claim with the location. The advantage is that you can read the claim without having to lookup the field from the database. You can use User.Identity.GetLocation(), assuming this is an extension that reads the claim containing the Location.

You can extend the IdentityUser with a field Location and add a claim, based on the field. But you don't have to if you add a claim to the AspNetUserClaims table, since it is not likeley to change. In that case the claim is automatically added to the identity.

Please note that the value of a claim is updated only if the user logs out and logs in again, or the token is expired.

-- update --

You can create a CustomClaimType, something like this:

```<code>public const string LocationClaimType = "https://schemas.mycompany.com/claims/location";
</code>```

It doesn't really matter, as long as it can uniquely identify the claim.

There isn't much to tell about the AspNetUserClaims table. Insert a record where claimtype is your custom claimtype and set the value for the specific user. And it is automatically added to the identity. You can also add claims to a user with code.

In your controller:

```<code>var identity = (System.Security.Claims.ClaimsIdentity)User.Identity;
var res = identity.Claims.FirstOrDefault(c => c.ValueType == LocationClaimType)?.Value;
</code>```

You can extend Identity (with GetLocation) with code like above. You can do the same thing for CompanyId.

In both cases the properties aren't likely to change and you won't need to call the database to get this additional information.

Body:
I have a survey's platform with all the score of a list of stores.

I need to make available to each user, the stores based in his location's area (region).

I use Microsoft Identity in my MVC project and I found only two aproaches for this:

1- Build a profile for each region, so I can filter based on the logged user's profile name - dbContext.Where(location == profileName)

2- Extend the ApplicationUser to include the region, so I can filter using dbContext.Where(location == User.Identity.GetLocation())

Or any other option?

I have been able to implement the second option:

Stores Model:

public enum PTLocationDistrict
{
    [Display(Name = "Aveiro")]
    Aveiro = 1,
    [Display(Name = "Beja")]
    Beja = 2,
    [Display(Name = "Braga")]
    Braga = 3
}

[Table("Stores")]
public class Store
{
    [Key]
    public int Id { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public PTLocationDistrict District { get; set; }
}

Identity ApplicationUser:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        // Add custom user claims here
        userIdentity.AddClaim(new Claim("PTLocationDistrict", this.PTLocationDistrict.ToString()));

        return userIdentity;
    }

    // Additional properties for the Application User
    public PTLocationDistrict? PTLocationDistrict { get; set; }
}

Identity Services:

   public static PTLocationDistrict? GetPTLocationDistrict(this IIdentity identity)
    {
        Claim claim = ((ClaimsIdentity)identity).FindFirst("PTLocationDistrict");

        PTLocationDistrict value;

        if (claim == null)
        {
            return null;
        }
        else if (Enum.TryParse(claim.Value, out value))
        {
            return value;
        }
        else
        {

            return null;
        }
    }

Dashboard Report Count Service:

public int GetCountToday(PTLocationDistrict? ptLocationDistrict)
{
    try
    {
        var today = DateTime.Today;

        IQueryable<SurveySession> surveySessions = _dbContext.SurveySessions.AsNoTracking().AsQueryable();

        if (ptLocationDistrict != null)
        {
            surveySessions = surveySessions.Where(ss => ss.Location.District == ptLocationDistrict.Value);
        }

        int count = surveySessions
                            .Where(p => p.DateCreated >= today)
                            .Count();

        return count;
    }
    catch (Exception error)
    {
        _logger.Error("[Error in SurveyService.GetCountToday" - Error: " + error + "]");

        return 0;
    }
}

Controller Action:

public virtual ActionResult Index()
{
    IndexViewModel model = new IndexViewModel();
    PTLocationDistrict? ptLocationDistrict = User.Identity.GetPTLocationDistrict();

    // Realizados Hoje
    model.SurveyCountToday = _surveyService.GetCountToday(ptLocationDistrict);

}

Body:
It seems that the information is not used for Identity (denying access based on location). So in case you have a 'Person' table, you can store the location there, outside the Identity Model, and use this table in a join on the location field.

If not, I would simply add a claim with the location. The advantage is that you can read the claim without having to lookup the field from the database. You can use User.Identity.GetLocation(), assuming this is an extension that reads the claim containing the Location.

You can extend the IdentityUser with a field Location and add a claim, based on the field. But you don't have to if you add a claim to the AspNetUserClaims table, since it is not likeley to change. In that case the claim is automatically added to the identity.

Please note that the value of a claim is updated only if the user logs out and logs in again, or the token is expired.

-- update --

You can create a CustomClaimType, something like this:

public const string LocationClaimType = "https://schemas.mycompany.com/claims/location";

It doesn't really matter, as long as it can uniquely identify the claim.

There isn't much to tell about the AspNetUserClaims table. Insert a record where claimtype is your custom claimtype and set the value for the specific user. And it is automatically added to the identity. You can also add claims to a user with code.

In your controller:

var identity = (System.Security.Claims.ClaimsIdentity)User.Identity;
var res = identity.Claims.FirstOrDefault(c => c.ValueType == LocationClaimType)?.Value;

You can extend Identity (with GetLocation) with code like above. You can do the same thing for CompanyId.

In both cases the properties aren't likely to change and you won't need to call the database to get this additional information.


问:
Load table from Ajax JSON with angular and ng-repeat
I try to load a table in HTML from Ajax json, using Angular and ng-repeat.
My problem is that the JSON is a bit complicated and I don't know how to access "informationstyp", which is what I want to display in the table.
The root of the JSON ("values") is a list. Next level ("informationstyper") is also a list.

How can I get "informationstyp" into the table?
What should I write instead of {{data.arendeslagId}} in my html?

What I want in my table is:

FK1002

FK1003

FK1004

Thank you for your help.

My html:

```<code>        <table class="table table-hover">
            <thead>
            <tr>
                <th>Arendeslagid</th>
            </tr>
            </thead>
            <tbody>
            <tr ng-repeat="data in infotyper">
                <td>{{data.arendeslagId}}</td>
            </tr>
            </tbody>
        </table>
</code>```

My JavaScript:

```<code>    $scope.infotyper = "";

    $scope.invoke = function() {
        $.ajax({
               "cache": false,
               "async": true,
               "crossDomain": true,
               "url": url",
               "method": "POST",
               "headers": {
                   "cache-control": "no-cache",
               },
            success: function (response) {
                   $scope.infotyper= response;
               }
           });
        };
</code>```

My JSON-response:

答:
Try to change this:

```<code>success: function (response) {
  $scope.infotyper= response;
}
</code>```

To this:

```<code>success: function (response) {
  $scope.infotyper= response.values;
  $scope.$apply();
}
</code>```

If you are using AngularJS I strongly suggest you to use $http service instead of jQuery for AJAX requests

Body:
I try to load a table in HTML from Ajax json, using Angular and ng-repeat.
My problem is that the JSON is a bit complicated and I don't know how to access "informationstyp", which is what I want to display in the table.
The root of the JSON ("values") is a list. Next level ("informationstyper") is also a list.

How can I get "informationstyp" into the table?
What should I write instead of {{data.arendeslagId}} in my html?

What I want in my table is:

FK1002

FK1003

FK1004

Thank you for your help.

My html:

                Arendeslagid

                {{data.arendeslagId}}

My JavaScript:

    $scope.infotyper = "";

    $scope.invoke = function() {
        $.ajax({
               "cache": false,
               "async": true,
               "crossDomain": true,
               "url": url",
               "method": "POST",
               "headers": {
                   "cache-control": "no-cache",
               },
            success: function (response) {
                   $scope.infotyper= response;
               }
           });
        };

My JSON-response:

Body:
Try to change this:

success: function (response) {
  $scope.infotyper= response;
}

To this:

success: function (response) {
  $scope.infotyper= response.values;
  $scope.$apply();
}

If you are using AngularJS I strongly suggest you to use $http service instead of jQuery for AJAX requests


问:
Make section dynamic on index.php (Wordpress)
I'm building my first Wordpress theme, so I'm pretty new to both Wordpress and PHP. I followed a bunch of tutorials and managed to take my existing website and convert it into a custom Wordpress theme.
However, I have a "About" section on my homepage (index.php) and I'd like to make it dynamic.

I was following a tutorial and they added the Biographical Info in the User Profile in one of the pages using the following code:

```<code><?php the_author_meta( 'description' ); ?>
</code>```

But that doesn't work on the index.php file. I'm guessing it's because the Index doesn't have any authors, so it doesn't really make sense to have the bio from one of the users there... I might be completely wrong though.

Any suggestions??

答:
you should use this in the index.php with the_author_meta like this:

the_author_meta('description', 12);

you have to include author ID here 12 and this way you'll make sure that there will be description there. you can find the author ID with get_user_by:

```<code>$the_user = get_user_by('email', 'foo@bar.com');
$the_user_id = $the_user->ID;
the_author_meta('description', $the_user_id);
</code>```

Body:
I'm building my first Wordpress theme, so I'm pretty new to both Wordpress and PHP. I followed a bunch of tutorials and managed to take my existing website and convert it into a custom Wordpress theme.
However, I have a "About" section on my homepage (index.php) and I'd like to make it dynamic.

I was following a tutorial and they added the Biographical Info in the User Profile in one of the pages using the following code:

<?php the_author_meta( 'description' ); ?>

But that doesn't work on the index.php file. I'm guessing it's because the Index doesn't have any authors, so it doesn't really make sense to have the bio from one of the users there... I might be completely wrong though.

Any suggestions??

Body:
you should use this in the index.php with the_author_meta like this:

the_author_meta('description', 12);

you have to include author ID here 12 and this way you'll make sure that there will be description there. you can find the author ID with get_user_by:

$the_user = get_user_by('email', 'foo@bar.com');
$the_user_id = $the_user->ID;
the_author_meta('description', $the_user_id);


问:
close windows application with sql query
I want to write a job in sql server that stop and run a specific windows form application.
is it possible to close a windows application with sql query or not?
if not, how can I do that? can I use vb.net?
I did use this code (EXEC MASTER.. xp_cmdshell     'taskkill /im filename.exe')
but get access denied error
thanks</p>

答:
I found the solution

I Can use SqlServer to close and open .exe files with (EXEC master.dbo.xp_cmdshell 'taskkill /F /IM filename.exe')
but before running we most use

  EXEC sp_configure 'xp_cmdshell', 1

    RECONFIGURE

   GO

to enable xp_cmdshell

but still we get access is denied error becouse:

when SQL server tries to access anything outside of the SQL instance(xp_cmdshell, files/folders/, network shares, anything outside of it's own databases)

it uses it's own startup account to do it. it's THAT account that has to have permissions to browse to network services...most likely, right now it does not.

Go to Control Panel/Administrative Tools>>Services>> find the instance of SQL server you are referencing:
the account shown here most likely needs to be changes from local account to an admin account that would have permissions to login to your domain, and browse to shares.


问:
zheev giving wrong eigenvalues (checked against zgeev and numpy.linalg.eig)
Tinkering with linalg libraries, I tried to get a diagonalisation routine for hermitian matrices up and running in c++ using LAPACKE

I followed this example to use ZHEEV, and then checked against some other methods, specifically numpy's eig and LAPACK(E)'s zgeev. I didn't want to use intel's own-brand stuff so I avoided MKL and just went for straight LAPACKE, but the majority of the code is the same as in the example.

For clarity, I see no reason why the general zgeev shouldn't be able to handle the specific case of a hermitian matrix, even if zheev is optimised.

Here's the c++

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

//Parameters
#define N 4
#define LDA N
#define lint lapack_int
#define ldcmplex lapack_complex_double

//Auxiliary routines prototypes
extern void print_matrix( char* desc, lint m, lint n, ldcmplex* a, lint lda         );
extern void print_rmatrix( char* desc, lint m, lint n, double* a, lint lda         );

//Main program
int main()
  {
    //Locals
    lint n = N, lda = LDA, info;
  ;
    //Local arrays
    double wr[N];
    ldcmplex ah[LDA*N] = {
           { 9.14,  0.00}, { 0.00,  0.00}, { 0.00,  0.00}, { 0.00,  0.00},
           {-4.37,  9.22}, {-3.35,  0.00}, { 0.00,  0.00}, { 0.00,  0.00},
           {-1.98,  1.72}, { 2.25,  9.51}, {-4.82,  0.00}, { 0.00,  0.00},
           {-8.96,  9.50}, { 2.57, -2.40}, {-3.24, -2.04}, { 8.44,  0.00}
    };
  ;
    //Executable statements
    printf( "LAPACKE_zheev (row-major, high-level) Example Program                         Results\n" )    ;
  ;
    //Print martix
    print_matrix( "Input Matrix", n, n, ah, lda );
  ;
    //Solve eigenproblem
    info = LAPACKE_zheev( LAPACK_ROW_MAJOR, 'V', 'L', n, ah, lda, wr );
  ;
    //Check for convergence
    if( info > 0 ) {
            printf( "zheev algorithm failed to compute eigenvalues.\n" );
            exit( 1 );
    }
  ;
    //Print eigenvalues
    print_rmatrix( "zheev Eigenvalues", 1, n, wr, 1 );
  ;
    //Print eigenvectors
    print_matrix( "Eigenvectors (stored columnwise)", n, n, ah, lda );
  ;
    //Local arrays
    ldcmplex wc[N];
    ldcmplex ag[LDA*N] = {
      { 9.14,  0.00}, {-4.37, -9.22}, {-1.98, -1.72}, {-8.96, -9.50},
      {-4.37,  9.22}, {-3.35,  0.00}, { 2.25, -9.51}, { 2.57,  2.40},
      {-1.98,  1.72}, { 2.25,  9.51}, {-4.82,  0.00}, {-3.24,  2.04},
      {-8.96,  9.50}, { 2.57, -2.40}, {-3.24, -2.04}, { 8.44,  0.00},
    };
  ;
    //Executable statements
    printf( "LAPACKE_zgeev (row-major, high-level) Example Program Results\n" );
  ;
    //Print martix
    print_matrix( "Input Matrix", n, n, ag, lda );
  ;
    //Solve eigenproblem
    info = LAPACKE_zgeev( LAPACK_ROW_MAJOR, 'N', 'V', n, ag, lda, wc, 0, lda, 0, lda);
  ;
    //Check for convergence
    if( info > 0 ) {
            printf( "zgeev algorithm failed to compute eigenvalues.\n" );
            exit( 1 );
    }
  ;
    //Print eigenvalues
    print_matrix( "zgeev Eigenvalues", 1, n, wc, 1);
  ;
    //Print eigenvectors
    print_matrix( "Eigenvectors (stored columnwise)", n, n, ag, lda );
    exit( 0 );
  }

//Auxiliary routine: printing a matrix
void print_matrix( char* desc, lint m, lint n, ldcmplex* a, lint lda ) {
        lint i, j;
        printf( "\n %s\n", desc );
        for( i = 0; i < m; i++ ) {
                for( j = 0; j < n; j++ )
                        printf( " (%6.2f,%6.2f)", creal(a[i*lda+j]),     cimag(a[i*lda+j]) );
                printf( "\n" );
        }
}

//Auxiliary routine: printing a real matrix
void print_rmatrix( char* desc, lint m, lint n, double* a, lint lda ) {
        lint i, j;
        printf( "\n %s\n", desc );
        for( i = 0; i < m; i++ ) {
                for( j = 0; j < n; j++ ) printf( " %6.2f", a[i*lda+j] );
                printf( "\n" );
        }
}
</code>```

compiled with

```<code>g++ diag.cc -L /usr/lib/lapack/ -llapacke -lcblas -o diag.out
</code>```

The only nonstandard packages being liblapacke-dev, and libcblas-dev, installed via apt-get install. What could possibly go wrong?

The output is

```<code>LAPACKE_zheev (row-major, high-level) Example Program Results

 Input Matrix
 (  9.14,  0.00) (  0.00,  0.00) (  0.00,  0.00) (  0.00,  0.00)
 ( -4.37,  9.22) ( -3.35,  0.00) (  0.00,  0.00) (  0.00,  0.00)
 ( -1.98,  1.72) (  2.25,  9.51) ( -4.82,  0.00) (  0.00,  0.00)
 ( -8.96,  9.50) (  2.57, -2.40) ( -3.24, -2.04) (  8.44,  0.00)

 zheev Eigenvalues
 -18.96 -12.85  18.78  30.71

 Eigenvectors (stored columnwise)
 (  0.16,  0.00) (  0.57,  0.00) ( -0.73,  0.00) (  0.35,  0.00)
 (  0.26, -0.81) (  0.17, -0.25) (  0.22, -0.38) (  0.06, -0.02)
 (  0.29,  0.27) ( -0.11, -0.30) ( -0.26, -0.42) ( -0.50, -0.50)
 ( -0.21,  0.23) (  0.50, -0.49) (  0.18, -0.09) ( -0.33,  0.51)

LAPACKE_zgeev (row-major, high-level) Example Program Results

 Input Matrix
 (  9.14,  0.00) ( -4.37, -9.22) ( -1.98, -1.72) ( -8.96, -9.50)
 ( -4.37,  9.22) ( -3.35,  0.00) (  2.25, -9.51) (  2.57,  2.40)
 ( -1.98,  1.72) (  2.25,  9.51) ( -4.82,  0.00) ( -3.24,  2.04)
 ( -8.96,  9.50) (  2.57, -2.40) ( -3.24, -2.04) (  8.44,  0.00)

 zgeev Eigenvalues
 ( 25.51,  0.00) (-16.00, -0.00) ( -6.76,  0.00) (  6.67,  0.00)

 Eigenvectors (stored columnwise)
 ( 25.51,  0.00) ( -0.00,  0.00) (  0.00,  0.00) (  0.00, -0.00)
 (  0.00,  0.00) (-16.00, -0.00) (  0.00, -0.00) (  0.00, -0.00)
 (  0.00,  0.00) (  0.00,  0.00) ( -6.76,  0.00) ( -0.00, -0.00)
 (  0.00,  0.00) (  0.00,  0.00) (  0.00,  0.00) (  6.67,  0.00)
</code>```

I tried using the Upper triangle, filling the matrix and various other fixes. Same results each time.

I'm suspicious of the #define ldcmplex lapack_complex_double macro, but all the documentation I can find says I should be using a double complex, so I'm a bit lost. Anyway, if that was the problem, why would zgeev work?

Anyway, here's the python check script:

```<code>#!/usr/bin/env python
from numpy import linalg as li
import numpy as np

mat=np.array([
[   9.14 + 0.00j,  0.00 + 0.00j,  0.00 + 0.00j,  0.00 +0.00j],
[  -4.37 + 9.22j, -3.35 + 0.00j,  0.00 + 0.00j,  0.00 +0.00j],
[  -1.98 + 1.72j,  2.25 + 9.51j, -4.82 + 0.00j,  0.00 +0.00j],
[  -8.96 + 9.50j,  2.57 - 2.40j, -3.24 - 2.04j,  8.44 +0.00j]])
mat[0]=np.conj(mat[:,0])
mat[1]=np.conj(mat[:,1])
mat[2]=np.conj(mat[:,2])
mat[3]=np.conj(mat[:,3])

mat=np.matrix(mat)

w, v = li.eig(mat)

print w
print v
</code>```

It agrees with zgeev (up to some rounding/machine errors). The result is also confirmed by the intel tutorial linked above. The zheev method is clearly in a minority of one, I just don't know why.

I've tried this on a couple of machines:

```<code>Linux parabox 4.8.0-52-generic #55-Ubuntu SMP Fri Apr 28 13:28:50 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
Linux glass 4.10.0-21-generic #23-Ubuntu SMP Fri Apr 28 16:14:22 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
</code>```

Any and all help appreciated.

Body:
Tinkering with linalg libraries, I tried to get a diagonalisation routine for hermitian matrices up and running in c++ using LAPACKE

I followed this example to use ZHEEV, and then checked against some other methods, specifically numpy's eig and LAPACK(E)'s zgeev. I didn't want to use intel's own-brand stuff so I avoided MKL and just went for straight LAPACKE, but the majority of the code is the same as in the example.

For clarity, I see no reason why the general zgeev shouldn't be able to handle the specific case of a hermitian matrix, even if zheev is optimised.

Here's the c++

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

//Parameters
#define N 4
#define LDA N
#define lint lapack_int
#define ldcmplex lapack_complex_double

//Auxiliary routines prototypes
extern void print_matrix( char* desc, lint m, lint n, ldcmplex* a, lint lda         );
extern void print_rmatrix( char* desc, lint m, lint n, double* a, lint lda         );

//Main program
int main()
  {
    //Locals
    lint n = N, lda = LDA, info;
  ;
    //Local arrays
    double wr[N];
    ldcmplex ah[LDA*N] = {
           { 9.14,  0.00}, { 0.00,  0.00}, { 0.00,  0.00}, { 0.00,  0.00},
           {-4.37,  9.22}, {-3.35,  0.00}, { 0.00,  0.00}, { 0.00,  0.00},
           {-1.98,  1.72}, { 2.25,  9.51}, {-4.82,  0.00}, { 0.00,  0.00},
           {-8.96,  9.50}, { 2.57, -2.40}, {-3.24, -2.04}, { 8.44,  0.00}
    };
  ;
    //Executable statements
    printf( "LAPACKE_zheev (row-major, high-level) Example Program                         Results\n" )    ;
  ;
    //Print martix
    print_matrix( "Input Matrix", n, n, ah, lda );
  ;
    //Solve eigenproblem
    info = LAPACKE_zheev( LAPACK_ROW_MAJOR, 'V', 'L', n, ah, lda, wr );
  ;
    //Check for convergence
    if( info > 0 ) {
            printf( "zheev algorithm failed to compute eigenvalues.\n" );
            exit( 1 );
    }
  ;
    //Print eigenvalues
    print_rmatrix( "zheev Eigenvalues", 1, n, wr, 1 );
  ;
    //Print eigenvectors
    print_matrix( "Eigenvectors (stored columnwise)", n, n, ah, lda );
  ;
    //Local arrays
    ldcmplex wc[N];
    ldcmplex ag[LDA*N] = {
      { 9.14,  0.00}, {-4.37, -9.22}, {-1.98, -1.72}, {-8.96, -9.50},
      {-4.37,  9.22}, {-3.35,  0.00}, { 2.25, -9.51}, { 2.57,  2.40},
      {-1.98,  1.72}, { 2.25,  9.51}, {-4.82,  0.00}, {-3.24,  2.04},
      {-8.96,  9.50}, { 2.57, -2.40}, {-3.24, -2.04}, { 8.44,  0.00},
    };
  ;
    //Executable statements
    printf( "LAPACKE_zgeev (row-major, high-level) Example Program Results\n" );
  ;
    //Print martix
    print_matrix( "Input Matrix", n, n, ag, lda );
  ;
    //Solve eigenproblem
    info = LAPACKE_zgeev( LAPACK_ROW_MAJOR, 'N', 'V', n, ag, lda, wc, 0, lda, 0, lda);
  ;
    //Check for convergence
    if( info > 0 ) {
            printf( "zgeev algorithm failed to compute eigenvalues.\n" );
            exit( 1 );
    }
  ;
    //Print eigenvalues
    print_matrix( "zgeev Eigenvalues", 1, n, wc, 1);
  ;
    //Print eigenvectors
    print_matrix( "Eigenvectors (stored columnwise)", n, n, ag, lda );
    exit( 0 );
  }

//Auxiliary routine: printing a matrix
void print_matrix( char* desc, lint m, lint n, ldcmplex* a, lint lda ) {
        lint i, j;
        printf( "\n %s\n", desc );
        for( i = 0; i < m; i++ ) {
                for( j = 0; j < n; j++ )
                        printf( " (%6.2f,%6.2f)", creal(a[i*lda+j]),     cimag(a[i*lda+j]) );
                printf( "\n" );
        }
}

//Auxiliary routine: printing a real matrix
void print_rmatrix( char* desc, lint m, lint n, double* a, lint lda ) {
        lint i, j;
        printf( "\n %s\n", desc );
        for( i = 0; i < m; i++ ) {
                for( j = 0; j < n; j++ ) printf( " %6.2f", a[i*lda+j] );
                printf( "\n" );
        }
}

compiled with

g++ diag.cc -L /usr/lib/lapack/ -llapacke -lcblas -o diag.out

The only nonstandard packages being liblapacke-dev, and libcblas-dev, installed via apt-get install. What could possibly go wrong?

The output is

LAPACKE_zheev (row-major, high-level) Example Program Results

 Input Matrix
 (  9.14,  0.00) (  0.00,  0.00) (  0.00,  0.00) (  0.00,  0.00)
 ( -4.37,  9.22) ( -3.35,  0.00) (  0.00,  0.00) (  0.00,  0.00)
 ( -1.98,  1.72) (  2.25,  9.51) ( -4.82,  0.00) (  0.00,  0.00)
 ( -8.96,  9.50) (  2.57, -2.40) ( -3.24, -2.04) (  8.44,  0.00)

 zheev Eigenvalues
 -18.96 -12.85  18.78  30.71

 Eigenvectors (stored columnwise)
 (  0.16,  0.00) (  0.57,  0.00) ( -0.73,  0.00) (  0.35,  0.00)
 (  0.26, -0.81) (  0.17, -0.25) (  0.22, -0.38) (  0.06, -0.02)
 (  0.29,  0.27) ( -0.11, -0.30) ( -0.26, -0.42) ( -0.50, -0.50)
 ( -0.21,  0.23) (  0.50, -0.49) (  0.18, -0.09) ( -0.33,  0.51)

LAPACKE_zgeev (row-major, high-level) Example Program Results

 Input Matrix
 (  9.14,  0.00) ( -4.37, -9.22) ( -1.98, -1.72) ( -8.96, -9.50)
 ( -4.37,  9.22) ( -3.35,  0.00) (  2.25, -9.51) (  2.57,  2.40)
 ( -1.98,  1.72) (  2.25,  9.51) ( -4.82,  0.00) ( -3.24,  2.04)
 ( -8.96,  9.50) (  2.57, -2.40) ( -3.24, -2.04) (  8.44,  0.00)

 zgeev Eigenvalues
 ( 25.51,  0.00) (-16.00, -0.00) ( -6.76,  0.00) (  6.67,  0.00)

 Eigenvectors (stored columnwise)
 ( 25.51,  0.00) ( -0.00,  0.00) (  0.00,  0.00) (  0.00, -0.00)
 (  0.00,  0.00) (-16.00, -0.00) (  0.00, -0.00) (  0.00, -0.00)
 (  0.00,  0.00) (  0.00,  0.00) ( -6.76,  0.00) ( -0.00, -0.00)
 (  0.00,  0.00) (  0.00,  0.00) (  0.00,  0.00) (  6.67,  0.00)

I tried using the Upper triangle, filling the matrix and various other fixes. Same results each time.

I'm suspicious of the #define ldcmplex lapack_complex_double macro, but all the documentation I can find says I should be using a double complex, so I'm a bit lost. Anyway, if that was the problem, why would zgeev work?

Anyway, here's the python check script:

#!/usr/bin/env python
from numpy import linalg as li
import numpy as np

mat=np.array([
[   9.14 + 0.00j,  0.00 + 0.00j,  0.00 + 0.00j,  0.00 +0.00j],
[  -4.37 + 9.22j, -3.35 + 0.00j,  0.00 + 0.00j,  0.00 +0.00j],
[  -1.98 + 1.72j,  2.25 + 9.51j, -4.82 + 0.00j,  0.00 +0.00j],
[  -8.96 + 9.50j,  2.57 - 2.40j, -3.24 - 2.04j,  8.44 +0.00j]])
mat[0]=np.conj(mat[:,0])
mat[1]=np.conj(mat[:,1])
mat[2]=np.conj(mat[:,2])
mat[3]=np.conj(mat[:,3])

mat=np.matrix(mat)

w, v = li.eig(mat)

print w
print v

It agrees with zgeev (up to some rounding/machine errors). The result is also confirmed by the intel tutorial linked above. The zheev method is clearly in a minority of one, I just don't know why.

I've tried this on a couple of machines:

Linux parabox 4.8.0-52-generic #55-Ubuntu SMP Fri Apr 28 13:28:50 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
Linux glass 4.10.0-21-generic #23-Ubuntu SMP Fri Apr 28 16:14:22 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Any and all help appreciated.

Body:
This is what I get when I run your python script:

$ ./diag.py
[ 25.51400517 +1.20330583e-15j -16.00474647 -2.91871119e-15j
  -6.76497015 -6.59630730e-16j   6.66571145 +1.54590036e-16j]
[[ 0.69747489+0.j          0.21857873+0.26662122j  0.47736933+0.26449375j     -0.02829581-0.30988089j]
 [-0.21578745+0.28003172j  0.69688890+0.j         -0.14143627-0.2852389j       0.24437193-0.47778739j]
 [-0.14607303-0.08302697j -0.01445974-0.60818924j 0.44678181+0.26546077j       0.57583205+0.j        ]
 [-0.34133591+0.49376693j  0.15930699-0.00061647j  0.57507627+0.j             -0.45823952+0.2713093j ]]

I don't know what that's supposed to match.  The eigenvalues match, but not the eigenvectors.


问:
Integer key to date in a named calculation
Trying to do a named calculation in SSAS from a integer key to Quarter.
IntegerDateKey Below:

```<code>  SalesDateKey
   20100101
   20100101
   20100101
   20100102
   20100102
   20100102
   20100102
</code>```

This doesn't work and no matter how I cast it, I can't get it to work.

```<code>  CONVERT(char(4), YEAR(SalesDateKey))+
  CASE
      WHEN MONTH(SalesDateKey) BETWEEN 1 AND 3 THEN 'Q1'
      WHEN MONTH(SalesDateKey) BETWEEN 4 AND 6 THEN 'Q2'
      WHEN MONTH(SalesDateKey) BETWEEN 7 AND 9 THEN 'Q3'
      ELSE 'Q4'
  END
</code>```

Any help would be greatly appreciated. Please test your findings on a named calculation in SSAS.

答:
Figured it out! </p>

```<code>CAST(DATEPART(YEAR, CAST(CAST(SalesDateKey AS char(8)) AS DateTime)) AS
VARCHAR(4)) + ' - ' +
CASE
   WHEN Month(CAST(CAST(SalesDateKey AS CHAR(8)) AS DATE)) BETWEEN 1 AND 3
   THEN 'Q1'
   WHEN Month(CAST(CAST(SalesDateKey AS CHAR(8)) AS DATE)) BETWEEN 4 AND 6
   THEN 'Q2'
   WHEN Month(CAST(CAST(SalesDateKey AS CHAR(8)) AS DATE)) BETWEEN 7 AND 9
   THEN 'Q3'
   ELSE 'Q4'
END
</code>```

Body:
Trying to do a named calculation in SSAS from a integer key to Quarter.
IntegerDateKey Below:

  SalesDateKey
   20100101
   20100101
   20100101
   20100102
   20100102
   20100102
   20100102

This doesn't work and no matter how I cast it, I can't get it to work.

  CONVERT(char(4), YEAR(SalesDateKey))+
  CASE
      WHEN MONTH(SalesDateKey) BETWEEN 1 AND 3 THEN 'Q1'
      WHEN MONTH(SalesDateKey) BETWEEN 4 AND 6 THEN 'Q2'
      WHEN MONTH(SalesDateKey) BETWEEN 7 AND 9 THEN 'Q3'
      ELSE 'Q4'
  END

Any help would be greatly appreciated. Please test your findings on a named calculation in SSAS.

Body:
Figured it out!

CAST(DATEPART(YEAR, CAST(CAST(SalesDateKey AS char(8)) AS DateTime)) AS
VARCHAR(4)) + ' - ' +
CASE
   WHEN Month(CAST(CAST(SalesDateKey AS CHAR(8)) AS DATE)) BETWEEN 1 AND 3
   THEN 'Q1'
   WHEN Month(CAST(CAST(SalesDateKey AS CHAR(8)) AS DATE)) BETWEEN 4 AND 6
   THEN 'Q2'
   WHEN Month(CAST(CAST(SalesDateKey AS CHAR(8)) AS DATE)) BETWEEN 7 AND 9
   THEN 'Q3'
   ELSE 'Q4'
END


问:
How to implement timer interruption in this code to count the amount of seconds of this fibonacci function?
I need to implemet extern void start_stopper(void) and extern void end_stopper().
How implement these two functions so they will count properely the seconds of this program execution?</p>

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

extern void start_stopper(void);

unsigned long int fibo(int n)
{
  if (n <= 1)
    return 1;
  else
    return(fibo(n-1) + fibo(n-2));

} /* fibo */

extern double end_stopper();

void main(void)
 {
   unsigned long int fn;
   unsigned int n;
   double time_in_secs;

   int i1, i2, result;

   printf("Enter an integer <= 47 )\n");
   scanf("%u", &n);

   system("time");
   start_stopper();

   fn = fibo(n);
   system("time");

   time_in_secs = end_stopper();

   printf("Fibo(%u) = %lu\n", n, fn);
   printf("Computation took %lf secs\n", time_in_secs);

 } /* main */
</code>```

答:
Instead of using the time shell command, you should use the clock() function defined in <time.h>. It is far more precise with much less overhead.

Here is the modified code:

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

unsigned long int fibo(int n) {
    if (n <= 1)
        return 1;
    else
        return fibo(n - 1) + fibo(n - 2);
}

int main(void) {
    unsigned long fn;
    unsigned int n;
    double time_in_secs;

    printf("Enter an integer <= 47:\n");
    if (scanf("%u", &n) == 1) {
        clock_t start = clock();

        fn = fibo(n);

        time_in_secs = (double)(clock() - t) / CLOCKS_PER_SEC;

        printf("Fibo(%u) = %lu\n", n, fn);
        printf("Computation took %f secs\n", time_in_secs);
    }
    return 0;
}
</code>```

If your are programming on an MS/DOS system, and clock() is not available there, you could try and define it this way:

```<code>#define CLOCK_PER_SEC  18.2
#define clock() (*(unsigned long __far *)0x0040006C)
</code>```

The tick interrupt (INT 8) updates a 32-bit tick counter 65536 times per hour. The 32-bit tick counter is accessible at absolute address 0040:006C.  If you want more precise timings, you can try and reprogram the interrupt controller to make it fire interrupts faster. You then need to install your own handler to filter these interrupts to avoid messing the system's tick counter.

Here is a useful site for more info about the PC/DOS system and its BIOS data: http://www.fysnet.net/rombios.htm

Also note that your Fibonacci sequence is not consistent with the classic definition fib(0) = 0, fib(1) = 1.  The Wikipedia article is here.

Here is the corresponding code:

```<code>unsigned long int fibo(int n) {
    if (n <= 1)
        return n;
    else
        return fibo(n - 1) + fibo(n - 2);
}
</code>```

Body:
I need to implemet extern void start_stopper(void) and extern void end_stopper().
How implement these two functions so they will count properely the seconds of this program execution?

#include <stdio.h>
#include <dos.h>

extern void start_stopper(void);

unsigned long int fibo(int n)
{
  if (n <= 1)
    return 1;
  else
    return(fibo(n-1) + fibo(n-2));

} /* fibo */

extern double end_stopper();

void main(void)
 {
   unsigned long int fn;
   unsigned int n;
   double time_in_secs;

   int i1, i2, result;

   printf("Enter an integer <= 47 )\n");
   scanf("%u", &n);

   system("time");
   start_stopper();

   fn = fibo(n);
   system("time");

   time_in_secs = end_stopper();

   printf("Fibo(%u) = %lu\n", n, fn);
   printf("Computation took %lf secs\n", time_in_secs);

 } /* main */

Body:
Instead of using the time shell command, you should use the clock() function defined in <time.h>. It is far more precise with much less overhead.

Here is the modified code:

#include <stdio.h>
#include <time.h>

unsigned long int fibo(int n) {
    if (n <= 1)
        return 1;
    else
        return fibo(n - 1) + fibo(n - 2);
}

int main(void) {
    unsigned long fn;
    unsigned int n;
    double time_in_secs;

    printf("Enter an integer <= 47:\n");
    if (scanf("%u", &n) == 1) {
        clock_t start = clock();

        fn = fibo(n);

        time_in_secs = (double)(clock() - t) / CLOCKS_PER_SEC;

        printf("Fibo(%u) = %lu\n", n, fn);
        printf("Computation took %f secs\n", time_in_secs);
    }
    return 0;
}

If your are programming on an MS/DOS system, and clock() is not available there, you could try and define it this way:

#define CLOCK_PER_SEC  18.2
#define clock() (*(unsigned long __far *)0x0040006C)

The tick interrupt (INT 8) updates a 32-bit tick counter 65536 times per hour. The 32-bit tick counter is accessible at absolute address 0040:006C.  If you want more precise timings, you can try and reprogram the interrupt controller to make it fire interrupts faster. You then need to install your own handler to filter these interrupts to avoid messing the system's tick counter.

Here is a useful site for more info about the PC/DOS system and its BIOS data: http://www.fysnet.net/rombios.htm

Also note that your Fibonacci sequence is not consistent with the classic definition fib(0) = 0, fib(1) = 1.  The Wikipedia article is here.

Here is the corresponding code:

unsigned long int fibo(int n) {
    if (n <= 1)
        return n;
    else
        return fibo(n - 1) + fibo(n - 2);
}