text:
Q: Matlab: How to count? I have above image with white background. I need to count the circles and get diameter of each circle using morphological, logical and set operations of matlab. Any ideas how to do it?

A: Use regionprops:
img = imread('http://i.stack.imgur.com/OJidJ.png');
bw = img(:,:,1) < 128; %// convert to logical mask
d = regionprops( bw, 'EquivDiameter' );
d = [d.EquivDiameter]; %// array with diameter of each coin.


text:
Q: Deeplink not handle http and https scheme I have used the following code to handle deep links in Android
<!-- Deep linking -->
<meta-data android:name="flutter_deeplinking_enabled" android:value="true" />
<intent-filter android:autoVerify="true">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="http" android:host="mywebsite.com" />
    <data android:scheme="https" />
</intent-filter>

But when I set the scheme to HTTP or HTTPS, it doesn't work and the website opens in the browser.
This code opens the website in the browser:
<data android:scheme="http" android:host="mywebsite.com" />

This code will open my app:
<data android:scheme="myapp" android:host="app" />

A: You cannot request domain login for android app. If you want a web project, then you should write codes related to the web project. Even then, you'll be using "localhost".

A: In android:host="app.page.link" would be same as you set in your firebase dynamic link
It should look like this

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I delete a file from disk in IntelliJ IDEA? How do I delete a file from disk (unlink) in IntelliJ IDEA?
I am referring to the file that is currently open in the editor tab.

A: Navigate | Select In... (Alt+F1) | Project View, Del or Delete from the context menu.
Or use Refactor | Safe Delete (Alt+Del).


text:
Q: Vim normal! sending literal  string instead of whitespace character I'm not sure what I'm doing wrong here.
:normal! I###<Space><Esc>

The end result I want when I execute this command over a word is this:
### word

But instead I get this:
###<Space>word

A: Vim's :normal is a nightmare with anything moderately complicated. I don't remember why, but this is the easiest way to get what you want. You need to escape the opening < in a string passed to execute.
execute "normal! I###\<Space>\<Esc>"

Edit: Vim doesn't really explain why, but :help normal
        An alternative is to use |:execute|, which uses an
        expression as argument.  This allows the use of
        printable characters to represent special characters.

A: Lets first explain the vim command:

*

*:normal! run the rest of the commands as normal mode

*I enter insert mode from the beginning of the line <shift> + i

*###<Space><Esc> - type out the characters ###<Space><Esc> literally since we are in insert mode (notice that if you just enter insert mode, and type ###<space><esc>, you'll get just that literally.)

When this command finishes, you'll notice how it's still in normal mode. This means that your command can just omit the <space><esc> and enter the space literally:
:norm! I###

(There is an extra space after the last hash)


text: Q: How can I make a Tomb of the Mask type of movement I tried to come up with an idea on how to make a Tomb of the Mask type of movement but so far all of my ideas have failed. Any ideas that I could try next?


text:
Q: ¿Cómo puedo salir de un bucle dada una cadena de caracteres? estaba haciendo una función que pida al usuario palabras en inglés y su traducción al español y para salir del bucle, el usuario debe escribir la palabra "Fin".
MAX y PAL son dos constantes, con el valor de 100 y 40 respectivamente donde MAX es el máximo de palabras que puede introducir el usuario y PAL es el tamaño de la cadena de caracteres.
Las palabras se guardan en el registro siguiente.
typedef struct {
    char ingles[PAL];
    char espanol[PAL];
} tDiccionario;

Aquí el código.
void IntroducirPalabras(tDiccionario *palabras){
    puts("Introduzca 1 palabra en ingles, pulse ENTER, y luego la traduccion en Espanol, si desea no introducir mas, teclee 'Fin'");

    int i = 0, fin = 1;

    do{
        if(i > MAX || !fin)
            printf("\nFin.\n");
        else{
            printf("\nIntroduzca la palabra en ingles (o Fin para finalizar): ");
            fflush(stdin);

            if(fgets(palabras[i].ingles, PAL, stdin))
                palabras[i].ingles[strcspn(palabras[i].ingles, "\n")] = 0;

            if(palabras[i].ingles == "Fin")
                fin = 0;
            else{
                printf("\nIntroduzca su traduccion en espanol: ");
                fflush(stdin);

                if(fgets(palabras[i].espanol, PAL, stdin))
                    palabras[i].espanol[strcspn(palabras[i].espanol, "\n")] = 0;
            }
        }

        i++;

    } while(i < MAX || !fin);
}

En la ejecución del programa, escribo Fin y es como si no entrara en la sentencia de  if(palabras[i].ingles == "Fin")


text:
Q: simple_form map check_boxes collection to integer mask I want to extend registration form in one Rails app for users to be able to submit their roles.
It basically adds few check boxes in the form.
I'm using simple_form gem and it looks like this:
    = f.input :role_mask, as: :check_boxes, label: false,
        collection: ['Investor', 'Mentor', 'Developer', 'Other']

To keep this information in database, I added role_mask:integer field to the User model.
So if the user checked, say, Mentor and Developer, it should store 6 in role_mask field (its mask = 0110).
I know, this mapping could be done inside controller, but since I'm contributing to this app, I don't want to touch controller. So I'm wondering does simple_form provide some tools to solve this or I should use JavaScript to do the mapping? Thanks for any help.

A: You are right. If you don't want to do it in the controller you will have to do it client side. There is no way to simple_form generate the javascript, so you will have to do it yourself.


text:
Q: Funny issue with incorrect forward reference There is well known example from JLS about incorrect forward reference error:
class Test1 {
   int i = j; // compile-time error:
   // incorrect forward reference
   int j = 1;
}

OK, I said, and apply well-known "hack" with keyword this:
class Test1 {
    int i = ++this.j;
    {
// line#4: System.out.println("j = " + j); // compile-time error: illegal forward reference
        System.out.println("j = " + this.j);
    }
    int j = this.j + 1;
    {
        System.out.println("j = " + j);
    }
}

Output will be:
j = 1
j = 2

Who can explain, why I can not access to variable j in line #4?
Is variable j initialized in this line or not?
If it isn't, how I can get value 1 in this.j and 2 on next step?
If if it is, why I can't get access via simple name?

A: It looks like what is happening is similar to what's happening in this question.
If you manage to work around the language restrictions and make a reference to an uninitialized variable, it will have it's default value (0 in the case of int).
So in this case, you call int i = ++this.j. Since  isn't yet initialized, it takes value 0, which is then incremented. On your next call, it preserves the value it had before and adds one to it.
I found another answer which goes into more detail about the restrictions on initialization. The key part is this

The declaration of a member needs to appear textually before it is
  used only if the member is an instance (respectively static) field of
  a class or interface C and all of the following conditions hold
...

*

*The usage is via a simple name

So basically, what you're doing is allowed just because the language designers didn't explicitly forbid it.
To deal with the other part of your question, I'll reference the Java documentation.

The Java compiler copies initializer blocks into every constructor.

So the initialization code you wrote happens in the constructor of the object. When the object is created, both variables are initialized with values of 0, after which your code runs to modify those values. So no, the line int i = ++this.j; doesn't initialize j. That happens automatically before that line is reached.

A: Q.Is variable j initialized in this line or not?**
Yes it is initialized as can be seen in the below class file of your java code.
// Compiled from Test1.java (version 1.6 : 50.0, super bit)
public class com.test.java.Test1 {

  // Field descriptor #6 I
  int i;

  // Field descriptor #6 I
  int j;

  // Method descriptor #9 ()V
  // Stack: 4, Locals: 1
  public Test1();
     0  aload_0 [this]
     1  invokespecial java.lang.Object() [11]
     4  aload_0 [this]
     5  aload_0 [this]
     6  dup
     7  getfield com.test.java.Test1.j : int [13]
    10  iconst_1
    11  iadd
    12  dup_x1
    13  putfield com.test.java.Test1.j : int [13]
    16  putfield com.test.java.Test1.i : int [15]
    19  aload_0 [this]
    20  aload_0 [this]
    21  getfield com.test.java.Test1.j : int [13]
    24  iconst_1
    25  iadd
    26  putfield com.test.java.Test1.j : int [13]
    29  return
      Line numbers:
        [pc: 0, line: 4]
        [pc: 4, line: 5]
        [pc: 19, line: 10]
        [pc: 29, line: 4]
      Local variable table:
        [pc: 0, pc: 30] local: this index: 0 type: com.test.java.Test1
}

Coming to your question as to why you cannot access j with simple name, it may have to do with how the compiler intelligently reorganizes and substitutes direct access to j with this.j. This looks like it doesnot happen when you try to access it in the initialization block (reasons not known to me) but the below code works with direct reference (may be because compiler smartly puts this referenece when we try to access j)
public Test1() {
        System.out.println(j);
    }
    int i = ++this.j;
    {
        // line#4: System.out.println("j = " + j); // compile-time error: illegal forward reference
        //System.out.println("j = " + this.j);
    }
    int j = this.j + 1;


text:
Q: android recorder start invalid state 4 I don't kno why but the start() method throw an error and crash the app:
public class Noise extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.noise);
    MediaRecorder recorder=new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    try{
        recorder.prepare();
    }catch(IllegalStateException e){
        Log.d("Error",e.toString());
        e.printStackTrace();
    }catch(IOException e){
        Log.d("Error",e.toString());
        e.printStackTrace();
    }
    recorder.start();
    Timer timer=new Timer();
    timer.scheduleAtFixedRate(new RecorderTask(recorder), 0, 500);
}
private class RecorderTask extends TimerTask{
    TextView risultato=(TextView) findViewById(R.id.risultato_recorder);
    private MediaRecorder recorder;
    public RecorderTask(MediaRecorder recorder){
        this.recorder = recorder;
    }
    public void run(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                risultato.setText("" + recorder.getMaxAmplitude());
            }
        });
    }
}
}

if i remove the prepare and the start, it work but return always 0 in the textview.
anyone can help me? this thing make me crazy
this is the logcat: https://dl.dropbox.com/u/16047047/log.txt
and in the phone, it crash.

A: It seems you miss a recorder.setOutputFile(PATH_NAME); See the documentation for MediaRecorder
At least, this is what the stack trace tells us:
11-29 16:04:08.933: W/System.err(9323): java.io.IOException: No valid output file

This is the relevant source code for MediaRecorder.prepare():
public void prepare() throws IllegalStateException, IOException
{
    if (mPath != null) {
        FileOutputStream fos = new FileOutputStream(mPath);
        try {
            _setOutputFile(fos.getFD(), 0, 0);
        } finally {
            fos.close();
        }
    } else if (mFd != null) {
        _setOutputFile(mFd, 0, 0);
    } else {
        throw new IOException("No valid output file");
    }
    _prepare();
}

(you can read it on grepcode) The exception is thrown if both the File object and the FileDescriptor are null. So I don't think you can use MediaRecorder without supplying a file. You can try the tricky /dev/null but I don't know if it works, and can't test right now

A: Looks like you're calling start() twice, once in the Activity onCreate(), once in the RecorderTask constructor. You should only need one. Without knowing how it crashes -- like a stack trace -- it's hard to know more.

A: Similar problem might happens with mediaRecoder.setOutputFormat(value) Check this post https://stackoverflow.com/a/37232920/3533092


text:
Q: x86_64 fasm: how to check if the result of a division is an integer and set the value of the array? How to check if the result of a division is an integer and, depending on it, do the analog of if else construction in other languages? I've tried subtracting one int from another and checking if the result is lesser than the subtractor, but it looks very primitive to me.
EDIT: I'd be also grateful if somebody shows me how to set the element of the passed as the argument to an assembly function C array. For example:
    mov dd [rdx], 0

where rdx is a pointer to an array, produces a segmentation fault when called from C.
EDIT 2: I'm adding the code snippet (the commented lines are causing an error):
format ELF64

section '.text' executable

public have_int_solns

have_int_solns:
    ;rdi
    ;rsi
    ;rdx
    ;ecx
    dec ecx
    l1:
    mov eax, [rsi]
    mov ebx, [rdi]
    xor edx, edx
    div ebx
    cmp edx, 0
    je Equal
;     mov dword [rdx], 0
    jmp Both
    Equal:
;     mov dword [rdx], 1
    Both:
    add edi, 4
    add rsi, 4
    add rdx, 4
    loop l1
    ret

section '.data' writable


text:
Q: Is it possible to have a mapped document as a nested object? [ElasticSearch] I have the following document types defined in elasticSearch:
"token":{
    "properties":{
         "beginning":{"type": "string", "index":"not_analyzed", "doc_values":"true"},
         "end":{"type": "string", "index":"not_analyzed", "doc_values":"true"},
         "semantic_category":{"type": "string", "index":"not_analyzed", "doc_values":"true"},
    }
}

"file":{
     "properties":{
         "abstract":{"type": "string", "index":"not_analyzed", "doc_values":"true"},
         "title":{"type": "string", "index":"not_analyzed", "doc_values":"true"},
    }
}

I would like to have 2 nested Token objects in the "file" document, one being title_tokens and the other being abstract_tokens. However the only way I found is to define two different nested types.
Is there a way to include a document type as an object in a document?


text:
Q: Why does my sprite flash in LibGDX? I'm trying to create a main menu just using a sprite. However, when it gets rendered and everything, the sprite flashes quickly. Why is it doing this?
@Override
public void show() {
    batch = new SpriteBatch();

    texture = new Texture("ui/mainmenu.png");
    mainMenu = new Sprite(texture);
    mainMenu.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

    batch.begin();
    mainMenu.draw(batch);
    batch.end();
}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}

A: this goes in your render method:
batch.begin();
mainMenu.draw(batch);
batch.end();

Render is the method that is constantly called, show is only called once when the screen is shown.

A: If you use this exact code, things should work. Each frame, you clear your screen, then render your sprite.
@Override
public void show() {
    batch = new SpriteBatch();

    texture = new Texture("ui/mainmenu.png");
    mainMenu = new Sprite(texture);
    mainMenu.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

}

@Override
public void render(float delta) {
    //clear screen to black.
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    //render sprite
    batch.begin();
    mainMenu.draw(batch);
    batch.end();
}

A: Render your sprite using orthographic camera. this might work for you
OrthographicCamera cam;
@Override
public void show() {
    batch = new SpriteBatch();
    cam= new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    cam.position.set(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2,0);
    cam.update();
    texture = new Texture("ui/mainmenu.png");
    mainMenu = new Sprite(texture);
    mainMenu.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

}

@Override
public void render(float delta) {
    //clear screen to black.
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    //render sprite
    batch.setProjectionMatrix(cam.combined);
    batch.begin();
    mainMenu.draw(batch);
    batch.end();
}


text:
Q: How to override method from the parent in multiple classes in the same way without creating class between parent and the child? It's hard to properly ask, so I will create an example:
class Animal {

    public void doSomething() {
    }
}

class Dog extends Animal {

}

class Cat extends Animal {

}

class Sheltie extends Dog {

    @Override
    public void doSomething() {
        super.doSomething();
        System.out.println("Exactly the same");
    }
}

class Abbysian extends Cat {

    @Override
    public void doSomething() {
        super.doSomething();
        System.out.println("Exactly the same");
    }
}

Is there a way in this case that I can override the doSomething() method in both Sheltie and Abbysian without duplicating a code and even typing @Override public void doSomething(). On top of that, I'd actually like to call super.doSomething() as well. I cannot change inheritance at all.
If those classes extended directly Animal I would create a class "between" them. I was thinking of using interface with default method but that didn't help as well.

A: Once you broke out into Cats and Dogs you discovered the limitations of class hierarchy - eventually you'll hit a point of no return.
Thankfully there is a thing called an Entity Component System (ECS) that is commonly used when you want to mish-mash functionality amongst many different entities.
A cat can wag its tail. A dog can wag its tail... but not all animals have tails!
So you register a component called Tail to the tailed animal entities.
I found this on the StackExchange code review group.  https://codereview.stackexchange.com/questions/163215/entity-component-system-ecs

A: Decorator pattern can do this trick but it would be applied to specific instances of Sheltie / Abyssinian not to these classes:
class AnimalDecorator extends Animal {
    protected Animal animal;

    public AnimalDecorator(Animal animal) {
        this.animal = animal;
    }

    @Override
    public void doSomething() {
        animal.doSomething(); // instead of call to super.doSomething
        System.out.println("Exactly the same");
    }
}

class Sheltie extends Dog { // doSomething not overridden
}

class Abyssinian extends Cat { // doSomething not overridden
}

// decorated instances
Animal sheltie = new AnimalDecorator(new Sheltie());
Animal abyssinian = new AnimalDecorator(new Abyssinian());
sheltie.doSomething();
abyssinian.doSomething();


text:
Q: What is different nami wallet signing and payment.skey signing? I built transaction at nodejs by using cardano-cli.
cardano-cli transaction build \
--alonzo-era \
--testnet-magic 1 \
--tx-in dbf7f56f844cc4b85daccb62bedf4eeff0a84cb060f0f79b206c7f087b3f0ba1#0 \
--tx-in dbf7f56f844cc4b85daccb62bedf4eeff0a84cb060f0f79b206c7f087b3f0ba1#1  \
--tx-in 61b88efd41ccbb0e71c48aca2cbe63728078ec7fb20ec9c27acfe33d0647248d#0 \
--tx-in-script-file /cardano/plutus/direct-sale.plutus \
--tx-in-datum-file /cardano/temp/testnet/datums/list.json \
--tx-in-redeemer-file /cardano/temp/testnet/redeemers/buy.json \
--required-signer-hash 2be4a303e36f628e2a06d977e16f77ce2b9046b8c56576bb5286d1be \
--tx-in-collateral dbf7f56f844cc4b85daccb62bedf4eeff0a84cb060f0f79b206c7f087b3f0ba1#1 \

... some txout ...

--change-address addr_test1qq47fgcrudhk9r32qmvh0ct0wl8zhyzxhrzk2a4m22rdr0sqcga2xfzv6crryyt0sfphksfr947jjddy3t4u0qwfmmfq2h0pj8 \
--protocol-params-file /cardano/testnet/protocol-parameters.json \
--mint "2 20edea925974af2102c63adddbb6a6e789f8d3a16500b15bd1e1c32b.4143544956495459" \
--mint-script-file /cardano/plutus/activity-minter.plutus \
--mint-redeemer-file /cardano/redeemers/mint.json \
--invalid-before 19059345 \
--invalid-hereafter 19059495 \
--out-file ./tx.raw

After run this command, I got cborHex and I used this at frontend.
When I sign by using name wallet, I got some error.
"transaction submit error ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (FromAlonzoUtxowFail (WrappedShelleyEraFailure (InvalidWitnessesUTXOW [VKey (VerKeyEd25519DSIGN \"cf949f966b426f25db11b6062edc31312001e3cd0ced4c6c7db3da7b5ac9766b\")])))])"

But when I sign with payment.skey at nodejs, it was worked.
I was discuss Alexd1985 at cardano forum.
https://forum.cardano.org/t/how-to-resolve-shelleytxvalidationerror-shelleybasederababbage-applytxerror-utxowfailure-fromalonzoutxowfail-wrappedshelleyerafailure-invalidwitnessesutxow-error/113555/4
What is solution for this problem?


text:
Q: JSP, EL, JSTL: learning from a web designer perpective I have two books geared toward learning JSP. From what I've read, one motivating feature/benefit is that it is easier for web designers (they apparently don't, as a rule, know Java) to work with dynamic pages via EL/JSTL.
From what I've seen so far, learning EL/JSTL requires a basic understanding of Java. I have yet to see an example that doesn't have a Java class to reference. Since that is what I've seen, I wonder if someone can tell me that this is true or not.
To make the question clear: Do web designers have to get a grasp, on a very basic level, of how a Java class works (e.g. fields, setters, getters, args, constructors...)?
This question is really meant to help me decide whether or not to ask another question; it is a qualifier.

A: In my experience, JSPs are not developed by web designers, but by the Java developers who also developed the Java classes which constitute the presentation layer of the application.
Those are rarely very good at web design, but most of the pages of an application follow the same design principles, and once a web designer has designed one or a few static pages with the appropriate markup and CSS styles, the developer can reuse this template and make his own dynamic pages without the help of a web designer.

A: Technically, you can create a very substantial set of custom tag libraries that cover everything you want to do that would need to deal with classes and other Java artifacts without those libraries.
In practice, however, such comprehensive taglibs are rarely created and maintained.
Thankfully, only a basic understanding of Java is needed to do most things that a non-programmer would need to get at when dealing with the page layout in the JSP.
So, while the promise that a designer doesn't need to know Java can be held to, the reality is that they will need to be able to understand how to use some basic Java to do things. In my experience, this is well within the abilities of most designers.


text:
Q: Correct syntax for multiple loops with list integers in Python I'm working on a loop that is basically the following
MyList = ['cttgaaat',attcggat',gtatcaag'...]

for value in text_file:
     print(key_nucleotide_position)

key_nucleotide_position is a given number from a text file, which would
return something like this
In [1]: 1
        3
        5
        7
        ...

I'm trying a for loop that looks something like this
for value in MyList:
     print(value[key_nucleotide_position])
     print('\n')

However, instead of printing what I want, which would be
t
t
t

g
c
t

a
g
a

t
t
g

I'm getting only this
t

t

g

I've managed to get it to work when I put a for loop within another for loop, but that just gives me a super long sequence of nucleotides (497 lines) in this format
a
t
t
g
g
c
g
...

which I know how to analyze, but not how to split it in the manner I want it to be split, which would be every 91 nucleotides - even then, the return value doesn't exactly make sense for the number of nucleotides I should get.
Any help would be appreciated.

A: The easiest way to help is with full details. I will infer this is school related and try to point you in the right direction. It is most helpful to post reproducible examples so that someone can easily recreate the setup and troubleshoot. Try using things like gists or pastebin if you have long files.
From your description, I think you have:

*

*a list of small sequences

*a text file of numbers, one per line

I think you want to take your list of n sequences, iterate through the integers in your file of key_nucleotide_position integers, and extract the ith element of MyList?
Let's just walk through what you're doing, first seeing how you iterate through MyList:
MyList = ['cttgaaat', 'attcggat', 'gtatcaag']
for value in MyList:
     print(value)

cttgaaat
attcggat
gtatcaag

Assuming a number (say, 3) is stored in the variable key_nucleotide_position, you're doing this with each loop:
MyList = ['cttgaaat', 'attcggat', 'gtatcaag']
for value in MyList:
     print(value[3])

Using the first value in MyList, let's see what that does:
'cttgaaat'[3]
g

You're extracting the ith character from the string according to the integer slice.
It's not exactly clear from the question, but I'm guessing you might want to reverse this and get the ith item from the list, not the ith character in the string.
i.e. consider:
MyList[1]

'attcggat'

Now, get your for loop to cycle through such that MyList[foo] changes foo to what you want on each loop.


text:
Q: Unit Testing a @PostConstruct method in a @Startup @Singleton bean I start by saying that I'm at the very beginning with my adventure with java-ee and arquillian (unit testing in general).
I'm using wildfly 8.0.0CR1.
I've a class (I'm going to call this "Initialization Bean") that is a simple @Singleton @Startup bean with a @PostConstruct method that does some basic db's initialization .
It's counterpart is a unit test that inside the @Before method, truncates all db's tables to prepare the database for the initialization phase.
The problem is that the Initialization Bean @PostContruct method gets called before my unit test is set up so that the method that should truncate all database table is actually called after the Initialization Bean @PostContruct method.
How can I debug a @PostContruct method in a @Singleton @Startup bean correctly?
I hope I've been enough clear, otherwise tomorrow I'll post some real code.
Thanks in advance

A: Did you annotate your init bean with @javax.ejb.Singleton?
I was experiencing the same problem, then I noticed that I annotated the init bean with @javax.inject.Singleton. After fixing the annotation the @PostConstruct method is called.

A: You could use reflection to instantiate any @StartUp classes and invoke the @PostConstruct methods before each test class. Apparently this is easily done with Spring but we are not using Spring in this environment. Here is an example of how I did it:
public class BaseTest {
    @BeforeClass
    public static void instantiateStartupClasses() throws InvocationTargetException, IllegalAccessException, InstantiationException {
        Reflections reflections = new Reflections("com.company.project");
        //Find all classes annotated with Startup in a given package.
        Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Startup.class);
        for(Class clazz : classes) {
            if(clazz.isInterface()) continue;
            //Instantiate the object
            Object instantiatedClass = clazz.newInstance();
            //Find any PostConstruct methods on the class and invoke them using the instantiated object.
            for(Method method : clazz.getDeclaredMethods()) {
                if(method.isAnnotationPresent(PostConstruct.class)) {
                    //Invoke the post constructor method.
                    method.invoke(instantiatedClass);
                }
            }
        }
    }
}

A: There is one way possible solution of the problem. You should not use Autowire for creating your bean objects with @PostConstruct method. You can create the bean through java code.
1 make in test class a method like this:
private BeanFactory getTestBeanFactory() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:<your test context>-test.xml");
    return applicationContext.getAutowireCapableBeanFactory();
}

2 in test do this code:
// get your bean object
YourBean yourBean = getTestBeanFactory().getBean(YourBean.class);
// call manually a post construct method of your bean
yourBean.<the post construct method of your bean>();
// do something with the yourBean
...

it`s work fine
good luck


text:
Q: how to send https/http request with network credentials in go in c#

var uri = new Uri("https://demo.com/");
                var encoding = new UTF8Encoding();
                var request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "POST";

                request.Credentials = new NetworkCredential(utility.commonkey, utility.commonsecrerkey);
                request.ContentType = "application/json";
                request.Accept = "application/vnd.demo+json;version=3;";
                request.ContentLength = encoding.GetByteCount(json);
                request.Headers.Add("data", json);
                HttpWebResponse response = null;

and in go i can add only add these

req.Header.Set("Content-Type", "application/json")
 req.Header.Set("Authorization", "Basic sdfsfscefewfewfew")
 req.Header.Set("Accept", "application/vnd.demo+json; version=3;")

here in go the challenge is how to add network credentials in go

A: From what I see in the C# docs what you're referring at as keys, could only be username and password. You could use the analogue http.Request's method to set username and password for basic auth.
// username has the same value as utility.commonkey
// password is the corresponding password in plain text
req.SetBasicAuth(username, password);

Don't forget to remove the following line from your Go code as well
req.Header.Set("Authorization", "Basic sdfsfscefewfewfew")


text:
Q: app sandbox container-migration.plist doesn't move files I have set up my container-migration.plist and rechecked it many times. My signing certificates are all ok and the old app plist is migrated automatically to the container of the new sandboxed app as it should. I have support files in the old app's ~Application Support/Birthdaybook folder and they are not being migrated on first launch of sandboxed app to the new container.
I remove the new container com.robdutoit.birthdayBook each time before testing to trigger the migration. The new container gets created with the app plist in Preferences but the Birthdybook folder is not moved to the Application Support folder in the new container. As suggested in previous post, I tried copying the sandboxed app to the desktop but migration does not work from there either. I have spent days on this and app is ready for submission except for this roadblock.  Any help appreciated.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict&gt
        <key>Move</key>
        <array>
            <string>${ApplicationSupport}/Birthdaybook</string>
        </array>
    </dict>
    </plist>

A: Check Console.app logs. Filter it by your app name. The issue, if any, should be in there. Other than that double check the paths your are using.


text:
Q: I ran bin/buildout to install Plone and got dozens of syntax errors, then failure -- but why? I'm following the instructions for setting up a development environment which can be found at the beginning of the book Professional Plone 4 Development.  I took the following steps.
First, I created a virtualenv called pln and a project directory also called pln
Second, I installed PIL into the pln virtualenv.
Third, I created a buildout.cfg file with the following contents:
[buildout]
extends = http://dist.plone.org/release/4.2/versions.cfg
parts = instance
[instance]
recipe = plone.recipe.zope2instance
user = admin:admin
eggs = Plone

Fourth, I downloaded bootstrap.py from http://svn.plone.org/svn/plone/buildouts/plone-coredev/branches/4.2/bootstrap.py
Fifth, I ran the command python bootstrap.py --distribute, which gave the following output:
Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.29.tar.gz
Extracting in /var/folders/xk/5xt9s5vd4bqd731qdkmxkxyr0000gn/T/tmpwMBNe9
Now working in /var/folders/xk/5xt9s5vd4bqd731qdkmxkxyr0000gn/T/tmpwMBNe9/distribute-0.6.29
Building a Distribute egg in /var/folders/xk/5xt9s5vd4bqd731qdkmxkxyr0000gn/T/tmpKSPdWX
/var/folders/xk/5xt9s5vd4bqd731qdkmxkxyr0000gn/T/tmpKSPdWX/distribute-0.6.29-py2.7.egg
Creating directory '/Users/Jon/dev/pln/bin'.
Creating directory '/Users/Jon/dev/pln/parts'.
Creating directory '/Users/Jon/dev/pln/eggs'.
Creating directory '/Users/Jon/dev/pln/develop-eggs'.
Generated script '/Users/Jon/dev/pln/bin/buildout'.

Sixth, from the project directory I ran the command bin/buildout.  Everything seemed to work okay for a while, but then I began getting scores of error messages similar to these below:
SyntaxError: ("'return' outside function", ('build/bdist.macosx-10.8-x86_64/egg/Products/kupu/plone/kupu_plone_layer/convertContentForKupu.py', 23, None, 'return str(content)\n'))

SyntaxError: ("'return' outside function", ('/Users/Jon/dev/pln/eggs/tmpEwAZSu/Products.CMFPlone-4.2.0.1-py2.7.egg/Products/CMFPlone/skins/plone_scripts/redirectToReferrer.py', 18, None, 'return request.RESPONSE.redirect(target_url)\n'))

SyntaxError: ("'return' outside function", ('build/bdist.macosx-10.8-x86_64/egg/Products/Archetypes/skins/archetypes/unicodeTestIn.py', 11, None, 'return 0\n'))

Finally, running bin/buildout fails with the following error:
While: Installing instance.
Getting distribution for 'plone.outputfilters==1.3'.

An internal error occured due to a bug in either zc.buildout or in a
recipe being used:
Traceback (most recent call last):
File "/Users/Jon/dev/pln/eggs/zc.buildout-1.4.4-py2.7.egg/zc/buildout/buildout.py", line 1683, in main
    getattr(buildout, command)(args)
File "/Users/Jon/dev/pln/eggs/zc.buildout-1.4.4-py2.7.egg/zc/buildout/buildout.py", line 555, in install
    installed_files = self[part]._call(recipe.install)

[about 50 lines of stack trace admitted for brevity...]

File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 365, in _read_status
line = self.fp.readline()
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 447, in readline
data = self._sock.recv(self._rbufsize)

error: [Errno 54] Connection reset by peer

Why is the connection reset by the peer at the end there?  Which peer is this, and how can I have any control over an error like this?
Thanks much, in advance, for your help.

A: From the book "Professional Plone 4 Development" I have the answer to why I am getting syntax errors:

You may also see some warnings about 'syntax errors' fly past when
  Setuptools/Distribute tries to pre-compile certain Python scripts. You
  can safely ignore these. They are issued because, these scripts are
  not normal Python modules, but rather scripts intended to be executed
  in Zope's untrusted scripting environment.

*

*Aspeli, Martin (2011-08-26). Professional Plone 4 Development (p. 38). Packt Publishing. Kindle Edition.

I'm still not sure why bin/buildout fails, however.  I just tried again with everything fresh and I got this error:

While:
  Installing.
  Getting section instance.
  Initializing section instance.
  Installing recipe plone.recipe.zope2instance.
  Getting distribution for 'docutils==0.9.1'.

An internal error occured due to a bug in either zc.buildout or in a
recipe being used:
Traceback (most recent call last):
  File "/Users/Jon/dev/pl/eggs/zc.buildout-1.4.4-py2.7.egg/zc/buildout/buildout.py", line 1683, in main
    getattr(buildout, command)(args)
  File "/Users/Jon/dev/pl/eggs/zc.buildout-1.4.4-py2.7.egg/zc/buildout/buildout.py", line 439, in install
    [self[part]['recipe'] for part in install_parts]

** 50 OR SO LINES OF STACK TRACE OMITTED FOR BREVITY **

  File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 365, in _read_status
    line = self.fp.readline()
  File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 447, in readline
    data = self._sock.recv(self._rbufsize)
timeout: timed out

EDIT: Okay, I've figured out that the whole thing just doesn't work with Plone 4.2.  Just make everything 4.1 instead and it will bin/buildout will finish without crashing.

A: It seems to me that you are using your system python instead of your virtualenv python.  Did you use your virtualenv python to bootstrap your buildout?
You just mentioned running "python bootstrap.py".  So unless you ran "source MyVirtualEnvDir/bin/activate", you invoked your system python.  If you have installed modules in your system python using pip or easyinstall, then some of these modules may conflict with your buildout and cause some weird errors.
BTW, as pointed out by others, the timeout could also be caused by server or network errors.
Any reason why you can not just use the unified installer?  It is the easiest to use and you can still use it to try out activities suggested by Martin's book.


text:
Q: Rails 5.1 and Cloudinary: Image files is invalid I'm working with Heroku in app made in Rails 5.1.1 which uses Cloudinary like image server and atacchinary to upload it.
This is the first time I use attachinary with rails 5, and when I upload the image with the input  <%= f.attachinary_file_field :image_event %>, it works fine. The image is uploaded and I can see it on cloudinary dashboard.
The question is: when I going to create the information, it returns to edit the info in the crud with a error in the file input.

Saying: Image files is invalid

I think its something with association, because the image is uploaded, but I'm not sure. The error occurs in development and in production.
The field is already in required parameters on controller
development:
  cloud_name: xxxxxxxxxxxxx
  api_key: 'xxxxxxxxxxxxx'
  api_secret: xxxxxxxxxxxxx
  enhance_image_tag: false // changed to false to work with rails 5
  static_image_support: false
production:
  cloud_name: xxxxxxxxxxxxx
  api_key: 'xxxxxxxxxxxxx'
  api_secret: xxxxxxxxxxxxx
  enhance_image_tag: false
  static_image_support: false
test:
  cloud_name: xxxxxxxxxxxxx
  api_key: 'xxxxxxxxxxxxx'
  api_secret: xxxxxxxxxxxxx
  enhance_image_tag: true
  static_image_support: true

My Model Event:
  has_attachment  :image_event, accept: [:jpg, :png, :gif]

A: The error is suggesting that the ORM might not be properly set up when an image is included through Attachinary. Make sure to include the specific ORM you wish to use by adding following line to your application.rb file (or custom initializer):
e.g.
require "attachinary/orm/YOUR_ORM" # active_record or mongoid

More info on that can be found here:
https://github.com/assembler/attachinary#installation


text:
Q: How to enable large page memory for the JVM? In the document(jbossperformancetuning.pdf), it suggest us to enable large page memory for the JVM.
But actually after I added the following to our command-line / script start-up:
"-XX:+UseLargePages"
It didn't work, so I investigated more, enabled the large page memory on OS first, then added "-XX:+UseLargePages -XX:LargePageSizeInBytes=2m" to start-up script.
But unfortunately, it didn't work neither, so could someone give us some suggestions of how to enable the large page memory for the JVM successfully?
Here are some details of our server:
[root@localhost ~]# cat /proc/meminfo
MemTotal:     37033340 kB
MemFree:        318108 kB
Buffers:        179452 kB
Cached:        5934940 kB
SwapCached:          0 kB
...
HugePages_Total: 10251
HugePages_Free:  10251
HugePages_Rsvd:      0
Hugepagesize:     2048 kB

[root@localhost ~]# ps aux | grep java
root     22525  0.2 20.3 28801756 7552420 ?    Sl   Nov03  31:54 java -Dprogram.name=run.sh -server -Xms1303m -Xmx24g -XX:MaxPermSize=512m -XX:+UseLargePages -XX:LargePageSizeInBytes=2m -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dsun.lang.ClassLoader.allowArraySyntax=true -verbose:gc -Xloggc:/tmp/gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Djava.net.preferIPv4Stack=true -Djava.endorsed.dirs=/opt/jboss-as/lib/endorsed -classpath /opt/jboss-as/bin/run.jar org.jboss.Main -c default -b 0.0.0.0
root     31962  0.0  0.0  61200   768 pts/2    S+   22:46   0:00 grep java

[root@localhost ~]# cat /etc/sysctl.conf
...
# JBoss is running as root, so the group id is 0
vm.hugetlb_shm_group = 0
# The pages number
vm.nr_hugepages = 12288

A: Finally I fixed this issue, at first set the large pages memory bigger than JVM heap size, then just reboot the server, because there is no way to make it work unless you upgrade the kernel to the newer one - in RHEL 6.0.


text:
Q: Pointer, Struct, and Function in C I'm learning about pointer and dynamic array in C, but I'm not clear about pointer in C.  I would appreciated if anyone could verify my understanding of the following codes based on the below information:
/*Struct*/
typedef struct {
   int *pInt;
}newStruct

/*Functions*/
newStruct *createMyStruct() {
   //codes
}

void printNewStruct(newStruct *pStruct) {
   //codes
}

Please verify:

*

*int *pInt: this is an array of type int that's in the struct

*newStruct *createMyStruct:  a function that's named createMyStruct. createMyStruct is a pointer that points to newStruct and create a copy of the newStruct.

*newStruct *pStruct: pStruct is the same as createMyStruct (?)

Question:
1) When I use malloc in a function (e.g. createMyStruct function from above code) to allocate memory, where would I have to free this memory?  Inside the function itself or in main? If in main, why in main?  I thought the memory has to be freed right away after it has been used.
My apology if my above statements aren't clear...I'm still really confuse about pointer and malloc.  Please verify/explain in simple terms for a Newbie.

A: Ok, let's try to clarify this:
1) int *pInt is a pointer to an Integer. This MAY point to the first value of an array, but it doesn't have to.
2) newStruct *createMyStruct() is a function that has a return value of a pointer to a newStruct structure. Most likely you want to malloc in this function and have it return the pointer.
3) newStruct *pStruct means that the input parameter for this function is a pointer to a newStruct structure, in this case named pStruct (I assume you know how to handle parameters in C)
As for your question: It kinda depends on when you no longer need the memory allocated. If you were to free it in the createMyStruct() function, you would basically return a pointer to an invalid location (causing undefined behaviour if you try to dereference it). Generally you should free the memory you allocated only when you are completely sure you no longer require whatever you allocated. You can either do it in your main or write your own function which you call.

A: 1 - if you malloc memory, you have to free it. It doesn't matter where. You should do it when you are no longer using the memory. It doesn't have to be immediately, but you should probably do it when you know you can, otherwise you have to remember to free it later.
You said

I thought the memory has to be freed right away after it has been used.

That's just advice. But it's very good advice. You could never free it, and keep using memory. You might run out of memory or your program might crash. C will not help you, the best thing you can do is stick to advice.
That's vague advice, but only you, the programmer, know the best place to do it. It's not easy, but memory management isn't easy.
2 - You need to remember how big the array is, because C will not check if you malloc(3) but access struct.pInt[4]. You could store this size as a variable in the struct.

A: Ok, I'm not going to give you a 1on1 pointer guide (I'm not planning to write a book), but here's the quick guide, based on your assumptions/questions:

*

*"int *pInt: this is an array of type int that's in the struct"
It Might be, pInt is a pointer to an integer. It needn't be an array. An array is a pointer, but a pointer isn't always an array. Right, an array is -of course- an array, but the way you access it in C is through either an array variable or a pointer.
The differences are clearly explained here
Basically: an array is a continuous block of memory, an array variable often (well, always save for 3 cases listed on the page I linked to above) decays into a pointer. Read the why's and how's, to get a clear understanding of the differences and similarities between pointers and arrays.
If you understand why one of the following snippets is not allowed and the other one is, you're there:
char *str = "Read only";
printf("%c\n", str[2]);//prints a from (0=>r, 1=>e, 3=> a...)
str[2] = 'q';//ILLEGAL
//BUT:
char str[] = "Read only";
str[2] = 'q';//perfectly legal...
printf("%c\n", str[2]);//prints q!

Why is this? Simple. In both cases, the literall "Read only" is stored in read-only memory. The difference is that, by assigning this string to a pointer(char *str), we're assigning the read-only mem address to the variable, so we can't change the memory it points to (that's what read-only means).
In the second case, the string literal is stored in the same read-only memory, but because we're assigning it to an array, it's values are copied to newly allocated stack memory, and we can write to that.
So, a pointer points to some chunk of data in memory. This memory can be writable or not, the memory address could be the address of part of an array or it could be a single int (like it is in your case), You could even have pointers that point to several pointers, and each of these pointers could, essentially, point to different places in memory (ie not a continuous block).
Anyway, consider this:
int i = 123;
int arr[3] = {1,2,3};//array
int *iPtr = &i;//iPtr contains the mem address of i
printf("%d\n", *iPtr);//prints 123
iPtr = arr;//iPtr points to the same as arr (note no & operator)
printf("%d\n", *iPtr);//prints 1
//now probably a mindfuck for you now, but:
printf("%d\n", *(iPtr+1));//prints 2!

The last bit is just to show what pointers are: it's a location in memory, big enough to accomodate an int, so if I take that space in memory, and do +1, I'm accessing that chunk of memory right next to the one my pointer points to. In memory, this might look something like this:
| 0x0f0 |   0x0f2  |  0x0f4   |  0x0f6   | //mem address
| *iPtr | iPtr + 1 | iPtr + 2 | iPtr + 3 | //access via pointer

That's why pointers can be dangerous. In the code above, iPtr points to the first of 3 ints (as defined in the arr array), but if I access *(iPtr+4), I'm accessing memory that is out of bounds. You are accessing memory that was not claimed/initialized, or owned by something else. This can, and probably will lead to unexpected behaviour... but I have seen this used to get some extra randomization...

*

*"newStruct *createMyStruct:  a function that's named createMyStruct. createMyStruct is a pointer that points to newStruct and create a copy of the newStruct."
You lost me here, this is a function definition. The function is indeed called createMyStruct, and it returns a pointer to something of the type newStruct. That's it, just like int some_function() is a function that returns an int

*

*"newStruct *pStruct: pStruct is the same as createMyStruct (?)"
No, pStruct is a pointer to a newStruct, and pStruct is a function argument, not a function, which createMyStruct is.
On calling free:
You call free on variables that are stored in memory allocated from the heap, when you don't need them anymore. If they go out of scope, you can't free them anymore, so you have to dellocate the memory when you still have a variable that points to it, but you shouldn't deallocate anything you might need later on in the program:
char *str = calloc(11, sizeof(char));
free(str);
//I can't use str here anymore

But:
int main()
{
    void some_function();
    some_function();
    //I can't free str here, mem-leak immanent!
   return 0;
}
void some_function()
{
    char *str = calloc(11, sizeof(char));
    //do stuff, but no calls to free
}

in this case, free(str); should have been the last statement in some_function. If some_function would've been char *some_function() and we'd have written this:
int main()
{
    char *return_val = NULL;
    char *some_function();
    return_val = some_function();
    printf("%s was returned by some_function\n", return_val);
    //the allocated memory is accessible here
    //And it has to be freed before main returns, so:
    free(return_val);//deallocate!
    return 0;
}
char *some_function()
{
    char *str = calloc(11, sizeof(char));
    //do stuff, but no calls to free
    return str;//return char pointer
}

it ended with return str, then you'd have to call free in the main function, as it has a pointer to the allocated memory.
That's it, in a nutshell...

A: *

*int *pInt - it's just a pointer to some possibly existing array (there's no space to put data in, it could point later to some place in memory to be used as array of ints, if you set it)

*newStruct *createMyStruct: a function that's named createMyStruct.
This is correct.
createMyStruct is a pointer that points to newStruct and create a copy of the newStruct

No, it's the pointer to the function (or the function name), but the function returns a pointer (newStruct*) to your structure, if you implement the function right you'll get allocated and initialized structure ready to use

*newStruct *pStruct - it's not the same as createMyStruct, pStruct will be uninitialized pointer,createMyStruct is your function
Here is how you would use your structure and methods:
int main()
{
    newStruct *pStruct = NULL; // nothing there yet
    pStruct = createMyStruct();
    if(pStruct==NULL) { printf("error"); }
    pStruct->pInt[0] = 123;
    ...
    free(pStruct->pInt); // you have to free the array in your struct too
    free(pStruct);
    return 0;
}

If you're wondering where to put the free, look at the example main function... The pStruct is declared and initialized at the beginning of main and free'd at it's end. For the most of the time, it's sufficient to free the memory at the same level (function) you did originally allocate it.


text:
Q: Null measure set and integrals Let $f,g:[a,b] \rightarrow \mathbb{R}$ be integrable functions and $$X=\{x \in [a,b];f(x) \ne g(x)\}$$
be a set with zero measure.
Prove that $$\int_a^b f(x)dx=\int_a^b g(x)dx$$ and show two functions $f \ne g$ such that $X$ is infinite and has zero measure.
How can i do this in a context of Riemman integration? I saw some anserws in other questions but it wasn't very helpfull.

A: We can prove this in the context of Riemann integration just using one measure-related fact: the measure of a non-empty interval is positive.
If $f$ and $g$ are Riemann integrable, then so is $h := f-g$ and $X = \{x \in [a,b]:h(x) \neq 0\}$ is given to be of measure zero.
For any partition $P: a = x_0 < x_1 < \ldots <x_n = b $, each subinterval $I_j = [x_{j-1},x_j]$ has positive measure and, hence, there is a point $x \in I_j$ where $h(x) = 0$.  This implies that $\inf_{x \in I_j} h(x) \leqslant 0 \leqslant \sup_{x \in I_j} h(x)$ and, consequently for upper and lower Darboux sums we have
$$\tag{1}L(P,h) \leqslant 0 \leqslant U(P,h)$$
Since $h$ is Riemann integrable we have for all $P$,
$$\tag{2}L(P,h) \leqslant \int_a^b h(x) \, dx \leqslant U(P,h)$$
and for any $\epsilon >0$, there exists a partition $P_\epsilon$ where $U(P_\epsilon,h) - L(P_\epsilon,h) < \epsilon$
In view of   (1) and (2) this implies that
$$-\epsilon < -(U(P_\epsilon,h) - L(P_\epsilon,h)) \leqslant \int_a^bh(x) \,dx \leqslant U(P_\epsilon,h) - L(P_\epsilon,h) < \epsilon$$
Since $\epsilon$ can be arbitrarily close to zero, it follows that
$$\int_a^bf(x) \, dx - \int_a^b g(x) \, dx = \int_a^bh(x) \,dx = 0$$


text:
Q: Using HW accelerated decoding of H264 content I am trying to setup a Linux based system to run my CCTV software Sinobi.
Currently I have one HD and one 4K IP camera connected. This causes the CPU to reach 200% This is a 16 core machine and two cores are completely used for h264 decoding. I have an old GeForce 9600 GPU installed. I think this card has a HW H264 decoder.
Please see below some info on the card and driver:
0f:00.0 VGA compatible controller: NVIDIA Corporation G94 [GeForce 9600 GT] (rev a1)
Kernel driver in use: nouveau
Kernel modules: nvidiafb, nouveau
37:05.0 FireWire (IEEE 1394): LSI Corporation FW322/323 [TrueFire] 1394a Controller (rev 70)

The way I understand this driver supports HW using HW acceleration.
Is there anything specific that I need to do in order to get the HW accel support?


text:
Q: What does "=" mean within Swagger path parameter? What does the "=" mean within the path parameter of the following OpenApi / Swagger spec?
https://github.com/grafeas/grafeas/blob/master/proto/v1beta1/swagger/grafeas.swagger.json#L18
Here is an excerpt (converted to YAML from JSON for readability):
swagger: '2.0'
info:
  title: grafeas.proto
  version: version not set
schemes:
  - http
  - https
consumes:
  - application/json
produces:
  - application/json
paths:
  '/v1beta1/{name=projects/*/notes/*}':
    get:
      summary: Gets the specified note.
      operationId: GetNote
      responses:
        '200':
          description: A successful response.
          schema:
            $ref: '#/definitions/v1beta1Note'
      parameters:
        - name: name
          description: |-
            The name of the note in the form of
            `projects/[PROVIDER_ID]/notes/[NOTE_ID]`.
          in: path
          required: true
          type: string
      tags:
        - GrafeasV1Beta1

The path is defined as /v1beta1/{name=projects/*/notes/*} and a parameter called name is defined, but when I put the whole .json into https://editor.swagger.io, I get errors of the form:

Declared path parameter "name=projects/*/notes/*" needs to be defined
  as a path parameter at either the path or operation level

A: I believe this swagger spec was auto-generated and the =TEXT within the {param} blocks to be an error.  I have raised this as https://github.com/grafeas/grafeas/issues/379.


text:
Q: Как удалить ошибку «TypeError: squareGen is not a function»? Выполняю простое решение задач, но попался на распространненую ошибку и не могу понять почему так. Прошу объяснить. Код длинный состоящий из 4-х частей.
Ошибка возникает в четвёртой части (task-4). При проверке через typeof, squareGen === 'number'. Почему 'number'?

// task-1
function sequence(start, step) {
  step = step || 1;
  start = start || 0;
  let flag = false,
    firstStep = 0;
  return function() {
    if (flag) {
      return start += step;
    } else {
      flag = true;
      return start += firstStep;
    }

  }
}
var generator = sequence(10, 3);
var generator2 = sequence(7, 1);
var generator3 = sequence(0, 2);

// task-2

function take(fn, steps) {
  let array = [];
  for (let i = 0; i < steps; i++) {
    array.push(fn());
  }
  return array;
}

// task-3

function square(x) {
  return x * x;
}
console.log(map(square, [1, 2, 3, 4])); // [1, 4, 9, 16]
console.log(map(square, [])); // []
var arr = [1, 2, 3];
console.log(map(square, arr)); // [1, 4, 9]
console.log(arr); // [1, 2, 3]

function map(fn, array) {
  let mas = array,
    newArray = [];
  mas.forEach(function(el) {
    newArray.push(fn(el));
  });
  return newArray;
}

// task-4

function fmap(a, gen) {
  let resultOfGen = gen();
  return a(resultOfGen);
}

var gen = sequence(1, 1);
var squareGen = fmap(square, gen);
squareGen();
console.log(typeof squareGen);
console.log(squareGen()); // 1
console.log(squareGen()); // 4
console.log(squareGen()); // 9
console.log(squareGen()); // 16


text:
Q: Print Screen Shot of Program VB.net Is there anyway to print out a screen shot of my program? Like... when I press the print button, it will print out a screenshot of the program? I have attached a picture of how it looks... I have a regular print out, but need the screen shot as well.
Thanks in advance,

A: Add the PrintForm component to your form:

Add a button with the following code:
Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
    PrintForm1.PrintAction = Printing.PrintAction.PrintToPrinter
    PrintForm1.Print()
End Sub

Done.

A: Save form as image (screenshot)
The above works.  I tried it, and had a slight issue with it capturing the full size of my form but starting below the title bar and extending beyond that.  you'd just need to change the new point to -X (X being the size of title bar and border of form).  That make sense?


text:
Q: hyphenation of adjective phrases Should adjectival phrases that are hyphenated when they modify a noun, e.g. a case-sensitive password, be hyphenated when they are predicate adjectives, e.g. The password is case-sensitive?

A: In Britain, whilst it is 'de rigeur' in Universities to hyphenate adjectival phrases, such as 'a time-honoured custom', 'a quick-witted response', 'an egg-headed professor' etc., there seems to me no such requirement for adjectival predicates, though I tend to do so on an ad hoc basis if it feels right.I would say, if in doubt hyphenate. I don't think one would be criticised for too much hyphenation in this way. At least that seems to be the case in the UK.

A: Technically, no, you don't hyphenate predicate adjectives, particularly in this case since there is no ambiguity when those are separated. I would only hyphenate a predicate adjective if the two words in question could mean something other than what I intended when taken separately.
To me this is a style issue rather than grammar; but if it's professional or academic writing, it might matter to your reader(s).


text:
Q: Is there something called the pochhammer expansion? I'm just playing around with the Pochhammer notation where
$$n^{\underline{k}} \equiv n(n-1)\ldots(n-k+1).$$
I've established the formulas
$$\begin{split}
n &= n^{\underline{1}}\\
n^2 &= n^{\underline{2}} + n^{\underline{1}}\\
n^3 &= n^{\underline{3}} + 3n^{\underline{2}} + n^{\underline{1}}\\
n^4 &= n^{\underline{4}} + 6n^{\underline{3}} + 7n^{\underline{2}} + n^{\underline{1}}\\
n^5 &= n^{\underline{5}} + 10n^{\underline{4}} + 25n^{\underline{3}} + 15n^{\underline{2}} + n^{\underline{1}}.
\end{split}
$$
Does it exist a general formula of the form
$$
n^k = \sum_{i=k}^1 c(i,k)n^{\underline{i}},
$$
for such expansions? What are in that case the closed form of the coefficients $c(i,k)$? Does this expansion have a name?

A: The general expression for $n\ge 0$ is
$$x^n=\sum_{k=0}^n{n\brace k}x^{\underline k}\,,$$
where $n\brace k$ is the Stirling number of the second kind that counts the partitions of $[n]$ into $k$ non-empty subsets. This is easily proved by induction on $n$ once you have the identity
$$x\cdot x^{\underline k}=x^{\underline{k+1}}+kx^{\underline k}$$
and the recurrence
$${n\brace k}=k{{n-1}\brace k}+{{n-1}\brace{k-1}}\,.$$
The induction step is:
$$\begin{align*}
x^n&=x\sum_k{{n-1}\brace k}x^{\underline k}\\
&=\sum_k{{n-1}\brace k}x^{\underline{k+1}}+\sum_k{{n-1}\brace k}kx^{\underline k}\\
&=\sum_k{{n-1}\brace{k-1}}x^{\underline k}+\sum_k{{n-1}\brace k}kx^{\underline k}\\
&=\sum_k\left(k{{n-1}\brace k}+{{n-1}\brace{k-1}}\right)x^{\underline k}\\
&=\sum_k{n\brace k}x^{\underline k}
\end{align*}$$

A: We have that
$$n^k = \sum_{q=0}^k {k\brace q} n^\underline{q}.$$
This is because we have for the RHS
$$\sum_{q=0}^k {k\brace q} q! {n\choose q}
= k! [z^k] \sum_{q=0}^k (\exp(z)-1)^q {n\choose q}.$$
Now $\exp(z)-1= z+\cdots$ so that $(\exp(z)-1)^q = z^q+\cdots$ and the
coefficient extractor enforces the upper limit of the sum and we find
$$k! [z^k] \sum_{q\ge 0} (\exp(z)-1)^q {n\choose q}
= k! [z^k] \exp(nz) = n^k.$$
We can also prove this combinatorially. The left side counts all
$k$-tuples with component values ranging from $1$ to $n.$ The right is a
classification by the number $q$ of different values that appear. We
choose these in ${n\choose q}$ ways, then we partition the slots of  the
tuple into $q$ non-empty sets in ${k\brace q}$ ways. To conclude  note
that we can assign the $q$ chosen values to the sets of slots in $q!$
ways. This is essentially the comment by @QuiaochuYuan.


text:
Q: how to align an item to the right of it's parent center? (android layouts) i want something like this:

i palyed with android relativelayout and it's tag like : android:layout_centerHorizontal="true" , and this give me this:

i player with other tags and combine them, but no success.
so is there any way to do this?

A: try this
<RelativeLayout
        android:layout_width="fill_parent"
        android:background="#FFFFFF"
        android:layout_height="wrap_content">

        <View
            android:layout_width="10dp"
            android:layout_height="1dp"
            android:layout_centerInParent="true"
            android:id="@+id/dummy"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SDADASd"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/dummy"
            android:textColor="#000000"

            />
    </RelativeLayout>

A:       or go with linearlayout...
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="right"
        android:layout_weight="1" >
        <View
            android:layout_width="10dp"
            android:background="@android:color/black"
            android:layout_height="match_parent"/>
    </LinearLayout>

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/linearLayout1"
        android:text="YOUR TEXT" />
</LinearLayout>

A: Try this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="20dp"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:background="@android:color/black" >
</LinearLayout>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/linearLayout1"
    android:text="YOUR TEXT" />

</RelativeLayout>

A: Add a transparent  view in the center of your RelativeLayout and with
height="match_parent"
width="15dp"//(it doesn't matter much)

then give your layout parameter relative to this view like
android:layout_alignRight="@+id/yourView"


text:
Q: Load swf at last frame Can anyone help? I have several swfs that need a back button and go to the last frame of the previous swf. I can get it to load but I can't get it it to go to a certain frame(the last frame of the swf to be specific). How do I add code to go to that frame? Here is the code:
lastPage2.addEventListener(MouseEvent.CLICK, fl_ClickToLoadUnloadSWF_1);

import fl.display.ProLoader;
var fl_ProLoader_1:ProLoader;

var fl_ToLoad_1:Boolean = true;

function fl_ClickToLoadUnloadSWF_1(event:MouseEvent):void
{
  if(fl_ToLoad_1)
  {
  fl_ProLoader_1 = new ProLoader();
  fl_ProLoader_1.load(new URLRequest("CEAS_I_1_16.swf"));
  addChild(fl_ProLoader_1);
   }
  else
  {
  fl_ProLoader_1.unload();
  removeChild(fl_ProLoader_1);
  fl_ProLoader_1 = null;
  }
  fl_ToLoad_3 = !fl_ToLoad_1;

}

A: mc.gotoAndStop(mc.totalFrames) should help


text:
Q: Spatial Interpolation for Irregular Grid How would I interpolate to a point P if I have four points around it such that:
Q1 = (x1,y1), Q2 = (x2,y2), Q3 = (x3,y3), Q4 = (x4,y4)
If the coordinates formed a regular 2D grid I would use a bilinear interpolation, but I don't think I can use it for irregular grid points. I have also tried to use the inverse distance weighting and found that the results aren't as accurate as I would like. A simple linear approximation is all I'm looking for. Any help or ideas would be greatly appreciated.

A: "words that end in GRY" has made an excellent suggestion in the comments: there are a lot of well-studied techniques for scattered data interpolation. In general, and especially if you had an arbitrary number of points, I would recommend using thin plate splines, which work very well in my experience.
Then again, if you have exactly four points, one might wonder if there is a general interpolation scheme that exactly recovers bilinear interpolation when the points form a rectangle. Well, here's one.
In bilinear interpolation, the interpolating function is of the form $$f(x,y)=a_{xy}xy+b_xx+b_yy+c,$$
which is a quadratic function of $(x,y)$. Let's consider a general quadratic instead,
$$f(x,y)=a_{xx}x^2+a_{xy}xy+a_{yy}y^2+b_xx+b_yy+c.$$
The known points give four equations that $f$ must satisfy,
$$\begin{align}
f(x_1,y_1)=a_{xx}x_1^2+a_{xy}x_1y_1+a_{yy}y_1^2+b_xx_1+b_yy_1+c&=z_1, \\
f(x_2,y_2)=a_{xx}x_2^2+a_{xy}x_2y_2+a_{yy}y_2^2+b_xx_2+b_yy_2+c&=z_2, \\
f(x_3,y_3)=a_{xx}x_3^2+a_{xy}x_3y_3+a_{yy}y_3^2+b_xx_3+b_yy_3+c&=z_3, \\
f(x_4,y_4)=a_{xx}x_4^2+a_{xy}x_4y_4+a_{yy}y_4^2+b_xx_4+b_yy_4+c&=z_4,
\end{align}$$
which can be written as a linear system of equations in the unknown parameters,
$$
\begin{bmatrix}
x_1^2 & x_1y_1 & y_1^2 & x_1 & y_1 & 1 \\
x_2^2 & x_2y_2 & y_2^2 & x_2 & y_2 & 1 \\
x_3^2 & x_3y_3 & y_3^2 & x_3 & y_3 & 1 \\
x_4^2 & x_4y_4 & y_4^2 & x_4 & y_4 & 1
\end{bmatrix}
\begin{bmatrix}
a_{xx} \\
a_{xy} \\
a_{yy} \\
b_x \\
b_y \\
c
\end{bmatrix}
=
\begin{bmatrix}
z_1 \\
z_2 \\
z_3 \\
z_4
\end{bmatrix},
$$
or, for short,
$$\mathbf X\mathbf a=\mathbf z.$$
We can't solve this yet because it's underdetermined: we have four equations but six unknowns. But of all the possible solutions to this system, we should probably pick the one that has the smallest quadratic coefficients. If the data can be fit by a purely linear model where the quadratic coefficients are zero, then that's the solution we should use. In the rectangular case, even if we do need the $xy$ term, we shouldn't involve the other two quadratic terms because they are redundant with the linear and constant terms; thus we will recover bilinear interpolation. So let's take the solution that minimizes
$$\begin{align}
e &= a_{xx}^2+a_{xy}^2+a_{yy}^2 \\
&= \mathbf a^T\mathbf E\mathbf a
\end{align}$$
where $\mathbf E$ is the diagonal matrix with entries $[1,1,1,0,0,0]$. Now by the method of Lagrange multipliers, minimizing $\mathbf a^T\mathbf E\mathbf a$ subject to $\mathbf X\mathbf a=\mathbf z$ is equivalent to solving
$$\begin{align}
\mathbf E\mathbf a + \mathbf X^T\mathbf\lambda &= \mathbf 0, \\
\mathbf X\mathbf a &= \mathbf z,
\end{align}$$
where $\lambda$ is a four-element vector of Lagrange multipliers.
Equivalently,
$$
\begin{bmatrix}\mathbf E & \mathbf X^T \\ \mathbf X & \mathbf 0\end{bmatrix}
\begin{bmatrix}\mathbf a \\ \mathbf\lambda\end{bmatrix}
=
\begin{bmatrix}\mathbf 0 \\ \mathbf z\end{bmatrix},
$$
which is a linear system that you can solve as usual.
Anyway, here's an animation where two points have $z=0$ and two have $z=1$. They initially form a square, and then the top edge rotates about its midpoint.


text:
Q: Does ::TIMESTAMP::DATE work in Java/Spring? I have this code that runs a query in PostgreSQL:
SELECT planned,COUNT(*) AS results
FROM dashboard.event
WHERE event_start_adj::TIMESTAMP::DATE = '2020-04-05'
GROUP BY planned

This code actually works but the problem is when i insert this to Java Spring like this:

it gives me an error like this:

org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
Position: 80

I've tried removing it to event_start_adj =  But it returns nothing since the data of my event_start_adj in PostgreSQL is timestamp without time zone That's why the query above extracts the date first. How can I fix this?

A: Obfuscation layers like JPA can't properly handle the :: operator, you need to rewrite it to use the CAST() operator instead:
WHERE cast(cast(event_start_adj as TIMESTAMP) as DATE) = '2020-04-05'

However if event_start_adj is already a timestamp the first case is useless, so it seems the following should be enough:
WHERE cast(event_start_adj as DATE) = '2020-04-05'

Unrelated to the problem at hand, but the expression you are using can't make use of an index on event_start_adj. So from a performance point of view, not casting at all would be better, but then you need to change the query to:
WHERE event_start_adj => date '2020-04-05'
  AND event_start_adj < date '2020-04-06'

A: WHERE timestamp_column::::DATE = '2020-04-05'

The above worked for me in springboot native query.


text:
Q: Form tries to submit to database when you open it When I open my form page it tries to submit to the database immediately and causes a skip in the primary key field. If I submit consecutive inputs it does not cause a skip. If I close and reopen it skips. Any ideas?
 $dbh = new PDO("pgsql:host=$host;dbname=$dbname", $dbuser, $dbpass);
if(!$dbh) {
      echo "Error : Unable to open database\n";
   } else {
      echo "Opened database successfully\n";
   }

if (!empty($_POST['submit'])) {
$custID = $_POST['custID'];
$CustFirstName = $_POST['CustFirstName'];
$CustLastName = $_POST['CustLastName'];
$CustAddress =$_POST['CustAddress'];
$CustCity = $_POST['CustCity'];
$CustState = $_POST['CustState'];
$CustZip = $_POST['CustZip'];
$CustCellPhone = $_POST['CustCellPhone'];
$CustWorkPhone = $_POST['CustWorkPhone'];
$CustEmail = $_POST['CustEmail'];
}
$sql = "INSERT INTO customers (custID, CustFirstName, CustLastName, CustAddress, CustCity, CustState, CustZip, CustCellPhone, CustWorkPhone, CustEmail)
VALUES (:custID, :CustFirstName, :CustLastName, :CustAddress, :CustCity, :CustState, :CustZip, :CustCellPhone, :CustWorkPhone, :CustEmail)";

$stmt = $dbh->prepare($sql);
$stmt->bindValue(':custID', $_POST['custID']);
$stmt->bindValue(':CustFirstName', $_POST['CustFirstName']);
$stmt->bindValue(':CustLastName', $_POST['CustLastName']);
$stmt->bindValue(':CustAddress', $_POST['CustAddress']);
$stmt->bindValue(':CustCity', $_POST['CustCity']);
$stmt->bindValue(':CustState', $_POST['CustState']);
$stmt->bindValue(':CustZip', $_POST['CustZip']);
$stmt->bindValue(':CustCellPhone', $_POST['CustCellPhone']);
$stmt->bindValue(':CustWorkPhone', $_POST['CustWorkPhone']);
$stmt->bindValue(':CustEmail', $_POST['CustEmail']);
$inserted = $stmt->execute();

/*
var_dump($_POST);*/

Here is what it is doing
accounting=# select * from customers;
 id | custid | custfirstname | custlastname |   custaddress   | custcity | custstate | custzip | custcellphone | custworkphone |       custemail       |             ts
----+--------+---------------+--------------+-----------------+----------+-----------+---------+---------------+---------------+-----------------------+----------------------------
  1 | Swo750 | Pat
  3 | Bod750 | Bob
  4 | Col555 | Sam           | Close        | 5525 East       | West     | TX        | 76052   | 555-555-5555  | 888-555-5555  | b@ya.com              | 2019-03-01 10:30:21.161783
  5 | Tim555 | Tim           | Tiny         | 666 Q St        | Hope     | AR        | 77858   | 222-222-2222  | 333-333-3333  | tim@tiny.com          | 2019-03-01 10:33:37.960887
  6 | a      | b             | c            | d               | e        | f         | 666     | 6666          | 6666          | g@g.com               | 2019-03-01 10:34:08.699302
  8 | e      | f             | g            | h               | i        | j         | 44      | 55            | 66            | j@j.com               | 2019-03-01 10:35:06.950209
(6 rows)

`
You can see the skips between 1&3, and 6&8 when reopened or refreshed
Form code
<form action="" method="post">
CustID:<input type="text" name="custID">

Fist Name: <input type="text" name="CustFirstName">

Last Name: <input type="text" name="CustLastName">

Address: <input type="text" name="CustAddress">

City: <input type="text" name="CustCity">

State: <input type="text" name="CustState">

Zip Code: <input type="text" name="CustZip">

Cell Phone: <input type="text" name="CustCellPhone">

Work Phone: <input type="text" name="CustWorkPhone">

E-mail: <input type="text" name="CustEmail">

<input type="submit">
</form>

A: Your SQL code is being executed no matter if the form has been submitted or not. Move the $stmt execution inside of the if (!empty($_POST['submit'])) block.
$dbh = new PDO("pgsql:host=$host;dbname=$dbname", $dbuser, $dbpass);
if(!$dbh) {
      echo "Error : Unable to open database\n";
   } else {
      echo "Opened database successfully\n";
   }

if (!empty($_POST['submit'])) {
  $custID = $_POST['custID'];
  $CustFirstName = $_POST['CustFirstName'];
  $CustLastName = $_POST['CustLastName'];
  $CustAddress =$_POST['CustAddress'];
  $CustCity = $_POST['CustCity'];
  $CustState = $_POST['CustState'];
  $CustZip = $_POST['CustZip'];
  $CustCellPhone = $_POST['CustCellPhone'];
  $CustWorkPhone = $_POST['CustWorkPhone'];
  $CustEmail = $_POST['CustEmail'];

  $sql = "INSERT INTO customers (custID, CustFirstName, CustLastName, CustAddress, CustCity, CustState, CustZip, CustCellPhone, CustWorkPhone, CustEmail)
VALUES (:custID, :CustFirstName, :CustLastName, :CustAddress, :CustCity, :CustState, :CustZip, :CustCellPhone, :CustWorkPhone, :CustEmail)";

  $stmt = $dbh->prepare($sql);
  $stmt->bindValue(':custID', $_POST['custID']);
  $stmt->bindValue(':CustFirstName', $_POST['CustFirstName']);
  $stmt->bindValue(':CustLastName', $_POST['CustLastName']);
  $stmt->bindValue(':CustAddress', $_POST['CustAddress']);
  $stmt->bindValue(':CustCity', $_POST['CustCity']);
  $stmt->bindValue(':CustState', $_POST['CustState']);
  $stmt->bindValue(':CustZip', $_POST['CustZip']);
  $stmt->bindValue(':CustCellPhone', $_POST['CustCellPhone']);
  $stmt->bindValue(':CustWorkPhone', $_POST['CustWorkPhone']);
  $stmt->bindValue(':CustEmail', $_POST['CustEmail']);
  $inserted = $stmt->execute();
}


text:
Q: SHA1 HMAC a byte array with Arduino How can I HMAC a byte array on an Arduino?  I've found this library for SHA1 HMACs, but it appears to be used only for strings.
I've passed it bytes in a null-terminated byte array.  This does give me the correct result.   But doesn't work so well for byte arrays that contain zeros!
uint8_t hmacKey1[]={   0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0xde, 0xad, 0xbe, 0xef };
uint8_t time[]={   0xb2, 0x00 };

Sha1.initHmac(hmacKey1, 10);
Sha1.print((char*)time);

Either I need to find another another library (crypto-arduino-library looks promising, but doesn't include any examples for what I'm doing), or hack up the Cathedrow library to do what I'm after.
Does anyone know of another way?

A: Adding my own method appears to have done the trick:
void Sha1Class::writebytes(const uint8_t* data, int length) {
 for (int i=0; i<length; i++)
 {
   write(data[i]);
 }
}

A: If you don't want to change sha1.cpp you can just loop and print each single byte, the trick is to use Sha1.print((char) basestring[i]);, like so:
#include <avr/pgmspace.h>
#include <sha1.h>

char key[] = "testKey";
uint8_t basestring[] = { 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67 }; // testing

void printHash(uint8_t* hash) {
  for (int i=0; i<20; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
  Serial.println();
}

void setup() {
  Serial.begin(115200);

  Serial.print("Input:              ");
  for (int i=0; i<sizeof(basestring); i++) {
    Serial.print((char) basestring[i]);
  }
  Serial.println();

  Serial.print("Key:                ");
  Serial.println(key);

  Serial.print("Hmac-sha1 (hex):    ");
  Sha1.initHmac((uint8_t*)key, strlen(key));

  for (int i=0; i<sizeof(basestring); i++) {
    Sha1.print((char) basestring[i]);
  }

  uint8_t *hash;
  hash = Sha1.resultHmac();
  printHash(hash);

}

void loop() { }

Output
Input:              testing
Key:                testKey
Hmac-sha1 (hex):    60d41271d43b875b791e2d54c34bf3f018a29763


text:
Q: Dynamic creation of class instances from a list I am trying to create new instances of a class from a list.
Everything seems to work, but if I add a new value to the list and create a new instance of the app class, I get the KeyError.
I don't know if I have to completely abandon this path or if there is a solution to this.
class app:
    def __init__(self):
        self.app=None
    def start_app(self):
        return self.app.start()
    def stop_app(self):
        return self.app.stop()
    def return_app(self):
        return self.app

list=[123456,654321]
myapp = {k: app() for k in list}
print("1 my list: ",list)
print ("1 my app: ",myapp)
myapp[(list[0])].__init__
x=myapp[(list[0])].start_app
list.append(789000)
print("2 my list: ",list)
print ("2 my app: ",myapp)
myapp[(list[0])].__init__
print(myapp[(list[2])].start_app())

And the error:
1 my list:  [123456, 654321]
1 my app:  {123456: <__main__.app object at 0x7ff6916a53d0>, 654321: <__main__.app object at 0x7ff6916a5430>}
2 my list:  [123456, 654321, 789000]
2 my app:  {123456: <__main__.app object at 0x7ff6916a53d0>, 654321: <__main__.app object at 0x7ff6916a5430>}
Traceback (most recent call last):
  File "/testCopia.py", line 25, in <module>
    print(myapp[(list[2])].start_app())
KeyError: 789000

A: The instance of app class gets created when you run app(), which you're only doing on the assignment to myapp. When you add a new key to list (you should use a different name, this is an existing type), you need to call app(), and maybe also add the new (kay, value) pair to myapp.

A: As per my comment, after this line:
list.append(789000)

You need to add:
myapp[789000] = app()


text:
Q: How to get GC Information in Silverlight? Silverlight does not provide perfmon counters for GC. How do i get GC Information?
Thanks

A: Silverlight does not provide this information out of the box. You would have to use ETW tracing to get this information. Here is how you can get ETW information on GC from silverlight


text:
Q: How to add custom fields to Kentico Modules? I want to use kentico's polls module but I need to add a "tooltip field" and add some extra HTML. Is there a way to clone the module with the same functionality and let me to edit/add fields to the module classes.
I was trying to edit the module but it shows a message saying Classes cannot be created or deleted in installed modules.

A: Are you trying to modify the class in the module and it's giving that error? Or modify the module info itself?
Some module classes allow edits and additions. If this is not the case for the polling, you have two options.
1: clone or recreate the module and clone the web parts that use it to use your new module. This is the safest but longest task and may require some digging into Kentico drivers using a decompiler like just decompile to find any other code pieces you need to clone and modify.
2: open the database in SQL management studio, and edit the cms_class on that class and manually change the bool values that allow it to be edited. This comes with the risk that on future upgrades it may break it, but it's a small risk.


text:
Q: Scribus 1.5.5 shows only English (US) spell checker From Scribus 1.4.2 on, Scribus should find previously installed dictionaries while installing and be able to use them.
With version 1.5.5 from the repository this doesn't seem to work. Although different dictionaries have been installed via LibreOffice, the option from the menu "Extras/Check Spelling" only shows  "English (US)". Furthermore I can't find an option within Scribus to install additional dictionaries.
I use three installations on three computers, all of them Ubuntu 20.04.
On one of them I can select from all installed dictionaries, on the two others there's only "English (US)".
Hunspell is not installed on any of the three.
apt-cache policy hunspell
hunspell:
  Installed: (none)

What am I missing here?

A: Aha!
As explained here Spell check and locale language packages are installed here: /usr/share/hunspell/
To install language packages via LibreOffice doesn't work for Scribus.
Language packages have to be installed using Ubuntu's "Language Support".


text:
Q: R matching function fails I've been trying to reorder a dataframe to fit the order of elements in a second dataframe, and there is a perfect overlap between the two.The dataframe is called RNAset2 and the dataframe containing the reference vector is called tab
> colnames(RNAset2)

  [1] "TCGA-CR-6487" "TCGA-BA-5153" "TCGA-CR-6481" "TCGA-BB-4223"
  [5] "TCGA-CR-7383" "TCGA-HD-7753" "TCGA-CN-5365" "TCGA-CR-6470"
  [9] "TCGA-CR-7385" "TCGA-CR-6467" "TCGA-HD-7754" "TCGA-CR-6482"
  [13] "TCGA-CR-6478" "TCGA-CN-5374" "TCGA-CR-7404" "TCGA-IQ-7630"
  [17] "TCGA-BA-5559" "TCGA-CR-5243" "TCGA-CR-5248" "TCGA-CR-5247"

> tab$pos.samples

  [1] "TCGA-CR-6481" "TCGA-BB-4223" "TCGA-CN-5365" "TCGA-CR-6467"
  [5] "TCGA-CR-5247" "TCGA-CR-7383" "TCGA-BA-5153" "TCGA-CR-6470"
  [9] "TCGA-CR-7404" "TCGA-BA-5559" "TCGA-CR-7385" "TCGA-CR-6478"
  [13] "TCGA-HD-7754" "TCGA-CR-6482" "TCGA-CR-6487" "TCGA-CR-5248"
  [17] "TCGA-CN-5374" "TCGA-IQ-7630" "TCGA-CR-5243" "TCGA-HD-7753"

The intersection between the two is complete...
> length(intersect(tab$pos.samples,colnames(RNAset2)))
[1] 20

Then I try to reorder RNAset2 based on the %in% operator and the match function with the reference vector being the intersection.
#Define vector for matching
> x<-as.character(intersect(tab$pos.samples,colnames(RNAset2)))
> x
 [1] "TCGA-CR-6481" "TCGA-BB-4223" "TCGA-CN-5365" "TCGA-CR-6467"
 [5] "TCGA-CR-5247" "TCGA-CR-7383" "TCGA-BA-5153" "TCGA-CR-6470"
 [9] "TCGA-CR-7404" "TCGA-BA-5559" "TCGA-CR-7385" "TCGA-CR-6478"
[13] "TCGA-HD-7754" "TCGA-CR-6482" "TCGA-CR-6487" "TCGA-CR-5248"
[17] "TCGA-CN-5374" "TCGA-IQ-7630" "TCGA-CR-5243" "TCGA-HD-7753"

#Run match command
RNAset2<-RNAset2[,match(colnames(RNAset2),x)]
> colnames(RNAset2)
[1] "TCGA-CR-6487" "TCGA-BA-5153" "TCGA-CR-6481" "TCGA-BB-4223"
[5] "TCGA-CR-7383" "TCGA-HD-7753" "TCGA-CN-5365" "TCGA-CR-6470"
[9] "TCGA-CR-7385" "TCGA-CR-6467" "TCGA-HD-7754" "TCGA-CR-6482"
[13] "TCGA-CR-6478" "TCGA-CN-5374" "TCGA-CR-7404" "TCGA-IQ-7630"
[17] "TCGA-BA-5559" "TCGA-CR-5243" "TCGA-CR-5248" "TCGA-CR-5247"

As you can see above, matching has failed and RNAset2 has not been reordered. The error is reproduced with the %in% operator
 >RNAset2<-RNAset2[,c(colnames(RNAset2) %in% x)]

 > colnames(RNAset2)
 [1] "TCGA-CN-5374" "TCGA-HD-7754" "TCGA-CR-6482" "TCGA-CR-7385"
 [5] "TCGA-HD-7753" "TCGA-CR-5247" "TCGA-CR-6478" "TCGA-CR-6470"
 [9] "TCGA-CR-6467" "TCGA-CR-7404" "TCGA-BB-4223" "TCGA-CN-5365"
 [13] "TCGA-BA-5153" "TCGA-CR-6481" "TCGA-BA-5559" "TCGA-CR-5243"
 [17] "TCGA-CR-6487" "TCGA-CR-5248" "TCGA-IQ-7630" "TCGA-CR-7383"

These are the classes of the otjects that matter...
> class(x)
[1] "character"

> class(RNAset)
[1] "data.frame"

> class(RNAset2)
[1] "data.frame"

> class(RNAset)
[1] "data.frame"

> class(tab$pos.samples)
[1] "character"

What is going on and why aren't these functions working as they should? It is driving me round the bend.
Edited to add dputs of objects
#tab

dput(tab)
structure(list(pos.samples = c("TCGA-CR-6481", "TCGA-BB-4223",
"TCGA-CN-5365", "TCGA-CR-6467", "TCGA-CR-5247", "TCGA-CR-7383",
"TCGA-BA-5153", "TCGA-CR-6470", "TCGA-CR-7404", "TCGA-BA-5559",
"TCGA-CR-7385", "TCGA-CR-6478", "TCGA-HD-7754", "TCGA-CR-6482",
"TCGA-CR-6487", "TCGA-CR-5248", "TCGA-CN-5374", "TCGA-IQ-7630",
"TCGA-CR-5243", "TCGA-HD-7753"), status = structure(c(1L, 1L,
2L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L,
1L, 2L), .Label = c("pos", "neg"), class = "factor")), .Names = c("pos.samples",
"status"), row.names = c(9L, 3L, 15L, 7L, 16L, 18L, 1L, 8L, 13L,
2L, 12L, 17L, 14L, 10L, 11L, 6L, 4L, 20L, 5L, 19L), class = "data.frame")

#RNAset2
structure(list(`TCGA-CR-6487` = c(50.7709, 0, 1.408, 96.6983,
445.9697, 9745.1531, 1915.5227, 0.352, 0, 1045.7585, 0.352, 929.6023,
0.352, 0, 0, 11.9676, 61.95, 1138.6836, 1213.6572, 2742.3442),
`TCGA-BA-5153` = c(72.5347, 0, 0, 91.8098, 3090.1389, 4361.9534,
1700.6354, 1.4121, 0, 650.0353, 46.1285, 2957.8724, 1.8828,
0, 0, 189.221, 10.3554, 546.0108, 2001.8828, 3092.4924),
`TCGA-CR-6481` = c(24.5963, 0, 0, 70.2659, 18032.5867, 15646.3773,
1255.453, 0, 0, 837.6615, 0, 1894.2652, 0, 0, 0, 0.3464,
75.8676, 1266.1922, 1125.1963, 2126.0251), `TCGA-BB-4223` = c(45.4087,
0, 2.0182, 153.0727, 6623.6125, 3212.3865, 1309.2836, 1.5136,
0, 1323.9152, 93.8446, 3918.7689, 1.5136, 0.5045, 0.5045,
171.0394, 67.1039, 1023.7134, 1318.3653, 2233.0979), `TCGA-CR-7383` = c(116.7844,
0, 22.4009, 43.3565, 326.9804, 8687.5549, 1142.8055, 0.7226,
0, 652.8769, 5.7809, 985.2768, 0.3613, 0, 0, 17.3426, 49.86,
1338.2712, 1287.6886, 4332.7613), `TCGA-HD-7753` = c(19.6301,
0, 3.7326, 88.3135, 935.5277, 2829.6505, 1006.4472, 0, 0,
671.5304, 1.3573, 1842.2124, 0.3393, 0, 0, 3.7326, 87.2073,
1442.8232, 1138.4459, 1698.3373), `TCGA-CN-5365` = c(70.5188,
0, 0, 44.5924, 1210.8083, 2219.5554, 129.9738, 0, 0, 817.6947,
2.7363, 1055.2959, 0.456, 4.1044, 0, 15.5056, 10.0331, 2023.4865,
1485.3494, 3096.1122), `TCGA-CR-6470` = c(98.556, 0, 0.7388,
140.1594, 3486.5293, 5359.4509, 988.1824, 0, 0, 700.7784,
13.2989, 1393.0602, 0, 0, 0, 5.9106, 91.2453, 1081.2748,
1517.9221, 2428.1582), `TCGA-CR-7385` = c(29.3766, 0, 0,
92.2289, 30960.205, 3308.5636, 3132.3655, 0, 0, 814.3467,
1.3664, 1919.0436, 0, 0, 0, 4.0991, 66.9513, 1202.3911, 1048.6763,
2246.2852), `TCGA-CR-6467` = c(111.2097, 0, 0, 223.7171,
2840.7601, 3214.4554, 2253.0623, 0.5297, 0, 1461.6964, 3.443,
3116.4669, 0.5297, 0, 0, 83.692, 2.3836, 787.9229, 1116.0697,
2482.6856), `TCGA-HD-7754` = c(25.4251, 0, 0, 89.4867, 27778.5606,
6172.3435, 1211.9259, 1.3484, 0, 413.414, 0.2697, 1310.6275,
77.1275, 0, 0, 471.3944, 61.7559, 1236.4665, 1335.7074, 2277.9569
), `TCGA-CR-6482` = c(44.1041, 0.4084, 0, 141.999, 1057.2741,
15538.9321, 1025.0128, 0.4084, 0, 699.1322, 1.6335, 540.2757,
6.9423, 0, 0, 8.1674, 81.6743, 960.49, 968.2491, 2362.8382
), `TCGA-CR-6478` = c(17.7005, 0, 0, 45.9815, 847.4861, 6413.3577,
629.8924, 0, 0.3052, 712.9015, 0, 809.6437, 0, 0, 0, 0.6104,
47.6081, 691.2337, 885.3285, 2536.3546), `TCGA-CN-5374` = c(151.6135,
0, 4.4139, 36.101, 4078.9603, 2920.0147, 2948.0137, 1.4713,
0, 660.6179, 0.4904, 1047.5723, 2.9426, 0, 0, 3.4331, 36.7827,
990.6817, 843.5508, 2396.7631), `TCGA-CR-7404` = c(49.0513,
0, 0, 79.0442, 3722.4464, 4740.2358, 960.519, 0.3165, 0,
632.3285, 11.0768, 1432.7083, 1.5824, 0, 0, 1.2659, 30.3822,
1307.6984, 1539.0458, 1901.7327), `TCGA-IQ-7630` = c(51.436,
0, 0.6658, 91.8923, 434.7924, 1538.4193, 602.5836, 0.3329,
0, 1002.4195, 4.6609, 1283.7362, 0, 1.3317, 0, 1.9975, 16.313,
1690.2304, 1232.1337, 2971.969), `TCGA-BA-5559` = c(75.0331,
0, 71.8129, 91.0836, 2949.9826, 8418.4966, 1015.5585, 1.1309,
0.5655, 1109.7069, 16.3982, 3296.0415, 0.5655, 0.2827, 0.2827,
6.7855, 24.5973, 798.989, 1486.8659, 3003.4182), `TCGA-CR-5243` = c(32.1345,
0, 0, 177.2034, 6428.2353, 4424.5311, 1047.395, 0.3361, 0,
786.5546, 71.2605, 3243.3613, 1.0084, 0, 0, 4.3697, 10.084,
555.9664, 1687.395, 2425.5462), `TCGA-CR-5248` = c(106.4973,
0, 0, 108.0117, 2060.5765, 6005.3493, 273.0826, 1.4656, 0,
979.9707, 17.0982, 1127.9922, 0.977, 0.4885, 0.4885, 2.9311,
26.3801, 921.8368, 973.6199, 3250.1221), `TCGA-CR-5247` = c(51.3896,
0, 1.0488, 61.2795, 3671.2113, 2693.7493, 2837.9654, 0, 0.5244,
930.7813, 1.0488, 2047.1945, 8.3901, 0, 0, 27.268, 134.2423,
2045.097, 1073.9381, 3438.9093)), .Names = c("TCGA-CR-6487",
"TCGA-BA-5153", "TCGA-CR-6481", "TCGA-BB-4223", "TCGA-CR-7383",
"TCGA-HD-7753", "TCGA-CN-5365", "TCGA-CR-6470", "TCGA-CR-7385",
"TCGA-CR-6467", "TCGA-HD-7754", "TCGA-CR-6482", "TCGA-CR-6478",
"TCGA-CN-5374", "TCGA-CR-7404", "TCGA-IQ-7630", "TCGA-BA-5559",
"TCGA-CR-5243", "TCGA-CR-5248", "TCGA-CR-5247"), class = "data.frame", row.names =
c("A1BG", "A1CF", "A2BP1", "A2LD1", "A2ML1", "A2M", "A4GALT", "A4GNT", "AAA1", "AAAS",
"AACSL", "AACS", "AADACL2", "AADACL3", "AADACL4", "AADAC", "AADAT", "AAGAB", "AAK1",
"AAMP"))

A: Here's how you can use match to re-order the columns of RNAset2 to match the order in tab$pos.samples
RNAset2 <- RNAset2[, match(tab$pos.samples, colnames(RNAset2))]

And we can verify that
all(colnames(RNAset2) == tab$pos.samples)

So the trick of the re-ordering was just getting the order of the parameters correct.

A: I don't think any use of match is needed. Just supply that vector to "[". Try this:
x <- as.character(intersect( tab$pos.samples, colnames(RNAset2) ))
RNAset2 <- RNAset2[ x ]


text:
Q: Como iterar sobre 2 arrays simultaneamente? Inicialmente tenho esse array de objetos contendo os produtos
const carros = [
  {produto: "uno 2022", fabricante: "fiat"},
  {produto: "gol g5", fabricante: "volkswagen"},
  {produto: "onix plus 2022", fabricante: "chevrolet"},
  {produto: "KWID", fabricante: "Renault"},
]

e também tenho esse array de objetos com as respectivas imagens de produtos
const imagemCarros =  [
  {image: "https://garagem360.com.br/wp-content/uploads/2021/08/screen-shot-2018-01-12-at-18-48-30.jpg"},
  {image: "https://static.kbb.com.br/Uploads/ResearchTools/News/1252/c79acb69-85e8-44f8-a373-94864ad5c5c8_1365x1024.jpg"},
  {image: "https://production.autoforce.com/uploads/picture/image/85087142/main_comprar-novo-onix-plus-2021-d602ab18-cada-49e7-a2bf-e270b7f8f3a0_6241cea229.jpg"},
  {image: "https://revistagaragem.com.br/wp-content/uploads/2021/11/renault-kwid-2022-renovado-2022-1536x864-1-780x470.jpg"},
]

Preciso que a cada iteração eu tenha a posição 0 dos arrays carros e imagemCarros, depois a posição 1, 2 e assim sucessivamente
um exemplo abaixo com a posição 0 dos 2 arrays de objetos
{produto: "uno 2022", fabricante: "fiat"}, {image: "https://garagem360.com.br/wp-content/uploads/2021/08/screen-shot-2018-01-12-at-18-48-30.jpg"},

A: Sua descrição está um pouco confusa, mas ao que tudo indica o que você quer é gerar um novo array a partir do primeiro. Para isso você pode utilizar a função map:

const carros = [
  {produto: "uno 2022", fabricante: "fiat"},
  {produto: "gol g5", fabricante: "volkswagen"},
  {produto: "onix plus 2022", fabricante: "chevrolet"},
  {produto: "KWID", fabricante: "Renault"},
];

const imagemCarros =  [
  {image: "https://garagem360.com.br/wp-content/uploads/2021/08/screen-shot-2018-01-12-at-18-48-30.jpg"},
  {image: "https://static.kbb.com.br/Uploads/ResearchTools/News/1252/c79acb69-85e8-44f8-a373-94864ad5c5c8_1365x1024.jpg"},
  {image: "https://production.autoforce.com/uploads/picture/image/85087142/main_comprar-novo-onix-plus-2021-d602ab18-cada-49e7-a2bf-e270b7f8f3a0_6241cea229.jpg"},
  {image: "https://revistagaragem.com.br/wp-content/uploads/2021/11/renault-kwid-2022-renovado-2022-1536x864-1-780x470.jpg"},
];

const juncao = carros.map((carro, indice) => ({ ...carro, ...imagemCarros[indice] } ));

console.log(juncao);

Array.prototype.map()
O método map() invoca a função callback passada por argumento para cada elemento do Array e devolve um novo Array como resultado.
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots é [1, 2, 3], numbers ainda é [1, 4, 9]


text:
Q: chars array in integer representation I'm reading post about pointers in C here>>>, and there is one example:
main() {
    ...
    char name[] = "Bill";
    int *q;
    ...
    q = name;
    printf("%d\n", *q);
    ...

Which gives me next result:
$ ./pointers_explained
1819044162

So question is about next explanation from author:

(to see how, line up the binary representation of the ascii values for
  those 4 characters, and then run the 32 bits together, and convert
  that resultant binary number as an integer.)

Binary for the "Bill" will be:

*

*B: 01000010

*i: 01101001

*l: 01101100

*l: 01101100

(from an ASCII binary table here>>>)
What I can't get is:

and then run the 32 bits together, and convert that resultant binary number as an integer

So - how can I convert this "Bill"'s binary into the decimal (or any other ) integer "1819044162"?

A: In ascii code, "Bill" is
B: 0x42
i: 0x69
l: 0x6c
l: 0x6c

1819044162 in hex mode is 0x6c6c6942, this is because of the endianness
In memory, "Bill" is stored as:
     B   i   l   l
name 42  69  6c  6c

But if it is little endianness, and reads an 4-byte integer from address name, it reads backwards, results 0x6c6c6942, which is 1819044162.
If the system is big endian, it will results 0x42696c6c.


text:
Q: When to use synthetic data and when to use regularization parameters to avoid the over fitting and which is better? Can anyone explain me when to consider generating the synthetic data or when to consider regularization parameters to reduce the error so the machine learning model will not overfit

A: If you have a problem with a time-consuming procedure for labeling, then you need to generate images synthetically for the training path. In the validation and test path, it is easier to label images since the number of inputs is few. Also, the model is robust if it validated by real images and works fine.


text:
Q: Different technologies to interact with SharePoint and External systems inside our SPFx web part I am developing 2 SPFx web parts. one which shows items from a SharePoint list and the other shows items assigned for the login user from SLACK.
now for the technologies, to connect to the SharePoint list and to the external systems i have those:-

*

*To connect to SharePoint list:-

*

*SPHttpClient

*Raw jQuery

*PnP/PnPjs

*To connect to Exernal API/system:-

*

*HttpClient

*Raw jQuery

now for SharePoint i usually use PnP/PnPjs because it ease the development compared to SPHttpClient & Raw jQuery + i use HttpClient to connect to external API because it is easier compared to Raw jquery.
but i am working with a client and they do not allow us to use any open source technologies not managed by Microsoft.so this mean i can not use PnP/PnPjs.. so is the alternative to use SPHttpCleint for internal and HttpClient of external for this customer?

A: SPFx & SharePoint uses open-source components in it, the Fluent UI!
That's the same scenario I was facing earlier with one of my clients where they can't accept the fact that Microsoft is now open source. I guess most of Microsoft products are from open source, although not exactly 100%. From Windows, SharePoint, Azure AD website, Power Apps, Power Automate, literally almost everything. Even jQuery is also free & open source.
If that's the case, you only left with the legacy SpHttpClient, or fetch (for javascript) leveraging on purely SharePoint REST API. Please take note that Microsoft no longer adding features to SharePoint REST API and legacy SharePoint SOAP web service. It's now moving to Graph API.
Else you could convince them, I'm sure unknowingly in the past/existing projects they leveraged on open-source components.
https://opensource.microsoft.com/


text:
Q: How parse XML empty node with Libxml2? In C I have a problem getting empty nodes with libxml2 in C. The problem is the node is like
<node /> and the lib recognizes it in the xPath, but if i try to put more nodes inside that him the lib don't do it.
Here the code i'm using to parse document:
xmlDocPtr xApiXmlUtilsGetDocFile(char *pcDocName)
{
    xmlDocPtr xDoc;
    xDoc = xmlReadFile(pcDocName,"utf-8",XML_PARSE_NOBLANKS);

    if (xDoc == NULL)
    {
        fprintf(stderr, "Document not parsed successfully. \n");
        return NULL;
    }
    TRACE("Document parsed successfully.");
    return xDoc;
}

Here the code to add nodes (put correctly if the node is something like <node></node>):
int lApiAddElement(xmlDocPtr xDoc, char* pcXPATHBrother, char* pcChildName, char* pcChildContent, AddType_t xAddType)
{
    xmlXPathObjectPtr xPathObj;

    /* Create xpath evaluation context */
    xPathObj = xApiXmlUtilsGetNodeSet(xDoc, BAD_CAST pcXPATHBrother);
    if( xPathObj == NULL )
    {
        return -1;
    }

    // Get the div node
    xmlNodeSetPtr xNodes = xPathObj->nodesetval;
    xmlNodePtr xDivNode = xNodes->nodeTab[0];

    xmlNodePtr xDivChildNode = xDivNode; //->xmlChildrenNode;
    if( (xAddType == eAddChildPrev) || (xAddType == eAddChildNext) )
    {
        xDivChildNode = xDivNode->xmlChildrenNode;
    }

    xmlNodePtr xHeadingNode = xmlNewNode(0, BAD_CAST pcChildName);
    xmlNodePtr xHeadingChildNode = xmlNewText(BAD_CAST pcChildContent);
    xmlAddChild(xHeadingNode, xHeadingChildNode);

    // Add the new element to the existing tree after the text content
    if( (xAddType == eAddPrev) || (xAddType == eAddChildPrev) )
    {
        xmlAddPrevSibling(xDivChildNode, xHeadingNode);
    }
    else
    {
        if( xAddType == eAddChildNext )
        {
            xmlAddSibling(xDivChildNode, xHeadingNode);
        }
        else
        {
            xmlAddNextSibling(xDivChildNode, xHeadingNode);
        }
    }

    //if you want to display the result
    xmlDocDump(stdout, xDoc);

    return 0;
}

OBS.: I don't have control over the generation of nodes, like that answer suggests.
How to convert <node/> to <node></node> with libxml (converting empty elements to start-end tag pairs)
So, how add nodes to a empty node with libxml2?
EDIT:
Debugging my function a little i find that in the line of i get the child:
xDivChildNode = xDivNode->xmlChildrenNode;

if the node is <node /> then the chindremNode will be null, so how to guarantee that not even return null?
thanks.

A: Based on your debug log, you need to replace
xmlNodePtr xDivChildNode = xDivNode; //->xmlChildrenNode;
if( (xAddType == eAddChildPrev) || (xAddType == eAddChildNext) )
{
    if (xDivNode->xmlChildrenNode == NULL){
        xmlNodeAddContent(xDivNode,BAD_CAST " ");//avoiding empty nodes, puting content in the node.
    }
    xDivChildNode = xDivNode->xmlChildrenNode;
}

To make sure the libxml don't add an empty node to your xml file.