text:
Q: recusrive chained axios calls with axios i am reading lines from XML document and sending them to the api with axios. i want recursively to send line by line and chain this requests (send second line after getting success from first line).
i am using Redux, Redux-saga and axios in my React project.
i created recursive function in my component and sendStatus field at reducer. This sendStatus has 3 fields (success,failed,sending)

*

*sending - i call function again,

*success - i am sending new line and increment index,

*failed or array.length > index i stop the function.
but it sends all lines togather and i get all success payloads at the same time

i want to create recursive sending in my saga. But dont know how to do.
here is my functions at my component kargo.tsx
    sendedIndex = 0
    const handleFileUpload = () => {
    sendedIndex = 0;
    sendGood(goods[sendedIndex]);
    sendedIndex++;
    setAlert({ ...alert, showUploadButton: false });
    recursiveSending();
  };

  const recursiveSending = () => {
    const { failed, sending, success } = kargo.sendingStatus;
    if (failed) {
      setAlert({ ...alert, sendingError: lang.errorDuringsending });
    } else if (goods.length - 1 < sendedIndex) {
      toast.success(lang.sendedSuccesfull);
    } else if (sending) {
      recursiveSending();
    } else if (success) {
      sendGood(goods[sendedIndex]);
      sendedIndex++;
      recursiveSending();
    }
  };

here is my reducer.ts
const initialState: IKargoState = {
  sendingStatus: {
    failed: false,
    success: false,
    sending: false,
  },
  loading: false,
};

export default handleActions(
  {
    [sendGoodAsync.started]: (state, action) => ({
      ...state,
      sendingStatus: {
        failed: false,
        success: false,
        sending: true,
      },
      loading: true,
    }),
    [sendGoodAsync.failed]: (state, action) => ({
      ...state,
      sendingStatus: {
        failed: true,
        success: false,
        sending: false,
      },
      loading: false,
    }),
    [sendGoodAsync.success]: (state, action) => ({
      ...state,
      sendingStatus: {
        failed: false,
        success: true,
        sending: false,
      },
      loading: false,
    }),
  },
  initialState
);

here is my saga.ts
export function* KargoSaga() {
  yield takeEvery(KargoActions.sendGood, bindAsyncActions(KargoActions.sendGoodAsync)(kargoApi.sendGood));
}

and my kargo.api.ts
export default class KargoApi {
  static sendGood = (data: any) => {
    return axios.post(`/cargo`, data).then(({ data }) => data);
  };
}


text:
Q: Inserting into a oracle table using Where condition I am new to write queries in oracle. I want to insert a row in a table using where condition of another table
For example : I have two tables: Table1 and Table2
insert into table1 (col1, col2, col3) values ('1', '2', '3')
            where exists (select * from table2 where col2 = '2')

Can i have a query like this? is there any syntax error, please correct me. Basically,, i want to insert a row into table one, if the table2 has a row with col2 = '2'.
Any help would be appreciated! Thanks in advance!!

A: Suggested way causes syntax error.
It's suitable to use in this way (for such an aim) :
insert into table1 (col2)
select col2 from table2 where col2 = '2';

or
insert into table1 (col1,col2,col3)
select col1,col2,col3 from table2 where col2 = '2';

or maybe(depending on the second table's data)
insert into table1 (col1,col2,col3)
select col1,col2,col3 from table2 where (col1,col2,col3) in ('1','2','3');

provided both table has at least these columns(col1,col2,col3).

A: It is unclear if you only need to compare if the col2 of TABLE2 should be '2', or you expect the col2 of TABLE2 to be same as the value of COL2 used for insertion.
If it is only about '2', you could use this.
INSERT INTO TABLE2(col1,col2,col3)  select '1', '2', '3'  FROM DUAL
WHERE EXISTS ( select 1 FROM TABLE2 WHERE col2 = '2' );

If it is about col2 in general, then you could use:
INSERT INTO TABLE1(col1,col2,col3)
                               with d(col1,col2,col3) AS
                                             ( select '1' , '2' , '5' FROM DUAL )
SELECT col1,col2,col3 FROM d
         WHERE EXISTS ( select 1 FROM TABLE2 t WHERE t.col2 = d.col2 );

DEMO

redpajama_set_name: RedPajamaStackExchange


text:
Q: Must declare the scalar variable error for stored procedure in nopcommerce 4.3 I want to search GTIN option in admin product list. So, for that I am providing GTIN value in ProductLoadAllPaged store procedure. Now, when I search GTIN value from product list at that time throw datatable error and from console application get message that System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "@GTIN"..
Here is store procedure added code,
ALTER PROCEDURE [dbo].[ProductLoadAllPaged]
(
    @GTIN nvarchar(50) = null--AWAZ
)
AS
BEGIN
    ...........

    --SKU (exact match)
    IF @SearchSku = 1
    BEGIN
        SET @sql = @sql + 'OR p.[Sku] = @OriginalKeywords '
    END

    --NEW ADDED CODE FOR GTIN SEARCH
    IF @GTIN is not null
    BEGIN
        SET @sql = @sql + 'AND p.Gtin = @GTIN'
    END

    --localized product name
    SET @sql = @sql + '
    UNION
    SELECT lp.EntityId
    FROM LocalizedProperty lp with (NOLOCK)
    WHERE
        lp.LocaleKeyGroup = N''Product''
        AND lp.LanguageId = ' + ISNULL(CAST(@LanguageId AS nvarchar(max)), '0') + '
        AND ( (lp.LocaleKey = N''Name'''

    ..........
END

A: In the stored procedure change this line of code:
EXEC sp_executesql @sql, N'@Keywords nvarchar(4000), @OriginalKeywords nvarchar(4000)', @Keywords, @OriginalKeywords

To this:
EXEC sp_executesql @sql, N'@Keywords nvarchar(4000), @OriginalKeywords nvarchar(4000), @GTIN nvarchar(50)', @Keywords, @OriginalKeywords, @GTIN

This will add your new parameter when executing the dynamic SQL query.


text:
Q: Reading class attribute from tr tag I have an HTML document with many
 tags in it. There is one specific table that I want to go through and make an array of id tags within each
. Each of the
's have the same class value. For example:
...

...

...

...

Within the HTMLDocument, I made an HTMLElementCollection using:
document.GetElementsByTagName("tr")

I would think the logical thing to do from there is to go through each row and use something along the lines of
row.GetAttribute("class")

or
row.GetAttribute("id")

however both of those return a blank string. I can see that the outterHTML attribute of the elements says "
...
Any suggestions other than having to dissect the string of the outterHTML attribute?

A: I finally figured out what the problem was. When running row.GetAttribute(), I had the wrong property in there. While the HTML looked like this:

The C# code should look like this:
row.GetAttribute("className");

And it turns out that the reason only half of the
 tags showed up was because the page does a full load unpopulated, then refreshes itself fully populated with the rest of the
 tags in place.


text:
Q: Configurar parametro sZeroRecord do Datatable mas sem paginação Estou utilizando a função DataTable:
"oLanguage": {
                "sZeroRecords": "Não há registros para mostrar"
            }
        });

Mas na minha tela aparece os botões de exportar, paginação sem eu ter configurado essas opções...
No caso eu gostaria só de utilizar sZeroRecords sem as outras opções, eu consigo fazer isso?

A:
Paging Description
DataTables can split the rows in tables into individual pages, which
is an efficient method of showing a large number of records in a small
space. The end user is provided with controls to request the display
of different data as the navigate through the data. This feature is
enabled by default, but if you wish to disable it, you may do so with
this parameter.

Conforme a documentação, se você não setar nada, o padrao é true, ou seja, terá paginação(como descrito acima) e outras features também por padrao. Para desativar algumas features, veja um exemplo:
$('#example').DataTable( {
    paging: false,    // desativa paginação
    ordering: false, //desativa ordenação no cabeçalho
    searching: false // desativa a pesquisa no topo
} );

Veja um exemplo na propria documentação aqui
Referencias:
https://www.datatables.net/manual/options
https://datatables.net/reference/option


text:
Q: Angular node_modules changes in .js files does not recompile...? I was trying to implement a try/catch clause inside Angular @swimlane line-chart node_modules folder, meaning I changed their sourcecode a bit and was trying to restart my program. But somehow, the changes are not reflected on the webpage / program. I did this on a .js file, are there any hidden .ts files that get compiled to .js by default inside node_modules modules? Because I didn't see any... or do I have to recompile or do a npm install after I change some code inside node_modules folder?
Edit: I get this.activeEntries.slice() error...
I changed the code inside ..\node_modules\@swimlane\ngx-charts\release\line-chart\line-chart.component.js and implemented a simple try-catch around the function:
LineChartComponent.prototype.deactivateAll = function () {
        try{
        this.activeEntries = this.activeEntries.slice();
        }
        catch(error) {};
        for (var _i = 0, _a = this.activeEntries; _i < _a.length; _i++) {
            var entry = _a[_i];
            this.deactivate.emit({ value: entry, entries: [] });
        }
        this.activeEntries = [];
    };

but it has no effect... or is my try...catch wrong somehow?


text:
Q: Using reflect to detect nil value I'm using the reflect package to create a re-usable JSON parser that maps JSON data to a particular struct at run-time.
I want it to detect when a particular required field is missing.
I create an variable "parsedInput" using:
parsedInput := reflect.New(reflect.TypeOf(exampleInputObject).Elem())

I've then used the JSON libraries to parse the data into that variable.  I now want to traverse through the values to spot anything missing:
    for i := 0; i < parsedInput.Elem().NumField(); i++ {
            logger.Info("Field name was: " + field.Name)
            fieldType := fmt.Sprintf("'%v'", field.Type.Kind().String())
            logger.Info("Field type was: " + fieldType)
            interfaceValue := fmt.Sprintf("'%v'", parsedInput.Elem().Field(i).Interface())
            logger.Info("Interface value was: " + interfaceValue)

            //Look to see if the field is a null pointer.  If so, this could be an issue
            if (field.Type.Kind().String() == "ptr") && (parsedInput.Elem().Field(i).Interface() == nil) {
        //Do null pointer stuff here
    }
}

For the field that's missing, I see the log output
Field name was: MissingFieldName
Field type was 'ptr'
Interface value was '<nil>'

My code is never dropping into the null pointer logic however - what am I doing wrong?

A: As per comment above - I managed to solve this using built-in functions in the Reflect package - specifically by testing for:
Reflect.ValueOf(parsedInput.Elem().Field(i).Interface()).IsNil()


text:
Q: Laravel chain With clause with multiple conditions I have a Notifications table that has the following content:
id  | user_id   | type      | table_id
1   | 1         | Receipt   | 201
2   | 1         | Receipt   | 391
3   | 2         | Reminder  | null
4   | 2         | Ticket    | 30

The column type can hold different values such as Receipt, Reminder or Ticket and the table_id column refers to the corresponding Table ID of the type selected. table_id can be null sometimes.
I'd like to know if there's a possibility to retrieve the data of Notifications table with all the chains already applied, like such:
[
    {
        id: 1,
        user_id: 1,
        type: Receipt,
        table_id: 201,
        receipt: { .... }
    },
    {
        id: 2,
        user_id: 1,
        type: Receipt,
        table_id: 201,
        receipt: { .... }
    },
    {
        id: 3,
        user_id: 2,
        type: Reminder,
        table_id: null
    },
    {
        id: 4,
        user_id: 2,
        type: Ticket,
        table_id: 30,
        ticket: { .... }
    },
]

I have the following Model:
class Notifications extends Model
{
    public function receipt()
    {
        return $this->hasOne('\App\Models\Receipts', 'id', 'table_id');
    }

    public function ticket()
    {
        return $this->hasOne('\App\Models\Tickets', 'id', 'table_id');
    }

    public function scopeWithReceipt($query)
    {
        return $query->with('receipt')->where('type', 'Receipt');
    }

    public function scopeWithTicket($query)
    {
        return $query->with('ticket')->where('type', 'Ticket');
    }
}

If I do something like:
\App\Models\Notifications::withReceipt()->get();

It returns only the rows with type = Receipt. If I add more "with chains" it doesn't return anything:
\App\Models\Notifications::withReceipt()->withTicket()->get();

Is it possible to accomplish what I want without looping the rows? I know I can do something like:
$notifications = \App\Models\Notifications::all();

foreach ($notifications as $notification)
{
    switch ($notification->type)
    {
        case 'Receipt':
            $notification->receipt = ..
            break;
        case 'Reminder':
            break;
        case 'Ticket':
            $notification->ticket = ..
            break;
    }
}


text:
Q: convert .avi video file to .mha For a research project I collected videos of the microcirculation in patients. For automatic analysis of these videos I need to convert the .avi files to a .mha file format.
I am not sure if this is even possible. But if anyone could help?
Thank you in advance.
I am not at home with these kinds of files. What I tried so far: Converting the .avi file to .png files and then using 3DSlicer software to convert the .png file to .mha. However would potentially create hundreds of separate .mha files for one .avi file.


text:
Q: ERROR 2003 on MYSQL 5.1 on Openshift Today, I have problem on my openshift account. Mysql on my openshift account gone rogue, i cant connect to MySql by php script and even from SSH.
Already try to restart the gear, but it's not working.When i try to SSH to the gear.And when i type MYSQL. It have this error:

ERROR 2003 (HY000): Can't connect to MySQL server

Can someone show me how to fix this issue ? thanks

A: My recommendation is to do the following from the command line:
1) rhc app-force-stop {your app name}
2) rhc app-start {your app name}
Seems like something is stuck and you need a "hard" restart


text:
Q: C++ relational operator == with strings I'm getting an error that I can't use the relational operator "==" to test for a string to string match. Is there a different operator needed because of the array (of strings)?
int searchArray(string name, string &firstNameArray); // declares the function

int main()
{
    string firstNameArray[7] = { "Jim", "Tuyet", "Ann", "Roberto", "Crystal", "Valla", "Mathilda" }; //declares and intializes the array

    string name = "";
    cout << "What's your name?";
    getline(cin, name);

    searchArray(name, firstNameArray[7]); // using the function

    return 0;
}

int searchArray(string name, string &firstNameArray) { //defining the function

    int position = 0; //declaring and intializing the return variable - positions 0 thru 6 for array elements and position 7 for not in array

    for (int i = 0; i < 7; i++) { //looping through the array

        if (firstNameArray[i] == name) //**error code "no operator "==" matches these operands
        {
            position == firstNameArray[i];
        }
        else
        {
            position == 7;
        }

    }

    return position;

}

A: Consider these Notes:

*

*No need for & in the function prototype as a pointer to the first element in the array will be passed

*You should assign the function to a variable to save the returned
value: ex: pos = searchArray(name, firstNameArray);

*No [] needed in the function call.

*You have to add output for the search result.

*Again no need for the reference in the array parameter, i.e. No &
needed.

*in position == firstNameArray[i]; you should use = not ==.

*You should initialize position with a value other than 0 to ARR_SIZE.

*There should not be else statement inside searchArray.

compare your code to this working code:
#include <iostream>
using namespace std;

int searchArray(string , string [], int);

int main()
{
    const int ARR_SIZE = 7;

    string firstNameArray[ARR_SIZE] = { "Jim", "Tuyet", "Ann", "Roberto",
                                 "Crystal", "Valla", "Mathilda" };
    string name = "";
    cout << "\n What's your name? ";
    getline(cin, name);

    int pos = searchArray(name, firstNameArray, ARR_SIZE);

    if (pos == -1)
        cout << "\n Not Found!";
    else
        cout << "\n Fount at position " << pos;

    cout << "\n\n\n";

    return 0;
}

int searchArray(string name, string fNameArray[],const int SIZE) {

    int position = -1;

    for (int i = 0; i < SIZE; i++)
        if (fNameArray[i] == name)
            position = i;

    return position;
}

A: Corrections/ Suggestions - more details on the comments:
    //const references
    //use of vector
    //use of vector size variable

    int searchArray(const string & name, const vector<string> & firstNameArray) {
            int position = -1; //declaring and intializing the return variable - positions 0 thru 6 for array elements and position 7 for not in array

            for (int i = 0; i < firstNameArray.size(); i++) { //looping through the array
                //== is for comparison
                if (firstNameArray[i] == name)
                {
                    position = i; //= is for assignment
                    break; // without break always returns not found
                }
            }
            return position;
        }

        int main(int argc,const char * argv[]) {

            vector<string> firstNameArray = { "Jim", "Tuyet", "Ann", "Roberto", "Crystal", "Valla", "Mathilda" }; //declares and intializes the array

            string name ;
            cout << "What's your name?";

            getline(cin, name);

            cout << "position: " << searchArray(name, firstNameArray) << endl;

            return 0;
        }

A: In searchArray(name, firstNameArray[7]);, you just pass one string, not a string array. And in int searchArray(string name, string &firstNameArray), the syntax of passing array by reference is not right.
I changed a few places, hope this will help
int searchArray(string name, string* firstNameArray); // declares the function

int main()
{
    string firstNameArray[7] = { "Jim", "Tuyet", "Ann", "Roberto", "Crystal", "Valla", "Mathilda" }; //declares and intializes the array

    string name = "";
    cout << "What's your name?";
    getline(cin, name);

    searchArray(name, firstNameArray); // right
    //searchArray(name, firstNameArray[7]);
    // this will pass a single string, not a string array, the index is out of boundary, the range is 0-6

    return 0;
}

int searchArray(string name, string* firstNameArray) { //pass a pointer
//or int searchArray(string name, string (&firstNameArray)[7])

    int position = 0; //declaring and intializing the return variable - positions 0 thru 6 for array elements and position 7 for not in array

    for (int i = 0; i < 7; i++) { //looping through the array

        if (firstNameArray[i] == name)
        {
            position = i; //not position == firstNameArray[i]; incompatible type, int and string.
        }
        else
        {
            position = 7;
        }

    }

    return position;

}

Reference
Passing an array by reference


text:
Q: TensorflowServing on a trained native Keras model with a preprocessing function for the input My final goal is to use the What-If-Tool on tensorboard. In order to do that, I need to serve my Keras model on TensorflowServing, and the data in a TFRecordFile. So the data has to be transformed into tf.Examples.
The tool is supposed to grab the network to run inference on the data.
however, the network cannot handle tf.Examples as an input. So the served model needs to have a preprocessing function.
According to the tensorflow documentation, one way is to create a tensorflow Estimator, and to use "serving_input_receiver_fn" to preprocess the data.
This would have been perfect except for the case that I can't make an already trained native Keras model into an Estimator. It seems that the only way it to create it from a tf.keras model (and not a native keras model like I have), and to train it directly with the estimator.
Another way would be to use the tf.saved_model.simple_save function, and then use TensorflowServing, but I did not find a way to preprocess the tf.Examples to make a correct input for the network.
Since this is not working, I have no clue on how to resolve this.
Edit: I tried to transform my native keras into a tf.keras model. My model is really big, so I build this function:
def create_tf_keras_model_from_native_keras(native_model):
    list_layers = []
    for i, layer in enumerate(native_model.layers):
        type_layer = str(layer).split('.')[2]
        second_type_layer = str(layer).split('.')[3].split(' ')[0]
        if type_layer == 'input_layer':
            new_layer = tf.keras.layers.InputLayer(**layer.get_config())
        elif type_layer == 'convolutional':
            new_layer = tf.keras.layers.Conv2D(**layer.get_config())
        elif type_layer == 'normalization':
            new_layer = tf.keras.layers.BatchNormalization(**layer.get_config())
        elif type_layer == 'core':
            if second_type_layer == 'Activation':
                new_layer = tf.keras.layers.Activation(**layer.get_config())
            elif second_type_layer == 'Dense':
                new_layer = tf.keras.layers.Dense(**layer.get_config())
            elif second_type_layer == 'Dropout':
                new_layer = tf.keras.layers.Dropout(**layer.get_config())
            elif second_type_layer == 'Lambda':
                config_lambda = layer.get_config()
                print(config_lambda)
                del config_lambda['function_type']
                del config_lambda['output_shape_type']
                new_layer = tf.keras.layers.Lambda(**config_lambda)
        elif type_layer == 'pooling':
            if second_type_layer == 'MaxPooling2D':
                new_layer = tf.keras.layers.MaxPooling2D(**layer.get_config())
            elif second_type_layer == 'AveragePooling2D':
                new_layer = tf.keras.layers.AveragePooling2D(**layer.get_config())
            elif second_type_layer == 'GlobalMaxPooling2D':
                new_layer = tf.keras.layers.GlobalMaxPooling2D(**layer.get_config())
        if new_layer == 'merge':
            new_layer = tf.keras.layers.Concatenate(**layer.get_config())
        list_layers.append(new_layer)
    model = tf.keras.Sequential(list_layers)
    return model

However, this is not working because of Lambda layer. In the config layer, the function is now written in the form of:
'function': ('4wIAAAAAAAAAAgAAAAMAAABTAAAAcxQAAAB8AGQBGQB8AGQC8ARQAFwBTACkDTukAAAAA6QEA\nAACpACkC2gZpbaBXNjYWxlcgMAAAByAwAAAPp/L2dwZnMvaGFpZmEtcDYvMDMvbXNpZXZl\nX2RldjMvdXNyL3BhdWxkYS9naXRfcmVwb0hJLUltYWdlQW5hbHl0aWNzL3Jlc291cmNlcy9y\ndW5fMTE3NC9jdXN0b21fcHJldHJhaW5lZF9JbmNlcHRpb25SZXNOZXRWMi5wedoIPGxhbWJkYT6d\nAAAA8wAAAAA=\n', None, None)

Hence, I gave up this method hoping something else would allow to pre-process the input of my serving model.

A: If you want to use Tensorflow Serving, in my opinion, it will be difficult to do it using Native Keras.
If you want to Prepare the Data ready for Training and Serving, you can perform the respective transformations using Tensorflow Transform.
But if you want to Prepare the Data only for Serving, The best way is the one mentioned by you, "It seems that the only way it to create it from a tf.keras model (and not a native keras model like I have), and to train it directly with the estimator."
And you rightly said that it can't be done using tf.saved_model.simple_save function.
Example Code for creating Keras Model is shown below and converting it to Estimator is shown below:
import tensorflow as tf
from tensorflow.python import keras
from tensorflow.python.keras import layers
from tensorflow.python.keras import models

def get_keras_model():
    inputs = layers.Input(shape=(INPUT_SHAPE,), name=INPUT_FEATURE)
    dense256 = layers.Dense(256, activation='relu')(inputs)
    dense32 = layers.Dense(32, activation='relu')(dense256)
    outputs = layers.Dense(NUM_CLASSES, activation='softmax')(dense32)
    model = models.Model(inputs, outputs)
    return model

Then convert the Keras Model to Estimator using the below code:
classifier = tf.keras.estimator.model_to_estimator(keras_model=model, model_dir=FLAGS.model_dir)

For more information, refer the link,
https://github.com/yu-iskw/tensorflow-serving-example/blob/master/python/train/mnist_keras_estimator.py


text:
Q: I Want to fetch total product those quantity is less than or equal to zero I have written a query (see image) which displays a result as shown in the image below.
Now, I want to show those product list whose total available quantity is less than or equal to zero.
I am calculating total available quantity using this formula -
(SUM(credit_quantity) - SUM(debit_quantity))

Please check the database table structure shown in image:

A: Try this query :-
SELECT * FROM nrk_product AS np LEFT JOIN
nrk_stock AS ns ON np.id = ns.product_id GROUP BY np.id
HAVING (SUM(ns.credit_quantity) - SUM(ns.debit_quantity)) <= 0


text:
Q: Use of to in the sentence- "to the unspeakable relief of the student ..." Why to is used here:

tuberculosis,bad tonsils,sleeping sickness, poor digestion,various forms of mental and nervous difficulty have been brought to light by the doctor during the past few months,to the unspeakable relief of the student and enlightenment of faculty.

A: In general, it's a prepositional phrase which conveys a sense of cause and effect. In your example, we can reword your sentence as:

There was unspeakable relief of the student and enlightenment of faculty after tuberculosis,bad tonsils,sleeping sickness, poor digestion,various forms of mental and nervous difficulty was brought to light by the doctor during the past few months.

In other words, the doctor's act or investigation made students feel a sigh of relief. However, I would like to know more about the context and who was suffering those maladies.
It terms of that to, it's common to use such phrases when talking about feeling. For instance,

To my surprise, he didn't bring my book.

This simply means that I got surprised when I found that he didn't bring the book.


text:
Q: How can one compare vertices in a triangle In this post Neighbor Polygons from List of Polygon Indices, in the accepted answer, for a given triangle consisting of three Vector3 points, they store its three edges as {min_vertex, mid_vertex}, {mid_vertex, max_vertex}, {min_vertex, max_vertex}, where min_vertex, mid_vertex and max_vertex are the  "sorted" triangle points (vertices).
But how does one compare vertices in a triangle structure? Do we compare the lengths (square root of sums squares of x, y and z value) of each vertex?
Vector3 here is a struct consisting of three floats x, y and z.

A: You don't use the coordinates at all. A triangle is a defined as sorted set of three vertices (which could be 2D, or 3D, or ND).
min_vertex is just the vertex given in first position of the triangle, and max_vertex is the last one.
Also, your set of edges should be {min_vertex, mid_vertex}, {mid_vertex, max_vertex}, {max_vertex, min_vertex}. It is important to keep the order given in the triangle when you build the list of edges.


text:
Q: In Kubernetes does a host (a worker node), a pod in the node and the container in the pod all have separate process namespace? In docker host and the containers do have separate process name-space. In case of Kubernetes the containers are wrapped inside a pod. Does that mean in Kubernetes the host (a worker node), the pod in the node and the container in the pod all have separate process namespace?

A: Pods don't have anything of their own, they are just a collection of containers. By default, all containers run in their own PID namespace (which is separate from the host), however you can set all the containers in a pod to share the same one. This is also used with Debug Containers.


text:
Q: Modify request query string before plugins I have an issue where a plugin allows some behavior I don't like. Basically, I want to grab and modify a request query string before the Ultimate Member plugin processes it. Basically if someone isn't a super admin, and the query parameter
URI?&..&..&um_action=action_to_take&..

is requested anywhere, I want it to force that query string to say edit, so Ultimate Member always responds like the request was this:
URI?&..&..&um_action=edit&..

Here's the idea, but I'm not sure what hooks/filters/what I'd need to do to trick Ultimate Member:
function called_before_ultimate_member () {
    // if not a super admin, don't let this query string
    // get parsed by Ultimate Member as anything but "edit"
    if (!is_super_admin())
    {
        if (isset($_GET['um_action'])) $_GET['um_action'] = "edit";
    }
}

Any ideas on how to achieve this? The plugin is huge, and I don't really have the time or patience to modify core files at this point.


text:
Q: Mixing class and function generics in Kotlin? I'm trying to create an interface that defines a single method. The type of the argument for that method must be a type parameter of the interface, because implementations of the interface will have unique implementations for this parameter. Fine so far, but the catch is that the parameter also has a type argument that is tied to the method. Can I have a parameter of a type defined as a class type argument, which also has its own type argument that's tied to the method?
Put another way:
I am trying to build an api client interface with two implementations. Each client makes api calls based on Request<T> objects that are passed into their rxecute functions (RxJava + execute, and yes, I am unduly proud of the name).
My issue is with how to define the rxecute method in the interface. Let me lay out some sample code (my actual code isn't using impl, don't worry).
interface Request<T> // T is return type of the request

class RequestImpl<T>: Request<T> { // impl }

interface ApiClient<R : Request<*>> {
  // R should somehow be of type Request<T>
  fun <T> rxecute(request: R): Single<T>
}

class ApiClientImpl : ApiClient<RequestImpl<????>> {
  override fun <T> rxecute(request: RequestImpl<T>): Single<T> = // impl
}

I would like to be able to use it like this:
val apiClient = ApiClientImpl()
apiClient.rxecute(RequestImpl<SomeClass>()).subscribe(someClassResult -> ...)

Is it possible to create an interface like this or do generics not work like that?

A: Unfortunately, Kotlin generics cannot be manipulated in that way; a type parameter R cannot be used as a generic type itself (R<T>), and its upper bound is fixed at the declaration site, and you can only use a type parameter R as a single upper bound (no way to add another one, where Q : R, Q : Request<T> doesn't work).
You can only parameterize concrete types, and one option that comes to my mind is recursive generics pattern (it is also used with Java). You can add another type parameter for the implementation type to Request, so that it becomes interface Request<R, T>. This requires you to add the types of the implementations to the inherited type declarations:
class RequestImpl<T>: Request<RequestImpl<*>, T> { /* impl */ }

Then modify ApiClient:
interface ApiClient<R : Request<R, *>> {
    fun <T> rxecute(request: Request<R, T>): Single<T>
}

An unwelcome side-effect that arises here is that you need to cast the request to use it as a RequestImpl: request as RequestImpl.
And transform ApiClientImpl as follows:
class ApiClientImpl : ApiClient<RequestImpl<*>> {
    override fun <T> rxecute(request: Request<RequestImpl<*>, T>): Single<T> = TODO()
}

This solution looks much more verbose than what you asked for, but recursive generics seem to be a common workaround for such cases, which require a stronger type system than what Java and Kotlin can offer.

(runnable demo of the code in the answer)


text:
Q: Take or Upload Photo with webView I'm trying to take or upload a photo in Kotlin using a website via webView, but I get the following error: ERROR Error: permission_denied at /images_total: Client doesn't have permission to access the desired data.
enter image description here
The permissions I'm putting on the Manifest file are:
<uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.BLUETOOTH" />
        <uses-feature android:name="android.hardware.camera"/>
        <uses-permission android:name="android.permission.CAMERA"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

In Activity Main I have the following:
class MainActivity : AppCompatActivity() {

        private lateinit var binding: ActivityMainBinding

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityMainBinding.inflate(layoutInflater)
            setContentView(binding.root)

            val url = "https://imagemeasurement.online/image/select"
            val webView = binding.mapWebview

            webView.loadUrl(url)
            webView.settings.javaScriptEnabled = true
            webView.settings.javaScriptCanOpenWindowsAutomatically = true
            webView.settings.setGeolocationEnabled(true)
            webView.settings.domStorageEnabled = true
    }
    }


text:
Q: The 32-bit OLE DB provider "Microsoft.ACE.OLEDB.12.0" cannot be loaded in-process on a 64-bit SQL Server I have the following code in a SQL Server database, recently we had migrated this database from a Server which is SQL Server 2008 R2 to another server which is SQL Server 2014.
IF EXISTS (SELECT 1 FROM sys.servers WHERE name = 'Excel_File_Src')
    EXEC sp_dropserver 'Excel_File_Src', 'droplogins'

EXEC sp_addlinkedserver 'Excel_File_Src',
        @srvproduct = 'ACE 12.0',
        @provider = 'Microsoft.ACE.OLEDB.12.0',
        @datasrc =  'E:\UCB_Data.xlsx' ,
        @provstr = 'Excel 8.0;'

EXEC sp_addlinkedsrvlogin 'Excel_File_Src', 'false'

EXEC SP_TABLES_EX 'Excel_File_Src'

New SQL Server version is:
Microsoft SQL Server 2014 - Microsoft Corporation Developer Edition (64-bit) on Windows

It is used to run perfectly on old server, but after moving it to new server we getting below error.

The 32-bit OLE DB provider "Microsoft.ACE.OLEDB.12.0" cannot be loaded in-process on a 64-bit SQL Server.

A: Firstly the message is telling you the office bits you have installed on the box are the 32bit version. You need the 64 bit version. Secondly, make sure you aren't running the "Developer" edition in production because you aren't allowed - see EULA.

A: You Could Download Both x64 and x86 and run these commands to install them without conflicting with one another:
"C:\AccessDatabaseEngine_x64.exe" /passive for 64-bit installation.
or
"C:\AccessDatabaseEngine.exe" /passive for 32-bit installation.
Source: "Microsoft.ACE.OLEDB.12.0" cannot be loaded in-process on a 64-bit SQL Server

A: Isn't the error self explanatory which saying that 32bit driver can't be used with 64 bit installation. You need a 64-bit driver to solve this issue.


text:
Q: Open files on CD using .HTA and VBScript I need to create a launcher for an autorun CD that creates buttons that opens files(pdfs, videos etc.) from on the CD using VBScript.
I have in the .HTA the following code
shell = new ActiveXObject("WScript.Shell").Run('My eBooks\Triniscene Link Me Campaign.pdf',1,false);

and the button is
pdf 1

However on clicking the link Internet Explorer opens instead of the file( it doesn't event show the pdf)
I want to be able to trigger the opening of the file with whatever the default application the system has

A: Try this HTA with Vbscript :

<HTA:APPLICATION
APPLICATIONNAME="Run Some Files"
BORDER="THIN"
BORDERSTYLE="NORMAL"
ICON="Explorer.exe"
INNERBORDER="NO"
MAXIMIZEBUTTON="NO"
MINIMIZEBUTTON="NO"
SCROLL="NO"
SELECTION="NO"
SINGLEINSTANCE="YES"/>
<META HTTP-EQUIV="MSThemeCompatible" CONTENT="YES">
<title>Run Some Files</title>

In Links List :

 Triniscene Link Me Campaign 1

 Triniscene Link Me Campaign 2

In Buttons List :

<button onclick="Call Run('My eBooks\Triniscene Link Me Campaign.pdf')"> Triniscene Link Me Campaign 1</button>

<button onclick="Call Run('My eBooks\MyPDF File 2.pdf')"> Triniscene Link Me Campaign 2</button>


text:
Q: Switching the body of scaffold dynamically I have application which has one scaffold and BottomNavigationBar inside.
Now I want to change the body of scaffold according to tapping.
At first I think I should use variable to stock BodyLayout || CatListLayout.
However it doesn't work. How should I do??
Widget build(BuildContext context) {
    return Scaffold(

    body: BodyLayout(articles),  // it works
  //body: CatListLayout(cats), // and it al so works

      bottomNavigationBar: BottomNavigationBar(
      items: const <BottomNavigationBarItem>[
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          title: Text('article'),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.business),
          title: Text('cat'),
        ),
      ],
        currentIndex: _selectedIndex,
        onTap: _onItemTapped,
      ),
    );
}

void _onItemTapped(int index) {
    if (index == 0){
     // want to change body to BodyLayout
    }
    if ( index == 1){
     // want to change body to CatListLayout
    }

}
class BodyLayout extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return ListView.builder(
        /////
        );
    }
}
class CatListLayout extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return ListView.builder(
        ////
        );
    }
}

A: The easiest way is this, but then you dont have any backbutton control cause you are not using a Navigator. Just keep this in mind. Using a Navigator for these kind of subpages inside a body is a bit more tricky than using different scaffolds.
import 'package:flutter/material.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  int myIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: myIndex == 0 ? BodyLayout(articles) : CatListLayout(cats),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('article'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            title: Text('cat'),
          ),
        ],
        currentIndex: _selectedIndex,
        onTap: _onItemTapped,
      ),
    );
  }

  void _onItemTapped(int index) {
    if (index == 0) {
      setState(() {
        myIndex = 0;
      });
    }
    if (index == 1) {
      setState(() {
        myIndex = 1;
      });
    }
  }
}

class BodyLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        /////
        );
  }
}

class CatListLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        ////
        );
  }
}

A: So there are several ways to do this. You can use the PageView widget and control its controller when you click on the button. Another option is to store the index of the current page for this the whole page widget should be stateful. After clicking on the button, you change this index and call setState to rebuild the widget. When building a widget, you look at the current index and display the content associated with this index


text:
Q: Return top # of rows from left table while returning all rows from right joined tables I'm trying to limit the number or orders returned but not the total of rows. I would like to select the top 15 rows from the orders table but return all related rows from the joined tables.
The statement below returns a total of 15 rows total rather than all data from the first 15 orders. Your help is appreciated.
sSQL2 = "SELECT TOP 15 orders.oID
    , orders.oName
    , cartoptions.coCartOption
    , cart.cProdID
    , cartoptions.coCartID
    , cart.cProdName
    , cart.cQuantity
FROM orders
LEFT JOIN cart
    ON orders.oid = cart.corderid
LEFT JOIN cartoptions
    ON cart.cid = cartoptions.cocartid
WHERE orders.oComplete = 1
    AND (
        cartoptions.coOptGroup = 'Logo Style'
        AND cartoptions.coCartOption = 'KGM'
        )
ORDER BY orders.oDate"

A: Quick and dirty, and untested, but this might work:
sSQL2 = "SELECT orderList.oName
              , cartoptions.coCartOption
              , cart.cProdID
              , cartoptions.coCartID
              , cart.cProdName
             , cart.cQuantity
           from (Select TOP 15 oID
                             , oName
                  from orders
                  order by oDate desc) orderList

LEFT JOIN cart
    ON orderList.oid = cart.corderid
LEFT JOIN cartoptions
    ON cart.cid = cartoptions.cocartid
WHERE orderList.oComplete = 1
    AND (
        cartoptions.coOptGroup = 'Logo Style'
        AND cartoptions.coCartOption = 'KGM'
        )"

A: Try this...
sSQL2 = "SELECT orders.oID
    , orders.oName
    , cartoptions.coCartOption
    , cart.cProdID
    , cartoptions.coCartID
    , cart.cProdName
    , cart.cQuantity
FROM (
    SELECT TOP 15 *
    FROM orders
    Where oid is not null
    )orders
LEFT JOIN cart
    ON orders.oid = cart.corderid
LEFT JOIN cartoptions
    ON cart.cid = cartoptions.cocartid
WHERE orders.oComplete = 1
    AND (
        cartoptions.coOptGroup = 'Logo Style'
        AND cartoptions.coCartOption = 'KGM'
        )"


text:
Q: How to insert image into into a DOORS attribute I'M probably just overlooking something obvious, but I can't figure out how to insert an image (a png of a chart created by plantuml) into a DOORS attribute.
If I drag and drop the image into the attribute, it wants to create an external link to the image on my hard drive. If I start editing the attribute, and drag the image into the editor, it just shows an image icon.

A: Try using Insert > Picture and selecting your PNG (you'll need to switch to 'all files' as the type)


text:
Q: What type of function is $x^2+y^2+6x$? So, the task is to calculate the volume of body formed when the surface bounded by these functions: $y=x^2/3$ and $x^2+y^2+6x$ rotates around $x$ axis.
Everything involving the actual calculation using definite integrals, finding the limits of integral, etc. is not a problem. The real problem is, I don't understand the function: $x^2+y^2+6x$
I hope not understanding the function won't influence calculating the volume later, but anyway, when I'm given a function, for example, like this one: $y-x$, not like $y=x$ or $y-2x=0$, so without equality, what do they represent and how can I write them in form $y=f(x)$?

A: Assuming that what is meant is $x^2+y^2+6x = 0$, we can write $x^2+y^2+6x+9 = 9$.  The point of doing this is to be able to write
$$
(x+3)^2+y^2 = 9
$$
which shows that this is a circle of radius $3 = \sqrt{9}$, centered at the point $(-3, 0)$.

It occurs to me that one other possibility afforded by the problem is that the curve is given by
$$
y = x^2+y^2+6x
$$
That's a bit odd, but it too can be worked into the form of a circle:
$$
(x+3)^2+\left(y-\frac{1}{2}\right)^2 = \frac{37}{4}
$$
The end result is, of course, not quite as nice.


text:
Q: Apply a list of functions to a list of objects This comes up sometimes in R, which implies to me that there has to be a way to do this in Python. If I have a list of functions, say:
functions = [lambda s: s + 'hi world', lambda s: s + '_(O.o)_']

and a list of inputs:
inputs = ['Buy', 'use', 'break', 'fix', 'trash', 'melt']

How can I apply all of the functions provided to the list of inputs? List comprehensions, to me, seem to allow me to apply to the list one of the functions, but not both of them (without hard-coding the functions themselves into the code).
To clarify, the output I'm looking for in this case would be:
output = ['Buyhi world_(O.o)_', 'usehi world_(O.o)_', 'breakhi world_(O.o)_' ...

In short, I'm trying to find a way to not have to write [f1(f2(f3(i))) for i in inputs], but instead simply have a list of 'f's and applying them all to the inputs.

A: Use a nested list comprehension:
functions = [lambda s: s + 'hi world', lambda s: s + '_(O.o)_']
inputs = ['Buy', 'use', 'break', 'fix', 'trash', 'melt']

outputs = [func(ipt) for func in functions for ipt in inputs]
print(outputs)

Output
['Buyhi world', 'usehi world', 'breakhi world', 'fixhi world', 'trashhi world', 'melthi world', 'Buy_(O.o)_', 'use_(O.o)_', 'break_(O.o)_', 'fix_(O.o)_', 'trash_(O.o)_', 'melt_(O.o)_']

UPDATE
Given the update on your question, you can use reduce:
from functools import reduce

functions = [lambda s: s + 'hi world', lambda s: s + '_(O.o)_']
inputs = ['Buy', 'use', 'break', 'fix', 'trash', 'melt']

outputs = [reduce(lambda x, f: f(x), functions, ipt) for ipt in inputs]
print(outputs)

Output
['Buyhi world_(O.o)_', 'usehi world_(O.o)_', 'breakhi world_(O.o)_', 'fixhi world_(O.o)_', 'trashhi world_(O.o)_', 'melthi world_(O.o)_']

A: With this particular example of functions, you can try a combination of functools.reduce and list comprehension:
from functools import reduce
functions = [lambda s: s + 'hi world', lambda s: s + '_(O.o)_']
inputs = ['Buy', 'use', 'break', 'fix', 'trash', 'melt']

[reduce(lambda inp, f: f(inp), functions, i) for i in inputs]

# ['Buyhi world_(O.o)_', 'usehi world_(O.o)_', 'breakhi world_(O.o)_', 'fixhi world_(O.o)_', 'trashhi world_(O.o)_', 'melthi world_(O.o)_']

A: This is probably not the most efficient way to do it. I learned Java first, so loops (or streams) feel intuitive. However that is, the following yields the answer.
functions = [lambda s: s + 'hi world', lambda s: s + '_(O.o)_']
inputs = ['Buy', 'use', 'break', 'fix', 'trash', 'melt']

for i, the_input in enumerate(inputs):
    for f in functions:
        the_input = f(the_input)  # keep answer between loops

    inputs[i] = the_input  # overwrite start value (could use a list and append)

print(inputs)

#['Buyhi world_(O.o)_',
# 'usehi world_(O.o)_',
# 'breakhi world_(O.o)_',
# 'fixhi world_(O.o)_',
# 'trashhi world_(O.o)_',
# 'melthi world_(O.o)_']


text:
Q: How to deploy a python webapp with dependencies using virtualenv? I'm looking for a way to automate deployment of web applications written in Python to a server. I would like to use virtualenv to have a clean environment for this application.
However, I am wondering how to manage dependencies when deploying to the server ?
In development, I have a virtualenv in which I install external libraries using pip, so I am looking for a way to automatically install those dependencies in production ?
Thank you for your time

A: With pip you can create a requirements file:
$ pip freeze > requirements.txt

Then in the server to install all of these you do:
$ pip install -r requirements.txt

And with this (if the server has everything necessary to build the binary packages that you might have included) all is ready.


text:
Q: Oracle Regex - Remove duplicates including chinese I'm trying to remove the duplicates in the results of a query involving listagg.
I'm using this syntax:
 REGEXP_REPLACE (LISTAGG (PR.NAME, ',' ) WITHIN GROUP (ORDER BY 1),
                 '([^,]+)(,\1)+',
                 '\1') AS PRODUCERS

However, occurrences including chinese characters are not removed:

Any idea ?

A: Your regular expression does not work. If the LISTAGG output is A,A,AA then the regular expression ([^,]+)(,\1)+ does not check that it has matched a complete element of your list and will match A,A,A which is 2½ elements of the list and will give the output AA instead of the expected A,AA. Worse, if you have the string BA,BABAB,BABD then the regular expression will replace BA,BA with BA and then replace BAB,BAB with BAB and you end up with the string BABABD which does not match any of the elements of the original list.
An example demonstrating this is:
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE names ( id, name ) AS
  SELECT 1, 'A' FROM DUAL UNION ALL
  SELECT 2, 'A' FROM DUAL UNION ALL
  SELECT 3, 'B' FROM DUAL UNION ALL
  SELECT 4, 'C' FROM DUAL UNION ALL
  SELECT 5, 'A' FROM DUAL UNION ALL
  SELECT 6, 'AA' FROM DUAL UNION ALL
  SELECT 7, 'A' FROM DUAL UNION ALL
  SELECT 8, 'BA' FROM DUAL UNION ALL
  SELECT 9, 'A' FROM DUAL
/

Query 1:
SELECT REGEXP_REPLACE (
         LISTAGG (NAME, ',' ) WITHIN GROUP (ORDER BY 1),
         '([^,]+)(,\1)+',
         '\1'
       ) AS constant_sort
FROM   names

Results:
| CONSTANT_SORT |
|---------------|
|       AA,BA,C |

If you want to get the distinct elements then you can use DISTINCT (as per Littlefoot's answer) or you can COLLECT the values into a user-defined collection and then use the SET function to remove duplicates. You can then pass this de-duplicated collection to a table collection expression and use LISTAGG to get your output:
Oracle 11g R2 Schema Setup:
CREATE TYPE StringList IS TABLE OF VARCHAR2(4000)
/

Query 2:
SELECT (
         SELECT LISTAGG( column_value, ',' )
                  WITHIN GROUP ( ORDER BY ROWNUM )
         FROM   TABLE( n.unique_names )
       ) AS agg_names
FROM   (
  SELECT SET( CAST( COLLECT( name ORDER BY NAME ) AS StringList ) )
           AS unique_names
  FROM   names
) n

Results:
|   AGG_NAMES |
|-------------|
| A,AA,B,BA,C |

Regarding your comment:

in the context of a bigger query involving a lot of join and given my begginers skills I would have no idea how to implement this model

For example, if your query was:
SELECT REGEXP_REPLACE(
         LISTAGG (PR.NAME, ',' ) WITHIN GROUP (ORDER BY 1),
         '([^,]+)(,\1)+',
         '\1'
       ) AS PRODUCERS,
       other_column1,
       other_column2
FROM   table1 pr
       INNER JOIN table2 t2
       ON (pr.some_condition = t2.some_condition )
WHERE  t2.some_other_condition = 'TRUE'
GROUP BY other_column1, other_column2

Then you can change it to:
SELECT (
         SELECT LISTAGG( COLUMN_VALUE, ',' ) WITHIN GROUP ( ORDER BY ROWNUM )
         FROM   TABLE( t.PRODUCERS )
       ) AS producers,
       other_column1,
       other_column2
FROM   (
  SELECT SET( CAST( COLLECT( PR.name ORDER BY PR.NAME ) AS StringList ) )
           AS PRODUCERS,
         other_column1,
         other_column2
  FROM   table1 pr
         INNER JOIN table2 t2
         ON (pr.some_condition = t2.some_condition )
  WHERE  t2.some_other_condition = 'TRUE'
  GROUP BY other_column1, other_column2
) t

A: (I can't see images; company policy).
Why wouldn't you remove duplicates before applying LISTAGG? Something like
select listagg(x.distinct_name, ',') within group (order by 1) producers
from (select DISTINCT name distinct_name
      from some_table
     ) x

A: Another way to remove duplicates is to use window functions and case:
select listagg(case when seqnum = 1 then name end, ',') within group (order by 1) as producers
from (select . . .,
             row_number() over (partition by name order by name) as seqnum
      from . . .
     ) t

This does require modifications to the rest of the query, but you should still be able to do the rest of the aggregations and computations.


text:
Q: pytorch model not updating I put my training code below. I am using  torch.optim.SGD as optimizer. I thought optimizer.step() would be doing the update but the model accuracy seems to stay the same. My friend said he didn't use the optimizer.step() and his works fine.
I tried taking it out, still the same result. What can I be doing wrong?
I don't think there's a problem with the accuracy calculation.
class FNet(nn.Module):
    def __init__(self, **kwargs):
        super().__init__()
        self.fc1 = nn.Linear(128*256, 1024)
        self.fc2 = nn.Linear(1024, 256)
        self.fc3 = nn.Linear(256, 2)

    def forward(self, X):
        X = F.relu(self.fc1(X))
        X = F.relu(self.fc2(X))
        X = self.fc3(X)
        return F.softmax(X, dim=1)

def main():

    learning_rate = 0.01
    model = FNet()
    optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=5e-04) # you can play with momentum and weight_decay parameters as well
    accs = [0,]

    for epoch in range(max_epoch):

        train(epoch, model, optimizer, train_batch)

        acc = test(model, val_batch)
        accs.append(acc)

def train(epoch, model, optimizer, trainloader):
    model.train()
    optimizer.zero_grad()
    for batch_idx, (data, labels) in enumerate(trainloader):

        outputs = model(data)
        loss = F.nll_loss(outputs, labels)
        loss.backward()

        optimizer.step()

def test(model, testloader):
    correct = 0
    total = 0
    model.eval()

    for batch_idx, (data, labels) in enumerate(testloader):

            outputs = model(data.view(-1,128*256))

            for sample_idx,output in enumerate(outputs):

                if torch.argmax(output) == labels[sample_idx]:
                    correct = correct + 1
                total = total + 1

    accuracy = correct/total
    return accuracy

A: I think this line should be under your for loop
optimizer.zero_grad(). You need to clear the parameter gradients after each loop.
try this
def train(epoch, model, optimizer, trainloader):
    model.train()
    for batch_idx, (data, labels) in enumerate(trainloader):
        optimizer.zero_grad()
        outputs = net(data)
        loss = F.nll_loss(outputs, labels)
        loss.backward()

        optimizer.step()

A: I think you should use log_softmax instead of softmax in the last line of your model.
def forward(self, X):
    X = F.relu(self.fc1(X))
    X = F.relu(self.fc2(X))
    X = self.fc3(X)
    return F.log_softmax(X, dim=1) # => use `log_softmax` instead.

The NLLLoss requires the input to be log-probabilities. The documentation says:

The input given through a forward call is expected to contain log-probabilities of each class.

Also, use optimizer.zero_grad() inside the for loop as mentioned in @Dishin's answer.


text:
Q: retry + circuitbreaker in resilience4j I tried to use retry with only circuitbreaker, even then it is not working. Can you please tell us how to chain them(retry + circuitbreaker) together.
It is giving preference to circuitbreakerm
I am using like this :
@CircuitBreaker(name = "backendA", fallbackMethod = "circuitBreakerFallback")
@Retry(name = "backendA", fallbackMethod = "retryFallback")
I have added this code too in yml file
resilience4j.circuitbreaker.circuit-breaker-aspect-order=2

resilience4j.retry.retry-aspect-order=1
Still doesent work ...
I am using Resilience4J 0.17.0 version


text:
Q: What are good sites or blogs for statistical analysis case studies? I'm NOT looking for articles that focus on presenting R/Python libraries or how-tos on new/cool/advanced techniques or "data science". I AM looking for articles that show how classical, established statistical analysis techniques, such as regression analysis or ANOVA, are used in demographics, politics, psychology, medicine, climatology or any other field.
Background for question: I'm a data scientist with a computer science background, trying to learn how to think like a classical statistician. The techniques themselves I can find in any book on statistics, but I want to understand how these techniques are used in practice.


text:
Q: HTML manually built datepicker I am trying to build an HTML datepicker using the code below, I am not using jquery because I am reading the returned value to a classic asp page.
<%@ Language=VBScript %>
<% Response.Expires = 0 %>

<LINK rel="stylesheet" type="text/css" href="../css/Intranet.css">
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">

<TITLE>Select Date</TITLE>

  <input onclick="navigateMonth(-1)" type="Button" Value="< " id=Button1 name=Button1><SELECT id=theYear size=1 name=theYear LANGUAGE=javascript onchange="return theYear_onchange()">
  <% For i =1940 to Year(Now) + 20 %>

    <OPTION value=<%=i%> selected><%=i%></OPTION>

  <%Next%>
  </SELECT>

  <SELECT id=theMonth size=1 name=theMonth LANGUAGE=javascript onchange="return theMonth_onchange()">
  <OPTION value=0 selected>January</OPTION>
  <OPTION value=1>February</OPTION>
  <OPTION value=2>March</OPTION>
  <OPTION value=3>April</OPTION>
  <OPTION value=4>May</OPTION>
  <OPTION value=5>June</OPTION>
  <OPTION value=6>July</OPTION>
  <OPTION value=7>August</OPTION>
  <OPTION value=8>September</OPTION>
  <OPTION value=9>October</OPTION>
  <OPTION value=10>November</OPTION>
  <OPTION value=11>December</OPTION></SELECT><input onclick="navigateMonth(1)" type="Button" Value=" >" id=Button1 name=Button1>

    <input onclick="selectDate('')" type="Button" Value="Clear" id=Button1 name=Button1>

     Sun
     Mon
     Tue
     Wed
     Thu
     Fri
     Sat

i get the sketch of the table but it seems that there is a problem with the "thiscell" span.
What might be the problem?

A: I am not really sure since I don't have the equipment to run a page written with VBScript, but as far as I can see you have written this.

Again. As you can see at the syntax highlighting. Now the JavaScript code isn't commented out. Also, ASP is kind of outdated now. It is better to use ASPX with .NET and C#. It also may be a good idea to check the settings of your IIS server.
EDIT
I took a closer look at the code
for(i=0;i<42;i++) thisCell(i).innerHTML = " ";

d = new Date(theYear.value, theMonth.value, 1)
d_next = new Date(theYear.value, theMonth.value, 1)
currdate = new Number(theMonth.value)

Where do you get the thisCell object? There is no you did not assign a value to this object when you used it i think. There are a few ways in which you can achieve this. For instance, if you are using jQuery.
var thisCell = $("#thisCell");

Or if you are using standard JavaScript
var thisCell = document.getElementById("thisCell");

The latter will work always. For the jQuery version you need to import jQuery first.
The function getElementById however is supposed to return only one element I think. The ID attribute is not supposed to have the same value assigned to multiple tags. Change every id attribute to a class attribute. After you have done that you can access the elements like this.
var x = document.getElementsByClassName("thisCell");
var i;
for (i = 0; i < x.length; i++) {
    x[i].style.backgroundColor = "red";
}

Hope this helps.


text:
Q: PropelBundle database:create for postgres I've installed propel bundle for symfony2.
my database configuration is:
propel:
    dbal:
        driver:               pgsql
        user:                 postgres
        password:             postgres
        dsn:                  pgsql:host=localhost;port=5432;dbname=test_database
        options:              {}
        attributes:           {}

When i wan to create this database from console (console propel: database:create) i have got strange error : Unable to open PDO connection [wrapped: SQLSTATE[08006] [7] FATAL: database "pgsql" does not exist.
i created pgsql database on my localhost and everything was good. Database "test_database" was succesfull created. Can somebody explain me why i got this previous error? On mysql i've created database without any problems.

A: This issue was a bug in the PropelBundle, it has been fixed by the following commit (even if the commit message is about MySQL, it fixes other RDBMS): https://github.com/propelorm/PropelBundle/commit/b4475d27fb1eb846d10cc2d2e2bd164f037508e3

A: I 've installed new PropelBundle via Composer and everything is ok now. I think maybe it was a problem with 1.0 bundle , now I have 1.1


text:
Q: Contravariant representable functor notation I'm reading Steve Awodey's lecture notes on category theory, and am confused about the notation for covarian/contravariant representable functors:
For a locally small category $\mathcal{C}$ with objects $A, B$, the covariant representable functor is defined as $\mathcal{C}(A, -): \mathcal{C} \to \texttt{Set}$, where
$$
\begin{align}
&\mathcal{C}(A, B) = \{ f \in \mathcal{C}_{1} \mid f: A \to B \} \\
&\mathcal{C}(A, g) : f \mapsto g \circ f
\end{align}
$$
The contravariant representable functor is defined as $\mathcal{C}(-, B): \mathcal{C}^{op} \to \texttt{Set}$. Here, I'm not sure if the following is correct:
$$
\begin{align}
&\mathcal{C}(A, B) = \{ f \in \mathcal{C}^{op}_{1} \mid f: B \to A \}
\end{align}
$$
If so, how can we differentiate between $\mathcal{C}(A, B)$ for the covariant representable functor and that of the contravariant representable functor?

A: No, $\mathcal{C}(A,B)$ is always the set of maps $A\to B$ in $\mathcal{C}$. The difference is simply whether we consider $A$ or $B$ as the variable; if $A$, then we have $\mathcal{C}(A,B)=[\mathcal{C}(-,B)](A)$, contravariant in $A$; if $B$, then we have $\mathcal{C}(A,B)=[\mathcal{C}(A,-)](B)$, covariant in $B$. It's perhaps least ridiculous to simply recognize that both of these are shadows of the full object, $\mathcal{C}(-,-)$, a functor of two variables $\mathcal{C}^{\mathrm{op}}\times \mathcal{C}\to\mathtt{Set}$. Regardless, $\mathcal{C}(A,B)$ is always the same thing: it's a value of at least three different functors, and which one, if any, the author has in mind can't be determined just from the notation, since the notation only indicates a set.


text:
Q: Is there a cross-browser standard on-load event for HTML's "object" tag? I am aware that IE supports the onreadystatechange attribute on the object tag, but this doesn't seem to be a standard way thus all other browsers do not support it.
Update: To clarify, I am not looking for the DOM Load event, I am looking for the load event of the object tag itself(e.g. an object tag embedding a PDF file into a page).
In a way, I am looking for something similar to img's onload event /complete attribute for the object tag.

A: The <object onload> attribute works well in latest versions of Firefox, Chrome and Opera (I've just tested it).
Also, the expression 'onload' in document.createElement('object') evaluates to true in Chrome and Opera; naturally, Firefox is an exception because such event support check doesn't work there generally. kangax describes cross-browser event support detection at http://perfectionkills.com/detecting-event-support-without-browser-sniffing/

A: So you want to trigger an event after the [PDF] object is loaded?
If so, this might help you:
http://www.webdeveloper.com/forum/showthread.php?t=160792
----- EDITED [19/10/2011] -----
If you load the PDF inside an iframe, it will work.
Check this: http://sykari.net/stuff/iframe
The script will alert only after the PDF is completely loaded.
(Tested with FF7 + Win7).
----- EDITED [20/10/2011] -----
Using JQuery: http://jsfiddle.net/fcABz
To be sure it is working i have added a 36 pages PDF file to the iframe, so you can watch the progress bar (at least in FF7 there is one, not sure about Chrome) going up, and after it is fully loaded, you will see an alert.
Why? Because the .load method from JQuery will wait until all subelements inside the iframe are loaded.

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

If you want to try more then once, clear the cache.
Or change the PDF to a bigger one, like this http://pubs.usgs.gov/tei/532/report.pdf (90 pages).

A: I'm not sure you can do this just using object attributes.
Have a look at this :

*

*You can try something using onreadystatechange
When data is well loaded, readyState==4 and xmlhttp.status==200

*You can try to use jQuery load function :
Export your <object/> in a page called object.html.
In your main page include :

The message will be display when the request completes.


text:
Q: The Search parameter does not work with Outlook restapi I've used the basic example/tutorial described in "https://github.com/jasonjoh/php-tutorial" and tried to add the "$search" parameter in the getMessages() function
    $getMessagesParameters = array (
        // Message Search Conditions
        "\$search" => 'subject:"pizza"',
        // Only return Subject, ReceivedDateTime, and From fields
        "\$select" => "Subject,Body",
        // Return at most 10 results
        "\$top" => "10"
    );
    $getMessagesUrl = self::$outlookApiUrl."/Me/Messages?".http_build_query($getMessagesParameters);
    $response = $this->makeApiCall($access_token, $user_email, "GET", $getMessagesUrl);

the request returns error 400
wonder what might be the correct syntax
I've referred the following links
https://msdn.microsoft.com/office/office365/api/complex-types-for-mail-contacts-calendar#UseODataqueryparametersSearchrequests
https://msdn.microsoft.com/en-us/library/cc513841%28v=office.12%29.aspx
https://support.office.com/en-us/article/Learn-to-narrow-your-search-criteria-for-better-searches-in-Outlook-d824d1e9-a255-4c8a-8553-276fb895a8da
If someone have a better idea to search through the mails, please suggest...

A: You can not use orderby in search results.
see https://msdn.microsoft.com/en-us/office/office365/api/complex-types-for-mail-contacts-calendar#UseODataqueryparametersSearchrequests
$search=subject:"pizza" should be $search=subject:pizza. But that is not working also.
I use $search=pizza and that works (without orderby)

A: I've figured out the exact issue...
The Problem is not with the search parameter specifications / server REST Endpoints...
But the problem is with how we send the query params to the server...
We should not url encode the data.
but we need to replace the spaces with + in the result url
This is the solution I've come up with...
    $search_AQS = '"Subject:(pizza+OR+hamburger+OR+tacos)+AND+subject:(NOT+beef+NOT+pork)"';
    $getMessagesParameters = array (
        "\$search" => $search_AQS,
        "\$select" => "Subject,Body",
        "\$top" => "10"
    );
    $tmp_uripiece = http_build_query($getMessagesParameters);
    $tmp_uripiece = urldecode($tmp_uripiece);
    $getMessagesUrl = self::$outlookApiUrl.'/Me/Messages?'.$tmp_uripiece;
    $response = $this->makeApiCall($access_token, $user_email, "GET", $getMessagesUrl);

Yay! microsoft also supports search feature in their endpoints... but they should've documented with more examples...
Everybody thanks for your support...


text:
Q: Quicksort - ошибка stack overflow Алгоритм сортирует таблицу со случайными числами на 100тыс, 500тыс, 1млн, но при сортировке уже отсортированной таблицы или таблицы обратно отсортированной выдает исключение Stack Overflow. Знаю, что это не хватает памяти, но как можно решить эту проблему?
#include "stdafx.h"
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <windows.h>

void quicksort(int *A, int p, int r);
int partition(int *A, int p, int r);

//int A[100000];
int A[500000];
//int A[1000000];

//int B[100000];
//int B[500000];
//int B[1000000];

//int C[100000];
//int C[500000];
//int C[1000000];

int main()
{
    srand(time(NULL));

    int length = 500000;

    for (int i = 0; i < length; i++)
    {
        A[i] = i;
        //printf("%d ", A[i]);
    }

    /*for (int i = 0; i < length; i++)
    {
        B[i] = i;
        //printf("%d ", B[i]);
    }*/

    /*for (int i = length-1; i >= 0; i--)
    {
        C[i] = i;
        printf("%d ", C[i]);
    }*/

    float start = GetTickCount();
    quicksort(A, 0, 499999);
    float finish = GetTickCount();
    float result = (finish - start) / 1000;

    printf("\n losowa (seconds): %f", result);

    getchar();
}

void quicksort(int *A, int p, int r)
{
    float start = GetTickCount();
    int q;
    if (p < r) {
        q = partition(A, p, r);
        quicksort(A, p, q - 1);
        quicksort(A, q + 1, r);
        float finish = GetTickCount();
        float result = (finish - start) / 1000;
    }
}

int partition(int *A, int p, int r)
{
    int i, j, x, tmp;

    x = A[r];
    i = p - 1;

    for (j = p; j <= r - 1; j++) {
        if (A[j] <= x) {
            i++;

            tmp = A[j];
            A[j] = A[i];
            A[i] = tmp;
        }
    }

    tmp = A[i + 1];
    A[i + 1] = A[r];
    A[r] = tmp;

    return i + 1;
}

A:
как можно решить эту проблему?

Использовать нерекурсивную реализацию QuickSort. Подробных разборов с исходниками на C много, например, здесь.
(а может и вообще подумать о другом алгоритме, не quicksort, так как из примера не очень понятно: речь идёт о реальных данных или об учебном примере)

A: Навскидку несколько вариантов:

*

*Увеличить размер используемого стека (см. ключи компилятора)

*Сократить количество передаваемых аргументов (они то как раз и пихаются в стек вызовов) - в вашем случае очевидный кандидат это параметр int *a - можно например его сделать глобальным

*Засунуть все параметры в динамический массив типа Stack и извлекать их вручную

A: После q = partition(A, p, r); посмотреть, какой из "подмассивов" короче и продолжать рекурсию с него
if (q - 1 - p < r - q + 1) {
    quicksort(A, p, q - 1);
    quicksort(A, q + 1, r);
} else {
    quicksort(A, q + 1, r);
    quicksort(A, p, q - 1);
}


text:
Q: is there any possibility for "if" block to go out of given choices in vhdl? Below is the code of VHDL which uses IF block.
In the last "elsif", the value of "my_choice" is assigned to "ch4". Then "else" block is executed, since no condition is satisfied. But, is there any chance that "my_choice" gets some other value other than (ch1,ch2,ch3,ch4), like high impedence (or anything else)? If so, how can i avoid that? Since this assignment can change the operation of the code.
    entity entity_name
    port
        .....
        .....
    end entity_name;

    architecture bhvr of entity_name

    type choices is (ch1, ch2, ch3, ch4);
    signal my_choice,next_choice : choices;

    begin
        process(clk, reset)
        begin
            if reset='1' tehn
                --------reset
            else
                  my_choice<=next_choice;
            end if;
        end process;

        process(my_choice)
        begin
            if my_choice = ch1 then
                next_choice <= ch2;
            elsif my_choice = ch2 then
                next_choice <= ch3;
            elsif my_choice = ch3 then
                next_choice <= ch4;
            else  ------------------------------------coming to ch4
                ---- task for ch4
        end process;
    end architecture;

A: Since my_choice is type choices, which is enumerated type with values 'ch1', 'ch2', 'ch3', 'ch4', then my_choice will always have one of these 4 values, at least in simulation.
In hardware, the available value space depends on the implementation, for example if the values are made as one-hot or binary.  After start-up a reset is a good way to make sure that the value is well-defined to one of the 4 values, and if the circuit then adheres to the timing requirements, then the value will stay in the defined values space of the 4 values.


text:
Q: Minimum code to render master page I created a new blank custom master page in SharePoint designer 2010. Made it the default page and now when I open the website in browser it shows error:
Error
An unexpected error has occured
Correlation ID: 44eccc...................

What is the minimum code that must be present in master page to make it work? I thought since I am creating it from SPD then it will take care of it but looks like that's not the case.

A: here is a good post how to create master pages with minimum generated code: http://johanleino.wordpress.com/2011/10/20/using-a-different-master-page-for-authenticated-users-in-sharepoint/
Hope it helps,
Andrew

A: There are a LOT of parts that have to be in a master page in order for it to work so it is a better approach to start with either an existing Master Page or a template.  I've used the Starter Master Pages on CodePlex in several projects and they work out really well as a "blank" starting point.
Just keep in mind that you really do not want to change the way that the Ribbon appears as doing so will bite you in any one of a dozen unique ways.


text:
Q: Is it safe to share a file handle between two processes in PHP? I've found similar questions here on Stack but I'm not sure whether they apply to PHP.
I'd like to create child processes with pcntl_fork(). I want to write messages to a log file, from both the parent and the child processes.
If I open a file handle in the parent, is it safe to write to the same handle from the childs? Note that I will only be appending to the file.
I'm afraid of the race conditions that could happen, in particular if the two processes are executed on different cores: what would happen if two processes executing on two different cores were to write to the same file handle at the same time?

A: Use flock or streamWrapper::stream_lock as the case may be or stream_set_blocking

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows).

flock works on file resource and is closed automatically if fclose() even if the file is not unlocked.
flock($fp, LOCK_EX);

You can loop and wait until the file is ready to be opened for writing in my case am using c+
while(! $fp = @fopen($this->file, "c+")) {
    if (time() - $time > $this->timeout)
        throw new Exception("File can not be accessed");
    usleep(100000);
}

$this->timeout is basically how long you ended to wait for the file a good example can be found PHP issues using flock - file locking


text:
Q: Get error: Cannot find control with path: 'excludedPeriods -> 0 -> dateTo' I am trying to use a FormArray inside a FormGroup. My HTML looks like this:
<div nz-row nzGutter="10" formArrayName="excludedPeriods">
            <ng-container *ngFor="let period of excludedPeriodsList().controls; let i = index">

              <div [formGroupName]="i">
                <div nz-row nzGutter="10">
                  <div nz-col nzSpan>
                    <nz-form-item>
                      <nz-form-label nzSpan="24">Exclude From</nz-form-label>
                      <nz-form-control>
                        <nz-date-picker nzShowTime nzFormat="dd/MM/yyyy HH:mm" formControlName="dateFrom"
                          [style.width]="'100%'"></nz-date-picker>
                      </nz-form-control>
                    </nz-form-item>
                  </div>
                  <div nz-col nzSpan>
                    <nz-form-item>
                      <nz-form-label nzSpan="24">Exclude To</nz-form-label>
                      <nz-form-control>
                        <nz-date-picker nzShowTime nzFormat="dd/MM/yyyy HH:mm" formControlName="dateTo"
                          [style.width]="'100%'"></nz-date-picker>
                      </nz-form-control>
                    </nz-form-item>
                  </div>
                </div>
              </div>
            </ng-container>
          </div>

Inside the TypeScript:
To initialize the form, I was checking if the form already contains any value or not via service call and passing that value to the createForm function:
private _createForm(product?: IProduct): void {
    console.log('_createForm ~ product', product.excludedPeriods);
    this.segmentIds = product?.segmentIds ?? [];
    const excludedPeriods = product?.excludedPeriods ?? [];
    this.productForm = this.fb.group({
      activeFrom: [product?.activeFrom],
      activeTo: [product?.activeTo],
      excludedPeriods: this.fb.array(excludedPeriods),
    });
}

excludedPeriodsList(): FormArray {
    return this.productForm.get('excludedPeriods') as FormArray;
}

newExcludePeriod(): FormGroup {
    return this.fb.group({
      dateFrom: '',
      dateTo: ''
    });
}

addExcludedPeriod() {
    this.excludedPeriodsList().push(this.newExcludePeriod());
}

I could not figure out what have I done wrong here. Can someone please enlighten me and give me a solution?

A: You have to provide the excludedPeriods value as FormGoup[] to the form array.
Solution 1: With .map()
this.productForm = this.fb.group({
  ...,
  excludedPeriods: this.fb.array(
    excludedPeriods.map(
      (x) =>
        this.fb.group({
          dateFrom: [x.dateFrom],
          dateTo: [x.dateTo],
        })
    )
  ),
});

Solution 2: With FormArray.push()
private _createForm(product?: IProduct): void {
  ...

  this.productForm = this.fb.group({
    ...,
    excludedPeriods: this.fb.array([]),
  });

  this.addFormGroupToExcludePeriodsList(excludedPeriods);
}

addFormGroupToExcludePeriodsList(
  excludedPeriods: { dateFrom: Date; dateTo: Date }[]
) {
  for (let excludePeriod of excludedPeriods) {
    this.excludedPeriodsList().push(
      this.fb.group({
        dateFrom: [excludePeriod.dateFrom],
        dateTo: [excludePeriod.dateTo],
      })
    );
  }
}

Demo Solution 1 & 2 @ StackBlitz


text:
Q: Liblinear logistic regression output always -1 I am new to machine learning and I am trying to use logistic regression prediction in liblinear using dataset from here http://www.ats.ucla.edu/stat/data/binary.csv
I am using java to train and test. However even if I run the prediction on the same file, I always get -1 as the prediction for all of them. I never get 100% even if I use the heart_scale provided with lib linear and libsvm. What I am doing wrong?
I am running the following commands in java
java -cp liblinear-1.94.jar de.bwaldvogel.liblinear.Train -s 0 trainFile
java -cp liblinear-1.94.jar de.bwaldvogel.liblinear.Predict -b 1 testFile testFile.model testFile.txt


text:
Q: From what files are the .fmt files generated? I am trying to dig into the inner workings of LaTeX and to see where basic macros such as \{ are defined. texdef gives nothing useful (saying that it is defined by LaTeX) and the .fmt files, being binary files, are obviously generated from something. How are the .fmt files generated, and where can I get the files from which they are made?

A: An .fmt file is a "format" file that is generated by the program inittex.  It loads a standard .tex file and in a sense "compiles" it using inittex's dump command which creates a binary representation of this "compiled" .tex file.
The original purpose of format files was to speed the loading of such tex files.  Bechtolsheim, in "TeX in Practice, Vol II", states that loading the plain.tex file would take 80 seconds on a VAX 11/780 under BSD UNIX 4.2, while loading plain.fmt took only 10 seconds.
Obviously, today's machines are so much faster that the difference probably isn't discernible.  Still, for reasons of efficiency, .fmt files might as well be used with common formats such as plain, csplain, LaTeX, etc.
The standard way of loading an .fmt file is something like tex --fmt=pdfcsplain ..., but that can be embedded inside a command, shell script or other executable.  (I'm sure latex is one of those.)


text:
Q: Bound on $a,b,c,d$ and truth of statement $\forall \, x \in \mathbb N, \exists \, a,b,c,d \le {l(x)} \in \mathbb N:x=a^b+c^d$ To render the statement in the title in relatively simple English, "For every natural number $x$, there exist four natural numbers $a,b,c,d \le l(x)$, where $l(x)$ is a function of $x$ which bounds these numbers, such that $x=a^b+c^d$. I have attempted to do some research on whether this statement is true, with no success. Obviously if $0$ is included as a possible value for $a,b,c,d$ then the statement is always true and an obvious bound on $l(x)$ is $x$, but I am excluding it for the sake of a more interesting problem. I haven't done much numerical testing of this one, so it is possible that there very low numbers that prove this false.
On a different but related question, we look at the similar statement $$\forall \, x \in \mathbb N, \exists \, a,b,c,d \le {L(x)} \in \mathbb N:x=a*3^b+c*2^d$$. Similarly, the statement is always true if $0$ is included as a possible value of $a,b,c,d$, as $b$ and $c$ can be set to $0$ and $a$ to $x$. If we exclude $0$, for all numbers that I have tested greater than $6$ the statement holds true for some value of $L$. I have, however, completely failed at determining any good bounds on $L$, other than that it appears to be in $O(x^c)$ where $\frac 1 4 \lt c \lt \frac 1 2$. I don't have a proof for that, just numerical evidence.
Truth of these statements, expressions for $l$ and $L$?

A: For the second problem, if $u,v$ are relatively prime, then every integer can be written as $xu+yv$, if we allow $x,y\in\mathbb Z$. This is because there exists a solution of $xu+yv=1$ with $x,y\in\mathbb Z$ and we can simply multiply this. Next, if $n=xu+yv$, then also $n=(x\pm v)u+(y\mp u)v$ so that a solution with $0<x\le v$ must exist. We conclude that a solution with $x,y>0$ exists for all $n>uv$.
Now for given $n\ge 10$, let $d=\lfloor \log_2\sqrt {n-1}\rfloor $ and let $b=\lfloor \log_3\frac {n-1}{2^d}\rfloor$.
Then

*

*$n\ge 10$ implies $d\ge 1$ as required

*$2^d\le \sqrt{n-1}$ implies $\frac{n-1}{2^d}\ge\sqrt{n-1}\ge3$ and hence $b\ge1$ as required.

*By the preceding paragraph, there exist integers $a,c>0$ such that $a\cdot 3^b+c\cdot 2^d=n$.

*From $2^{d+1}> \sqrt{n-1}$ we conclude $c<\frac n{2^d}< \frac{2n}{\sqrt{n-1}}=O(\sqrt n)$

*From $3^{b+1}>\frac{n-1}{2^d}\ge\sqrt{n-1}$, we conclude $a<\frac{n}{3^b}<\frac{3n}{\sqrt{n-1}}=O(\sqrt n)$.

This confirms your observation that $L=O(\sqrt n)$ (and you can extract an exact expression from the above).
You cannot expect any substantially better bound: Assume $L=O(n^\alpha)$ with $\alpha<\frac12$, say $L\le Cn^\alpha$ for all $n>n_0$. For  $N\in\mathbb N$, there are about $CN^{2\alpha}\log_2 N\log_3N$ tuples $(a,b,c,d)$ with $a,c\le CN^\alpha$ and $3^b, 2^d<N$. For large $N$, we have $CN^{2\alpha}\log_2 N\log_3N\ll N$, hence there are not enough tuples to provide solutions for all $n$ with $n_0<n\le N$.


text:
Q: UiTableView bug, added cell doesnt insert text needed Hey guys i have a table view that can add and delete cells. but when i delete the only cell that comes with the app, and i try to add a new cell with the text of "Meghan Way" and the text just automatically changes it self to the original cells text which is "House 1" here is my code!
- (IBAction)saveButton:(id)sender {
FacePlatesViewController * viewController = (FacePlatesViewController
*)self.parentViewController;

[viewController addObject:[NSMutableDictionary dictionaryWithObject:text.text
forKey:@"name"]];

[self dismissModalViewControllerAnimated:YES];
}

- (IBAction)cancel:(id)sender {
[self dismissModalViewControllerAnimated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.text = [[cells objectAtIndex:indexPath.row] valueForKey:@"name"];
UIImage * myimage = [UIImage imageNamed: @"check.png"];
image = [[UIImageView alloc]initWithImage:myimage];

tableView.backgroundColor = [UIColor clearColor];

    self.myTableView = tableView;

}
return cell;

}

this is for the save button! any help would be very appreciated:D Thanks

A: You code is quite messed up. I have improved it below and added comments:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";

    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
    reuseIdentifier:CellIdentifier] autorelease];
    }  //The if block should end here. You should set the cell's label irrespective whether the cell was nil. This is the cause of the issue you are facing.

    cell.textLabel.text = [[cells objectAtIndex:indexPath.row] valueForKey:@"name"];

    //You are doing nothing with the UIImage
    //UIImage * myimage = [UIImage imageNamed: @"check.png"];
    //image = [[UIImageView alloc]initWithImage:myimage];

    //You should be setting the background color just once, in ViewDidLoad, not here.
    //tableView.backgroundColor = [UIColor clearColor];

    //I don't see why this is required
    //self.myTableView = tableView;

    return cell;

}

A: Are you storing the text labels for these cells in any kind of array or dictionary and loading them in there using the standard "cellForRowAtIndexPath?" If so, then you need to delete the dictionary / array entry in that data source to prevent it from being used again.
I can't tell for sure without seeing some more code...but it sounds like a cell recycling issue. I could be wrong...but I'd need to see more info.


text:
Q: Why can we assume $\pi = 0.5$ in sign test? When using the sign test, we assume, that:
$\textrm{test statistic} \sim Bi(n_+ + n_-, 0.5)$
ie. that the probablity of $+$ or $-$ to occur is $0.5$. But how about the case of values being the same (resulting in $0$). The probablity of $0$s increases when dealing with ordinal variables.
How can the probablity still be $0.5$? What am I missing on?


text:
Q: How can i change the border of  in Bootstrap 4.2? Briefly, i want to change the color of an outline of a fieldset to a color of my choice (blue for example) instead of the default grey outline color.
And this happens when i click on the (input) field:
Note CSS property does not work
I use this code

fieldset {
  border: 2px solid blue;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="legned.css">

  <link rel="stylesheet" href="https://cdn.rtlcss.com/bootstrap/v4.2.1/css/bootstrap.min.css" integrity="sha384-vus3nQHTD+5mpDiZ4rkEPlnkcyTP+49BhJ4wJeJunw06ZAp+wzzeBPUXr42fi8If" crossorigin="anonymous">

  <title>Bootstrap Legned</title>

  <fieldset class="border p-2 w-25 mr-auto ml-2">
    <legend class="w-auto">First Name</legend>
    <input name="text1" type="text" />
  </fieldset>
  <fieldset class="border p-2 w-25 mr-auto ml-2">
    <legend class="w-auto">Last Name</legend>
    <input name="text1" type="text" />
  </fieldset>

The illustrations are attached below:
Before click on input
After click on input

A: You should fix how you're importing your Bootstrap as well, but when I removed .border, your CSS worked after adding !important to make sure it overrides the inherited Bootstrap CSS.

fieldset {
  border: 2px solid blue !important;
}

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

  <fieldset class="p-2 w-25 mr-auto ml-2">
    <legend class="w-auto">First Name</legend>
    <input name="text1" type="text" />
  </fieldset>
  <fieldset class="p-2 w-25 mr-auto ml-2">
    <legend class="w-auto">Last Name</legend>
    <input name="text1" type="text" />
  </fieldset>

A: Just add an empty div to the fieldset and style it this way:

fieldset {
  border: none;
  position: relative;
  margin-bottom: 0.5em;
}

input:focus ~ div {
  border: 2px solid blue;
}

fieldset > div {
  height: calc(100% - 0.5em);
  width: 100%;
  position: absolute;
  top: 0.5em;
  left: 0;
  border: 2px solid lightgray;
  z-index: -1;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="legned.css">

  <link rel="stylesheet" href="https://cdn.rtlcss.com/bootstrap/v4.2.1/css/bootstrap.min.css" integrity="sha384-vus3nQHTD+5mpDiZ4rkEPlnkcyTP+49BhJ4wJeJunw06ZAp+wzzeBPUXr42fi8If" crossorigin="anonymous">

  <title>Bootstrap Legned</title>

  <fieldset class="p-2 w-25 mr-auto ml-2">
    <legend class="w-auto">First Name</legend>
    <input name="text1" type="text" />

  </fieldset>
  <fieldset class="p-2 w-25 mr-auto ml-2">
    <legend class="w-auto">Last Name</legend>
    <input name="text1" type="text" />

  </fieldset>


text:
Q: JavaFX Enable and disable elements from outside I would like to access my Main Stage from outside.
My mainstage is loaded with a fxml.
After that I can press a login button on the mainstage and then a login popup opens.
I want to set the button to Visi... as long as the login window is open. and then set it to Visi... afterwards.
Furthermore I want to show several elements in the mainstage after my login was successful.
   @Override
   public void start(Stage primaryStage) throws Exception
   {
       Parent root = FXMLLoader.load(getClass().getResource("../resource/views/lobbyMain.fxml"));
       primaryStage.setTitle("Hello World");
       primaryStage.setScene(new Scene(root, 1000, 700));
       primaryStage.show();
       primaryStage.setOnCloseRequest(windowEvent -> {
           Platform.exit();
           if (loginStage != null){
               loginStage.close();
           }
           if (registrationStage != null){
               registrationStage.close();
           }
       });
   }

I hope you can help me in this regard.
Thank you very much.


text:
Q: How can this Visual studio Resource warning be resolved or removed? Anyone can help us here - we have been having this error for several months and had many a stab to remove it, but we still havnt figured out why its there or how to remove it. How is this warning resolved or removed?

Warning   351 A custom tool 'GlobalResourceProxyGenerator' is associated
  with file 'App_GlobalResources\GridLocalization.bg-BG.resx', but the
  output of the custom tool was not found in the project.  You may try
  re-running the custom tool by right-clicking on the file in the
  Solution Explorer and choosing Run Custom Tool.

A: In my case this was caused by a <LastGenOutput> entry in the csproj file that referred to a non-existent file. Removing that line got rid of the warning.

A: After checking out the csproj file and discussing it in the group, we came up with the following answer:
When the resources were added to the project they were added using the wizard. This wizard added the designer files also, so for each reasource file there was also a .designer file.
This was seen as something that was not needed for the language specific resources and the designer files were deleted.
However the csproj files maintained the custom tool reference.
Deleting this reference (to "GlobalResourceProxyGenerator") for each of these resource files removed the issue.
The issue is that Visual Studio 2010 does not automatically remove this tool reference when the designer files are removed manually, creating this warning.

A: In Visual Studio 2017 I had the same issue with the following error
Warning A custom tool 'ResXFileCodeGenerator' is associated with file <snip name>, but the output of the custom tool was not found in the project.

Removing the reference to
<Generator>ResXFileCodeGenerator</Generator> within the resource file declaration, fixed the issue.

A: In VS 2019, I also fixed the error:
Warning A custom tool 'ResXFileCodeGenerator' is associated with file , but the output of the custom tool was not found in the project.
By removing the reference to ResXFileCodeGenerator
found within the project's  " .csproj"  file!


text:
Q: Is there a way I can use a user's input in a WHERE clause in triggers? (SQL SERVER) I am trying to create a trigger to prevent insertion if the conditions are not met. Here is what I have so far:
CREATE TRIGGER flightBookingLimit
ON Booking_Ticket
INSTEAD OF INSERT
AS
BEGIN
IF EXISTS(
SELECT COUNT(Booking_Details.Booking_ID), Passenger_Details.Name, Booking_Details.Flight_No
FROM Booking_Ticket
LEFT JOIN Booking_Details ON Booking_Ticket.Booking_ID = Booking_Details.Booking_ID
LEFT JOIN Passenger_Details ON Booking_Details.Passenger_ID = Passenger_Details.Passenger_ID
LEFT JOIN Flight_Schedule ON Booking_Details.Flight_No = Flight_Schedule.Flight_No
LEFT JOIN Aircraft ON Flight_Schedule.AircraftID = Aircraft.AircraftID
LEFT JOIN Airline ON Aircraft.AirlineID = Airline.AirlineID
WHERE Airline.AirlineName = 'Emirates Airlines'
GROUP BY Passenger_Details.Name, Booking_Details.Flight_No
HAVING COUNT(Booking_Details.Booking_ID) >= 4
)
BEGIN
    PRINT 'This flight only allows a maximum of 4 bookings'
END
ELSE
    INSERT INTO Booking_Ticket
    SELECT Booking_ID,Passenger_ID,Flight_No,Reservation_Status,Special_ServiceID,Flight_MealsID,Flight_TripsID,Flight_ClassesID,Ticket_Status,Basic_Fare,Total_Fare
    FROM inserted
END

In the WHERE clause, I would like to do something like:
WHERE Airline.AirlineName = 'Emirates Airlines' AND Passenger_Details.Name = 'Michael Stuart' AND Booking_Details.Flight_No = 'MH101'

Is there a way I can retrieve the user's input when performing insertion queries? Hardcoding these clauses does not help me do what I want to achieve.

A: No, not on 2 levels.

*

*One, a WHERE clause in general allows no user interaction. SQL is not having, generally, ANY user interaction.

*Triggers are FULLY reactive. There is zero way to inject anything that is not in a different table (you COULD have settings in a table). This is just how they are done.

Generally the UI of the application layer puts together the SQL as you want it.


text:
Q: Java get NULL value from getUsername(); (diffrent class files) So i am practising my java skills and after 2.5hrs of trying and thinking without asking help i am kinda lost...
The problem is in the class Welcome i am setting a username and role.
but in the terminal i want to use the username via the Getter but it comes out null
check for classes below
Welcome class:
public class Welcome {

    public static void welcome(){
        Player m = new Player();
        String user;
        String roletype;
        Float startersmoney;
        // welcome msg
        System.out.println("Welcome to 'Roots'.");

        //enter your desired username
        System.out.println("Enter your alias : ");
        Scanner scanner = new Scanner(System.in);
        Ruler.ruler();
        user = scanner.nextLine();
        m.setUsername(user);
        // returns username

        System.out.println("Your alias is now set to : " + m.getUsername());
        // are you a hacker?
        System.out.println("What are you? a 'hacker' or ? ");
        Ruler.ruler();
        roletype = scanner.nextLine();
        m.setRole(roletype);
        m.setCurrency(250.00);
        //checks user input. and gives output
        if (m.getRole().equalsIgnoreCase("hacker")) {
            System.out.println("So you are a : " + m.getRole().toLowerCase());
        } else {
            System.out.println("hahahaha... NOOOOB!!!\n only hackers are allowed to play 'Roots'..");
        }
        System.out.println("Okay lets get started. hint : 'help' ");
        Ruler.ruler();
        Terminal.terminal();
    }

Ruler Class
  public class Ruler {

    // for input markup '@root:~ > ' <- feels like terminal :D
    public static void ruler(){
        Player r = new Player();
        System.out.print(r.getUsername() + "@root:~ > ");
    }
}

Player class
public class Player {

    //variables
    private String username;
    private String role;
    private double currency;

    //setters
    public void setUsername(String value)   {   this.username = value;      }
    public void setRole(String role)        {   this.role = role;           }
    public void setCurrency(Double currency){   this.currency = currency;   }

    //getters
    public String getUsername() {   return this.username;        }
    public String getRole()     {   return this.role;            }
    public Double getCurrency() {   return this.currency;        }

}

A: Your problem is common -- that of creating a new instance of an object and expecting it to magically acquire the state of other objects of the same class. This is not how Java works.
Look at how many times you see new Player() in your code. Each time you see it, you're doing just that, creating a new Player object, one distinct from all others. So setting the state of one will have no effect on the other one whose state you're checking.
Solution: by passing references, check the state of the previously created Player object only. Don't create a new one in your listener code.
So:
public class Ruler {
   private Player player;

   public Ruler(Player player) {
      this.player = player;
   }

    // **** this shouldn't be static!
    public void checkState(){
        // Player r = new Player();
        // System.out.print(r.getUsername() + "@root:~ > ");
        System.out.print(player.getUsername() + "@root:~ > ");
    }
}

then in
public static void main(String[] args) {
    Player player = new Player();
    Ruler ruler = new Ruler(player);

    // now call player and ruler methods as desired
}

Edit
You state:

.btw it has to be static otherwise i cant use it.... for some reason..

NO! Then you're fixing the wrong thing. The key is to fix your code so that it doesn't have to be static.

look here : /home/stefano/intelliJ_Projects/Roots/src/com/stefano/Welcome.java Error:(32, 14) java: non-static method ruler() cannot be referenced from a static context Error:(44, 14) java: non-static method ruler() cannot be referenced from a static context Error:(45, 17) java: non-static method terminal() cannot be referenced from a static context

Again, as my code shows, get rid of the static ruler method and instead use only a non-static method. The Ruler class must have state, must have non-static variables, and so you should call instance methods on objects of the class, not static methods. You're doing things backwards, I'm afraid.

A: You should initialize the username of the player before displaying it.  For example, after creating a new player, set the value of the username.
public class Ruler {

    // for input markup '@root:~ > ' <- feels like terminal :D
    public static void ruler(String username){
        Player r = new Player();
        r.setUserName(username); // Here you can give it a value

        System.out.print(r.getUsername() + "@root:~ > ");
    }
}

In your Welcome class
public class Welcome {

    public static void welcome(){
        ....

        //enter your desired username
        System.out.println("Enter your alias : ");
        Scanner scanner = new Scanner(System.in);
        user = scanner.nextLine();
        Ruler.ruler(user);
        ...

}

And Ruler should have a Player attribute
public class Ruler {
   private Player player;
   ...
}