text:
Q: Proper nuclear fission simulation in C++ I'm trying to simulate atomic fission in C++.
Fissile nuclides have known probabilities to produce certain atomic numbers and mass numbers as fission products, such distributions are called fission products yield.
I know mass product and atomic product fission yields of uranium-235 (available here).
A fission product yield distribution adds up to 2, since a nuclear fission produces 2 new nuclides and 2 or 3 free neutrons.
While I may have misunderstood some physics concept, from a computer science point of view my problem is to generate 5 integers with known probability distributions, in pseudocode:
massYield = [...]
possibleMassProducts = [...]
atomicYield = [...]
possibleAtomicProducts = [...]
firstProductMassNumber = generateRandom(massYield, possibleMassProducts)
firstProductAtomicNumber = generateRandom(atomicYield, possibleAtomicProducts)
secondProductMassNumber = generateRandom(massYield, possibleMassProducts)
secondProductAtomicNumber = generateRandom(atomicYield, possibleAtomicProducts)
freeNeutrons = generateRandom([0.5, 0.5], [2, 3])

I've made a class called IntegerRandomGenerator which generates random numbers following a specific distribution:
class IntegerRandomGenerator
{
public:
    IntegerRandomGenerator(std::vector<double> distribution, std::vector<int> values)
    {
        size_t size_dist = distribution.size();
        size_t size_val  = values.size();
        if( size_dist != size_val )
        {
            throw std::invalid_argument("distribution and values vectors shall have the same length");
        }
        else
        {
            for( double p_i : distribution )
            {
                mDist.push_back(p_i);
            }
            for( int x_i : values )
            {
                mValues.push_back(x_i);
            }
        }
    }

    int generate();

private:
    std::vector<double> mDist;
    std::vector<int>   mValues;
    std::mt19937_64 mRng;
};

int IntegerRandomGenerator::generate()
{
    uint64_t timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();

    std::seed_seq ss{uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed>>32)};
    mRng.seed(ss);

    std::uniform_real_distribution<double> unif(0,1);
    double random = unif(mRng);

    uint32_t distSize = static_cast<uint32_t>(mDist.size());
    for(uint32_t i = 0; i < distSize; i++)
    {
        if(random < mDist.at(i))
        {
            return mValues.at(i);
        }
        else
        {
            random -= mDist.at(i);
        }
    }

    return -1;
}

Hence my strategy to generate fission products is the following:
std::vector<int> generateFissionValues(std::vector<double> aYields, std::vector<double> zYields, std::vector<int> aNumbers, std::vector<int> zNumbers)
{
    std::vector<double> massNormalized, atomicNormalized;
    std::vector<double> unif;
    std::vector<int> nNumbers;

    for(double p_i : aYields)
    {
        massNormalized.push_back(p_i/2);
    }

    for(double q_i : zYields)
    {
        atomicNormalized.push_back(q_i/2);
    }

    unif.push_back(0.5);
    unif.push_back(0.5);
    nNumbers.push_back(2);
    nNumbers.push_back(3);

    IntegerRandomGenerator massGenerator(massNormalized, aNumbers);
    IntegerRandomGenerator atomGenerator(atomicNormalized, zNumbers);
    IntegerRandomGenerator freeGenerator(unif, nNumbers);

    int a_Product1 = massGenerator.generate();
    int z_Product1 = atomGenerator.generate();

    int a_Product2 = massGenerator.generate();
    int z_Product2 = atomGenerator.generate();

    int freeNeutr = freeGenerator.generate();

    std::vector<int> fissionProducts;

    fissionProducts.push_back(a_Product1);
    fissionProducts.push_back(z_Product1);

    fissionProducts.push_back(a_Product2);
    fissionProducts.push_back(z_Product2);

    fissionProducts.push_back(freeNeutr);

    return fissionProducts;
}

What I expect to get, repeating this routine a fixed number of times and counting occurrencies of each atomic and mass number, is to get an empirical distribution which is similar to the theoretically known.
This is my main:
#define MIN_MASS_NUMBER 66
#define MIN_ATOMIC_NUMBER 23
#define MASS_YIELD_LENGTH 107
#define ATOMIC_YIELD_LENGTH 49

double MASS_YIELD[]=
{
        7.2405671e-10,  3.6155178e-09,  8.3798843e-09,  1.4793428e-08,  3.7126096e-08,  8.4074658e-08,  2.6566021e-07,
        1.0675927e-06,  3.3943611e-06,  1.0705677e-05,  3.0947722e-05,  7.5980282e-05,  2.0984921e-04,  4.4786922e-04,
        1.2829461e-03,  1.9049358e-03,  3.2662529e-03,  5.3619387e-03,  8.9643421e-03,  1.2891416e-02,  1.4066064e-02,
        2.5282028e-02,  3.4205412e-02,  4.7612426e-02,  5.8969791e-02,  5.8718196e-02,  5.9912701e-02,  6.2513918e-02,
        6.5931230e-02,  6.5585160e-02,  6.3729133e-02,  6.1194661e-02,  5.7681295e-02,  6.1623490e-02,  6.5885448e-02,
        5.1864512e-02,  4.2059644e-02,  3.0389326e-02,  1.8792336e-02,  9.7353401e-03,  4.0277579e-03,  1.4658471e-03,
        5.4222280e-04,  3.1255579e-04,  2.5608411e-04,  1.7477930e-04,  1.3934770e-04,  1.3765549e-04,  1.1957731e-04,
        1.3077006e-04,  1.3324824e-04,  1.1755897e-04,  1.1374826e-04,  1.2290949e-04,  1.2642393e-04,  1.3080367e-04,
        1.5523846e-04,  1.1021012e-04,  2.6858588e-04,  2.9061019e-04,  5.8370361e-04,  1.5268885e-03,  3.4896815e-03,
        5.3614445e-03,  1.8159164e-02,  2.8895004e-02,  4.3250233e-02,  6.7141993e-02,  7.8703816e-02,  6.5640320e-02,
        6.1137911e-02,  6.3605380e-02,  6.7934012e-02,  6.4934315e-02,  6.2395971e-02,  5.8687079e-02,  5.8447475e-02,
        5.9831620e-02,  5.5176036e-02,  3.9532454e-02,  3.0059773e-02,  2.2527624e-02,  1.6771722e-02,  1.0853545e-02,
        6.5508342e-03,  4.1317995e-03,  2.6763110e-03,  1.5870986e-03,  7.4634286e-04,  3.2221285e-04,  1.4892861e-04,
        6.1673994e-05,  3.2940204e-05,  1.0121245e-05,  3.1986347e-06,  8.5523451e-07,  1.5949051e-07,  6.1183839e-08,
        1.8867389e-08,  9.5405554e-09,  3.6338899e-09,  2.4780248e-09,  5.7277553e-10,  2.3914282e-10,  5.0200588e-11,
        2.3540988e-11,  7.7074464e-12
};

double ATOMIC_YIELD[]=
{
        2.0558300e-19,  2.8862345e-14,  1.3368750e-11,  1.6193162e-09,  1.3709663e-08,  3.0150265e-07,  3.6301782e-06,
        1.1200954e-04,  7.0351909e-04,  4.4498299e-03,  9.1719425e-03,  3.6528367e-02,  5.2682609e-02,  1.5625724e-01,
        1.2071735e-01,  1.9331319e-01,  1.2675553e-01,  1.8037105e-01,  6.8939851e-02,  4.3268378e-02,  3.4683702e-03,
        4.1462569e-04,  2.2779437e-04,  3.4012286e-04,  2.7543142e-04,  1.6063619e-03,  1.7210332e-03,  3.6208508e-02,
        7.7033688e-02,  1.7331044e-01,  1.1582092e-01,  2.0090419e-01,  1.1037331e-01,  1.6401242e-01,  6.0615264e-02,
        4.1834320e-02,  1.3435892e-02,  4.5405310e-03,  4.6638638e-04,  1.0987593e-04,  5.1296865e-06,  3.9564637e-07,
        1.1679425e-08,  1.9805406e-09,  7.0990343e-11,  4.8416648e-12,  2.4283831e-14,  2.4747259e-17,  0.0000000e+00
};

int main()
{
    const int nSim = 10000;

    std::vector<double> distMass(std::begin(MASS_YIELD), std::end(MASS_YIELD));
    std::vector<double> distAtom(std::begin(ATOMIC_YIELD), std::end(ATOMIC_YIELD));
    std::vector<int>   massNumbers;
    std::vector<int>   atomNumbers;

    for(int i = 0; i < MASS_YIELD_LENGTH; i++)
    {
        massNumbers.push_back(i + MIN_MASS_NUMBER);
    }
    for(int i = 0; i < ATOMIC_YIELD_LENGTH; i++)
    {
        atomNumbers.push_back(i + MIN_ATOMIC_NUMBER);
    }

    int countsPerZ[ATOMIC_YIELD_LENGTH];
    std::vector<double> relCountsPerZ;

    int countsPerA[MASS_YIELD_LENGTH];
    std::vector<double> relCountsPerA;

    memset(countsPerZ, 0x00, ATOMIC_YIELD_LENGTH * sizeof(int));
    memset(countsPerA, 0x00, MASS_YIELD_LENGTH * sizeof(int));

    std::cout << "Start " << nSim << " atomic fission simulations . . ." << std::endl;
    for(int i = 0; i < nSim;)
    {
        std::vector<int> fissionProducts = generateFissionValues(distMass, distAtom, massNumbers, atomNumbers);

        int a1 = fissionProducts.at(0);
        countsPerA[a1 - MIN_MASS_NUMBER] += 1;

        int z1 = fissionProducts.at(1);
        countsPerZ[z1 - MIN_ATOMIC_NUMBER] += 1;

        int a2 = fissionProducts.at(2);
        countsPerA[a2 - MIN_MASS_NUMBER] += 1;

        int z2 = fissionProducts.at(3);
        countsPerA[z2 - MIN_ATOMIC_NUMBER] += 1;

        i++;

        double percentage = (100.0 * i)/nSim;
        printf("Progress: %d %%\r", static_cast<int>(percentage));
        fflush(stdout);
    }

    //here I pass countsPerA and countsPerZ to another function which plots results
}

Here are my results, out of 10000 repetitions of the experiment.
For Mass Numbers:

For Atomic Numbers:

It is strange because with the same strategy, atomic numbers seems to be correctly simulated, while mass numbers definitely not. What am I doing wrong with mass numbers?

A: When you're populating the countsPerA and countsPerZ arrays:
    int a1 = fissionProducts.at(0);
    countsPerA[a1 - MIN_MASS_NUMBER] += 1;

    int z1 = fissionProducts.at(1);
    countsPerZ[z1 - MIN_ATOMIC_NUMBER] += 1;

    int a2 = fissionProducts.at(2);
    countsPerA[a2 - MIN_MASS_NUMBER] += 1;

    int z2 = fissionProducts.at(3);
    countsPerA[z2 - MIN_ATOMIC_NUMBER] += 1; //typo here

You're adding data from the atomic numbers results into the Mass Numbers count due to a typo.


text:
Q: Animate children inside StackPanel - WPF (C#) I have a StackPanel with UserControls as the children. I would like to apply a Storyboard animation which increases the height of the children from 0 to 100 in a second which creates a smooth slide down animation. This will be called for when a new child is added to the StackPanel - StackPanel1.children.Add(usercontrol1). The StackPanel children are UserControls so I do not want to use DataTemplates. Below is an example layout of what I mean.

Could someone please help me create this as I have no idea how to make it. Thank you.

A: You need To target the object for the StoryBoard.
private void Button_Click(object sender, RoutedEventArgs e)
{
    var usercontrol1 = new Label();
    usercontrol1.Background = new SolidColorBrush(Colors.Red);
    usercontrol1.Content = "Hello";
    usercontrol1.Name = "UniqueName" + System.Guid.NewGuid().ToString("N");
    RegisterName(usercontrol1.Name, usercontrol1);

    StackPanel1.Children.Add(usercontrol1);
    // Create a DoubleAnimation to animate the width of the button.
    DoubleAnimation myDoubleAnimation = new DoubleAnimation();
    myDoubleAnimation.From = 0;
    myDoubleAnimation.To = 100;
    myDoubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(1000));

    // Configure the animation to target the button's Width property.
    Storyboard.SetTargetName(myDoubleAnimation, usercontrol1.Name);
    Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Button.HeightProperty));

    // **Set the Target Object for the Animation.**
    Storyboard.SetTarget(myDoubleAnimation, usercontrol1);

    // Create a storyboard to contain the animation.
    Storyboard myWidthAnimatedButtonStoryboard = new Storyboard();
    myWidthAnimatedButtonStoryboard.Children.Add(myDoubleAnimation);
    myWidthAnimatedButtonStoryboard.Begin(usercontrol1);

}

A: Well, that's more or less a copy paste from the link written in the comment above.
First, you need to create your control (let's say usercontrol1) and give it a unique name for the storyboard to reference it.
EDIT: Below is a code of a simple application that works:
XAML:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="800"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <StackPanel Name="StackPanel1">

    </StackPanel>
    <Button Grid.Row="1" Click="Button_Click">

    </Button>
</Grid>

and code behind:
private void Button_Click(object sender, RoutedEventArgs e)
    {
        var usercontrol1 = new Label();
        usercontrol1.Background = new SolidColorBrush(Colors.Red);
        usercontrol1.Content = "Hello";
        usercontrol1.Name = "UniqueName" + System.Guid.NewGuid().ToString("N");
        RegisterName(usercontrol1.Name, usercontrol1);

        StackPanel1.Children.Add(usercontrol1);
        // Create a DoubleAnimation to animate the width of the button.
        DoubleAnimation myDoubleAnimation = new DoubleAnimation();
        myDoubleAnimation.From = 0;
        myDoubleAnimation.To = 100;
        myDoubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(1000));

        // Configure the animation to target the button's Width property.
        Storyboard.SetTargetName(myDoubleAnimation, usercontrol1.Name);
        Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Button.HeightProperty));

        // Create a storyboard to contain the animation.
        Storyboard myWidthAnimatedButtonStoryboard = new Storyboard();
        myWidthAnimatedButtonStoryboard.Children.Add(myDoubleAnimation);
        myWidthAnimatedButtonStoryboard.Begin(usercontrol1);

    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to add or set up two log paths for logging in laravel or lumen? There is provision to change log paths according to log levels. But what if, i have two different path for log files each contains log with all levels or custom configured level?
For example I have two paths for Api Logs and Sms Logs having different path.
How can i define two logs? currently logging is done like
ex

Log::emergency('Log string');

This string is logged according to defined stream handler of emergency level.
But instead i want this log to write in API path log or Sms path log.

A: Laravel used the Monolog as far as I can remember, go ahead and check that out. Monolog is really flexible and gives you a ton of control.
If you want to use Monolog's advanced features, I assume you can just do it out of the box as advertised:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$view_log = new Logger('View Logs');
// used the different path for laravel or lumen
$view_log->pushHandler(new StreamHandler('path/to/log.log', Logger::INFO));
$view_log->addInfo("User $user clicked");


text:
Q: ggplot error in if (node$tag == "span") after trying to split a faceted plot over multiple pages My dataset includes the variable "annual_TRW" measured over different "survey_year", with 5 "Sample_Core_ID" within each "block" nested within each "site".
The following code was working to plot all samples for a plot subset.
pdf("plots.pdf")
library(ggplot2)

dataset %>%
  group_by(site, block, Sample_Core_ID ) %>%
  ggplot(., aes(x = survey_year, y = annual_TRW, colour = Sample_Core_ID)) +
  geom_line() +
  facet_grid(Sample_Core_ID ~ .)

dev.off()

Then, I was trying to split a faceted plot over multiple pages, with each page including the faceted plots (1 column, 5 rows) corresponding to the samples of each block. I was testing using different different functions ggplus::facet_multiple, gridExtra::marrangeGrob, and ggforce::facet_wrap_paginate, but without success i.e. pdf were created empty.
The problem is that, after trying different options, now I get the following error every time that I try to use any ggplot on the same dataset. Now, I dont manage to plot the code that worked before without giving this error.
Error in if (node$tag == "span") { : argument is of length zero

Question 1: How can I solve this error every time I try to use this ggplot?
Question 2: Once this works again, how can I split the faceted plot over multiple pages as explained before?
Thanks a lot in advance!
I tried re-running the entire code, and re-calling the packages, but it doesnt work.

A: Regarding Problem 1: the error was "temporarily" solved after updating the R version and reinstalling only the necessary packages that worked. (I thought the issue might have come from installing the packages ggplus as described here https://github.com/guiastrennec/ggplus).
However, after updating the R version, a new issue appeared: How to plot in RStudio and not have a new window pop up (R Graphics: Device (ACTIVE)?
Then I solved it by updating the R studio version ..... BUT this returned me to the original problem again when trying to plot !!! =S =( So frustrating ...
Error in if (node$tag == "span") { : argument is of length zero


text:
Q: Algorithm generating subset of primes, can we classify which of them or estimate how large percent of primes are generated? Assume I have following algorithm:
Two lists of numbers, first starting at 2, second starting empty.
We now follow rule:

*

*Add a number to first list which makes difference with latest number the smallest prime not already in either list. Add this difference to list nr 2.

After some iterations we will get:
[2,5,12,23,36,53,...] with primes 5,23,53
[3,7,11,13,17,...] with (by construction) all members a prime, but lacking precisely the ones in list 1.
Example of executing algorithm:

*

*First state 2 is only prime in either list, smallest prime is 3, so we add it as new element: Now we have [2,2+3] first list, [3] second list

*Next state is [2,5], [3], we see smallest prime not in either list is 7, so we update [2,5,5+7],[3,7]

*Next state is [2,5,12], [3,7], smallest prime not in either is 11, so we update: [2,5,12,12+11], [3,7,11]

*Next state is [2,5,12,23], [3,7,11], smallest prime not in either is 13, so we update : [2,5,12,23+13], [3,7,11,13]

*And so on

We will get one subset of primes in list 2 and it's complement will be another subset of primes.
Can we say anything about how large percent of primes will be in first list after say, $n$ iterations?

A: Almost all primes will end up in the second list.
Because the differences between successive elements of the first list start at $3$ and increase by at least $2$ each time, it is easy to show by induction that the $n$th term of the first list is at least $n^2$. Thus of the first $N$ integers, at most $\sqrt N$ appear in the first list.
However, by the prime number theorem, of the first $N$ integers about $\frac{N}{\log N}$ are prime. At most $\sqrt N$ of these primes are in the first list, so the proportion of primes less than $N$ which appear in the first list is about $\frac{\log N}{\sqrt{N}}$, and tends to $0$.


text:
Q: Python default version not opening by default (Windows) It seems my default python is v3.11 (indicated by the asterisk when doing command line "py -0p") and yet at the same time it says it's v3.10 (command line "python --version") and v3.10 is also the version it opens by default via command line.
I've updated the environment variables (PY_PYTHON and Path) to point to v3.11, as well as the registry setting Computer\HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command, but still no joy.
Anyone any idea what else might be affecting this?
see the conflicting command line results here

A: The easiest way to switch to the newest version is to uninstall the older ones but if you want to keep them, try restarting your cmd.


text:
Q: Reorder array based on values I have an array with classes (the class is called Note), and in those classes are basic values. Two important values are the Note.Pinned (boolean whether it's pinned or not) and Note.Modified (a timestamp when it was last edited).
I would like to sort this array of classes by the Modified timestamp, then reorder it that the Pinned notes are on top of this list.
I already tried sorting the notes.
const SortedNotes = Notes.sort((a, b) => a.Modified > b.Modified);

Notes being the array with classes.
But, then, is there a better way to rearrange this array? Or is this the only method I can use?
SortedNotes.filter(n => n.Pinned).concat(SortedNotes.filter(n => !n.Pinned));

The above would work, and I know I can use Array.prototype.partition, so is there any other way of doing this?
Thanks

A: You can just add the pinned sorting requirement to the sort:

const arr = [{
    pinned: false,
    modified: 7
  },
  {
    pinned: false,
    modified: 6
  },
  {
    pinned: true,
    modified: 2
  },
  {
    pinned: false,
    modified: 4
  },
  {
    pinned: true,
    modified: 1
  },
  {
    pinned: true,
    modified: 8
  },
  {
    pinned: false,
    modified: 3
  },
]

arr.sort((a, b) => {
  if (a.pinned != b.pinned)
    return a.pinned ? -1 : 1;
  return b.modified - a.modified;
})

console.log(arr)

As long as the execution of the sort function returns the same result for the same two given parameters the sort will work fine. Knowing this, you can handle the two states where the pinned state is different and then sort by modified only if the pinned state is the same.

A: Not the best solution perhaps, but this should help you in the right direction.
This sorts the array so that notes are in decending date order, with the pinned ones at the top.
Unlike other (better) answers, this has a O(2n) sorting complexity, so bear that in mind.

const notes = [
  {
    text: "foo",
    modified: 1583337610387,
    pinned: false
  },
  {
    text: "bar",
    modified: 1583337610388,
    pinned: true
  },
  {
    text: "baz",
    modified: 1583337610389,
    pinned: false
  },
  {
    text: "qux",
    modified: 1583337610390,
    pinned: true
  }
];

const sortedNotes = [...notes];
sortedNotes.sort((a, b) => a.modified > b.modified ? -1 : 1);
sortedNotes.sort((a, b) => (a.pinned === b.pinned) ? 0 : a.pinned ? -1 : 1);
console.log(sortedNotes);

A: You can sort by multiple conditions:
const SortedNotes = Notes.sort((a, b) => {
  if (a.Pinned == b.Pinned) {
    if (a.Modified > b.Modified) return -1;
    if (a.Modified < b.Modified) return 1;
  } else {
    return a.Pinned ? -1 : 1;
  }
});

The missing branch of a.Pinned == b.Pinned && a.Modified == b.Modified would return undefined, which in turn would be interpreted as equal.
Btw, the array Notes itself would've been modified in place, so both SortedNotes and Notes would exhibit the same ordering; of course, assigning to a const variable can't hurt.

A: Shorter, you can try
const SortedNotes = Notes.sort((a, b) => {
    if (a.Pinned > b.Pinned)
       return 1;
    if (a.Pinned == b.Pinned)
       return a.Modified > b.Modified;
    return -1;
})

A: I edited @Ja͢ck's answer to be a little more compact.
const SortedNotes = Notes.sort((a, b) => {
    if (a.Pinned == b.Pinned) return a.Modified > b.Modified ? -1 : 1;
    else return a.Pinned ? -1 : 1;
});


text:
Q: How to check if a row is affected with codeigniter active record I search through the net but i didn't find any solution,
My problem is that how do I now during update that if a row values has changed or not
or if a row is affected?

A: use affected_rows();
 $this->db->affected_rows()

Displays the number of affected rows, when doing "write" type queries (insert, update, etc.).

A: When we are working with CodeIgniter, the data is only updated when there is some change in the input field's value and then the $this->db->affected_rows() will return a value greater than 0.
Suppose we have two fields, 'name' and 'email'.  If we try to submit the form without changing any of the field, then $this->db->affected_rows() will return 0, else it will return 1.
A better approach is to use:
if ($this->db->affected_rows() >= 0) {
    return true; // your code
} else {
    return false: // your code
}

A: I think this is the simplest way to achieve this goal.
return ($this->db->affected_rows() != 1) ? false : true;


text:
Q: Magento2: php bin/magento setup:di:compile issue When I run this command php bin/magento setup:di:compile got the error below:
[ReflectionException]
Class Magento\Catalog\Model\Product\Link\Resolver does not exist.

A: please check your vendor/magento folder the Resolver class should be exist in this path :
<folder_root>/vendor/magento/module-catalog/Model/Product/Link/

if you don't see the class file maybe it's deleted or there is something wrong in your magento installation
as @Miroslav Petroff comment, it could be 3rd extension that inject existing core class. you can checking again 3rd extension that already install in your magento project :)


text:
Q: Simple way to use mod_rewrite My site has two parts that uses id to unique identify itens. How can i use mod_rewrite to change both URLs when the user click on them?
URL1:
http://www.example.com/category.php?id=1
URL2:
http://www.example.com/article.php?id=1
Would like:
URL1: http://www.example.com/category/1
URL2: http://www.example.com/article/1
With the code below i've achieved what i want but loses the CSS style:
RewriteEngine On
RewriteRule ^category/([a-z0-9]+)$ category.php?id=$1
RewriteRule ^article/([a-z0-9]+)$ article.php?id=$1

Appreciate any help!

A: You can achieve that result doing this:
RewriteEngine On
RewriteRule ^category/(\d+)$ category.php?id=$1
RewriteRule ^article/(\d+)$ article.php?id=$1

A: To solve the problem i had to add (/) before each path of the link style and js source:
Before:
<link type = "text/css" rel = "stylesheet" href = "css/style.css">
<script src="js/bootstrap.min.js"></script>

After
<link type = "text/css" rel = "stylesheet" href = "/css/style.css">
<script src="/js/bootstrap.min.js"></script>


text:
Q: iphone get both camera image for iphone 7 plus? Can I get both images of regular and wide angle camera at the same time? What about videos, can I get video streams from both cameras?

A: I have not done but you can do it by View containers. Add 2 ViewController contener to the UIViewController and add UIImagePickerController in both containers.
In first Container make CameraMode to frontCamera and for second Container make cameraMode to BackCamera.
Hope it helps.


text:
Q: PyCharm: auto-insert Django template closing-tags ( {% endif %} {% endfor %} , etc. ) option? I've yet to find a setting that will enable auto-insertion of these closing tags, similar to how closing HTML tags are handled.
Is this even possible?

A: Just hit tab after if
{% if<tab>

and you get
    {% if <cursor> %}

    {% endif %}

This works for many tags: for, block, filter, spaceless, with, but inexplicably not blocktrans, autoescape, and comment changes to <comment></comment>


text:
Q: Proof Verification: $T$ is complete if and only if $\text{Mod}(T)$ satisfies the joint embedding property This answer has an example exercise to show a relationship between the joint embedding property of the category of models of a given theory and the completeness of that theory, paraphrased in the section below with links to definitions.
I tried to prove it. I'm pretty sure my proof attempt works but I'm not totally certain.

*

*Does the proof attempt work?

*Is there a more elegant way to prove this?

*Am I assuming any nontrivial results improperly (e.g. without naming the theorem when it would be idiomatic to name it)?

A theory $T$ is complete if and only if its category of models with arrows given by elementary embeddings $\text{Mod}(T)$ satisfies the joint embedding property.

Suppose that $T$ is complete.
For any pair of objects $x$ and $y$ in $\text{Mod}(T)$, $x$ and $y$ are elementarily equivalent because they satisfy the same sentences due to the completeness of $T$. Suppose without loss of generality that $|x| \le |y|$, then there exists an elementary embedding $f : x \to y$. The cardinals are totally ordered and every object has an identity arrow going to itself, therefore both $x$ and $y$ have arrows going to $\max(x, y)$, the larger of the two by cardinality, or $x$ if they have the same cardinality. Since $x$ and $y$ were chosen arbitrarily, $\text{Mod}(T)$ has the joint embedding property.
Suppose $T$ satisfies the joint embedding property.
For any objects $x$ and $y$ in $\text{Mod}(T)$, there exists an object $z$ so that there exist arrows $f : x \to z$ and $g : y \to z$. By definition of $\text{Mod}(T)$, if an arrow exists between two objects, then they satisfy the same sentences. Therefore, $x$ satisfies the same sentences as $z$ and $y$ satisfies the same sentences as $z$. Therefore, $x$ satisfies the same sentences as $y$. Since $x$ and $y$ were chosen arbitrarily, this means that all models satisfy the same sentences. Thus, $T$ is complete.

A: As others have pointed out in the comments, your proof of the implication "complete$\implies$ JEP" is not quite right. In particular, the claim that $|M|\leqslant |N|$ implies the existence of an elementary embedding $M\to N$ is not true in general. Alex gives a nice example of this, but here is perhaps a simpler one:
Let $\mathcal{L}=\{P_1,P_2\}$ consist of two unary predicate symbols, and let $T$ assert that $P_1\cap P_2=\emptyset$, that each $P_i$ is infinite, and that every element belongs to one of the $P_i$. Then $T$ is $\aleph_0$-categorical (why?), and is hence in particular complete. However, consider a model $M$ of $T$ where $|P_1^M|=\aleph_1$ and $|P_2^M|=\aleph_1$, and a model $N$ of $T$ where $|P_1^N|=\aleph_0$ and $|P_2^N|=\aleph_2$. Then $|M|=\aleph_1<\aleph_2=|N|$, but there is no elementary embedding $M\to N$,  since such an embedding would induce an injection $P_1^M\to P_1^N$.
There is a relevant notion you might find interesting, of a "prime model" of a complete theory, the defining property of which is that they elementarily embed into every other model. You can read about these in, eg, chapter 4 of Marker.

Here's an alternative proof.
Let $\mathcal{L}'=\mathcal{L}\cup\{c_a\}_{a\in M}\cup\{d_b\}_{b\in N}$, where the $c_a$ and $d_b$ are constant symbols corresponding to the elements of $M$ and $N$, respectively. We can naturally consider $M$ as an $\mathcal{L}\cup\{c_a\}_{a\in M}$-structure, by realizing each $c_a$ as $a$; let $T_M$ be the set of all $\mathcal{L}\cup\{c_a\}_{a\in M}$ sentences satisfied by $M$. (This is known as the "elementary diagram" of $M$.)
Similarly, let $T_N$ be the elementary diagram of $N$ in the language $\mathcal{L}\cup \{d_b\}_{b\in N}$, and let $T'=T\cup T_M\cup T_N$. Can you use completeness of $T$ to show that $T'$ is finitely satisfiable?

 Since $M\models T\cup T_M$, it suffices to show that $T_N$ is finitely satisfiable in $M$. By taking conjunctions, we therefore just need to to show that $\psi(d_{b_1},\dots,d_{b_n})$ is satisfiable in $M$ for any $\mathcal{L}$-formula $\psi(\overline{w})$ with $\psi(\overline{d})\in T_N$. By construction, we know $$N\models\psi(d_{b_1},\dots,d_{b_n}),$$ and so in particular $N\models\exists w_1,\dots,w_m\ \psi(w_1,\dots,w_n)$. Moreover, the sentence $\exists \overline{w}\ \psi(\overline{w})$ is an $\mathcal{L}$-sentence (ie, it contains no symbols outside $\mathcal{L}$). Since $T$ is complete, this means we must have $\exists \overline{w}\ \psi(\overline{w})\in T$, and hence $M\models\exists\overline{w}\ \psi(\overline{w})$. Interpreting the $d_{b_i}$ as witnesses of this sentence in $M$ then gives the desired result.

Thus $T'$ is finitely consistent, and so – by compactness – there exists an $\mathcal{L}'$-structure $O$ modeling $T'$. Now, consider the functions $f:M\to O$ and $g:N\to O$ given by $f(a)=c_a^O$ and $g(b)=d_b^O$. Can you show that this map is an elementary $\mathcal{L}$-embedding?


text:
Q: Exchange principle in terms of states and coordinates? I have seen the exchange principle written in two ways, one in terms of coordinates and the other in terms of states:

If $\psi_{AB}(1,2)$ represents particle $A$ in state $1$ and particle $B$ in state $2$ then for bosons:
  $$\psi_{AB}(1,2)=\psi_{AB}(2,1)$$ and for fermions: $$\psi_{AB}(1,2)=-\psi_{AB}(2,1)$$

and

If $\psi_{AB}(\vec x_1, \vec x_2)$ represents particle $A$ at $\vec x_1$ and particle $B$ at $\vec x_2$ then for bosons:
  $$\psi_{AB}(\vec x_1,\vec x_2)=\psi_{AB}(\vec x_2,\vec x_1)$$ and for fermions: $$\psi_{AB}(\vec x_1,\vec x_2)=-\psi_{AB}(\vec x_2,\vec x_1)$$

Do both these tell us the exactly same information (i.e. may one hold when the other doesn't) and can this be shown?

A: In the first convention, by state they mean total state (including spatial and spin components) but for the second convention, by state they mean only spatial component. This means that the first convention has more information and hence more restrictive. Particles can be at the same place (following the second convention) yet have different spin states (not following the first convention). So, the second convention is a subset of the first convention by being less restrictive.
By the end of the day, however, fermions should have an antisymmetric total state and bosons should have a symmetric total state.

A: I am pretty sure that the vector $\vec{x}$ includes spin coordinates.
The coordinate itself is an observable which has a continuum spectrum. So a coordinate operator has eigenvalues that characterize a state. So there is no much difference between the first and second definition, since instead of saying an electron has a coordinate $x$, we can also say that the electron is in the state $x$.


text:
Q: Rewriting Markov process Let $X$ be a Markov proces with state space $(E,\mathcal{E})$with initial distribution $\nu$ and transition function $P_{t}$, so $$E_{\nu}(f(X_{t+s})\mid\mathcal{F}_{s})=P_{t}f(X_{s})$$
Suppose that $(E',\mathcal{E}')$ is a measurable space and let $\phi:E\rightarrow E'$ be measurable and onto.
Let $Q_{t}$ be a collection of kernels such that $$P_{t}(f\circ\phi)=(Q_{t}f)\circ\phi$$
I would now like to prove that $\phi(X)$, is a Markov process with respect to the state space $(E',\mathcal{E}')$, initial measure $\nu'$, where $\nu'(B')=\nu(\phi^{-1}(B'))$ and transition function $Q_{t}$.
So basically I would like to prove that $$E_{\nu'}(f(\phi(X_{t+s}))\mid\mathcal{F}_{s})=Q_{t}f(\phi(X_{s}))$$
Here is my try as $\phi$ is onto and f is assumed to be a bounded function
$$E_{\nu'}(f(\phi(X_{t+s}))\mid\mathcal{F}_{s})=E_{\nu}(\phi^{-1}(f(\phi(X_{t+s})))\mid\mathcal{F}_{s})$$
$$=P_{t}\phi^{-1}(f(\phi(X_{s})))=(Q_{t}\phi^{-1})(f(\phi(X_{s})))$$
From this point on I do not know how to proceed.
Could anyone help me further?

A:
So basically I would like to prove that $$E_{\nu'}(f(X_{t+s})\mid\mathcal{F}_{s})=Q_{t}f(X_{s})$$

No, basically you would like to prove that, if $Y_t=\phi(X_t)$ and $\mathcal{F}^Y_t=\sigma(Y_s;s\leqslant t)$ for every $t$, then
$$
E_{\nu'}(f(Y_{t+s})\mid\mathcal{F}^Y_{s})=Q_{t}f(Y_{s}),
$$
not what you wrote. You could then show that this is equivalent to
$$
E_{\nu}(f(\phi(X_{t+s}))\mid\mathcal{F}_{s})=Q_{t}f(\phi(X_{s})),
$$
the definition of $\nu'$ allowing you to replace $\nu'$ by $\nu$, and the hypothesis that $\phi$ is onto allowing you to replace each $\mathcal{F}^Y_{s}$ by $\mathcal{F}_{s}$. You might want to proceed from there.


text:
Q: Determine angular momentum from angular velocity for SKSpriteNode I have an node in space (no angular dampening, no friction, no gravity) and I apply a torque to it (20 newton meters) over 1 second.  It begins to spin and will continue forever.  If I apply an inverse force (-20 newton meters) it comes to a complete stop.
If I don't know how much angular torque was applied initially (for instance it collided with another object), how can I determine what the inverse torque to apply would be in order to bring the object to a stop?  I tried angularVelocity*mass, and this is close... but always a little shy (like I'm missing something):
-physicsBody!.angularVelocity*physicsBody!.mass

How can I determine Angular Momentum (torque) to use to remove all object rotation?

A: In my games I use active braking to manage stopping a node's motion over time.  I do this in the update() function.   For your requirements, I present this answer:
let X = -0.2  // This needs to be customized by your needs .. how fast you want to stop.
var need_braking_list : [SKSpriteNode] = []   // Append your spinning nodes here

override func update() {
    for (index,node) in need_braking_list {
        // We're almost stopped, so force a stop or this goes on forever.
        if node.physicsBody?.angularVelocity < 0.1 &&
               node.physicsBody?.angularVelocity > (-0.1)
        {
             node.physicsBody?.angularVelocity = 0
             need_braking_list.removeAtIndex(index)
        // Apply some braking ... screeech
        } else {
            let impulse_factor = node.physicsBody?.angularVelocity * (X)
            node.physicsBody?.applyAngularImpulse(impulse_factor)
        }
    }
}

Hope this helps!

A: How about whenever torque is applied (like during collision detection), save the value in the nodes's .userData for future reference?
edit:
Do you need to apply an opposing impulse, or can you just stop the rotation by setting angularVelocity to zero? Or potentially slowly reducing it toward zero through SKActions?

A: In space there is no drag, so if you apply a force to an object the object will continue accelerating for as long as the force is applied. Similarly, the force you need to apply to stop your object needs to have a certain magnitude and be applied for a specific time in order to stop your object, because if you just apply the force continuously then the object will start to go back from where it came. So, you'd need to know the force and the time during which it was applied (almost instantly) in order to create an equal force to cancel its effects. I don't think this is the right approach.
What you need to do is to determine the direction of your moving object (I'll call this the speed vector, which is determined by the object's position now and its position one frame earlier) and apply a force opposed to that vector with, say, module 1 (or bigger if you want to slow your object earlier). And keep applying that force until the speed of your object (the speed vector) is zero. If you want a smooth reduction of speed and better results, linearly decrease the module of your opposing force as time advances.
Was this what you needed?


text:
Q: Query MySQL database and display using variable from response I got this far by reading here on Stack Overflow. I have a table full of delivery hubs. Table structure is:
name - name of hub
zip - zip code of hub
lng - longitude of hub
lat - latitude of hub
radius - delivery radius

I am currently using this to get the closest delivery hub:
$dist1 = '20';

$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare("SELECT name,
       lat,
       lng,
       zip,
       radius,
       3956 * 2 * Asin(Sqrt(Power(Sin(( :lat - lat ) * Pi() / 180 / 2), 2) +
                                            Cos(:lat * Pi() / 180) * Cos(
                                            lat * Pi() / 180) *
                                            Power(Sin(( :lng - lng ) * Pi()
                                                           /
                            180 / 2), 2))) AS dist
FROM   hubs
WHERE  lng BETWEEN ( :lng - :dist1 / Cos(Radians(:lat)) * 69 ) AND ( :lng +
                          :dist1 / Cos(Radians(:lat
                                      )) * 69 )
       AND lat BETWEEN ( :lat - ( :dist1 / 69 ) ) AND ( :lat + ( :dist1 / 69 ) )
HAVING dist < :dist1
ORDER  BY dist
LIMIT  100 ");

$stmt->execute([
  'lng' => $lng,
  'lat' => $lat,
  'dist1' => $dist1
]);

while ($row = $stmt->fetch()) {

  if ($row['radius'] >= $row['dist']){

    echo $row['name'];
    echo " - ";
    echo $row['zip'];
    echo " - ";
    echo $row['dist'];
    echo "<br>";

  }

}

I would optimally like to eliminate the $dist1 variable from the query and instead only display the closest delivery hubs that deliver in that radius set by the hub, using only MySQL, not PHP (as I am using now).
How can I do this?

A: Easy, change your MySQL to this:
SELECT name,
       lat,
       lng,
       zip,
       radius,
       3956 * 2 * Asin(Sqrt(Power(Sin(( :lat - lat ) * Pi() / 180 / 2), 2) +
                                            Cos(:lat * Pi() / 180) * Cos(
                                            lat * Pi() / 180) *
                                            Power(Sin(( :lng - lng ) * Pi()
                                                           /
                            180 / 2), 2))) AS dist
FROM   hubs
WHERE  lng BETWEEN ( :lng - radius / Cos(Radians(:lat)) * 69 ) AND ( :lng +
                          radius / Cos(Radians(:lat
                                      )) * 69 )
       AND lat BETWEEN ( :lat - ( radius / 69 ) ) AND ( :lat + ( radius / 69 ) )
HAVING dist < radius
ORDER  BY dist
LIMIT  1


text:
Q: Патч datetime.timedelta.total_seconds Я столкнулся с проблемой при тестировании python модуля.
Мне необходимо изменить задержку TIME_TO_WAIT выполнения функции в тесте.
Примерный код функции:
import time
from datetime import datetime as dt

def function_under_test():
    TIME_TO_WAIT = 300
    start_time = dt.now()
    while True:
        if (dt.now() - start_time).total_seconds() > TIME_TO_WAIT:
            break
        time.sleep(1)

Я вижу решение в заплате для datetime.timedelta.total_seconds(), но не знаю, как правильно это сделать.

A: Можно попробовать модуль mock или готовую библиотеку freezegun


text:
Q: get UserName without the 20 char Limit I have to read the user log in my app even with run as and the name created in domain in windows server 2012have 23 char,
i used :
Environment.UserName

new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name;

System.Security.Principal.WindowsIdentity.GetCurrent().Name

but all this give me the name without the 3 last char
I used :
UserPrincipal.Current.UserPrincipalName
UserPrincipal.Current.Name

but give me the displayed name
how can i get the full length login name

A: This is a hard limit on the samAccountName property:

"You can't modify the length of the user's samAccountName, it is a
  defined value within the schema and is set to 20."

See: this page for source
Maybe you could try the UserPrincipalname
System.DirectoryServices.AccountManagement.UserPrincipal.Current().UserPrincipalName

you need to add a reference to the AccountManagement Namespace


text:
Q: "See an example" Is it correct to talk about a product on a website and then show a button "See an example" next to it?
I wonder if the verb "see" is correct here or if I must use another verb, like "Watch an example" or "Check out an example".

A: As a native English speaker and having been involved in many web design projects, I can tell you that you are absolutely correct. "See an example." is perfect for what you need.


text:
Q: Displaying Model Association Data I'm trying to display many to many associations but everything I try returns undefined. I'm basically trying to do exactly what this guy here is asking Sails.js Associations many-to-many relation
but he got no responses. I'm using postgres but I don't think that matters.
I can see the extra tables created to link the two entities. Basically I have a User, Group, Role Model. User has a many to many with groups and roles. When I look at the table the User model actually holds no information like group.name or role.name and the relationship table created only holds id numbers to reference the association. I'm assuming I need to find all roles in the association table that have user id match my current user id and display those.
Two questions, is there any other way to just display the associated records without querying by id. so user.roles.name (for example). Or how can I add the role/group name to the actual association table created by sails and not just display the id number.
User model
module.exports = {

  attributes: {

    username: 'string',
    password: 'string',
    firstname: 'string',
    lastname: 'string',
    email: 'string',
    group: {
      collection: 'groups',
      via: 'users',
      dominant: true
    },
    roles: {
      collection: 'role',
      via: 'users',
      dominant: true
    }
  }
};

Group Model
module.exports = {

  attributes: {

    name: 'string',
    users: {
      collection: 'user',
      via: 'group'
    }
  }

};

Role Model
module.exports = {

  attributes: {

    name: 'string',
    users: {
      collection: 'user',
      via: 'roles'
    }

  }

};

Thanks for any help!
EDIT
ejs file

      ID
      Username
      First Name
      Last Name
      Email
      Groups
      Roles

    <% users.forEach(function(user){ %>

      <%= user.id %>
      <%= user.username %>
      <%= user.firstname %>
      <%= user.lastname %>
      <%= user.email %>
      <%= user.group.collection %>
      <%= user.roles.collection %>
      <a href="/user/edit/<%= user.id%>">Edit

    <% }); %>

UserController:
users: function(req, res) {
    User.find().exec(function(err, users){
    res.view({users: users});
    });
  },

I've tried lots of different variations of user.roles and user.group. I'm guessing that's completely wrong though but didn't find much documentation on anything other then just setting up the many to many relationships.

A: You need to populate the associations when you  query for users, as demonstrated in the documentation for many-to-many associations.
User.find()
    .populate('group')
    .populate('roles')
    .exec(function(err, users){...}

OR
User.find().populateAll().exec(function(err, users){...}

Either of these will add a group array and a roles array to each individual user.  So if you leave your view code as is, you'll probably just get [Object object] for the output for those two columns.  You could use Lodash to at least create a comma-delimited list of names.  For example:
<%= _.pluck(user.group.collection, 'name').join(', ') %>

will give you a list of groups that the user belongs to.  Lodash is globalized by Sails by default, so you shouldn't have to add anything to your project to make this work.
Full docs for .populate are here.


text:
Q: SFML undefined reference to `Bat::Bat(float, float)' I've been trying to teach myself SFML. Recently I've been following this tutorial: http://gamecodeschool.com/sfml/building-a-simple-game-engine-in-c-plus-plus/ to build a little pong game. The first attempt I read through everything and followed along with the code, and kept getting errors for Bat and Ball, such as:
main.cxx:(.text+0x11e): undefined reference to `Bat::Bat(float, float)'

I went back through and tried fixing things, comparing code side by side, and even rewriting each file. However, I still keep getting the same errors:
main.cxx:(.text+0x11e): undefined reference to `Bat::Bat(float, float)'
main.cxx:(.text+0x11e): undefined reference to `Bat::Bat(float, float)'
main.cxx:(.text+0x279): undefined reference to `Bat::moveLeft()'

etc.
I understand that an undefined reference means that the linker can't find the definitions when looking through all of the object files and libraries. However, I haven't worked with C++ in a while, and I honestly can't seem to find where I am going wrong?
My current environment is Geany IDE on Debian 9. All of the header and implementation files are in the same folder. The code is exactly as it is in the tutorial in the link posted above. For example, here is my Bat.h file:
ifndef BAT_H
#define BAT_H
#include <SFML/Graphics.hpp>
using namespace sf;

class Bat
{
private:
    Vector2f position;

    // A RectangleShape object
    RectangleShape batShape;

    float batSpeed = .3f;

public:
    Bat(float startX, float startY);

    FloatRect getPosition();

    RectangleShape getShape();

    void moveLeft();

    void moveRight();

    void update();

};
#endif

Can someone point me in the right direction or possibly tell me what I am doing wrong? I would really appreciate it.
Thanks.

A: The linker cannot find the code for you Bat constructor and moveLeft methods. Most likely cause is that you have either not included your Bat.cpp file in the build, or your cpp file has a different signature for those methods, that differs from the one in your header file.
If you check it and still cannot find the cause, post your cpp file here, too.


text:
Q: Ошибка "конфликт имен" У меня проблема при объявлении константы в начале кода. У меня компилятор дает ошибку, не видя её (константу) в main; если объявить в самом классе, тогда не видит функция. Вот, например:
using namespace std;

const int max = 5;

int main()
{
    void centimize(double *);
    double varray[max] = { 10.0, 41.1, 95.9, 87.4, 87.3 };
    centimize(varray);

    for (int j = 0; j < max; j++)
        cout << "varray [ " << j << "] = " << varray[j] <<
            "сантимаетров " << endl;
    return 0;
}

void centimize(double *ptrd)
{
    for (int j = 0; j < max; j++)
        *ptrd++ *= 2.54;
}

A: У вас какой-то clash. Похоже что max уже где-то в стандартных внутренностях объявлена. Переименуйте max во что-нибудь другое и всё взлетит.
A: Вы написали using namespace std; и теперь поиск имен видит две сущности с именем max - const int max и шаблон функции std::max.
Используйте префикс глобального пространства имен :: чтобы явно указать, что надо брать имя из глобального пространства имен (а не из пространства имен ::std::)
double varray[::max] = {...};

Более правильное решение - это не использовать using namespace std;.


text:
Q: Spearman's partial correlation in R : ppcor or RVAideMemoire? which is preferable for Spearman's ? RVAideMemoire::pcor.test() or ppcor::pcor.test() ?

*

*I'm running a set of partial correlations, I've came across
RVAideMemoire::pcor.test() as well as (which seems to be the most used one) ppcor::pcor.test(). The functions give me similar outputs, but not quite the same. By reading their documentations, I suppose that RVAideMemoire::pcor.test() bootstrap the correlation when its Spearman's method (aka, my case). Which one is the better option?

*examples:

> RVAideMemoire::pcor.test(data$VarB,
+                          data$VarC,
+                          data$VarA, ## this one is the "third" one
+                           method = "spearman")

    Spearman's rank partial correlation

data:  data$VarB and data$VarC, controlling for VarA
S = 178, p-value < 2.2e-16
alternative hypothesis: true rho is not equal to 0
95 percent confidence interval:
 0.9819397 0.9978322
sample estimates:
      rho
0.9935786

>
> ?RVAideMemoire::pcor.test()
>
> data <- data %>%
+         filter(!is.na(VarA) & !is.na(VarB) & !is.na(VarC))
>
> ppcor::pcor.test(data$VarB,
+                  data$VarC,
+                  data$VarA, ## this one is the "third" one
+                  method = "spearman")

   estimate      p.value statistic  n gp   Method
1 0.9951837 3.925764e-54  73.20786 55  1 spearman

?ppcor::pcor.test()

*

*Data:

structure(list(VarA = c(263L, 223L, NA, 257L, 285L, 211L, 210L,
NA, 147L, 311L, 342L, 97L, 216L, 241L, 296L, 296L, 211L, 60L,
339L, 318L, 358L, 167L, NA, 183L, 92L, 283L, 169L, NA, 298L,
NA, 162L, NA, 211L, 308L, 92L, 269L, NA, 197L, 280L, 259L, 313L,
252L, 98L, 258L, 201L, 341L, 456L, 308L, 252L, 64L, 259L, 158L,
161L, NA, NA, 129L, 264L, NA, 216L, 109L, 91L, 236L, 275L, 254L,
221L, NA, NA, NA, NA, NA, NA), VarB = c(145L, 120L, NA, 119L,
142L, 132L, 100L, NA, 64L, 144L, 164L, 56L, 102L, 136L, 139L,
135L, 91L, 32L, 123L, 164L, 145L, 93L, NA, 99L, 51L, 143L, 98L,
NA, 158L, NA, 79L, NA, 96L, 149L, 55L, 114L, NA, 94L, 137L, 130L,
135L, 113L, 61L, 113L, 117L, 154L, 199L, 152L, 142L, 42L, 111L,
74L, 92L, NA, NA, 85L, 116L, NA, 99L, 64L, 60L, 114L, 151L, 136L,
116L, NA, NA, NA, NA, NA, NA), VarC = c(145L, 121L, NA, 120L,
145L, 133L, 101L, NA, 64L, 146L, 166L, 58L, 103L, 136L, 142L,
135L, 91L, 34L, 123L, 167L, 148L, 93L, NA, 99L, 51L, 145L, 98L,
NA, 159L, NA, 81L, NA, 97L, 149L, 56L, 115L, NA, 96L, 137L, 132L,
135L, 113L, 62L, 113L, 118L, 154L, 199L, 154L, 145L, 43L, 112L,
74L, 92L, NA, NA, 86L, 116L, NA, 100L, 66L, 60L, 114L, 153L,
136L, 120L, NA, NA, NA, NA, NA, NA), myVarUnlist = c(145L, 120L,
NA, 119L, 142L, 132L, 100L, NA, 64L, 144L, 164L, 56L, 102L, 136L,
139L, 135L, 91L, 32L, 123L, 164L, 145L, 93L, NA, 99L, 51L, 143L,
98L, NA, 158L, NA, 79L, NA, 96L, 149L, 55L, 114L, NA, 94L, 137L,
130L, 135L, 113L, 61L, 113L, 117L, 154L, 199L, 152L, 142L, 42L,
111L, 74L, 92L, NA, NA, 85L, 116L, NA, 99L, 64L, 60L, 114L, 151L,
136L, 116L, NA, NA, NA, NA, NA, NA)), row.names = c(NA, -71L), class = "data.frame")

*

*thanks in advance!


text:
Q: Jetty: unpack .war to specific folder I need to run Jetty, specify war-file and have it unpacked by Jetty into specific location. The common behavior of Jetty is to take TEMP directory or JETTY_HOME/work directory and unpack war-file into a sub-folder named like this: jetty-HOST-PORT-CONTEXT.war-_-any-
This is absolutely inappropriate for our environment because the PORT part is random. War-file must be unpacked by Jetty and the destination must be 100% flexible.
Is it possible? Please advice. Jetty isn't my area of expertise, forgive me if the question is lame or trivial, however googling didn't help much.
Thank you very much!

A: Thank you everyone. I've managed to achieve the requirement extending Jetty with the following code:
int port = 8080;
String context_path = "/";
File tmp_directory = "C:\\some-custom-path\\";
String war_path = "C:\\path-to-a\\file.war";

WebAppContext app = new WebAppContext();
app.setContextPath( context_path );
app.setWar( war_path );
app.setTempDirectory( tmp_directory );

Server server = new Server( port );
server.setHandler( app );
server.start();
server.join();

app.setTempDirectory call makes Jetty unpack war-file into custom folder. I've not found any other way but the solution suits me right.

A: (not tried it, just reading from the wiki page  jetty wiki)
You could extract the war to a predefined direcory. And then provide that folder as setWar argument.
    Server server = new Server(8080);
    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setWar(jetty_home+"/webapps/testlocation/");
    server.setHandler(webapp);


text:
Q: Confused with the effect number of decimals at the output of transducer There is an ultrasonic device which measures and outputs both wind speed and direction and has a very long manual. But to keep it short and summarize, the accuracy and the resolution for the wind direction is given in the following table:

As default, the device outputs the wind direction as for instance: 355.2 which is the direction with one decimal. Now the number of decimals can be user defined and be like 355.467 ect.
My questions are about comparing the logging of the output with one decimal versus with three decimals.

*

*In terms of accuracy would increasing the number of decimals make any difference in the accuracy?

*And in terms of resolution would increasing the number of decimals
make any difference in the resolution?

*If neither, what parameter would improve doing so?

A:
In terms of accuracy would increasing the number of decimals make any
  difference in the accuracy?

The accuracy is specified as 1° up to wind speeds of 35 m/s so, acquire the number with enough resolution to avoid making the accuracy any worse than 1°. In other words you would need one decimal place to be confident.

And in terms of resolution would increasing the number of decimals
  make any difference in the resolution?

The number of decimal places is the resolution. It doesn't give more accuracy but it does allow you to see small changes of wind speed if that is important to you.

A: That selectable output format is probably just meant as convenience to the user.

*

*Of course, if you used less decimals than your sensor had resolution, you'd lose information in that quantization step.

*Your 0.1° resolution at accurracies worse than 1° is of course also only meaningful if you have some information on how the error between reported angle and actual angle is distributed, in which you can use that to implement an estimator for the actual angle based on multiple observations.

*To that end, it might be more useful to have more digits, even if they're just the result of noise. Or it might not, if your estimation method boils down to be mathematically equivalent to first rounding all numbers.

We might need to talk about what "resolution" is: that's easy if you have say simply a piece of plastic mounted on a rotatable platform that you hold into the wind, it rotates so that it's in the direction of the wind, and you've got some optical encoder linked to the platform that gives you one out of 360 possible angles. 1° resolution, easy. The measurement noise will be simply the quantization noise (i.e. assuming wind directions are equiprobable, you'll be off by ¼° on average, simply because of your resolution).
This device is way more complex. It's something that measures the direction of wind by estimating the doppler shift in orthogonal directions and then calculating a likely direction of wind that led to these estimates of doppler shift.
Doing that math, you can often get arbitrarily close to the real value, if you can observe the same phenomenon (wind direction) just for long enough (for details on what's possible with an unbiased estimator: see Cramer-Rao Lower Bound).
However, in a real system, you have a limited amount of observations, which limits the amount of noise due to actual physical uncertainty (wind isn't 100% constant), measurement errors (amplifier temperature, for example), digitization, doppler estimation (that's spectral estimation, there's libraries full of books on that), and from that, direction estimation. All these steps can introduce new errors!
So, if you're designing a system, you'd go through all these things and say, OK, in the end, my estimate of direction will have a variance \$\sigma^2\$, i.e. a mean squared deviaion from its mean, and that gives us an interval that we can be pretty sure about being in. In a normally distributed variable, more than 95% of values fall into \$2\sigma\$ around the mean!
So, probably, they used some statistics to say (for example) something like

if we don't promise we're more accurate than \$2\sigma\$, which is 0.1°, then our measurement is right 95% of time! Let's call that the resolution.

I don't know what you're measuring, but 0.1° is pretty impressive in angular resolution for anything that isn't solid.

A: There is nothing to be gained by increasing the resolution beyond the accuracy quoted. Taking the example you quote, the figure 355.467 is spurious; the true value lies between 354.467 and 356.467. Accordingly, it is more realistic to quote the value as 355.5, and I would prefer to quote simply 355. In my experience, wind is turbulent to the extent that it is difficult to define a direction to single-degree value, and averaging results over a period of time is complicated by random gusts.

A: I've used a similar kind of device from a different manufacturer, and have done a fair amount of weather data logging for various clients.  It's hard to believe there's much meaning even in 0.1° measurements of direction for a single sensor in a fluid.  Is your device oriented to within 0.1°?
My understanding of the functioning of this kind of device is that it works out the speed of (ultra)sound between three outputs and three inputs by doppler, then works out the direction of the wind which would give that effect.  As such, the outputs are the results of pretty tricky calculations.  When they say it has a resolution of 0.1°, what does it mean?  I can only assume it means you put it in a wind tunnel with laminal flow and if you rotate the device by 0.1°, you get a change of output of 0.1°.You could print as many decimals as you cared for -- and you would, while designing the machine -- but what does it mean for weather?
A quick reading of the manual suggests you might need to correct wind speeds according to "acoustic virtual temperature".  Are you doing this?
Depending on application, I would decid according to one of two principles:

*

*Log what I have  If the device claims 0.1, log 0.1.  You can then worry about it later.

*Log what I can replace If most anemometers give whole degrees, log whole degrees.  Then I can't have any dependencies on this particular model.

If it was me I'd just log whole degrees.


text:
Q: data not loading onto list from API [ReactJs] so I am currently working on an admin control panel that retrieves objects from an API.
The API has two different endpoints, it's either of:
http://localhost:3000/videos
http://localhost:3000/manuals

And the API's both return objects with sets of data such as "id, url, title and thumbnailUrl"
I have a module that's responsible for the card that has the following code:
export interface Manual {
  id?: string | number;
  url: string;
  title: string;
  thumbnail?: string | null;
}

I have a module that's responsible for creating the actual HelpCard components
And then the HelpCard components are then loaded up into my HelpList component
And then finally, I have my HelpAdmin.view module that brings it all together
The issue is, even when I call a
console.log(this.props.data);

within my HelpList module, I am returned with 8 empty arrays that look like so:
[]
length: 0
__proto__: Array(0)

I am curious as to why my video / manual cards are not actually being displayed onto my list?
Thank you in advance for reading and helping.

A: You are calling the API in HelpList Component and setting it to state
In your HelpAdminView component you have a state of manuals that is an empty array and passing it as a data prop, it would remain empty as you are not updating it,
You can do your API calling in HelpAdminView component and then pass it as a prop to your HelpList component
Hope it helps

A: The manuals and videos data is in your HelpList component's state, but you are using this.props.data.map which comes empty from your HelpListAdmin using  data={this.state.videos}.
So you need replace the related code like this in your HelpList component's render.
              {this.state.manuals.map((card: Manual) => (
                <HelpCard
                  card={card}
                  key={card.id}
                  deleteProduct={this.props.onDelete}
                  editProduct={this.props.onEdit}
                  type={this.props.type}
                />
              ))}

But if you want to manage the state in your HelpAdminView component, you need to make the api calls in this component instead of HelpList component.
And I think you should keep the state in parent (HelpAdminView) and pass the manuals and videos to the HelpList component.
So you need to move this code from HelpList to HelpAdminView.
  async componentDidMount() {
    const res = await axios.get(this.state.url);
    this.setState({ card: res.data });
    this.loadAdminHelpCard("videos");
    this.loadAdminHelpCard("manuals");

    //console.log(res.data);
  }

  loadAdminHelpCard = (type: "videos" | "manuals"): void => {
    const baseApiUrl = `http://localhost:3000`;
    const url = `${baseApiUrl}/${type}`;
    axios
      .get(url)
      .then((res) => {
        this.setState({ [type]: res.data } as any);
      })
      .catch(function(error) {
        // handle error
        console.log(error);
      });
  };

Remove the state in HelpList component.
And pass the videos and manuals as props (like you did now) to HelpList component.

Videos

              <HelpList
                data={this.state.videos}
                type="videos"
                onEdit={this.editProduct}
                onDelete={this.deleteProduct}
              />

Manuals

              <HelpList
                data={this.state.manuals}
                type="manuals"
                onEdit={this.editProduct}
                onDelete={this.deleteProduct}
              />

And use this props in HelpList component (as you did now).
export default class HelpList extends Component<Props, State> {

  static props: any;

  render() {
    console.log(this.props.data);

    return (
      <React.Fragment>
        {this.state.card ? (

            {this.props.data.map((card: Manual) => (
              <HelpCard
                card={card}
                key={card.id}
                deleteProduct={this.props.onDelete}
                editProduct={this.props.onEdit}
                type={this.props.type}
              />
            ))}

        ) : (

Loading Cards...

        )}
      </React.Fragment>
    );
  }
}


text:
Q: Navigator share not work in converting the web site into APK

$(".shared").click(function() {

    if (navigator.share !== undefined) {
    navigator.share({
      title: '<? echo $title_share; ?>',
      url  : '<? echo $url_share; ?>'
    })
    .then(() => console.log('Shared successfully'))
    .catch((error) => console.log('An error has occurred'));
  } else {
    console.log('Your browser doesn\'t support Web Share API');
  }

 });

navigator share does not work in converting the website into APK with appsgeyser or gonative.io
can not make web APIs work from the conversion, so it gives me as if the browser does not support it. In the Android mobile browser, it works perfectly. is there a way to create a share button in native Java and integrate it into HTML?

A: Maybe because your website runs in a different browser check the user agent, for debugging.
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share -> see here for compatabilatie
https://www.w3schools.com/jsref/prop_nav_useragent.asp -> JavaScript check user agent

A: gives me this result with  gonative.io
User-agent header sent: Mozilla/5.0 (Linux; Android 6.0.1; SM-G900F Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36 GoNativeAndroid/1.0 gonative
gives me this result with appsgeyser
User-agent header sent: Mozilla/5.0 (Linux; U; Android 2.2; en-ie; GT-P1000 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
in theory it should not work with gonative.io?


text:
Q: Builder Design Pattern with sub-classing and required parameters? Recently I came into a situation where the builder pattern was very strong, but I had the need to subclass. I looked up some solutions and some suggested generics while others suggested normal subclassing. However, none of the examples I looked at had required fields in order to even begin building an object. I wrote a tiny example to illustrate where I'm getting stuck. At every turn I kept running into a wall of problems where things would return the wrong class, can't override static methods, returning super() returns the wrong data type, etc. I have a feeling there is no way out except excessive use of generics.
What is the correct way to go in this situation?
Tester
import person.Person;
import person.Student;

public class Tester
{
    public static void main(String[] args)
    {
        Person p = Person.builder("Jake", 18).interest("Soccer").build();
        // Student s = Student.builder(name, age) <-- It's weird that we still have access to pointless static method
        // Student s = Student.builder("Johnny", 24, "Harvard", 3).address("199 Harvard Lane") <-- returns Person builder, not student
        Student s = ((Student.Builder)Student.builder("Jack", 19, "NYU", 1).address("Dormitory")).build(); // really bad
    }
}

Person Class
package person;

import java.util.ArrayList;
import java.util.List;

public class Person
{
    // Required
    protected String name;
    protected int age;

    // Optional
    protected List<String> interests = new ArrayList<>();
    protected String address = "";

    protected Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
    public List<String> getInterests() { return interests; }
    public String getAddress() { return address; }

    // person.person does not allow builder construction
    // unless all required fields are provided

    /* Problem: I have to repeat the constructor fields here, very annoying */
    public static Builder builder(String name, int age)
    {
        Person p = new Person(name, age);
        return new Builder(p);
    }

    public static class Builder
    {
        Person reference;

        protected Builder(Person reference)
        {
            this.reference = reference;
        }

        public Builder address(String address)
        {
            reference.address = address;
            return this;
        }

        public Builder interest(String interest)
        {
            reference.interests.add(interest);
            return this;
        }

        public Person build()
        {
            return reference;
        }
    }
}

Student Class
package person;

import java.util.ArrayList;
import java.util.List;

public class Student extends Person
{
    // Required
    protected String school;
    protected int year;

    // Optional
    protected List<String> subjects = new ArrayList<>();

    // This looks good
    public Student(final String name, final int age, final String school, final int year)
    {
        super(name, age);
        this.school = school;
        this.year = year;
    }

    public String getSchool() { return school; }
    public int getYear() { return year; }
    public List<String> getSubjects() { return subjects; }

    /* Here's where my issues are:

      * Override doesn't compile on static methods but how else can I describe that I want to
      * override this functionality from the Person class?
      *
      * Extending 'Person' does not enforce that I need to provide 'name', 'age', etc like it would
      * if this was a normal design pattern using the 'new' keyword. I have to manually drag fields
      * from 'person' and place them here. This would get VERY messy with an additional class
      *
      * User can STILL call the Person builder on a Student object, which makes no sense. */
    /*@Override*/ public static Builder builder(String name, int age, String school, int year)
    {
        Student s = new Student(name, age, school, year);
        return new Builder(s);
    }

    public static class Builder extends Person.Builder
    {
        // Student reference; <--- this should not be needed since we already
        //                      have a variable for this purpose from 'Person.Builder'

        public Builder(final Student reference)
        {
            super(reference);
        }

        /* Things begins to get very messy here */
        public Builder subject(String subject)
        {
            ((Student)reference).subjects.add(subject);
            // I guess I could replace the reference with a student one, but
            // I feel like that infringes on calling super() builder since we do the work twice.
            return this;
        }

        @Override public Student build()
        {
            // I can either cast here or
            // rewrite 'return reference' every time.
            // Seems to infringe a bit on subclassing.
            return (Student)super.build();
        }
    }
}

A: What you write here :
Student s = ((Student.Builder)Student.builder("Jack", 19, "NYU", 1).address("Dormitory")).build(); // really bad

is indeed not very natural and you should not need to cast.
We expect rather something like :
Student s = Student.builder("Jack", 19, "NYU", 1).address("Dormitory")).build();

Besides all casts you did in the implementation of  Student.Builder are also noise and statements that may fail at runtime :
    /* Things begins to get very messy here */
    public Builder subject(String subject)   {
        ((Student)reference).subjects.add(subject);
        return this;
    }

    @Override public Student build() {
        return (Student)super.build();
    }

Your main issue is the coupling between the Builder classes and the building methods.
A important thing to consider is that at compile time, the method binding (method selected by the compiler) is performed according to the declared type of the target of the invocation and the declared type of its arguments.
The instantiated type is considered only at runtime as the dynamic binding is applied: invoking the method bounded at compile time on the runtime object.
So this overriding defined in Student.Builder is not enough :
@Override public Student build() {
    return (Student)super.build();
}

As you invoke :
Student.builder("Jack", 19, "NYU", 1).address("Dormitory").build();

At compile time, address("Dormitory") returns a variable typed as Person.Builder as the method is defined in Person.Builder :
public Builder address(String address){
    reference.address = address;
    return this;
}

and it not overriden in Student.Builder.
And at compile time, invoking build() on a variable declared as Person.Builder returns a object with as declared type a Person as the method is declared in Person.Builder as :
public Person build(){
    return reference;
}

Of course at runtime, the returned object will be a Student as
Student.builder("Jack", 19, "NYU", 1) creates under the hood a Student and not a Person.
To avoid cast to Student.builder both from the implementation and the client side, favor composition over inheritancy :
public static class Builder {

  Person.Builder personBuilder;
  private Student reference;

  public Builder(final Student reference) {
    this.reference = reference;
    personBuilder = new Person.Builder(reference);
  }

  public Builder subject(String subject) {
    reference.subjects.add(subject);
    return this;
  }

  // delegation to Person.Builder but return Student.Builder
  public Builder interest(String interest) {
    personBuilder.interest(interest);
    return this;
  }

  // delegation to Person.Builder but return Student.Builder
  public Builder address(String address) {
    personBuilder.address(address);
    return this;
  }

  public Student build() {
    return (Student) personBuilder.build();
  }

}

You can now write :
Student s = Student.builder("Jack", 19, "NYU", 1)
                   .address("Dormitory")
                   .build();

or even that :
Student s2 = Student.builder("Jack", 19, "NYU", 1)
                    .interest("Dance")
                    .address("Dormitory")
                    .build();

Composition introduces generally more code as inheritancy but it makes the code
both more robust and adaptable.
As a side note, your actual issue is enough close to another question I answered 1 month ago.
The question and its answers may interest you.

A: A few thoughts as background

*

*Static methods are not so great,
they make unit testing more difficult.

*It is fine to put the builder as a static, nested class, but if you are using a builder to construct a class you should make the constructor not-public.

*I prefer to have the builder be a separate class in the same package and to make the constructor (of the class that is created by the builder) package access.

*Limit the builder constructor parameters.

*I'm not a fan of using a class hierarchy for builders.

*The Person and Student classes each have a builder.

Some Code
public class PersonBuilder
{
    private String address;
    private int age;
    private final List<String> interestList;
    private String name;

    public PersonBuilder()
    {
        interestList = new LinkedList<>();
    }

    public void addInterest(
        final String newValue)
    {
        // StringUtils is an apache utility.
        if (StringUtils.isNotBlank(newValue))
        {
            interestList.add(newValue);
        }

        return this;
    }

    public Person build()
    {
        // perform validation here.
        // check for required values: age and name.

        // send all parameters in the constructor.  it's not public, so that is fine.
        return new Person(address, age, interestList, name);
    }

    public PersonBuilder setAddress(
        final String newValue)
    {
        address = newValue;

        return this;
    }

    public PersonBuilder setAge(
        final int newValue)
    {
        age = newValue;

        return this;
    }

    public PersonBuilder setInterestList(
        final List<String> newValue)
    {
        interestList.clear();

        if (CollectionUtils.isNotEmpty(newValue))
        {
            interestList.addAll(newValue);
        }

        return this;
    }

    public PersonBuilder setName(
        final String newValue)
    {
        name = newValue;

        return this;
    }
}

public class Person
{
    private Person()
    {
    }

    Person(
        final String addressValue,
        final int ageValue,
        final List<String> interestListValue,
        final String name)
    {
        // set stuff.
        // handle null for optional parameters.
    }

    // create gets or the fields, but do not create sets.  Only the builder can set values in the class.
}


text:
Q: How to bold only a portion of Word paragraph in Visual Studio (VB) I am trying to export a Word document from a Visual Basic program. Different parts of the document will need different formatting.
I have several paragraphs, and I need to bold only portions of each of those paragraphs. I am trying to set the range within each paragraph that needs to be bolded, but no matter what I do, it only seems to want to to bold the entire paragraph.
I want to do something like this:
Dim Para1 As Word.Paragraph
Para1 = WordDoc.Content.Paragraphs.Add
Para1.Range.Start = 1
Para1.Range.End = 14
Para1.Range.Font.Bold = True
Para1.Range.Text = "Job number is: " + myJobID

... so that it bolds from the 'J' to the ':' (in Para1.Range.Text) but does not bold the myJobID (which is a variable I'm getting from the user). However, no matter what I do, it bolds the entire paragraph, including the myJobID.
I've also tried creating a Range variable that sets a range based on the entire document, but the problem with that is, the lengths of several variables I'm outputting on the Word document are going to be varying sizes, and thus there's no way to know where the start of the next section I want to bold will start at. So basically, I have to work within the Paragraph object rather than iterating through all of the characters in the entire document.
Hope that made sense. Any ideas?

A: In order to format individual text runs it's necessary to break the text down into individual runs when inserting. Also, it's best to work with an independent Range object. Between formatting commands the Range needs to be "collapsed" - think of it like pressing the right (or left) arrow of a selection to make it a blinking cursor. Something along these lines
Dim Para1 As Word.Paragraph
Dim rng as Word.Range
Para1 = WordDoc.Content.Paragraphs.Add
rng = Para1.Range
rng.Text = "Job number is: "
rng.Font.Bold = True
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
rng.Text = myJobID
rng.Font.Bold = False
rng.Collapse Word.WdCollapseDirection.wdCollapseEnd

If it's really necessary to insert the full text in one go, then Find/Replace to locate the text that should be formatted differently is one way to format after-the-fact, although less efficient.
Another possibility is to use string manipulation functions, such as Instr (or Contains), Left, Mid etc. to determine where in a longer string the substring is located. Then Range.Start and Range.End can work with those values. But generally it's better to not rely on the start and end values since Word can insert non-visible characters that can throw this numbering off.

A: Create another Range object that only covers the characters that you want to bold.
The code below is not tested (don't have full VS set up on this machine), but should give you an idea:
Dim para1 As Word.Paragraph
Dim textToBeBolded As Word.Range

para1 = WordDoc.Content.Paragraphs.Add 'ThisDocument.Paragraphs.Add in VBA
para1.Range.Text = "Job number is: " + myJobID
para1.Range.SetRange 1, 14
textToBeBolded = para1.Range
textToBeBolded.SetRange 1, 14
textToBeBolded.Font.Bold = True


text:
Q: PowerShell 3 Parameters Hi Basically i'm having an issue i need to load Arguments in to the following code  located at the $URL & $Output but i need it to work with the Join-Path but every time i try it kicks back a load of errors i'm new to this so i am trying everything to get it working I've been asked to do this by my boss completely out my depth but never been one to shy away from a challenge
Function DownloadFileFromURL
{
Add-Type -AssemblyName Microsoft.Visualbasic
#$url = 'http://download.microsoft.com/download/F/4/2/F42AB12D-C935-4E65-9D98-4E56F9ACBC8E/wpilauncher.exe'
$url = $args[0]
$filename = Split-Path -leaf $url
$output = Join-Path $args1 + $filename
$response = [System.Net.WebRequest]::Create($url).GetResponse()
$realurl = $response.ResponseUri.OriginalString
$response.Close()
(New-Object Net.WebClient).DownloadFile($url, $output)

#################Time Taken To Download Files######################
$start_time = Get-Date
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

}

    DownloadFileFromURL ('http://download.microsoft.com/download/F/4/2/F42AB12D-C935-4E65-9D98-4E56F9ACBC8E/wpilauncher.exe','C:\Users\Martin.beardmore\Downloads\test')

Errors being Recieved
Join-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\Martin.beardmore\Documents\Query download.ps1:6 char:21
+ $output = Join-Path $args[1] + $filename
+                     ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand

Cannot convert argument "requestUri", with value: "System.Object[]", for "Create" to type "System.Uri": "Cannot convert the "System.Object[]" value of type "System.Object[]" to type
"System.Uri"."
At C:\Users\Martin.beardmore\Documents\Query download.ps1:7 char:1
+ $response = [System.Net.WebRequest]::Create($url).GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

You cannot call a method on a null-valued expression.
At C:\Users\Martin.beardmore\Documents\Query download.ps1:9 char:1
+ $response.Close()
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Cannot convert argument "address", with value: "System.Object[]", for "DownloadFile" to type "System.Uri": "Cannot convert the "System.Object[]" value of type "System.Object[]" to type
"System.Uri"."
At C:\Users\Martin.beardmore\Documents\Query download.ps1:10 char:1
+ (New-Object Net.WebClient).DownloadFile($url, $output)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

A: You need to remove the + between the paths you want to join. Look at the syntax for Join-Path.
PS> Get-Command Join-Path -Syntax

Join-Path [-Path] <string[]> [-ChildPath] <string> [-Resolve] [-Credential <pscredential>] [-UseTransaction] [<CommonParameters>]

You should use it like $output = Join-Path $args1 $filename
Also, where does $args1 come from? In functions, you should name your parameters. The order in which you define them will be the order they are binded to, so they will still behave the same as arguments, but they are easier to work with.
Function DownloadFileFromURL ($url, $folder)
{
    Write-Host "URL: $url"
    Write-Host "Folder: $folder"
}

Sample:
PS > DownloadFileFromURL stackoverflow.com c:\folder
URL: stackoverflow.com
Folder: c:\folder

You are also calling the function wrong. Comma is used to seperate objects in an array, so DownloadFileFromURL ('http://download.microsoft.com/download/F/4/2/F42AB12D-C935-4E65-9D98-4E56F9ACBC8E/wpilauncher.exe','C:\Users\Martin.beardmore\Downloads\test') results in:
$url = $args[0] = @('http://download.microsoft.com/download/F/4/2/F42AB12D-C935-4E65-9D98-4E56F9ACBC8E/wpilauncher.exe','C:\Users\Martin.beardmore\Downloads\test')

Modify your function to use parameters and call it like I've as shown above and it should work.
Updated script:
Function DownloadFileFromURL ($url, $destination)
{
    Add-Type -AssemblyName Microsoft.Visualbasic
    $filename = Split-Path -Leaf $url
    $output = Join-Path $destination $filename
    $response = [System.Net.WebRequest]::Create($url).GetResponse()
    $realurl = $response.ResponseUri.OriginalString
    $response.Close()
    (New-Object Net.WebClient).DownloadFile($url, $output)

    #################Time Taken To Download Files######################
    $start_time = Get-Date
    Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

}

DownloadFileFromURL 'http://download.microsoft.com/download/F/4/2/F42AB12D-C935-4E65-9D98-4E56F9ACBC8E/wpilauncher.exe' 'C:\Users\Martin.beardmore\Downloads\test'
#or even better
#DownloadFileFromURL -url 'http://download.microsoft.com/download/F/4/2/F42AB12D-C935-4E65-9D98-4E56F9ACBC8E/wpilauncher.exe' -destination 'C:\Users\Martin.beardmore\Downloads\test'


text:
Q: found nil while populating modal from JSON parsing in Swift4 I'd like to parse the following retrieved data using Swift 4.

{"bannerCategory":{"name":"","apps":[{"ImageName":"enhancedWith3dTouch"},{"ImageName":"drSeussBanner"},{"ImageName":"indieGameBanner"},{"ImageName":"clashRoyaleBanner"}],"type":""},"categories":[{"name":"Best
  New Apps","apps":[{"Id":1,"Name":"Disney Build It:
  Frozen","Category":"Entertainment","Price":3.99,"ImageName":"frozen"},{"Name":"Spot
  - the best places according to experts and friends","Category":"Travel","ImageName":"spot"},{"Name":"Dine - More
  Dates, Not Swipes","Category":"Social
  Networking","ImageName":"dine"},{"Name":"Today: Habit tracker for your
  daily goals and routines","Category":"Health \u0026
  Fitness","ImageName":"today"},{"Id":1,"Name":"Disney Build It:
  Frozen","Category":"Entertainment","Price":3.99,"ImageName":"frozen"},{"Name":"Spot
  - the best places according to experts and friends","Category":"Travel","ImageName":"spot"},{"Name":"Dine - More
  Dates, Not Swipes","Category":"Social
  Networking","ImageName":"dine"},{"Name":"Today: Habit tracker for your
  daily goals and routines","Category":"Health \u0026
  Fitness","ImageName":"today"}],"type":""},{"name":"Best New
  Games","apps":[{"Id":2,"Name":"Telepaint","Category":"Games","Price":2.99,"ImageName":"telepaint"},{"Name":"Dirac","Category":"Games","Price":1.99,"ImageName":"dirac"},{"Name":"Clash
  Royale","Category":"Games","ImageName":"clashroyale"},{"Name":"Beat
  Stomper","Category":"Games","Price":1.99,"ImageName":"beatstomper"},{"Id":2,"Name":"Telepaint","Category":"Games","Price":2.99,"ImageName":"telepaint"},{"Name":"Dirac","Category":"Games","Price":1.99,"ImageName":"dirac"},{"Name":"Clash
  Royale","Category":"Games","ImageName":"clashroyale"},{"Name":"Beat
  Stomper","Category":"Games","Price":1.99,"ImageName":"beatstomper"}],"type":""},{"name":"50%
  Off for a Limited
  Time","apps":[{"ImageName":"luminocity"},{"ImageName":"theroom"},{"ImageName":"badland"},{"ImageName":"shadowmatic"},{"ImageName":"luminocity"},{"ImageName":"theroom"},{"ImageName":"badland"},{"ImageName":"shadowmatic"}],"type":"large"},{"name":"More
  Games You Might Like","apps":[{"Name":"Summoners
  War","Category":"Games","ImageName":"summonerswar"},{"Name":"Angry
  Birds
  Space","Category":"Games","Price":0.99,"ImageName":"angrybirdsspace"},{"Name":"Star
  Wars™: Commander - Worlds in
  Conflict","Category":"Games","ImageName":"starwars"},{"Name":"Death
  Worm","Category":"Games","Price":2.99,"ImageName":"deathworm"}],"type":""}]}

modal object to retrieve data
struct FeaturedApps: Codable {

    var bannerCategory: AppCategory?
    var categories: [AppCategory]?

    struct AppCategory: Codable {

       let name : String?
       let apps : [App]?
       let type: String?

        struct App : Codable {

            let id: Int?
            let name: String?
            let category : String?
            let imageName : String?
            let price : Float?

        }
     }
}

codes for JSON parsing
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonUrl = "https://api.letsbuildthatapp.com/appstore/featured"
                guard let url = URL(string: jsonUrl) else { return }

       let task = URLSession.shared.dataTask(with: url) { (data, response, error)  in

            guard let data = data else { return }

            if let error = error {
                print(error)
                return
            }
            do {

                let courses = try JSONDecoder().decode(FeaturedApps.self, from: data)
                print(courses)

            } catch let jsonErr {
                print("Error serializing json:", jsonErr)
            }
        }
        task.resume()
     }
}

That yields the following output:

FeaturedApps(bannerCategory:
  Optional(JsonParseSwift4.FeaturedApps.AppCategory(name: Optional(""),
  apps: Optional([JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil,
  name: nil, category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil)]), type: Optional(""))),
  categories: Optional([JsonParseSwift4.FeaturedApps.AppCategory(name:
  Optional("Best New Apps"), apps:
  Optional([JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name:
  nil, category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil)]), type: Optional("")),
  JsonParseSwift4.FeaturedApps.AppCategory(name: Optional("Best New
  Games"), apps:
  Optional([JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name:
  nil, category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil)]), type: Optional("")),
  JsonParseSwift4.FeaturedApps.AppCategory(name: Optional("50% Off for a
  Limited Time"), apps:
  Optional([JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name:
  nil, category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil)]), type:
  Optional("large")), JsonParseSwift4.FeaturedApps.AppCategory(name:
  Optional("More Games You Might Like"), apps:
  Optional([JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name:
  nil, category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil),
  JsonParseSwift4.FeaturedApps.AppCategory.App(id: nil, name: nil,
  category: nil, imageName: nil, price: nil)]), type: Optional(""))]))

Any pointers as to what I'm doing wrong and getting nil values ?

A: The name of your properties should be the same as it is in the JSON response. If a property uses different naming convention(case and/or spelling), it is treated as not found and is assigned a value of nil (if it is optional) or the program crashes (if it is required)


text:
Q: Is this addfront() function used with nalloc() for linked list wrong? This code is taken from: page 20-21 of this lecture notes pdf from ocw.
 struct node∗ nalloc ( int data )
 {
    struct node∗ p=( struct node ∗) malloc ( sizeof (node )) ;
    if ( p!=NULL) {
        p−>data=data ;
        p−>next=NULL;
    }
    return p;
 }

struct node∗ addfront ( struct node∗ head , int data )
{
    struct node∗ p= nalloc (data );
    if ( p==NULL) return head ;
    p−>next=head;
    return p;
}

I think the code is wrong because the pointer p is local to nalloc() and using it in addfront() would yield undefined behavior. I have seen the answer to this question and believe I am correct but can someone verify?

A: The function is right. But your logic is not so wrong. The variable p is effectively local and won't exist anymore when the function will return. However, p is not the memory you allocated with malloc, but a variable storing the address of the memory you allocated.
Thus, the statement return p; will return a copy of p, so a copy of the address of the memory you allocated using malloc().
In the linked question, the user creates a local array and returns a pointer to it. See, the array is local and now dynamically allocated using new or malloc(). So his variable effectively contains the (automatically) allocated memory, and not the address of it. However, only the address is returned so the memory is lost.

A: You are not correct. While p is a local variable on stack, what it points to isn't. What is happening is a pointer to a node on the heap is returned from nalloc and a copy of that pointer is used safely in addfront. The code is fine.


text:
Q: Apply function to clasiffy R I have a table with ids numbers and age:
This is part of the table:
View(clasificador1)
    edad    median  count
1   21  37758012    1
2   22  36505316    1
3   23  36395050    3
4   24  35430589    3
5   25  34419796    14
6   26  33903223    24

I want to classify another table using median field. The minimun distance in ids numbers would bring me the age:
clasifico_edad<-function(tabla,casificador,dni){
   ff<-function(dni){distances <- abs(dni - clasificador1$median)
                 clasificador1$edad[which.min(distances)]}
   tabla$edad_approx_median <- sapply(tabla[,dni], ff)
   return(tabla)}

I filter the letters in the Number field in the table I want to classify:
ventas1<-ventas[!grepl("[A-Za-z]", ventas$Number), ]

And apply the function:
aaaaa<-clasifico_edad(ventas1,clasificador1,"Number")

It runs but I get in field edad_approx_median =integer(0) in all rows:
Don't know how to solve it.
Thanks.


text:
Q: ExcelJS fill the multiple cells of excel with for loop I have an excel template like this:
The data I get is sadly just an 1D array like:
data = [a-b, 24, c-d, 25, g-h, 26, e-f, 27, a-c, 24, b-d, 25, e-g, 26, f-h, 27, a-e, 24, e-g, 25, b-f, 26, d-h, 27];

I am using NodeJS and Exceljs NPM package.
So I need to somehow fill the cells C95:C98, F95:F98, I95:I98..
This similar (but not the same pattern) will apply to other few tables in the same worksheet, so I need to do this with loop.
I am havin trouble with filling the multiple lines and also to fill the overy other value from my array, because i already have an a-b, c-d, g-h,... inserted in excel (I can overwrite, that is not a problem).
Code for now is:
 for (let i = 1; i < 9; i++) {
  console.log(dimensionalCheck[i]);

  let rowNum = 95;
  rowNum++;
  let row = worksheet.getRow(rowNum);
  row.getCell(3).value = dimensionalCheck[i + 1];
  row.commit();
}

But what I get as return is only this:


text:
Q: is there a way NicEditor be on a subfolder and not outside the demo page folder? Hello I just want to know if I can put it on a subfolder instead ? When I tried to put it on subfolder or within the same folder of my page, it displays normal textare. But whenever I put it outside the folder it works fine.
Just asking for convenience.
Or if there is already an answer please tell me.
Thank you

A: If you put NicEditor in subfolder then you have to give subfolder's path for NicEditor.


text:
Q: Comparing in SQL and SUM I really couldn't figure out a good title for this question, but I have a problem that I'm sure you can help me with!
I have a query which outputs something like this:
Month | Year | Subcategory | PrivateLabel | Price
-------------------------------------------------
  1   | 2010 | 666         | No           | -520
  1   | 2010 | 666         | No           | -499,75
  1   | 2010 | 666         | No           | -59,95
  1   | 2010 | 666         | No           | -49,73
  1   | 2010 | 666         | No           | -32,95

I want to SUM on the price because all the other data is the same. I thought I could do this with SUM and GROUP BY, but I can't figure out how to do it or at least it doesn't output the right result.
The query is an inner join between two tables, if that helps.

A: select
   month
   ,year
   ,subcategory
   ,privatelabel
   ,sum(price) as [total sales]
from
   a inner join b ...
where
   any where clauses
group by
   month
   ,year
   ,subcategory
   ,privatelabel

should work if i am understanding you correctly.. every colum in the select either needs to be part of the group by or an aggregate function on all rows in the group
added a fiddle.. mainly as i didn't know about he text to DDL functionality and wanted to test it ;-) (thanks Michael Buen)
http://sqlfiddle.com/#!3/35c1c/1
note the where clause is a place holder..

A: select month, year, subcategory, privatelabel, sum(price)
  from (put your query in here) dummyName
 group by month, year, subcategory, privatelabel

Basic idea is it will run your current query to get above output then do the sum and group by on the result.
You query has to be in parentheses and you have to give it some name e.g. dummyName. As long as it's unique in the sql and preferably not a key word, doesn't matter what it is.
There might be a way of doing all this in one go, but without the sql for your query we can't help.