text:
Q: How to Add Multiple Products to Shopify Cart with One Button Click Here is the button's code:
    {% assign p_annual = all_products[section.settings.paid_product_annual] %}
    {% assign p_free = all_products[section.settings.free_product] %}

        {% if section.settings.productlink1label != blank %}
            <button class="btn"
                 type="submit"
                 name="paid-plan"
                 id="paid-plan-option-annual"
                 data-variant-id="{{ p_annual.selected_or_first_available_variant.metafields.subscriptions.discount_variant_id }}"
                 data-variant-interval-value="{{ p_annual.metafields.subscriptions.shipping_interval_frequency }}"
                 data-variant-interval-unit="{{ p_annual.metafields.subscriptions.shipping_interval_unit_type }}"
                 data-quickadd-id="{{ p_annual.selected_or_first_available_variant.id }}"
                 data-quickadd-properties
             >
                        {{ p_annual.selected_or_first_available_variant.price | money_without_trailing_zeros }}{{ section.settings.productlink1label }}
             </button>
        {% endif %}

The code grabs the item by the ID and makes an AJAX request.
// quick add
    _document.on('click', '[data-quickadd-id]', function() {
        let _this = $(this);

        loadingBarTrigger('start');

        itemAdd(
            _this.attr('data-quickadd-id'),
            _this.attr('data-quickadd-properties'),
            (_this.attr('data-quickadd-quantity'))
                ? _this.attr('data-quickadd-quantity')
                : 1,
            (!html.is('#cart')) ? true : false,
            (html.is('#cart')) ? true : false
        );
    });

inside of cart function:
onst itemAdd = (variantId, properties, qty, openCart, reloadPage) => {
        $.ajax({
            type: 'POST',
            dataType: 'html',
            url: `/cart/add.js`,
            data:
                {
                    id: variantId,
                    quantity: qty,
                    properties: (properties)
                        ? JSON.parse(properties) : null
                },

            error: function(data) {
                console.error(data);

                loadingBarTrigger('done');
            },
            success: function() {
                loadingBarTrigger('move');

                $.ajax({
                    url: '/cart',
                    dataType: 'html',
                    error: function(data) {
                        console.error(data);

                        loadingBarTrigger('done');
                    },
                    success: function(data) {
                        let minicartContent = $('#minicart-content');
                        let cartItemsHtml = $(data).find('#cart-content #cart-items').html();

                        // insert or prepend cart HTML
                        (minicartContent.find('#cart-items').length)
                            ? minicartContent.find('#cart-items').html(cartItemsHtml)
                            : minicartContent.prepend(cartItemsHtml);

                        // remove giftbox content if exists
                        (minicartContent.find('#cart-giftbox .item-info').length)
                            ? minicartContent.find('#cart-giftbox .item-info').remove()
                            : '';

                        loadingBarTrigger('done');
                        cartTotalUpdate();

                        // open cart
                        (openCart && !html.is('#cart'))
                            ? minicartTrigger.trigger('click') : '';

                        (reloadPage)
                            ? location.reload() : '';
                    }
                });
            }
        });
    }

I know this is possible with the AJAX API update last year. But I'm unsure how to implement it in my store. The data-variant-id only accepts one value if I'm not mistaken. And what's data-variant-id comes first gets precedence. I guess the main thing is that I'm unsure how to send json with the submit button.
Any ideas?

A: In a classic add product form, you can replace:
<input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}" disabled> with:
<input type="hidden" name="items[0][quantity]" value="1">
<input type="hidden" name="items[0][id]" value="ID_OF_YOUR_FIRST_PRODUCT_VARIANT">
<input type="hidden" name="items[1][quantity]" value="1">
<input type="hidden" name="items[1][id]" value="ID_OF_YOUR_SECOND_PRODUCT_VARIANT">

If you want to add the products in ajax, you just have to use the "FormData" object in the body of the request:
let addToCartForm = document.querySelector('form[action$="/cart/add"]');
let formData = new FormData(addToCartForm);
fetch(window.Shopify.routes.root + 'cart/add.js', {
  method: 'POST',
  body: formData
})
.then(response => {
  return response.json();
})
.catch((error) => {
  console.error('Error:', error);
});

A: I think you need to check and default Shopify documentation and make changes to the code according to the documentation.
Here into documentation they clearly mentioned how you can add multiple product using AJAX API.
https://shopify.dev/docs/themes/ajax-api/reference/cart

So you can check and update the code and past the multiple variants to items array like this demo code.
jQuery.post('/cart/add.js', {
  items: [
    {
      quantity: quantity,
      id: 1st ID
    },
    {
      quantity: quantity,
      id: 2nd ID
    },
    {
      quantity: quantity,
      id: 3rd ID
    }
  ]
});


text:
Q: extjs store proxy not invoking for xtype I have a popup window that has some xtypes, one xtype is a grid and that has a Store but i dont see it invoking any ajax call. Can someone tell me what am i missing?
Ext.define('myApp.view.myPopup' {...
....
{
            xtype: 'grid',
            store: 'MyStore',
            iconCls: 'x-fa fa-users',
            height : 450,
            columns: [{
                header...

...}

Store
Ext.define('myApp.store.MyStore', {
    extend: 'Ext.data.Store',
    model: 'myApp.model.modelA',
    pageSize: 100,
    remoteSort: true,
    autoload : true,
    proxy: {
        type: 'ajax',
        url : 'getStatusId',
        reader: {
            type: 'json',
            root: 'rows',
            successproperty: 'status',
            totalProperty: 'records'
        }
    },
    listeners : {
        beforeload : function(store, operation, eOpts) {
            ...
            store.getProxy().extraParams = submitParams;
        }
    }

});

A: You have a typo: autoload -> autoLoad.
Your code also doesn't show an instance of the store being created. store: 'MyStore' requires an existing store instance with a storeId: 'MyStore'.
You probably want something more like:
Ext.define('myApp.view.myPopup' {...
....
{
            xtype: 'grid',
            store: { type: 'myStore' },
            iconCls: 'x-fa fa-users',
            height : 450,
            columns: [{
                header...

...}

Ext.define('myApp.store.MyStore', {
    extend: 'Ext.data.Store',
    alias: 'store.myStore',
    model: 'myApp.model.modelA',
    // ....
});

A: Create an instance of store and point to it.
 var store = Ext.create('myApp.store.MyStore' {
                autoLoad : true,
            });
..........

    {       xtype: 'grid',
            store: store,
            iconCls: 'x-fa fa-users',
            height : 450,

    }

A: Like @evan-trimboli states out you have to either use an excisting store instance or you can use a config. The config will then lead to a new store instance created for you internal.
To use a config to create a store instance on the fly, you need to provide an alias on the store class e.g. alias: "store.mystore".
Now you can reference to it in the store config of the grid class like store: { type: 'myStore' }.
Bring it all together below and see also a running fiddle.
Ext.define('myApp.store.MyStore', {
    extend: 'Ext.data.Store',
    alias: 'store.mystore',  // the alias we need for the store config of the grid
    // ...
});

Ext.define('myApp.view.myPopup', {
    extend: 'Ext.grid.Panel',
    store: {
        type: 'mystore' // references the store by it's alias
    },
    // ...
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get axios error post/request payload on catch when I catch an axios error, how can i get the request body? (what I've sent to the server, not the server response)
example of what i want to achieve
axios.post("url",{
    name:jesus
}).then((response) => {
    ....
}).catch((error) => {
    console.log(error.request.body)  //name:jesus
})

A: You can access the original request data via error.config.data. Note that it will be the serialised format (in your case JSON) so you may need to parse it back into a JS object.

axios
  .post("http://httpbin.org/status/400", {
    name: "jesus",
  })
  .then((res) => {
    console.log("response", res);
  })
  .catch((error) => {
    const data = JSON.parse(error.config.data);
    console.error("request data", data);
  });
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>


text:
Q: tf.matmul doesn't works as expected i try to write and (logic operation) in tensor flow , there are two inputs and two weights multiply them to get one number and add this number to bias, my problem in matmul a send X (input) and W (weight) to method in shape .
[[1],
[1]]
for X (vertical), and [0.49900547 , 0.49900547] for W (horizontal) to get one number as result but it's give me two numbers , how i can make is multiply right ??
this is my code >>
import tensorflow as tf
import numpy
rng = numpy.random

# Parameters
learning_rate = 0.01
training_epochs = 2000
display_step = 50

# Training Data
train_X = numpy.asarray([[[1.0],[1.0]],[[1.0],[0.0]],[[0.0],[1.0]],[[0.0],[0.0]]])
train_Y = numpy.asarray([1.0,0.0,0.0,0.0])
n_samples = train_X.shape[0]

# tf Graph Input
X = tf.placeholder("float",[2,1],name="inputarr")
Y = tf.placeholder("float",name = "outputarr")

# Create Model

# Set model weights
W = tf.Variable(tf.zeros([1,2]), name="weight")
b = tf.Variable(rng.randn(), name="bias")

# Construct a linear model
activation = tf.add(tf.matmul(X,W), b)
mulres = tf.matmul(X,W)

# Minimize the squared errors
cost = tf.reduce_sum(tf.pow(activation-Y, 2))/(2*n_samples) #L2 loss
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #Gradient descent

# Initializing the variables
init = tf.initialize_all_variables()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        #Display logs per epoch step
        if epoch % display_step == 0:
            print "Epoch:", '%04d' % (epoch+1),  \
                "W=", sess.run(W), "b=", sess.run(b) , "x= ",x," y =", y," result :",sess.run(mulres,feed_dict={X: x})

    print "Optimization Finished!"
    print  "W=", sess.run(W), "b=", sess.run(b), '\n'

    # Testing example, as requested (Issue #2)
    test_X = numpy.asarray([[1.0,0.0]])
    test_Y = numpy.asarray([0])

    for x, y in zip(train_X, train_Y):
        print "x: ",x,"y: ",y
        print "Testing... (L2 loss Comparison)","result :",sess.run(mulres, feed_dict={X: x})
        print sess.run(tf.matmul(X, W),feed_dict={X: x})
        print "result :"
        predict = sess.run(activation,feed_dict={X: x})
        print predict

A: As with standard matrix multiplication, if A has shape [m, k], and B has shape [k, n], then tf.matmul(A, B) has shape [m, n] (m rows, n columns in the order TensorFlow uses).
In your program, you are computing tf.matmul(X, W). X is defined to be a placeholder with shape [2, 1]; W is defined to be variable initialized to a [1, 2] matrix of zeros. As a result, mulres = tf.matmul(X, W) will have shape [2, 2], which is what is printed (result: ...) when I run your code locally.
If you want to define a hidden layer with a single output, the change is simple:
W = tf.Variable(tf.zeros([1,2]), name="weight")

...should be replaced with:
W = tf.Variable(tf.zeros([2, 1]), name="weight")

(Indeed, initializing your weights to tf.zeros will prevent it from training, because all of the input elements will get the same gradient in backpropagation. Instead, you should initialize them randomly, for example using:
W = tf.Variable(tf.truncated_normal([2, 1], stddev=0.5), name="weight")

This will enable the network to learn different values for each component of the weight.)

A: matmul operates directly on the tensors which in your case have 2 rows and 1 column.
There is an argument in matmul to transpose either entry like:
matmul(X, W, transpose_a=True)

You can check out the docs here: docs


text:
Q: Raspberry PI/PHP + Arduino serial communication I'll try to give a brief summary of the project and then the current code approach.

*

*I have a RPi all set up with the latest Stretch OS.

*I have installed MySQL, PHP, APahce and PhpMyAdmin and it working correctly.

*I have it booting up to the default (locally hosted) webpage and in full screen (KIOSK) mode.

*DB created, tables populated, queries in place.. and the webpage (drink menu) is displaying correctly as expected.

*

*I have my Arduino UNO connected to the RPI via USB

*The webpage displays a bunch of menu options.. each with its own 'order' button.

*When any order button is clicked.. I save this button data to a hidden field, and use jQuery to submit/post the form (to itself)

*Upon $_POST I grab this submitted data, and send it out via PHP over serial comm 1.

And here is where I am currently.

*

*Since my Arduino is connected via USB to the RPi. I can not use the serial monitor to debug things.... do I have any other options here?

*When I submit the webpage.. I -do- see the RX/TX lights on the Arduino  blinking (leading me to believe it is receiving the serial data)..  I can/will check if it is correct tonight by hooking up the stepper motor again and see if ti moves to the correct position(s)...
Here is where I am stuck/stumped a bit.. and could use some discussion to get me on the right path.
So after the Arduino 'does its magic'.. it is supposed to send a confirmation message back to the RPi.. saying the drink is complete.. and I can go back to the main drink menu awaiting another order
Because the webpage has already $_POSTed..and the serial data sent to the connected Arduino.. .. I then leave the page displaying a 'please wait' message...   but because the page is already parse on the server side of things, I am left with the need on how to 'listen' to the serial posrt via PHP now.
I figured.. I could use some AJAX to call/load an external php script.. that will just wait/listen to the serial port.. and return the data to the AJAX 'success' callback.
But as I have never done this before.. I'm kind of leery if this will work.. or if this is even the correct way to do so.
Also random questions about the best place(s) to open and close the port.. especially if there is 2 separate scripts?  (ie: can I open the port in one script.. and still access it in another? or does that file accessing it.. need to be the one that opens it?)
Here is my current snippet to handle the sending and waiting/listening of the serial port:
[code]
<?
if ($mode == 'submit') {

    //grab posted data (save to var)
    $drinkRecipe = $_POST['selectedDrink'];

    //set-up com port
    exec("mode /dev/ttyACM0 BAUD=9600 PARITY=N data=8 stop=1 xon=off");
    //saw this on several RPi posts?  (but not sure of the difference? or why one would be used over the other?)
    //stty -F /dev/ttyACM0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

    //open serial port
    $fp = fopen("/dev/ttyACM0", "w+"); //w = write w+ = read/write

    //check if open
    if (!$fp) {
        echo "Not open";
        //die();
    } else {
        //if open send data (via PHP) to connected Arduino on serial comm port 1 (ttyACM0)
        fwrite($fp, '<' . $drinkRecipe . '>');

        //arduino takes serial data, parsed it.. does it duty,
        //and is supposed to reply back via serial to the awaiting (listening)
        //PHP script executed via AJAX, since the front end needs to display
        //a 'waiting' type message.. and the callback 'success' will
        //re-direct back to menu/initial state
        ?>

        <?

        //close connection
        fclose($fp); //needed? //should this go in the external php script instead now?

    }

}

Not even sure what should go into the: serial_listener.php script yet... just a while loop or something? Waiting for data? or end of file or something?  (not sure how that works using fread() on serial port?)
Any suggestions to try and wrap my head around this is appreciated.
Update:  I'm not sure if I am not explaining things correctly/clearly?
But when the page submits (to itself).. that is when the OUTGOING serial data is sent to the connected (via USB to the RPi) Arduino....
When the page 'posts' it sends the above data OUT..  and then displays a 'please wait' type of message.
At this point (as far as I understand it).. the server side script/parse is now COMPLETE...  and I am left with a page saying 'please wait'...
There is no more parsing/server side ANYTHING going at this point..
That is why I thought/brought up the use an AJAX call to an external script that can sit and 'wait' (listen) to the serial port  (un-clear as to how best going about this... a while() loop or something?)...
and then when the data eventually comes back...
*

(which there is no telling how long it will take for this 'serial
  feedback' from the Arduino.. as each drink takes different amounts of
  time to create).........

*
it will use the AJAX 'success' callback function to then update the page.. and ultimately just re-direct it back to the main drink menu page again.. to start all over.
I dont feel the use of timeout() or delay() on the Arduino is not only bad advice (ie: never use delay() if can help it).....  but I dont even see where/why that makes any sense?

Update:
And the contents of the serial_listener.php script: (script the AJAX snippet calls)
//set-up com port
exec("mode /dev/ttyACM0 BAUD=9600 PARITY=N data=8 stop=1 xon=off");

//open serial port
$fp = fopen("/dev/ttyACM0", "w+"); //w = write w+ = read/write

//check if open
if (!$fp) {
    echo "Not open";
    //die();

} else {

    while(!feof($fp)){
        $response = fread($fp, 10);
    }
    echo $response;
    fclose($fp);

}

Final update:
I re-wrote things to use the AJAX call to SEND my data.. and also wait for the response.
The external php script the AJAX call executes is the ONLY place the port gets opened now (and I am not closing it)
Here is the SUBMIT state of the PHP form that has the AJAX call:
The sending of data works 100% of the time.. but I can NOT read my response.
if ($mode == 'submit') {

    //grab posted data (save to var)
    $drinkRecipe = $_POST['selectedDrink'];

    ?>

Please wait, your brink is being made.

    <?
}

Here are the contents of the serial_listener.php script the AJAX call executes:
//data sent from AJAX call (works)
$drinkData = $_POST['drinkData'];

//open serial port
$fp = fopen("/dev/ttyACM0", "w+"); //w = write w+ = read/write  (works)
//$fp = fopen("/dev/ttyUSB0", "w+"); //w = write w+ = read/write  //tried with USB-TTL cable too.. couldnt even send data)

//check if open
if (!$fp) {
    echo "Not open";
    //die();
} else {

    if($drinkData != ''){
        //send drink data
        fwrite($fp, '<' . $drinkData . '>');

        //wait for response
        $chars = "";
        do{
            $char = fread($fp, 1);
            $chars .= $char;
        }while(strlen($char) < 1);
        echo $char;
    }else{
        echo 'drink recipe is empty';
    }
}

A: Can't comment to make a suggestion (no reputation)
I have no knowledge on Ajax , jquery, Raspberry Pi or PHP but...
If you have a Serial to USB TTL device like this you can use the SoftwareSerial library. Set up SoftwareSerial on a couple of unused digital pins on the arduino and send debugging info out there.
Not an answer, but a suggestion.
*********Edit***********
Come to think of it, doesn't the Raspberry Pi have a serial port?
If so you don't need the USB converter. Just set up a softwareSerial port on the Arduino and use that to connect to the Pi. Taht way you can use the USB port to send debug coms to your computer.

A: First, I dont have expirience with Raspberry nor Arduino, but do have played with serial communication in the past.
You are making things waay too complicated. Serial communication is not some strange animal from history channel - take it as a data layer. You would easely create needed front- and backend IF data would come from/go to database? Now, implement your system exactly same way, just instead of database connection use Serial communication.
Your serial_listener is simple:

*

*create/configure port

*send data

*read data

*close port

So, whole case:
frontend --post(d)--> serial_listener::COM1::send(d) ... COM1::read('OK') -->reply 'success'
PS.
with those small controllers... timeout() is your real friend ;)
And for serial communication I would suggest to use some library (e.g. php_serial.class)

I try to clarify with a code. I try to keep it as simple, just to illustrate the system as a whole.
Frontend, pure js/html and AJAX request:
<!DOCTYPE html>

Content: forms/scripts/...

        <button type="button"
            onclick="makeSerialCall('serial.php')">order (send AJAX call to php script)
        </button>

Serverside:
<?php
if(!empty($_POST))
  $data = $_POST["data"];

include "php_serial.class.php";

$serial = new phpSerial();
$serial->deviceSet("/dev/ttyUSB0");
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");

$serial->deviceOpen();
$serial->sendMessage($data);
$read = $serial->readPort();
$serial->deviceClose();

header('Content-type: application/json');
$response_array['status'] = 'success';
$response_array['info'] = 'some additional info:'.$read;
echo json_encode($response_array);
?>

This way you have "loading.." image on the screen until response. Initial rendered page is there all the time. Ofcourse, you need alot of (error)checking, solution when there's no response from serial etc.etc. But basic system is not "rocket science".


text:
Q: Rebinning data in Excel I have some wind data in excel that is binned by wind speed and direction.  I want to re-bin it to cover different intervals (assuming the data is uniform across the original intervals). i.e I want to go from:

To

Can anyone give me some pointers?  Struggling to think of an elegant way to do this.


text:
Q: redundant results are saved when using Export-CSV I have a working script for detecting Log4j but trying to export all the result to CSV.
The current script was able to export but is giving me multiple rows of exact result.
$hostnames = "PC1"
foreach ($hostname in $hostnames){

Write-Host "Starting..."

$List = Invoke-Command -ComputerName $hostname  {Get-ChildItem 'C:\' -Recurse -Force -Include *.jar -ea 0 | foreach {select-string "JndiLookup.class" $_} | select -exp Path}

if ($List -ne $null)
{
    $List1 = [system.String]::Join("`r`n", $List)

    $file_location = "C:\Powershell\log4j-test.csv"

    $global:name = @{N="Computer Name";E={$hostname}}
    $global:lists = @{N="Affected Location";E={$List1}}

    Write-Host "Done.."

    $name, $lists | Export-CSV $file_location -noTypeInformation -Force -Append -Encoding UTF8

}

}

A: You're probably looking for something like this:
[pscustomobject] @{
  'Computer Name' = $hostname
  'Affected Location' = $List -join "`r`n"
} | Export-CSV $file_location -noTypeInformation -Force -Append -Encoding UTF8

Note that each single CSV row created in each iteration will (potentially) span multiple lines, due to using newlines ("`r`n") as separators in the Affected Location column.

As for what you tried:

*

*Your hashtable literals (e.g. @{N="Computer Name";E={$hostname}}) use the syntax of a calculated property, yet you're not using a cmdlet - typically Select-Object - that is capable of creating calculated properties.

*More generally, Export-Csv and ConvertTo-Csv in Windows PowerShell do not meaningfully support hashtables as input objects - you'll need to provide [pscustomobject] instances instead, which you can easily create by casting[1]  a hashtable literal to [pscustomobject], as shown above

*

*By contrast, in PowerShell (Core) 7+ you may now use hashtables directly as input, though you'll probably want to use [ordered] hashtables for predictable column ordering.

[1] Strictly speaking, the form [pscustomobject] @{ ... } isn't a cast, but built-in syntactic sugar for creating [pscustomobject] instances as literals. This is evidenced by the fact that the key-definition order in the hashtable literal is maintained in this case, whereas it isn't in stand-alone hashtable literals.


text:
Q: Как можно сделать систему уровней в дискорд? Каким образом я могу сделать систему уровней за актив в чата(много сообщений)?

A: Вы можете использовать DiscordSuperUtils.
Вот простой пример, в котором уровни участников хранятся в базе данных:
import discordSuperUtils
import sqlite3
from discord.ext import commands

database = discordSuperUtils.DatabaseManager(sqlite3.connect("database"))
bot = commands.Bot(command_prefix='-')
LevelingManager = discordSuperUtils.LevelingManager(database, 'xp', bot)

@bot.event
async def on_ready():
    print('Готов.')

@LevelingManager.event()
async def on_level_up(message, member_data):
    await message.reply(f"Ты повысил левел до {member_data['rank']}")

@bot.command()
async def rank(ctx):
    member_data = LevelingManager.get_member(ctx.author)
    await ctx.send(f'Твой левел: **{member_data["rank"]}**, с **{member_data["xp"]}** XP.')

bot.run("token")


text:
Q: Bizarre behaviour in simple Delphi code I am passing TProcessItem structure as a return value from my function. While in GetProcessFromHandle function, the ExeFile property of the structure returned by FindByID, contains the expected executable name, but in the structure returned by GetProcessFromHandle it somehow becomes empty. I added two Messageboxes to demonstrate it. Is anyone able to explain what is happening here?
function GetProcessFromHandle(hWnd: HWND): TProcessItem;
var
  ProcessInfo: TProcessInfo;
  PID: Cardinal;
begin
  Result := nil;
  GetWindowThreadProcessId(hWnd, @PID);
  ProcessInfo := TProcessInfo.Create(nil);
  try
    Result := ProcessInfo.RunningProcesses.FindByID(PID);
    if Assigned(Result) then ShowMessage(Result.ExeFile); //first message
  finally
    ProcessInfo.Free;
  end;
end;

procedure Test;
var
  Process: TProcessItem;
begin
  Process := GetProcessFromHandle(FindWindow(nil, 'My App'));
  if Assigned(Process) ShowMessage(Process.ExeFile); //second message
end;

A: The TProcessInfo object owns the TProcessItem object that GetProcessFromHandle() is returning a pointer to.  As such, when the TProcessInfo object is freed, so is the TProcessItem object, and thus the pointer being used by Test() is invalid.  So you run into undefined behavior.  You are lucky your code did not just crash instead.
If you want to return the path to the EXE file, return only that value, eg:
function GetProcessExeFileFromHandle(hWnd: HWND): string;
var
  ProcessInfo: TProcessInfo;
  ProcessItem: TProcessItem;
  PID: DWORD;
begin
  Result := '';
  GetWindowThreadProcessId(hWnd, @PID);
  ProcessInfo := TProcessInfo.Create(nil);
  try
    ProcessItem := ProcessInfo.RunningProcesses.FindByID(PID);
    if Assigned(ProcessItem) then
      Result := ProcessItem.ExeFile;
  finally
    ProcessInfo.Free;
  end;
end;

procedure Test;
var
  ProcessExeFile: string;
begin
  ProcessExeFile := GetProcessExeFileFromHandle(FindWindow(nil, 'My App'));
  ShowMessage(ProcessExeFile);
end;


text:
Q: I am trying to post data in stream parameter of WCF method from Jquery. But not working I have made a WCF service method to upload the file on the server and wanted to pass other relevant values as well along with stream but from jquery i am unable to short out that how can i do that.
Here is my WCF method.
    public void UploadCustomFile(RemoteFileInfo request)
    {

        string FilePath = Path.Combine(HostingEnvironment.MapPath("~/Downloads"), "abc");
        int length = 0;
        using (FileStream writer = new FileStream(FilePath, FileMode.Create))
        {
            int readCount;
            var buffer = new byte[8192];
            while ((readCount = request.FileByteStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                writer.Write(buffer, 0, readCount);
                length += readCount;
            }
        }

    }

Here is my RemoteFileInfo Class :
[DataContract]
    public class RemoteFileInfo : IDisposable
    {
        [DataMember]
        public string FileName;

        [DataMember]
        public long Length;

        [DataMember]
        public System.IO.Stream FileByteStream;

        public void Dispose()
        {
            if (FileByteStream != null)
            {
                FileByteStream.Close();
                FileByteStream = null;
            }
        }
    }

and Here is the jquery+html,

        <input type="file" id="fileUpload" value="" />

        <button id="btnUpload" onclick="UploadFile()">
            Upload</button>

    <button id="btnDownload" onclick="DownloadFile()">
        Download</button>

Also Here is the json request Body which i suppose to use while posting the data from jquery side,
{
    "FileByteStream":{
        "__identity":{
            "__identity":{
                "__identity":null
            }
        }
    },
    "FileName":"String content",
    "Length":9223372036854775807
}

A: You aren't even sending the file...you are sending an empty FormData object.
As for including both you need to use FormData.append(key, value) to set each part of what you want to send be it file or data
you can also pass a whole form element into new FormData(formelement)


text:
Q: Gallery child count Есть галерея с миниатюрками картинок. При создании активити мне нужно поменять фон первых двух миниатюр на экране.
Проблема в том, что getChildCount() возвращает 1 для этого состояния. Всего отображено, к примеру 9-10 миниатюр.
Какой юзкейс тут применить?
UPD
Впринципе, я зря заморачивался с чайлдами.
Все просто и решение ниже. В адаптере, getView():
if( conf.orientation == Configuration.ORIENTATION_LANDSCAPE ){
    if( position == 0 || position == 1){
        view.setBackgroundColor(Color.parseColor("#0099cc"));
    }
}
else {
    if( position == 0 ){
        view.setBackgroundColor(Color.parseColor("#0099cc"));
    }
}

ибо, в методе подсветки все равно делаю так:
public void highlightSelectedThumbs(Gallery bigPages, Gallery thumbPages){
        ...

    for(int i = 0; i < thumbPages.getChildCount(); i++) {
        thumbPages.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
    }

A: Надо делать рекурсию по чайлдам, скорее всего картинки обернуты сверху ViewGroup, который вы видите. Возьмите от него еще getChildCount()


text:
Q: Eliminate mismatch between two GeoTIFF satellite images I have two GeoTIFF satellite images of the same area made on different dates (both are in the same CRS). When I open the images in QGIS, I can see that objects (buildings, etc.) have slightly different coordinates (e.g., a building can be about 20 meters apart from the same building on the other image).
How can I change one of the images to minimize that distance?
I am probably looking for a library that can match the images automatically and shift one of them, or for a tool where it can be done manually (shifting an image and matching objects on both images).
Since the error/shift is different in different parts of the image, I am thinking about splitting both images into tiles and then aligning them tile by tile, so some sort of automated way of doing it would be preferred.
UPDATE:
This is not a duplicate question because it is about matching two satellite images of the same area which (at least in theory) can be achieved with, say, a library using a machine learning based solution.
The other question is about matching a vector layer (a shape file) and a satellite image. I do not expect any fully automated solution there. In case of a manual solution, it probably goiong to be a different tool/approach.


text:
Q: Spring WebFlow future and version This is more to Spring Team supporting Spring WebFlow --
What is the Spring WebFlow road-map.  Can you describe its version convention how come it differs from rest of the core Spring Offerings.
Ex Spring 4 support offered in Spring WebFlow 2.4 not 3.
Why did it stay at version 2.X and not moved to 3?
Also I heard a rumor that Spring WebFlow will not be supported is this true?
Thanks.


text:
Q: Altering UI colour within ArcMap I was wondering if anyone knows if it's possible to change the colours of the user interface within ArcMap?
Specifically the background and text colours of the table of contents and the ArcCatalog/Toolbox Windows etc.
I've done some of my own extensive searching online as well as searching through the questions here on the site and haven't found anything helpful relating to it.
So me educated guess would be that it's not possible but I still wanted to get a definitive answer either way.

A: ArcMap takes color and font settings from the Windows theme, so strictly speaking, you can change those. It's a system wide setting, though. I included a screenshot from ArcMap with the High Contrast theme included with Windows 8.1.

If you want to change ArcMap only, then it would need to be programmed (if you're a developer yourself, search for 'intercept wndproc').


text:
Q: How should I restrict direct url access to a form mail script in perl-cgi? My project is running on a apache server on CentOS.
My project is one-page site that contains a form that send mail when submitted.
I wrote that form mail script in Perl CGI.
It is able to send mail when submitted but I want to restrict the direct URL access to that mail script.
How should I do, please?

A: You can't.
Some people tell you that you can do it by looking at the HTTP Referer in the request. But that can be faked.


text:
Q: Cross-Origin PATCH and DELETE requests blocked by Spring Boot application, but not GET requests I have the below security configuration in my Spring-Boot app at the moment. This is the standard stuff I've found online to allow all CORs requests (there are a lot of other configurations online that I've also tried).
These work fine for GET requests, however PATCH and DELETE requests are still being blocked due to CORs policy. Has anyone experienced this before?
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
    }
}

A: Right, so I fixed this with the below configuration, however there is a caveat to it: I'd tried this before, however I the first import suggestion for CorsFilter was not the correct one (org.apache.catalina.filters.CorsFilter). This time, I imported the second instead (org.springframework.web.filter.CorsFilter) and this now works.
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
    }

    @Configuration
    public class CorsConfig {

        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin("http://localhost:3000");
            config.addAllowedHeader("*");
            config.addAllowedMethod("POST");
            config.addAllowedMethod("GET");
            config.addAllowedMethod("PATCH");
            source.registerCorsConfiguration("/**", config);
            return new CorsFilter(source);
        }
    }
}

A: You can add the global support for CORS by creating the following bean
@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*");
        }
    };
}

A: You can use addAllowedMethod to add additional method in default allowed methods(GET, HEAD, POST)
CorsConfiguration corsConfig = new CorsConfiguration().applyPermitDefaultValues();
corsConfig.addAllowedMethod(HttpMethod.DELETE);
corsConfig.addAllowedMethod(HttpMethod.PUT);

http.cors().configurationSource(request -> corsConfig);

A: On more recent versions of Spring Security if you look at the CorsRegistration allowedMethods() you'll see
/**
 * Set the HTTP methods to allow, e.g. {@code "GET"}, {@code "POST"}, etc.
 *
The special value {@code "*"} allows all methods.
 *
By default "simple" methods {@code GET}, {@code HEAD}, and {@code POST}
 * are allowed.
 */
public CorsRegistration allowedMethods(String... methods) {
    this.config.setAllowedMethods(Arrays.asList(methods));
    return this;
}

That by default only GET, HEAD, and POST are allowed.
Adding the additional methods or all ... which might look something like this
@Profile(value = { "LOCAL" })
@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("/**")
                        .allowedMethods("*") <-- This is the ticket
                        .allowedOrigins("*")
                ;
            }
        };
    }
}

Should do the trick


text:
Q: How to use `FindResourceEx()` and `LoadResource()` to load a new menu? I am developing a multilingual Win32 program in C using the Windows API. It will allow the user to choose the language of the interface. In accordance to the MSDN documentation, I need to use FindResourceEx() + LoadResource() and not the unreliable SetThreadLocale().
My problem is: I do not know how to load the menu from the resources.
Considering the example code below, how should it be modified to load and update the menu?
HMENU hMenu = GetMenu(hWnd);
SetMenu(hWnd, NULL);
DestroyMenu(hMenu);

HRSRC rcMenu = FindResourceEx(NULL, RT_MENU, MAKEINTRESOURCE(IDM_MENU),
    MAKELANGID(LANG_AFRIKAANS, SUBLANG_AFRIKAANS_SOUTH_AFRICA));

hMenu = LoadResource(NULL, rcMenu); /* ??? HGLOBAL used as a HANDLE? */
SetMenu(hWnd, hMenu);

A: The alternative solution suggested in the commands (separate DLL resource files per-language) is a good option and one we use ourselves. However to answer your question:
The LoadMenuIndirect() function lets you create a menu (user object) from a resource template. It's the template that's loaded from resources.
For example (no error checking),
HRSRC hRes = FindResourceEx(NULL, RT_MENU, MAKEINTRESOURCE(IDM_MENU),
    MAKELANGID(LANG_AFRIKAANS, SUBLANG_AFRIKAANS_SOUTH_AFRICA));
HGLOBAL hGlob = LoadResource(NULL, hRes);
LPVOID pData = LockResource(hGlob);

// create the menu
HMENU hMenu = LoadMenuIndirect((MENUTEMPLATE*)pData);


text:
Q: C# - Cannot tag a random number with a statement So i'm working on a revision tool that'll ask defined questions randomly using console command C#. I can create the random number but cannot seem to use the Switch function properly. Can anyone help?
           // The random Object
        Random Number = new Random();

         while (true)
        {
            int Question = Number.Next(1);
            Console.WriteLine("{0}", Question);
            string Answer = Console.ReadLine();

            if (Answer.ToLower() == "finished")
            {
                break;
            }

            if(Answer.Length == 0)
            {
                Console.WriteLine("Write Please");
                continue;
            }

            switch (Question)
            {
                case 0:
                    {
                            Console.WriteLine("What is the nucleus of an atom made of");
                            if (Answer == "neutrons and protons")
                            {
                                Console.WriteLine("Well Done!");
                            }
                            if (Answer == "protons and neutrons")
                            {
                                Console.WriteLine("Well Done!");
                            }
                             Console.WriteLine("Try Again");
                        break;
                    }
            }

        }
    }
}

}

A: Your code is quite strange; for example you are trying to read a response before you have even printed a question.  However, your immediate question relating to the random number is simple.
You are using int Question = Number.Next(1);.  According to MSDN:

Returns a non-negative random integer that is less than the specified maximum.

since you are storing the number as an int, and you have 1 as the specified maximum, you will always receive 0 from this assignment.  I would assume that you have other case statements in your switch, and if you use the number of questions you have rather than 1, your switch will work.  You will still have other issues with things printing in the wrong order, though....


text:
Q: ClassNotFound launchig maps activity declared in Android library I am getting this exception when trying to start an activity (TestLocationActivity) that is derived from MapActivity, and which is declared inside an Android library project:
09-08 09:29:45.357: ERROR/AndroidRuntime(7502): java.lang.NoClassDefFoundError: msumo.business.testlocation.impl.view.TestLocationActivity
09-08 09:29:45.357: ERROR/AndroidRuntime(7502):     at msumo.app.test2.impl.Test2AppManagerImpl.loadNewScreen(Test2AppManagerImpl.java:94)
09-08 09:29:45.357: ERROR/AndroidRuntime(7502):     at msumo.business.common.GuiAppManager.handleMessage(GuiAppManager.java:101)
09-08 09:29:45.357: ERROR/AndroidRuntime(7502):     at msumo.core.MessageBus.dispatchMessage(MessageBus.java:338)
09-08 09:29:45.357: ERROR/AndroidRuntime(7502):     at msumo.core.MessageBus$1.doWork(MessageBus.java:251)
09-08 09:29:45.357: ERROR/AndroidRuntime(7502):     at msumo.core.util.WorkerThread.run(WorkerThread.java:29)

I can not find the source of the problem. I have included in both AndroidManifest.xml of main application and library project the Google Maps library declaration:
 <uses-library android:name="com.google.android.maps" />

In Eclipse I get no error and application launches normally, but when trying to start the indicated Activity it fails. The chunck of code that starts the activity is the following one:
    Intent intent = new Intent(ctx, TestLocationActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    ctx.startActivity(intent);

I have no clue about what can be wrong. Is it maybe impossible to use a Google APIs library from an Android Library project?
Update

I found some System traces that could help clear the situation:
09-08 10:53:34.615: INFO/dalvikvm(13221): Rejecting re-init on previously-failed class Lmsumo/platform/location/impl/LocationModuleImpl$2; v=0x0
09-08 10:53:34.654: WARN/System.err(13221): java.lang.NoClassDefFoundError: msumo.platform.location.impl.LocationModuleImpl$2
09-08 10:53:34.654: WARN/System.err(13221):     at msumo.platform.location.impl.LocationModuleImpl.doUseBestProvider(LocationModuleImpl.java:189)
09-08 10:53:34.654: WARN/System.err(13221):     at msumo.platform.location.LocationModule.performQuery(LocationModule.java:329)
09-08 10:53:34.662: WARN/System.err(13221):     at msumo.platform.location.LocationModule.handleMessage(LocationModule.java:543)
09-08 10:53:34.662: WARN/System.err(13221):     at msumo.core.MessageBus.dispatchMessage(MessageBus.java:338)
09-08 10:53:34.662: WARN/System.err(13221):     at msumo.core.MessageBus$1.doWork(MessageBus.java:251)
09-08 10:53:34.669: WARN/System.err(13221):     at msumo.core.util.WorkerThread.run(WorkerThread.java:29)
09-08 10:53:34.685: WARN/System.err(13221): java.lang.NoClassDefFoundError: msumo.platform.location.impl.LocationModuleImpl$2
09-08 10:53:34.685: WARN/System.err(13221):     at msumo.platform.location.impl.LocationModuleImpl.doUseBestProvider(LocationModuleImpl.java:189)
09-08 10:53:34.685: WARN/System.err(13221):     at msumo.platform.location.LocationModule.performQuery(LocationModule.java:329)
09-08 10:53:34.693: WARN/System.err(13221):     at msumo.platform.location.LocationModule.handleMessage(LocationModule.java:543)
09-08 10:53:34.693: WARN/System.err(13221):     at msumo.core.MessageBus.dispatchMessage(MessageBus.java:338)
09-08 10:53:34.693: WARN/System.err(13221):     at msumo.core.MessageBus$1.doWork(MessageBus.java:251)
09-08 10:53:34.693: WARN/System.err(13221):     at msumo.core.util.WorkerThread.run(WorkerThread.java:29)

A: If you want to use the MapView provided by google you need to complete 3 steps:

*

*Obtain an Api Key for your debug and deploy certificate and use the right one inside your app

*Use an Emulator or Device that comes with the Google API. During creation of an AVD you can choose if the device should be with or without the Google Libraries.

*Register the usage of the Google Maps Library in your Manifest. This is done through adding:
<uses-library android:name="com.google.android.maps" />
to the application tag of your manifest. Be sure that the uses library is inside the application tag and not only in your manifest

A: Did you register TestLocationActivty in your manifest?

A: maybe this can help you.
Did you register to obtain a Maps API Key? This may be the reason for your problem.

A: Just a guess: have you chosen the right SDK for your project? You have the choice of every version twice. One with Google API and one without and to use maps, you should used the version with Google API.


text:
Q: Nginx fails to serve files from 9p I have a VM with a 9p share and nginx. It worked fine until I updated my VM to Debian 10. Since then, it fails to serve files from my 9p share. Nginx returns an empty response and
2020/09/11 09:57:49 [alert] 864#864: *449 pread() read only 4096 of 32768 from "/9p/test.png" while sending response to client
Files under 4096 work. Anything over 4096 will fail. It always says 'read only 4096 of xxxx'. File cache isn't enabled. What could cause this?

A: One reason could be that 9p driver in guest kernel is incompatible with the 9p driver on host.
Try using same kernel on both guest and host.


text:
Q: Developing a web app with ZK, IntelliJ and Maven I would like to create a web app with the ZK framework with Maven and the IntelliJ IDE.
I can't find any tutorial that can help me on this. Do you have any tips?

A: Add zk as maven dependency. Then go to zk home page and read documentation.
But i guess using Zk-Studio, means use eclipse, is a better idea.


text:
Q: I got Cannot read property 'name_restaurant' of undefined When I tried to return thedetails of each restaurant on my detail page I've created a dynamic routing for a ProductDetail page (each Restaurant has its own details that should be shown on this page). the routing is working but I don't get any data and I can't figure out the right way to get data from firestore by the Id of each restaurant.
PS: the product details are rendering in the console but the problem still how to display to the detailpage
ProductDetail.js

import { firestore } from "../../../../../fire";
import {useParams} from "react-router-dom";
import {useEffect} from "react";
import {useState} from "react";
import {Fragment} from "react";

function ProductDetail() {
  const {productId}= useParams();

  const [product,setProduct]=useState();

  useEffect( () =>  {

   firestore
     .collection("Restaurants")
     .doc(productId).get()
     .then( doc => {
       console.log(doc.data());
       setProduct(doc.data());

     });

   }, () => {

 }
 );

  return (

{product.name_restaurant}

Price:$

        {/*
{product.email}
 */}

  );
  }
export default ProductDetail;

this my console : all details of the restaurant are returned

Still cannot return details on my page

I got this error

A: This happens because when you first render the component your product state variable is null, then you make the API call in the useEffect, your state variable is populated and the component is re-rendered, but at that point, you already have the error. To fix it, you  just have to render your markup when the product is ready to be rendered (not null)
return product ? (

{product.name_restaurant}

Price:$

        {/*
{product.email}
 */}

  ) :
Loading...
;

A: SOLVED By adding an ? to product and that's to check undefined {product?.name_restaurant}


text:
Q: How to mock ASP.NET 3.5 to unit test my web controls? I want to mock ASP.NET 3.5 behavior in order to unit test my WebControls: I want to test how they perform with mock data with existing system of events. Basically I want to test generated result HTML based on input mock data.
How to do it?
I looked into NMock, but it doesn't suit my needs for 2 reasons:

*

*It just runs ASP.NET server in
separate process in order to get
resulting HTML;

*My WebControls output HTML as a text
on render, so there are elements
which do not correspond to any
ASP.NET control (except
LiteralControl in some cases).

Also, I have huge legacy system, so rewriting everything for MVC won't work for me (too much job), I need to write unit tests to existing controls.

A: Unit testing is really ideal for middle-tier and back-end code which can be called without regard to the environment or context.  The more you can separate out your code and build environmental/contextual requirements into parameters the easier and more reliable it is to test.
Unit testing UI code is not as straightforward.  Typically the best thing is to separate the pure UI code (html generation in this case) from the UI-related logic code into a View and ViewModel classes.  However, you said you have a large codebase and can't make major changes.
Therefore it's probably appropriate to look at the next step beyond unit testing.  Use a UI-based regression testing tool to do UI automation and verification.


text:
Q: What is the difference between USB 2.0 and USB 3.0? I want to buy a Pen Drive and a HDD. For both case I get two categories. USB2.0 and USB 3.0.
I wish to ask my T.V. is compatible with USB 2.0 pen drive. I wish to buy USB 3.0 pen drive. But that is much costlier than USB 2.0.
also please let me know If  USB 3.0 Pen drive is compatible with USB 2.0 ?

A: *

*USB 2.0 has a max speed of 480mbps while USB 3.0 has a max speed of 4.8gbps (Roughly 1 gbps = 1000 mbps).

*USB 3.0 devices are Green Devices, meaning they use less power and are more efficient/stable.

*USB 3.0 devices are capable of communicating their latency speeds to their host for better transfer speeds.

*USB 3.0 devices leave eSATA and Bluetooth technologies far behind, and are the next generation devices.

USB 3.0 devices will work on USB 2.0 ports, but getting a USB 3.0 compatible machine or host is far more expensive than getting a USB 3.0 device. Ideally you should be buying a 3.0 device, buy if you aren't planning to run it on a 3.0 compatible host, you might as well get a 2.0 device. Another [cheaper] option includes buying a PCI-E x1 card with USB 3.0, which run fairly cheap (I've seen one for $10 with a molex connector). Then you only get enough ports for what you need.

A: You can use a USB 3 device in a USB 2 socket, but it will be limited to USB 2 speeds.
USB 3 is much faster (10x) than USB 2, it has the same 4 pins as USB 2 and a set of extra pins for USB 3, but in the same physical form factor (the plugs are the same)
You can use a USB 2 device in a USB 3 socket, and vice versa quite happily. But you'll be speed limited in both scenarios.
Additionally, the USB 2 spec dictates that a single device cannot draw more than 500ma, for USB 3 this is increased to 900ma. For self-powered devices or very small devices like pendrives this isn't a issue - but is a significant benefit for larger devices like external hard drives, or for charging other devices.


text:
Q: why do C functions work even without importing the libraries they are written in? int main()
{
    srand(time(0));
    int minimo = rand();
    int generato;

    while(1)
    {
        generato = rand();
        if(generato < minimo)
        {
            minimo = generato;
            printf("%d\n", minimo);
        }
    }
    return 0;
}

this code works perfectly on my computer without importing any library. I just wrote it how you see here and it compiled and ran succesfully with no errors.
I'm using a c11 std-GNU compiler

A: Due to the history of C, some compilers still allow use of functions without declaring them. When an identifier is used to call a function, a default declaration of a function without a prototype (the number and types of parameters are unspecified) return int is provided. If the function does indeed return int, as rand and printf do, and the arguments after default argument promotions match the actual types of the parameters, this works. It may also work if the function does not return anything (has return "type" void, as srand does).
The 1990 C standard said, in clause 6.3.2.2:

… If the expression that precedes the parenthesized argument list in a function call consists solely of an identifier, and if no declaration is visible for this identifier, the identifier is implicitly declared exactly as if, in the innermost block containing the function call, the declaration
extern int identifier();
appeared.

This was dropped in the 1999 C standard.

I'm using a c11 std-GNU compiler

If you mean you are using GCC, then I would expect it to issue warnings at least, in its default mode or if -std=c11 is used.
You should not use this "feature." It exists to support old source code, and its acceptance in default compiler settings is questionable.

A: When I compile this code on my computer, with no special options, I get lots of warnings:
$ cc test.c
test.c: In function 'main':
test.c:3:5: warning: implicit declaration of function 'srand' [-Wimplicit-function-declaration]
    3 |     srand(time(0));
      |     ^~~~~
test.c:3:11: warning: implicit declaration of function 'time' [-Wimplicit-function-declaration]
    3 |     srand(time(0));
      |           ^~~~
test.c:4:18: warning: implicit declaration of function 'rand' [-Wimplicit-function-declaration]
    4 |     int minimo = rand();
      |                  ^~~~
test.c:13:13: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
   13 |             printf("%d\n", minimo);
      |             ^~~~~~
test.c:13:13: warning: incompatible implicit declaration of built-in function 'printf'
test.c:1:1: note: include '<stdio.h>' or provide a declaration of 'printf'
  +++ |+#include <stdio.h>
    1 | int main()

I suspect you saw similar messages and ignored them because you got an executable anyway.  It is very dangerous to do that with C.  For historical reasons, a whole lot of diagnostics that should be hard errors are only warnings with most C compilers.  Therefore, until you have a lot more experience with the language, you should treat all warning messages as if they were hard errors.
Since it sounds like you're using GCC, I recommend you use this set of options until you get more experience:
    -g -Og -std=gnu11 -Wall -Wextra -Wpedantic -Wstrict-prototypes -Werror

They turn on a bunch more diagnostics that ought to be hard errors but, again for historical reasons, aren't printed at all by default, and promote all of them to hard errors.  Adjust the optimization level (-Ox) as you see fit, and maybe add more warning options (there's a huge list in the manual) but don't take anything out.
(You need to turn on some level of optimization to get all of the diagnostics.  Yes, really.)
(I advise against using the hyperconformant -std=c11 mode until you get more experience; it enables things you actively don't want (like trigraphs) and has a nasty tendency to break the system headers.)


text:
Q: Как записать N чисел в 1 строке Иван Васильевич пришел на рынок и решил купить два арбуза: один для себя, а другой для тещи. Понятно, что для себя нужно выбрать арбуз потяжелей, а для тещи полегче. Но вот незадача: арбузов слишком много и он не знает как же выбрать самый легкий и самый тяжелый арбуз? Помогите ему!
Входные данные
В первой строке входного файла INPUT.TXT задано одно число N – количество арбузов. Вторая строка содержит N чисел, записанных через пробел. Здесь каждое число – это масса соответствующего арбуза. Все числа натуральные и не превышают 30000.
Выходные данные
В выходной файл OUTPUT.TXT нужно вывести два числа через пробел: массу арбуза, который Иван Васильевич купит теще и массу арбуза, который он купит себе.

A: Здесь банальный поиск максимума и минимума. Сортировка не нужна от слова совсем. Вот пример кода
filer=open("input.txt","r")
n=int(filer.readline())
numbers=[ float(x) for x in filer.readline().split()]
filer.close()
zmax=numbers[0]
zmin=numbers[0]

for i in range(n):
    if numbers[i]>zmax:
        zmax=numbers[i]
    if numbers[i]<zmin:
        zmin=numbers[i]

filer=open("output.txt","w")
out=str(zmin)+" "+str(zmax)
filer.write(out)
filer.close()

input.txt
10
1.2 2 0.4 2 3 4 8 2.1 1 3.2

output.txt
0.4 8.0

A: Сплитом разделяете значения по ключу ( в вашем случае это пробел) - имеете несортированный массив.
Сортируете любым удобным для вас способом. И array[0] это будет Васильича арбуз, а array[N-1] арбуз для любимой тещи

A: вот начало кода:
n = int(input('Количество арбузов'))
mas = [float(a) for a in input('Веса арбузов через пробел: ').split()]

получается что будет создан массив(mas) в котором в каждой новой ячейке будет вес арбуза
пример:
>>>mas = [float(a) for a in input('Веса арбузов через пробел: ').split()]
Веса арбузов через пробел: 0.9 2.2 5.1 3.1 1 4.2
>>>print(mas)
[0.9, 2.2, 5.1, 3.1, 1.0, 4,2]

ну вы потом отсортируйте и возьмите последний элемент(mas[-1]) для Ивана а для тёщи предпоследний элемент(mas[-2])
>>> mas = [4.1, 1.1, 0.9, 2.7]
>>> print(mas)
[4.1, 1.1, 0.9, 2.7]
>>> mas.sort()
>>> print(mas)
[0.9, 1.1, 2.7, 4.1]


text:
Q: change the color of text inside text box how to change the color for the text inside the text box......
gave the color property but its not working....
providing my code and fiddle below
http://jsfiddle.net/Zkdfq/1/embedded/result/
<form class="navbar-form pull-right">
              <input class="span2" type="text" placeholder="Email">
              <input class="span2" type="password" placeholder="Password">
              <button type="submit" class="btn">Sign in</button>
            </form>

A: Just add:
input[type="text"] {
    color:red;
}

somewhere after the bootstrap.css to override it. The placeholder text will not change, but once you enter text it will.
Or if you only want it to affect the nav bar:
.navbar-form input[type="text"] {
    color:red;
}


text:
Q: How do browser speeds vary in applying inline v. internal v. external CSS? Regarding inline v. internal v. external CSS, I understand the cacheing issues, and the tradeoff between multiple downloads and single downloads of larger files. What I would like to know is how rendering speed varies, based on the three places you can put CSS.
In other words, what takes the least time to actually draw the page? I assume that external is the slowest, because even if it's cached, the browser still has to retrieve the rules, parse them, and apply them to the current elements. I also assume that internal (in the page but inside style tags) would be second slowest, because there's still the process of parsing the rules and determining which rules to apply to which elements. And I assume that inline (applied directly via style attribute) is the fastest, because the browser can skip the process of matching rules to elements.
Anybody ever looked at this in depth? I know that I've had some rendering problems on large pages with complex CSS that could only be solved by going inline. (Please, no lectures on the evils of large pages with complex CSS.)

A: either way, once the actual rule text is loaded, it's run through the same css parser - there aren't different parsers for external v.s. internal css. it's all just css. External might be a bit slower to get applied because it'll require an extra HTTP request to fetch that file, but once it's transferred to the host browser, it'll parse just as fast as if you'd physically embedded the same rules in an inline <style> block.

A: I don't think you should care which mode is fastest. HTML, CSS and JS are not meant to be fast in any case.
I think you should worry about readability and maintainability, think about managing a webpage with styles directly applied inside HTML tags. You wouldn't be able to manage anything complex in that way.
What you are asking mainly depends on browser implementation (with respect to the css file that could be downloaded separately according to which solution we are talking about). In any case I don't think the difference is so much considerable just because they all need to be parsed by the same parser.
If a page is really too complex to be styled with a stylesheet and requires inline style then the problem should be solved not by having inline css but refactoring things at a different level.
In addition I would say that many performance issues could be caused by writing CSS just without any kind of structure, just adding things day by day without even considering having strict/clever selectors. Developing things while thinking about them (that is something that is usually left behind in web development, especially with front ends) usually is the best way.


text:
Q: Creating and Writing txt files in Android studio ( Java Code ) I'm trying to create files and write arrray's values on it and I don't have errors in my code most probably there is some exception that i can not see.
Here is my code :
        for (int i = 0; i < groups.size(); i++) {
        try{
           Log.d("a" , "broj grupa " + groups.size());
           h = "C" + (i+1) + ".txt" ;
           // File root = new File(Environment.getExternalStorageDirectory(), "Notes");
           File root = new File(Environment.DIRECTORY_DOWNLOADS +h);
            if (!root.exists()) {
                root.mkdirs(); // this will create folder.
               // root.createNewFile();
            }
            File filepath = new File(root, h );
            FileWriter writer = new FileWriter(filepath);

            for(int ii=0 ; ii < groups.get(i).size(); ii++)
            {
                //  System.out.println(groups.get(i).get(ii)+"\n");
                String broj = groups.get(i).get(ii).toString();
                Log.d("ima li podataka ovamo ", broj);
                writer.write(broj);
                writer.flush();

            }

            writer.close();

        }
        catch(IOException e){
         e.toString();
        }
    }

And Main Activity :
                public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    long [] array = new long[142];

    int kkkod;
    try {

        // OPENING THE REQUIRED TEXT FILE
        BufferedReader reader = new BufferedReader(new InputStreamReader(
           getAssets().open("renkhex.txt")));

        String myLine = reader.readLine();
         int i = 0;

        while (myLine != null) {

            String heksakodbezpraznina = myLine.replaceAll(" ", "");
            //Log.d("a da li je  to : " ,  heksakodbezpraznina);
             kkkod = Integer.parseInt(heksakodbezpraznina, 16);
           // Log.d("to je" , "integer vrednost = " + kkkod);
            array[i]= kkkod;
            i=i+1;
            myLine = reader.readLine();

          }

      reader.close();

    }
    catch (IOException e) {
             Toast.makeText(getApplicationContext(),
                "Error Opening the File !!!", Toast.LENGTH_LONG).show();
    }

    new  KMeans(3,142,array) ;

}

}
Here is my LogCat :
         Process: hesh.rtxt, PID: 2119
java.lang.RuntimeException: Unable to start activity ComponentInfo{hesh.rtxt/hesh.rtxt.MainActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
        at android.app.ActivityThread.access$800(ActivityThread.java:135)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5001)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
        at hesh.rtxt.KMeans.<init>(KMeans.java:98)
        at hesh.rtxt.MainActivity.onCreate(MainActivity.java:59)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)

 When I run program it's not stoping, also It writes to much Output to process.


text:
Q: How to limit row number in pagination with select option I have a page is already pagination. But now i want to implement new feature:
when we select number of rows in select box. The webpage will be show matching data. I tried it with ajax. A limit variable has been send, but controller can not get it to process. Can anyone help me!
here is sample image
html code:
<form method="post">
<select name="select_limit" id="select_limit">
     <option value="10">10</option>
     <option value="100">100</option>
</select>
</form>

ajax code:
$(document).ready(function() {
    $('#select_limit').change(function() {
        var limit = $("#select_limit option:selected").val();
        $.ajax({
            type: "POST",
            cache:false,
            url:"<?php //link to controller ?>",
            //send data
            data:{'limit': limit},
            });
    });
});

and in controller, I get a limit variable the same normal code:
$limit = $_POST['select_limit'];

A: You are sending data:{'limit': limit}, and you try to get $_POST['select_limit']; so you are trying to get a POST value that you are not sending. Try $_POST['limit'];

A: maybe you need not to use ajax, you can try:
$(document).ready(function() {
    $('#select_limit').change(function() {
        $(this).closest('form').submit();
    });
});

// use get method, and form action should be same url like pagination link
<form method="get">
  <select name="select_limit" id="select_limit">
     <option value="10" <?php echo $limit == 10 ? 'selected' : ''?>>10</option>
     <option value="100" <?php echo $limit == 100 ? 'selected' : ''?>>100</option>
  </select>
</form>

this sloution will refresh the page.

edit

==================================================================
and add the &limit=<?php echo $limit?> to the link like:
 <li class="<?php  if($crr_page=$i) echo 'active' ?>">
      <a href="<?php echo $this->url->get('dashboard/list-user') ?>?page=<?php echo $i ; ?>&txt_keyword=<?php echo $keyword; ?>&limit=<?php echo $limit?>"><?php  echo $i  ?>


text:
Q: how can i find where syscall ( some number ) routine? I am working on a self compiled linux kernel. The person who modified the kernel has added some syscalls. What I want to do is knowing where does the actual routine (.c file) for the that specific number is i.e. syscall(300), so how would I know where is the routine for the 300 ?
More elaboration: syscall should know what file, which is a compiled .c file, to invoke when I do syscall (300), I want to see that .c file.
I am usuing Ubuntu 9.10
Look forward for your input,

A: The file syscall_table.S should contain the list.

A: Let's see how the system call implemented on x86_32 (look there):
 500 ENTRY(system_call)
 501        RING0_INT_FRAME                 # can't unwind into user space anyway
 502        pushl_cfi %eax                  # save orig_eax
 503        SAVE_ALL
 504        GET_THREAD_INFO(%ebp)
 505                                        # system call tracing in operation / emulation
 506        testl $_TIF_WORK_SYSCALL_ENTRY,TI_flags(%ebp)
 507        jnz syscall_trace_entry
 508        cmpl $(NR_syscalls), %eax
 509        jae syscall_badsys
 510 syscall_call:
 511        call *sys_call_table(,%eax,4)
 512        movl %eax,PT_EAX(%esp)          # store the return value
 [...]

As you see there is a system call dispatch instruction here at line 511:
call *sys_call_table(,%eax,4)

So, the first thing you'll need to do is to get the sys_call_table address. The next thing is to get $(NR_syscalls) value. And the last thing is simple - iterate over all the sys_call_table values.
If you have gdb, vmlinux and /proc/kcore you can do the following:
# gdb vmlinux /proc/kcore

Besides that you can use objdump -rd vmlinux to dump the disassembly of your kernel.


text: Q: I am getting the node_module like problem how to resolve this Vue in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/Landing.vue, ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/Signin.vue and 1 other


text:
Q: will keeping same version of jar in ear lib and war lib creates issue? I am keeping of same version of jar inside war/lib and ear/lib.
Could you please let me know whether this will create any issues.

A: Better to have your common libs in EAR/lib , since Web module can access the JARs on EAR/lib. Also another option to have your common libraries in you application server ext/lib folder but then you have to separately send those when releasing EAR which is also not a good practice.
BIG.ear
 +-- lib (contains common libs for all modules)
 +-- META-INF
 |    +-- application.xml (lists modules myWEB.war and myEJB.jar)
 |    +-- MANIFEST.MF
 +-- myEJB.jar
 |    +-- META-INF
 |    |    +- ejb-jar.xml
 |
 |         +-- ...
 +-- myWEB.war
      +-- META-INF
      |    +-- MANIFEST.MF
      +-- WEB-INF
      |    |+-- lib (3rd party libs only used by .war)
      |    +-- web.xml
      +-- index.html


text:
Q: Batch-convert throws System.Security.SecurityException I've got following .bat-file which is proposed to open a fully working java_cmd portable task.
@echo off
cd /d "%~dp0"
:: cd ..\CommonFiles
:: set Path=%cd%\bin;%path%

set Path=%~d0\PortableApps\CommonFiles\bin;%path%

:: set "JAVA_HOME=%~d0\PortableApps\CommonFiles\jre"

set "JAVA_HOME=%~d0\PortableApps\CommonFiles"

nircmd regsetval dword "HKCU\console" "QuickEdit" "1" >nul 2>&1

cd /d "\Documents\workspaces\java"

start "Java_cmd" cmd /k "cs -w 100x25 -b 100x3000"

I have translated to the following as far:
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using con = System.Console;

namespace javacmd
{
    class Program
    {
        const int HWND_BROADCAST = 0xffff;
        const uint WM_SETTINGCHANGE = 0x001a;

        [DllImport("user32", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam);

        static string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        static string drive = Path.GetPathRoot(codeBase);
        static string oldjavahome = "";

        static int Main(string[] args)
        {
            PrintOutStart();
            string args0 = null;
            try
            {
                if (args == null || args0 == "?" || args0 == "/?" || args0 == "--?" ||  args0 == "help" || args0 == "/help" || args0 == "--help")
                {
                    return PrintOutHelp();
                }
                else
                {
                    args0 = args[0];
                }
            }
            catch
            {
                return PrintOutHelp();
            }
            if (args0 != null)
            {
                if (!File.Exists(args0+ ".java"))
                {
                    con.WriteLine($"Error: FileNotFound!\nDie Datei {args0} wurde nicht gefunden. Bitte überprüfen Sie, dass\nSie den Namen richtig geschrieben haben!");
                    con.WriteLine("");
                    con.Write("Drücken Sie eine beliebige Taste . . .  ");
                    con.ReadLine();
                    return 1;
                }
                else
                {
                    string javahome = Path.Combine(drive, @"PortableApps\CommonFiles");
                    string javabin = Path.Combine(drive, @"PortableApps\CommonFiles\bin");

                    using (var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
                    {
                        var ojh = key.GetValue("JAVA_HOME");
                        if (ojh != null)
                        {
                            oldjavahome = ojh.ToString();
                            if (oldjavahome != javahome)
                            {
                                key.SetValue("JAVA_HOME", javahome);
                            }
                        }
                        var path = key.GetValue("path");
                        if (path != null)
                        {
                            if (!path.ToString().Contains(javabin))
                            {
                                key.SetValue("Path", javabin + ";" + path);
                            }
                        }
                        SendNotifyMessage((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, (UIntPtr)0, "Environment");
                    }
                    Process p = new Process() { StartInfo = new ProcessStartInfo() { FileName = "javac", Arguments = $"{args0}.java", CreateNoWindow = true, RedirectStandardOutput = true } };
                    try
                    {
                        p.Start();
                        p.WaitForExit();
                        con.WriteLine($"output javac: \"{p.StandardOutput}\"");
                    }
                    catch
                    {
                        con.WriteLine("Error while compiling!\nFehler während des Kompilier-Vorgangs!");
                        con.WriteLine("");
                        con.Write("Drücken Sie eine beliebige Taste . . .  ");
                        con.ReadLine();
                        return 1;
                    }
                    p.StartInfo.FileName = "java";
                    p.StartInfo.Arguments = args0;
                    try
                    {
                        p.Start();
                        p.WaitForExit();
                        con.WriteLine($"output java: \"{p.StandardOutput}\"");
                    }
                    catch
                    {
                        con.WriteLine("Fehler während des Start-Vorgangs!");
                        con.WriteLine("");
                        con.Write("Drücken Sie eine beliebige Taste . . .  ");
                        con.ReadLine();
                        return 1;
                    }
                }
            }
            else
            {
                con.WriteLine("Der benötigte Parameter \"args0\" hat den Wert \"null\". Bitte versuchen Sie es erneut!");
                con.WriteLine("");
                con.Write("Drücken Sie eine beliebige Taste . . .  ");
                con.ReadLine();
                return 1;
            }
            return 0;
        }

        private static void PrintOutStart()
        {
            con.WriteLine("");
            con.WriteLine("###################################################");
            con.WriteLine("#                                                 #");
            con.WriteLine("#                     javacmd                     #");
            con.WriteLine("#                                                 #");
            con.WriteLine("###################################################");
            con.WriteLine("");
        }

        private static int PrintOutHelp()
        {
            string name = Path.GetFileNameWithoutExtension(codeBase);
            con.WriteLine("Der javacmd compiliert und startet eine angegebene .java-Datei mit nur einem Befehl.");
            con.WriteLine("");
            con.WriteLine("Syntax: " + name + ".exe [name | [  | / | --]? | [  | / | --]help]");
            con.WriteLine("");
            con.WriteLine("  name\t\t\tDie zu startende Datei (ohne die Endung \".java\").");
            con.WriteLine("  [  | / | --]?\t\tZeigt die Hilfe an. Dies entspricht einer Eingabe ohne Optionen.");
            con.WriteLine("  [  | / | --]help\tZeigt die Hilfe an. Dies entspricht einer Eingabe ohne Optionen.");
            con.WriteLine("");
            con.WriteLine("Wird der javacmd ohne Argument aufgerufen, zeigt er diese Hilfe an.");
            con.WriteLine("");
            con.Write("Drücken Sie eine beliebige Taste . . .  ");
            con.ReadLine();
            return 1;
        }
    }
}

The problem is that it throws a System.Security.SecurityException whilst opening the reigstry key. I think this is caused by missing admin rights - which I don't get on all computers I wanna use the program. How do I get this code running the same as the batch code?
My program is located in \Documents\workspaces\java where Documents is a child of (root) usb drive.
Thanks in advance!


text:
Q: Usage of "being" in sentence Why is being used in the sentence below, and what does it mean?

Lisa is upset about not being invited to the party

Are they trying to use the passive voice?
If yes, how would the sentence look if we use the active voice to frame the same sentence?

A: The example sentence is

*

*Lisa is upset about not being invited to the party
There are two clauses.
The main clause

*

*Lisa is upset about np[S]
has a psych predicate adjective upset (which requires an auxiliary be),
and a gerund complement clause indicating the source of the upset, namely

*

*(Lisa('s)) not being invited to the party
(Note that the subject of not being invited has to be Lisa.)
The subject is deleted under identity with the subject of be upset.
So we'll never know whether it was sposta be Lisa or Lisa's; both are possible.
(they're called the ACC-ing and POSS-ing complementizers, respectively.)
OK, so what is the purpose of being in the complement?
Well, it turns out that the complement is a passive construction,
and passive constructions require some form of the auxiliary verb be,
followed by a past participle.
That's the

*

*being invited
part. Being is a form of be, and invited is a past participle.
That explains why it's a form of be, but it doesn't explain why being was the form chosen.
The reason is that the predicate in the main clause,

*

*is upset about
takes a gerund complement, and the gerund form of be is being.
See the Verb Phrase Study Guide for further details.

A: While this is a case of active versus passive, it is complicated by the use of a gerund.  Being is a gerund, a verb form used as a noun. The full verb in this case is being invited

Lisa is upset about clowns
Lisa is upset about being a clown

The phrase being a clown is a noun phrase using the gerund being.
The phrase not being invited is a gerund phrase that is basically passive in its intent.  Lisa is not the one doing the inviting, it is someone else.
If you wanted to transform it to an active voice, you need to bring in the person doing the inviting.

Lisa is upset that her friend did not invite her to the party.
or
Lisa's friend upset her by not inviting her to the party [preserving the gerund form].

A: being invited is the gerund form of to be invited, as you suggested, a passive construct. If I were to write this sentence, I would make it more clear by writing the following.
Lisa is upset by her not being invited to the party.

However, more likely, I would opt for a that clause instead. The following switched to the active voice.
Lisa is upset that she was not invited to the party.

Conversion to the active voice directly would be the following.
Lisa is upset by the host's not inviting her to the party.

A: This is passive voice because the expression in English uses the passive voice:
to be invited to a party.
to be swindled by a coworker.
to be driven to work
Without the infinitive, one says:
Being invited to parties is fun.
Being swindled by coworker is terrible.
Being driven to work is not fun.
Now, you can mix and match all those with other verbs of emotion:
to be happy/upset about by or about, was happy about
to be annoyed by, was annoyed by
to be angry about, was angry
Just trying to elucidate the structure while avoiding too much tech talk.

A: The forms of the gerund and participle
The gerund has four forms — two for the active voice and two for the passive. The forms for the participles are the same.
----------------Active--------------------Passive
Present ----loving-------------------being loved
Perfect------having loved---------having been loved
From en.wikipedia, gerund  Link
"about not being invited" is the preposition about + a gerund, the negative gerund present passive. Another gerund present passive would be:
(the) being chosen.


text:
Q: Mongoose/MongoDB batchSize(30) still returning all results The following query returns all my users. I was hoping it would be batched.
statics.findAllUsers = function findAllUsers(callback) {
  this.find({}, callback).batchSize(30);
};

A: batchSize() instructs the driver to retrieve a certain number of items per time. It'll still get everything from the DB, only a batch at a time.
To make it clearer: If you use batchSize(30) then it'll ask for 30 items then, when you need the 31st, it'll query the next 30 and so forth.
If you need only that number of items, then use limit() (and offset() to set which is the first item)
Docs: http://docs.mongodb.org/manual/reference/method/cursor.batchSize/


text:
Q: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY' in NODE JS While Calling the third party API (https://) I am trying to call third party HTTP API from my node express app, but am getting the error:
       at TLSSocket.onConnectSecure (_tls_wrap.js:1055:34)
       at TLSSocket.emit (events.js:198:13)
       at TLSSocket._finishInit (_tls_wrap.js:633:8) code: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY' ```

node: "8.9.3"
windows 10
I have tried

*

*generated the certificate from openssl

*npm config set strict-ssl true

*npm config -g set cafile C:\Users\youruser\.certificates\yourcertname.crt
I don't know what I am missing


text:
Q: Custom image button with clicked functionality I know this is a stupid question but a google search did not give me a good answer. I have a button in my activity but when I press it, I cannot visually see it. Although the button works just fine. I know I have to do something in the xml file but I'm not sure what. Is there a way to automatically make the image button change slightly without me having to manually upload two pictures?

A: You can disable the button if u want by using
   button.setEnabled(false);

& can also be enabled again using
   button.setEnabled(true);

EDIT:
You can also try by changing the background color of Button by
 onClick()
 {
  button.setBackgroundColor(#CCCCCC);
 }

A: import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * Applies a pressed state color filter or disabled state alpha for the button's background
 * drawable.
 *
 * @author shiki
 */
public class SAutoBgButton extends Button {

  public SAutoBgButton(Context context) {
    super(context);
  }

  public SAutoBgButton(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public SAutoBgButton(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  public void setBackgroundDrawable(Drawable d) {
    // Replace the original background drawable (e.g. image) with a LayerDrawable that
    // contains the original drawable.
    SAutoBgButtonBackgroundDrawable layer = new SAutoBgButtonBackgroundDrawable(d);
    super.setBackgroundDrawable(layer);
  }

  /**
   * The stateful LayerDrawable used by this button.
   */
  protected class SAutoBgButtonBackgroundDrawable extends LayerDrawable {

    // The color filter to apply when the button is pressed
    protected ColorFilter _pressedFilter = new LightingColorFilter(Color.LTGRAY, 1);
    // Alpha value when the button is disabled
    protected int _disabledAlpha = 100;

    public SAutoBgButtonBackgroundDrawable(Drawable d) {
      super(new Drawable[] { d });
    }

    @Override
    protected boolean onStateChange(int[] states) {
      boolean enabled = false;
      boolean pressed = false;

      for (int state : states) {
        if (state == android.R.attr.state_enabled)
          enabled = true;
        else if (state == android.R.attr.state_pressed)
          pressed = true;
      }

      mutate();
      if (enabled && pressed) {
        setColorFilter(_pressedFilter);
      } else if (!enabled) {
        setColorFilter(null);
        setAlpha(_disabledAlpha);
      } else {
        setColorFilter(null);
      }

      invalidateSelf();

      return super.onStateChange(states);
    }

    @Override
    public boolean isStateful() {
      return true;
    }
  }

}

To use this, just replace your original button declarations like this:
<Button
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:background="@drawable/button_blue_bg"
  android:text="Button with background image" />

do this:
<com.buttondemo.SAutoBgButton
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:background="@drawable/button_blue_bg"
  android:text="Button with background image" />

Here's a sample output using this custom button:
Hope its worked


text:
Q: The view xxx didn't return an HttpResponse object. It returned None instead I have an error I do not understand because the logic I use in my view has not changed and works for my other project. And when I read the Django doc, my logic's view is conform: https://docs.djangoproject.com/fr/2.2/topics/forms/#the-view

We call the form's is_valid() method; if it's not True, we go back to the template with the form. This time the form is no longer empty (unbound) so the HTML form will be populated with the data previously submitted, where it can be edited and corrected as required.

In my form, I have validation control.
My clean method below have 3 validations controls and the control #2 raised
errors

__all__

Ce patient ne peut être randomisé dans ce site. Veuillez vérifier votre saisie.

So in my understanding of the doc, it should be redirected to the completed form with errors message display (as it do usually in my project) even if there is no else condition for no valid form in my view(is_valid() == False).
What is wrong?
views.py
def randomization_edit(request):
    if request.method == "POST":
        print("request", request.POST.dict())
        form = RandomizationEditForm(request, data=request.POST or None)
        if form.is_valid():
            # do stuff
            return redirect('randomization:confirmation', pk=randomisation.pk)

    else:
        if request.session.get('user_can_randomize'):
            form = RandomizationEditForm(request)
            return render(request, 'randomization/edit.html', {'form': form})
        else:
            return redirect("home")

forms.py
   def clean(self):
        cleaned_data = super(RandomizationEditForm, self).clean()
        # control #1
        if Randomisation.objects.filter(pat=self.data.get('pat').upper()).exists():
            bras = Randomisation.objects.get(pat=self.data.get('pat').upper()).bra_lib
            raise forms.ValidationError("Ce patient a déjà été randomisé dans le bras " + bras + ". Veuillez vérifier votre saisie.")
        # control #2
        if Pays.objects.get(pay_abr=self.data.get('pat').upper()[0:2]).pay_ide != int(self.data.get('pay_ide')):
            raise forms.ValidationError("Ce patient ne peut être randomisé dans ce site. Veuillez vérifier votre saisie.")
        # control #3
        if not patient_code_is_valid(self.data.get('pat').upper()):
            raise forms.ValidationError("Il y a incohérence entre le site et le pays dans le numéro patient. Veuillez vérifier votre saisie.")
        return cleaned_data

A: If you make a POST request, and the form is not valid, you do not return any result. In that casee, one normally rerenders the template with the form containing the errors:
def randomization_edit(request):
    if request.method == 'POST':
        form = RandomizationEditForm(request, data=request.POST)
        if form.is_valid():
            return redirect('randomization:confirmation', pk=randomisation.pk)
    else:
        if not request.session.get('user_can_randomize'):
            return redirect("home")
        else:
            form = RandomizationEditForm(request)
    return render(request, 'randomization/edit.html', {'form': form})
The return render(…) will thus return a HTTP response in case it is a GET requjest with a user_can_randomize value for the session, or in case you make a POST request, and the from is not valid.


text:
Q: Why can't gcc see a static constexpr array in struct when initializing? I was building an static constexpr array in a class which references previously defined elements in the same array.  I've tried before without problems, but I've found that gcc is having some issues finding the array's symbol name when it is within a struct.
struct Y {
  static constexpr char command_info[8][5][(6)*2] = {
    {
      { 0, 0 , 0,0},
      { 0, 0 , 0,0},
      { 1, 0 , 1 , static_cast<char>(command_info[0][2] [ (0 +1)*2 - 1 ] + command_info[0][2] [ (0 +1)*2 - 2 ]) , 0,0},
      { 2, 0 , 1 , static_cast<char>(command_info[0][3] [ (0 +1)*2 - 1 ] + command_info[0][3] [ (0 +1)*2 - 2 ]), 1, static_cast<char>(command_info[0][3] [ (1 +1)*2 - 1 ] + command_info[0][3] [ (1 +1)*2 - 2 ]) , 0,0},
      { 1, 0 , 1 , static_cast<char>(command_info[0][4] [ (0 +1)*2 - 1 ] + command_info[0][4] [ (0 +1)*2 - 2 ]) , 0,0},
    },
  };
};

The Demo shows simplified expanded code, removing other constexpr variables and functions.
Moving this definition outside of the struct works fine.  Is there something wrong with gcc or am I doing something illegal here?


text:
Q: Performance of voting system (with account) implemented by using Mysql + PHP I'm currently creating a voting system with good and bad option for a comment. Basically, the idea is like facebook's one, but have a bad option(or more) for the comment. Here is the table structure
id | comment_id | voter_id | voter_option

So, once the user vote it, a record will be store in the mysql database on the above format, why I'm doing this is because I don't want the user re-vote, and want to record what they like/dislike.
my question is, I think, if there have 10,000 comments in my website, and each comments got 1,000 votes, then my database is become very large, are there any good method(example maybe) to prevent the database become too large? Or I need to create a table for each comments in my case, thanks in advance.

A: What does your comments table look like? The database will only get large if there's many posts, 10,000 entries in a table is childsplay for mysql if you query correctly and your table is a sane size.
Performance wise, it may be an idea that when someone likes/dislikes a comment, you do a tally of all the votes and store that value in the comment row, this way when you query out the comment you'll have its last known like/dislike count and don't have to do that counting each time you query for comments.
Edit: I should add, make sure your indexes are ints (judging by the column names they are) and you're using foreign keys for data restraints. With foreign keys you can keep your tables clean, for example, if someone deletes a comment you can tell your tables to delete cascade, based on that id, so the comment gets deleted, all of the votes for that comment get deleted from the other table. http://en.wikipedia.org/wiki/Foreign_key


text:
Q: PHP : How to manage "Document labelled UTF-16 but has UTF-8 content" error on simplexml_load_string() Language: PHP 7.3 / Laravel 6.*
Problem: My system receive email from third parties that contain information about a potential customer. One of them send us data that contain UTF-16 tag but the content is UTF-8.
Goal: I want to let the system try the data as it receive it. Then, if an error occur, try something else. I don't want to change the UTF-16 string on every request.
Code:
$input = $request->all();
try {
    $xml = simplexml_load_string($input['body-plain']);
    throw new Exception();
} catch(Exception $e) {
    try {
        $input['body-plain'] = str_replace("UTF-16", "UTF-8", $input['body-plain']);
        $xml = simplexml_load_string($input['body-plain']);
        throw new Exception();
    } catch(Exception $e) {

    }
}
$prospect = $xml->prospect;

Error:

simplexml_load_string(): Entity: line 1: parser error : Document labelled UTF-16 but has UTF-8 content

    try {
        $xml = simplexml_load_string($input['body-plain']); //This is the line where the error happen.
        throw new Exception();

Data:
...
  "body-plain" => """
    <?xml version="1.0" encoding="UTF-16"?>
    <?ADF version="1.0"?>
    <adf>
    <prospect>
    <id source="language">Français</id>
    <requestdate>2019-11-20T11:35:24-05:00</requestdate>
    <vehicle interest="buy" status="Used">
...

Conclusion: I don't understand why the try catch don't work when I use it like that.Is there a way I can tell PHP to look if the contain and label match?

A: The XML library used by PHP is not object-oriented and does not throw exceptions. In addition, you're throwing your own exception right in the code, ensuring the catch block gets executed every time.
Step one is to disable libxml's error output. Then check for errors and take appropriate action.
<?php
$input = $request->all();
libxml_use_internal_errors(true);
$xml = simplexml_load_string($input['body-plain']);
$err = libxml_get_last_error();
// you'll need to confirm the error code, try `print_r($err);` here
if ($err->code === 5032) {
    libxml_clear_errors();
    $input['body-plain'] = str_replace("UTF-16", "UTF-8", $input['body-plain']);
    $xml = simplexml_load_string($input['body-plain']);
}
if (libxml_get_last_error()) {
    // something bad happened
}
$prospect = $xml->prospect;

This info, along with a small example, can be found in the manual.


text:
Q: ¿Cómo puedo separar un string parcialmente? Estoy intentando tratar un dataset en el que tengo una columna de los MB que dispone un cliente. Ejemplo cliente 1 tiene contratados 600MB, cliente 2 900MB. Quiero únicamente el número, sin el MB. He probado con split pero no obtengo nada más que fallos. lo tengo en una columna de un datframe.
¿Podéis ayudarme con ello?
Gracias
vel_conexion_= {'MB':['600MB', '500MB','800MB']}
df=pd.DataFrame(vel_conexion_)
df

A: Puedes utilizar uno de los siguientes dos metodos:
lista=['600MB', '500MB', '800MB']

# Metodo 1: Elimina las letras 'MB'
nuevaLista=[e.lower().replace('mb','') for e in lista]

# Metodo 2: Elimina los ultimos dos caracteres
nuevaLista=[e[:-2] for e in lista]

vel_conexion_= {'MB':nuevaLista}
df=pd.DataFrame(vel_conexion_)
df

A: A un dataframe pandas le puedes aplicar una función a todos los elementos de una columna, a través del método .apply()
En este caso la función que quieres aplicar es una que se quede con los primeros caracteres descartando los dos últimos. Esta función es tan simple que se puede escribir con una lambda así: lambda x: x[:-2].
Por tanto tu problema se resolvería con una línea:
df.MB = df.MB.apply(lambda x: x[:-2])