text:
Q: Useful data analysis methods for engineering applications I'm currently working on a dynamic simulation of an already existing product. The simulation is supposed to help in future development of this product by enabling the engineers to get a better understanding of the influence different parameters have.
However the mathematical and physical models manifesting the simulation are only simplifications of the real system because of its sheer complexity. Therefore no quantitative results are created.
Nevertheless this simulation is useful as it is faster and cheaper to change a parameter in a simulation rather than building a prototype and  physically test it.

Now being at the point that the simulation runs as expected with acceptable performance I'm starting to implement the evaluation of the data.
Which gives me the problem: What am I even supposed to do with all of this data?
The Question now is: What are useful methods to analyze moderate sets of data of real world (mechanical) systems.
My discipline is hardware development and not data analysis so this topic is mostly new to me. (Apart from outdated mathematical lectures about statistics). Additionally I'm really junior in this industry so experience is rather limited.
I think this question (or more precisely the answers) could be a good resource for engineers in the same positions as me independent from the application.

A bit of background for my application:

*

*40 static inputs/starting parameters

*30 outputs presenting physical properties "plotted" over time (e.g. speed, height, current, etc.)

*Monte Carlo method is already implemented

This question might me considered as to broad or not answerable, because of this I'm open for feedback or accept the fact that it might be closed.

A: I normally relly on Discrete-Event System Simulation by Jerry Banks to perform statistical analysis of simulation outputs. The topics covered in Section V include:

*

*Modelling simulation inputs as probability distributions.

*Validation of simulation output with respect to the real system.

*Comparison of multiple system instances, with respect to a performance metric.

*Optimization via simulation.

Among many others. It all depends on your analysis needs.


text:
Q: strpos(): Passing null to parameter #1 ($haystack) of type string is deprecated I am getting error with Magento 2.4.4 & 2.4.5
Here is my line of code
<?php echo strpos($pos, $viewMode . '-primary') ? $position : ''; ?>>

A: In Magento 2.4.4 was changed some important logic in vendor/magento/module-catalog/view/frontend/templates/product/list.phtml

*

*getProductDetailsHtml renders for non saleable products

*Added options logic
                                            <?php $options = $block->getData('viewModel')->getOptionsData($_product); ?>
                                            <?php foreach ($options as $optionItem): ?>
                                                <input type="hidden"
                                                       name="<?= $escaper->escapeHtml($optionItem['name']) ?>"
                                                       value="<?= $escaper->escapeHtml($optionItem['value']) ?>">
                                            <?php endforeach; ?>

*strpos to $pos to:

                <?= ($pos && strpos($pos, $viewMode . '-actions')) ?
                /* @noEscape */ $secureRenderer->renderStyleAsTag(
                    $position,
                    'product-item-info_' . $_product->getId() . ' div.product-item-actions'
                ) : '' ?>

                                <?= ($pos && strpos($pos, $viewMode . '-secondary')) ?
                                    /* @noEscape */ $secureRenderer->renderStyleAsTag(
                                        $position,
                                        'product-item-info_' . $_product->getId() . ' div.actions-secondary'
                                    ) : '' ?>

*bottom toolbar renders with:

    <?= $block->getChildBlock('toolbar')->setIsBottom(true)->toHtml() ?>

I'm strongly suggest to compare your design file with core file and make related changes

A: Insted of passing  null in the method strpos() pass an empty string if the variable is null i check the variable first and then use them in code
here is my code
<?php //Modifications 29 August 2022 (hassan)
      if(!$pos)
       {
          $pos = '';
       }
       if(!$viewMode)
       {
          $viewMode = '';
       }
  ?>

EDIT:
You may also just use the same syntax used on your question, and use empty() to make sure your variables are empty or not:
$pos = !empty($pos) ? $pos : '';

$viewMode = !empty($viewMode) ? $viewMode : '';

A: <?= strpos($pos, $viewMode . '-primary') ?
                                    /* @noEscape */ $secureRenderer->renderStyleAsTag(
                                        $position,
                                        'product-item-info_' . $_product->getId() . ' div.actions-primary'
                                    ) : '' ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Layout constraint error I'm struggling with auto layout in XCode6 so I'm trying to set the constraints in code.
I have a scrollview wich covers most of the screen. Inside the scrollview I've placed a button, a imgview and a textview. The button is a fixed 44px and now I want to split what's left of the scrollview between the imgview and textview (resulting in them being the same size).
this is my SubViewsDidLoad function:
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let screenWidth = screenSize.width;
    let screenHeight = screenSize.height;
    let scrollViewTop = self.navigationBar.frame.height + self.navigationBar.frame.minY
    let scrollViewBottom = self.toolBar.frame.height

 // set scrollView frame

    println ("navigationbarTop: ", scrollViewTop)
    println ("toolbarHeight: ", scrollViewBottom)
    self.scrollView.frame = CGRect(x: 0, y: scrollViewTop, width: screenWidth, height: screenHeight-(scrollViewTop+scrollViewBottom))

// set btnLocation size & constraints

    self.view.addConstraint(NSLayoutConstraint(item:self.btnLocatie, attribute:.CenterX, relatedBy:.Equal, toItem:self.view,attribute:.CenterX, multiplier:1, constant:0))
    self.view.addConstraint(NSLayoutConstraint(item:self.btnLocatie, attribute:.Top, relatedBy:.Equal, toItem:self.scrollView,attribute:.Top, multiplier:1, constant:8))
    self.view.addConstraint(NSLayoutConstraint(item:self.btnLocatie, attribute:.Left, relatedBy:.Equal, toItem:self.scrollView,attribute:.Left, multiplier:1, constant:8))

 // set imageview size & constraints

    //X - align to center
    self.view.addConstraint(NSLayoutConstraint(item: self.imgAfbeelding, attribute:.CenterX, relatedBy:.Equal, toItem:self.view, attribute:.CenterX, multiplier:1, constant:0))
    //Top - Scrollview+8
    self.view.addConstraint(NSLayoutConstraint(item:self.imgAfbeelding, attribute:.Top, relatedBy:.Equal, toItem:self.btnLocatie, attribute:.Bottom, multiplier:1, constant:+8))
    //Left - scrollview leftside+8
    self.view.addConstraint(NSLayoutConstraint( item:self.imgAfbeelding, attribute:.Left, relatedBy:.Equal, toItem:self.scrollView, attribute:.Left, multiplier:1, constant:8))
    //Size - scrollView size
    self.view.addConstraint(NSLayoutConstraint(item:self.imgAfbeelding, attribute:.Bottom, relatedBy:.Equal, toItem:self.scrollView, attribute:.Bottom, multiplier:1, constant:(scrollView.frame.height-btnLocatie.frame.height+16)/2))

 // set textview size & constraints

    self.view.addConstraint(NSLayoutConstraint( item:self.txtTekst, attribute:.Left, relatedBy:.Equal, toItem:self.scrollView, attribute:.Left, multiplier:1, constant:0))

    self.view.addConstraint(NSLayoutConstraint(item: self.txtTekst, attribute:.Top, relatedBy:.Equal, toItem:self.imgAfbeelding, attribute:.Bottom, multiplier:1, constant:+8))

    self.view.addConstraint(NSLayoutConstraint(item:self.txtTekst, attribute:.Bottom, relatedBy:.Equal, toItem:self.scrollView, attribute:.Bottom, multiplier:1, constant:scrollView.frame.height-8))
 }

When I run the code, at first everything looks good. But when I rotate the device the console shows a lot of constraint errors and the position and size of the image view and textview are completely off.
I'm guessing there's a better way to get this to work properly, but I can't seem to get it to work. Can anyone help me?

A: Try this
self.btnLocatie.setTranslatesAutoresizingMaskIntoConstraints(false)
self.imgAfbeelding.setTranslatesAutoresizingMaskIntoConstraints(false)


text:
Q: Excel VBA delete row based on cell value I wrote some VBA code that is meant to delete a row based on the value of a cell.
Const VENDRO_FIELD = 4

Dim rDataTable As Range
Set rDataTable = Range(Cells(1, 1), Cells(1, 1).End(xlToRight).End(xlDown))
Dim sCurrentRecord As Single
Dim sNumberOfRecords As Single
sNumberOfRecords = rDataTable.Rows.Count
Dim tVendor As String

For sCurrentRecord = 1 To sNumberOfRecords
    tVendor = rDataTable.Cells(sCurrentRecord, VENDOR_FIELD)
    If tVendor = "MTR" Then
        Selection.Rows(sCurrentRecord).EntireRow.Delete
    End If
Next sCurrentRecord

The cells containing the vendor are in column D, which is why the const is set to 4. But whenever I run this code it is deleting the wrong row. I don't know how it's selecting the row it decides to delete, so right now it seems random to me.
Does anyone know why it's not deleting the row that should be selected based off sCurrentRecord?


text:
Q: Only one document in dbs - how to update it? I have a node js program where I only want to allow one document in a specific collection.
Mongo Schema:
var DefaultPollSchema = new mongoose.Schema({
    milliseconds: Number
});

So the collection always looks like this:
> db.defaultpolls.find()
{ "_id" : ObjectId("58500051a4b71d0c4d5c6ab3"), "milliseconds" : 15000, "__v" : 0 }

I want to create an API for updating this value, however I do not want to use the objectId in order to do the update. Since I will only have one document in this collection - is there a way to do it?
I tried using this:
router.put('/update', function(req, res, next) {
  var milliseconds = req.body.milliseconds;
    defaultPoll.updateMany({}, {$set: {milliseconds: milliseconds}}, function (err, interval){
      if (err) {
          res.json(err);
        } else {
          res.json(interval);
        }
    })
});

However this gives me the following error:
TypeError: Object function model(doc, fields, skipId) {
    if (!(this instanceof model)) {
      return new model(doc, fields, skipId);
    }
    Model.call(this, doc, fields, skipId);
  } has no method 'updateMany'

Is there any other way to write the API?
Thanks

A: The method for Mongoose updates is called update, so the approach is fine, but it should be:
defaultPoll.update({}, {$set: {milliseconds: milliseconds}}, function (err, raw) { ...

A: JohnnyHK's solution will not work. Mongoose documentation mentions the following:

Passing an empty object {} as the doc will result in a no-op unless
  the overwrite option is passed. Without the overwrite option set, the
  update operation will be ignored and the callback executed without
  sending the command to MongoDB so as to prevent accidently
  overwritting documents in the collection.

So the following code should work in your case
(Note the { overwrite: true } as options):
router.put('/update', function(req, res, next) {
  var milliseconds = req.body.milliseconds;
    defaultPoll.update({}, {$set: {milliseconds: milliseconds}}, { overwrite: true }, function (err, interval){
      if (err) {
          res.json(err);
        } else {
          res.json(interval);
        }
    })
});


text:
Q: Camera Smoothly Zoom Into Object Position On Mouse Click So I have a scene with multiple boxes and a PerspectiveCamera.
I'd like to achieve this effect whenever I click on a specific box.

*

*The camera will smoothly transition from its current position to the box's position

*The box is centered in the camera's viewport

*The camera will smoothly zoom in and focus on the box

This effect was inspired by 100,000 Stars. Whenever a user would click on a star, the camera would zoom into the star and display it in the center. I'm trying to replicate that effect.
I'm currently able to grab the box's position and look at it. But I want to do more than that and I'm unsure how to proceed.

A: I think what you need is an animation, there are many animation libraries like anime.js and tween.js. As you have grabbed the position after translating, you can make an animation to smooth your translation. Here is a snippet with tween.js:
var tween2 = new TWEEN.Tween(camera.position)
                .to({
                    x : target.position.x,
                    y : target.position.y,
                    z : target.position.z
                } , 1000)
                .easing(TWEEN.Easing.Linear.None)
                .start();

If you want to locate the box on the center of your camera. we also need to change the camera rotation. Here is a way to compute the target rotation by using matrix.
    var rotation_matrix = new THREE.Matrix4();
    rotation_matrix.lookAt(target_position,target_box.position,camera.up);
    var target_rotation = new THREE.Euler(0,0,0,"XYZ");
    target_rotation.setFromRotationMatrix(rotation_matrix);
    //now, the target_rotation would be the rotation after translating.

Then, you can use the same way to make an animation to change the rotation.
BTW, It seems in 100000 stars they switch camera in the end.


text:
Q: Python Spark Dataframes: Better way to export groups to text file I want to export data to separate text files;  I can do it with this hack:
for r in sqlContext.sql("SELECT DISTINCT FIPS FROM MY_DF").map(lambda r: r.FIPS).collect():
    sqlContext.sql("SELECT * FROM MY_DF WHERE FIPS = '%s'" % r).rdd.saveAsTextFile('county_{}'.format(r))

What is the right way to do it with Spark 1.3.1/Python dataframes?  I want to do it in a single job as opposed to N (or N + 1) jobs.
May be:
saveAsTextFileByKey()

A: Spark in general does not have RDD operations with multiple outputs. But for writing files there is a nice trick: Write to multiple outputs by key Spark - one Spark job


text:
Q: How to refund amount of paypal adaptive payment using PayPal.AdaptivePayments SDK? I`m using PayPal.AdaptivePayments sdk for chained payment and refund process of chained payment.
Using following methods:
for payment : pay() method
for refund : refund() method as per sdk.
When try to refund with payKey then getting response with status: "NO_API_ACCESS_TO_RECEIVER"
Currently I`m sandbox account on development.
I have also followed paypal developer api/sdk docs but still getting same problem.
So please help me to refund process with status of "Refunded".
I have already review post related to this on stack-overflow but I didn`t proper solution in any post.
https://devtools-paypal.com/guide/ap_chained_payment?interactive=ON&env=sandbox
 private void Refund(HttpContext contextHttp)
    {
        NameValueCollection parameters = contextHttp.Request.Params;

        RefundRequest request = new RefundRequest(new RequestEnvelope("en_US"));

        // Set optional parameters
        if(parameters["receiverEmail"].Length > 0)
        {
            //(Required) Amount to be paid to the receiver
            string[] amt = contextHttp.Request.Form.GetValues("receiverAmount");

            // Maximum length: 127 characters
            string[] receiverEmail = contextHttp.Request.Form.GetValues("receiverEmail");

            //Telephone country code
            string[] phoneCountry = contextHttp.Request.Form.GetValues("phoneCountry");

            string[] phoneNumber = contextHttp.Request.Form.GetValues("phoneNumber");

            //Telephone extension
            string[] phoneExtn = contextHttp.Request.Form.GetValues("phoneExtn");

            string[] primaryReceiver = contextHttp.Request.Form.GetValues("primaryReceiver");

            string[] invoiceId = contextHttp.Request.Form.GetValues("invoiceId");

            string[] paymentType = contextHttp.Request.Form.GetValues("paymentType");
            //(Optional) The transaction subtype for the payment.
            string[] paymentSubType = contextHttp.Request.Form.GetValues("paymentSubType");

            List<Receiver> receivers = new List<Receiver>();
            for(int i=0; i<amt.Length; i++) {
                Receiver r = new Receiver(Convert.ToDecimal(amt[i]));
                r.email = receiverEmail[i];
                r.primary = Convert.ToBoolean(primaryReceiver[i]);
                if(invoiceId[i] != string.Empty) {
                    r.invoiceId = invoiceId[i];
                }
                if(paymentType[i] != string.Empty) {
                    r.paymentType = paymentType[i];
                }
                if(paymentSubType[i] != string.Empty) {
                    r.paymentSubType = paymentSubType[i];
                }
                if(phoneCountry[i] != string.Empty && phoneNumber[i] != string.Empty) {
                    r.phone = new PhoneNumberType(phoneCountry[i], phoneNumber[i]);
                    if(phoneExtn[i] != string.Empty) {
                        r.phone.extension = phoneExtn[i];
                    }
                }
                receivers.Add(r);
            }
            request.receiverList = new ReceiverList(receivers);
        }

        if(parameters["currencyCode"] != string.Empty) {
            request.currencyCode = parameters["currencyCode"];
        }

        if(parameters["payKey"] != string.Empty) {
            request.payKey = parameters["payKey"];
        }

        if(parameters["transactionId"] != string.Empty) {
            request.transactionId = parameters["transactionId"];
        }

        if(parameters["trackingId"] != string.Empty) {
            request.trackingId = parameters["trackingId"];
        }

        AdaptivePaymentsService service = null;
        RefundResponse response = null;
        try
        {
            Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();
            service = new AdaptivePaymentsService(configurationMap);
            response = service.Refund(request);
        }
        catch (System.Exception e)
        {
            contextHttp.Response.Write(e.Message);
            return;
        }

        Dictionary<string, string> responseValues = new Dictionary<string, string>();

       // string redirectUrl = null;

        string redirectUrl = null;

        if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
            !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
        {
            responseValues.Add("Currency code", response.currencyCode);
            int idx = 1;
            foreach (RefundInfo refund in response.refundInfoList.refundInfo)
            {
                //Receiver's email address.Maximum length: 127 characters
                responseValues.Add("Refund receiver " + idx, refund.receiver.email);
                // Amount to be refunded to the receiver.
                responseValues.Add("Refund amount " + idx, refund.receiver.amount.ToString());

                responseValues.Add("Refund status " + idx, refund.refundStatus);

                responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
            }
        }
        Display(contextHttp, "Refund", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
    }


text:
Q: How to import an array into a function in javascript? I need some help with the code below:
    <script type="text/javascript">
        var opcao = new Array (
            document.getElementById("cred_form_1864_1_wpcf-pde_Pesquisas_descontinuadas"),
            document.getElementById("cred_form_1864_1_wpcf-pnps_Pesquisas_nao_patenteaveis-sigilosas")
        );

        function check1(){
            if (opcao[0].checked == true){
                for (var i = 0; i < opcao.length; i++){
                    if (i != 0){
                        opcao[i].checked = false;
                        opcao[i].disabled = true;
                    }
                }
            }
        }

        function check2(){
            if (opcao[1].checked == true){
                for (var i = 0; i < opcao.length; i++){
                    if (i != 1){
                        opcao[i].checked = false;
                        opcao[i].disabled = true;
                    }
                }
            }
        }
    </script>

I need to call the array 'opcao' within the functions 'check1 ()' and 'check2 ()'. How can I do this?
====================
I tried the suggestion of Mishik did not work. What I need is that the functions 'check1 ()' and 'check2 ()' to access the same array 'opcao'.
If I write the array within each function the code works perfectly. But how are the same values I would have to repeat the same array for each function created.

A: If your code is executed before the page is loaded, then opcao array will not actually contain required elements.
You need to wrap your code in window.onload, so that by the time script is executed all the required elements will be available in the document.
window.onload = function() {
    var opcao = new Array (
        document.getElementById("cred_form_1864_1_wpcf-pde_Pesquisas_descontinuadas"),
        document.getElementById("cred_form_1864_1_wpcf-pnps_Pesquisas_nao_patenteaveis-sigilosas")
    );

    function check1(){
        if (opcao[0].checked == true){
            for (var i = 0; i < opcao.length; i++){
                if (i != 0){
                    opcao[i].checked = false;
                    opcao[i].disabled = true;
                }
            }
        }
    }

    function check2(){
        if (opcao[1].checked == true){
            for (var i = 0; i < opcao.length; i++){
                if (i != 1){
                    opcao[i].checked = false;
                    opcao[i].disabled = true;
                }
            }
        }
    }
}


text:
Q: Capturing network traffic in ruby - pcap related issues What I need is to write very simple application, which would listen to network traffic, filter out some packets based on various layer 4/5 information and then dump those information into database.
I am quite confused on which pcap gem/plugin should I use. The basic pcap implemention seem to be a bit outdated (no changes since 2001) and doesn't work properly. I also tried pcaprub, but I am not quite sure how to get around with this library. It seem to capture raw packets without te ability to actualy get any data out of the pcap dump.
Do you have any advices on how can I realize this simple task?
Thanks in advance. :-)

A: Check out pcaprub - its used/maintained by the metasploit project:
svn checkout http://metasploit.com/svn/framework3/trunk/external/pcaprub/

A: Try xtractr: http://code.google.com/p/pcapr/wiki/Xtractr


text:
Q: How can I merge multiple tfrecords file into one file? My question is, if I want to create one tfrecords file for my data , it will take approximately 15 days to finish it, it has 500000 pairs of template , and each template is 32 frames( images). In order to save the time,  I have 3 GPUs, so I thought I can create three tfrocords file each one file on one GPUs and then I can finish creating the tfrecords in 5 days. But then I searched about a way to merge these three files in one file and couldn't find proper solution.
So Is there any way to merge these three files in one file, OR is there any way that I can train my network by feeding batch of example extracted form the three tfrecords files, knowing I am using Dataset API.

A: Addressing the question title directly for anyone looking to merge multiple .tfrecord files:
The most convenient approach would be to use the tf.Data API:
(adapting an example from the docs)
# Create dataset from multiple .tfrecord files
list_of_tfrecord_files = [dir1, dir2, dir3, dir4]
dataset = tf.data.TFRecordDataset(list_of_tfrecord_files)

# Save dataset to .tfrecord file
filename = 'test.tfrecord'
writer = tf.data.experimental.TFRecordWriter(filename)
writer.write(dataset)

However, as pointed out by holmescn, you'd likely be better off leaving the .tfrecord files as separate files and reading them together as a single tensorflow dataset.
You may also refer to a longer discussion regarding multiple .tfrecord files on Data Science Stackexchange

A: The answer by MoltenMuffins works for higher versions of tensorflow. However, if you are using lower versions, you have to iterate through the three tfrecords and save them them into a new record file as follows. This works for tf versions 1.0 and above.
def comb_tfrecord(tfrecords_path, save_path, batch_size=128):
        with tf.Graph().as_default(), tf.Session() as sess:
            ds = tf.data.TFRecordDataset(tfrecords_path).batch(batch_size)
            batch = ds.make_one_shot_iterator().get_next()
            writer = tf.python_io.TFRecordWriter(save_path)
            while True:
                try:
                    records = sess.run(batch)
                    for record in records:
                        writer.write(record)
                except tf.errors.OutOfRangeError:
                    break

A: As the question is asked two months ago, I thought you already find the solution. For the follows, the answer is NO, you do not need to create a single HUGE tfrecord file. Just use the new DataSet API:
dataset = tf.data.TFRecordDataset(filenames_to_read,
    compression_type=None,    # or 'GZIP', 'ZLIB' if compress you data.
    buffer_size=10240,        # any buffer size you want or 0 means no buffering
    num_parallel_reads=os.cpu_count()  # or 0 means sequentially reading
)

# Maybe you want to prefetch some data first.
dataset = dataset.prefetch(buffer_size=batch_size)

# Decode the example
dataset = dataset.map(single_example_parser, num_parallel_calls=os.cpu_count())

dataset = dataset.shuffle(buffer_size=number_larger_than_batch_size)
dataset = dataset.batch(batch_size).repeat(num_epochs)
...

For details, check the document.

A: Customizing the above the script for better tfrecords listing
import os
import glob
import tensorflow as tf
save_path = 'data/tf_serving_warmup_requests'
tfrecords_path = glob.glob('data/*.tfrecords')
dataset = tf.data.TFRecordDataset(tfrecords_path)
writer = tf.data.experimental.TFRecordWriter(save_path)
writer.write(dataset)


text:
Q: Plotting the average values for each level in ggplot2 I'm using ggplot2 and am trying to generate a plot which shows the following data.
df=data.frame(score=c(4,2,3,5,7,6,5,6,4,2,3,5,4,8),
              age=c(18,18,23,50,19,39,19,23,22,22,40,35,22,16))
str(df)
df

Instead of doing a frequency plot of the variables (see below code), I want to generate a plot of the average values for each x value. So I want to plot the average score at each age level. At age 18 on the x axis, we might have a 3 on the y axis for score. At age 23, we might have an average score of 4.5, and so forth (Edit: average values corrected). This would ideally be represented with a barplot.
ggplot(df, aes(x=factor(age), y=factor(score))) + geom_bar()
Error: stat_count() must not be used with a y aesthetic.

Just not sure how to do this in R with ggplot2 and can't seem to find anything on such plots. Statisticially, I don't know if the plot I desire to plot is even the right thing to do, but that's a different store.
Thanks!

A: If I understood you right, you could try something like this:
library(plyr)
library(ggplot2)
ggplot(ddply(df, .(age), mean), aes(x=factor(age), y=factor(score))) + geom_bar()

A: You can use summary functions in ggplot. Here are two ways of achieving the same result:
# Option 1
ggplot(df, aes(x = factor(age), y = score)) +
  geom_bar(stat = "summary", fun = "mean")

# Option 2
ggplot(df, aes(x = factor(age), y = score)) +
  stat_summary(fun = "mean", geom = "bar")

Older versions of ggplot use fun.y instead of fun:
ggplot(df, aes(x = factor(age), y = score)) +
  stat_summary(fun.y = "mean", geom = "bar")

A: You can also use aggregate() in base R instead of loading another package.
temp = aggregate(list(score = df$score), list(age = factor(df$age)), mean)
ggplot(temp, aes(x = age, y = score)) + geom_bar()

A: Another option is doing a group_by of the x-values and summarise the "mean_score" per "age" using dplyr to do it in one pipe. Also you can use geom_col instead of geom_bar. Here is a reproducible example:
df=data.frame(score=c(4,2,3,5,7,6,5,6,4,2,3,5,4,8),
              age=c(18,18,23,50,19,39,19,23,22,22,40,35,22,16))
library(dplyr)
library(ggplot2)
df %>%
  group_by(age) %>%
  summarise(mean_score = mean(score)) %>%
  ggplot(aes(x = factor(age), y = mean_score)) +
  geom_col() +
  labs(x = "Age", y = "Mean score")

Created on 2022-08-26 with reprex v2.0.2


text:
Q: T-SQL Object Definition null for tables with non-null create statements I'm trying to select the create statement for a table in T-SQL like
select OBJECT_DEFINITION(OBJECT_ID('dbo.tablename', 'U'))

but it always returns null. I have the view definition permission on the table in question, and when I'm in SQL Server Management Studio, I can see the definition by right clicking on the table and going to Script View As > Create To > New Query Editor Window, which does show the create statement for the table.
The problem seems to be with OBJECT_DEFINITION because
select OBJECT_ID('dbo.tablename', 'U')

returns the table's id integer without issue. Does anyone know what the cause of this problem could be.

A: You cannot use OBJECT_DEFINITION() with User Tables (type 'U'):

OBJECT_DEFINITION applies to the following object types:
C = Check constraint
D = Default (constraint or stand-alone)
P = SQL stored procedure
FN = SQL scalar function
R = Rule
RF = Replication filter procedure
TR = SQL trigger (schema-scoped DML trigger, or DDL trigger at either the database or server scope)
IF = SQL inline table-valued function
TF = SQL table-valued function
V = View


text:
Q: android - How to search in xml file i have a XML file in : /res/xml/countries.xml
and also i have a view with editText inside.
i want to search that text (users should type in editText) in my countries.xml file!
here is my xml file :
<?xml version="1.0" encoding="utf-8"?>
  <countries>
     <country>
       <name>United State</name>
     </country>
  <countries>

A: If you want to read a whole document, use XML Parser, like Pull already mentioned. If you only want to pick out only one or few certain things, I would suggest XPath. Here is a good Tutorial on how to use XPath in Java.

A: This tutorial explain clearly how to parse an XML file : XML parser
Other tutorial simpler with XPath : Xparse tutorial

A: First you need to parse that xml file containing the countries name. Store list of countries in any arraylist and then write any search algo to search the text found from that edittext.

A: Try this xpath tutorial...
You will have good learning experience...


text:
Q: Where can ask I questions about carbon/environmental footprint and comparisons? Lately the following question has been in my head:

What is the carbon footprint of ebooks compared to regular paperbacks?
Given a book that's ready to be published (e.g. layout completed for either book or PDF) and an estimated sales of 20k over the next 5 years, what is the carbon footprint of the printed books (paper, printing, ink, storage, ...) compared to the carbon footprint of an ebook distribution with its accompanied electrical footprint (servers, clients, ...), if we don't include the retail or e-commerce footprint?

This question could of course get cut in two or more questions which are a lot easier to handle, e.g.

*

*What is the carbon footprint of a 20k run of regular paperbacks after its final edit?

*What is the carbon footprint of an ebook that sells 20k over the span of 5 years after its final edit?

However, the overall intend should be clear from the first question: I'm looking for a site where I can ask about environmental economics. Thus, Economics.SE came to mind; however, I'm not sure whether those questions is the right fit for Eco.SE.
Economics.SE's help center does not rule this kind of question out per se, but it neither convinces me to post my question there with confidence1. I might be mistaken here though, and Eco.SE is the correct SE site.
Do I post question on environmental economics on Eco.SE, or is there another more fitting site on the SE network that I've missed in my (albeit short) research? Are these kind of question too-broad for any of the current SE sites?

1 that might be a small language barrier, as English isn't my first language and due to the current beta state of the site

A: I believe the site you're looking for is Sustainable Living Beta.
Short excerpt from their help page:

What topics can I ask about here?
Sustainable Living Stack Exchange is for folks dedicated to a lifestyle that can be maintained indefinitely without depleting available resources.


text:
Q: How can I interrupt a loop on a MySQL query when the are no affected rows? I have an array of objects I need to loop through.
For every object I need to perform a MySQL INSERT IGNORE type of query.
The problem is I have to stop looping as I see that the data I get from one of the objects present in the array already exists in the DB checking the affectedRows property on the results object that comes with mysql.
cont arrayOfObjects = [{foo: foo, bar: bar}, {foo: foo1, bar: bar1}];

for(obj of arrayOfObjects){
   let sql = `INSERT IGNORE INTO TABLE table_name VALUES(${obj.foo}, ${obj.bar});`;
   connection.query(sql, (error, results, fields) => {
       if(results[0].affectedRows === 0){
           // I want to stop looping
       }
   }
}

A: In order to do so, you can run update operations one by one and checking the result.
For example :
async function runUpdates() {
  const arrayOfObjects = [{foo: foo, bar: bar}, {foo: foo1, bar: bar1}];
  const needToStop = false;
  for (const obj of arrayOfObjects) {
     if (!needToStop) {
        const updated = await runQuery(obj);
        if (updated > 0) { needToStop = true; }
     }
  }
  return 'OK';
}

function runQuery(obj) {
  return new Promise((resolve, reject) => {
       let sql = `INSERT IGNORE INTO TABLE table_name VALUES(${obj.foo},${obj.bar});`;
     connection.query(sql, (error, results, fields) => {
         if (error) { return reject(error);}
         resolve(results[0].affectedRows);
     });
 })
}

A:

function CallMeMaybe() {
                connection.query(sql, (error, results, fields) => {
                    if (results[0].affectedRows === 0) {
                        // I want to stop looping
                    } else {
                        setTimeout(() => {
                            CallMeMaybe();
                        }, 1000);
                    }
                });
}
CallMeMaybe();

I'd not be looping it but calling it if the condition is met--AGAIN!


text:
Q: How to cover full extent of spreadsheet table? I am brand new to Google Scripting spreadsheets (Google Apps Script, ed.) and new to Java Javascript also.
I am fairly confident with Excel VBA and now attempting to make the transition
I have a small table in Google sheets.
I am trying to create a script to cover the full range of the table.
I have the following however I can't seem to get the Logger to show the range of the table. Please bear in mind I'm new to Google Apps Script so if someone does provide an answer can you annotate.
I thought by making x = my function, then I can declare x when I want to get the range. (I think this is not as straight forward as VBA.)
function CountColb(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];
function CountColA(){
 //var ss = SpreadsheetApp.getActiveSpreadsheet();//goes to active spreadsheet
 //SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);//goes to sheet tab 0 = first sheet, 1 = sheet 2
  var data = ss.getDataRange().getValues();
  for(var i = data.length-1 ; i >=0 ; i--){
    if (data[i][0] != null && data[i][0] != ''){
      return i+1 ;
    }
  }
}

  var x = function CountColA(){

 var range = sheet.getRange(1, 1, x, 3);
 values = range.getValues();
 Logger.log(values);

}
  }

A: First, remember that Google Apps Script is a variant of Javascript, not Java. If you're starting out with Google Apps Script, Javascript tutorials should be your first stop. (Codecademy for example.) That will quickly get you familiar with variables, functions, objects, methods, declarations, scope - all the problems you've run into here.
The Google Apps Script editor will check the syntax of your code whenever you save it. If you have syntax errors, the save will fail. On this piece of code, though, there are no syntax errors. However, that's not the same as being semantically correct - the code does not mean what you think it does.
Let's start by reformatting your code to expose logical structure. Take a look at the indenting - it provides clues about the scope of your functions. I've annotated it to highlight key aspects.
/**
 * CountColb is a function at global scope. You'll see its name in the debug
 * controls of the editor (see Fig 1 below).
 */
function CountColb() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];    //** Always uses "Sheet 1"

  /**
   * CountColA is in the local scope of CountColb. It does not appear in the
   * debug controls, because the debugger can only invoke functions at global
   * scope. It's available only to other code in the same local scope - this
   * is great for encapsulation, if that is what you're after.
   */
  function CountColA() {
    /**
     * Since CountColA is in CountColb local scope, it has access to other
     * local scope variables - in this case ss and sheet. In terms of scope,
     * this is called "closure". Within CountColb local scope, there can be
     * only one "ss". If we declare it a second time here, within CountColA,
     * it will in fact use the same storage location as the version first
     * declared in CountColb.
     */
    //var ss = SpreadsheetApp.getActiveSpreadsheet();//goes to active spreadsheet
    //SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);//goes to sheet tab 0 = first sheet, 1 = sheet 2

    /**
     * This statement gets all the populated cell values from the sheet
     * into an array of arrays. While spreadsheet rows and column number
     * from 1 to n, javascript arrays index from 0 to n-1.
     */
    var data = ss.getDataRange().getValues();

    /**
     * This is a down-counting for loop, properly set up. It will start
     * at the highest-numbered row, and work back to the first.
     */
    for (var i = data.length - 1; i >= 0; i--) {
      if (data[i][0] != null && data[i][0] != '') {
        /**
         * The first time we find that the first element in a row is neither
         * null nor a blank string, we will return the spreadsheet row number.
         * If the content of the spreadsheet remains constant, this function
         * will ALWAYS return the same result. (Is that what you want?)
         */
        return i + 1;
      }
    }
  }

  /**
   * Here is another variable, x, in CountColB local scope. The value of x
   * is being set to a function (we can do that in Javascript). Since we are
   * supplying the function keyword, a name 'CountColA', and a function body
   * enclosed in braces, this is an entirely new function. While it has the
   * same name that was previously used in CountColB local scope, that is not
   * a problem for the javascript interpreter because the function name here
   * is x, NOT CountColA.
   *
   * This does not invoke CountColA and assign the return value to x.
   */
  var x = function CountColA() {

    /**
     * Because of closure, the x in here is the same as the x out at
     * CountColB local scope. The statement below will throw an exception
     * (crash) because it is passing a function (this function) as the
     * third parameter to getRange, which expects a number.
     */
    var range = sheet.getRange(1, 1, x, 3);
    values = range.getValues();
    Logger.log(values);

  }
}

/**
 * We've reached the end of CountColB without any statements that
 * invoke CountColA or x, the two functions within CountColB.
 * As a result, CountColB does nothing.
 */

Fig 1: CountColb in debug controls
Working Example
It's not clear what "cover the full range of the table" means, but let's presume the intent is to count the all cells that contain values. This function will do that:
/**
 * Counts all non-blank cells in sheet 1 of the spreadsheet.
 *
 * @return {number}      count of non-blank cells
 */
function countCells() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];    //** Always uses "Sheet 1"
  var data = ss.getDataRange().getValues();
  var result = 0;

  // For every row
  for (var row = (data.length - 1) ; row >=0 ; row--) {
    // ... and every column in that row
    for (var col = (data[0].length - 1) ; col >=0 ; col--) {
      // ... check for existence and content of a cell's contents
      if ((data[row][col] !== null) && (data[row][col] !== '')) {
        // ... and count it
        result++;
      }
    }
  }
  // Return the count of non-blank cells
  return result;
}


text:
Q: ATL COM to add a function to excel I'm trying to build an ATL COM with a c++ class and add it to excel by automation. I found some guides but I have many problems, one is that my dll donesn't compare in automation and if I try to add it excel says there's a problem about not contain a server or there aren't permissions. Could someone give me a guide? I'm using Visual Studio 2012. Thanks.

A: I will give a simple example of how to create a c++ ATL/COM dll that will be referenceable in Excel's vba. The dll will expose to the VBA a ATL/COM object and this object will have a method that will be able to take a double from excel/vba, multiply it by 2.0 and output it to the VBA. The VBA code will be usable to define a excel function. Of course, no need to resort to a c++ dll for having an excel function mutiplying the content of a cell by two, but it is just for the demonstration.
Last remark before start : better run visual studio (called mvs for short throughout this answer) as admin for all of this. All versions of mvs from 2005 included work for this.
Let us start. open your favourite mvs, create a new project : choose the template "ATL project" in the Visual c++ template project types list. Name it "MyATLProject", and choose to save it in "C:\Users...\Desktop" for instance. Click ok. This will open a new window. Do not click there on finish, but on next : now check that only "dll" is checked, and if so, click on finish. (Of course for our basic need we need nothing more here.
All we have done has created a solution (in "C:\Users...\Desktop\MyATLProject", I call $(SOL) this path.) with two projects in it : MyATLProject & MyATLProjectPS. The PS ended project (PS stands for proxy/stub) is useless for what we want to do, but anyway. We will do everything here in debug. Do a rebuild solution. (You'll note that MyATLProjectPS has been skipped from rebuid : this is normal.) Now you could see that a folder $(SOL)\MyATLProject\debug has been created, with various files in it, the one of interest to us being MyATLProject.dll --> this file is the one we will have to reference in the VBA and that we expose us objects and methods. For now, it would expose nothing to us in the VBA, for we haven't yet implemented any ATL/COM object, a fortiori nor any method.
Now, let us create an ATL/COM object. There is a hard way for this and a soft way, I will only show the soft way. Right click on the "MyATLProject" project in the solution explorer, then "add", then "class", and in categories choose "ATL" and then "ATL simple object". Then click on "add". In simple name put "MyATLObject" and click finish. (Here again we could do more, but for such an intro, we don't need more.) This will create and open a "MyATLObject.h" file. MyATLObject.cpp has also been created, and MyATLProject.idl (present at the project generation) has been modified. This three files are the holy trinity for what we intend to do. Do a rebuild all for sake's sake. ;-) An ATL/COM object MyATLObject, without any methods for now, has been created. You could see it the VBA if you would reference the dll there, but be patient, we will do it later.
Now, let us give a method to this object. There is a hard way for this and a soft way, I will show you both, starting with the hard one first. First modification. Go in MyATLProject.idl and replace
interface IMyATLObject : IDispatch{
};

by
interface IMyATLObject : IDispatch{
    [id(1), helpstring("method MULT")] HRESULT MULT([in,out] DOUBLE* theDouble);
};

What have we done ? The idl file "references our MyATLObject" (I am voluntarily vague) (as well as other objects/interfaces if needed), and we specify in it that our MyATLObject will have a method called MULT, method that will take a reference (pointer to) a double. As you may guess, MULT will multiply by 2.0 the double pointed to. Now, we have to modify accordingly MyATLObject.h and MyATLObject.cpp. Second modification : go to MyATLObject.h and replace
public:

};

OBJECT_ENTRY_AUTO(__uuidof(MyATLObject), CMyATLObject)

at the end of it by
public:

    STDMETHOD(MULT)(DOUBLE* theDouble);
};

OBJECT_ENTRY_AUTO(__uuidof(MyATLObject), CMyATLObject)

What have we done ? We have declared the method MULT in the class, as we would have done it for a class in "vanilla" c++. Third and last modification : go to MyATLObject.cpp and after
// CMyATLObject

add
STDMETHODIMP CMyATLObject::MULT(DOUBLE* theDouble)
{

    return S_OK;
}

S_OK is of type HRESULT and tells by return if our MULT method finished well or not. (No need to be more verbose here for what we plan here.) Now we have to implement the MULT method really, like this for instance (I am voluntarily ugly and unsafe here, you'll fashion the stuff yourself later) :
STDMETHODIMP CMyATLObject::MULT(DOUBLE* theDouble)
{
    *theDouble *= 2.0 ;
    return S_OK;
}

Rebuild solution. The ATL/COM object MyATLObject has been now updated to have a method MULT now. This was for the (not very in fact) hard way of adding a method. The soft way is by using the wizard : undo all three modifications we did and rebuild, so that we are now at the same stage as the one we were in when we were about adding the MULT method. Go to class view, expand MyATLProject, right click on the interface IMyATLObject (the one with the handle icon, the icon looking like a little key), click on "add", and then "add method". This opens the add method wizard. Put MULT in method name, choose DOUBLE * in parameter type, and "theDouble" in the parameter name. The fact the our parameter is a pointer DOUBLE * will give us access to the out and retval parameter attributes. Click "in" and "out". Then click on add, and then on finish. This will recreate all what we did by hand (for MULT only, and without its implementation of course) before. Add the
    *theDouble *= 2.0 ;

line in the implementation of the MULT method in the MyATLObject.cpp file.
Warning : depending on the mvs version, by experience, it may happen that everything is recreated well except the idl file part, check it, and if this is the case, do it by hand as we did it in the first place, during the hard way.
Now, it is time to use our ATL/COM c++ dll in the VBA of excel. Pick your favourite excel version, and create a spreadsheet (in xlsm format for earlier excel versions and in xls for late version, because we will need macros) called MyATLProjectTEST.xls. Make sure to enable the use of all macros. (How to do it varies with excel's version, but you'll find how to do it with your friend google.) Alt+F11 to open VBA. Click on tool, references, browse to your MyATLProject.dll and click to add a reference to it. (To be safe, maybe regsvr32 the dll before --> this is explained everywhere on the internet, google is your friend again on this.) Insert a module, it will be automaticaly called Module1. In it, code :
Public Function MULT(x As Double) As Double

    Dim o As MyATLProjectLib.MyATLObject
    Set o = New MyATLProjectLib.MyATLObject
    Call o.MULT(x)
    MULT = x

End Function

Now go in a sheet of the spreadsheet, put 3.14159 in cell B2 let's say, and put formula
=MULT(B2)

in cell B3, and enjoy the result.
Remark : try to build to solution in mvs while the spreadsheet is open : you'll have a
Error   1   Could not delete file         'c:\users\...\desktop\myatlproject\myatlproject\debug\MyATLProject.dll'.

Make sure that the file is not open by another process and is not write-protected.  MyATLProject
error. This is because the dll is referenced (used) in the VBA, who "owns" it somehow, empeaching mvs to modify (recompile) it. At each code modification, you'll have to close your spreadsheet for building/rebuilding. The demo is over.
Now, the "fun" part, the debug session. Rebuild the solution, reopen the spreadsheet and rereference the dll in it if needed. Put a breakpoint on the line
*theDouble *= 2.0 ;

Do a ctrl+alt+p (or "debug" and then "attach to process") in mvs, choose the excel spreadsheet in the list and wait a bit to have access to your spreadsheet again (let the symbols load, in fact). Now open the VBA and put a breakpoint at the line
Call o.MULT(x)

Now go to cell B3, and recalculate it. You will break in the VBA at the specified line, and if you step into (F8) you will break at the
*theDouble *= 2.0 ;

line in MyATLObject.cpp.
Some last remarks.
1) DOUBLE * even if it works is not the right way to pass info from vba to c++ and from c++ to vba, for the following simple reason : you sell your dll and vba code to someone, and he puts a string LUDWIGVONMISES in B2 instead of putting a number. What would happen ? An error : constated in a "not-debug" mode that you'll have to track in debug to see where it happens. Why ? Because you do not handle error at all. For handling them, you should pass VARIANT * between c++ and VBA, and operate in c++, at the beginning of your MULT method for instance, to check that the VARIANT * pointer passed to MULT points to a VARIANT "wrapping" a double and not a string.
2)

Making a COM Automation Add-In is not the best way to add user-defined
  functions to Excel - it is slow and has various limitations. Better is
  to make etc

Being extremely focused on execution time for the code I am working on and delivering, and having developped a lot of ATL/COM dll's for excel/VBA, as well as xla/xll using the excel sdk, I do not agree at all with this statement from Govert. What could we say about the small demo above ? We have entered in the c++ when we enter in the MULT method, and our calculation (multiplication by two) was done inside the method. This was quick, but imagine that the calculation that was done was something extremely intensive numerically, or in memory terms. We could be stupid and doing it in our ATL/COM method, but we could deport the calculation outside our method, in plain c++. This would be the quickest thing to do, and afaik, it is the only reasonable way to do it. Same thing if you want to use the excel sdk, for producing excel functions directly, without wrapping ATL/COM methods in VBA code to produce these excel functions yes. Here you could say : hey, the xll option using the excel sdk is then better, because I do not loose wrapping time. Maybe, but wrapping time is really not that big, and with ATL/COM, you have VBA with you, where you could use ATL/COM object in quite an elegant fashion, and you can use it to generate com object etc etc. You can even access excel memory to instantiate object there through excel functions coded by wrapping ATL/COM method in VBA ! Moreover, any such ATL/COM dll is referenceable in c# project, and usable there in the same way that you use it in VBA. Even in java. ;-) This is not the case of any xla/xll coded with excel's sdk, like the solutions Govert is advertising for. Serious lack of reusability concern.
3) The OP wants to use ATL COM to do something which is perfectly doable with it, and Govert tells him that ATL/COM is too slow - which is false - and to use something else. For this I should downvote Govert's answer. ;-)

A: Making a COM Automation Add-In is not the best way to add user-defined functions to Excel - it is slow and has various limitations. Better is to make an .xll add-in based on the native C API (http://msdn.microsoft.com/en-us/library/office/bb687883.aspx). If you are using C++ there are a number of toolkits that help a lot (using only the SDK is not so easy). You might like to have a look at:

*

*XLW - an open source wrapper for the API that's the standard starting point

*Keith Lewis's xll library - uses modern C++ paradigms, with a nice variety of example projects.

*XLL+ - a highly regarded commercial toolkit, with various advanced features like async functions and ribbon integration.

If you prefer to use a managed language, like VB.NET, C# or F#, you should use the open--source Excel-DNA library which allows the integration of .NET with Excel using the C API, and also has various advanced features.


text:
Q: Komodo Edit 8.5 Tab key I am new to Komodo edit but I have searched and read numerous articles and help and can't understand why when I press the Tab key it moves over one space as if I press the Space Bar??
example: (in any other program on my PC when I press Tab I get 5 spaces which I will represent with underscores _)
Tab should = _____
and Space bar should = _
BUT!!
in Komodo 8.5:
Tab = _
and
Space Bar = _
and no matter what settings I have changed it stays the same
Indent settings, settings for this file, settings for each language (php or javascript)
am I missing something?

A: I found out it seems to be the opposite of what people are talking about, or what I took from what people are saying
Number of spaces per indent: 5
Width of each tab character: 1
when you first open Komodo its like 4 and 8 and I just could not get it to change I tried like 1 and 10, 5 and 10, 8 and 10 etc...
if you want the tab to work like in other programs, BIG NUMBER FIRST


text:
Q: How can I get list of apps, images and videos of my device in react native? I want to get list of apps, images and videos from my device and show them into list, how can i do this using react native?
Thank in advance!!

A: There are many modules for this like
react-native-android-installed-apps-unblocking  or react-native-installed-apps for installed apps and react-native-cameraroll to access the gallery


text:
Q: Upon their visit or on their visit
In the report, the police have said the menu was neither displayed nor shared with the police by the canteen Staff upon  their visit

1-upon
2-on
I read this sentence  from a Indian news paper "the Hindu" and I am confused whether to use on or upon, in sentence  they used "upon"  as shown  above in sentence.

A: The subtle difference is that upon denotes moment in time whereas on denotes both moment in time and during.
We can use "on" to mean "at a moment in time"
On our arrival...  (the moment of our arrival)
or "during"
On our journey...
Locative uses aside, we use "upon"  nowadays mainly to refer to moments in time

upon our arrival...
we set out upon our journey
upon seeing it for the first time...
upon being informed that

not to duration:
archaism We met him while we were upon our journey.

A: "Upon" is less used now but remains common in formal writing. "On" is deemed an acceptable substitution nowadays. They are interchangeable in cases like that. In some special cases only "upon" may be used. "Once upon a time..." and "Breakfast-time is upon us" are examples. These are special , less common, or more formal cases that emphasise the connection "upon" has with time and place in contrast to "on" being simply proximity.

A: But you look up the prepositions on and upon in McMillan, Oxford, Longman, Cambridge, or The Free Dictionary, you will know that these prepositions can be used interchangeably in many cases. See McMillan for details. One of these cases is when one thing happens immediately after another. Look at the following sentences:
Please report to the reception desk on/upon your arrival.
Upon/On arriving home I discovered that he had gone.
She was joyful upon/on seeing her child.
Similarly, you can say 'on/upon their visit' in the sentence presented by the OP, without any difference in meaning.  However. the use of 'upon' is much more formal than 'on'.

A:
In the report, the police have said the menu was neither displayed nor shared with the police by the canteen Staff during their visit.

In your example I would use during, since the "display or sharing" could have occurred anytime during their "visit". Upon would be better if you were referring to their arrival (upon being a moment in time).
I would not use "on" here, but it is not specifically wrong.


text:
Q: Call a function argument stored in a list I need to test a suite of argument conditions in order to find the best model (using the drc package). That is, I'd like to store function arguments in a list and then call them into the drm() function. The drc package has a function (mselect()) to do this, but it has been known to fail for unknown reasons (https://www.reddit.com/r/Rlanguage/comments/a1bu44/any_idea_what_im_doing_wrong_with_the_mselect/).

Example Data
library(drc) # This also loads in the S.alba data
data(S.alba)

head(S.alba)
  Dose  Herbicide DryMatter
1    0 Glyphosate       4.7
2    0 Glyphosate       4.6
3    0 Glyphosate       4.1
4    0 Glyphosate       4.4
5    0 Glyphosate       3.2
6    0 Glyphosate       3.0

Failed Attempt
# List of function arguments to be assessed e.g. drm(...fct = W1.4(fixed = c(NA, 0.1, NA, NA)
model_list <- list(curve = c(W1.4(fixed = c(NA, 0.1, NA, NA)),
                             LL.4(fixed = c(NA, 0.1, NA, NA))))

# Failed function, attempting to return a list of results
model_select <- function(data, mlist){
    model =  data %>%
        drm(DryMatter ~ Dose, Herbicide, data = . , fct = mlist)
    metric = AIC(model)
    return(metric)
}
model_select(data = S.alba, mlist = model_list)

Error in drm(DryMatter ~ Dose, Herbicide, data = ., fct = mlist) :
    First entry in list to 'fct' NOT a function

Semi-Working Attempt
model_select_2 <- function(data){
    model =  data %>%
        drm(DryMatter ~ Dose, Herbicide, data = . , fct = W1.4(fixed = c(NA, 0.1, NA, NA)))
    metric = AIC(model)
    return(metric)
}
model_select_2(data = S.alba)

model_select_2(data = S.alba)
[1] 106.9226

Desired Output
model_select(data = S.alba, mlist = model_list)
[1] W1.4-106.9226
[2] LL.4-99.54702

A: Part of the problem is how you are creating model_list. You want to combine those values with list() rather than c(). The latter tried to combine them into the same object.
The next thing you can do is sapply over the list of curves to get the result for each input. A working example would be
model_list <- list(curve = list(W1.4(fixed = c(NA, 0.1, NA, NA)),
                             LL.4(fixed = c(NA, 0.1, NA, NA))))
model_select <- function(data, mlist){
   sapply(mlist$curve, function(curve){
      model <- drm(DryMatter ~ Dose, Herbicide, data = data , fct = curve)
      metric = AIC(model)
   })
}
model_select(data = S.alba, mlist = model_list)
# [1] 106.92259  99.54702


text:
Q: CSS Table set max row height I'm trying to set the maximum height of a cell of a css table. There are several stack overflow threads that suggest to create an inner div and set a maximum height there. The problem is that this doesn't seem to work with big fonts:

Test

Test

.table {
  display: table;
  border-spacing: 10px;
  width: 300px;
}
.table-cell {
  display: table-cell;
  height: 50px;
  background: yellow;
}
.table-cell-inner {
  height: 50px;
  max-height: 50px;
  overflow: hidden;
}
.big {
  font-size: 50px;
}

Fiddle: http://jsfiddle.net/ru1dr2y3/
The big class styles the word Test with a font size of 50 pixels and leads to a table cell that is bigger than allowed. How can I fix that? position: absolute; seems to be a solution but this seems like an ugly fix.

A: The problem is that when you fake a table in CSS, the elements don't all take on all properties that a real table would have. If you were to rewrite this as a real table, the problem wouldn't exist.

table {
  border-spacing: 10px;
  width: 300px;
}
td {
  height: 50px;
  background: yellow;
}
.table-cell-inner {
  height: 50px;
  max-height: 50px;
  overflow: hidden;
}
.big {
  font-size: 50px;
}

Test

Test

Reference: This is 50px height.

So the solution is to add those properties in manually.
(I also took the liberty to insert the missing table row, if you don't mind.)

.table {
  display: table;
  border-spacing: 10px;
  width: 300px;
}
.row {
  display:table-row}
.table-cell {
  display: table-cell;
  height: 50px;
  background: yellow;
  vertical-align:middle; /* there you go */
}
.table-cell-inner {
  height: 50px;
  max-height: 50px;
  overflow: hidden;
}
.big {
  font-size: 50px;
}

Test

Test

Reference: This is 50px height.

The issue was that with the default vertical-align:baseline the browser shifted the leftmost table-cell-inner down to align its baseline to the rightmost one, which would cause the accumulated height to be larger. (See what I mean by giving table-cell-inner a border in your original fiddle.)

A: change your css bit according to the below snippet

.table {
    display: table;
    border-spacing: 10px;
    width: 300px;
}
.table-cell {
display: inline-block;
    background: yellow;
    /* width: 20px; */
    max-height: 50px;
    margin-right: 10px;
}
.table-cell-inner {
    height: 50px;
    overflow: hidden;
    /* max-width: 90px; */
    display: inline-block;
    line-height: 50px;
}
.big {
    font-size: 50px;
}

Test

Test

Reference: This is 50px height.


text:
Q: How do I enable Wayland on Ubuntu 21.10 (NVIDIA)? I installed Ubuntu 21.10 on my laptop today, but I'm still not seeing the option on the login screen to use Wayland instead of X11. I've really been looking forward to getting GNOME 40 with multi-touch support.
As I understand it, Ubuntu 21.10 is supposed to bring Wayland support to computers with NVIDIA drivers (I'm running version 470.74). Does anybody know how to get this functionality added?

A: In my case the answer was:
sudo apt install libnvidia-egl-wayland1

For some reason this package is not installed automatically, so unless you install it manually, NVidia + Wayland won't work.

A: I can see in the "/lib/udev/rules.d/61-gdm.rules" file that there are still a few things that can prevent Wayland from being selectable at the login screen (GDM):

*

*the system is running on a PC with the Hi1710 chipset

*kernel modesetting is disabled

*the "nvidia-drm" modeset is disabled

*the system's NVIDIA driver version is lower than 470

Through manual testing, I have determined that my problem was that the "nvidia-drm" modeset was disabled. The best way I have found so far to remedy the situation is by adding the following to the "/etc/default/grub" file:
GRUB_CMDLINE_LINUX="nvidia-drm.modeset=1"

Lastly, run "sudo update-grub" to write your changes out to your system's GRUB configuration file (/boot/grub/grub.cfg) and reboot.
Note: To actually use Wayland, you will need to manually select it if it isn't already the default on your system. On Ubuntu, this can be done at the login screen by first selecting the desired user and then clicking on the gear icon in the lower right-hand corner of the screen. If no gear icon is visible, Wayland is not available on your system in its current configuration. If this is the case, check to verify that none of the other issues listed above are to blame.

Although the steps above were all that was required to get hardware-accelerated Wayland running on my laptop, I later discovered that a separate Ubuntu installation on my home desktop was still using software rendering—as opposed to GPU-accelerated rendering—for programs running under XWayland (i.e. most games).
This can be fixed by adding the "universe" repository to APT (as it's not currently available in "main", the Canonoical-supported repo), and then running:
sudo apt install libnvidia-egl-wayland1

This has caused some applications to behave unexpectedly in my experience, but it has also fixed my hardware rendering issues.

A: On the login screen, click on the settings icon at the bottom right-hand corner. Ensure "Ubuntu" is ticked and then log in as normal. This should log you into Wayland and not x11.


text:
Q: Redirect olddomain querystring layout to newdomain and new querystring layout? OK, say my blog site myurl.org as many links to a separate domain:
old.myurl.org?oldvar=foo

Only old.myurl.org no longer exists and has been replaced by new.myurl.org.
If the query string vars were the same on new.myurl.org, I believe I could rewrite from .htaccess using:
RewirteCond %{http_host} ^old.myurl.org$ [NC]
RewriteRule ^(.*)$ new.myurl.org [L,R=301,QSA]

The only problem is that I also need to change the query string var from oldvar to newvar and preserve it's data (foo).
There are plenty of examples of how to rewrite query string vars in different ways, but I can't seem to find an example of this scenario.
I need to rewrite:
old.myurl.org?oldvar=foo

To:
new.myurl.org?newvar=foo

Edit
Furthermore, I have several potential query string key values to account for, but not all will always be present.
So I may need:
old.myurl.org?oldvar=foo&oldvar2=bar --> new.myurl.org?newvar=foo&newvar2=bar

or
old.myurl.org?oldvar2=bar --> new.myurl.org?newvar2=bar

This may not even be possible, but in one case I need to strip off part of the query string value.  So ?oldvar=foo{term} might need to become ?newvar=foo
Thanks again!

A: First condition match the domain, second condition match the query string and the rule will match your domain root:
RewriteCond %{HTTP_HOST} ^old\.myurl\.org$ [NC]
RewriteCond %{QUERY_STRING} ^oldvar=(\w+)$
RewriteRule ^$ http://new.myurl.org/?newvar=%1 [R=301,L]

You can place more than one query string as well:
RewriteCond %{HTTP_HOST} ^old\.myurl\.org$ [NC]
RewriteCond %{QUERY_STRING} ^oldvar=(\w+)$ [OR]
RewriteCond %{QUERY_STRING} ^oldvar=(\w+)&oldvar2=(\w+)$
RewriteRule ^$ http://new.myurl.org/?newvar=%1&newvar2=%2 [R=301,L]

RewriteCond %{HTTP_HOST} ^old\.myurl\.org$ [NC]
RewriteCond %{QUERY_STRING} ^oldvar2=(\w+)$
RewriteRule ^$ http://new.myurl.org/?newvar2=%1 [R=301,L]

To use a path like x/y/z as you have mentioned on the comment you change the RewriteRule for example the rule we are currently using, will only redirect from yourdomain.com/?... which is:
RewriteRule ^$ http://new.myurl.org/?newvar2=%1 [R=301,L]

If you want to catch a different path you would do this:
RewriteRule ^x/?$ http://new.myurl.org/?newvar2=%1 [R=301,L]

The above would catch yourdomain.com/x?... and yourdomain.com/x/?...
You can have more than one path as well and use a OR condition like this:
RewriteRule ^(x|x/y|x/y/z)/?$ http://new.myurl.org/?newvar2=%1 [R=301,L]

The above means we want to match x/?... OR x?... OR x/y?... and x/y/?... OR x/y/z?... OR x/y/z/?...
By encapsulating it on the parenthesis and using the | as separator and OR.
The ^ and $ means match from begin to end, so when it contains nothing means match nothing which means root folder domain.com/, when there is content it will match the content for instance domain.com/x or whatever you place into it.


text:
Q: Existence of a matrix in $\mathbb{F}_2$ with some invertibility properties All the matrices in this statement are in the field $\mathbb{F}_2$. Let $I$ be the identity matrix of size $10 \times 10$. What are all the possible $n$ ($\geq 6$) for  which
there exists a matrix $X$ of size $n \times 10$, such that any $6$ rows of $X$ jointly with any $4$ rows of $I$ form a $10 \times 10$ invertible matrix?

A: There is no such $n$. Assume that it exists, then $n=6$ also satisfies this property. Denote the rows of $X$ by $r_1,\ldots,r_6$, the columns of $X$ by $c_1,\ldots,c_{10}$, the rows of $I$ by $e_1,\ldots,e_{10}$. Assume that, say, $c_1,\ldots,c_{6}$ are linearly dependent. Then the minor formed by the first 6 rows and columns of $X$ equals to 0, this yields that $r_1,\ldots,r_6,e_7,e_8,e_9,e_{10}$ are linearly dependent. So any 6 vectors in the set $\{c_1,\ldots,c_{10}\}$ are linearly independent. But $c_1,\ldots,с_7$ are linearly dependent. Thus their linear dependence is $c_1+\ldots+c_7=0$. Analogously $c_8+c_1+c_2+\ldots+c_6=0$ and we get $c_7=c_8$, a contradiction.


text:
Q: GWT - Passing arguments when deploying with google plugin for eclipse I'm using GWT + GAE in Eclipse and I use the Google Plugin for Eclipse (GPE) to deploy my app to my server. Although I can modify my compiler arguments when launching my app in DevMode (in "Run configurations" menu), it seams I cannot find a way to pass additional arguments (like -deploy) to the GWT compiler when the app is deployed using GPE.
Any solution here ?

A: I found the solution: it seams that the GWT compiler uses the arguments passed in the "Advanced" panel (when selecting "GWT compile project...", which is in the same menu as the deploy to app engine option). This is both for local as well as the deployment gwt compilation.


text:
Q: Is it possible to place a whole function in babel's block statement I am trying to write a babel plugin using AST that will change the arrow function of React usememos hook to my own custom function.
This is a basic use memo function I am using to explore the syntax tree.

const  data = useMemo(() => {
    return "Hello"
    }, [])

I would love to change the arrow function in the above function to the one below on compile

async function handler() {
  const response = await window
    .fetch(`https://jsonplaceholder.typicode.com/todos/1`, {
      method: `GET`,
      headers: {
        "content-type": "application/json"
      }
    })
    .then((res) => res.json());

  return response;
}

My babel code

module.exports = function (babel) {
  const { types: t } = babel;

  return {
    name: "change-gatsby-function", // not required
    visitor: {
      ArrowFunctionExpression(path) {
        if (path.parent.callee === undefined) {
          return;
        }
        if (path.parent.callee.name === "useMemo") {
          path.replaceWith(
            t.ArrowFunctionExpression([], t.blockStatement(), true)
          );
        }
      }
    }
  };
};

If I try adding the block directly into the block statement I get an error. Whats the best way to convert the arrow function to the new function on compile?


text:
Q: How to deploy changes of nodejs app to ALL AWS E2 instances (load balancer)? I have a NodeJs application.
Now app deployed through TeamCity on the single instance in the Amazon Cloud.
It should - raise the farm for the load balancer, and contain the current state of the application on those instances.
At the start of the instance - not a problem, I think just a script that will extort from GIT changes.
But when running instances, how to initialize (preferably with computation in teamcity) - download new files on the instances?

A: I am not sure if I am answering in right context. I would suggest you use some kind of Continuous Integration setup for this like Jenkins. So once you push your code to a cloud repository (Github, Gitlab, Bitbucket, etc) it is built and deployed on all the instances including the main server. So this is a kind of automation where you do a one time setup and you can monitor builds from a proper dashboard (in case of jenkins)

A: *

*Create a snapshot of your existing instance.

*Create a new instance (and create a new volume by snapshot) after that attach it to newly created instance. This new volume should be dev/sda

*Restart the server on new machine.

*Create a load balancer and attach the both instance.


text:
Q: Do the Clojure Inspector (inspect) ui buttons do anything? Clojure comes with some basic ui apps that let you inspect objects.  The generic "inspect" ui has buttons on the top for List, Table, Bean, Line, Bar, Prev, Next, etc but as far as I can tell they don't do anything.  I looked at the source and they seem functionless from the code as far as I can tell.  Am I crazy?
(use 'clojure.inspector)
(inspect (System/getProperties))

A: Hm ... I never use clojure.inspector, but as far as I can tell from taking a glimpse at the source those buttons really seem to do nothing.


text:
Q: How to add OnClickListener to image button in the ListView Header in Android? I have added a custom header to the ListView in android. The layout xml file for Header contains an Image button. How can I add an OnClickListener to this ImageButton
Header Layout File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#336699">

<ImageButton
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/add" />

</LinearLayout>

Code for binding the ListView (I have created a custom Adapter)
 ListView listView1 = (ListView) findViewById(R.id.listView1);
    LocationAdapter adapter = new LocationAdapter(this,R.layout.listrow,webresult);
    View header = (View)getLayoutInflater().inflate(R.layout.listheader, null);
    listView1.addHeaderView(header);
    listView1.setAdapter(adapter);

A: When you add a header to listview it's considered the element 0 of your list. So you don't add an onClickListener but do it as you'd do with a regular row in a list:
    listview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          if(position==0) //do your stuff
        }
    });


text:
Q: Rails devise user function How do I execute a particular function after a user has signed up.
(I wanted to add to one of my associations, I already have it coded in a non-devise rails but now I need it here)

A: Device has provided helper action 'after_sign_in_path_for' you can override it within your application controller.
def after_sign_in_path_for(resource_or_scope)
.... #write your customize code or call any method
end

A: For sign up it would look like:
def after_sign_up_path_for(resource_or_scope)
  if resource_or_scope.is_a? User  # and perhaps other conditions
    #... do something, go somewhere
  else
    super
  end
end

Ofc. Assuming that your Devise user model is called User.

A: You can use the after_create callback in your User model.
The following guide has tons of examples: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html


text:
Q: Entity Framework Enable-Migrations –EnableAutomaticMigrations? I am working on forms Authnetication, where i have used my own Entity Framework and also i have used the DataContext for giving the roles for the users. I have hardcoded the DataCOntectInitializer as below
public class DataContextInitializer : CreateDatabaseIfNotExists
    {
        protected override void Seed(DataContext context)
        {
            Roles role1 = new Roles { RoleName = "Admin" };
            Roles role2 = new Roles { RoleName = "User" };
        User user1 = new User { Username = "admin", EmailId = "admin@ymail.com", FirstName = "Admin", Password = "123456", IsActive = true, DateCreated = DateTime.UtcNow, Roles = new List<Roles>() };

        User user2 = new User { Username = "user1", EmailId = "user1@ymail.com", FirstName = "User1", Password = "123456", IsActive = true, DateCreated = DateTime.UtcNow, Roles = new List<Roles>() };

        user1.Roles.Add(role1);
        user2.Roles.Add(role2);

        context.Users.Add(user1);
        context.Users.Add(user2);

        context.SaveChanges();
    }
}

And my Login Method is :
[HttpPost]
        [AllowAnonymous]
    public ActionResult Login(LoginViewModel model, string returnUrl=" ")
    {
        if (ModelState.IsValid)
        {
            var user1 = Context.Users.Where(u => u.Username == model.Username && u.Password == model.Password).FirstOrDefault();
            var user = ob.Users.Where(u => u.Username == model.Username && u.Password == model.Password).FirstOrDefault();
            if (user != null)
            {
                var roles = user.Roles.Select(m => m.RoleName).ToArray();
                CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
                serializeModel.UserId = user.UserId;
                serializeModel.FirstName = user.FirstName;
                serializeModel.LastName = user.LastName;
                serializeModel.roles = roles;

                string userData = JsonConvert.SerializeObject(serializeModel);
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user1.EmailId, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData);

                string encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                Response.Cookies.Add(faCookie);
                if ( roles.Contains("Admin"))
                {
                    return RedirectToAction("Index", "Admin");
                }
                else if (roles.Contains("User"))
                {
                    return RedirectToAction("Index", "User");
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }

        }
        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

And my Model classes are as below:
public class User
    {
    public int UserId { get; set; }
    [Required]
    public String Username { get; set; }
    [Required]
    public String EmailId { get; set; }

    [Required]
    public String Password { get; set; }

    public String FirstName { get; set; }
    public String LastName { get; set; }

    public Boolean IsActive { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual ICollection<Roles> Roles { get; set; }
}

and
public class Roles
    {
    [Key]
    public int RoleId { get; set; }

    [Required]
    public string RoleName { get; set; }
    public string Description { get; set; }

    public virtual ICollection<User> Users { get; set; }
}

The problem is like when im trying to login using my username and password, the roles need to be checked from the DatContext class.
But at that time my Roles are not comin from DataContext class, and it is  giving ArgumentNullException.

A: See this article answered by @Oliboy50 (Entity Framework 6 - Handling loading of nested objects) this might help, you need to include your virtual Roles so that the collection gets loaded


text:
Q: IIS 7 Windows Authentication keeps showing login popup I'm trying to be able to login to a simple IIS7 website using windows authentication. I turned on Windows Authentication for the website and put NTLM at the top of the providers list.
When I access the page in web browser, I get the windows security login popup. I enter in my user name and password and click OK, but the windows login popup keeps popping up.  I am using a administrator username so it should not be a folder security issue.
Thanks!


text:
Q: Partial derivatives of polynomial in two variables Let $k \in \mathbb N$, $a_{ij} \in \mathbb R$ for $i,j \in \mathbb N$, $i+j \le k$. A function $f:\mathbb R^2 \to \mathbb R$
$$f(x,y) = \sum_{i+j \le k} a_{ij}x^iy^j$$
is called polynomial of degree $k$ in $x,y$.
I have to show that the partial derivatives of polynomials of degree $k \ge 1$ exist, and the partial derivatives $\frac{\partial f}{\partial x}, \frac{\partial f}{\partial y}$ are polynomials of degree $k-1$.
I start showing that for a polynomial of degree $1$ its partial derivatives $D_1f(x)$ and $D_1f(y)$exists and in the next step that the $D_if(x)$ and $D_if(y)$ derivative exists, but I dont know how to deal with the matrix and the indices of the sum in the formula, how can I take a take a partial derivative of it? Dealing with the matrix and other variable as a constant and use normal derivative rules for the variable in which I want to take the partial derivative?
Any help is appreciated!!!

A: There is at least one caveat to your problem that needs to be stated. At least one $a_{ij}$ such that $i+j=k$ must be non-zero. Otherwise your polynomial is of degree less than $k$. And in order for the partial derivative w.r.t. $x$ to be a polynomial of degree $k-1$ one of the $a_{ij}$ must have $i\ge 1$. Similarly for $y$.
Otherwise, show that if $i+j=k$, the partial derivative of $a_{ij}x^iy^j$ for both $x$ and $y$ is of total degree $i+j-1=k-1$.
I don't think you need to use induction here.
To actually perform the partial derivatives, note that:
$$\frac{\partial f}{\partial x} \sum_{i+j \le k} a_{ij}x^iy^j = \sum_{i+j \le k} i*a_{ij}x^{i-1}y^j$$ and vice versa for the partial derivative with respect to y. Just note that in cases where there is no $x$ the partial derivative with respect to $x$ is 0.


text:
Q: poor audio quality with OpenAL on iOS/OSX I find myself porting an old multimedia title to iOS/OSX and I'm somewhat disappointed with the quality of audio output I've achieved via OpenAL, in that it's got that "scratchy" quality one hears when PCM is resampled poorly.  However, I'm feeding it 8-bit PCM at 11025KHz and I do believe the native rate is 44100KHz so I can't imagine why anything other than a 1:4 integral expansion of the samples would be occurring.  The sound itself is very clean when played back on a Win32 system so I know there's no problems with the data itself.  Nor are there any buffering problems in that I'm keeping about 32K buffered ahead of the playback position.  But the sound quality just isn't that good.  Has anyone else encountered this and are there configuration options to work around it?  I've gone through the docs and nothing seems applicable to the problem ...

A: iOS doesn't handle 8-bit data very well. Try converting it to 16-bit.
afconvert -f caff -d LEI16@11025 sourcefile.wav destfile.caf

You could also compress it to mp3 or aac, but that's a little more complicated to load since it needs to be converted to 16-bit little endian format when loaded.
Here's a loader that handles any 16-bit audio format: https://github.com/kstenerud/ObjectAL-for-iPhone/blob/master/ObjectAL/ObjectAL/Support/OALAudioFile.m


text:
Q: Error starting Eclipse on Ubuntu, JVM terminated Exit code=13 I know, This question is repeated. But I couldn't find solution to my problem.
I do not have sudo permission on ubuntu 12.04.1 LTS, so downloaded eclipse-cpp-luna-SR1-linux-gtk-x86_64.tar.gz and jdk-8u25-linux-i586.tar.gz. set JAVA_HOME ->jdk, JRE_HOME->JRE and PATH variable to JAVAHOME/bin
Getting the below error
JVM terminated. Exit code=13
/vol/users/pradeep.rajan/eclipse/jdk1.8.0_25/bin/java
-Dosgi.requiredJavaVersion=1.7
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m
-jar /home/work/pradeep.rajan/eclipse//plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
-os linux
-ws gtk
-arch x86_64
-showsplash /home/work/pradeep.rajan/eclipse//plugins/org.eclipse.platform_4.4.0.v20140925-0400/splash.bmp
-launcher /home/work/pradeep.rajan/eclipse/eclipse
-name Eclipse
--launcher.library /home/work/pradeep.rajan/eclipse//plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20140603-1326/eclipse_1605.so
-startup /home/work/pradeep.rajan/eclipse//plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.appendVmargs
-exitdata 2f48018
-product org.eclipse.epp.package.cpp.product
-vm /vol/users/pradeep.rajan/eclipse/jdk1.8.0_25/bin/java
-vmargs
-Dosgi.requiredJavaVersion=1.7
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m
-jar /home/work/pradeep.rajan/eclipse//plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar

My eclipse.ini file
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20140603-1326
-product
org.eclipse.epp.package.cpp.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.7
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m

A: Copy the JRE to eclipse/jre so eclispse can use eclipse/jre/bin/java!


text:
Q: How do I detect empty cells in a cell array? How do I detect empty cells in a cell array? I know the command to remove the empty cell is a(1) = [], but I can't seem to get MATLAB to automatically detect which cells are empty.
Background:
I preallocated a cell array using a=cell(1,53).
Then I used if exist(filename(i)) and textscan to check for a file, and read it in. As a result, when the filename(i) does not exist, an empty cell results and we move onto the next file.
When I'm finished reading in all the files, I would like to delete the empty cells of a. I tried if a(i)==[]

A: Use CELLFUN
%# find empty cells
emptyCells = cellfun(@isempty,a);
%# remove empty cells
a(emptyCells) = [];

Note: a(i)==[] won't work. If you want to know whether the the i-th cell is empty, you have to use curly brackets to access the content of the cell. Also, ==[] evaluates to empty, instead of true/false, so you should use the command isempty instead. In short: a(i)==[] should be rewritten as isempty(a{i}).

A: All above mentioned answers are incorrect, because in my case when i used them, they removed empty cells and then all elements of my cell array situated in a row manner instead of preserving their actual shape. In fact after using this kind of approach your cell array elements tend to be a row cell vector.
I have found this approach which works correctly in my case.
source : https://groups.google.com/forum/#!topic/comp.softsys.matlab/p3NX0fI6u90
approach:
myCellARRAY(all(cellfun(@isempty,myCellARRAY),2), : ) = [];


text:
Q: 400 Bad Request when attempting to import CSV file into Google Drive Spreadsheet I am using Drive API files/create to upload  a file to Google Drive. Everything is fine as long as I don't specify the mimeType, or anything except application/vnd.google-apps.spreadsheet.
Here is my request:

The response is 400 with not so useful body:
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "badRequest",
    "message": "Bad Request"
   }
  ],
  "code": 400,
  "message": "Bad Request"
 }
}

I tried setting the mimeType to text/csv, it works fine. I even tried requesting https://www.googleapis.com/drive/v3/about, and funnily they list my import as valid:
"text/csv": [
  "application/vnd.google-apps.spreadsheet"
],

but in reality it is not. Did I do something wrong?

A: How about this modification? Although I'm not sure about your script and the CSV data, from your request body, I propose 2 modification points as follows. Can you modify the following points and try to run again? I propose to remove ; of the last letter of the following 2 lines.
From:
Content-Type: application/json;charset=utf-8;

To:
Content-Type: application/json;charset=utf-8

And
From:
Content-Type: text/csv;charset=utf-8;

To:
Content-Type: text/csv;charset=utf-8


text:
Q: caret position changing according to current mouse position in textarea Is there any way to set caret's position according to current mouse's position in textarea.
When user drag some selected text and moving in the textarea, caret's position will change during to current mouse's position so that user can specify the inserting position conveniently.
I mimic the drag and drop event, but I didn't find an effective way to changing caret's position. Any idea or examples will be helpful.


text:
Q: How precise is a cron daemon? Is the cron job scheduler really precise?
I mean, I need a script to run every night the latest possible, BUT before 00:00 of the next day.
I'd ideally run a cron job at 23.59 (or 11:59 pm), but will the system be really precise? Since a second does matter, should I set the cron job to 23:58 to leave it some time?

A: Usually cron will start at 23:59:00, scan all your crontab files, filter out those who are relevant for 23:59 and then start them. Scanning this files is very fast, because there are not many of them and they all only include a few lines. So usually, the cronjobs start at 23:59:00 or 23:59:01
There are sure ways to intentionally slow down this process. (add millions of lines to the crontab, for example).
If the system is totally overloaded, this also won't work that fast.
Also, this is obviously implementation dependent.
If you need very exact start times, you are better off creating a programm that sleeps until the time you want and then runs (e.g. using c++11). But on a non real-time OS, this also won't be exact! Also the clock of the PC doesn't know the exact time!
In all cases, this only makes sure the program starts at (more or less) the time you want. There cannot be any guarantee that the program ends successful until a given time, so I strongly believe you should change something on that requirement.

A: What cron can guarantee is that your job will start no sooner than the specified time (subject to precision of the system clock). But there is no way to give you any guarantee about the termination time of the job. It will depend on a lot of factors:

*

*How loaded is the system

*What does the job do

*Slowness due to hardware issues

*Slowness due to networking issues (assuming the job depends on networking)

My recommendation is to change your design such that a specific completion time is not a requirement.

A: I suppose this depends on your cron daemon, but the documentation and the standard indicate that if you specify minutes, the job will execute at the specified minute.
See:

*

*The crontab documentation

*SUSv2 on crontab and the crontab file format
Be aware that your script will be started when the clock ticks over to the correct time, but will finish some time after that.

A: It depends from your overall script execution time and precision of server time.
59 23 * * * /some/script/file.sh

will launch your script exactly at 23:59, but, if you have some commands which works a long time, part of script may be executed after midnight.


text:
Q: Product of a disjoint cycle Would somebody help me with part (b) the following question?
I have proven part (a) but have no idea how to do (b).
Thank you!

A: Hint:
If $\gamma=(a_1\,a_2\,\dots\,a_r)$ is a cycle  in the decomposition of the permutation $\sigma_1$, $\tau\gamma\tau^{-1}$ is the cycle
$$\bigl(\tau(a_1)\,\tau(a_2)\,\dots\,\tau(a_r)\bigr),$$
so the question is really: given any two cycles with the same length, can you find a permutation that maps one cycle onto the other?

A: Hint:
Let
\begin{eqnarray*}
\sigma_1&=&(a_{1,1}a_{1,2} \cdots a_{1,l_1}) (a_{2,1}a_{2,2} \cdots a_{2,l_2}) \cdots (a_{r,1}a_{r,2} \cdots a_{r,l_r}) \\
\sigma_2&=&(b_{1,1}b_{1,2} \cdots b_{1,l_1}) (b_{2,1}b_{2,2} \cdots b_{2,l_2}) \cdots (b_{r,1}b_{r,2} \cdots b_{r,l_r}). \\
\end{eqnarray*}
Now if $ \sigma_2 =\tau \sigma_1 \tau^{-1}$ then $ \tau= ?$


text:
Q: Can I draw on top of a canvas inside of another canvas? I am creating a Solitaire clone using Python's Tkinter window toolkit. My window contains a main canvas, and within the main canvas a series of widgets that inherit from Canvas that hold the cards. I have implemented a "Drag to Move" system where a user can click the mouse down to select a card in one of the inner canvases, drag it to a new canvas, and let go to place the card into the receiving canvas.
The Problem: I want to draw the cards in motion between the canvas on which they are drawn, and the canvas they are moving to, so the user can see them moving across the screen during the click and drag motion. When I try to draw cards in-between the canvases that I already have, they are always drawn behind, meaning I can only see cards through the padding around the inner canvases.
Here is an example where I drew several of them so the effect could be seen clearly, and the inner canvases are also clearly visible.

What I've Tried: I've tried to move the canvases back using Misc.lower(aCanvas), but i wasn't able to create the desired effect. I've also tried to design a custom overridden cursor, but it seems my cursor size is limited to 32px*32px, which is insufficient for the size of the card images I want to move.
My Question: How can I draw on top of a canvas that is inside of another canvas? If I can't, how would you solve this problem?

A: You cannot do what you want. Embedded widgets are always above the canvas items.
Why is it that you are embedding canvases insidebcanvases? Why not just use a single canvas?


text:
Q: " Cannot use import statement outside a module" error while using jest and react I am trying to make a test using jest and react-testing-library but when I try to render the app inside a test block I am getting this error:
...{import axios from './lib/axios.js';

SyntaxError: Cannot use import statement outside a module

After a little research I see that jest ignores everything in node_modules when it transforms modules using babel-jest. Is there a way to allow the axios module to be transformed?
Here is my package.json file
{
  "name": "weather_app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest",
    "start": "webpack serve --config webpack.config.js",
    "react-dev": "webpack --mode development --watch",
    "server-dev": "npx nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.19.3",
    "@babel/plugin-proposal-class-properties": "^7.18.6",
    "@babel/preset-env": "^7.19.4",
    "@babel/preset-react": "^7.18.6",
    "@testing-library/react": "^13.4.0",
    "babel-jest": "^29.2.0",
    "babel-loader": "^8.2.5",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^6.7.1",
    "html-webpack-plugin": "^5.5.0",
    "jest": "^29.2.0",
    "jest-environment-jsdom": "^29.2.0",
    "react-test-renderer": "^18.2.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.11.1"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^6.2.0",
    "@fortawesome/free-solid-svg-icons": "^6.2.0",
    "@fortawesome/react-fontawesome": "^0.2.0",
    "axios": "^1.1.2",
    "dotenv": "^16.0.3",
    "mysql2": "^2.3.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "url": "^0.11.0"
  }
}

And my .babelrc file
    {
  "presets": [
    "@babel/preset-env",
    ["@babel/preset-react", {"runtime": "automatic"}],
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties"
  ]
}

I do not have any other config files for jest or babel

A: I found a solution. You can add a property to your jest.config.js file and specify modules from node modules to transform specifically but still ignore the rest of node modules. To tell babel-jest to transform axios it looked like this:
transformIgnorePatterns: ['<rootDir>/node_modules/(?!(axios)/)']

A: This axios issue (#5106) helped me (just downgrade axios to v0.27.2 and it works).


text:
Q: How to force alert window to pop-up After several time showing alert window the browser ask whether to prevent creating additional dialog.
Is there a way to force JavaScript show alert window even the user has checked the 'Prevent this page from creating additional dialog' ?

A: No, there isn't.
Thank goodness.
(you could, however, fake it with a modal dialog--possibly jQuery UI would suit your needs)

A: The whole point of that checkbox is to prevent sites from continuously spamming the user with alert boxes, preventing them from accessing anything in their browser anymore, even switching tabs. If it were possible for a site to continue posting new alert messages after the user decided he doesn't want to see it anymore, the whole buisness of "Don't click this link" where you'd end up on an infinite loop of alerts if you did click it, would be made possible again. Nobody wants that.


text:
Q: Java Thread : Query regarding Thread waiting state Suppose i have one synchronized block , and say 1000 threads access to that block simultaneously and one thread got access to sync block. Other 999 threads will go to waiting state till they are notified.
I want to know where exactly these 999 threads resides in waiting state. Which data structure is used to hold these 999 threads during waiting state and as soon as they are notified , how one thread is selected by jvm to get access to sync block.
Also any best article that covers thread synchronization and thread monitor. I googled it out but still confused how synchronization actually works internally.
Thanks

A: In java threads are user level threads. Unlike Kernel level threads these are managed by the client side library. This library takes care of handling the states of these threads. For example even if 10 threads out of your 1000 threads are processing on 10 different resources and 1 of the thread makes a system call then all the threads(of that process) are blocked with respect to the kernel. However for the user library only the one thread which made the system call is blocked while others are in running state.
Also there is no guarantee which thread will be acquire the next lock. If you want fairness you can use ReentrantLock which provides for more functionality than synchronized block. Also it has an optional fairness paramether which if set to true will provide lock to the thread who has waited the longest.