text:
Q: How to cut addressing to external resource registry-1.docker.io in GitLab Code Quality Docker image? How to cut addressing to external resource registry-1.docker.io in GitLab Code Quality Docker image?
I have docker image from the registry.gitlab.com/gitlab-org/ci-cd/codequality:0.85.24
After I injected this image to my .gitlab-ci.yml I get the following error:
Error response from daemon: Get https://registry-1.docker.io/v2/: dial tcp 52.55.168.20:443: connect: connection refused
Unable to find image 'codeclimate/codeclimate:0.85.23' locally
docker: Error response from daemon: Get https://registry-1.docker.io/v2/: dial tcp 3.224.96.239:443: connect: connection refused.
See 'docker run --help'.

I understand that I can use a proxy to addressing this address, but access to external resources is denied in our gitlab registry.
However, this error occurs during the execution of the command in gitlab-ci:
- docker run \
    --env SOURCE_CODE="$PWD" \
    --volume "$PWD":/code \
    --volume /var/run/docker.sock:/var/run/docker.sock \

A: You can use a private registry for pulling Code Quality images:
https://docs.gitlab.com/ee/user/project/merge_requests/code_quality.html#configure-code-quality-to-use-a-private-container-image-registry

A: Not only can you use a private registry for pulling Code Quality images, but since GitLab 15.5 (October 2022):

Use Code Quality with a private, authenticated image registry
The Code Quality scanner downloads and runs container images to scan your code.
Previously, you could pull these images from a custom image registry, but you couldn't use a private registry that required authentication.
Now, you can provide a registry username and password by setting CI/CD variables when you include the Code Quality CI/CD template.
See Documentation and Issue.


text:
Q: Quick remote logging system? I want to be about to quickly insert some logging into some testing using either (Linux) command line or Python.  I don't want to do anything system wide (e.g. re-configuring syslogd).
I've done something like this before by doing:
wget URL/logme?im=module_name&msg=hello_world
And then just parsing the server log file.  It's a bit hackish and you have to URL encode all your data.  Surely someone has a better way by now.
Is there a better way to quickly get some remote logging?

A: You can use a remote syslog server: rsyslog or the python package loggerglue implements the syslog protocol as decribed in rfc5424 and rfc5425. . When you use a port above 1024 you can run it as a non-root user.
Within the python logging module you have a SyslogHandler which also supports the syslog remote logging.
import logging
import logging.handlers

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

handler = logging.handlers.SysLogHandler(address = ('127.0.0.1',514))

my_logger.addHandler(handler)

my_logger.debug('this is debug')
my_logger.critical('this is critical')

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use input text tag inside map in javascript I am trying to traverse my map on javascript to use the keys and values to form the input type="text" 's  id and name  = map's key
and value = tempMap[key]
var tempMap =  {"user" : "abc","password" : "xyz","Month" : "1", "Year" :"2016"}
for(item in tempMap){
        var itemVal = tempMap[item];
         var defaultRow = $('
 '+
                 ' '+
                   '
'+
                       ''+item+':'+''+
                       '<input type="text" name="'+item+'" id="' +item+ '" value = "' +itemVal+ '" />'+
                      '
'+
                    '	'+
                  '
' );

    }

for label it is working good, but its not working for input tag. How can I achieve this.

A: Your code work.
Another solution can be:
var tempMap = {"user" : "abc","password" : "xyz","Month" : "1", "Year" :"2016"};
$.each(tempMap,function(key,value){
var defaultRow = $('
 '+
             ' '+
               '
'+
                   ''+key+':'+''+
                   '<input type="text" name="'+key+'" id="' +key+ '" value = "' +value+ '" />'+
                  '
'+
                '	'+
              '
' );

alert(defaultRow.html())
});

A: Thank you all.

I used the below code and it worked fine now:

var resolvedStr =  '
 '+
        ' '+
        '
'+
            ''+item+':'+''+
            '<input type="text" name="itemName" id="itemId" value="itemVal"/>'+
           '
'+
         '	'+
       '
';
       resolvedStr = resolvedStr.replace("itemVal",itemVal);
       resolvedStr = resolvedStr.replace("itemId",item);


text:
Q: StackBlitz Ionic 5 Vue 3 sample: Import error, can't find file index.cjs.js I want to create a Ionic 5 Vue 3 sample:
https://stackblitz.com/edit/vue-ionic-attempt-qj2xsx?
But its always telling me:
Import error, can't find file:
./cjs/index.cjs.js

Any idea how to solve this?

A: Looks like there was an issue with some ionic vue releases only including index.js, and not variants like cjs and esm.
https://github.com/ionic-team/ionic-framework/issues/22765
I forked your stackblitz and updated ionic vue to 5.6
# package.json
-    "@ionic/vue": "^5.5.2",
-    "@ionic/vue-router": "^5.5.2",
+    "@ionic/vue": "^5.6.0",
+    "@ionic/vue-router": "^5.6.0",

https://stackblitz.com/edit/vue-ionic-attempt-pwwqq3?file=package.json
Still not starting though, just got a new error from vue router.
Error in /turbo_modules/vue-router@4.0.6/dist/vue-router.global.js (3343:7)
Vue is not defined


text:
Q: Dropped procedure shows up in USER_OBJECTS I've composed this SQL*Plus script, based upon other's suggestions, to remove all objects from current user:
SET ECHO OFF
SET HEADING OFF
SET PAGESIZE 0
SET FEEDBACK OFF
SET TIMING OFF
SET TIME OFF
SET TRIMSPOOL ON
SET TRIMOUT ON
SET LINESIZE 100

SET TERMOUT OFF
SPOOL eliminar-todo
/*
 * Descartamos objetos en la papelera ya que intentar eliminarlos directamente genera
 * «ORA-38301: no se puede realizar DDL/DML en objetos de la papelera de reciclaje»
 */
SELECT 'DROP ' || UO.OBJECT_TYPE || ' "' || UO.OBJECT_NAME || '"' ||
    DECODE(UO.OBJECT_TYPE,
        'CLUSTER', ' INCLUDING TABLES CASCADE CONSTRAINTS',
        'OPERATOR', ' FORCE',
        'TABLE', ' CASCADE CONSTRAINTS',
        'TYPE',  ' FORCE',
        'VIEW', ' CASCADE CONSTRAINTS',
    '') || ';'
FROM USER_OBJECTS UO
LEFT JOIN USER_RECYCLEBIN UR ON UO.OBJECT_NAME=UR.OBJECT_NAME
WHERE UO.OBJECT_TYPE IN (
    'CLUSTER', 'CONTEXT', 'DATABASE LINK', 'DIMENSION', 'DIRECTORY', 'FUNCTION', 'INDEX TYPE',
    'JAVA', 'LIBRARY', 'MATERIALIZED VIEW', 'OPERATOR', 'OUTLINE', 'PACKAGE', 'PROCEDURE',
    'SEQUENCE', 'SYNONYM', 'TABLE', 'TYPE', 'VIEW'
)
AND UR.OBJECT_NAME IS NULL
ORDER BY UO.OBJECT_TYPE, UO.OBJECT_NAME;
/
SPOOL OFF
SET TERMOUT ON

@eliminar-todo.lst

PURGE RECYCLEBIN;

I had an older simpler version that worked fine all the time:
select 'drop '||object_type||' '||object_name||
       decode(object_type,'CLUSTER',' including tables cascade constraints',
                          'OPERATOR', ' force',
                          'TABLE',' cascade constraints',
                          'TYPE', ' force',
                          'VIEW',' cascade constraints',
                          '')||';'
from user_objects
where object_type in ('CLUSTER', 'CONTEXT', 'DATABASE LINK', 'DIMENSION',
                      'DIRECTORY', 'FUNCTION', 'INDEX TYPE', 'JAVA',
                      'LIBRARY', 'MATERIALIZED VIEW', 'OPERATOR',
                      'OUTLINE', 'PACKAGE', 'PROCEDURE', 'SEQUENCE',
                      'SYNONYM', 'TABLE', 'TYPE', 'VIEW')
order by object_type, object_name

... but triggered syntax errors when user had BIN$... tables.
I tried double-quoting identifiers but got ORA-38301 instead:

can not perform DDL/DML Over Object in Recycle Bin

Current version attempts to avoid issuing DELETE TABLE statements for BIN$... tables. To do so, I join user objects with user recycle bin and omit matches. I've no longer had issues with BIN$... tables again. However, now I get this error message like 1 in 3 times:
DROP PROCEDURE "RESET_SEQUENCE"
*
ERROR en línea 1:
ORA-04043: el objeto RESET_SEQUENCE no existe

Apparently, procedure RESET_SEQUENCE shows up in USER_OBJECTS but no longer exists when DROP PROCEDURE "RESET_SEQUENCE" runs.

*

*How's that possible?

*How can I fix it?

A: firstly, in your script you're running the cursor twice because you have ; and /.
ORDER BY UO.OBJECT_TYPE, UO.OBJECT_NAME;
/

From SQL: the semicolon or the slash?:

There is a huge difference in SQL*Plus between the meaning of a / and
  a ; because they work differently.
The ; ends a SQL statement, whereas the / executes whatever is in the
  current "buffer". So when you use a ; and a / the statement is
  actually executed twice.


text:
Q: Keras loss output doesn't change - activation and open topics checked I'm currently struggling with my CNN.
I use the categorial_crossentropy and I will add on my model.
Neither the acc increases nor decreases the loss.
The amount of labeled data is now 600, which is fairly small, but no changes at all seem pretty strange to me.
### Define architecture.
model.add(Conv2D(32, 4, strides=(11,11),padding="same",input_shape=(200,200,3), activation="relu"))

model.add(Dropout(0.2))

model.add(BatchNormalization())

model.add(Conv2D(64, 4, strides=(9,9),padding="same", activation="relu"))

model.add(Dropout(0.2))

model.add(BatchNormalization())

model.add(Conv2D(128, 4, strides=(5,5),padding="same", activation="relu"))

model.add(Dropout(0.2))

model.add(BatchNormalization())

model.add(GlobalMaxPooling2D())

model.add(Dense(128, activation="relu"))

model.add(Dense(y_test.shape[1], activation="sigmoid"))

model.summary()

sgd = optimizers.SGD(lr=0.1,) #0.1
model.compile(loss='categorical_crossentropy', optimizer='sgd',
              metrics=['accuracy'])

model1 = model.fit(x_train, y_train,batch_size=32, epochs=10, verbose=1)

Epoch 1/10
420/420 [==============================] - 5s 11ms/step - loss: 1.4598 - acc: 0.2381

Epoch 2/10
420/420 [==============================] - 1s 3ms/step - loss: 1.4679 - acc: 0.2333

Epoch 3/10
420/420 [==============================] - 1s 3ms/step - loss: 1.4335 - acc: 0.2667

Epoch 4/10
420/420 [==============================] - 1s 3ms/step - loss: 1.4198 - acc: 0.2310

Epoch 5/10
420/420 [==============================] - 1s 3ms/step - loss: 1.4038 - acc: 0.2524

Epoch 6/10
420/420 [==============================] - 1s 3ms/step - loss: 1.4343 - acc: 0.2643

Epoch 7/10
420/420 [==============================] - 1s 3ms/step - loss: 1.4281 - acc: 0.2786

Epoch 8/10
420/420 [==============================] - 1s 3ms/step - loss: 1.4097 - acc: 0.2333

Epoch 9/10
420/420 [==============================] - 1s 3ms/step - loss: 1.4071 - acc: 0.2714

Epoch 10/10
420/420 [==============================] - 1s 3ms/step - loss: 1.4135 - acc: 0.2476

Is there something wrong with my model?
I tried changing the lr, the size of the pictures, tried to simplfy the model, changed the kernelsize, let it run for more epochs( up to 60) and printed the prediction for x_test.
The prediciton seemed wrong aswell:
error = model.predict(x_test)

print(error)

[[0.49998534 0.49998534 0.4999715  0.50000155]

 [0.49998188 0.49998283 0.49997032 0.5000029 ]

 [0.49998188 0.4999858  0.49998164 0.5000036 ]

 [0.4999795  0.49998736 0.4999841  0.5000008 ]

 [0.49998784 0.49997187 0.49996948 0.5000013 ]

 [0.49997532 0.49997967 0.49997616 0.50000024]

Every kind of help is very appreciated! Thank you!

A: I can suggest you several things based on my experiences for you to try:

*

*Since you are using categorical crossentropy, you can try 'softmax' as an activation function instead of 'sigmoid' at the last layer.

*You should decrease your learning rate. (With new settings suggested here)

*You may try to use different optimizer such as 'adam' instead of 'sgd'.

*You can delete dropout and batch normalization layers and add them only if they are necessary.

*Make your kernels dimension [2x2] instead of 1. Change kernel size from 4 to (3x3) maybe. Also decrease size of strides, maybe you can start with (1,1). Using kernel with size 4 on image with dimension [200x200] with strides (11,11) is almost equal to learning 'nothing'.

Please try final suggestion first as it seems like the main problem. I hope one of these may help you.

A: Please try the below setting:

*

*Reduce the strides to 1*1 or 2*2 or at the max 3*3

*Remove the dropouts between Convolutional layers, use dropouts only before dense layers, if necessary

*Try adding pooling layers, preferably of strides 2*2 and kernel size of 2*2 after Convolutional layers.

*Change optimization to adam/nadam

*Use softmax instead of sigmoid

*Increase the number of epochs, 10 is too low.

All the above points can vary depending upon the problem, never the less, you can give a try, and modify the model accordingly.

A: it seems like you lose almost all the spatial information in the image in the first two layer because of the strides you used.
your model.summary() shows the problem:
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 19, 19, 32)        1568
_________________________________________________________________
dropout_1 (Dropout)          (None, 19, 19, 32)        0
_________________________________________________________________
batch_normalization_1 (Batch (None, 19, 19, 32)        128
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 3, 3, 64)          32832
_________________________________________________________________
dropout_2 (Dropout)          (None, 3, 3, 64)          0
_________________________________________________________________
batch_normalization_2 (Batch (None, 3, 3, 64)          256
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 1, 1, 128)         131200
_________________________________________________________________
dropout_3 (Dropout)          (None, 1, 1, 128)         0
_________________________________________________________________
batch_normalization_3 (Batch (None, 1, 1, 128)         512
_________________________________________________________________
global_max_pooling2d_1 (Glob (None, 128)               0
_________________________________________________________________
dense_1 (Dense)              (None, 128)               16512
_________________________________________________________________
dense_2 (Dense)              (None, 4)                 516
=================================================================
Total params: 183,524
Trainable params: 183,076
Non-trainable params: 448

what you see is an immediate drop in tensor size from 200 in the original image to 19 after the first convolution, and to 3 after the second. we would expect a much more gradual decrease in size in order to really use the advantage of the convolutional layers.
if you keep your code as is and change all the strides to(2, 2) you will get a much more reasonable structure:
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 100, 100, 32)      1568
_________________________________________________________________
dropout_1 (Dropout)          (None, 100, 100, 32)      0
_________________________________________________________________
batch_normalization_1 (Batch (None, 100, 100, 32)      128
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 50, 50, 64)        32832
_________________________________________________________________
dropout_2 (Dropout)          (None, 50, 50, 64)        0
_________________________________________________________________
batch_normalization_2 (Batch (None, 50, 50, 64)        256
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 25, 25, 128)       131200
_________________________________________________________________
dropout_3 (Dropout)          (None, 25, 25, 128)       0
_________________________________________________________________
batch_normalization_3 (Batch (None, 25, 25, 128)       512
_________________________________________________________________
global_max_pooling2d_1 (Glob (None, 128)               0
_________________________________________________________________
dense_1 (Dense)              (None, 128)               16512
_________________________________________________________________
dense_2 (Dense)              (None, 4)                 516
=================================================================
Total params: 183,524
Trainable params: 183,076
Non-trainable params: 448
_________________________________________________________________


text:
Q: Django request.is_ajax returns False when using XMLHttpRequest I'm sending cross-domain ajax request and on another end request.is_ajax() gives False
var text = getSelectedText();
  text = 'text';
  if (text){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText)
        }
    };

    xhttp.open("GET", "http://example.com/text=" + encodeURIComponent(text), true);
    xhttp.send();}

A: You will have do add it manually (as jQuery and other libraries does):
xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');


text:
Q: Remove audio from video using Python I need to remove all audio from a video and save the video without the audio. The original can de discarded.
All answers I've found use ffmpeg, but this is not really an option for my use case.

A: You can use moviepy:
from moviepy.editor import VideoFileClip

videoclip = VideoFileClip("video.mp4")
new_clip = videoclip.without_audio()
new_clip.write_videofile("final_cut.mp4")


text:
Q: Add 1 to a random value in a column using dplyr I have the following dataframe, in tibble format:
> Colours_and_numbers

# A tibble: 10 × 2
   colours numbers
   <chr>     <dbl>
 1 Yellow        7
 2 Red          19
 3 Orange        8
 4 Blue         10
 5 Green         5
 6 Black         9
 7 Purple        9
 8 White        13
 9 Grey         11
10 Brown         9

I would like to add 1 to a randomly chosen row from the numbers column using dplyr. For that purpose I tried using
Colours_and_numbers %>%
   mutate(numbers= replace(numbers, sample((1:10), 1), colours[sample((1:10), 1)] + 1))

However, this is not working, as first sample() and second sample() will hardly ever refer to the same element of the numbers column.
Is there a way I can make sure both sample() refer to the same element without creating a specific variable to store the value generated by the first sample() and then using it in the last part of the replace() function? If you come up with a simpler way to add 1 to a random row, it would also appreciate that.

A: Try this:
Colours_and_numbers %>%
  mutate(
    numbers = numbers + sample(c(rep(0, n()-1), 1), n(), F)
  )

Reprex with some dummy data:
set.seed(1)
library(dplyr, warn.conflicts = F)
tibble(numbers = 1:10) %>%
  mutate(
    numbers = numbers + sample(c(rep(0, n()-1), 1), n(), F)
  )
#> # A tibble: 10 x 1
#>    numbers
#>      <dbl>
#>  1       1
#>  2       2
#>  3       3
#>  4       4
#>  5       5
#>  6       6
#>  7       7
#>  8       9
#>  9       9
#> 10      10

Created on 2022-08-18 by the reprex package (v2.0.1)

A: You could use ifelse so that there is no need to refer to the sampling number twice.
Colours_and_numbers %>%
  mutate(res = ifelse(1:n() == sample(n(), 1), numbers+1, numbers))

#    colours numbers res
# 1   Yellow       7   7
# 2      Red      19  19
# 3   Orange       8   8
# 4     Blue      10  10
# 5    Green       5   5
# 6    Black       9   9
# 7   Purple       9  10 <here>
# 8    White      13  13
# 9     Grey      11  11
# 10   Brown       9   9

Data
Colours_and_numbers <- structure(list(
  colours = c("Yellow", "Red", "Orange", "Blue", "Green", "Black", "Purple", "White", "Grey", "Brown"),
  numbers = c(7L, 19L, 8L, 10L, 5L, 9L, 9L, 13L, 11L, 9L)),
  class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))

A: If you want to append a randomly selected row to an existing table, you can sample the row index and bind the rows.
Colours_and_numbers %>% dplyr::bind_rows(.[sample(nrow(.), 1),])

A: Simpler with magrittr + base R:
library(magrittr)

row <- sample(nrow(Colours_and_numbers), 1L)
Colours_and_numbers[row, "numbers"] %<>% add(1L)


text:
Q: ANOVA or Fisher's Exact? I need to compare (check for any statistical significance)  eight groups (categorical data: group A-H) for which I have only the frequencies (ranging from 4-40) which are one point data (No replicate values). I have values for these eight groups for males and females separately (2 x 8 ?).
Can I carryout an ANOVA for my comparison between the groups within one gender, and to compare between genders or do I have to do a Fisher's exact test as I do not have replicates?
Please explain, for I am a complete novice in statistics
Edit: Actually 148 humans were tested for the group (A-H) of bacteria they harbour, and one subject /human has exclusive one of the eight groups. In other words, the total of the frequencies under each group adds up to 148


text:
Q: SQL Server : query to get sum of values in Col1 of Table1 for a condition in Col2 of Table 2 I have two tables. Table1 has Col1 and Col2 and Table2 has Col1 and Col3.
So col1 name is common in both the tables.
I need a query that should do sum of matched strings for common ROW IDs (Table1-col1 value)
Attached this screenshot:

A: I would try this (udpated for nulls and empty spaces):
SELECT 'Success', SUM(t2.Col2) FROM Table1 t1 JOIN Table2 t2 ON t1.Col1 = t2.Col1 WHERE t1.Col2 = 'Success' UNION ALL
SELECT 'Failure', SUM(t2.Col2) FROM Table1 t1 JOIN Table2 t2 ON t1.Col1 = t2.Col1 WHERE t1.Col2 = 'Failure' UNION ALL
SELECT 'NULL', SUM(t2.Col2) FROM Table1 t1 JOIN Table2 t2 ON t1.Col1 = t2.Col1 WHERE t1.Col2 IS NULLUNION ALL
SELECT 'EMPTY SPACE', SUM(t2.Col2) FROM Table1 t1 JOIN Table2 t2 ON t1.Col1 = t2.Col1 WHERE t1.Col2 = ' '

will give you two rows with the results you wanted.

*

*UNION ALL simply concatenates two or more rows (with the same columns); ALL tells to ignore duplicates (which is not a concern here and actually speeds up performance)

*SUM of course sums all cells in a column

*JOIN will "merge" your tables

A JOIN clause is used to combine rows from two or more tables, based on a related column between them.


text:
Q: adngular 4 sass compiling issue Seems that angular doesn't compile sass correctly for components or it does not as expected.
For e.g. this code works well for app.component.scss:
/* Works well */
.container {
   .header {
      margin-top: 20px;
   }
}
.container {
   .header {
      background-color: black;
   }
}

But if I generate header component and then add style to the header.component.scss that has repetitive selectors for some reason then this will not work!
/* Doesn't work */
.container {
   .header {
      padding: 15px;
   }
}

Just don't tell me that I shouldn't write such scss code untill it would be recognized by Angular framework correclty. Or explain if I'am doing something wrong :)

A: I can see, I think you are facing the issue of view-encapsulation

*

*Native view encapsulation uses the browser's native shadow DOM
  implementation (see Shadow DOM on the MDN site) to attach a shadow
  DOM to the component's host element, and then puts the component
  view inside that shadow DOM. The component's styles are included
  within the shadow DOM.

*Emulated view encapsulation (the default) emulates the behavior of
      shadow DOM by preprocessing (and renaming) the CSS code to
      effectively scope the CSS to the component's view.

*None means that Angular does no view encapsulation. Angular adds the
      CSS to the global styles. The scoping rules, isolations, and
      protections discussed earlier don't apply. This is essentially the
      same as pasting the component's styles into the HTML.

encapsulation: ViewEncapsulation.Native


text:
Q: Ringbuffer with sprintf I'm trying to create a ringbuffer and fill it with an array of split string elements. Buffer Code is taken from here and works well enough.
Here is my main and the buffer implementation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 struct buffer {
    int size;
    int start;
    //int end;  // position of last element
    /* Tracking start and end of buffer would waste
     * one position. A full buffer would always have
     * to leave last position empty or otherwise
     * it would look empty. Instead this buffer uses
     * count to track if buffer is empty or full
     */
    int count; // number of elements in buffer
    /* Two ways to make buffer element type opaque
     * First is by using typedef for the element
     * pointer. Second is by using void pointer.
     */
    /* different types of buffer:
    int *element;   // array of integers
    char *element;  // array of characters
    void *element;  // array of void type (could cast to int, char, etc)
    char **element; //array of char pointers (array of strings)
    void **element; // array of void pointers
    Choosing array of void pointers since it's the most flexible */
    char **element;
};

typedef struct buffer buffer_t;

void init(buffer_t *buffer, int size) {
    buffer->size = size;
    buffer->start = 0;
    buffer->count = 0;
    buffer->element = malloc(sizeof(buffer->element)*size);
    /* allocated array of void pointers. Same as below */
    //buffer->element = malloc(sizeof(void *) * size);

}

int full(buffer_t *buffer) {
    if (buffer->count == buffer->size) {
        return 1;
    } else {
        return 0;
    }
}

int empty(buffer_t *buffer) {
    if (buffer->count == 0) {
        return 1;
    } else {
        return 0;
    }
}

void push(buffer_t *buffer, void *data) {
    int index;
    if (full(buffer)) {
        printf("Buffer overflow\n");
    } else {
        index = buffer->start + buffer->count++;
        if (index >= buffer->size) {
            index = 0;
        }
        buffer->element[index] = data;
    }
}

void * popqueue(buffer_t *buffer) {
    void * element;
    if (empty(buffer)) {
        printf("Buffer underflow\n");
        return "0";
    } else {
        /* FIFO implementation */
        element = buffer->element[buffer->start];
        buffer->start++;
        buffer->count--;
        if (buffer->start == buffer->size) {
            buffer->start = 0;
        }

        return element;
    }
}

int main() {
    char input[] = "[MVOLT][S1][M1]40.05[S1][M2]39.95";
    char *string_buffer = malloc(sizeof(char)*10);
    buffer_t buffer;
    init(&buffer, 5);

    char delimiter[] = "[";
    char *ptr;

    int i;
    ptr = strtok(input, delimiter);

    for (i = 0; i < 5; i++) {
        sprintf(string_buffer,"[%s", ptr);
        printf("push: %s", string_buffer);
        // works but with missing character
        push(&buffer, ptr);
        // outputs the last element to the queue?
        push(&buffer, string_buffer);
        ptr = strtok(NULL, delimiter);
    }

    printf("\n");
    for (i = 0; i < 5; i++) {
        printf("pop from queue: %s\n", popqueue(&buffer));
    }

}

When I pass the ptr element to the push function everything works correctly. However if I use sprintf to add the missing character I only get the last element. What is sprintf doing that is triggering this behavior?
Output from putting the ptr input directly:
push: [MVOLT]
push: [S1]
push: [M1]40.05
push: [S1]
push: [M2]39.95

pop from queue: MVOLT]
pop from queue: S1]
pop from queue: M1]40.05
pop from queue: S1]
pop from queue: M2]39.95

Output using sprintf:
push: [MVOLT]
push: [S1]
push: [M1]40.05
push: [S1]
push: [M2]39.95

pop from queue: [M2]39.95
pop from queue: [M2]39.95
pop from queue: [M2]39.95
pop from queue: [M2]39.95
pop from queue: [M2]39.95

A: As I guessed, you have an array of pointers and only store pointers.
When you do
push(&buffer, string_buffer);

you pass a pointer to the first element of the string_buffer array. This pointer will always be the same.
One possible solution is to use the non-standard (but commonly available) strdup function to dynamically create a new string:
push(&buffer, strdup(string_buffer));

Note that this requires you to free the pointer when you're done with it, or you'll have a memory leak.


text:
Q: Integer literal with single quotes? What exactly as been assigned to value? I am surprised that this has compiled at all.
//g++  7.4.0

#include <iostream>

int main()
{
    auto value = 123'456'7;
    std::cout << value << std::endl;

    value += 1;
    std::cout << value << std::endl;
}

outputs:
1234567
1234568

A: Since C++14,
from https://en.cppreference.com/w/cpp/language/integer_literal

Optional single quotes(') may be inserted between the digits as a separator. They are ignored by the compiler.

A: C++ allows single quotes to separate the digits for better reading:
https://en.cppreference.com/w/cpp/language/integer_literal

Optional single quotes(') may be inserted between the digits as a separator. They are ignored by the compiler.


text:
Q: How to display value of selected row to next view controller? I have an array.This array loading from web service in TableView.
There are all BranchId in tableview.I want display fields of selected branchId when selected row.
e.g Selected "1234" in tableview
Open new view controller(DetailViewController) :
BranchID:1234
BranchName: ABCDEFGH
I have Branchname in web service
TableviewCodes:  http://pastie.org/8052416
How can I display selected ID's detail on new view controller ? Thanks

A: There are different ways, here is one:
From your first viewController:
 NSDictionary* dict = [NSDictionary dictionaryWithObject:
                          [NSNumber numberWithInt:theIdYouWantToSend]
                                                     forKey:@"index"];

[[NSNotificationCenter defaultCenter] postNotificationName: @"getID" object: dict];

Now from the new view controller (detailViewController), in the viewDiDLoad method:
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getID:) name:@"getID" object:nil];

and create method:
-(void)getID:(NSNotification*)notification{
    NSDictionary* dict = (NSDictionary*) notification.object;

}

You can easily get the ID from the dictionary
myId = [dict objectForKey:@"index"];

A: you should modify didSelectRow method by below way:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

     DetailViewController *second=[[DetailViewController alloc]
initWithNibName:@"DetailViewController" bundle:nil] ;

    second.branchId = [myArray objectAtIndex:indexPath.row];

    [self presentModalViewController:second animated:YES];
}


text:
Q: GitHub Actions step executed while it shouldn't, based on a conditional I have the following steps' sequence in a GitHub Actions job (first one is used more or less for debugging purposes
env:
  FAIL_OUTCOME: 'fail'

      - name: debug
        shell: bash
        run: |
          echo "evaluation-1 result is ${{ steps.evaluation_1.outputs.evaluation-1-outcome }}
          echo "evaluation-2 result is ${{ steps.evaluation_2.outputs.evaluation-2-outcome }}
          echo $FAIL_OUTCOME

      - name: send slack failure
        if: ${{ steps.evaluation_1.outputs.evaluation-1-outcome }} == $FAIL_OUTCOME || ${{ steps.evaluation_2.outputs.evaluation-2-outcome }} == $FAIL_OUTCOME
        uses: rtCamp/action-slack-notify@v2
        env:
           ...

      - name: send slack success
        if: ${{ steps.evaluation_1.outputs.evaluation-1-outcome }} != $FAIL_OUTCOME && ${{ steps.evaluation_2.outputs.evaluation-2-outcome}} != $FAIL_OUTCOME
        uses: rtCamp/action-slack-notify@v2
        env:
          ...

Here is the outcome of the debug action:
  echo "evaluation-1 result is
  echo "evaluation-2 result is fail

where it seems that first outcome is not set.
However, what puzzles me is that success action is also executed, i.e.
${{ steps.evaluation_1.outputs.evaluation-1-outcome }} != $FAIL_OUTCOME && ${{ steps.evaluation_2.outputs.evaluation-2-outcome}} != $FAIL_OUTCOME

becomes true. How is it possible?
To provide for more context, the outputs' assignment in previous steps are as follows:
echo "::set-output name=evaluation-2-outcome::$FAIL_OUTCOME"

A: The straight answer to your question is that you are misusing the $FAIL_OUTCOME value in if statements.
There you need to use:
if: steps.evaluation_1.outputs.evaluation-1-outcome == env.FAIL_OUTCOME || steps.evaluation_2.outputs.evaluation-2-outcome == env.FAIL_OUTCOME
...
if: steps.evaluation_1.outputs.evaluation-1-outcome != env.FAIL_OUTCOME && steps.evaluation_2.outputs.evaluation-2-outcome != env.FAIL_OUTCOME

or:
if: ${{ steps.evaluation_1.outputs.evaluation-1-outcome == env.FAIL_OUTCOME || steps.evaluation_2.outputs.evaluation-2-outcome == env.FAIL_OUTCOME }}
...
if: ${{ steps.evaluation_1.outputs.evaluation-1-outcome != env.FAIL_OUTCOME && steps.evaluation_2.outputs.evaluation-2-outcome != env.FAIL_OUTCOME }}

Env variables can be accessed as $FAIL_OUTCOME only in bash scopes - everywhere else, you need to explicitly use env. prefix.
However, I would recommend doing it properly and not fighting with env variables combined with set-output madness - which has a lot of gotchas and it's hard to debug and maintain.
Slack success and failures can be easily handled by checking the output of the whole job:
 - name: send slack failure
   if: failure()

 - name: send slack success
   if: success()

If you want to communicate about failure of some steps only:
notify_failure:
    if: always() && !cancelled() && needs.check_failure_step.result != 'success'
    needs: check_failure_step

And instead of using echo set-output:: just exit 1 to fail a certain job.
Combining that with needs and jobs output values and if: always() you can achieve anything you want.
It gives you also a huge advantage of seeing which job has failed straight on workflow run summary without looking to its "output" or "debug" logs.


text:
Q: AdWords clicks/cost lower than Google Analytics clicks/cost I'm having an issue where Google AdWords is reporting fewer clicks/cost than what is shown in Google Analytics clicks and cost.  I will take a 7 day range in AdWords and Analytics.  AdWords is usually reporting about 11%-14% fewer clicks and cost than Analytics.  The top 5 or so campaigns match exactly in AdWords and Analytics (i.e. campaign #1 shows 100 clicks and $100 cost in both GA and AdWords).
I've checked my code and the embed code is right before .
Only 1 AdWords account is linked to Google Analytics.
Is there anything else to check?  I don't expect the numbers to match exactly, but 11%-14% is a fairly big variation.  In my research, it seems like most users are having the inverse issue (more adwords clicks/cost than analytics clicks/cost)

A: Check invalid click activity. You can enable this in your columns and also check the billing activity to see if there are any refunds from Google for invalid activity. Google AdWords removes those data from your reporting and Google Analytics don't.


text:
Q: Sorting by relevance performance issues Is there a function / method within mongoose (and or mongodb) which could be used to sort a queries results based on relevance (highest number of matching query params)?
The example below is what I am using at the moment (the query uses $in:[], otherwise the same) - my collection is quite small so performance is fine but on larger collections it slows things down dramatically.
Alternatively, if there is a better performing method (outside of mongoose / mongodb) I'd be happy to know about it.
Example:
var docs = [
    {
        fruits: ['apple', 'orange', 'tomato'],
        colors: ['blue', 'green'],
        // relevance: 3
    },
    {
        fruits: ['apple', 'carrot'],
        colors: ['red', 'green'],
        // relevance: 2
    }
]

var query = {fruits: ['apple', 'orange'], colors: ['green']}

docs.forEach(function(doc){
    var relevance = 0
    Object.keys(query).forEach(function(_query){
        var arrays = [doc[_query], query[_query]]
        var result = arrays.shift().filter(function(v) {
            return arrays.every(function(a) {
                return a.indexOf(v) !== -1;
            });
        });
        relevance += result.length
    })
    doc.relevance = relevance
})

Result:
var docs = [
    {
        fruits: ['apple', 'orange', 'tomato'],
        colors: ['blue', 'green'],
        relevance: 3
    },
    {
        fruits: ['apple', 'carrot'],
        colors: ['red', 'green'],
        relevance: 2
    }
]

A: You can do it with aggregation:

db.getCollection('docs').aggregate([
{$match: {fruits: {$in: ['apple', 'orange']}, colors: {$in: ['green']}}},
{$project: {
    relevance: {
        $sum: [
          {$cond: {if: { "$setIsSubset": [['orange'], "$fruits" ]}, then: 1, else: 0}},
          {$cond: {if: { "$setIsSubset": [['apple'], "$fruits" ]}, then: 1, else: 0}},
          {$cond: {if: { "$setIsSubset": [['green'], "$colors" ]}, then: 1, else: 0}}]
    },
    doc: '$$ROOT'}}
])

result:

/* 1 */
{
    "_id" : ObjectId("57be8a9b65d2835e960df543"),
    "relevance" : 3,
    "doc" : {
        "_id" : ObjectId("57be8a9b65d2835e960df543"),
        "fruits" : [
            "apple",
            "orange",
            "tomato"
        ],
        "colors" : [
            "blue",
            "green"
        ]
    }
}

/* 2 */
{
    "_id" : ObjectId("57be8aa865d2835e960df544"),
    "relevance" : 2,
    "doc" : {
        "_id" : ObjectId("57be8aa865d2835e960df544"),
        "fruits" : [
            "apple",
            "carrot"
        ],
        "colors" : [
            "red",
            "green"
        ]
    }
}


text:
Q: Update custom column data in quote table Magento 2 I inserted a custom column in quote table like this:
if (version_compare($context->getVersion(), '1.0.1', '<')) {
          $setup->getConnection()->addColumn(
              $setup->getTable('quote'),
              'custom_column',
              [
                  'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                  'nullable' => true,
                  'comment' => 'Custom Column',
             ]
          );
        }

The custom column was successfully created, and added to every single row in quote table with null value, but the problem is, i don't know how to update the custom column data in the quote table by using only quote id

A: The easiest way to solve this is to fill in this field in the quote model and save it using the Repository:
class QuoteUpdater
{
    /**
     * @var \Magento\Quote\Model\QuoteRepository
     */
    protected $quoteRepository;

    /**
     * @param \Magento\Quote\Model\QuoteRepository $quoteRepository
     */
    public function __construct(
        \Magento\Quote\Model\QuoteRepository $quoteRepository
    ) {
        $this->quoteRepository = $quoteRepository;
    }

    public function updateQuoteData($quoteId, int $customData)
    {
        $quote = $this->quoteRepository->get($quoteId); // Get quote by id
        $quote->setData('custom_column', $customData); // Fill data
        $this->quoteRepository->save($quote); // Save quote
    }
}

A: To set data in quote table, use below code -
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$quoteId = 10;
$customColumnValue = 1;
$quote = $objectManager->create('Magento\Quote\Model\Quote')->load($quoteId);
$quote->setCustomColumn($customColumnValue);
$quote->save();

Here replace $quoteId variable with your quote ID .


text:
Q: Идентификаторы: createHanningWindow и phaseCorrelate не найдены Пытался скомпилировать демку
\#include "opencv2/core/core.hpp"

\#include "opencv2/highgui/highgui.hpp"

\#include "opencv2/imgproc/imgproc.hpp"

using namespace cv;

int main(int, char* [])

{

    // Создание видеопотока с камеры

    VideoCapture video(0);

    Mat frame, curr, prev, curr64f, prev64f, hann;

    int key = 0;

    do
    {
        video >> frame; // Очередной фрейм
        cvtColor(frame, curr, CV_RGB2GRAY); // Перевод в градации серого

        if(prev.empty())
        {
            prev = curr.clone(); // клонирование изображения
            createHanningWindow(hann, curr.size(), CV_64F); // Создание окна Ханна
        }

        prev.convertTo(prev64f, CV_64F);
        curr.convertTo(curr64f, CV_64F);

        Point2d shift = phaseCorrelate(prev64f, curr64f, hann); // Фазовая корреляция
        double radius = cv::sqrt(shift.x*shift.x + shift.y*shift.y); // Вычисление радиуса отклонения

        if(radius > 5)
        {
            // вывод на экран окружности и направления смещения
            Point center(curr.cols >> 1, curr.rows >> 1);
            cv::circle(frame, center, (int)radius, cv::Scalar(0, 255, 0), 3, CV_AA);
            cv::line(frame, center, Point(center.x + (int)shift.x, center.y + (int)shift.y), cv::Scalar(0, 255, 0), 3, CV_AA);
        }

        imshow("phase shift", frame);
        key = waitKey(2);

        prev = curr.clone();
    } while((char)key != 27); // Esc to exit...

    return 0;
}

Но Visual Studio не смог найти идентификаторы createHanningWindow и phaseCorrelate.
Подскажите, пожалуйста, в чём может быть проблема?


text:
Q: Greek letters do not function inside tabular even with dollar sign I am trying to use Greek letters inside a tabular-table, but it does not work. Underneath is the sourcecode and error report. Does anyone know how to fix this?
source code (relevant source only):
\begin{tabular}{| c | c | c | c |}
\hline
Klein & Groß & Sprechweise & \LaTeX{}-Schreibweise\\
\hline
\hline
$ \alpha $ & $ \Alpha $ & Alpha & \\
\hline
\end{tabular}
\end{document}

Error report:
! Undefined control sequence [in line with the dollar signs]

A: As described in the comments to your question the capital version of the greek letter alpha is identical to capital a (A). Thus, there is no LaTeX command for this letter as it is already defined by A.
The set of greek letters that do not have a special command for their capital representation is Alpha (A), Beta (B), Epsilon (E), Zeta (Z), Eta (E), Iota (I), Kappa (K), Mu (M), Nu (N), Omicron (O), Rho (P), Tau (T), Upsilon (Y) and Chi (X).
To make your code compile simply replace \Alpha with A.
\documentclass{article}
\usepackage[utf8]{inputenc}

\begin{document}
  \begin{tabular}{| c | c | c | c |}
    \hline
    Klein & Groß & Sprechweise & \LaTeX{}-Schreibweise\\
    \hline
    \hline
    $ \alpha $ & $ A $ & Alpha & \\
    \hline
  \end{tabular}
\end{document}


text:
Q: ArrayIndexOutOfBoundsException: length=20; index=20? it shows me this error when I enter in my listview over 20 "pieces", how can I do to avoid this?
> java.lang.ArrayIndexOutOfBoundsException: length=20; index=20
>  at com.Amarildo.asd.List_View_Esercizi.getView(List_View_Esercizi.java:33)

the error is at this line
img.setImageResource(imageId[position]);

appears only if I post in the listview more than 20 components
This is my adapter
public class List_View_Esercizi extends ArrayAdapter<String> {

private Activity context;
private String[] nome;
private Integer[] imageId;

public List_View_Esercizi(Activity context, String[] nome, Integer[] imageId) {
    super(context, R.layout.list_view_esercizi, nome);
    this.context = context;
    this.nome = nome;
    this.imageId = imageId;
}

public View getView(int position, View view, ViewGroup parent){
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView = inflater.inflate(R.layout.list_view_esercizi, null, true);
    TextView txt = (TextView) rowView.findViewById(R.id.textView);
    ImageView img = (ImageView) rowView.findViewById(R.id.imageView2);
    txt.setText(nome[position]);
    img.setImageResource(imageId[position]);
    return rowView;
}

A: you are providing the nome as dataset for your adapter that is bigger then imageId. Since the getCount() is based on nome, you will get getView called nome.lenght - 1 times. When position exceed the value of imageId.length - 1, you will get an ArrayIndexOutBoundException

A: index goes from 0 to length-1. Therefore you get the Exception when trying to access element[length].

A: If you're unsure of the sizes of your array just add a simple check, so setting the text and/or image is skipped.
if (nome.lenght > position) {
    txt.setText(nome[position]);
}
if (imageId.lenght > position) {
    img.setImageResource(imageId[position]);
}

A: This is occurring because one of your array is bigger in size than another ,
So I have a suggestion for you, If you have both of them same sized you should try to create a POJO class and make your ArrayAdapter use your POJO[] , that would reduce complexity and enhance readability and your code will be easy to debug also.
Njoy!


text:
Q: Подключение к трансляции через python Я только начал осваивать python и многое еще остается непонятным. Прошу помочь с возникшей трудностью.
Суть в следующем:
Через запрос к стриму онлайн камеры
import requests
req = requests.get("https://599da0b457148.streamlock.net:1936/traffic/trafcam6zel.stream/playlist.m3u8")
req.status_code

Получаю ответ 403 (Forbidden)
Однако, после захода на сайт используя браузер, где этот стрим опубликован (https://kgd.ru/traffic/camera/18-zelenogradsk-plyazh)
подключение через скрипт начинает осуществляться нормально, ответ req.status_code получаю "200" и я нормально подключаюсь к стриму используя cv2.VideoCapture.
Прошу объяснить почему так происходит, и какие есть возможности подключиться к этой трансляции без посещения сайта через браузер? Хочу периодически получать фотографии с этой камеры, чтобы наблюдать за волнами, но каждый раз приходится заходить на сайт через браузер, чтобы это получилось.
Заранее спасибо.


text:
Q: Is there any advantage of using size_t over int in this code? #include <iostream>
#include <array>

int main()
{
    std::array myArray { 7, 3, 1, 9, 5 };

    // Iterate through the array and print the value of the elements
    for (int i{ 0 }; i < myArray.size(); ++i)
        std::cout << myArray[i] << ' ';

    std::cout << '\n';

    return 0;
}

It is stated that
There is a signed/unsigned mismatch. The size() function and array index parameter to operator[] use a type called size_type.  Our loop counter/index (variable i) is a signed int. Therefore both the comparison i < myArray.size() and the array index myArray[i] have type mismatches.
I understand the statement, but what is the consequence of this mismatch?
My IDE (VS2019) neither gives a error nor a warning. Are there any performance benefits from using std::size_t in place of int in this code?
#include <array>
#include <cstddef> // std::size_t
#include <iostream>

int main()
{
    std::array myArray { 7, 3, 1, 9, 5 };

    for (std::size_t i{ 0 }; i < myArray.size(); ++i)
        std::cout << myArray[i] << ' ';

    std::cout << '\n';

    return 0;
}


text:
Q: How to handle microphone sound level update event in gnome extensions? I have certain global shortcuts to update the microphone sound input level. Therefore, I was creating a gnome extension that adds a label in the top bar, displaying the current microphone sound percentage.
The code in extension.js is something like this:
const Microphone = new Lang.Class({
  Name: 'Microphone',

  _init: function() {
    this.active = null;
    this.stream = null;
    this.muted_changed_id = 0;
    this.mixer_control = new Gvc.MixerControl({name: 'Some random name'});
    this.mixer_control.open();
    this.mixer_control.connect('default-source-changed', Lang.bind(this, this.refresh));
    this.mixer_control.connect('stream-added', Lang.bind(this, this.refresh));
    this.mixer_control.connect('stream-removed', Lang.bind(this, this.refresh));
    this.stream = this.mixer_control.get_default_source();
  },

  // ...

  get level() {
    return 100 * this.stream.get_volume() / this.mixer_control.get_vol_max_norm();
  }
});

function enable() {
  // ...
  microphone = new Microphone();
  let panel_button_label = new St.Label({
    y_expand: true,
    y_align: Clutter.ActorAlign.CENTER
  });
  panel_button_label.text = microphone.level + '%';
  Main.panel._rightBox.insert_child_at_index(panel_button_label, 0);
}

function disable() {
  // ...
  Main.panel._rightBox.remove_child(panel_button_label);
  panel_button_label.destroy();
  panel_button_label = null;
}

However, I don't know how to update the microphone.label label text each time the microphone level is updated by the global shortcut. As of now, it displays 0% always. I checked out the logs in journalctl, it has no warnings or errors.
I figured out a StackOverflow link on How to handle keyboard events in gnome shell extensions?, however, I don't want this to be linked to a particular keyboard event. Rather, the label should get updated even if the microphone level is changed through some other means.
I guess I need to connect this to a signal or use something similar to that, however, I don't know how to. I am new to gnome extensions, so a detailed explanation might be helpful.

A: You probably want to connect to the notify signal of Gvc.MixerStream for the volume property:
stream.connect('notify::volume', (stream) => {
  log(`New volume is ${stream.volume}`);
});

You can work that into your wrapper class if you want, perhaps making it a GObject subclass.


text:
Q: java: would jdwp slow down the performance? As known, after jdk 5, no need to specify -Xdebug for debugging, instead, use -agentlib:jdwp, but does it mean debug mode is gone? And does it mean the java program would run in normal mode without any performance trade-off, while you could still attach it anytime you want to debug it?
Compared to C/C++, you could debug the app compiled in optimized mode, as long as you do not strip debug symbols, although, in optimized mode the debugging is not so precised, due to e.g. some function is inline or eliminated. So BTW, does java have the concept of debug symbols/info when you need to take care when building the app?

A:
As known, after jdk 5, no need to specify -Xdebug for debugging, instead, use -agentlib:jdwp, but does it mean debug mode is gone?

Yes.  Old-school debug mode is gone.  (The -Xdebug option is ignored by modern JVMs.)

And does it mean the java program would run in normal mode without any performance trade-off, while you could still attach it anytime you want to debug it?

See Overhead of enabling JVMTI *capability* to query local variables for example.
There is some performance tradeoff1, but less than with -Xdebug.  A JVMTI agent suppresses some JIT compiler optimizations, not all.

Does java have the concept of debug symbols/info when you need to take care when building the app?

Yes it does.  See the -g option to javac.

1 - Most sources say that the cost is small or negligible, but I saw a comment that claimed a 10-fold performance hit.  It is not clear if this was the cost of -agentlib:jdwp ... or what the commenter was doing with the agent.  For example, if you enable entry / exit tracing, the performance cost is significant.  Unfortunately, this is all anecdotal ...


text:
Q: Wcf RESTful service returning xml without xml schema Here is my code:
[DataContract(Name = "ThisPlan")]
public class ThisPlanTemplate
{
    [DataMember (Name = "length", Order = 1), XmlAttribute]
    public decimal length { get; set; }
    [DataMember (Name = "height", Order = 2), XmlAttribute]
    public decimal height{ get; set; }
    [DataMember]
    public List<MyClass> parts { get; set; }
}

I want to get xml like the following:
<ThisPlan>
    <sections/>
    <length>100.00</length>
    <height>100.00</height>
</ThisPlan>

But I get this:
 <ThisPlan xmlns="some url">
    <sections xmlns:a="some url" i:nil="true"/>
    <length>100.00</length>
    <height>100.00</height>
</ThisPlan>

And how to remove the xmlns?

A: You would do this by specifying the XML namespace in your calls to Serialize().
var serializer = new XmlSerializer(typeof(myObject));
var myNamespace = new XmlSerializerNamespaces();
var myFile = File.Open(mypath, FileMode.OpenOrCreate);
myNamespace.Add("", "");
serializer.Serialize(myFile, myObject, myNamespace);

This code is for reference only and I would not use this in production, but it shows how you can specify your own namespace (or none at all). Hope this helps!


text:
Q: Reading IPTC properties on QuickTime files with MetadataExtractor in C#? I'm successfully using the MetadataExtractor library in C# to read EXIF and IPTC information out of JPEG files.
In Windows Explorer and Lightroom I can set similar values on .mp4 files (like headline and description), and see those values reflected in Windows Explorer and Lightroom. I can't see them with MetadataExtractor, however.
Is there a way to access them? The only metadata directories I'm getting back are File Type, Movie Header, Track Header, and File.
Thanks!


text:
Q: ImportError: cannot import name 'keras' from 'tensorflow' (unknown location) import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Activation, BatchNormalization, Conv2D, Dense, Dropout, Flatten, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import CategoricalCrossentropy
from tensorflow.keras.regularizers import l2
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping

i got this error
enter image description here


text:
Q: HIbernate optimistic locking only for certain updates I am looking into an issue in our system where two concurrently running transactions of a particular long operation try to update the same table row. As there is no locking currently, the transaction that commits second causes the updates of the first transaction to be lost. I would like to avoid this by optimistic locking.
The issue is that we don't have optimistic locking enabled currently. If I enable optimistic locking now by adding a dedicated version number column, this would then get enabled for every update on that table. The codebase is legacy and we are not aware of most parts of it. So, there might be other long running operations in the system which will start failing on enabling optimistic locking, some of these might even be OK to live with stale updates. Also, we would not like to introduce any new errors without knowing which parts of the system might be impacted.
So, my question:
Is there a way in hibernate to do optimistic locking for only certain updates.
From what I understood by reading hibernate documentation, using a dedicated version number or timestamp will enable optimistic locking on the table for every update.


text:
Q: Newtons law of gravity universal? Im a bit puzzled about the video from "One Minute Physics" claiming that Newtons law of gravity is not universal, but breaks down on very heavy objects and are not really confirmed on very light ones.
https://youtu.be/OTMELHUAzSM
I found the topic interesting, also because I teach basic physics in primary school (children age 13-16), and dont want to use wrong information. We do use some pretty odd examples just to make it a little more fun. But trying to read more on the subject just added confusion, because most places (books, web etc.) treats the gravitational law as a fundamental universal law.
Any takes on this? Is it fair to apply Newtons law using the weight of a student and the weight of a grain of dust (and explaining that in reality other forces will totally cancel out any measurable effect) etc? And does the law really break down on the extreme heavy objects as claimed in the video?

A: At present we are at the following level of mathematically modeling interactions of matter:
1) the underlying framework for all matter is quantum mechanical, all other theories will be emergent ( gravity has a question mark as it is only effectively quantized). This framework is evident in the microworld of particle physics and is important as long as boundary  conditions are with small distances  and $h$ ( Planck's constant)  in the uncertainty relationa $[x,p] >h/2π $  is fulfilled non trivially, i.e. the measurement accuracies are small enough . If $h/2π$ can be considered zero within measurement accuracies, one is in the classical frame.
2) The classical framework theories are emergent from the underlying quantum mechanical, and in the region of overlap it can be shown mathematically that the known classical equations hold non trivially. This means there is mathematically a smooth transition to Newton's mechanics
Newtonian gravity laws hold until masses and energies reach very high values.
c) For high velocities special relativity describes the data, and for high energies and masses the framework of General Relativity fits all cosmological observations to date.Again in the overlap region General Relativity reduces to Newton's law. Please note that both General  and special relativity are used in the GPS system that is so wide spread over the world .

Is it fair to apply Newtons law using the weight of a student and the weight of a grain of dust (and explaining that in reality other forces will totally cancel out any measurable effect) etc?

Yes, because if you put in the numbers, neither quantum mechanics nor special and general relativity are needed, the classical formulae are well within the errors.

And does the law really break down on the extreme heavy objects as claimed in the video?

Break down if used in the sense that the Newtonian formulae do not predict the correct numbers , yes. The situation has to extend to another framework
For particle physics special relativity is necessary, but models still use the gravitational potential even if it has little meaning for such small masses. It will depend on the particular problem and the boundary conditions . Since quantum mechanics is necessary for particle interaction models, it is fair to say that Newtonian gravity is not easily modeled.
Theortical physicists are working towards a theory of everything where gravity will also be definitevely quantized, the the transition between frameworks will be mathematically predictable. At the moment string theories can have quantization of gravity and embed the standard model of particle physics, but the definite theory is not yet attained. In any case for everyday classical experiments there will be no difference when it is attained (imo of course).

A: Newtonian gravity is said to be universal. However when they mean universal they mean it is mostly universal. There are times when it does not work. For example in the Big Bang or near or even inside a black hole(even general relativity does not work in the inside of a black hole). When things get really small or really big there is a possibility that gravity leaks out into another dimension. Einstein's theory of relativity does this a little better. It tries to explain gravity as not a force but a property of space. Curvature of space results in gravity. Even this however does not fully explain the nature of quantum gravity and gravity in extremely large scales.


text:
Q: Query for unique item in list I have an SP list of items, each item has a unique Title. I would like to use the title as my way to find and then update that row of data. I thought the below code would find only the item that has a Title = "Apptest" but it always gives me all items in the list and all of them are updated. I get the same results if I remove the ViewXml line, so I think there is something wrong with that line but I can't find it. Before:
 After:
var list = clientContext.Web.Lists.GetByTitle("Test");
            var camlQuery = new CamlQuery
            {
                ViewXml = @"<Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>Apptest</Value></Eq></Where></Query>"
            };

            var listItems = list.GetItems(camlQuery);
            clientContext.Load(listItems);
            clientContext.ExecuteQuery();

            foreach (var listItem in listItems)
            {
                Console.WriteLine($"{listItem["Title"]}");
                listItem["Title"] = "AppUpdateTest";
                listItem.Update();
                clientContext.ExecuteQuery();
            }

A: Please have a try to add 'View' around 'Query' like below:
{ ViewXml = "<View><Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>xxxxx</Value></Eq></Where></Query></View>"};

Reference docs:

*

*https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee534956(v%3Doffice.14)#retrieving-items-from-a-list


text:
Q: parent expand when child expand css - react I have a textarea that expand up from bottom.
I also want that the parent div will expand with him.
JS
const [value, setValue] = useState("");
const rows = value.split("\n").length;

<textarea type="text" className="chat-box" value={value} rows={rows}
  onChange={(e) => setValue(e.target.value)} style={{ height: "unset" }} />

CSS
.right-bottom{
    background-color: black;
    float: right;
    width: 33vw;
    height: 7vh;
    position: relative;
}
.chat-box{
    width: 70%;
    border-radius: 25px;
    border: solid 1px #b7b7b7;
    background-color: #eeeeee;
    margin-left: 2%;
    margin-bottom: 1%;
    padding-left: 3%;
    padding-right: 3%;
    padding-top: 2%;
    padding-bottom: 2%;
    margin-top:0.5%;
    resize: none;
    vertical-align: middle;
    overflow: hidden;
    position: absolute;
    bottom: 0;
    max-height: 13vh;
}

I want that the black parent div will expand also with the textarea:

A: I made this for u , somthing like this should be good.
HTML - CSS

.body{
  display:flex;
  flex-direction:column;
  width:200px;
  height:180px;
  margin:auto;
  background-color:red
}
.chat-area {
  flex:9
}
.text-area-holder{
  flex:1;
  background-color: black;
}
.chat-box{
  display: block;
  overflow: hidden;
  background-color: white;
  margin: 2px;
  padding: 0 5px;
  max-width: 80%;
  min-height: 25px;
  line-height: 25px;
}

REACT

const App =()=> {
  const expandHandler = (e) =>{
   const textarea = e.currentTarget
   textarea.style.height = calcHeight(textarea.value) + "px";
  }
  function calcHeight(value) {
    let numberOfLineBreaks = (value.match(/\n/g) || []).length;
    let newHeight = 20 + numberOfLineBreaks * 20;
    return newHeight;
  }
 return (

      <textarea onKeyUp={expandHandler} className="chat-box"  />

 )
}

ReactDOM.render(
  <App />,
  document.getElementById("react")
);
.body{
  display:flex;
  flex-direction:column;
  width:200px;
  height:180px;
  margin:auto;
  background-color:red
}
.chat-area {
  flex:9
}
.text-area-holder{
  flex:1;
  background-color: black;
}
.chat-box{
  display: block;
  overflow: hidden;
  background-color: white;
  margin: 2px;
  padding: 0 5px;
  max-width: 80%;
  height: 20px;
  line-height: 20px;
  resize:none;
}

Source idea : https://css-tricks.com/auto-growing-inputs-textareas/


text:
Q: How do I force a drop temp table command to fully drop the table? I'm working on a script, just experimenting and developing. A lot of what I do involves temp tables, where I will select ... into #SomeTable from ..., at least in the initial experimentation/early dev stage.
Then I'll look at the results, make some changes, and go again. But to make things a little easier on myself, I also have a drop table if exists #SomeTable, so I can just rerun the code. So far so good. But, if I add a column to the temp table and then try to access it, I get the error Invalid column name 'newColumn'. I can avoid the error by executing JUST the drop statement, and then executing the whole script, but I would rather not have to do that. As I understand it, there is some caching of temp tables that goes on, and I wonder if that's the culprit. In any case, is there any way to fix this?
Edit: Here is a short script demonstrating the problem. Run the script, then uncomment both comments and run it again:
drop table if exists #DemoTable
select column1 = '1'
      ,column2 = '2'
--      ,column3 = '3'
into #DemoTable

select column1
      ,column2
--      ,column3
from #DemoTable

A: In SSMS you can just add a GO statement to separate the code in 2 batches.
This way the drop is executed before the 2nd part of the script is checked for errors.
drop table if exists #DemoTable
GO

select column1 = '1'
      ,column2 = '2'
--      ,column3 = '3'
into #DemoTable

select column1
      ,column2
--      ,column3
from #DemoTable

A: I have tried to follow the steps mentioned in the question.
Please find the following query samples using Northwind Database.
Added a new column to the temp table and also updated it sucessfully.
-- Create the temporary table #temp_Employees from a physical table called 'Employee' in schema 'dbo' in database 'Northwind'
SELECT EmployeeID, FirstName, LastName , BirthDate
INTO #temp_Employees
FROM [Northwind].[dbo].[Employees]

-- SELECT data from temptable '[#temp_Employees]'
SELECT * FROM #temp_Employees;

-- Add a new column '[City]' to table '[#temp_Employees]'
ALTER TABLE #temp_Employees
    ADD [City] NVARCHAR(15)  NULL
GO

-- SELECT data from temptable '[#temp_Employees]'
SELECT * FROM #temp_Employees;

-- UPDATE the new column '[City]' in the table '[#temp_Employees]'
UPDATE T
SET  T.[City]=E.[City]
FROM #temp_Employees T INNER JOIN [Northwind].[dbo].[Employees] E ON T.EmployeeID=E.EmployeeID;

-- SELECT data from temptable '[#temp_Employees]'
SELECT * FROM #temp_Employees;

-- Drop the temptable if it already exists
IF OBJECT_ID('tempDB..#temp_Employees', 'U') IS NOT NULL
DROP TABLE #temp_Employees;
GO

-- SELECT data from temptable '[#temp_Employees]'
SELECT * FROM #temp_Employees;

Thank you.


text:
Q: Replacing values in dataframe to nan when greater than x? I'm trying to replace values in a column to NaN. I normally use
imputed_data_x = imputed_data_x.replace(0, np.nan)

But my problem is that my values are not exactly 0, some are 0.01111,etc.  How can I replace all values in a data frame that is less than 1?
I tried imputed_data_x = imputed_data_x.replace(>1, np.nan)
But it didn't work. I'm curious to see if I can use replace to do this or do I need a different command for conditions?

A: Use standard boolean indexing:
imputed_data_x[imputed_data_x < 1] = np.nan

A: DataFrame.replace is just for replacing fixed values. In your case you want to replace if the value is "close" to 0 which you can express as a predicate function. The API command to replace a value where the predicate returns false (keep the value where it is true) is
imputed_data_x = imputed_data_x.where(lambda x: x >= 1, np.nan)


text:
Q: How to set the Focus to a License Agreement Checkbox control using NSIS I wanted to set the by default Focus to the "License Agreement" checkbox in the License Agreement Page using NSIS. And then the taborder should work.
Please help me how to set the focus?
Below is my code snippet:
!include LogicLib.nsh

  !define MUI_TEXT_WELCOME_INFO_TITLE $(welcometitle)
  !define MUI_TEXT_WELCOME_INFO_TEXT $(welcometext)

  !insertmacro MUI_PAGE_WELCOME

  !define MUI_LICENSEPAGE_CHECKBOX ""
  !define MUI_INNERTEXT_LICENSE_BOTTOM ""
  !define MUI_INNERTEXT_LICENSE_TOP ""
  !define MUI_INNERTEXT_LICENSE_BOTTOM_CHECKBOX ""

  !define MUI_TEXT_LICENSE_TITLE $(licensetitle)
  !define MUI_TEXT_LICENSE_SUBTITLE $(licensesubtitle)
  !define MUI_LICENSEPAGE_CHECKBOX_TEXT $(licensecheckboxtext)

  !insertmacro MUI_PAGE_LICENSE "C:\Program Files (x86)\NSIS\Docs\Modern UI 2\license.txt"

 !define MUI_DIRECTORYPAGE_TEXT_TOP $(mydirtoptext)
 !define MUI_TEXT_DIRECTORY_TITLE $(mydirtitle)
 !define MUI_TEXT_DIRECTORY_SUBTITLE $(mydirsubtitle)

  !insertmacro MUI_PAGE_DIRECTORY

  !insertmacro MUI_PAGE_INSTFILES

  !define MUI_TEXT_FINISH_INFO_TITLE $(Finishpagetitle)
  !define MUI_TEXT_FINISH_INFO_TEXT $(Finishpagesubtitle)

  !define MUI_FINISHPAGE_RUN ""
  !define MUI_FINISHPAGE_RUN_TEXT $(FinishonlineReg)

  !insertmacro MUI_PAGE_FINISH

  !insertmacro MUI_UNPAGE_INSTFILES

 ;--------------------------------
  !insertmacro MUI_LANGUAGE "English"

; The stuff to install
Section "My TestApp (required)"
SectionEnd

A: The Windows UI guidelines says:

For keyboard navigation, tab order should flow in a logical order, generally from left to right, top to bottom.

but if you think you must force then you can do this:
!include WinMessages.nsh
!include MUI2.nsh

!insertmacro MUI_PAGE_WELCOME
!define MUI_LICENSEPAGE_CHECKBOX ""
!define MUI_PAGE_CUSTOMFUNCTION_SHOW myForceLicenseFocus
!insertmacro MUI_PAGE_LICENSE "${__FILE__}"
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_LANGUAGE English

Function myForceLicenseFocus
!if ${MUI_SYSVERSION} >= 2.0
    FindWindow $0 "BUTTON" "" $mui.LicensePage
!else
    FindWindow $0 "#32770" "" $hWndParent
    FindWindow $0 "BUTTON" "" $0
!endif
System::Call 'USER32::SetFocus(pr0)'
!define /ifndef WM_CHANGEUISTATE 0x127
System::Call 'USER32::PostMessage(pr0,i${WM_CHANGEUISTATE},p0x30002,p0)' ; This forces the checkbox to display the focus rectangle
System::Call 'USER32::SetWindowPos(pr0,p0,i,i,i,i,i0x13)' ; Change tab order
FunctionEnd


text:
Q: Does backbone do _.bindAll by default now? This tutorial suggests that we need to do _.bindAll to get the correct value of this in our functions. It seems that _.bindAll is no longer required with Backbone. The following code logs the same thing twice:
var TestView = Backbone.View.extend({
    initialize: function () { _.bindAll(this, 'func1'); },
    func1: function () { console.log(this); },
    func2: function () { console.log(this); }
});
var testView = new TestView();

testView.func1();
testView.func2();

Am I correct in assuming that bindAll is no longer required, or am I just making a stupid mistake?

A: It is still necessary when the method is called out of context of the Class. Since you'recalling it in context, it isn't a mistake that you haven't needed it.
As mentioned in the underscore documentation for _.bindAll (http://documentcloud.github.com/underscore/#bindAll), it's "very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this." You would also use it for methods where you need to create a callback.
To see how there are differences for callbacks, look at this fiddle. http://jsfiddle.net/joshvermaire/YQdZu/


text:
Q: Ubuntu 16.04 unexplained swap usage I fail to understand why my swap is getting full on my Ubuntu 16.04 although I have plenty of available memory:

When looking at what processes are actually using swap :
************************************
Swap's process in count 1
systemd : 1 : VmSwap:        520 kB
otrs.Daemon.pl : 21002 : VmSwap:        3324 kB
systemd-journal : 2326 : VmSwap:        2356 kB
lvmetad : 2353 : VmSwap:           8 kB
systemd-udevd : 2358 : VmSwap:      3052 kB
/usr/sbin/apach : 25162 : VmSwap:        176 kB
/usr/sbin/apach : 28879 : VmSwap:        176 kB
bash : 30064 : VmSwap:      1460 kB
/usr/sbin/apach : 34334 : VmSwap:        180 kB
otrs.Daemon.pl : 36841 : VmSwap:        3708 kB
otrs.Daemon.pl : 36847 : VmSwap:        2976 kB
/usr/sbin/apach : 39489 : VmSwap:        176 kB
/usr/sbin/apach : 39491 : VmSwap:        176 kB
/usr/sbin/apach : 39493 : VmSwap:        176 kB
/usr/sbin/apach : 39494 : VmSwap:        176 kB
/opt/otrs/bin/c : 39496 : VmSwap:        176 kB
/usr/sbin/apach : 39497 : VmSwap:        176 kB
/usr/sbin/apach : 39498 : VmSwap:        176 kB
otrs.Daemon.pl : 43266 : VmSwap:        4320 kB
sshd : 43477 : VmSwap:        12 kB
sshd : 43555 : VmSwap:        72 kB
bash : 43556 : VmSwap:      1328 kB
bash : 43577 : VmSwap:       212 kB
ldapsearch : 43623 : VmSwap:         672 kB
ldapsearch : 43625 : VmSwap:         648 kB
ldapsearch : 43741 : VmSwap:         636 kB
sshd : 44183 : VmSwap:        12 kB
sshd : 44257 : VmSwap:        48 kB
bash : 44258 : VmSwap:      1044 kB
otrs.Daemon.pl : 44373 : VmSwap:        5912 kB
otrs.Daemon.pl : 45169 : VmSwap:        4344 kB
lxcfs : 4987 : VmSwap:      2208 kB
vmtoolsd : 4991 : VmSwap:      27168 kB
cron : 5044 : VmSwap:        136 kB
snapd : 5053 : VmSwap:      4728 kB
systemd-logind : 5055 : VmSwap:       48 kB
accounts-daemon : 5057 : VmSwap:          52 kB
dbus-daemon : 5059 : VmSwap:           4 kB
rsyslogd : 5082 : VmSwap:         44 kB
otrs.Daemon.pl : 50961 : VmSwap:        4348 kB
sshd : 5141 : VmSwap:        588 kB
polkitd : 5149 : VmSwap:           4 kB
mysqld : 5153 : VmSwap:   675748 kB
mdadm : 5162 : VmSwap:         4 kB
master : 5459 : VmSwap:      360 kB
qmgr : 5462 : VmSwap:         68 kB
otrs.Daemon.pl : 57161 : VmSwap:        4324 kB
systemd : 57265 : VmSwap:        896 kB
(sd-pam) : 57274 : VmSwap:       572 kB
otrs.Daemon.pl : 57937 : VmSwap:       56068 kB
/usr/sbin/apach : 8414 : VmSwap:         176 kB
************************************
Swap's process in count 2
systemd : 1 : VmSwap:        520 kB
otrs.Daemon.pl : 21002 : VmSwap:        3324 kB
systemd-journal : 2326 : VmSwap:        2356 kB
lvmetad : 2353 : VmSwap:           8 kB
systemd-udevd : 2358 : VmSwap:      3052 kB
/usr/sbin/apach : 25162 : VmSwap:        176 kB
/usr/sbin/apach : 28879 : VmSwap:        176 kB
bash : 30064 : VmSwap:      1460 kB
/usr/sbin/apach : 34334 : VmSwap:        180 kB
otrs.Daemon.pl : 36841 : VmSwap:        3708 kB
otrs.Daemon.pl : 36847 : VmSwap:        2976 kB
/usr/sbin/apach : 39489 : VmSwap:        176 kB
/usr/sbin/apach : 39491 : VmSwap:        176 kB
/usr/sbin/apach : 39493 : VmSwap:        176 kB
/usr/sbin/apach : 39494 : VmSwap:        176 kB
/usr/sbin/apach : 39496 : VmSwap:        176 kB
/usr/sbin/apach : 39497 : VmSwap:        176 kB
/usr/sbin/apach : 39498 : VmSwap:        176 kB
otrs.Daemon.pl : 43266 : VmSwap:        4320 kB
sshd : 43477 : VmSwap:        12 kB
sshd : 43555 : VmSwap:        72 kB
bash : 43556 : VmSwap:      1328 kB
bash : 43577 : VmSwap:       212 kB
ldapsearch : 43623 : VmSwap:         672 kB
ldapsearch : 43625 : VmSwap:         648 kB
ldapsearch : 43741 : VmSwap:         636 kB
sshd : 44183 : VmSwap:        12 kB
sshd : 44257 : VmSwap:        48 kB
bash : 44258 : VmSwap:      1044 kB
otrs.Daemon.pl : 44373 : VmSwap:        5912 kB
otrs.Daemon.pl : 45169 : VmSwap:        4344 kB
lxcfs : 4987 : VmSwap:      2208 kB
vmtoolsd : 4991 : VmSwap:      27168 kB
cron : 5044 : VmSwap:        136 kB
snapd : 5053 : VmSwap:      4728 kB
systemd-logind : 5055 : VmSwap:       48 kB
accounts-daemon : 5057 : VmSwap:          52 kB
dbus-daemon : 5059 : VmSwap:           4 kB
rsyslogd : 5082 : VmSwap:         44 kB
otrs.Daemon.pl : 50961 : VmSwap:        4348 kB
sshd : 5141 : VmSwap:        588 kB
polkitd : 5149 : VmSwap:           4 kB
mysqld : 5153 : VmSwap:   675748 kB
mdadm : 5162 : VmSwap:         4 kB
master : 5459 : VmSwap:      360 kB
qmgr : 5462 : VmSwap:         68 kB
otrs.Daemon.pl : 57161 : VmSwap:        4324 kB
systemd : 57265 : VmSwap:        896 kB
(sd-pam) : 57274 : VmSwap:       572 kB
otrs.Daemon.pl : 57937 : VmSwap:       56068 kB
/usr/sbin/apach : 8414 : VmSwap:         176 kB
************************************
Swap's process in count 3
systemd : 1 : VmSwap:        520 kB
otrs.Daemon.pl : 21002 : VmSwap:        3324 kB
systemd-journal : 2326 : VmSwap:        2356 kB
lvmetad : 2353 : VmSwap:           8 kB
systemd-udevd : 2358 : VmSwap:      3052 kB
/usr/sbin/apach : 25162 : VmSwap:        176 kB
/usr/sbin/apach : 28879 : VmSwap:        176 kB
bash : 30064 : VmSwap:      1460 kB
/usr/sbin/apach : 34334 : VmSwap:        180 kB
/usr/sbin/apach : 39489 : VmSwap:        176 kB
/usr/sbin/apach : 39491 : VmSwap:        176 kB
/usr/sbin/apach : 39493 : VmSwap:        176 kB
/usr/sbin/apach : 39494 : VmSwap:        176 kB
/usr/sbin/apach : 39496 : VmSwap:        176 kB
/usr/sbin/apach : 39497 : VmSwap:        176 kB
/usr/sbin/apach : 39498 : VmSwap:        176 kB
otrs.Daemon.pl : 43266 : VmSwap:        4320 kB
sshd : 43477 : VmSwap:        12 kB
sshd : 43555 : VmSwap:        72 kB
bash : 43556 : VmSwap:      1328 kB
bash : 43577 : VmSwap:       212 kB
ldapsearch : 43623 : VmSwap:         672 kB
ldapsearch : 43625 : VmSwap:         648 kB
ldapsearch : 43741 : VmSwap:         636 kB
sshd : 44183 : VmSwap:        12 kB
sshd : 44257 : VmSwap:        48 kB
bash : 44258 : VmSwap:      1044 kB
otrs.Daemon.pl : 44373 : VmSwap:        5912 kB
otrs.Daemon.pl : 45169 : VmSwap:        4344 kB
lxcfs : 4987 : VmSwap:      2208 kB
vmtoolsd : 4991 : VmSwap:      27168 kB
cron : 5044 : VmSwap:        136 kB
snapd : 5053 : VmSwap:      4728 kB
systemd-logind : 5055 : VmSwap:       48 kB
accounts-daemon : 5057 : VmSwap:          52 kB
dbus-daemon : 5059 : VmSwap:           4 kB
rsyslogd : 5082 : VmSwap:         44 kB
otrs.Daemon.pl : 50961 : VmSwap:        4348 kB
sshd : 5141 : VmSwap:        588 kB
polkitd : 5149 : VmSwap:           4 kB
mysqld : 5153 : VmSwap:   675748 kB
mdadm : 5162 : VmSwap:         4 kB
master : 5459 : VmSwap:      360 kB
qmgr : 5462 : VmSwap:         68 kB
otrs.Daemon.pl : 57161 : VmSwap:        4324 kB
systemd : 57265 : VmSwap:        896 kB
(sd-pam) : 57274 : VmSwap:       572 kB
otrs.Daemon.pl : 57937 : VmSwap:       56068 kB
/usr/sbin/apach : 8414 : VmSwap:         176 kB
************************************
Swap's process in count 4
systemd : 1 : VmSwap:        520 kB
otrs.Daemon.pl : 21002 : VmSwap:        3324 kB
systemd-journal : 2326 : VmSwap:        2356 kB
lvmetad : 2353 : VmSwap:           8 kB
systemd-udevd : 2358 : VmSwap:      3052 kB
/usr/sbin/apach : 25162 : VmSwap:        176 kB
/usr/sbin/apach : 28879 : VmSwap:        176 kB
bash : 30064 : VmSwap:      1460 kB
/usr/sbin/apach : 34334 : VmSwap:        180 kB
/usr/sbin/apach : 39489 : VmSwap:        176 kB
/usr/sbin/apach : 39491 : VmSwap:        176 kB
/usr/sbin/apach : 39493 : VmSwap:        176 kB
/usr/sbin/apach : 39494 : VmSwap:        176 kB
/usr/sbin/apach : 39496 : VmSwap:        176 kB
/usr/sbin/apach : 39497 : VmSwap:        176 kB
/usr/sbin/apach : 39498 : VmSwap:        176 kB
otrs.Daemon.pl : 43266 : VmSwap:        4320 kB
sshd : 43477 : VmSwap:        12 kB
sshd : 43555 : VmSwap:        72 kB
bash : 43556 : VmSwap:      1328 kB
bash : 43577 : VmSwap:       212 kB
ldapsearch : 43623 : VmSwap:         672 kB
ldapsearch : 43625 : VmSwap:         648 kB
ldapsearch : 43741 : VmSwap:         636 kB
sshd : 44183 : VmSwap:        12 kB
sshd : 44257 : VmSwap:        48 kB
bash : 44258 : VmSwap:      1044 kB
otrs.Daemon.pl : 44373 : VmSwap:        5912 kB
otrs.Daemon.pl : 45169 : VmSwap:        4344 kB
lxcfs : 4987 : VmSwap:      2208 kB
vmtoolsd : 4991 : VmSwap:      27168 kB
cron : 5044 : VmSwap:        136 kB
snapd : 5053 : VmSwap:      4728 kB
systemd-logind : 5055 : VmSwap:       48 kB
accounts-daemon : 5057 : VmSwap:          52 kB
dbus-daemon : 5059 : VmSwap:           4 kB
rsyslogd : 5082 : VmSwap:         44 kB
otrs.Daemon.pl : 50961 : VmSwap:        4348 kB
sshd : 5141 : VmSwap:        588 kB
polkitd : 5149 : VmSwap:           4 kB
mysqld : 5153 : VmSwap:   675748 kB
mdadm : 5162 : VmSwap:         4 kB
master : 5459 : VmSwap:      360 kB
qmgr : 5462 : VmSwap:         68 kB
otrs.Daemon.pl : 57161 : VmSwap:        4324 kB
systemd : 57265 : VmSwap:        896 kB
(sd-pam) : 57274 : VmSwap:       572 kB
otrs.Daemon.pl : 57937 : VmSwap:       56068 kB
/usr/sbin/apach : 8414 : VmSwap:         176 kB

Can anyone please explain my why it is happening? Can a process by itself swap even if there is plenty available memory?
EDIT:
Running vmstat shows 0 for both si an so(note that the output is truncated and I have run the command for a fair amount of time):

A: Yes, processes can be swapped even when there's memory available. This is controlled by the virtual memory swappiness value which, as you show, is set to 60 on your system (the default on many installations). The Red Hat documentation has a nice explanation (this is applicable to any Linux):

swappiness
A value from 0 to 100 which controls the degree to which the system
  favors anonymous memory or the page cache. A high value improves
  file-system performance, while aggressively swapping less active
  processes out of physical memory. A low value avoids swapping
  processes out of memory, which usually decreases latency, at the cost
  of I/O performance. The default value is 60.
A low swappiness value is recommended for database workloads. For example, for Oracle databases, Red Hat recommends a swappiness value of 10.

If you want to set it to a lower value, 10 for example, edit /etc/sysctl.conf and add a line like this:
vm.swappiness=10

Note that for newer versions of systemd, you need to edit/create files in /etc/sysctl.d/ instead. As explained in the Arch Wiki:

Note: From version 207 and 21x, systemd only applies settings from /etc/sysctl.d/*.conf and /usr/lib/sysctl.d/*.conf. If you had customized /etc/sysctl.conf, you need to rename it as /etc/sysctl.d/99-sysctl.conf. If you had e.g. /etc/sysctl.d/foo, you need to rename it to /etc/sysctl.d/foo.conf.

However, bear in mind that swapping is not necessarily a problem. It all depends on what your machine is doing. There is a nice and detailed answer addressing this issue on Ask Ubuntu, which I suggest you read. Basically, unless your machine feels sluggish, let it be.
Further reading:

*

*Ubuntu SwapFaq


text:
Q: gearman is returning old worker results I have a PHP gearman client and worker. I am testing my worker with very minimal output to ensure all is working as intended. Strangely, I am getting old results from previous workers and I can't figure out why. It seems that they cycle through in order of creation so it's as if they still exist somewhere, somehow.
I have killed all gearman processes using killall gearmand and then verified no connections are running by netstat -plnt in terminal. I've even restarted the whole box but nothing is killing off these old workers it seems.
As a side note, I'm using Supervisord to load the worker via terminal and killing that process by removing the socket (unlink /tmp/supervisor.sock).
Anyone have a hint? I don't know where else to look.


text:
Q: Should statically-declared character arrays with a specified size be initialized with a literal in C? For example,
gcc compiles this ok...
char s[7] = "abc";

But it gives the error "incompatible types in assignment" with...
char s[7];
s = "abc";

What is the difference?

A: The first one is an initialization; it means "declare an array of 7 char on the stack, and fill the first 3 elements with 'a', 'b', 'c', and the remaining elements with '\0'".
In the second one, you're not initializing the array to anything.  You're then trying to assign to the array, which is never valid.  Something like this would "work":
const char *s;
s = "abc";

But the meaning would be slightly different (s is now a pointer, not an array).  In most situations, the difference is minimal.  But there are several important caveats, for instance you cannot modify the contents.  Also, sizeof(s) would given you the size of a pointer, whereas in your original code, it would have given you 7 (the size of the array).
Recommended reading is this: http://c-faq.com/charstring/index.html.


text:
Q: Distance Formula showing "Resource leak: 'scan' is never closed" import java.util.Scanner;
//distance = square root of [(x2-x1)squared + (y2-y1)squared + (z2-z1)squared]

public class FirstCode
{
    static double distance(double x1, double y1, double z1, double x2, double y2, double z2)
    {
        return Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) + (z2-z1)*(z2-z1));
    }

    public static void main(String[] args)
    {
        double x2, x1, y2, y1, z2, z1;
        double distance;

        Scanner scan = new Scanner (System.in);

        System.out.println("Enter the x coordinate for point 1: ");
        x1 = scan.nextDouble();

        System.out.println("Enter the y coordinate for point 1: ");
        y1 = scan.nextDouble();

        System.out.println("Enter the x coordinate for point 2: ");
        x2 = scan.nextDouble();

        System.out.println("Enter the y coordinate for point 2: ");
        y2 = scan.nextDouble();

        System.out.println("Enter the z coordinate for point 3: ");
        z1 = scan.nextDouble();

        System.out.println("Enter the z coordinate for point 3: ");
        z2 = scan.nextDouble();
        distance = distance(x1,y1,x2,y2,z1,z2);
        System.out.println("The distance between the two points is " + distance + " .");
    }
}

A: Just close the Scanner at the end.
scan.close();


text:
Q: cx_freeze: ModuleNotFoundError and program stopped working I have a console mode program that I would like to distribute with cx_Freeze. I have just downloaded python 3.6.3 (both amd64 and win32 version) on a newly installed win 10 machine. I have installed cx_Freeze 5.1 from wheels (not from pypi). Then I have built both amd64 and win32 versions of the program. If I try to execute that exe file on the same machine where I have built it, I get this error:
Fatal Python error: Py_Initialize: unable to load the file system codec
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\encodings\__init__.py", line 31, in <module>
ModuleNotFoundError: No module named 'codecs'

I have the same error on both architectures. The setup file looks like this:
#!/usr/bin/env python3
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {
    "packages": [
        "os", "io", "copy", "struct", "hashlib", "random",
        "urllib", "pycurl", "json", "multiprocessing",
        "cryptography",
        "tornado", "watchdog", "pathtools"
    ],
    "includes": [
        "cryptography", "urllib.parse",
    ],
    "include_files": ["tmp", "server.ini", "client.ini"],
    "excludes": ["tkinter"],
}

setup(
    name="BlindBackup",
    version="1.0",
    description="BlindBackup",
    options={"build_exe": build_exe_options},
    executables=[
        Executable("backup.py", base=None),
        Executable("bsync.py", base=None),
        Executable("server.py", base=None),
    ]
)

In other words, I have specified the "codecs" package explicitly.
What is wrong?
UPDATE There is a file called library.zip in the distribution dir. It contains codecs.pyc but the exe file does not see it. If I extract all files from that zip, then I get a different error message:
C:\Python\Projects\blindbackup\build\exe.win-amd64-3.6>backup.exe
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 14, in run
    module.run()
  File "C:\Program Files\Python36\lib\site-packages\cx_Freeze\initscripts\Console.py", line 22, in run
    importer = zipimport.zipimporter(os.path.dirname(os.__file__))
zipimport.ZipImportError: not a Zip file

I guess that the problem is with the code that tries to import modules from the library.zip file? But not sure how to fix it.

A: The solution was this:

*

*install cx_freeze 6, because version 5 does not support python 3.6 (apparently)

*install pywin32 (although it was not required for my program)

*add all missing pyd files to "includes" and all missing packages to "packages" section it the setup script.


text:
Q: Finding a word specified in the command line from a file I'm trying to search a word specified in the command line from a file. However, when it is being run, it displays nothing. What could the problem be? Here is a part of my code. Thank you for helping me!

class ClientHandler extends Thread {
        private Socket client;
        private Scanner input;
        private PrintWriter output;
        private ArrayList<String> quotes;
        public ClientHandler3(Socket socket, String file) {
            client = socket;
            try {
                BufferedReader buffer = new BufferedReader(new FileReader(file));
                BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                String line = reader.readLine();
                try {
                    int ctr = 0;
                    quotes = new ArrayList<String>();
                    while(line != null){
                        quotes.add(ctr, line);

                        ctr++;
                        line = buffer.readLine();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                input = new Scanner(client.getInputStream());
                output = new PrintWriter(client.getOutputStream(), true);
            }
            catch(IOException e) {
                e.printStackTrace();
            }
        }

        public void run(String[] args) {
            String target;
            String message = "";
                target= args[3];
                for(int i = 0; i<quotes.size(); i++){
                    if(quotes.get(i).toUpperCase().contains(target.toUpperCase())){
                        output.println(quotes.get(i));
                    }
                }
                output.println("|");
            try {
                if (client != null) {
                    System.out.println("Closing down connection...");
                    client.close();
                }
            }
            catch(IOException e) {
                System.out.println("Unable to disconnect!");
            }
        }
    }

A: Your client reads args[1] (the host), args[2] (the port), but not args[3], the word to be searched.
Your code is also hard to read, because it doesn't respect the standard naming conventions. Classes start with an uppercase letter, whereas methods start with a lowercase letter. Your code does the inverse.


text:
Q: How to select fields according to input array in eloquent - laravel 9 $arr = array('field1', 'field2', 'field3');
From User Inputs I get array containing Field names.
I have to fetch data from multiple table joins so, The goal is to select respective fields from tables according to table input from array.
    $update_co_column = Co_Total_Ia::
                      ->select(current($arr), next($arr), next($arr))
                     //->join('All Joins here')
                       ->where("user_key", "=", session()->get("user_id"))
                       ->where("student_details.deleted_at", "=", null);

I tried using PHP array methods, curret(arr) and next(arr). It is working, but just as an temporary solution.
Problems in current solution -

*

*Don't know exact how many fields to fetch

*Need to fetch extra useless field all times.

A: You can do it like this:
$fields = ['field1', 'field2', 'field3'];

Model::select($fields)->get();

results:
SELECT
  `field1`,
  `field2`,
  `field3`
FROM
  `model`


text:
Q: How can a DLL have zero exports? I recently ran across a DLL installed on my system that Dependancy Walker (and every other utility I tried) says has zero exports by name or ordinal, yet the file is approximately 4mb in size. I thought the sole purpose of a DLL was to export functions for use by other code so what would be the purpose of a dll with no visible exports?

A: One way to think of a DLL is as a container for functions. Exporting a function from a DLL makes those functions visible to callers outside of the DLL. While exporting functions from a DLL is perhaps the most common way to provide access to them, many platforms provide other ways to access functions which have not been exported such as reflection in the .NET Framework and Java and (I think) LoadLibtary / GetProcAddress in Win32
Reasons for doing this are varied, often it is because it is beneficial to the developer to have functions in a library but undesirable for those functions to be called from external applications

A: Resource-only DLL, maybe? Those are used quite often for localization purposes, for example.
EDIT: it's also possible to have a DLL with code that does something in DllMain() to somehow make its functionality available. The DLL can register itself with some global dispatcher, for example, or create named kernel objects...


text:
Q: how to run a compiled CPP file with geany I have recently compiled a .CPP file with Geany. The result file is a .o file. How can I run this .o program?

A: You usually can't run a .o (object code) file directly: it lacks the necessary library linkage.
Instead of Compile, you need to Build (Geany shortcut F9 rather than F8). This will produce an executable file with default name the same as your CPP file but without the .cpp extension.
You should then be able to run it within Geany's shell using Execute from the Geany Build menu, or shortcut F5


text:
Q: Gnome Mail Icon not showing up on system tray I recently wiped my drive and re-installed 12.04 then upgraded back to 12.10. My mail icon that is supposed to be there is not. What do I do?

A: Several solutions from this topic might help you solve your problem: How do I access and enable more icons to be in the system tray?


text:
Q: Import xlsx file into html page via javascript I want to read the data of a specific xlsx file into javascript to show them on a .html page.
For that i downloaded sheetjs.  A .xlsx parser.
But now I realized that you kinda must choose a file in the html site to read it. But I only want to use one file the whole time. Also the html site will only run local. So is there any way to get going with setting up a absolute path in the js to the file. So something like
file= "C:\test.xlsx"
Code example from the documemtary:
function handleFile(e) {
  var files = e.target.files;
  var i,f;
  for (i = 0, f = files[i]; i != files.length; ++i) {
    var reader = new FileReader();
    var name = f.name;
    reader.onload = function(e) {
      var data = e.target.result;

      var workbook = XLSX.read(data, {type: 'binary'});

      /* DO SOMETHING WITH workbook HERE */
    };
    reader.readAsBinaryString(f);
  }
}
input_dom_element.addEventListener('change', handleFile, false);


text:
Q: how to fire mouseleave when the mouse leaves 2 divs using jquery i have 2 divs next to each other i want mouseleave to fire when the mouse leaves the 2 divs not when it leaves one of them.
how can i do that using jquery?
Cheers

A: You could surround the two divs with another div and catch the mouseleave on that.


text:
Q: Using rand( ) to generate a random sequence of integers in C I am trying to implement a function int choose_N(void) that generates and returns a random list of integers N (up to four integers). I am not sure if I am using rand( ) in the correct way, but this is what I have so far:
int choose_N(void)
{
  int x, integer[4];
  srand ((int) time(NULL));
  for (x=0; x<4; x++)
   integer[x]=rand();
  return integer;
}

Would looping it like this work? Is time initialized in the correct way?

A: Two problems: most importantly, the array integer is local, and will go away when you return. If you want to return an array of things in C, you have to make the caller pass it in (see below).  Secondly, srand() should only be called once per program, so it doesn't belong inside a function like this--it should be in main or some similar initialization function, otherwise multiple calls to this function will be correlated (at worst, they might even be identical).  So here's a better approach:
void choose_n(int *out, int count) {
    for (int i = 0; i < count; i += 1) {
        out[i] = rand();
    }
}

int main(int argc, char *argv[]) {
    int results[4];

    srand(time(NULL));
    choose_n(results, 4);
}

A: Your loop is correct but your return statement will not work.  The array integer is local to the function and will not be available outside.  In either case, your function is supposed to return int and not an array.
And if you want to limit the random number to a range, you are better off using the mod operator such as rand() % range.

A: You can't return a pointer to a local variable from a function.
See this post for the reason why? Can a local variable's memory be accessed outside its scope?
You have to allocate the array on heap.
Change it to:
int choose_N(void)
{
  int x;
  int *integer = (int*)malloc(sizeof(int)*4);
  srand ((int) time(NULL));
  for (x=0; x<4; x++)
   integer[x]=rand();
  return integer;
}

Don't forget to free() the memory when you are done.
In case you are wondering about malloc & free, you can read here:http://www.codingunit.com/c-tutorial-the-functions-malloc-and-free

A: You could define your choose_N() like this
void choose_N(int integer[4])
{
    int x;
    srand ((int) time(NULL));
    for (x=0; x<4; x++)
        integer[x]=rand();
}

and use it likes this
int integer[4];
choose_N(integer);

A: About the random part:
If you really want to feel the randomness of c rand() seeded by time(0), you should run rand() like 3 times before you use it for generating actual numbers. To justify that, try running this code few times one after another while printing the numbers. You will notice that first one will be almost the same. My out:
1023384829 832292180 1773676349 957893636
1023401636 1114767429 1248842775 1942837294
1023418443 1397242678 724009201 780297305

So your srand should look like this:
  srand ((int) time(NULL));
  rand(); rand(); rand();