text:
Q: Logarithmic sampling in Monte Carlo instead of linear The common case for a Monte Carlo simulation is, if we want to run our simulation for $N$ steps, we define a delta $\Delta,$ such that $N/\Delta = n$ tells us the frequency with which we measure/evaluate quantities of interest during the MC run.
For instance, say $N=1000,$ and we want to measure the average of an observable $f,$ after each $n=100$ steps (so here $\Delta=10$). The average is obtained by dividing $f$ by the number of times $f$ has been measured.
This is linearly sampling the time or MC steps and the simulation looks schematically like (writing in python style):
interval = N/delta
f = 0
countmeasurement = 0
for mcstep in range(1,N):
  interval -= 1
  .
  .
  .
  if interval == 0:
    f += computef()
    .
    .
    interval = N/delta
    countmeasurement += 1
  #save or print
  print "steps ", mcstep, "average f ", f/countmeasurement

Question:
With this scheme as sketched above, if later we plot $f$ as a function of MC-steps, on a log-log scaled plot, we will not have sampled the same amount of datapoints for each time scale as we sampled the total steps only linearly. How do we alter our sampling scheme, thus redefining interval, such that we gather the same number of datapoints for $f$ for each part (time-scale) of the log-log plot? Is it common to sample the MC-steps logarithmically in Monte Carlo simulations?

A: If I've understood the question correctly -
What you have to do is construct the step values of your simulation to be evenly distributed on a log scale, then exponentiate the step values for use in the relevant function.  The differences between the step values, when plotted on a log-log graph, will be equal.
For example, consider plotting the cumulative density function of a Pareto (power law) variate as a highly simplified version of this.  We set the mean and scale equal to 5, and plot the CDF for values of $x = 1, \dots, 30$:
ub <- 30
x <- 1:ub
y <- ppareto(x, m=5, s=5)
plot(y~x, log="xy")

which gives us the following graph:

This shows the unequal scaling referred to in the OP, admittedly in a different context, and how we lose a lot of information about the shape of the curve at values of the CDF below about 0.7 (i.e., most of it.)
Altering the stepsizes of $x$ to be equal on the log scale fixes the problem:
log_ub <- log(30)
x <- exp(seq(from=0, to=log_ub, length.out=30))
y <- ppareto(x, m=5, s=5)
plot(y~x, log="xy")

The $x$ values cover the same range in the two cases - $(1,30)$ - but are distributed more informatively in the second case:

In certain contexts, the "step sizes" referred to above are the number of iterations some sub-task is performed at each master step of the simulation.  The procedure in those cases would have to be adjusted so as to generate integer values for the number of iterations, but for any significant number of iterations, just rounding off would be sufficient.
For example, sampling from a Pareto distribution with different sample sizes ranging from 1 to 10,000:
log_ub <- log(10000)
y <- rep(0,30)
x <- round(exp(seq(from=0, to=log_ub, length.out=30)))
for (i in 1:30) y[i] <- mean(rpareto(x[i], 1, 5))
plot(y~x, log="xy", xlab="# observations", ylab="Sample mean")

yields the following plot:


text:
Q: Textbox is not empty even when I delete contents and click update
I have a Wishlist page with a comment box to add notes to it.  When there is no text, it says "Add your notes here..." in the gray text like the 4th product.  When you write a note, you go to Update Wishlist btn and click it to update what note you wrote.  This works.  What doesn't work is that when you already have a note added and you delete the text and click the update wishlist btn, it doesn't revert to "Add your notes here".  It stays the same.  I have written a comment for the first 3 input boxes, the 4th is blank.
However, if there is an update on the comment box and you change it from "testing1" to "testing123456" then click the Update Wishlist btn, it works.  If the text is "texting1" and I delete the text and only press the spacebar, the input box will be completely blank (obviously the space counts).  Just a notice, the red (x) button on the top right of each product is to take off a product from the Wishlist page which works, the Update Wishlist btn is the button I use every time I need to make a change in the comment section.
Thank you for your time!
<textarea type="text" placeholder="Add your notes here..." class="searchBox" title="Comment" name="description[<?php echo $item->getWishlistItemId() ?>]"
rows="3" cols="5" style="width:700px; min-height: 80px; margin-bottom: 5px;">
<?php echo ($this->escapeHtml($item->getDescription())) ?>
</textarea>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change the color of navigationBar along with the status Bar in iOS? I have a view Controller. I have added a navigationBar from Object library and I have change its BackgroundColor. Now, the problem is that my statusBar color is dull White and its looking bad. How do I change that color?
What I an Getting
What I Want

A: you can change the background color to the view controller's view. or add UIView at the most top of the screen behind the navigation bar and set it's background color then set navigation background color to clear


text:
Q: git diff specific file my-branch to master
*

*what is the simplest way to see a specific file diff from my branch to master?

*everything on my branch is pushed

*I prefer to use branch names rather than commits' hashes (like here)

*I want a single file diff rather than a full blown diff of branches (like here)

A: Here is what worked for me:
$ git diff origin/master:path/to/myfile.py path/to/myfile.py

Note that order does matter (master branch should come first)


text:
Q: find max of a function that is minimized of a group of functions I want to find an algorithm that find the max of a function which is minimized of a group of other functions. The problem can be described as follow:
Find max of F(x). F(x) = min (f1(x), f2(x), ..., fn(x)) with a <= x <= b.

A: This is a classic maximin problem, commonly used in tree searching to prune sub-trees.
In a maximin, the "current max" is kept.  Then, for each iteration of x, loop through f(1->n).  If any fn comes up with a value < the current max, there is no point to continue (as the minimum of all the functions will definitely be <= this value).  Therefore, stop and go for another iteration of x.
Without knowing the fn functions, there is no analytical method to get the answer without iteration.

A: In Python:
def F(x):
   return min(f1(x),f2(x),f3(x),f4(x),f5(x))

max(F(x) for x in xrange(a,b+1))


text:
Q: Launcher IOS app Can I submit to App Store an app that only launch Safari with one specific url?
If the answer is "yes": Can I hide default image, that is, can I launch Safari inmediatly from Main without show deafault image? (I can do it in BlackBerry and Windows Mobile)
I know.. is a horrible app but is what I have to do..
Thanks!

A: See section 2.12 of the App Store Review Guidelines:

Apps that are not very useful, are
  simply web sites bundled as apps, or
  do not provide any lasting
  entertainment value may be rejected

And section 12.3:

Apps that are simply web clippings,
  content aggregators, or a collection
  of links, may be rejected

In short, the answer is: Yes, you can submit whatever you like. My guess based on the guidelines above, though, is that such an app is unlikely to pass the review process.


text:
Q: AOP not intercepting in Spring Batch I've a method in Spring Batch Item Writer that I want to run @After on it, but for some reason the AOP Advice isn't running after the method returns.
The code goes as follows:
package com.mypackage.item;
// some imports

@Slf4j
@Component
@StepScope
public class MyItemWriter implements ItemWriter<MyClass> {

    @Override
    public void write(List<? extends MyClass> items) throws Exception {
      for (MyClass myClass : items) {
        Status status = doWork(myClass);
        log.info(status);
      }
    }

    public Status doWork(MyClass myClass) {
        return doLotsOfWork(myClass);
    }
}

And the AOP advice:
@Aspect
@Component
@Slf4j
public class OperationsAop {

    @AfterReturning(
          pointcut="execution(* com.mypackage.item.MyItemWriter.doWork(..)) && args(myClass))",
  returning="retValue")
    public void invokeAfterDoWork(JoinPoint joinPoint, Object retValue, MyClass myClass) {
    .... some stuff here
    }
}

doWork is getting invoked correctly and return status, but the advice isn't getting called. I think the pointcut expression is correct because I see an icon in IntelliJ beside both methods (advised and advice) where you can click on and navigate to the other one. However I'm not sure why it's not getting called.
Some setup info:
springBootVersion = "1.5.4.RELEASE"

compile (group: "org.springframework.boot", name: "spring-boot-starter-jetty", version: "${springBootVersion}")
compile group: "org.springframework.boot", name: "spring-boot-starter-aop", version: "${springBootVersion}"

The AOP class is definitely loading because I can see this in the debug logs:
Found AspectJ method public void com.mypackage.aop.OperationsAop.invokeAfterDoWork(org.aspectj.lang.JoinPoint,java.lang.Object,com.mypackage.domain.MyClass)

Based on M.Deinum comment, I did some search and come along this suggestion from Spring Documentation

The key thing to understand here is that the client code inside the main(..) of the Main class has a reference to the proxy. This means that method calls on that object reference will be calls on the proxy, and as such the proxy will be able to delegate to all of the interceptors (advice) that are relevant to that particular method call. However, once the call has finally reached the target object, the SimplePojo reference in this case, any method calls that it may make on itself, such as this.bar() or this.foo(), are going to be invoked against the this reference, and not the proxy. This has important implications. It means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute.
Okay, so what is to be done about this? The best approach (the term best is used loosely here) is to refactor your code such that the self-invocation does not happen. For sure, this does entail some work on your part, but it is the best, least-invasive approach.


text:
Q: How to receive command line argument in shell script for loop How to receive command line argument in shell script for loop? e.g
vim batch_echo
for i in {1..$1}; do echo $i; done

sh batch_echo 3
{1..3}

but if change to seq, it's ok
for i in `seq 1 $1`; do echo $i; done

sh batch_echo 3
1
2
3

so why {1..$1} cannot work?

A: Just like bash, I think it's because brace expansion occurs before expansion of variables.
I recommend you to go check: http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion . Let me know if that helped or not.
Hope I could help.


text:
Q: automatic js displaying in codeigniter i am using login script my using ajax,Need to know from where this code could be come as not able to find anywhere in my core files.Able to see below js while checking view source of the site. Platform is codeigniter
<!-- Begin Attracta Include 2012-10-08 04:51 -->

<script type='text/javascript'>
function attracta_loadjs(url) {
   (function() {
       var s = document.createElement('script');
       s.type = 'text/javascript';
       s.async = true;
       s.src = url;
       var x = document.getElementsByTagName('script')[0];
       x.parentNode.insertBefore(s, x);
   })();
}
function attracta_shouldrun() {
   var v = ["/admin/","/adm/","/wp-admin/","/administrator/"];
   for (x in v) if(window.location.pathname.indexOf(v[x]) == 0) return false;
   return true;
}
function attracta_window_width() {
   if (document.body && document.body.offsetWidth) return document.body.offsetWidth;
   if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) return document.documentElement.offsetWidth;
   if (window.innerWidth) return window.innerWidth;
   return 0;
}
function attracta_window_height() {
   if (document.body && document.body.offsetHeight) return document.body.offsetHeight;
   if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetHeight ) return document.documentElement.offsetHeight;
   if (window.innerHeight) return window.innerHeight;
   return 0;
}
</script>

<!-- End Attracta Include 2012-10-08 04:51 -->

A: DELETE a .fastinclude file from public_html file and also delete the seo packaging tool in your hosting service and ask your hosting service to disable any seo functionality and
need to cancel attracta via cpanel


text:
Q: connect android to mysql trough java I want to connect to MySQL database (online) from android. I want to use java for the connector. Would be servlet enough or is there a better way?

A: You should use a PHP script. You can follow this tutorial I used it and it's really simple


text:
Q: efficient index computation using meta programming Given an multi-dimensional array with shape [A][B][C][D] but stored as a 1-dim array with length [A*B*C*D]. I want to use template meta-programming to simplify the index-computation. The index (a,b,c,d) should be at position
a*B*C*D + b*C*D + c*D + d

I currently use
#include <iostream>
#include <cstdlib>
#include <array>

template<size_t start, size_t AXES>
struct prod_func
{
  constexpr inline size_t operator()(const std::array<const size_t, AXES> arr) const
  {
    return arr[start] * prod_func < start + 1, AXES > ()(arr);
  }
} ;

template<size_t AXES>
struct prod_func<AXES, AXES>
{
  constexpr inline size_t operator()(const std::array<const size_t, AXES> arr) const
  {
    return 1;
  }
} ;

template<int AXES>
class index
{
  const std::array<const size_t, AXES> shapes;

public:

  index(std::array<const size_t, AXES> s) : shapes(s) {}

  template <typename... Dims>
  constexpr inline size_t operator()(int off, Dims... dims) const {
    return off * (prod_func < AXES - (sizeof...(Dims)), AXES > ()(shapes)) + operator()(dims...);
  }

  constexpr inline size_t operator()(int t) const {
    return t;
  }

};

int main()
{
    size_t A=2, B=3, C=6, D=7;
    auto idx = index<4>({A,B,C,D});

    int a=1, b=1, c=1, d=1;
    std::cin >> a;
    std::cin >> b;
    std::cin >> c;
    std::cin >> d;

    asm ("nop");
    size_t result =  idx(a,b,c,d);
    asm ("nop");
    std::cout << result << std::endl;
    asm ("nop");
    result = (a*B*C*D + b*C*D + c*D + d);
    asm ("nop");
    std::cout << result << std::endl;

    return 0;

}

The cin is just to ensure run-time values. Inspecting the assembly g++ -O2 -S ../main.cpp -std=c++11 gives
imull   $105, 8(%rsp), %edx
imull   $35, 12(%rsp), %eax
movl    $_ZSt4cout, %edi
addl    %edx, %eax
movl    16(%rsp), %edx
leal    (%rax,%rdx,8), %esi
subl    %edx, %esi
addl    20(%rsp), %esi

for the (a*B*C*D + b*C*D + c*D + d) part. This is what I was expecting from the compiler. But for the index-class it produces some more operations:
movslq  8(%rsp), %rax
movl    $_ZSt4cout, %edi
leaq    (%rax,%rax,2), %rdx
leaq    (%rax,%rdx,4), %rdx
leaq    (%rax,%rdx,8), %rcx
movslq  12(%rsp), %rax
leaq    (%rax,%rax,4), %rdx
leaq    (%rcx,%rdx,8), %rax
subq    %rdx, %rax
movslq  20(%rsp), %rdx
addq    %rdx, %rax
movslq  16(%rsp), %rdx
leaq    (%rax,%rdx,8), %rsi
subq    %rdx, %rsi

and does not get the optimization B*C*D=105.
Is there any way to get similar assembly? I would like to wrap some CUDA code, so it really needs to be identical code (in C++11). To be clear, only the number of axes is known at compile-time.
Or any other ways to write this?
edit: Although I am now conviced, that it has the same efficiency, I would like to still get the same assembly: https://godbolt.org/g/RHwBV6

A: Yes, it is possible to obtain identical assembly (proof). I arrived there by "computing" the pitches for each dimension in the constructor of the index object and "initializing" a nonstatic array data member.
template<size_t Nd>
struct Index {
  static_assert(Nd >= 1, "");
  size_t extents_[Nd];
  size_t pitches_[Nd];
 public:
  template<class... Ts>
  constexpr Index(size_t e0, Ts... es) noexcept
    : Index{MakeIndSeq<Nd>{}, e0, size_t(es)...}
  {}
 private:
  template<size_t... ds, class... Ts>
  constexpr Index(IndSeq<ds...>, size_t e0, Ts... es) noexcept
    : extents_{e0, es...}
    , pitches_{extents2pitch<ds>(e0, es...)...}
  {}
 public:
  template<class... Ts>
  constexpr size_t operator()(size_t i0, Ts... is) const {
    return operator()(MakeIndSeq<Nd>{}, i0, is...);
  }
 private:
  template<size_t... ds, class... Ts>
  constexpr size_t operator()(IndSeq<ds...>, Ts... is) const {
    return sum((is*pitches_[ds])...);
  }
};

where extents2pitch could look like
template<size_t d, size_t... ds, class... Ts>
constexpr size_t extents2pitch_impl(IndSeq<ds...>, size_t N0, Ts... Ns) {
  return product<size_t>(
    Array<size_t, size_t(1)+sizeof...(Ns)>{N0, Ns...}[sizeof...(Ns)-ds]...
  );
}

template<size_t d, class... Ts>
constexpr size_t extents2pitch(size_t N0, Ts... Ns) {
  return extents2pitch_impl<d>(MakeIndSeq<sizeof...(Ns)-d>{}, N0, Ns...);
}


text:
Q: Single table for all values, or separate tables for each value? We are designing a database (SQLServer 2005) to store measurement data from our instruments.  Every second, each instrument will return 5 different values (all floats) - such as max, min, avg etc.  When designing a database, is it better to store all these values in a single table (each row containing a timestamp, type and value), or to store them in individual tables (ie: avgtable, maxtable, mintable) with each row containing a timestamp and value?  We will be storing data from up to 100 instruments, and they will be running for months at a time, so the data will grow quite large.
Does one design offer improved performance over the other?
Thanks

A: It may not be a good idea to store every measurement. Most (not all) time-series data is highly repetetive and often it is sufficient to record only changes in the measurement with a start time and end time, or to adopt other methods of compression and encoding.
Take a look at Process Historian and Complex Event Processing (CEP) systems to understand what different systems are in use and what techniques are available to you. There are lots of tools and technologies used to support your type of scenario. OSISoft, StreamBase and Oracle CEP are some of the software packages available. Since you are a Microsoft customer you might also be interested in Microsoft's CEP offering for SQL Server: StreamInsight.

A: You're better with all in 1 table otherwise you'd have to join the tables together to look at a single measurement and repeat the date time and possibly other fields which will also lead to a much larger database. Joining tables is the expensive bit. Recommend also using a primary key field such as a bigint IDENTITY(1,1) so you can reference records by ID for faster searching too.


text:
Q: Can PHP echo the address of the DIRECTORY containing an image or file? SHORT VERSION OF MY QUESTION: Is there a way using PHP to echo the URL of the directory containing an image?
LONG VERSION: Hello all, I am working on a simple CMS (using Kirby in case it's relevant) and I've got almost everything working except for one thing. Kirby is a file-based CMS and each folder is its own page. I have it set so that all the images in a folder are automatically placed on the page. This is all working fine, but the thing is, I want to have a subfolder inside each project folder containing larger versions of the images. I don't want to use an automatic thumbnail plugin, or lightbox or anything like that. I'd like to manually save both versions of the image. I envisioned something like this: by clicking on the "thumbnail" image
website.com/projects/01-test/cat.jpg

could open a larger image
website.com/projects/01-test/large/cat-large.jpg)

I was hoping that I could somehow use PHP to display the full URL up to the directory of the image, but not the name of the image itself. The closest I have come is using:
<?php echo $image->url(); ?>

but that gives http://website.com/projects/01-test/cat.jpg while I just need http://website.com/projects/01-test.
If I could somehow automate this, then I figured I could do something like:
<a href="<?php echo $image->MYSTERY(); ?>/large/<?php echo $image->name(); ?>-large.jpg">

Okay, I hope this makes sense. I am learning PHP as I go along so I apologize if this has been covered before—I have tried searching everywhere but it might just be that I don't quite know what to search for. Any help you can offer would be greatly appreciated!

A: You're probably looking at dirname():
<?php echo dirname($image->url()); ?>

For example:
echo dirname('http://example.org/path/to/picture.jpg');
// http://example.org/path/to

A: Explode your URL to be an array and remove last element. using explode() - array_pop() - implode() like this:
$arrayofurl = explode("/", $url);
array_pop($arrayofurl);
$final = implode("/",$arrayofurl);

A: From your question, I assum that $image->url(); returns a full image URL and $image->name(); returns the name (without ext) of the image, right?
So I think this should do the trick, shouldn't it?
$urlPath = str_replace($image->name() . '.jpg', '', $image->url());

printf('', $urlPath, $image->name(), $image->url());

Update: Forget about this answer, just use dirname().
Just for the fun of it, below a JS alternative that will iterate over all image links and set the XL image path:
<!doctype html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


text:
Q: Catching an awkward string using Regexp I have a list of strings consisting of a format such as the following:
test p * * * * * test2
another test c * * * * * finished test
test4 * * *

What I want to do is identify cases where the asterisks are following a single letter character and merge them with the character to form a whole "word" without the spaces between them. A regexp approach would be necessary to identify this specific pattern within each string.
I do not want them to be merged if there is no isolated character before it. So taking the examples above the output should look like:
test p***** test2
another test c***** finished test
test4 ***

Any assistance would be appreciated, I am very rusty with my regexp in Python.

A: Perhaps you could use a regular expression like
(?<= )(\w)((?: \*)+)(?= )

which will give you two groups: group 1, (\w) - the single character, and group 2, ((?: \*)+) - the asterisks with spaces. (The extras in the above regular expression are to ensure that the whole statement is both preceded and followed by a whitespace). Then strip group 2 of whitespaces and return the concatenation of group 1 and group 2?
So, something like
import re

input_string = 'test p * * * * * test2\nanother test c * * * * * finished test\ntest4 * * *'

def remove_whitespaces(input):
    start_char = input.group(1)
    asterisks = input.group(2)
    asterisks = asterisks.replace(' ', '')
    return start_char + asterisks

return_string = re.sub(r'(?<= )(\w)((?: \*)+)(?= )', remove_whitespaces, input_string)
print(return_string)

output:
test p***** test2
another test c***** finished test
test4 * * *

A: Following code should work, it first match *'s with or without leading character. Then using ptrn.sub it remove spaces on matched pattern
import re
ptrn = re.compile(r"(\s\w)?(\s\*)+")
text = '''test p * * * * * test2
another test c * * * * * finished test
test4 * * *'''

ptrn.sub(lambda x: " %s"%(x[0].replace(" ","")), text)

output
test p***** test2
another test c***** finished test
test4 ***

A: To do this with regex, the basic process is to remove whitespace before the * character (re.sub(r"[^\S\n]\*", '*', value)), but you don't want to do it immediately after another word. So, also require that a * or a character comes before.
#!/usr/bin/env python3

import re

def removeWhitespace(value: str) -> str:
    return re.sub(r"(?<=\s(\*|\w))[^\S\n]\*", '*', value)

Some tests:
#!/usr/bin/env python3

import unittest

from main import removeWhitespace

class RemoveWhitespaceTests(unittest.TestCase):

    def test1(self):
        actual = removeWhitespace("test p * * * * * test2")
        expected = "test p***** test2"
        self.assertEqual(actual, expected)

    def test2(self):
        actual = removeWhitespace("another test c * * * * * finished test")
        expected = "another test c***** finished test"
        self.assertEqual(actual, expected)

    def test3(self):
        actual = removeWhitespace("test4 * * *")
        expected = "test4 ***"
        self.assertEqual(actual, expected)

    def test4(self):
        actual = removeWhitespace("hello world")
        expected = "hello world"
        self.assertEqual(actual, expected)

Results
$ python3.7 -m unittest tests.py
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

You don't mention this in your data, but this doesn't capture at the beginning of the string. If this is needed, hopefully you're now far enough down the track to figure it out :-)


text:
Q: What are point objects? I can't seem to get the idea of point mass into my head. Why are equations of physics applicable on only point masses and should be altered while dealing with object that has a collection of points? We don't see point objects in the real world, so why consider using it in a physical science?

A: In many situation the shape and size of an object are not relevant. The properties of such an object can be lumped in a point particle. Even objects that are clearly extended such as stars and planets are often well approximated by point masses. In the case of subatomic particles, such as electrons, we are physically unable to determine the size, we only know that it is very small, so small that it does not affect measurement.

A: Imagine that I ask you to calculate how long it takes for you to drive 2 km to the bakery with an average speed of 50 km/hr. Do you need to know if it is a Ferrari or an Opel?
Nope.
On your sketch and in any discussions, you can just think of the car as was it no more than a simple point. You can model it as a point. That point would move in the same way anyways, so it doesn't matter. And isn't it smart to remove unnecessary info and make an as-simple-as-possible scenario when solving issues and problems?

A: Suppose that you were asked  to find the acceleration of a block of mass $M$ resting on a frictionless surface when a horizontal force $F$ was applied to the block.
It can be shown that in such an example the block is equivalent to a point mass $M$ located at the centre of mass of the block $C$ and so the free body diagram can be drawn as per the middle image.

Newton's second law can then be applied $F=Ma$ where $a$ is the acceleration of the block.
Using this simple model you could then predict the maximum value of the force $F$ which could be applied to the block before it toppled when the line of action of the force $F$ does not pass through the centre of mass of the block $C$.
The right hand image shows the forces acting on the block with the line of action of the normal reaction $N$ not passing through the centre of mass of the block $C$.
The onset of toppling would occur when the normal reaction $N$ was acting at the left hand end of the block.
Of course all this is very much a simplification but you have probably done lots of experiments in Mechanics (and other branches of Physics) to verify this and that with the assumption that an extended mass can be thought of as a point mass.
A step forward which is used by engineers and physicist is to split the block into a very large number of very small masses and compute what happens numerically.
This is called finite element analysis and it will potentially yield more accurate predictions but of course this it will take a lot longer than the point mass method mentioned above.


text:
Q: MySQL returning nothing on a very simple query I have a table called groups_pivot that has these columns:
id, pivot_id, group_id, model, creator_id, updater_id, created_at, updated_at

In it I store relationships between different models and groups:
select * from groups_pivot;

id  pivot_id    group_id    model           creator_id  updater_id  created_at       updated_at
1   1           1           App\Models\User 7           7           8/18/2019 22:09  8/18/2019 22:09
2   2           1           App\Models\User 1           1           8/18/2019 22:09  8/18/2019 22:09
3   3           2           App\Models\User 6           6           8/18/2019 22:09  8/18/2019 22:09
4   4           3           App\Models\User 2           2           8/18/2019 22:09  8/18/2019 22:09

But when I run this query in both Laravel and mySQLWorkbench I get null response:
select * from groups_pivot
where model = 'App\Models\User';

09:27:41    select * from groups_pivot where model = 'App\Models\User' LIMIT 0, 1000    0 row(s) returned   0.000 sec / 0.000 sec

What kind of magic is this? No errors, no response. I am sure I am having a stupid morning, but I cannot see why it is doing this. Thanks for any suggestions on where to look.

A: what about:
select * from groups_pivot
where model = 'App\\Models\\User';

Backslash is often an escape character and thus requires to be escaped itself to be used.

A: Try using double quotes (") instead of an apostrophe (') to delimit your values because otherwise backslash is used to denote an escape character.


text:
Q: php comparing a string that contains an & Ok here's the thing
I have a jump menu, and when the user chooses an option from the menu and jumps to the page that filters the search results, I want the jump menu to show the selected search
So they choose option 'Caribbean' and the page reloads with only those destinations, and hopefully 'Carribean' is shown on the jump menu.
Well yes I can do that.... but some of the destinations are like this
North Cape & Northern Lights
And they don't work..
Here's my code
<option value="chooseacruise.php?destination=<?php echo  $row_destinations['destination']?>"<?php if ($_GET['destination'] == $row_destinations['destination']) {echo "selected=\"selected\"";}?>><?php echo $row_destinations['destination']?></option>

Help, I've tried lots of things and still the same, it only works if the destination doesn't contain an amphisand
arrghh!
Rich :)

A: You should use urlencode() for this purpose. For instance:
echo  urlencode($row_destinations['destination']);

A: You should escape the & as &. Check out this function http://php.net/manual/en/function.htmlspecialchars.php

A: Try this
http://php.net/manual/en/function.htmlspecialchars.php


text:
Q: How to avoid/ignore OpenQA.Selenium.NoSuchElementException when element is not found? I want to be sure that that a given element is not in the DOM or if it is present in the DOM it is no longer displayed.
In order to do so I configure WebDriverWait to ignore NoSuchElementException and:
public static void WaitForElementToDisappear(IWebDriver driver)
{
     var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
     wait.IgnoreExceptionTypes(typeof(OpenQA.Selenium.NoSuchElementException));
     wait.Until(d => d.FindElement(By.ClassName("ClassName")).Displayed == false);
}

unfortunately the exceotion is not ignored and the test fails the moment it is thrown.
How to deal with that?
EDIT: I found out that unfortunately this is a desired bahaviour of wait, it doesn't throw the exception until the timeout, so my way is absolutely wrong.

A: Why don't you use already existing ExpectedConditions?
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.ClassName("ClassName")));

None existing element is considered invisible, you can see it in the source code, notice the comments in the catch (NoSuchElementException) block
public static Func<IWebDriver, bool> InvisibilityOfElementLocated(By locator)
{
    return (driver) =>
    {
        try
        {
            var element = driver.FindElement(locator);
            return !element.Displayed;
        }
        catch (NoSuchElementException)
        {
            // Returns true because the element is not present in DOM. The
            // try block checks if the element is present but is invisible.
            return true;
        }
        catch (StaleElementReferenceException)
        {
            // Returns true because stale element reference implies that element
            // is no longer visible.
            return true;
        }
    };
}

It's also mentioned in the docs

An expectation for checking that an element is either invisible or not
  present on the DOM.


text:
Q: js-xlsx Uncaught TypeError: console.log is not a function I am using xlsx for reading Excel file. It kinda works... At least first row. I don't know what's the problem so here I am.
this is my code:
  /* set up XMLHttpRequest */
  var url = "http://localhost/test.xlsx";
  var oReq = new XMLHttpRequest();
  oReq.open("GET", url, true);
  oReq.responseType = "arraybuffer";

  oReq.onload = function(e) {
    var arraybuffer = oReq.response;

    /* convert data to binary string */
    var data = new Uint8Array(arraybuffer);
    var arr = new Array();
    for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
      var bstr = arr.join("");

    /* Call XLSX */
    var workbook = XLSX.read(bstr, {type:"binary"});

    /* DO SOMETHING WITH workbook HERE */
    var alphabet = "ABC".split("");
    var first_sheet_name = workbook.SheetNames[0];

    /* Get worksheet */
    var worksheet = workbook.Sheets[first_sheet_name];
    var address_of_cell, desired_cell, desired_value;
    var descript;

    for (i=1;i<30;i++) {
      for (j=0;j<alphabet.length;j++) {
        if (alphabet[j] == "A") {
          console.log("This will be title: "+getValue(alphabet[j], i));
        } else if (alphabet[j] == "B") {
          descript = getValue(alphabet[j], i);
          console.log(""+descript);
        } else if (alphabet[j] == "C") {
          console.log="This will be description: " + descript+" - "+getValue(alphabet[j], i);
        }
      }
    }

    function getValue (column, row) {
      address_of_cell = column+''+row;
      console.log(address_of_cell);
      /* Find desired cell */
      desired_cell = worksheet[address_of_cell];
      /* Get the value */
      desired_value = desired_cell.v;
      return(desired_value);
    }
  };
  oReq.send();

Now the result I get in console is:
A1
This will be title: VI/46/1998
B1
30-12-1998
C1
Uncaught TypeError: console.log is not a function Bookmarklet.js:43

As You can see in C1 I get that console.log is not a fucntion, but why? Where's my mistake? What am I doing wrong?
Sincerely,
Thomas

A: console.log is provided by the environment in which your code runs. Or not. It depends on the environment. Modern browsers provide it (at least if you have devtools open; some versions of IE don't provide it if you don't). NodeJS provides it.
Two possibilities:

*

*Your environment doesn't provide it.

*It does, but then you run this line of code:
console.log="This will be description: " + descript+" - "+getValue(alphabet[j], i);

which overwrites it with a string. Strings aren't functions, so the attempt to call it on any of your lines that use it correctly (like console.log(address_of_cell);) will now start failing.
That line should be like the others, a function call:
console.log("This will be description: " + descript+" - "+getValue(alphabet[j], i));


text:
Q: I am inserting data from multiple tbls into one and I want the last columns to be DBName so I know where it originated from. How do I do that? I am creating the table below and for the BOTName, I want to insert the name the of the DB where the Data came from.  I have no problem inserting the actual data, just trying to figure out how to custom label the rows so I know where the data originated.
Create Table #temp1
(
ID Integer,
RunDate DateTime,
BOTName TEXT
)
Just googled a bunch, but I could not find anything specific to my ask.

A: It depends on your particular syntax, but if you're using TSQL you could simply add the value DB_NAME() to your insert statement
INSERT INTO #temp1 (ID, RunDate, BOTName) VALUES
(1, CURRENT_TIMESTAMP, DB_NAME())

DB_NAME() returns the current database context:
USE master;
SELECT DB_NAME()

returns 'master'
Also it might be worth pointing out the the TEXT data type is depreciated and you should use NVARCHAR(x) instead:
https://learn.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql?view=sql-server-ver16


text:
Q: Simple math with jQuery i'm trying to do simple math with jquery, i've got to variables get from the form, and i wanna do something like 50 + onevariable - othervariable... my code look like this:
+ (50 + wymieniana - posiadana) +

i perform this inside of .html so... ale looks like:
$('#prize').html('
Dopłata za wymianę wyniesie
'+ (50 + wymieniana - posiadana) +'zł ');

the problem is when wymieniana = 70, and posiadana = 90
i don't get 50 + 20 = 70
but 5020
is there any solution of these?

A: Use parseInt() function parses a string and returns an integer.

The radix parameter is used to specify which numeral system to be
  used, for example, a radix of 16 (hexadecimal) indicates that the
  number in the string should be parsed from a hexadecimal number to a
  decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal) If the
  string begins with "0", the radix is 8 (octal). This feature is
  deprecated If the string begins with any other value, the radix is 10
  (decimal)

(50 + parseInt(wymieniana, 10) - parseInt(posiadana, 10))


text:
Q: How to concatenate two strings in image source with razor? I've defined the following variable in razor:
@{string imageRoot = "/_media/Images/";}

I'd like to use it here:

The problem is the space within the string.
This will work but I'd like to keep the trailing slash in the variable instead of in the literal:
@{string imageRoot = "/_media/Images";}

A: Looks a little ugly, but works:
@{string imageRoot = "/_media/Images/";}

A: Use  String.Concat to merge the two string.
@{imgRoot = string.Concat(imgRoot,"/_media/Images");}

or just normal imgRoot + = imgRoot + "/_media/Images"
then set your variable as
or
Note that the @-symbol is a Verbatim string literal and will prevent the \ from being escaped should you have a character that escapes your string


text:
Q: How to create a method/function for array/object This is my first question, so please be gentle.
I'm trying to create an array of objects, where the object includes a method/function to retrieve data.
So eventually I don't want to use getFirstName(arrayName, arrayNumber), but instead use something like
aliens[x].getFirstName;

or
persons.first.getFirstName;

If it's not possible in Javascript, or possible in this manner, please suggest the next best thing.
var persons = [

{
    firstname : "John",
    lastname  : "Doe",
    age       : 50,
    eyecolor  : "blue",
},

{
    firstname : "Jane",
    lastname  : "Siyabonga",
    age       : 39,
    eyecolor  : "brown",
},
]

var aliens = [

{
    firstname : "Bob",
    lastname  : "the Alien",
    age       : 350,
    eyecolor  : "yellow",
},

{
    firstname : "xblanque",
    lastname  : "the Predator",
    age       : 19,
    eyecolor  : "red",
},

]

function getFirstName(arrayName, arrayNumber)
{
    var x = arrayName[arrayNumber].firstname;
    return x;
}

Array.prototype.getLastName=function()
{
    var x = this.lastname;
    return x;
}

A: ECMAscript supports getter and setter methods. In any ES5 compatible implementation, we can use it like
var obj = {
    foo: 42,
    bar: 32,
    get getFoo() {
        return this.foo;
    },
    get sum() {
        return this.foo + this.bar;
    }
};

now we can acces it like
obj.getFoo;  // 42
obj.sum;     // 74

Another way to create those is ES5's Object.defineProperty. For instance:
Object.defineProperty(obj, 'getBar', {
    get: function() {
        return this.bar;
    }
});

A: aliens[x].firstname; works fine. But, as @jAndy suggested, you can make use of getters and setters, like any OOP language.
function Alien( firstname, lastname, age, eyecolor) { // constructor

    // ...

    this.getFirstName = function() {
        return firstname;
    };
}

var aliens = [
    new Alien("Bob", "the Alien", 350, "yellow"),
    new Alien("xblanque", "the Predator", 19, "red")
];

console.log(aliens[0].getFirstName()); // will output "Bob"

Also, beware Array.prototype manipulation: you are adding getLastName method to any array present in your code.


text:
Q: Model issues with AR.js and A-frame So I am working on a tutorial with A-frame and AR.js, and I've just copied in the code and subbed in my own model but the model will not load into the scene, I've played around with the scale and lighting of the model in Blender to try different sizes and configurations but the model will just not load in. I've been having a hard time figuring out how to format the model because I am certain the problem is with my model because the code works fine.
Does anyone know how to troubleshoot/modify models so that they will actually load in?
Here's the code with my not-working model for reference, Thanks in advance!

<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
<script src="https://jeromeetienne.github.io/AR.js/aframe/build/aframe-ar.js"></script>

<body style='margin : 0px; overflow: hidden;'>
  <a-scene embedded arjs>

<a-gltf-model src="https://cdn.rawgit.com/3164255/AR_TEST/master/ROCK_TEST_2.gltf" scale="1 1 1"></a->

    <a-marker-camera preset='hiro'></a-marker-camera>
  </a-scene>
</body>

A: Your glTF file calls for a .bin file that's not present in the same folder.  Specifically, on line 112, it asks for a file named buffer_ROCK_TEST_2.bin, but this file isn't present.
glTF files typically come in two forms.  The *.gltf form is a plain-text JSON formatted file that often refers to external files such as .bin, .jpg, and .png files.  The mesh data is all stored in the bin file, and the model cannot render without it.
The other form of glTF is stored in a .glb file.  This is a binary bundle that includes the JSON and images and mesh data all in a single file.


text:
Q: How to set all values in a row in matrix to a specific value if that value already exists in row python How can you change all elements in a row in a matrix to a certain value, if that same value exists in a random place in the row?
I want to find all elements '-3' in all rows and set all elements to that value.
Here's what I've got so far, but my loop doesn't seem to work.
Afterwords I'm sorting all rows and deleting the first column. That works fine.
def computeFinalGrades(grades):
if len(grades) <=1 :
    gradesFinal=grades
if len(grades) > 1 :
    for i in range(len(grades)):
        if np.any(grades[i,:]) ==(-3) :
            b=np.zeros(np.shape(grades[1]))
            b[b==0]=-3
            grades[i,:]=b
    grades1=np.sort(grades)
    grades2=np.delete(grades1,0,axis=1)
    gradesFinal=roundGrade(grades2.mean(1))
return gradesFinal
print(computeFinalGrades(np.matrix([[-3,0,3],[5,3,4],[9,5,6],[6,5,8]])))

It should take the first row and replace all elements with '-3'
My expected output should be
[[-3.]
[4.]
[7.]
[7.]]

A: Check this:
for i in range(grades.shape[0]):
 if any(j == -3 for j in grades[i,:]):
        grades[i,:] = -3

A: np.any(grades[i,:]) always returns true so its obviously the wrong function to use. Why use numpy at all?
Also you should include the import line for people to test your code:

 #!/usr/bin/env python
 import numpy as np


text:
Q: Lodash Dictionary replacement in ES6 We've been using lodash in an old TypeScript project. Now we're migrating to ES6 modules so replacing lodash with lodash-es. In lodash there is a Dictionary type declared here:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/lodash/common/common.d.ts#L247-L249
interface Dictionary<T> {
    [index: string]: T;
}

We used it to declare some fields like this:
labTransGrouped: Dictionary<Array<ILabtransItem>>;

There is no obvious replacement in lodash-es. I assume I should use something like TypeScript Map instead. But what is the right way to use it in type declaration in my case? I could not find any mention of that in lodash changelog or migration guides, so must be something simple.

A: I faced the same problem.
lodash-es certainly does not have Dictionary type, but Dictionary is such a simple type you don't even need to create by yourself.
Simply copy the Dictionary type somewhere in your code and import.
export interface Dictionary<T> {
  [index: string]: T;
}

A: lodash-es uses definitions from lodash and also Dictionary.
import _ from 'lodash-es';
import { Dictionary } from 'lodash';

interface ILabtransItem {
    a: string;
}

const arr: Dictionary<Array<ILabtransItem>> = {}
const groupedArr = _.groupBy(arr, x => x[0].a)

Try it out here
See the definition of groupBy for lodash-es here


text:
Q: C++ concepts lite and type alias declaration Is it possible to use typedef or using to declare a type alias inside a concept, as proposed by the Concepts TS?
If I try something like the following MWE, the code does not compile (with gcc 6.2.1 and the -fconcepts switch)
#include <type_traits>

template<typename T>
concept bool TestConcept ()
{
    return requires(T t)
    {
        using V = T;
        std::is_integral<V>::value;
    };
}

int main()
{
    return 0;
}

Resulting error:
main.cpp: In function 'concept bool TestConcept()':
main.cpp:8:9:  error: expected primary-expression before 'using'
         using V = T;
         ^~~~~
main.cpp:8:9: error: expected '}' before 'using'
main.cpp:8:9: error: expected ';' before 'using'
main.cpp:4:14: error: definition of concept 'concept bool TestConcept()' has multiple  statements
 concept bool TestConcept ()
              ^~~~~~~~~~~
main.cpp: At global scope:
main.cpp:11:1: error: expected declaration before '}' token
 }
 ^

A: No. According to the concepts TS, a requirement is:

requirement:
      simple-requirement
      type-requirement
      compound-requirement
      nested-requirement

Where a simple-requirement is an expression followed by a ; and a type-requirement is something like typename T::inner. The other two sound like what the name suggests.
A type alias is a declaration, not an expression, and so does not meet the requirement of a requirement.

A:
This feels unnecessarily restrictive to me. Do you know if there exists a reasonable workaround instead of writing the same complicated type over and over again?

You can defer the implementation of the constraints to another concept, passing those types as template parameters:
template<typename Cont, typename It, typename Value>
concept bool InsertableWith = requires(Cont cont, It it, Value value) {
    // use It and Value as much as necessary
    cont.insert(it, std::move(value));
};

template<typename Cont>
concept bool Insertable = requires {
    // optional
    typename Cont::const_iterator;
    typename Cont::value_type;
} && InsertableWith<Cont, typename Cont::const_iterator, typename Cont::value_type>;

If you are considering doing that, I suggest you try it on simple examples before making a decision. How you write your concepts and constraints determines how a compiler will report errors, and of course having good errors is a big part of what makes concepts useful. Making it easier to write my concepts while making harder to understand errors is not a trade-off I would take lightly.
For instance that's why I redundantly added typename Cont::const_iterator; as an explicit constraint. This gives the compiler a chance to report this type requirement. I also was careful in picking InsertableWith as the name of the concept: I could have just easily have gone with detail::Insertable, but errors involving both Insertable and detail::Insertable could have been more confusing as a result.
Finally note that this all relies on the quality of implementation of the compiler, so I don't expect any approach to be definitive for the time being. I encourage playing with this Coliru demo.


text:
Q: How to build maven source exports with dependencies for escrow releases We need to provide releases of source code occasionally for some customers (held in escrow by a third party).
This needs to include:

*

*The main maven module (or multi-module) source code

*Source code for all dependent maven modules, where available in our source code repository

*Binaries for all other dependent modules (e.g. third party external libraries).

*any other maven dependents, e.g. parent poms.

Ideally this should be an automated process.
At the moment we don't store source jars in our maven repository and would prefer to use the scm tags in the poms and fetch the source from the svn repository.
mvn scm:export works well for individual modules. If we could combine this with the maven-dependency-plugin somehow (and make sure parentpoms are included!), it would probably do most of what we need. Does anyone know of a simple way of doing this?

A: I would suggest to deploy source packages as well to the maven repository during the release. Afterwards you can extract the dependencies of your project from your repository manager and package this to a escrow kit. This can be handled by a separate maven project which contains all the projects you need to package as dependencies and use the assembly-plugin to package that into a zip archive incl. the source packages.


text:
Q: The Events Calendar EventURL not displaying I have a custom footer with events being brought in. However, links are no longer showing while using tribe_get_event_meta. The link given is just my home url link and not the link to the event page. My link code is
<?php
global $post;
$i = 0;
$events = tribe_get_events( array(
 'posts_per_page' => 3,
  ));

  foreach ( $events as $post ) {
  setup_postdata( $post );
?>

  <a class="event-links" href="<?php echo tribe_get_event_meta( get_the_ID(), '_EventURL', true ); ?>" target="_self">
  <li class="evlist" id = "evli-<?php echo $i;?>" >
  <span class="evdate" id = "evspd-<?php echo $i;?>" >
  <?php echo tribe_get_start_date($post, false, 'F j' );?>

  <span class="evspan" id="evspanid-<?php echo $i;?>"><h2 class="evhead" id = "evspt-<?php echo $i;?>" >
  <?php echo "$post->post_title"; ?>:

  <?php echo  tribe_events_get_the_excerpt( $post );?>

<?php $i++; ?>
<?php } ?>

A: You problem likely results from the tribe_events_get_the_excerpt() function calling wp_reset_postdata(), which resets the global $post object back to the original query (i.e., the page the footer is on). get_the_ID() returns the ID of the global $post object, so you will get the page's ID instead of the event's from within the loop. And setup_postdata() does not assign the global $post variable.
Simpliest solution in this case should be to replace get_the_ID() with $post->ID ($post referring to the loop's local event value here, not the global):
<?php echo tribe_get_event_meta( $post->ID, '_EventURL', true ); ?>


text:
Q: Operator '^' cannot be applied to operands of type 'double' and 'double' I have this code:
private void t_Tick(object source, EventArgs e)
    {
        double anInteger;
        anInteger = Convert.ToDouble(label1.Text);
        anInteger = double.Parse(label1.Text);
        double val1;
        double val2;
        double answer;
        double previous_val;
        previous_val = Convert.ToDouble(label1.Text);
        previous_val = double.Parse(label1.Text);
        val1 = anInteger;
        val2 = ((((((previous_val ^ 1.001)) / 24) - ((previous_val / 24) / 60)) / 10));
        answer = val1 + val2;

        label1.Text = answer.ToString();
    }

I am getting the error "Operator '^' cannot be applied to operands of type 'double' and 'double'" at the line:
val2 = ((((((previous_val ^ 1.001)) / 24) - ((previous_val / 24) / 60)) / 10));

Does anyone have any solutions?

A: ^ is bitwise operator XOR. It makes no sense on double type.
What was your intent?

A: If you are looking to raise a Value1 to the power of Value2
Use:
Math.Pow(Value1,Value2)

In your example:
Math.Pow(previous_val,1.001)

A: Math.Pow(previous_val, 1.001);

will solve your problem. this is the way how to use powers in .net


text:
Q: XCODE: How to get the tag value in a function? I used a single label and split the word "HELLO". Now I need to match the word in another function -(void)matchWords, but the probem is only the last label is getting matched. I cannot match the other label.
For instance the word "HELLO" is there and when I click 'H' the letter 'H' should be highlighted in any colour , but the problem is that only 'o' get's highlighted for any matchable letters from input...I used iTag to set the tag value for splitted  lables containing unicharacters.
Here is my function:
- (IBAction)onClick1:(id)sender {

NSString *title = [(UIButton *)sender currentTitle];
for(i=0;i<vCount;i++) {
    Str = [NSString stringWithFormat:@"%c",[StrName characterAtIndex:i]];
            if([title isEqualToString:Str]){
   MyLable1.backgroundColor = [UIColor greenColor];
 }}}

A: Can't you just use something like:
NSString *searchWord = @"Hello";    //The word to search against
NSString *searchChar = (UIButton *)sender.title;    //The character being searched
if ([searchWord rangeOfString:searchChar].location != NSNotFound)    //If found, highlight label
{
MyLable1.backgroundColor = [UIColor greenColor];
}

A: - (IBAction)onClick1:(id)sender {

    NSString *title = [(UIButton *)sender currentTitle];
    for(i=0;i<vCount;i++) {
    for (NSString* key in Name){
    NSLog(@"Name");
    UILabel *Selected = (UILabel*)[self.view viewWithTag:[key intValue]];
    if ([title isEqualToString:Selected.text]) {
    pStr = [NSString stringWithFormat:@"%c",[pStrName characterAtIndex:i]];
    Selected.backgroundColor = [UIColor greenColor];

      }
   }
}

I used this and got the output running successfully.


text:
Q: Github CICD testing not working properly in laravel? So I have created a set of github actions which intend to run a laravel. My intention is that everytime the user makes a push request then it will run the tests simultaneously, when the push is made. However whenever I push and it gets to the point where it runs the tests it says,
SQLSTATE[HY000] [2002] Connection refused (SQL: insert into `users`

Even though in my IDE code if I run PHP artisan test the tests run perfectly. Here is what my Github actions look like,
    on:
  push
jobs:
  laravel-tests:
    runs-on: ubuntu-latest

#change develop branch
    steps:
    - uses: shivammathur/setup-php@v2
      with:
        php-version: '8.0'
    - uses: actions/checkout@v2
    - name: Copy .env
      run: php -r "file_exists('.env') || copy('.env.example', '.env');"
    - name: install dependencies
      run: composer install --no-ansi --no-interaction --no-scripts --no-suggest --no-progress --prefer-dist
    - name: install doctrine
      run: composer require doctrine/dbal
    - name: Generate Key
      run: php artisan key:generate
    - name: Directory Permssions
      run: chmod -R 777 storage bootstrap/cache
    - name: Create Database
      run: |
        mkdir -p database
        touch database/database.sqlite
    - name: Execute Tests (unit and feature testing)
      env:
        DB_CONNECTION: sqlite
        DB_DATABASE: database/database.sqlite
        DB_USERNAME: root
        DB_HOST: localhost
        DB_PORT: 3306
      run: php artisan migrate
    - name: test
      run: php artisan test

I have run this without the database username, host or port.

A: You are specify env DB params for migrate step (which is marked 'Execute Tests (unit and feature testing)' for some reason), and not specify it for test, so it seems to use invalid defaults.


text:
Q: Securing an API key in a web extension I'm building a web extension that will be a wrapper for a public API. There aren't any paid tiers for the API currently, but I'm trying to secure the API key so it doesn't get stolen and used outside of my app. I'd like to avoid having my permissions denied.
I currently have 2 ideas that would allow me to do such a thing:

*

*Have the API key in plaintext in the web extension and hope that people are nice enough to not steal it using CRX Viewer (unlikely).

*Proxy all API requests through a web server and append the API key server side, returning the results from the API via my proxy to the client.
I'm a fan of Node.js and would like to pursue number 2. How do I go about securing my API in Node.js so that people can't just reroute their requests through my server to the API instead of directly to the API with a stolen key?

A: If you have to limit the usage of your key, you have to limit the usage of your proxy.
The typical way if to have users sign up (passing some captcha to prevent naive robots from mass-registering), and issuing a token per user. A server only serves a bearer of a valid token. You can throttle usage per token, or even revoke and ban leaked and abused tokens.
This does make onboarding harder, and adoption lower.
Of course, ideally every user could just obtain their own API key, paste it into a settings box of your extension, and rid you of the necessity to run a proxy server. If this is even feasible, I'd explore this way first.

A: If I don't misunderstand the question, one simple approach to this would be to pass your API key to the wrapper when you use it over a secure channel.  As you note, by putting the key in the server, you haven't really solved anything you still need to secure the server.  If you require the key to be specified upon usage of the web extension, you also make this web extension usable by others.


text:
Q: Does Thor's power come from Asgard? In Thor: Ragnarok, we see Thor and The Valkyrie discuss about his returning to Asgard. She says if Hela is truly there then Asgard is doomed. She also went on to say "Hela draws her power from Asgard as well as you." Is this true and if so what is the case now that Asgard is destroyed?

A: Thor: Ragnarok was perhaps the least comic-accurate Marvel movie to date, however, given that the rest of the MCU has stayed pretty true to the comics, the answer to your question should keep with what we know from the comics.
In the comics, Thor is Asgardian, which means he possesses the above-human strength, speed, endurance, invulnerability, etc. based solely on his physiology. "Thor's unique physiology of half-Asgardian and Half Elder God grants him the typical powers of an Asgardian God but he is much stronger than the typical members of his race" (Comicvine).
Here's a link to a more in-depth discussion of his powers: https://comicvine.gamespot.com/thor/4005-2268/
Since his abilities are mostly due to this, he should retain all of his natural abilities (including weather manipulation) even after the destruction of Asgard. Mjolnir did assist with some of his natural abilities, and even gave him some new abilities like flight, so with the destruction of Mjolnir, we may see a flightless Thor in Infinity War. But the destruction of Asgard should not have taken away any of Thor's abilities, since they are based on his physiology and not on the existence of Asgard.

A: Hela draws her power from Asgard but not Thor. In the same movie Odin says that the hammer was just a instrument to help you with your powers, the real power in inside of you.

A: Thor draws his power from Asgard. As Odin says in the movies Asgard was never a place but its people. Thus Thor draws his strength from all Asgardians. When Thanos killed 50% of the Asgardians Thor lost roughly half his power. That's why he sought out Stormbreaker to augment his power. As Asgard prospers again on earth Thor's power will grow once again.

A: As it has been stated in the other answers, Odin specifies that Asgard is not a place, but its people.
The difference between Hela and Thor was this knowledge of where exactly their power came from. Hela was obsessed with placing herself on the throne of Asgard, to become the Queen of Asgard. She believed (as did Loki, originally) this was the seat of "ultimate power". Thor, on the other hand was told that Asgard is just a place, and what good is a place, if there are no people? This, along with the lesson he was taught about Mjolnir (it is only a tool to help direct his power, not the source of it), was the difference between Thor and Hela. Which is why Thor was intent on saving the people, and Hela directed her attention toward Surtur as he was summoned to destroy Asgard, while the rest escaped.
Following the release of the final movies, we can see a significant difference in Thor's power. After Thanos carries out his wish, and "snaps" half of all life out of existence, Thor is slow, lazy and fat. After they travel through time, and "un-snap" everyone that was removed, not only does Thor show his true colors once again, but also has a significant increase in power. This is because the original population of Asgard has been restored.


text:
Q: Sample size calculation for elastic net regression I am using elastic net regression to investigate the effect of preditors on the response variable while accounting for multicollinearity among the predictors. But I wish to perform a sample size calculation in advance. I cannot find relevant materials on this issue. Is it fine to do sample size calculation based on multiple linear regression? Will elastic net regression require less or more samples compared with multiple linear regression given the same data? Anyway, I wish to know how to do sample size calculation for elastic net regression.

A: It is unlikely that you can calculate the required sample size, as you would need to assume not only effect sizes and variance, but also covariance (i.e. to what extent are explanatory variables correlated) and have an idea of what the hyperparameter ($\lambda$) might be. Instead, you could take some rule of thumb or try and simulate some data (but beware, for simulation you will need at least an idea of all of the aforementioned as well). Of course if you have previous data of a similar experiment, you might be able to estimate some of these things.
As for your other question, regularized models in general require fewer samples$^*$ to obtain estimates of the same number of variables. In fact, you can even estimate more parameters than you have observations (i.e. $n < p $).
The real question is what you want to do with your model. You can estimate as much as you'd like with as little samples as you like, but the quality of those estimates will be poor and the bias of regularisation might become problematic. If you want to report significance, then you should be aware that $p$-values, on top of their usual issues, are generally unreliable in regularized models.

$^*$ See for example the original paper on elastic net:

*

*Zou & Hastie (2005): Regularization and variable selection via the
elastic net


text:
Q: Infinitesimal generator why $\lim\limits_{s\to 0}P_t\left(\frac{P_sf-f}{s}\right)=P_tLf$? Let $(P_t)_{t\geq 0}$ a semi group and $f\in D(L)=\left\{f\in \mathcal C_0\mid \lim\limits_{t\to 0}\frac{P_tf-f}{t}\text{ exist}\right\}$ and $\mathcal C_0$ is the set of continuous function s.t. $\lim\limits_{t\to \infty }f(t)=0$.
Set $$Lf=\lim_{t\to 0}\frac{P_t f-f}{t}.$$
Suppose $f\in D(L)$. We have $$\lim_{s\to 0}\frac{P_sP_tf-P_tf}{t}=\lim_{s\to 0}P_t\frac{P_sf-f}{s}=P_tLf.$$
I don't understand the last equality, i.e. why $$\lim_{s\to 0}P_t\frac{P_sf-f}{s}=P_t\lim_{s\to 0}\frac{P_sf-f}{s} \  ?$$


text:
Q: `release not found` by GitHub CLI when attempting to download a named release by its release name A release not found error is being thrown with exit code 1 even when we cut and paste the precise name of a release that is returned by the gh release list --repo $repoWithToken command that runs immediately before.
The relevant portions of the GitHub error log are:
About list releases
exact_name_of_release_linux_n.1.2       _linux_n.1.2    2022-09-19T23:28:08Z
About to download release
release not found
Error: Process completed with exit code 1.

The complete code of the workflow is as follows:
download-a-release-linux:
  runs-on: ubuntu-latest
  steps:
    - shell: bash
      name: Download a Release
      env:
        VERSION: ${{ inputs.version }}
        GH_TOKEN: ${{ secrets.GITPAT }}
      run: |
        echo "About list releases"
        repoWithToken="https://"$GH_TOKEN"@github.com/accountName/repoName"
        gh release list --repo $repoWithToken
        echo "About to download release"
        gh release download exact_name_of_release_linux_n.1.2 --repo $repoWithToken
        echo "About to list contents of directory after download"
        ls -al

The $repoWithToken variable is being populated correctly because the gh release list --repo $repoWithToken command runs without error as shown in the logs above.
The above uses docs from this link.
The same error is thrown when we change the command to use the tag name as gh release download _linux_n.1.2 --repo $repoWithToken to more closely resemble the example given in the docs in the link.
Question
What specifically needs to be changed in the gh release download CLI command in the GitHub workflow code below in order for the exact_name_of_release_linux_n.1.2 release to be successfully downloaded?
Steps to Reproduce

*

*Create an empty repo with nothing other than:

*

*a workflow file that includes the download-a-release-linux job shown above, and

*a main.py file with a simple print("Hello World") command to represent an app.

*Create a release using the API as follows, which can be done in a preceding job in the same workflow above:
gh api \
  --method POST \
  -H "Accept: application/vnd.github+json" \
  /repos/AccountName/RepoName/releases \
  -f tag_name=$vers \
  -f target_commitish='source-branch-name' \
  -f name=$nameOfRelease \
  -f body="$DESCRIPTION" \
  -F draft=false \
  -F prerelease=false \
  -F generate_release_notes=false

*Get the name of the release, which above we are calling exact_name_of_release_linux_n.1.2

*Run the workflow that contains the download-a-release-linux job using the code above with whatever modifications are required to get it to successfully download the release and list the valid contents of the app that are included in the release.

A: Read the docs that you linked carefully. According to the docs for gh release download, the command takes a git tag name- not a GitHub release name.

gh release download [<tag>] [flags]

"exact_name_of_release_linux_n.1.2" is a GitHub release name- not a release git tag name. _linux_n.1.2 is the git tag name for that release. At the time of this writing, the docs for gh release list don't actually explain what each column of the output table mean. I only knew by reading the source code of the GitHub cli tool. I'll explain later.
Answer

What specifically needs to be changed in the gh release download cli command in the GitHub workflow code below in order for the exact_name_of_release_linux_n.1.2 release to be successfully downloaded?

You need to change your call to gh release download to use the git tag name of the release instead of the name of the GitHub release.
# ...
jobs:
  download-a-release-linux:
    runs-on: ubuntu-latest
    steps:
      - shell: bash
        name: Download a Release
        env:
          VERSION: ${{ inputs.version }}
          GH_TOKEN: ${{ secrets.GITPAT }}
        run: |
          echo "About to list releases"
          repoWithToken="https://"$GH_TOKEN"@github.com/accountName/repoName"
          gh release list --repo $repoWithToken
          echo "About to download release"
          gh release download _linux_n.1.2 --repo $repoWithToken
          echo "About to list contents of directory after download"
          ls -al
# ...

Note (since you commented about this in confusion): the tarball and zipball are not part of the assets list of the release even though they are displayed in the same list as the other actual assets of the release in the GitHub releases UI. If you want to download those, use the --archive argument of the gh release download command.
Also, I don't think you need to use repoWithToken if you are already setting the GH_TOKEN environment variable. You should just be able to use accountName/repoName.
An Exercise in Reading Source Code
Note: This is applicable to the source code of the v2.16.1 release, but future behaviour may change.
If you look at the source code implementing the gh release list command, you'll see that it prints a table where the columns are:

*

*The release name (which defaults to the git tag if no release name was set for the release)

*A "badge" indicating if the release is the latest release, a draft release, or a pre-release

*The git tag of the release (which is what gh release download expects to receive)

*The publish date of the release

If you look at the source code implementing the gh release download command, you'll see that the "release not found" error is returned when FindDraftRelease doesn't find any releases, and tracing calls to FindDraftRelease, that it is called when FetchRelease's attempt to find a release with the given git tag doesn't find any non-draft releases when it makes a GitHub rest api call to get a release by a git tag.
I have opened an issue for discussion with the maintainers of the GitHub cli tool on the topic of the gh release list command's table columns' meanings not being explicitly documented. The issue has been resolved with an update which adds a header row labeling what each column of the output means.


text:
Q: Create an Observable object from a list of Observables I'm still wrapping my head around RxJS and there is this pattern I keep running into and that I would like to find a more elegant way to write.
Implementing the model part of a Model-View-Intent pattern component, I have a function that takes actions as input an returns a single state$ Observable as output.
function model(actions) {
    const firstProperty$ =
    const anotherProperty$ = …

    // Better way to write this?
    const state$ = Rx.Observable.combineLatest(
        firstProperty$, anotherProperty$,
        (firstProperty, anotherProperty) => ({
            firstProperty, anotherProperty
        })
    );
    return state$;
}

So my model method computes a bunch of observables, every one of them emit items that represents a part of the state of my application. That is fine.
But how to I cleanly combine them into a single one observable that emits states, each state being a single object whose keys are the initial observable names?

A: I borrowed this pattern from https://github.com/cyclejs/todomvc-cycle :
function model(initialState$, actions){
  const mod$ = modifications(actions)

  return initialState$
  .concat(mod$)
  .scan( (state, mod) => mod(state))
  .share()
}

function modifications(actions){
  const firstMod$ = actions.anAction$.map(anAction => (
    state => ({ ...state,
      firstProperty: anAction.something
    })

  const secondMod$ = actions.otherAction$.map(otherAction => (
    state => ({ ...state,
      firstProperty: otherAction.something,
      secondProperty: aComputation(otherAction)
    })

  return Rx.Observable.merge([firstMod$, secondMod$ ]).share()
}

In the main function :
const initialState$ = Rx.Observable.from({})
const actions = intent(DOM)
const state$ = model(initialState$, actions).share()

A: Using help from CHadrien, here is a working solution.
const prop1$ = Rx.Observable.of('foo');
const prop2$ = Rx.Observable.of('bar');
const prop3$ = Rx.Observable.of('baz');
const prop4$ = Rx.Observable.of('foobar');

function combineObservables(objectOfObservables) {
  const keys = Object.keys(objectOfObservables);
  const observables = keys.map(key => objectOfObservables[key]);
  const combined$ = Rx.Observable.combineLatest(
    observables, (...values) => {
      var obj = {};
      for (let i = 0 ; i < keys.length ; i++) {
        obj[keys[i]] = values[i];
      }
      return obj;
    }
  );
  return combined$;
}
combineObservables({prop1$, prop2$, prop3$, prop4$}).subscribe(x => console.log(x));

And the result:
[object Object] {
  prop1$: "foo",
  prop2$: "bar",
  prop3$: "baz",
  prop4$: "foobar"
}


text:
Q: Redirect after User Activation I am using BuddyPress 2 registration and activation for three different sites with my own registration form.
To know where the user has registered, I add the user meta key registered_from at registration.
Is there a way to redirect the user after activation to the site where he registered?

A: Paste this code in your bp-custom.php file or, if you prefer, your active theme's functions.php file:

add_action( 'bp_core_activated_user', 'wpse_70289_activated_user_redirect' );

function wpse_70289_activated_user_redirect( $user_id ) {
    $registered_from = get_user_meta( $user_id, 'registered_from', true );
    wp_redirect( $registered_from );
}

I haven't tested this code myself yet, but it should work just fine.
References:

*

*http://codex.wordpress.org/Function_Reference/get_user_meta

*http://codex.wordpress.org/Function_Reference/wp_redirect


text:
Q: Image flickering in Adobe Flex In Flex4, I use an Image control.
After every 10 seconds, i am changing the image programatically using Timer.
But when the image changes, flickering occurs.
Is there any method to prevent this?
Thanks in Advance

A: Without seeing your code, it's hard to recommend a way to stop the flickering.  In any case, one method could be to have two Image components occupying the same space, one visible, one hidden.  When you load the next image, put it into the hidden component and then swap visibility after the new image has loaded.  This is sort of like "double-buffering".  Hope that helps.

A: Try this along with your image Tag, ioError handler helps in identifying what error occurs when image loads, also if there is an error you can easily replace it with another image.
 <mx:Image ioError=""


text:
Q: How to identify ppt and pptx based on file header How do I get the byte array for PPT and PPTX file types?
I'm currently validating the following:
private static readonly byte[] BMP = { 66, 77 };
private static readonly byte[] DOC = { 208, 207, 17, 224, 161, 177, 26, 225 };
private static readonly byte[] JPG = { 255, 216, 255 };
private static readonly byte[] PDF = { 37, 80, 68, 70, 45, 49, 46 };
private static readonly byte[] PNG = { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 };

But these byte arrays were easy to find online.


text:
Q: how to group by in mongoose Let's say I have a Collection with a field name and only "Sally" and "Bob" names exist. I want to group my results by this value. I'm currently getting my results and then using underscore to perform the group. But I should be able to do this with an aggregate.
The following is my code
  const names = ['Bob', 'Sally'];
  const docs = Collection.find({name: { $in: names}}, { fields: { name:1, age:1}, sort: { name:-1 } }).fetch();

  //How can I do this part in the query above
  const { Bob, Sally } = _.groupBy(docs, "name");

A: You can try,

*

*$match your condition

*$group by name and make array called fields and push name and age

*$sort by _id means name

*$replaceWith to replace object in root, $arrayToObject convert k, v format to object

const names = ['Bob', 'Sally'];
const docs = Collection.aggregate([
  { $match: { name: { $in: names } } },
  {
    $group: {
      "_id": "$name",
      fields: {
        $push: {
          name: "$name",
          age: "$age"
        }
      }
    }
  },
  { $sort: { _id: -1 } },
  {
    $replaceWith: {
      $arrayToObject: [
        [
          {
            k: "$_id",
            v: "$fields"
          }
        ]
      ]
    }
  }
])

Playground

A: You can do something like this :
db.collection.aggregate([
  {
    $match: {
      name: {
        $in: names
      }
    }
  },
  {
    $group: {
      "_id": "$name",
      age: {
        $first: "$age"
      }
    }
  },
  {
    $sort: {
      name: -1
    }
  }
])

Try it here : MongoPlayground


text:
Q: Control the door release function of an apartment intercom I have a Aiphone GT-1C system and am trying to see if its possible to trigger the door release feature for my apartments intercom system.

The pinout reads:
    IN  | OUT | IN | OUT |
    ----+-----+----+-----+
    R R |R R  |B B |B B  |
    1 2 |1 2  |1 2 |1 2  |
   23.4v|23.4v| 0v | 0v  |

I measured the In and Out for R1/2 at 23.4v and 0v for In and out of B1/2. When I press the door release button (when its off not being called) all the pins go to 23.4v high. This leads me to believe that they are sending data over wire. I do have an oscilloscope that I could use but I feel like if it got to that point it would be over my head.
I emailed tech support asking if they had a dedicated door release pin and they responded with this:

An option switch dry contact closure can be used when connecting a
  dedicated strike circuit to the gray and black wires of the 6-pin
  option cable.
The door release button on the GT-1C triggers the Form C contact built
  into the back of the speaker module of the entrance. The tenant would
  need to press the Option button (the icon looks like a laptop monitor)
  to unlock their own unique door.

I was confused by the response. From what I understand dry contact just means it's volt free meaning its a secondary relay or something. But I don't understand the part about the dedicate strike circuit.
With the information would it be possible to trigger the door release using a some kind of hardware (microcontroller, switch, etc.)

A: The door strike is the bit on the frame that the lock latches into.
https://en.wikipedia.org/wiki/Electric_strike
What I get from this badly worded instruction sheet is that if you want an electric strike, so you can operate the door release remotely you route the power supply to the strike (which must be within the specified parameters) via these two pins. Internally there is a normally open contact activated by the "option" button which will complete your circuit and activate your strike (that is it will release the door).
So you will need to supply an electric strike (if not fitted) and its up to 24V supply, and all the intercom does is activate it when you press "option". So if you don't want to have the "press option" feature, just ignore that and create your own entirely independent circuit with a strike, power supply and switch.

A: It was clear to me.

*

*In low current relays they have to be non-oxidizing and free of big arcs.

*

*Mercury bulb "Wet contacts"  ( bounce free )

*Gold-plated "Dry-contacts"

*

*(always rated < 2A to prevent gold plating damage)

Door Strikers come in both AC and DC

. V . . I

*

*12V 0.44A   or

*24V 0.23A

*(6 watts)

simulate this circuit – Schematic created using CircuitLab


text:
Q: Variadic template not working with an initializer list I created a factory function template:
template <typename M, typename... Args>
std::shared_ptr<M> create(Args... args)
{
    return std::make_shared<M>(args...);
}

And a simple container:
struct Group {
    std::vector<int> vec;
    Group(std::initializer_list<int> il) : vec(il) {}
};

Then I try to create a Group
int main()
{
    auto gr = create<Group>({1, 2, 3});
    return 0;
}

This doesn't compile,
error: no matching function for call to 'create'
    auto gr = create<Group>({1, 2, 3});
candidate function not viable: requires 0 arguments, but 1 was provided
std::shared_ptr<M> create(Args... args)
                   ^

but if I use a temporary variable:
int main(int argc, char *argv[])
{
    std::initializer_list<int> il = {1, 2, 3};
    auto gr = create<Group>(il);
    return 0;
}

it does. Why?
What is the recommended solution for such case?

A: A template parameter cannot be deduced from an initializer list (it's a non-deduced context), but can from an expression of type std::initializer_list<something>. The two are not the same.

[temp.deduct.call]/1 Template argument deduction is done by comparing each function template parameter type (call it P) with the type of the corresponding argument of the call (call it A) as described below. If removing references and cv-qualifiers from P gives std::initializer_list<P'> for some P' and the argument is an initializer list (8.5.4), then deduction is performed instead for each element of the initializer list, taking P' as a function template parameter type and the initializer element as its argument. Otherwise, an initializer list argument causes the parameter to be considered a non-deduced context (14.8.2.5). [ Example:
template<class T> void f(std::initializer_list<T>);
f({1,2,3}); // T deduced to int
f({1,"asdf"}); // error: T deduced to both int and const char*

template<class T> void g(T);
g({1,2,3}); // error: no argument deduced for T

—end example ]

A: From cppreference:

A braced-init-list is not an expression and therefore has no type, e.g. decltype({1,2}) is ill-formed. Having no type implies that template type deduction cannot deduce a type that matches a braced-init-list, so given the declaration template<class T> void f(T); the expression f({1,2,3}) is ill-formed.

There is one exception though: auto a = { 1, 2 }; results in a being a std::initializer_list. But this is only in auto type deducing, not for templates.


text:
Q: Logging in Joomla platform 11 JLog I'm playing with the new Joomla 1.7 system built on the Joomla platform 11-- and all my logging code from earlier versions of Joomla no longer work (they appear to be writing log entries but with improper syntax, so the messages are blank).
Does anyone know the proper syntax for the new version of JLog? Here's my existing code--
$log = &JLog::getInstance('test.log.php');
$log->addEntry(array('COMMENT' => 'A test Logging message'));

This creates the log file, but the actual log entry looks like this:
#<?php die('Forbidden.'); ?>
#Date: 2011-08-08 16:59:42 UTC
#Software: Joomla Platform 11.1 Stable+Modified [ Ember ] 01-Jun-2011 06:00 GMT

#Fields: date   time    priority    clientip    category    message
2011-08-08  16:59:42    INFO    127.0.0.1   -

I've searched the Joomla docs and the web and found no examples of how to use this class.
Thanks!

A: Yes, the logging changed a bit indeed in Joomla 1.7:
// Include the JLog class.
jimport('joomla.log.log');

// Add the logger.
JLog::addLogger(
     // Pass an array of configuration options
    array(
            // Set the name of the log file
            'text_file' => 'test.log.php',
            // (optional) you can change the directory
            'text_file_path' => 'somewhere/logs'
     )
);

// start logging...
JLog::add('Starting to log');

A: @hbit thx a lot..I fixed like this and it work..
but I created as function..
<?php
function logWrite($level, $values, $file='%s.php',$path='',$showOnTop=0,
   $option='',$component=''){
/****
jlog Joomla 3.4
created by:gundambison (2015.04.26).
THX: hbit@stackoverflow
****/
    jimport('joomla.log.log');
    $level=strtoupper($level);
//You can change this com_name
    $component= $component==''? 'com_gundambison': $component;
    $date= date("Ymd");
    $filename= sprintf($file, $date);
    $format= $option=='' ?"{TIME}\t{CLIENTIP}\t{CATEGORY}\t{MESSAGE}": $option;

// create options and text
    $txt = is_array($values)? json_encode($values): $values;
    $options = array('text_file' => $filename,'text_entry_format'=>$format );
    $options['text_file_path']=$path==''?'logs': $path;
    JLog::addLogger ($options);
/*
if you want the error to show in your page.
*/
    if($showOnTop==1){
        JLog::add("$level\t$txt");
    }else{
        JLog::add("$level\t$txt",$level,$component);
    }
}
/****
result:
  14:28:39  ::1 com_whatever    ALERT   task:error
****/
?>

Hope this Help


text:
Q: Unable to implement security to SSAS Cube when connecting through Excel Users connects to Cube data through Excel. but they need role level security.
So, we are hiding a measure for a role. When connecting to Excel,It is throwing error.
Here is the way that we are hiding a measure to a role.
BIDS -> Solution Explorer -> Roles -> Dimension data ->Select MeasuresDimension--> Unselecting the measures which should not be displayed.I am unselecting [mymeasure].
And I am connecting to the cube data through Excel. But I am getting error " The member [mymeasure] was not found in the cube when the String [measures].[mymeasure], was parsed"
Please help.

A: The errors are unfortunately prompted in Excel because of calculated members exists that uses measures that the user has no authorization on.
To 'catch' the error you will have to adapt your MDX script
Check Jorg Klein's blog, he knows how to solve this stuff:
http://sqlblog.com/blogs/jorg_klein/archive/2013/02/18/implement-ssas-md-cell-security-using-dimension-security-with-blazing-performance.aspx
Solution and examples are listed there.


text:
Q: Printing something on the basis of a condition in a column of a df I have a df as below and need to print a string on the basis of the condition as follows:
       Name Age     University  City
0      Ankit    23          BHU     Pune
1     Aishwarya 21          BHU     Pune
2     Shaurya   22          BHU     Pune
3     Shivangi  21          BHU     Pune

for i in df:
    if df['Age']=='BHU'and df['City']=='Pune':
        print('correct')
    else:
        print('error')

gives ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: I think you are comparing University and City name. If University is "BHU" and city is "Pune" then you want to print("correct") otherwise you want to print error. If my thought is right then you should follow this code below.
for i in range(0,len(df)):
    if df.loc[i, "University"] == "BHU" and df.loc[i, "City"] == "Pune":
        print("correct")
        break
    else:
        print("error")

A: You can looping by array created in numpy.where:
arr = np.where((df['Age']=='BHU') & (df['City']=='Pune'), 'correct', 'error')

for val in arr:
     print(val)

Your solution is possible use:
for row in df.itertuples():
    if (row['Age']=='BHU') and (row['City']=='Pune'):
        print('correct')
    else:
        print('error')


text:
Q: difference of two arrays javascript I want to compare two arrays and return a new array with any items only found in one of the two given arrays, but not both
This is my code :

function diffArray(arr1, arr2) {
    var newArr = [];
    for(var i =0; i <arr1.length ; i++){

            if(arr2.indexOf(arr1[i]) < 0){
                newArr.push(arr1[i]);
              }
            }
    for(var j =0; j <arr2.length ; j++){

                if(newArr.includes(arr2[i]) !== true){
                    if(arr1.indexOf(arr2[i])<0){
                    newArr.push(arr2[i])
                  }
                }
            }

    return newArr;
  }

its not working right. newArr after first for loop is empty , i cant get where i am wrong .. thank you in advance for any idea

A: This works embed it into function

let ad=[1,2,3,4,8,9];
let b=[2,7,8,1];

let k=ad.reduce((o,a)=>{
  if(b.indexOf(a) > -1)
  {
    o.push(a);
  }
  return o;

},[])

console.log(k);


text:
Q: Ubuntu 20.04 Elantech touchpad not working I've recently installed Ubuntu 20.04 on my laptop only to find the touchpad didn't work, it is recognized in xinput and is turned on in settings. Which drivers can I install to make it work?
(HP Pavilion 15 Gaming, Nvidia GeForce GTX 1050, AMD Ryzen 5)
Output of Xinput :
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ ETPS/2 Elantech Touchpad                  id=15   [slave  pointer  (2)]
⎜   ↳ MOSART Semi. 2.4G Keyboard Mouse Consumer Control id=11   [slave  pointer  (2)]
⎜   ↳ MOSART Semi. 2.4G Keyboard Mouse          id=18   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Power Button                              id=8    [slave  keyboard (3)]
    ↳ HP TrueVision HD Camera: HP Tru           id=13   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=14   [slave  keyboard (3)]
    ↳ HP Wireless hotkeys                       id=16   [slave  keyboard (3)]
    ↳ HP WMI hotkeys                            id=17   [slave  keyboard (3)]
    ↳ MOSART Semi. 2.4G Keyboard Mouse          id=9    [slave  keyboard (3)]
    ↳ MOSART Semi. 2.4G Keyboard Mouse System Control   id=10   [slave  keyboard (3)]
    ↳ MOSART Semi. 2.4G Keyboard Mouse Consumer Control id=12   [slave  keyboard (3)]

ssg-004@ssg-004-HP-Pavilion-Gaming-Laptop-15-ec0xxx:~$ xinput list-props 15
Device 'ETPS/2 Elantech Touchpad':
    Device Enabled (148):   1
    Coordinate Transformation Matrix (150): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    libinput Tapping Enabled (303): 1
    libinput Tapping Enabled Default (304): 0
    libinput Tapping Drag Enabled (305):    1
    libinput Tapping Drag Enabled Default (306):    1
    libinput Tapping Drag Lock Enabled (307):   0
    libinput Tapping Drag Lock Enabled Default (308):   0
    libinput Tapping Button Mapping Enabled (309):  1, 0
    libinput Tapping Button Mapping Default (310):  1, 0
    libinput Natural Scrolling Enabled (285):   1
    libinput Natural Scrolling Enabled Default (286):   0
    libinput Disable While Typing Enabled (311):    1
    libinput Disable While Typing Enabled Default (312):    1
    libinput Scroll Methods Available (287):    1, 1, 0
    libinput Scroll Method Enabled (288):   0, 1, 0
    libinput Scroll Method Enabled Default (289):   1, 0, 0
    libinput Click Methods Available (313): 1, 1
    libinput Click Method Enabled (314):    1, 0
    libinput Click Method Enabled Default (315):    1, 0
    libinput Middle Emulation Enabled (292):    0
    libinput Middle Emulation Enabled Default (293):    0
    libinput Accel Speed (294): 0.000000
    libinput Accel Speed Default (295): 0.000000
    libinput Left Handed Enabled (299): 0
    libinput Left Handed Enabled Default (300): 0
    libinput Send Events Modes Available (270): 1, 1
    libinput Send Events Mode Enabled (271):    0, 0
    libinput Send Events Mode Enabled Default (272):    0, 0
    Device Node (273):  "/dev/input/event10"
    Device Product ID (274):    2, 14
    libinput Drag Lock Buttons (301):   <no items>
    libinput Horizontal Scroll Enabled (302):   1

A: Had the same issue on my HP Pavillion running Ubuntu 20.04. I spent two days looking for a solution.
The first thing that worked for me was editing the /etc/default/grub file:
GRUB_CMDLINE_LIN UX_DEFAULT="quiet splash psmouse.proto=bare"
GRUB_CMDLINE_LINUX="i8042.reset i8042.nomux i8042.nopnp i8042.noloop"

The link below has the full procedure:
https://medium.com/@barcelos.ds/how-to-fix-touchpad-mouse-not-working-in-linux-operating-systems-b328bb43b4c5
After making those changes I could not use two-finger scrolling. To get that working I had to update the Linux kernel to version 5.10
The link below is what I followed to update the kernel:
http://ubuntuhandbook.org/index.php/2020/12/install-linux-kernel-5-10-ubuntu-linux-mint/
Hope this helps.

A: This is a kind of a bug in Ubuntu 20.04 where xorg-synaptics is in use when it shouldn't be.
This can be fixed by
sudo apt remove xserver-xorg-input-synaptics

The touchpad should start working with libinput after a logoff or reboot.

A: I had this problem. In the end what fixed it was upgrading the linux kernel through the HWE:
sudo apt install linux-generic-hwe-20.04
This brings in newer device drivers from the linux 5.11 kernel.

A: I found this post that said to go into the boot menu and select the linux boot and it worked for me. However, you have to do this every time you reboot.

A: I've been using Ubuntu since 08.04 but don't consider myself 'knowledgable' on the subject. I have noted however that I suffered the same issues with my new HP laptop when I replaced Windows10 with Ubuntu 20.04. No touchpad detected ergo just no touchpad! I recently decided to dual boot Win10 & Ubuntu but the problem persisted until today. I selected UEFI Firmware Setup from the Grub menu. This took me to Windows Boot Manager where I selected Ubuntu.This took me back to the GRUB menu where I selected Ubuntu. Hey Presto, fully functioning Touchpad with one and two finger scrolling etc. Hope this helps someone else with similar setup to gain functionality. My motive was simply to get back to Ubuntu as I tired of Windows very quickly and just wanted to come 'home'.


text:
Q: Can I use set builder notation to define indicies of a matrix? If I have two sets $A = \{a_1,a_2,\dots,a_n\}$ and $B = \{b_1,b_2,\dots,b_m\}$, can I define a matrix in the following way?
$C = \{c_{ij} \mid (i,j) \in A \times B\}$
or do the $i$ and $j$ refer to the values of $a_1,a_2$, etc - and not their indices?

A: As you say, $(i,j)\in A \times B$ refers to the elements, not to the indices, sets have no notion of indices. So if you want to be really strict and rigorous with your notation, you have to use ordered sets $A=\langle a_1, a_2, ... \rangle$ and $B=\langle b_1, b_2, ... \rangle$ (or some kind of similar construction). However, what does $c_{ij}$ means here? If you already have a way of specifying $c_{ij}$, then using $A$ and $B$ is not necessary.

A: It is indeed reasonable to use arbitrary sets as the index sets for matrices, rather than specifically sets of the form $\{ 1, 2, \ldots, n \}$.
Note that even infinite sets are reasonable here, giving you infinite dimensional matrices! This introduces some extra complications that you have to deal with; e.g. matrix multiplication would involve an infinite sum, so if you want to multiply such matrices you have to impose some restrictions.
Also note that the empty set is reasonable here too. This also introduces complications, but these are mainly problems of being unfamiliar with how linear algebra degenerates, rather than technical obstructions. For example, every $0 \times 0$ matrix is both a zero matrix and an identity matrix, and the choice of index sets need to be included in the definition of the matrix, so that you can tell the difference between $0\times 0$ and $0 \times 1$ matrices.


text:
Q: SwipeRefershLayout is not working in Android SwipeRefershLayout is not working in Android.
This is my XML code:
//other code
.....

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/swipeRefreshLayout"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/searchCardView">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="8dp"
        tools:listitem="@layout/room_dashboard_sample"/>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
.....
//other codes

This is My MainActivity:
        modelList = new ArrayList<>();
    dashboardAdapter = new DashboardAdapter(this, modelList);
    binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
    binding.recyclerView.setAdapter(dashboardAdapter);

    modelList.clear();
    firestore.collection("Rooms").orderBy("timestamp", Query.Direction.DESCENDING).get().addOnSuccessListener(queryDocumentSnapshots -> {
        List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
        for (DocumentSnapshot d : list) {
            DashboardModel obj = d.toObject(DashboardModel.class);
            modelList.add(obj);
        }
        dashboardAdapter.notifyDataSetChanged();
    }).addOnFailureListener(e -> Timber.d("onFailure: %s", e.getMessage()));

    //please give attension in this below code!
    binding.swipeRefreshLayout.setOnRefreshListener(() -> {
        dashboardAdapter.notifyDataSetChanged();
        binding.swipeRefreshLayout.setRefreshing(false);
    });

A: It is better you create a specific method to call the database. You can wrap them up inside a method.
private void getRoomsList(){
    firestore.collection("Rooms").orderBy("timestamp", Query.Direction.DESCENDING).get().addOnSuccessListener(queryDocumentSnapshots -> {
        List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
        for (DocumentSnapshot d : list) {
            DashboardModel obj = d.toObject(DashboardModel.class);
            modelList.add(obj);
        }
        dashboardAdapter.notifyDataSetChanged();
    }).addOnFailureListener(e -> Timber.d("onFailure: %s", e.getMessage()));
}

Then, you just need to call it inside onCreate and swipeRefreshLayout.
binding.swipeRefreshLayout.setOnRefreshListener(() -> {
    getRoomList();
    binding.swipeRefreshLayout.setRefreshing(false);
});

For better approach, you can call the setRefreshing after the notifyDataSetChanged and remove it from below getRoomList like below:
//another code...
dashboardAdapter.notifyDataSetChanged();
binding.swipeRefreshLayout.setRefreshing(false); //place it here

While at the swipeRefreshLayout.
binding.swipeRefreshLayout.setOnRefreshListener(() -> {
    getRoomList();
});


text:
Q: Load div on the page one by one

        WISHINDIA
        SHOUTIT
        SNAKE
        TESTING
        TESTING
        TESTING
        TESTING

I'm trying to load div one after another with some delay but unable to do so please help to do this

A: First of all, you would need to fix the syntax errors around the anonymous function passed to the .each function. Basically your closing ) bracket for .each should come after the closing } of the anonymous function passed to it.
Then, instead of iterating on #clr, you should be iterating over #clr > a - meaning on the anchor tags rather than the div element.
Also you don't have to specify the selector inside the .each function. You can instead refer to the elements using $(this).
Finally, you can either refer to the index of element inside .each as id or i. In the snippet below I have used id.

  WISHINDIA
  SHOUTIT
  SNAKE
  TESTING
  TESTING
  TESTING
  TESTING

A: Try to use callback function:
$(document).ready(function(){
    $('[id^="clr"]').each(function(i) {
        let $this = $(this);
        $this.fadeOut(0, function () {
            setTimeout(function() {
                $this.fadeIn(1850);
            }, 1000 * i);
        });
    )};
});