text:
Q: (partial) template specialization for bool I'm struggling to understand how template specialization for bool works for this slide taken from cppcon 2017
Short question: why (first) primary template handles odd N cases when its signature is
<..., bool = (N % 2 == 0)> ?
Trying to understand myself I simplified down to
#include<iostream>
template<unsigned N, bool =(N%2==0)> struct S { void operator()(){ std::cout << "A\n"; } };
template<unsigned N> struct S<N, true> { void operator()(){ std::cout << "B\n"; } };
int main()
{
    S<2>{}();
    S<3>{}();
}

which prints B A, showings same (yet mysterious to me) behavior as linked talk, but if I change  template specialization to
template<unsigned N> struct S<N, false> { void operator()(){ std::cout << "B\n"; } };
                                 -----

it prints A B: how compiler chooses between primary S and its specialization?

A: The compiler always prefers the specialization over the generalization and thus will always pick it if it can.
The struct S has a partial template specialization that will only be picked if the second template parameter evaluates to true, so let's see how that works:
S<2>{}();

Here the template parameter N is 2 and so 2 % 2 == 0 holds true. Which means the specialization will be picked over the generalized S because the specialization requires the second parameter to be true and B is printed.
This isn't the case for S<3>{}(); because 3 % 2 == 0 holds false, and thus the generalized case is used, giving you A.
If you swap it around and make the specialization only accept false for N % 2 == 0 then the results will be the exact opposite, 2 % 2 == 0 still holds true but the specialization only accepts false so it's not picked, 3 % 2 == 0 holds false and thus it will be picked, resulting in A B.

A: It's specialization; the compiler choose the most specialized version available.
Ignore for a moment the default value for bool (that transform S<2> in S<2, true> and S<3> in S<3, false>); you have
template <unsigned N, bool>
struct S
 { /* something */};

template <unsigned N>
struct S<N, true>
 { /* something */};

The first one is neutral regarding the second (the bool one) template parameter; so matches both S<2, true> and S<3, false>.
The second one require that the second template parameter is true, so matches only S<2, true>. And is more specialized than the first one because every match for the second template is also a match for the first one but there are matches for the first one that aren't matches for the second one (S<3, false>, by example).
For S<3, false> the compiler find only a template that matches (the first one) so choose the first one.
For S<2, true> the compiler find both templates that match and coose (rule of C++) the most specialized, that is the second one.
When you change the true in false you have that S<3, false> matches both version, so the second one is choosed, and S<2, true> matches only the first one.


text:
Q: Why do I get different sort order of the same query executed in Teradata & Snowflake? I am getting different sort order even if I have added order by clause in both the queries.
Here are queries that I am executing on Teradata & snowflake-
Teradata :
Select column1, column2, column3, column4,column5 From Teradata_Table  Where column1 in (1027837724,1040965189,1046224751) and column2='2021-03-11'
order by column1 ;

Result -->

column1
column2
column3
column4
column5

1027837724
3/11/2021
0
42.66
5942

1027837724
3/11/2021
12052.34
2.99
5735

1040965189
3/11/2021
5336.72
10.87
5944

1040965189
3/11/2021
0
311.16
5942

1046224751
3/11/2021
0
14.99
5735

1046224751
3/11/2021
0
2.99
5735

Snowflake :
Select column1, column2, column3, column4,column5 From Snowflake_Tablename  Where column1 in (1027837724,1040965189,1046224751) and column2='2021-03-11'
order by column 1

Result -->

column1
column2
column3
column4
column5

1027837724
3/11/2021
12052.34
2.99
5735

1027837724
3/11/2021
0
42.66
5942

1040965189
3/11/2021
5336.72
10.87
5944

1040965189
3/11/2021
0
311.16
5942

1046224751
3/11/2021
0
14.99
5735

1046224751
3/11/2021
0
2.99
5735

A: As the comments say:

*

*You are only sorting by one column, and the order of the rows ordered by that column is the same regardless of database.

*But you are not asking the database to sort by any other column, so rows that have the same column1 can be presented in any arbitrary order.

If you want to make the order consistent, you should ORDER BY column1, column2, column3, etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: In VSTS, how can I set default backlog columns? In our project, we've deemed certain fields pointless while adding others that have more value to us, and unfortunately some of the default columns include fields that have no value to us.
Per documentation, column options can only be changed by the user... I'm hoping there's another way, because we are planning to onboard ~75 people, many of which are non-technical and have never used VSTS before.
Can I change the default column options in the backlog?
Or is there a way I can automate it for each user? The REST API seems to only allow reads.

A: I cannot find a way to set default backlog columns in the template.
However, based on my test, the REST API works to update the column options for a specific backlog.
POST https://your-account.visualstudio.com/_api/_webSettings/setString?__v=5


text:
Q: Rectangular to polar conversion angle error I am trying to determine the polar form of the following rectangular vector:
-105 + 140j

The polar form is $\sqrt(-105)^2+140^2$ = 175 and the angle is determined by $\arctan(\frac{140}{-105}) = -53.13$
The answer provided gives an angle of $\theta=126.87$, which is 180 degrees later. Also this website gives the 126.87 degrees.
Why is that and which is correct?

A: Here is a visualization:
 (Large Version)
So $-53.13$ is not a correct answer, it would run clockwise, assigning a point in the $4$-th quadrant.
It is a problem with how to pick $\tan^{-1}$.
 (Large Version)
The $\color{green}{\text{dark green curve}}$ is the graph of $y = \tan(x)$. If one inverts it, by mirroring it along $y = x$, you would get a multivalued relation, but a function must have at most one value per argument.
So one limits the inverse to a strip parallel to the $x$-axis of width $\pi$.
The $\color{red}{\text{red curve}}$ is the graph of the $\arctan$ function your calculator offered, and is offered by much of the available mathematical software.
The $\color{purple}{\text{purple curve}}$ is the graph of the inverse function you would need, which is $y = \arctan(x) + \pi$
Note that there is nothing wrong with your calculator, instead of offering many versions of $\tan^{-1}$ the user is expected to do the shift himself.


text:
Q: read data and send data to a database I'm trying to use an android app with my data base. I know how to retrieve and send information to the data base, but I don't know how to do it in Android.
When I type the URL, lets say "http://01.01.001.001/api/example" in the browser, I can see this:
<ArrayOfArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<ArrayOfstring>
<string>52</string>
<string>Pregunta español prueba 52</string>
<string>NO</string>
<string>SI</string>
<string>NO</string>
<string/>
<string/>
<string/>
<string/>
<string/>
<string/>
<string/>
<string i:nil="true"/>
</ArrayOfstring>
<ArrayOfstring>
<string>53</string>
<string>Pregunta 53 NIVEL 2</string>
<string>NO</string>
<string>53 mucho</string>
<string>53 Algo</string>
<string>53 Nada</string>
<string>53 Poco</string>
<string>53 Fin</string>
<string i:nil="true"/>
<string i:nil="true"/>
<string i:nil="true"/>
<string i:nil="true"/>
<string i:nil="true"/>
</ArrayOfstring>

which is a bunch of strings. How can I place each string in a variable in android? If I try
public static InputStream getInputStreamFromUrl(String url) {
    InputStream content = null;
    try {
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpclient = new DefaultHttpClient();
        // Execute HTTP Get Request
        HttpResponse response = httpclient.execute(httpGet);
        content = response.getEntity().getContent();
    } catch (Exception e) {
        //handle the exception !
    }
    return content;

}

The content is always null when using the URL. Once the content is not null, how can I translate it to a set of strings?
Thanks a lot!


text:
Q: How do I make pass and fail count work in c++? I'm working on this function for one of my classes and my pass count works just fine, however, my fail count ALWAYS prints out 12. I've been reading my code top to bottom and just can't seem to find the problem.
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

string passAndFailCount(string grades){
  int pass_count;
  int fail_count;
  istringstream myStream(grades);
  string grade;
  while(myStream>>grade){
    int i_grade=stoi(grade);
    if (i_grade>=55){
      ++pass_count;
    }
    else{
      ++fail_count;
    }
  }
  cout<<"Pass: "<<pass_count<<endl<<"Fail: "<<fail_count<<endl;
}

int main()
{
  string grades;
  getline(cin, grades);
  passAndFailCount(grades);
}

A: Your problem are uninitialized variables.
int pass_count = 0;
int fail_count = 0;

and you're set.
For an explanation. Non-global variables (which automatically get initialized to 'default' (0) as per the standard), automatic and dynamic variables (like the one you are using), assume the value of 'whatever was in memory at the time of allocating the variable'.
Memory is never empty, there's always 'something' written in there.
So the memory of your fail_count variable just 'happened to be' 12 during allocation, which is why you start with that value. This value can be anything within scope.
By explicitly assigning a variable, you 'initialize' the variable, putting it into a defined state (0) and your program should start working as expected.


text:
Q: Replace a structure with a different one and preserve some values I would like to transfer input to output in bash. I tried to use sed but it didn't work - I have it probably wrong. So far I have this (just to try if I can extract id) but it does not work:
sed 's;id="([a-zA-Z:]+)";\\1;p' input

Input
<mediaobject>
    <imageobject id="fig:deployment">

Application deployment

        <imagedata fileref="images/deployment.png" width="90%" />
    </imageobject>
</mediaobject>

Output

A: awk is available virtually everywhere that bash is installed and can avoid some of the pitfalls you might encounter with sed (for example if the attributes in the xml are not consistently ordered).
awk '
    ## set a variable to mark that we are in a mediaobject block
    $1=="<mediaobject>" { object=1 }

    ## mark that we have exited the object block
    $1=="</mediaobject>" { object=0 }

    ## if we are in an mediaobject block and we find an imageblock
    $1=="<imageobject" && object==1 {
        iobject=1                          ## record that we are in an imageblock
        id = substr($2, 5, length($2) - 6) ## this is unnecessary for output
    }

    ## if we have a line with image data
    $1~/<imagedata/ && iobject==1 {
        fileref=substr($2,9,length($2)-8)  ## the path, including the quotations
        width=$3                           ## the width
    }

    ## if we have a caption line
    $1~/
/ && iobject==1 {
        gsub("(</?caption>|^ *| *$)", "")  ## remove xml and leading/trailing whitespace
        caption=$0                         ## record the modified line as the caption
    }

    ## when we arrive at the end of an imageblock
    $1=="</imageobject>" && object==1 {
        iobject=0                                                            ## record it
        printf("\n", fileref, width, caption)  ## print record
    }

' input

Although as I mentioned, this code should work equally well no matter how the attributes are orded, it will fail if the attributes on the line change order (which is less likely). If you encounter that problem you can do something like:
## use match to find the beginning of the attribute
## use a nested substr() to pull only the value of fileref (with quotations)
fileref = substr(substr($0, match($0,/fileref=[a-z\/"]+/),RLENGTH),9))

A: Using xsh:
open 1.xml ;
rename img mediaobject ;
mv img/imageobject/@id into img ;
set img/@title img/imageobject/caption ;
set img/@src img/imageobject/imagedata/@fileref ;
mv img/imageobject/imagedata/@width into img ;
rm (img/* | img/text()) ;

A: With sed:
 sed -n '\!<mediaobject>!{
  n;
  s/ *[^ ]* \(id="[^"]*"\).*/\1/;
  h; n;
  s/ *[^>]*>\([^<]*\).*/title="\1"/;
  H; n;
  s/ *<[^ ]* *fileref=\("[^"]*"\) *\(width="[^"]*"\).*/src=\1 \2/;
  H; n;
  x;
  s/\n/ /g;
  s/^//;
  p
 }' input


text:
Q: Do I need an Rc type for storing a pointer to a Rust struct inside of it's member C struct I would like to store the pointer to a rust struct inside of it's member C struct. Is it required that the struct be enclosed in a Rc rather than a Box?
The reason I'm asking is because although there is shared ownership here, the pointer is only ever accessed from within unsafe member functions of the Rust struct and the C struct's lifetime is tied to that of the enclosing Rust struct.
Here's an example ->
// C struct with constructor/destructor
struct c_foo {
    void*   internal; // pointer to rust `struct`
    /* ... */
};

struct c_foo* c_foo_new();
void c_foo_free(struct c_foo* foo);

// FFI struct generated by bindgen
#[repr(C)]
#[derive(Debug, Copy)]
pub struct Foo {
    pub internal: *mut libc::c_void, // pointer to rust `struct`
    /* ... */
}

// Rust struct that wraps the FFI struct
struct Bar {
    ptr: *mut Foo, // private
    /* ... */
}

impl Bar {
    fn new() -> Box<Bar> {
        unsafe {
            let mut bar = Box::new(Bar { ptr: c_foo_new() });
            let bar_ptr: *mut ffi::c_void = &mut bar as *mut _ as *mut ffi::c_void;
            (*bar.ptr).internal = bar_ptr;
            bar
        }
    }
}

impl Drop for Bar {
    fn drop(&mut self) {
        unsafe {
            c_foo_free((*bar.ptr).internal);
        }
    }
}

So there's a C struct c_foo with a void * that stores a reference to the Rust struct Bar. Foo is just the bindgen generated Rust wrapper for c_foo.
Do I need a Box or Rc in the Bar::new() function?
To clarify, there is no shared ownership on the Rust side. There is shared ownership b/w the Rust and C side so I guess there is no benefit in using a Rc type.

A: E_net4 is renamed all the time's comment answers my question -

use Rc only if you need shared ownership in Rust code. Since C does not retain the semantics of this pointer type, C code needs to handle boundaries manually regardless.


text:
Q: Regex - Include up to a certain character and exclude occurences after Want to include the below:
com/signup?product=exampleproduct_5

com/signup?product=exampleproduct_10

com/signup?product=exampleproduct_20

etc., but exclude the below format:
com/signup?product=exampleproduct_5&opc=50cf4090b21efc35b211990818a33db210396d80

com/signup?product=exampleproduct_10&opc=50cf4090b21efc35b211990818a33db210396d80

com/signup?product=exampleproduct_20&opc=50cf4090b21efc35b211990818a33db210396d80

etc.
Tried the below but didn't obviously doesn't work hence being here!
.*/signup\?product=payroll__(.*)&$

Using the "&" following the two numbers is how I think I should differentiate between them both. For example do not include if it has an "&" after the two numbers.
Appreciate all the advice and help as I've spent hours trying and getting nowhere due to my limited knowledge.

A: If you want to match only strings that don't have the & and other arguments, then:
.*/signup\?product=payroll__([^&]*)$

If you don't want to exclude cases where there are more arguments, but want to match only the part before the & when that is the case, then remove the ending $ anchor:
.*/signup\?product=payroll__([^&]*)


text:
Q: How to build a zoomable choropleth map with insets to handle discrete data in d3.v5? Very new to D3 and coming from R but looking to develop some interactive choropleth maps.
I'm wanting to develop this zoomable choropleth: https://bl.ocks.org/cmgiven/d39ec773c4f063a463137748097ff52f
into something like this V5 choropleth with easily attachable data: https://bl.ocks.org/denisemauldin/3436a3ae06f73a492228059a515821fe
I can mainipulate the V5 choropleth fairly easily, still figuring out how to adjust continuous scale to a discrete scale but I don't really know how to build the zoomable svg in V5.

A: I think in your question you are asking about continuous scale, here is a code snippet for continuous scaling for an zoomable choropleth, What is just apply the same mechanism in this bl.ocks.org just wrap everything in <g> group tag and apply the zoom on this <g> tag:
const zoom = d3.zoom()
  .scaleExtent([1, 8])
  .on('zoom', zoomed);

svg.call(zoom);

function zoomed() {
  zoomG.selectAll('path') // To prevent stroke width from scaling
    .attr('transform', d3.event.transform);
}

var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

var unemployment = d3.map();
var stateNames = d3.map();

var path = d3.geoPath();

var x = d3.scaleLinear()
    .domain([1, 10])
    .rangeRound([600, 860]);

var color = d3.scaleThreshold()
    .domain(d3.range(0, 10))
    .range(d3.schemeBlues[9]);

var g = svg.append("g")
    .attr("class", "key")
    .attr("transform", "translate(0,40)");

g.selectAll("rect")
  .data(color.range().map(function(d) {
      d = color.invertExtent(d);
      if (d[0] == null) d[0] = x.domain()[0];
      if (d[1] == null) d[1] = x.domain()[1];
      return d;
    }))
  .enter().append("rect")
    .attr("height", 8)
    .attr("x", function(d) { return x(d[0]); })
    .attr("width", function(d) { return x(d[1]) - x(d[0]); })
    .attr("fill", function(d) { return color(d[0]); });

g.append("text")
    .attr("class", "caption")
    .attr("x", x.range()[0])
    .attr("y", -6)
    .attr("fill", "#000")
    .attr("text-anchor", "start")
    .attr("font-weight", "bold")
    .text("Unemployment rate");

g.call(d3.axisBottom(x)
    .tickSize(13)
    .tickFormat(function(x, i) { return i ? x : x + "%"; })
    .tickValues(color.domain()))
  .select(".domain")
    .remove();

var promises = [
  d3.json("https://d3js.org/us-10m.v1.json"),
  d3.tsv("https://gist.githubusercontent.com/denisemauldin/3436a3ae06f73a492228059a515821fe/raw/954210175a18c646eb751d59e04d5a4814fe3b03/us-state-names.tsv", function(d) {
    stateNames.set(d.id, d.name)
  }),
  d3.tsv("https://gist.githubusercontent.com/denisemauldin/3436a3ae06f73a492228059a515821fe/raw/954210175a18c646eb751d59e04d5a4814fe3b03/map.tsv", function(d) {
    unemployment.set(d.name, +d.value);
  })
]

Promise.all(promises).then(ready)

function ready([us]) {

  let zoomG = svg.append("g");

    zoomG.append("g")
      .attr("class", "counties")
    .selectAll("path")
    .data(topojson.feature(us, us.objects.states).features)
    .enter().append("path")
      .attr("fill", function(d) {
          var sn = stateNames.get(d.id)
          d.rate = unemployment.get(stateNames.get(d.id)) || 0
          var col =  color(d.rate);
          if (col) {
            return col
          } else {
            return '#ffffff'
          }
      })
      .attr("d", path)
    .append("title")
      .text(function(d) {
       return d.rate + "%"; });

    zoomG.append("path")
      .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
      .attr("class", "states")
      .attr("d", path);

    const zoom = d3.zoom()
      .scaleExtent([1, 8])
      .on('zoom', zoomed);

    svg.call(zoom);

    function zoomed() {
      zoomG.selectAll('path') // To prevent stroke width from scaling
        .attr('transform', d3.event.transform);
    }
}
.counties {
  fill: none;
}

.states {
  fill: none;
  stroke: #fff;
  stroke-linejoin: round;
}
<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>


text:
Q: Geometric Picture of z'(x, y(x)) When using the multivariable chain rule to compute $dz/dt$ of something with the form $z = f(x(t), y(t))$, the geometry involves moving from a number line ($t$) to a plane ($x$, $y$) to a new number line ($z$).  The equation $z = f(x(t), y(t))$ itself can be viewed as a progression of position vectors, or perhaps points to avoid later confusion, from the $t$ line to the $xy$ plane, to the $z$ line.  These are shown as red points below.  Similarly, $dz/dt$ can be viewed as a progression of tiny vectors stemming from these points, shown as relatively large purple arrows, but with the understanding that they're actually arbitrarily small.  The dependencies are shown in the tree structure on the right.

How does this geometric picture change in the alternative case of computing $dz/dx$ of $z = f(x, y(x))$, the following tree structure?

One bizarre facet of this latter case is that its formula, $dz/dx = ∂z/∂x + (∂z/∂y)(dy/dx)$ reveals in clear terms that $dz/dx$ and $∂z/∂x$ aren't the same thing; the total change in $z$ with respect to $x$ isn't the same as the partial change in $z$ with respect to $x$.
My hypothesis is that the axis of the intermediate $xy$ plane in this case is replaced by something other than an orthogonal axis.  The English clause "y is a function of x" or "y depends on x" sounds a lot like "y is influenced by x" or "y is partially determined by x," which aren't too unlike "a component of y points in the x direction."  Consider a plane starting with standard basis vectors $î$ and $ĵ$ that is then transformed by $\left[\begin{array}{l}1&\sqrt{2}/2\\0&\sqrt{2}/2\end{array}\right]$.  The transformed bases aren't orthogonal to each other anymore.  Viewed in light of our original basis, we could say that a component of $y$ now points in the $x$ direction, which is very reminiscent of our multivariable calculus situation.  This also shows promise for an analogy to the inequality of $dz/dx$ and $∂z/∂x$, as the basis vector that spans this plane's x-axis wouldn't be the full story of the $x$ components of the purple vectors.  So a red point and purple vector would start on an $x$ number line and move to a $y$ number line, but from $z$'s perspective, its input wouldn't (in general) look like a Cartesian $xy$ plane, but a modified $xy$ plane, where the x-axis remains in place, but the y-axis is rotated, sheered, etc., perhaps even twisted in some non-linear way.  It would stand to reason that iff $y$ is a linear function of $x$, the y-axis would be straight, and tools of linear algebra could be applied to shed new geometric insight into the problem.
Am I on the right track for thinking about the geometric picture of z(x, y(x)) and z'(x, y(x)), and if so, how can this be drawn out in a bit more detail?


text:
Q: Validation is skipped when constraints are only in parent class I am using MOXy as JAXB provider along with Bean Validation.
I'm trying to validate a class where only parent fields are annotated with constraints.
I can see that MOXy is skipping validation for this class, probably it is not looking into the parent class.
Can you advise on how to overcome this?

A: I found a quick workaround. It is about creating dummy constraints which will always pass. Then you can put it on any class. and MOXy will turn on validation.
Dummy constraints:
@Target( {ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PutItWhenYouDoNotHaveConstraintsButParentHas.Validator.class)
@Documented
public @interface  PutItWhenYouDoNotHaveConstraintsButParentHas {

    String message() default "{com.mycompany.constraints.checkcase}";
    Class<? extends Payload>[] payload() default {};
    Class<?>[] groups() default {};
    public static class Validator implements ConstraintValidator<PutItWhenYouDoNotHaveConstraintsButParentHas, Object>{

        @Override
        public void initialize(PutItWhenYouDoNotHaveConstraintsButParentHas constraintAnnotation) {

        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            return true;
        }
    }
}

Example usage:
public class IdoNotHaveConstraints extends ButMyParentHas{

    @PutItWhenYouDoNotHaveConstraintsButParentHas
    public IdoNotHaveConstraints (){

    }
}

A: It's a known issue in 2.6.0. It is fixed in master (2.7.x) and will be backported to 2.6.2, backporting to 2.6.1 is not planned. Unfortunately these builds are not available for public yet. You should wait for 2-3 months.
As a workaround I can suggest moving BV annotations from superclass to all children. And yes, I agree that it's ugly. :(


text:
Q: Count strings in database table I would like to know how to count choosed strings from database table. In one of my column are two strings called "correct" and "wrong". I have everything in array. I want to count how many strings called "correct" I have in column and how many called "wrong". I'm using sqlite.

A: You can try count(*) and a where.. something like:
SELECT Count(*) FROM yourTable WHERE yourColumn = 'wrong';

And another one to count the correct, or maybe you can subtract from the total.. I hope that helped!


text:
Q: I want to display 13.00 rather than 13 now I have 3 textboxes that the user can type in them his degrees and the average will be calculated and displayed in another textbox! I've made the result to show just two fractional digits by calling the Math.Round() Method
This is my code:
double Sum = int.Parse(textBox1.Text) + int.Parse(textBox2.Text) + int.Parse(textBox3.Text);
double Avg =  Sum / 3;
textBox4.Text = Math.Round(Avg, 2).ToString();

My problem is whenever the average is equal to an integer number like 20, I want it to display 20.00

A: Since C# 6.0 you can use string interpolation to format variables into a string (in this case, format the number with two decimal places):
$"{Avg:.00}"

Alternatively, use string#Format:
string.Format("{0:.00}", Avg);

If you don't want to use either of those, you can use the ToString function with this parameter for that as mentioned in the comments:
Avg.ToString("0.00")


text:
Q: finding last value with matching row in excel I want to find out last occurrence of particular value and if it is there apply some formula.
Machine Starttime             Alert
a       10/19/2016 12:16:15   S
a       10/19/2016 12:18:15   E
a       10/19/2016 12:19:20   S
b       10/19/2016 12:21:45   S
b       10/19/2016 12:21:48   S
b       10/19/2016 12:21:55   E
a       10/19/2016 12:23:15   S
a       10/19/2016 12:27:30   E

Machine column will have machine name, Starttime is log time of that particular event and alert can be start of End.
I need output like following:
Machine Starttime   Alert   Difference
a   10/19/2016 12:16:15 S
a   10/19/2016 12:18:15 E   120
a   10/19/2016 12:19:20 S
b   10/19/2016 12:21:45 S
b   10/19/2016 12:21:48 S
b   10/19/2016 12:21:55 E   10
a   10/19/2016 12:23:15 S
a   10/19/2016 12:27:30 E   490

Difference will be populated only in case of E and there is corresponding start event for that machine, if there are more than one start event then pick first one. I just want to understand if it is possible with just excel formula(without macro)? if yes, how?
I already tried it using index function without success
=IF(C3="E",MATCH(A3,A2:$A$2,0),"")

A: Yes it is possible but it is not easy. You have to use an array formula to solve this. The formula would be:
=IF(C2="S","",(B2-MIN(IF($A$2:A2=A2,IF($C$2:C2="S",IF(ROW($A$2:A2)>MAX(IF(ROW($A$2:A2)<ROW(A2),IF($A$2:A2=A2,IF($C$2:C2="E",ROW($A$2:A2))))),$B$2:B2)))))*86400)

First data row is 2, column A has the machine names, column B the log times, column c the "S"/"E". Put the formula in column D in the first data row and push CTRL+SHIFT+ENTER to make it an array formula. You should see {} around the formula now.
Copy the cell (CTRL+C) and paste it into all rows except the row where the formula is already in.
If you need any more help, place a comment.

A: It can be done with some complicated array formula, but a helper formula can make it easier to distinguish the groups. For example in D2:
= ( ABS(N(D1))+($A2<>$A1) ) * IF(C2="S",1,-1)

and the final Index + Match formula next to it in E2 :
=IF($C2="E", ROUND( ($B2 - INDEX($B$2:$B$9, MATCH(ABS($D2),$D$2:$D$9,0) ) )*24*60*60,0),"")

With your sample data, it should result in something like this:
A       B                   C       D       E
-----------------------------------------------------------
Machine Starttime           Alert   Group   Index+Match
a       10/19/2016 12:16    S        1
a       10/19/2016 12:18    E       -1      120
a       10/19/2016 12:19    S        1
b       10/19/2016 12:21    S        2
b       10/19/2016 12:21    S        2
b       10/19/2016 12:21    E       -2      10
a       10/19/2016 12:23    S        3
a       10/19/2016 12:27    E       -3      255


text:
Q: UI Dialog - pageX pageY position I've constructed a data page with many rows of data (over 300 table rows).
In each row I have an image the triggers a small ui dialog containing HTML (a context type menu).
If I click any if the trigger images in the viewport there is no issue.
If I scroll down and click a trigger image the ui is always aligned to the bottom of my page, not the element I clicked.
function showMenu(){
$("#modalMenu").dialog("open");
return false;
}
$(document).ready(function() {
$('#modalMenu').dialog({autoOpen: false,modal: true,height: 200,width: 200});
$('.menu').click(function(e){$('#modalMenu').dialog('option', 'position', [e.pageX,e.pageY]);});
$('.menu').click(function(){showMenu();});
});

  Do Something
  Do Something Else

** This image is in the first cell of every row

A: Figured it out. Needed to capture scrollTop, then deduct from e.pageY.
This accounts for position after scroll.
$('.menu').click(function(e){
  var y=$(window).scrollTop();
  $('#modalMenu').dialog('option', 'position', [e.pageX,(e.pageY-y)]);
  });


text:
Q: How to always load a fresh page in TWebBrowser? I am trying to load a web page into TWebBrowser using Browser.Navigate(URL). However, the browser won't care that the page was updated online so as long I won't restart the program it won't show the new page.
A more concrete example:
If I navigate to a web page that has an visitor counter (as image), the counter will increment. If I navigate away from that page and then I return (without using Back), the counter won't increment. In Firefox, it does increment.
This is what I tried and won't work:
const
  DLCTL_PRAGMA_NO_CACHE = $00004000;

procedure TBrowserFrm.LoadURL(URL: string);
var
  Flag: OleVariant;
begin
  Flag:=DLCTL_PRAGMA_NO_CACHE;
  Browser.Navigate(URL, Flag);
end;

procedure TBrowserFrm.LoadURL(URL: string);
var
Flags: OleVariant;
begin
 Flags := 'navNoHistory, navNoReadFromCache, navNoWriteToCache';
 Browser.navigate2(URL, Flags);
end;

Any idea on how to make the TWebBrowser load the real page?

A: In VCL, TWebBrowser is a wrapper for Internet Explorer, specifically the IWebBrowser2 interface.
DLCTL_PRAGMA_NO_CACHE is NOT a flag you can pass to Navigate2(). Read the documentation:
SHDocVw.TWebBrowser

TWebBrowser wraps the IWebBrowser2 interface from Microsoft's Shell Doc Object and Control Library (SHDOCVW.DLL) to allow you to create a customized Web browsing application or to add Internet, file and network browsing, document viewing, and data downloading capabilities to your applications.

IWebBrowser2::Navigate2 Method

Flags [in] A pointer to a VARIANT of type VT_I4 or VT_I2 that specifies a combination of the values defined by the BrowserNavConstants enumeration.

BrowserNavConstants Enumerated Type
typedef enum BrowserNavConstants {
    navOpenInNewWindow = 0x1,
    navNoHistory = 0x2,
    navNoReadFromCache = 0x4,
    navNoWriteToCache = 0x8,
    navAllowAutosearch = 0x10,
    navBrowserBar = 0x20,
    navHyperlink = 0x40,
    navEnforceRestricted = 0x80,
    navNewWindowsManaged = 0x0100,
    navUntrustedForDownload = 0x0200,
    navTrustedForActiveX = 0x0400,
    navOpenInNewTab = 0x0800,
    navOpenInBackgroundTab = 0x1000,
    navKeepWordWheelText = 0x2000,
    navVirtualTab = 0x4000,
    navBlockRedirectsXDomain = 0x8000,
    navOpenNewForegroundTab = 0x10000
} BrowserNavConstants;

As you can see, DLCTL_PRAGMA_NO_CACHE is not on that list.  It is actually a flag you specify as an output value when implementing a handler for the browser's DISPID_AMBIENT_DLCONTROL property.  Read the MSDN documentation:
WebBrowser Customization | Controlling Download and Execution

The WebBrowser Control gives you control over what it downloads, displays, and executes. To gain this control, you need to implement your host's IDispatch so it handles DISPID_AMBIENT_DLCONTROL. When the WebBrowser Control is instantiated, it will call your IDispatch::Invoke with this ID. Set pvarResult to a combination of following flags, using the bitwise OR operator, to indicate your preferences.
  ...
  •DLCTL_RESYNCHRONIZE and DLCTL_PRAGMA_NO_CACHE: These flags cause cache refreshes. With DLCTL_RESYNCHRONIZE, the server will be asked for update status. Cached files will be used if the server indicates that the cached information is up-to-date. With DLCTL_PRAGMA_NO_CACHE, files will be re-downloaded from the server regardless of the update status of the files.
  ...

So you would have to implement a custom IDispatch object and hook it into IWebBrowser2 in order to use DLCTL_PRAGMA_NO_CACHE correctly.
Alternatively, you might consider switching to TEmbeddedWB, which handles the browser customization for you, and has a DownloadOptions property that accepts DLCTL... flags, including DLCTL_PRAGMA_NO_CACHE.

A: I suppose you have to use 4, not $00004000.
Since I use www.ghisler.com (counter is at bottom) I can use
procedure TForm2.Button2Click(Sender: TObject);
var
  Flags: OLEVariant;

begin
  Flags:=4; //NavNoReadFromCache
  WebBrowser1.Navigate('http://www.ghisler.com/', Flags);
end;

and it works perfectly (Delphi XE7). I see TC main page, click on hyperlink then on Button2 again and counter is new. When I use Navigate(URL) only, counter is still the same.

A: Browser.EnableCaching:=False;
Browser.Navigate;


text:
Q: Implementing DateSlider from codeus.net When I tried to import the project it did not work. There were no project files found. What I did next was tried to build my own app and included the files mentioned here https://github.com/bendemboski/DateSlider but facing some xml errors as the app: not getting recognized. This DateSlider looks cool and if anyone has any idea of how do I implement would be awesome help. Thank You

A: I've used it, and it is slick, but I had to make changes (and I used it when I was first learning, so there might be an easier way, but I haven't had the desire to go back and re-visit it).
1) Copy all the files into your own package (contents of src, res and values to their respective folders).  Put all of the src files into your main package (without all the subdirectories from the zip file).
2) Edit all of the layout and source files to remove references to the old package/app name and replace it with your package.  Basically replace any occurence of com.googlecode.android.widgets.DateSlider with com.yourpackage.name.
An example:
com.googlecode.android.widgets.DateSlider.SliderContainer becomes com.yourpackage.name.SliderContainer and so on.
3) Examine the demo and set up dialog as you desire following examples in demo program.
Here it is in action:


text:
Q: Autoplay Video with Sound I am a beginner in HTML and just want to write a page with a little video and a text.
I want to autoplay the video but with sound. Since it's only possible to autoplay without sound I assume that I need javascript.
This is my code so far
index.html
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="generic.css">
    </head>
    <body>
        <video autoplay="autoplay" loop="" class="myVideo" id="myVideo">
            <source src="vid.mp4" type="video/mp4">
            Your browser does not support HTML5 video.
          </video>
    </body>
</html>

css file:
video {
    position: fixed;
    text-align: center;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

Is it somehow possible or am I forced to use a button to autoplay?

A: Your code is correct, But here are google's poilcy
Chrome's autoplay policies are simple:
Muted autoplay is always allowed.

*

*Autoplay with sound is allowed if:

*User has interacted with the domain (click, tap, etc.).

*On desktop, the user's Media Engagement Index threshold has been
crossed, meaning the user has previously played video with sound. The
user has added the site to their home screen on mobile or installed
the PWA on desktop.
TRY INTREACT WITH SNIPPET BEFORE VIDEO LOADS

video {
    position: fixed;
    text-align: center;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="generic.css">
    </head>
    <body>
        <video autoplay="autoplay" loop="" class="myVideo" id="myVideo">
            <source src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4" type="video/mp4">
            Your browser does not support HTML5 video.
          </video>
    </body>
</html>

A: A hacky trick I've seen people use is add an iframe containing an autoplay material before the element itself thus forcing subsequent elements to have audio. You can check something like it done here.
<iframe src="SOME_EMPTY_VIDEO_WITH_SILENCE_URL" type="video/mp4" allow="autoplay" id="video" style="display:none"></iframe>
<video autoplay>
     <source src="ACTUAL_VIDEO_URL" type="video/mp4">
</video>

Still, like I said, this is a nasty hack.


text:
Q: Transfer Files from Rackspace CloudSite to Cloud Files Just wondering if anyone knows of a prewritten php script to to transfer files from rackspace cloud site to rackspace cloud files.
Rackspace does provide a script to backup files to the cloud but not transfer. (and I only realized that after spending a couple of hours and finally getting the script working).
http://www.rackspace.com/knowledge_center/article/how-to-use-cron-to-backup-cloudsites-to-cloudfiles
I don't know PHP (which is required for Rackspace cron jobs), so if there's a script that would help me with this it would be great.
Thanks.

A: Below is the script I use when I backup to rackspace. It uses the php cloud files master library from racker labs.  I set it up as a simple cron.  Simply replace the emai
php 'path/to/backup.php'

<?

require_once('php-cloudfiles-master/cloudfiles.php');

$server_name = 'YOUR_SERVER_NAME'; //Name of the Current Server
$curr_date_time = date("Y-m-d--H:i:s"); //DON' CHANGE - Date
$curr_day = date("Yd"); //DON' CHANGE - Date
$sites = array("ENTERDATABASES HERE IN ARRAY FORMAT"); //Array of Databases to be Backed up
$site_root = "/var/www/";
$temp_dir = "/bak/mysql/"; //temp directory
$site_temp_dir = "/bak/site/"; //temp directory
$rscfUsername = 'YOUR RACKSPACE USERNAME'; // the username for your rackspace account
$rscfApiKey = 'YOUR RACKSPACE API KEY'; // the api key for your account
$rscfContainer = 'YOUR RACKSPACE CONTAINER'; //rackspace containr
foreach($sites as $site) {

try{

 exec("tar -czpf {$site_temp_dir}{$site}{$curr_date_time}_site.tar.gz {$site_root}{$site}");
 // check if the file is created
 if(file_exists("{$site_temp_dir}{$site}{$curr_date_time}_site.tar.gz")) {

 $auth = new CF_Authentication($rscfUsername, $rscfApiKey);
 $auth->ssl_use_cabundle();
 $auth->authenticate();
 $conn = new CF_Connection($auth);
 $conn->ssl_use_cabundle();

 // I allready created a container with this name otherwise user create_container
 $container = $conn->get_container($rscfContainer);

 // make a unique name with date in it so you know when it was created
 $objectName = $site.$curr_date_time.'.tar.gz';
 $store = $container->create_object($objectName);
 $store->load_from_filename("{$site_temp_dir}{$site}{$curr_date_time}_site.tar.gz"); // send to rackspace

 }

 } catch (Exception $e) {
     print_r($e, true);
 }

}

?>


text:
Q: Flipping Variables for a Poisson Distribution Not sure exactly how to word this, but I'm stuck on a current question about poisson distributions.
So far, the questions have gone along the lines of "What is the probability that x SUCCESSES will occur in a two-day period?" and "What is the probability that at least x SUCCESSES will occur in a two-day period? I've found the respective probabilities for these on python, but how would I approach a question worded like this:
"What is the probability that at least one of these two-day periods sees at least 2 SUCCESSES?"
For reference, my basic code looks like this for a question about at least 2 successes in a 2-day period:
mu = 0.11
k = 2
P = stats.poisson.cdf(k-1, mu)
P1 = 1-P
How can I figure out how to instead find the probability about two-day periods with at least two SUCCESSES?

A: You already know the answer to: "What is the probability that at least k SUCCESSES will occur in a two-day period?" In particular, you know this for $k=2$.
Let's call this probability $p_1$ (you called it P1, so I changed it slightly).
Your question: "What is the probability that at least one of these two-day periods sees at least 2 SUCCESSES?" For this to be meaningful, you need a number of those periods, let's call this $m$.
And, also, let's call this probability you are looking for $p_m$.
If your data is created by a proper Poisson process (and I will presume this here in my answer), then the events at different times are independent (given the Poisson process). That means there are two cases:
First Case: The two-day periods are disjoint:
If all your two-day periods are disjoint, then the counts of successes in each of those two-day periods are independent, and, since they are of the same length, their distributions are identical. So, first, you note that the probability $p_1$, that you have already figured out, is the same for all of those two-day periods. Next, you realize that the probability that you have at least one two-day period with at least two SUCCESSES is the same as one minus the probability that none has at least two SUCCESSES. Since the probability of "there are less than two SUCCESSES in a two-day period" is $1-p_1$, and because, as stated above, the counts in all those periods are independent, we get:
$$
p_m = 1 - (1-p_1)^m.
$$
(Recall, that the probability of a collection of independent events to all occur together is equal to the product of their individual probabilities.)
Second Case: The two-day periods are not disjoint:
In this case, the counts of SUCCESSES in those two-day periods are not anymore independent. Think of e.g. having the same period twice. Then, of course, the number of SUCCESSES in those "two" periods is not independent. So the analysis would be far more complicated in this situation, so I hope you can content yourself with having only a solution to the first case.


text:
Q: Google Bigquery java client listTables return numBytes and numRows as null When I try to find the size of all the tables using listTables API of BigQuery java client, it returns null. But if I use getTable individually, I get the proper data. Is this a known issue, or am I doing something wrong. Following is the code that returns null value for numBytes:
Page<Dataset> datasetPage = getAllDatasets("projectId");
        if(datasetPage!=null) {
            for (Dataset dataset : datasetPage.iterateAll()) {
                for(Table table : dataset.list().iterateAll()) {
                    System.out.println(table.getNumBytes());  // Returns Null. **
                }
            }
        }

A: In this Public Issue Tracker thread, it has been discussed that getting null value for numBytes and numRows using listTables is the expected behaviour. The BigQuery API considers retrieving numBytes and numRows to be an expensive operation and thus returns null. So, the listTables only returns partial information on a table.
As a workaround, use getTable() to retrieve the information of the table individually in a loop. I tested the below code snippet and was able to get the table size in bytes for all the tables.
public static void getAllTableSize(String projectId) {
    try {
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
      Page<Dataset> datasetPage = bigquery.listDatasets(projectId);
        if(datasetPage!=null) {
            for (Dataset datasetTemp : datasetPage.iterateAll()) {
                for(Table table : datasetTemp.list().iterateAll()) {
                    Table tableTemp = bigquery.getTable(table.getTableId());
                    String tableName = tableTemp.getTableId().getTable();
                    Long tableSize = tableTemp.getNumBytes();
                    System.out.println("Table Name: " + tableName + "  " + "Table Size: " + tableSize);
                }
            }
        }
    } catch (BigQueryException e) {
        System.out.println("Error occurred: " + e.toString());
      }
    }

A: To answer my own question listTables api is designed to return only the partial information. This is mentioned in the code document
https://github.com/googleapis/java-bigquery/blob/dfa15e5ca08a3227f015a389c4c08732178a73e7/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/spi/v2/BigQueryRpc.java#L155


text:
Q: Is there a way to add a Sharepoint Survey App to a Sharepoint List (Possibly with a flow)? I would like to be able to add a flow to a survey that would allow it go through and approval process and update a list within SharePoint. The only options that I'm finding for the Survey app now is to export to Excel.

A: Like Mike Mentioned, you can create a workflow with Call Http Web Service action to call SharePoint rest api for creating/updating new item in Survey list.
You can use sharepoint designer to add your workflow to your List. Detailed steps are here.
Here are the references for CRUD operation on List Item with Rest API.


text:
Q: Generate fake data that don't change I'm creating a temporary GraphQL backend, that should serve mocked data.
E.g. I need ~500 objects of the model Person (with firstName, lastName, email, country, etc), where the properties shouldn't change on each request.
Is there any library where it's possible to get fake data always created in the same order?

A: Not sure if this is exactly what you want, but I discovered this site: https://crudpi.io/ this weekend, you can mock some data in a JSON file and use it for your API. I guess that it's limited to 100 objects or something, but if you need the same data, you can copy it 5 times I guess. Hope it helps!
I wish that I could write this as a comment but I don't have enough reputation yet.

A: Here's an API. https://uinames.com/api/?amount=500
You should easily just create a script, add the data you got from this to a temp-database.

A: You can easily create your custom JSON with https://next.json-generator.com/ which allows using internal scripts for data generation
Here is an example of generating a list of names: https://next.json-generator.com/Vk95XL5mv

A: You can use a generator like https://randomuser.me/
Make a loop to create your object then keep the result in a file to ensure the data will be the same.
You can get an exemple here : https://gist.github.com/Yexan/cb8b79390e01272a4912fb4d6773ee1a
I used https://randomuser.me/api/?results=500


text:
Q: Angular can't parse Spring response I am having some issues trying to receive a response message from a Spring RESTful web service to an AngularJS client.
I am using ResponseEntity<String> to return a response to the client. This works when only returning a status code but AngularJS fails with Unexpected token R when I send a response message in the body.
What am I doing wrong?
return new ResponseEntity<String>(HttpStatus.OK);

But this does not work:
return new ResponseEntity<String>("Report was updated successfully", HttpStatus.OK);

AngularJs code:
$http.get(url, header)
    .success(function(data, status, headers, config) {
        // some logic
    }).error(function(resp, status) {
        // some logic
    });

Response:

A: Is Angular expecting JSON or HTML/text back?
I've experienced issues in the past returning text/javascript or application/json instead of text/html. It looks like Angular is expecting JSON or JSONP in that instance, hence the Unexpected Token R (which is the first letter of your response string).
I could give a more precise answer, but I'd need to also know if you're using JSONP vs JSON, etc.


text:
Q: Is quorum disk required for standalone installations? A provider is setting up a single bare-metal Oracle server for us, which will not be part of any grid or cluster. It has over 20 disks connected via fiber to a SAN, each 1TB.
OVM is installed on a remote redhat server and the bare metal has Oracle linux with OVS.
Is the quorum disk really obligatory? It is my understanding that it requires a small dedicated disk, but the smallest disk I have is 1TB and it would be a terrible waste-
If you could please send links to the documentation which states that it is (or isn't) I would greatly appreciate it.
I have my concerns if the provider is over engineering.
Thanks


text:
Q: Doing an insert remapping for commenter I am trying to do a remapping when I'm in insert mode to insert a comment but am having a tough time figuring out what all the keys map to. What I am trying to do is:
:inoremap leadercspace ==> escleadercspacei
Basically, if I'm in insert mode I want to get out of insert mode to insert the comment (leader+c+space) and then go back into insert mode.
What would the correct :inoremap mapping for this be? What I have right now is:
:inoremap <leader>c<space> <Esc><Leader>c<space>i

But this doesn't seem to work (at least the latter half of it -- it does seem to be executing the mapping command). Note: the plugin I'm trying to remap is:
https://github.com/preservim/nerdcommenter

[count]<leader>c<space> |NERDCommenterToggle|
Toggles the comment state of the selected line(s). If the topmost selected line is commented, all selected lines are uncommented and vice versa.

A: From vim doc (:help nore):

Disallow mapping of {rhs}, to avoid nested and recursive mappings

In other words, the nore part forbids mapping to be applied to the rhs (right hand side).
So in your case, the <Esc><Leader>c<space>i doesn't trigger the VimCommenter mapping for that reason.
To allow recursion, you can take off the nore:
:imap <leader>c<space> <Esc><Leader>c<space>i

A: My recommendation is that, instead of creating an insert-mode mapping for this purpose, just use the native Ctrl+O mapping to run a single Normal mode command from Insert mode.
Assuming your leader key is set to the default \, you can use:
Ctrl+O, \, c, Space
You'll be left in Insert mode at the end of this sequence.
The advantages of this approach over an insert mode mapping are:

*

*You don't need any extra configuration, since Ctrl+O is a native Vim command.

*This works for any Normal mode command, so you don't need to add extra mappings for other commands you might want to be able to access from Insert mode.

*Adding a multi-character mapping in Insert mode starting with <Leader> means Vim will always pause and hold if you insert the leader character. In this case, it will also pause when you insert <Leader> and c. I find that avoiding this kind of mappings of otherwise printable characters is usually best.


text:
Q: How to stop an observedObject from updating the UI in SwiftUi? I am working with a navigationView with swiftUI.
My problem is whenever I go to another view with a Navlink and the observedObject of
the root of my navigationView changes, my interface come back to the root view also.
So my question is : Is there a way to tell the observedObject Of the root of the navigationView to stop updating the UI when I navigate to a navLink ?
The root of my navigationView:
listChatViewModel is an Observable object and recentMessages is a Published Property
NavigationView{

            ScrollView(.vertical, showsIndicators: false){
                VStack(spacing : 6){
                    //Recent
                    ForEach(listChatViewModel.recentMessages){recentMessage in
                        NavigationLink(destination: ChatView(ChatViewModel(myUserId : self.session.session!.uid, userId : recentMessage.senderProfile!.user_id))) {
                            RecentCellView(recentMessage: recentMessage)
                        }
                    }
                    .padding()

                }

            }
            .navigationBarTitle("Chat", displayMode: .inline)
            .navigationBarItems(leading:
                Image("logo_black").resizable().frame(width: 32.0, height: 32.0)
            )
        }

When I am in the ChatView and that the recentMessages property updates, this make me go back to the root view


text:
Q: Yii 1.1 paths not working on remote server I'm new to Yii and i'm having troubles setting up the config on a remote server.
Locally, everything works great, but on the server, using the exact same GH repo including config/main.php, none of the links seem to work.
for example , in site/index, i have a link to /video/index
however, whenever i click the link, the path is added like : /site/video/index. and pressing it repeatedly will add more /video/ in front.(/site/video/video/video/video/index). ->note this only happens on the server and not locally.
things that i've tried: manually inserting pretty and ugly urls in the browser bar, nothing worked. actually, anything i add after .com (.com/asdfbfdgvdipgfbsd/ ) will just render the site/index page, with the path i write remaining in the bar, but content being not an error or anything else, just my main index file.
how i managed to access the videos page:

*

*setting 'defaultUrl' => '/video/index' (instead of site/index), but this doesn't help as obviously i can only access this page now.

*commenting out  'urlFormat'=>'path' ----> this allows me to get to the video page from my site/index page , but this results in the following path displayed in the browser: /video/?r=video/index. Now, in this page i display 20 video thumbnails and have included a self-loading gallery (magicScroller). locally it works fine, more thumbs being added as i scroll down. however, in this config from the server, instead of more thumbs being rendered, i am getting /site/index page rendered below the first videos batch.
here is my 'components'->UrlManager  from main.php config file:
'urlManager'=>array(
    //'urlFormat'=>'path',
    'showScriptName'=>false,
    'rules'=>array(
      '<controller:\w+>/<id:\d+>'=>'<controller>/view',
      '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
      '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
    ),
),

i tried adding 'enablePrettyUrl'=>true, but this results in the error: Property "CUrlManager.enablePrettyUrl" is not defined.
note. locally everything works perfect, paths look normal (no double /video/video or anything peculiar)
Not sure what else to check and try so looking forward to hearing from this community of brilliant minds:)
EDIT:
here is the config. maybe it sheds a bit of light on my issue
 server {
     listen       80;
     server_name my.site.com;

     #charset koi8-r;
     access_log  /var/log/nginx/my.site.com.access main;
     root   /www/my.site.com/public;

     location / {
         index  index.html index.php;
         try_files $uri $uri/ index.php?$args;
     }

     error_page  404              /404.html;

     # redirect server error pages to the static page /50x.html
     #
     error_page   500 502 503 504  /50x.html;
     location = /50x.html {

     }

     # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
     location ~ \.php {
          fastcgi_split_path_info  ^(.+\.php)(.*)$;

          #let yii catch the calls to unexising PHP files
          set $fsn /index.php;
          if (-f $document_root$fastcgi_script_name){
              set $fsn $fastcgi_script_name;
          }

          #fastcgi_pass   127.0.0.1:9000;
          fastcgi_pass   unix:/var/run/fastcgi.sock;
          include fastcgi_params;
          fastcgi_param  SCRIPT_FILENAME  $document_root$fsn;

          #PATH_INFO and PATH_TRANSLATED can be omitted, but RFC 3875 specifies  them for CGI
          fastcgi_param  PATH_INFO        $fastcgi_path_info;
          fastcgi_param  PATH_TRANSLATED  $document_root$fsn;
     }

     location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml|map)$ {
         try_files         $uri $uri/ =404;
         #log_not_found     off;
         expires           1d;
     }

     # deny access to .htaccess files, if Apache's document root
     # concurs with nginx's one
     #
     #location ~ /\.ht {
     #    deny  all;
     #}
 }


text:
Q: What is the permeability of a permanent magnet? The following is a diagram that shows the B- and H-fields of a permanent magnet.
Inside the magnet, the H-field is in the opposite direction to the B-field, because of the magnetisation M-field and the relationship
$$ \vec{B} = \mu_0 (\vec{H} + \vec{M})$$
(in SI units).
It is also commonly stated that the relationship between $\vec{B}$ and $\vec{H}$ can be written as $\vec{B} = \mu \vec{H}$, where in general, $\mu$ can be a tensor that depends on the H-field, position, time, temperature etc. (i.e. not necessarily restricted to linear media).
Yet when I look up the relative permeability for magnets (for example here for Neodymium magnets), it is given as a positive scalar $>1$. But surely if the B-field and H-field are in opposite directions then $\mu$ is negative?
What is the source of my confusion?

A: The book that the wikipedia article refers to is "Design of Rotating Electrical Machines" by Pyrhonen et al, one can read some pages via Google. It is an engineering book, and it uses engineering-type concepts like "reluctance" that are useful to calculate "magnetic circuits" and things like that.
In those kind of calculations, a  strong permanent magnet acts like an air gap, because its magnetization hardly changes in an applied field (as long as its value does not get too close to the coercive field in the wrong direction). So it can be modeled with $\mu_r \approx 1$.

A: The relation between $B$ and $H$ (or for the electric case between $E$ and $D$) are completely material dependent and have no closed form expression. They are called constitutive relations. There are only models for these relations. The permeability model is just the simplest one.
Even when one would say $μ$ is tensorial and allowed to depend on space, time, $H$ and $B$, this (extended permeability) model is still not fully general. This is because there may be dynamic effects ($M$ may depend on past values of $H$) and/or dependencies on spatially neighboring points of $H$. Dynamic effects are very common (a.k.a. frequency dependence)
If one really wants to write down an equation capturing all this, one has probably something like this (this is from the Wikipedia link above):
$M = \frac{1}{\mu_0} \iiint d^3r' dt' \chi_m(r',t',r,t,H) H(r',t')$
However, I think this equation is not very useful. In my opinion, it is equally helpful to say $M$ is formed by applying a causal operator to $H$ (potentially nonlinear and time variant). But even that is not most general:
Magnetization can also be caused by other physical quantities such as temperature (Seebeck effect), electric field (Hall Effect), stress (Piezomagnetic effect), radio frequency waves (Nuclear magnetic resonance -> e.g. Bloch equaitions) with all these effects having different equations to describe magnetization.
Concluding, it is probably best to see magnetization (and its electric equivalent polarization) as a quantity which is given by many physical effects and has to be determined by the equations specific for the effects to be taken into account. A permeability based model is only valid for isotropic material, low fields and slow temporal variations.
For permanent magnet the first breaks down (fields are constantly there and are not "low") and the second very quickly with increasing frequency.
So for a magnetized magnet a permeability based model makes no sense.
One can specify a permeability for the (unmagnetized) material the magnet is made of, though. This is probably what you saw.
A good starting point is probably an advanced book on electromagnetism, such as Jacksons. More specific topics are likely handled in special book on magnetics, superconduction, spectroscopy (NMR or else methods), nonlinear optics or optoelectronics.

A: To your question "So is the concept of a relative permeability invalid for any material with a permanent magnetisation?" let me quote [1]

(page 26) The formal theory of magnetostatics, as presented in elementary textbooks on electricity, is usually based on the linear approximation $\mathbf{M} = \chi \mathbf{H}$ or $\mathbf{B} = (1+4\pi\chi) \mathbf{H}$, where the susceptibility $\chi$ and the permeability $\mu = 1+4\pi\chi$ are assumed to be constants for a given material at a given temperature. For ferromagnetic materials, such a relation is never more than a very crude approximation usable over a limited range; it has some usefulness in practical applications, for example in the conventional "magnetic circuit" formulas, but it has almost no value in basic physical theory. In ferromagnetism, permeability - so far as it warrants introduction at all- is not a quantity to be used in the theoretical formulas
  but a quantity to be calculated by means of them. Furthermore, on the basis of the definitions that we have adopted for the flux density B and magnetizing force H at points of a magnetic specimen, there is no reason for even expecting that the magnetization will
  be a function of either of these field vectors. And in fact the physical theory of ferromagnetism justifies this scepticism: for sufficiently small bodies, the magnetizatiou depends, among other things, on the size and shape of the body, so that no M vs H relation
  exists.
(page 86) From these considerations it is clear that for ferromagnetics a "permeability" $\mu$, must never be defined simply as the value of $B/H$ but must be defined as a value of $B/H$, of $dB/dH$, or of $\Delta B/\Delta H$ under specified conditions. Such special definitions lead to such concepts as initial permeability, reversible permeability,
  incremental permeability, and ideal permeability, whose uses are limited and mostly of engineering nature.
  For calculation of the field in a gap, or at a more general point outside a magnetized body, it is often a good approximation to assume that B ~ H everywhere inside the material and therefore to replace it with a linear material for which $\mu = \infty$. The electrostatic analogue is a perfect conductor. The internal H is zero, and the flux lines emerge from the specimen surface along its unit normal; the specimen surface is an equipotential for the total scalar potential $\phi$, of which, in any region not occupied by conduction currents, H is the negative gradient.
  The specification $B =\mu H$, with $\mu$ assumed constant, fixes the magnetization distribution and therefore the demagnetizing factor of a non-ellipsoidal specimen. Even in this approximation, however, the calculation of the demagnetizing factor (now a function of $\mu$) is an unsolved problem of potential theory except in the following
  cases: (1) the ellipsoid and its degenerate forms; (2) the limit $\mu \to 1$, where the magnetization becomes uniform, the theorems of Ch. 3, § 3 hold, and the calculation reduces to a calculation of the volume-average H due to uniform M; (3) certain two-dimensional problems in the limit $\mu \to \infty$. Examples of (2) are the circular cylinder in a longitudinal or transverse field and the infinitely long rectangular bar in a transverse field. An example of (3) is the infinitely long rectangular bar in a transverse field. Since numerical values for these cases are not given in the standard
  literature, they are given in the Appendix, with some corresponding ellipsoid values for comparison.

Brown: Magnetostatic Principles in Ferromagnetism, North Holland, 1962


text:
Q: basic authentication with REST in Solr 6.6.1 I have deployed Apache Solr 6.6.1 with basic authentication by following their reference guide. At the end they have discussed how to use curl with security. For my case, I am using REST API to query SOLR.
Due to Basic Authentication i am using this query. https://user:pswd@serverhost/solr/...
in this way my user & paswd will expose. i want to know the safest method to use basic authetication with REST API that will not be exposed to external worl.

A: As you can see here:

The use of these URLs is deprecated. In Chrome, the username:password@
  part in URLs is even stripped out for security reasons. In Firefox, it
  is checked if the site actually requires authentication and if not,
  Firefox will warn the user with a prompt "You are about to log in to
  the site "www.example.com" with the username "username", but the
  website does not require authentication. This may be an attempt to
  trick you.".

You don't need to expose it in your URL, you should add an "Authorization" Header to your request. The value will have "username:password" encoded in Base64, which is not safe, but since you're using https, it will be protected.
The full value of the header will be something like "Basic dXNlcm5hbWU6cGFzc3dvcmQ=". It's formed by the type of authentication ("Basic") plus a whitespace plus the value of "username:password" encoded in Base64.


text:
Q: How to make MATLAB return char instead of ASCII? So, I'm using AT Commands with Matlab to return the Caller ID, but this doesn't really matter.
Everything is working great except for the fact that it returns ASCII numbers and I have to take my time "translating" that ASCII code to char so I can know what is it saying.
>> s = serial('COM8');
>> fopen(s)
>> fwrite(s, [65 84 43 67 82 67 61 49 13])
>> s

   Serial Port Object : Serial-COM8

   Communication Settings
      Port:               COM8
      BaudRate:           9600
      Terminator:         'LF'

   Communication State
      Status:             open
      RecordStatus:       off

   Read/Write State
      TransferStatus:     idle
      BytesAvailable:     47
      ValuesReceived:     0
      ValuesSent:         18

>> fread(s, 47)

It returns me 47 ASCII numbers like this(note that I have deleted most of the returned code):
ans =

    65
    84
    43
    67
    82
    67
    61
    49
    13

I've tried the following things:
char(fread(s,47))

and
z = fread(s,47)
char(z)

but neither of those worked, however
z = [65 84 43 67 82 67 61 49 13]
char(z)

works fine. I suppose it is because fread returns the ASCII code with newline between them and not just space like I wrote in the code above.

A: try str2double, str2num or just subtract '0' ( the ascii value of the char '0' ) from the ascii code you have.

A: Here's how I would do it when reading from a file --
>> s = fopen('.gitignore') # Just a file in my current directory
>> z = fread(s,10)         # Returns a column of numbers
z =
    43
    97
    114
    98
   105
   116
   114
    97
   114
   121
>> char(transpose(z))      # You could write z' instead of transpose(z)
ans =
+arbitrary

Where "+arbitrary" are the first 10 characters of the file I read.

A: I used class(s) to find out that the returned class is serial. So I found out about fgets and it worked great.More info about fgets on http://www.mathworks.com/help/matlab/ref/serial.fgets.html
Here is the input/output.
tline = fgets(s)
tline =
ATD0888123456


text:
Q: Exchange 2019 Archive Policy moves items to Recoverable Items Folder So we have 3 Exchange 2019 servers in our environment. Two of them are DAG servers storing mailboxes, third is archive mailboxes only.
For most users everything works fine, however there are few, where all items marked with archive retention tags are moved to inplace archive mailboxes, but straight to "Recoverable Items" folder (found this by exporting user archive to pst).
What's interesting, if I move archive mailbox to the same database, as mailbox connected to it, everything works fine.
Of course I checked all the retention tags set by user.
Here is how it looks if i use Get-MailboxFolderStatistics

xxx@domain.com\Folder nadrzędny magazynu informacji - 290.1 MB (304,214,249 bytes) (root folder)
xxx@domain.com\Recoverable Items - 1.467 GB (1,575,517,001 bytes)
Tried creating new inplace archive mailbox, repairing, moving to different DB - nothing.
Any ideas, Guys?

Edit: I have found that this problem occurs only when mailbox is on different SERVER than archive

A: Whose "Recoverable Items" folder did these emails reach to? The primary mailbox or the archive mailbox?
Were emails removed immediately since they were sent(Move to the Recoverable Items folder)? Or they were saved for one or more days and then be deleted?
If the emails went straight to "Recoverable Items", it seems that these items have been Delete and Allow Recovery(Retention actions). Did you add a retention tag(which is like the following snapshot) in the retention policy which was applied by your mailboxes?

For further troubleshooting, please provide the retention policy which was applied by your mailboxes and its retention tags by running the following commands and viewing the following interface:
Get-Mailbox <MailboxIdentity> | fl RetentionPolicy

Get-RetentionPolicy "<Retention Policy Name>" | fl Id, RetentionPolicyTagLinks


text:
Q: proper backup & restore mediawiki on ubuntu mate I am trying to create a streamlined approach to backing up and restoring my MediaWiki.  My wiki is installed in folder /var/www/html/mediawiki and is running on an Ubuntu Mate 20.10 machine, MediaWiki verson 1.35.1, PHP 7.4.9, and mysql version Server version: 10.3.25-MariaDB-0ubuntu1 Ubuntu 20.10.
Backup:

*

*I installed automysqlbackup and configured it to automatically make gzip backups of my mysql databases, which go into an SMB mounted folder mapped to my NAS (/mnt/wiki-backup)

*I manually zipped the entire MediaWiki folder with the following tar command.
tar zcvhf mybackupfilename.tgz /var/www/html/mediawiki
Restore:
To make sure I could restore the wiki, I made a textual change to one of it's pages.  Then I restored the MediaWiki's sql database using the following command (which I ran from /mnt/wiki-backup where the backup .sql file was located) where mediauser is the admin name for my wiki database, and mediadb is the name of the database.
sudo mysql -u mediauser -p mediadb < mediadb_2021-03-19_14h22m.Friday.sql
Sure enough, this worked fine - and the page was back to what it was before I made my test textual changes.
My Questions:

*

*Is all text for MediaWiki pages stored in the sql database, and all images stored in the MediaWiki folder structure (e.g. /mediawiki)?  From this page this seems to indeed be the case.

*How do I restore the /mediawiki folder from the tar I created at step 2. above?  Would it simply be the following?
tar zxvhf mybackupfilename.tgz /var/www/html/mediawiki -C /var/www/html/mediawiki
I'd appreciate any other constructive feedback on how best to do this.


text:
Q: In Azure DevOps, is there a way to export the details of the execution history of test points? Our client is asking if there's a way for us to provide them a list of testers who have executed test points in DevOps. I saw that each test point would have execution history. If there's a way to export those details (please see attached screenshot), that would really help.

A: You can bulk export Test Cases from a Test Suite like the following:

Link: https://www.ecanarys.com/Blogs/ArticleID/415/Bulk-Export-Import-Test-Cases-to-Azure-DevOps-Test-Plans-using-CSV-file


text:
Q: Stop dragging left in resizable split view I have resizable split view where I can drag the splitter to resize the left and right sides. But I'm unable to stop dragging left at a point. But I can set a width to stop dragging right.
Here is the code snippet which stops dragging to right.
`this.mousemoveListener = (e) => {
      if (this.resizing) {
        this.showResizeIndicator(e.pageX);
      }
    };

showResizeIndicator(offsetLeft: number): void {
    if (this.resizeIndicator) {
      let positionLeft = offsetLeft - this.containerElement.getBoundingClientRect().left + this.containerElement.scrollLeft;
      // Ensure that resize indicator cannot be dragged completely to the right - minimum table with should be considered.
      const indicatorTreshold = this.containerElement.getBoundingClientRect().width - this.minTableWidth;
      if (positionLeft > indicatorTreshold) {
        positionLeft = indicatorTreshold;
      }
      this.resizeIndicator.style.left = positionLeft + 'px';
      this.resizeIndicator.style.height = this.containerElement.offsetHeight + 'px';
      this.resizeIndicator.style.display = 'block';
    }
  }

  get containerElement() {
    return this.parentDirective.element.nativeElement;
  }`

A: I already implemented such a splitter with three events.
mousedown event for when it is selected.
I will listen to the other two when it element is selected.
One mousemove to change the size.
and another mouseup to stop the operation.
this.mousedownSubscription = fromEvent(
        this.vl.nativeElement,
        'mousedown'
      ).subscribe((e: any) => {
        this.onMouseDown();
      });

onMouseDown() {
    this.isMouseDown = true;
    const body = document.body;
    this.mousemoveSubscription = fromEvent(body, 'mousemove').subscribe(
      (e: any) => {
        this.onMouseMove(e);
      }
    );
    this.mouseupSubscription = fromEvent(body, 'mouseup').subscribe(
      (e: any) => {
        this.onMouseEnd();
      }
    );
  }

onMouseEnd() {
    this.isMouseDown = false;
    this.mouseupSubscription.unsubscribe();
    this.mousemoveSubscription.unsubscribe();
  }

I think you should use mouseup event.


text:
Q: Recalling the date that was picked by the user rather than current date I have a date picker as below which is not bringing back the date that was picked by the user, instead it is bringing back the latest month and the year. How can i change the function so that it always brings back the date that was saved in the database, or the date that selected by the user on the input field rather than the original date.This is what the function is returning as of now

   <script>

   $(document).ready(function ()
   {
   $(".datepicker").datepicker({
     showOn: 'both',
     dateFormat: 'dd/mm/yy',
     showButtonPanel: true,
     constrainInput: false,
     buttonImage: "../jquery-ui-1.11.4.custom/images/calendarNew.gif",
     buttonText:"Please select a date",
     buttonImageOnly: true,
     closeText: 'Clear', // Text to show for "close" button
     onClose: function () {
      var event = arguments.callee.caller.caller.arguments[0];
      // If "Clear" gets clicked, then really clear it
      if ($(event.delegateTarget).hasClass('ui-datepicker-close')) {
       $(this).val('');
         }}});

   });

    </script>

 <style>
         img.ui-Datepicker-trigger {
          position: relative;
          left: -25px;
          top: 2px;
    }
    </style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<input name="Date" id="Date"  class ="datepicker" value="#dDate#" onChange="setFormChanged(this);"/> <font color="Teal" size="-2"> {dd/mm/yyyy} #dOccDate# </font>


text:
Q: Python, pygame, collisions and dictionaries I am using the below code to try and code basic collisions using pygame. Almost all of the built in collision method return python dictionaries which are new to me. Using many internet sources I have discovered how to search a dictionary, however the dictionary returned by the method does not appear to follow the same rules and therefore i am unable to search it for which sprites collide. Either a new collision method or a way to search my dictionary would be very much appreciated.
RED=(255,0,0)
BLACK=(0,0,0)
WHITE =(255,255,255)
GREEN = (0,255,0)
player_health = 10
enemy_health = 10
collision_counter = 0
attack_counter = 0
attack = False

import pygame

#Creating screen and sprites
all_sprites_list = pygame.sprite.Group()
all_enemies_list = pygame.sprite.Group()

pygame.init()

screen = pygame.display.set_mode((1,1))

class Sprites(pygame.sprite.Sprite):

    def __init__(self,x,y,img):
        super().__init__()

        #Colour and position
        #Set the background colour and set the image to be transparent
        self.image = pygame.Surface([x, y])
        self.image.fill(WHITE)
    self.image.set_colorkey(WHITE)

    #Or using an image
    self.image = pygame.image.load(img).convert_alpha()

    #Fetch a rectangle that is the same size
    self.rect = self.image.get_rect()

    self.mask = pygame.mask.from_surface(self.image)

def AI(self,charX):

    #If the player is on the left
    if self.rect.x < charX:
        self.rect.x +=  1

    #On right
    if self.rect.x > charX:
        self.rect.x -= 1

def update(self,charX):
    self.AI(charX)

img = "BadCrab.png"
#Creating the first AI sprite with width,height,colour and x,y position
AI1 = Sprites(30,20,img)
AI1.rect.x = 0
AI1.rect.y = 150
#Adding to to the necessary groups
all_enemies_list.add(AI1)

#Creating the character sprite with width,height,colour and x,y position
char = Sprites(30,20,"Crab.fw.png")
char.rect.x = 150
char.rect.y = 150
#Adding to to the necessary group
all_sprites_list.add(char)

screen = pygame.display.set_mode((800,400))
clock = pygame.time.Clock()
counter = 0

while True:
    pygame.event.pump()
    screen.fill(BLACK)
    clock.tick(60)
    pygame.event.pump()
    keys = []

    #Getting the keys which are pressed down
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            keys.append(event)

    #Converting the array to a string so it can be searched
    keys=str(keys)

    #Using the keys numbern value to determine if it has been pressed
    #Left arrow = 276
    if "276" in keys:
        char.rect.x -= 40

    #Right arrow = 275
    elif "275" in keys:
        char.rect.x += 40

    counter += 1
    #Space = 32
    if "32" in keys:
        counter = 0
        #Removing orignal sprite and then changing it to the attack sprite
        all_sprites_list.remove(char)
        char = Sprites(30,20,"Crab_attack.fw.png")
        char.rect.y = 150
        char.rect.x = charX
        all_sprites_list.add(char)
        attack = True
    #Allwoing the attack sprite to be drawn before replaced by original sprite
    if counter == 12:
        all_sprites_list.remove(char)
        char = Sprites(30,20,"Crab.fw.png")
        char.rect.y = 150
        char.rect.x = charX
        all_sprites_list.add(char)
        counter = 0
        attack = False

    charX = char.rect.x
    all_enemies_list.update(char.rect.x)
    all_enemies_list.draw(screen)
    all_sprites_list.draw(screen)
    pygame.display.flip()

    #Checking for collisions
    collisions = pygame.sprite.groupcollide(all_sprites_list, all_enemies_list,False,False)
    print(str(collisions))

A: keys = []

#Getting the keys which are pressed down
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        keys.append(event)

#Converting the array to a string so it can be searched
keys=str(keys)

#Using the keys numbern value to determine if it has been pressed
#Left arrow = 276
if "276" in keys:
    char.rect.x -= 40

#Right arrow = 275
elif "275" in keys:
    char.rect.x += 40

counter += 1
#Space = 32
if "32" in keys:
    counter = 0
    #Removing orignal sprite and then changing it to the attack sprite
    all_sprites_list.remove(char)
    char = Sprites(30,20,"Crab_attack.fw.png")
    char.rect.y = 150
    char.rect.x = charX
    all_sprites_list.add(char)
    attack = True

I don't know why you're trying to do it the most complicated way, just use
#Getting the keys which are pressed down
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            char.rect.x -= 40
        if event.key == pygame.K_RIGHT:
            char.rect.x += 40
        if event.key == pygame.K_SPACE:
            counter = 0
            #Removing orignal sprite and then changing it to the attack sprite
            all_sprites_list.remove(char)
            char = Sprites(30,20,"Crab_attack.fw.png")
            char.rect.y = 150
            char.rect.x = charX
            all_sprites_list.add(char)
            attack = True

counter += 1

however the dictionary returned by the method does not appear to follow the same rules

The dictionary returned by groupcollide works the same way as every other dictionay. I don't know what rules you're talking about. If you have trouble figuring out what exactly is returns, just take a look at the documentation:

Every Sprite inside group1 is added to the return dictionary. The value for each item is the list of Sprites in group2 that intersect.

and the return value is a simple dict, so you could do e.g.:
for sprite, others in collisions.items():
   for other in others:
      print(str(sprite) + ' collides with ' + str(other))


text:
Q: How to hide media stream url I have a link like this: http://example.com/temp/test/index.php?v=de72800bf2682d7d1b808e48cf351543db88c7a0
I have a datatable row like this:
ID=1, Title="short movie", direct_url="http://example.com/temp/test/Ideas(short_film).webm", "indirect_url = "de72800bf2682d7d1b808e48cf351543db88c7a0"
I wanna do so: If I go to the link that I mentioned above, in that page will be video tag:
<video src="**http://example.com/temp/test/index.php?v=de72800bf2682d7d1b808e48cf351543db88c7a0**"></video>

And it starts to play video from direct url http://example.com/temp/test/Ideas(short_film).webm, but it will not appear in the page, so nobody can use the direct link. By which way I can do this? Maybe Javascript, maybe php can help me, but I don't know. Help me, please.

A: Do you want to prevent capturing or saving the video? Impossible

Do you want to hide the URL? Impossible

That's impossible because the browser needs to access it. And that information is saved at some place (e.g. in the network traffic list).
Even if you would find other ways of streaming/sending the video information, it won't go directly to the browser. The information is passed through many stations and one of it could copy the data.

A: You can't. If my browser can request the URL, I can see the URL. You'll have to look into other ways of protecting your content.

A: You can certainly do this with php.
If a user opens a page which contains
<video src="**http://example.com/temp/test/index.php?v=de72800bf2682d7d1b808e48cf351543db88c7a0**"></video>
Your index.php should perform the lookup to determine the video file's path which should not be web accessible, open that file and then stream it to the browser.


text:
Q: How to allow JSON post (and later get) only "time" (not date/timestamp) property of resource Creating API to allow JSON POST of "resource" with persistence to backend.
Have one of the property which is basically a "time" of the day (format 2.00 PM, 5.00 PM etc). Trying to explore various options of either passing it as plain String or text (from rest client) OR should be of any specific "time" format easy for api implementation to accept it(easy mapping/parsing). Looking for suggestions ?
Sample Json:
{

   "name" : "Mark",
   "age" : 15,
   "cutOffTime": "2.00 PM" (????)
   ........

}

A: Go for LocalTime
The modern date-time API which was first introduced with Java SE 8 and has been further enriched in the subsequent releases, provides a rich set of API to manage date, time and their formatting. Given below is a demo of the same:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Test strings
        String[] strTimes = { "1:00", "01:00", "1:00 pm", "1:00 am", "01:00 am", "01:00 pm", "13:10", "8:9", "8:9 am" };

        // Define the formatter
        DateTimeFormatter inputFormatter = new DateTimeFormatterBuilder()
                                            .parseCaseInsensitive()
                                            .appendPattern("[h:m a][H:m]")
                                            .toFormatter(Locale.ENGLISH);

        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("HH:mm");

        for (String strTime : strTimes) {
            LocalTime time = LocalTime.parse(strTime, inputFormatter);

            // String to be displayed or saved into the database
            String formattedTime = time.format(outputFormatter);
            System.out.println(formattedTime);
        }
    }
}

Output:
01:00
01:00
13:00
01:00
01:00
13:00
13:10
08:09
08:09

It was error-prone as well as complex to do the same thing using the legacy date-time API. For your requirement, I recommend you use LocalTime (this is why I've chosen LocalTime in the demo). You can learn more about the modern date-time API from Trail: Date Time


text:
Q: Extract population count from GeoTIFF based on mask layer I downloaded Population Count data from Gridded Population of the World (GPW), v4 as a *.GeoTIFF file. In a next step, I would like to extract the population count of a given area based on a mask layer (e.g. the political boundaries of Portugal imported from a *.geojson).
I came across an answer on StackExchange, which I believe is trying to achieve a similar result. However, I could not reproduce it due to NotImplementedError: multi-dimensional sub-views are not implemented and I suspect the solution would be overengineered for me.
When I open the *.GeoTIFF file in QGIS and display the layer properties, I see the following information (I suppose, I am interested in the STATISTICS_MEAN):

The files are avialble for download here (only for seven days or 100 downloads though):
GeoTIFF: https://send.firefox.com/download/a4be075f0dda3acb/#UlUv5RDx8i3XXvV4dQHtEA
Geojson: https://send.firefox.com/download/54d3458a17ca355a/#DM8M3hGOfcoIDOVeKcMZJA

A: This is something you can do with geocube and rioxarray.
Here is an example I followed to generate this:
https://corteva.github.io/geocube/stable/examples/zonal_statistics.html
import geopandas
import numpy
import rioxarray
from geocube.api.core import make_geocube

gpd = geopandas.read_file("portugal.geojson")
gpd["mask"] = 1

raster = rioxarray.open_rasterio(
    "gpw_v4_population_count_rev11_2020_30_sec_portugal.tif",
    mask_and_scale=True,
)
mask = make_geocube(
    gpd,
    measurements=["mask"],
    like=raster,
    fill=0,
)

Then, to get the total population:
total_population = raster.where(mask.mask).sum().item()

16079493.21870717

EDIT:
Installation method:
conda create -n geo geocube
conda activate geo
(geo)

A: You can do that directly with GDAL, which is likely installed if you have QGIS already, both in Python and in the console. Python version here:
import numpy as np
import matplotlib.pyplot as plt
import gdal

fname = "gpw_v4_population_count_rev11_2020_30_sec_portugal"
world = "TM_WORLD_BORDERS_SIMPL-0.3.shp"
data = gdal.Warp("", fname, format="MEM",
                 cutlineDSName=world, cropToCutline=True,
                 dstNodata=-999,
                 cutlineWhere="NAME='Portugal'"
                ).ReadAsArray()
print(f"Total population {data[data != -999].sum()}")

A couple of things:
1. I have cropped to only consider the envelope of Portugal
2. I have set the no data value to -999
3. Your links aren't working anymore, so I just
    * Downloaded the original dataset (see filename)
    * Used the TM_WORLD_BORDERS_SIMPL dataset
4. From the TM_WORLD_BORDERS_SIMPL, I just select the Portugal entry.


text:
Q: Wildfly and Wildfly-swarm injecting CDI beans from war deployment vs custom module In the process of experimenting with Wildfly-swarm I have run into a strange situation regarding bean injection.
I have a very simple bean, more or less like this:
@ApplicationScoped
public class FooServiceImpl implements FooService {
    Foo delegate;
    @PostConstruct public void init() {
        delegate = .....;
    }

    public Foo getFoo() {
        return delegate;
    }
}

If I bundle this in a jar directly in the war deployment, everything works fine and as expected. However, I need internal parts of this implementation to be completely isolated from the application, why I packaged the service api and its implementation into separate jboss modules.
These modules are added to the swarm uberJar and my app depends on them through the MANIFEST Dependencies entry. Now, everything seems to work ok, the FooService bean  is injected in my application servlet/rest resources, but the init() method is not called.
I cannot figure out what's going on here. It's like the bean resolution process doesn't recognize the @ApplicationScope annotation. Could there be two different class loaders for it?
UPDATE
I enabled tracing and to me it looks like Weld is treating the FooImpl class as ApplicationScoped, i.e. adding a LifecycleMixin.lifecycle_mixin_$$_postConstruct() to the proxy being created:
2017-09-14 23:11:34,315 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001538: Created context instance for bean Managed Bean [class com.xxx.FooImpl] with qualifiers [@Any @Default] identified as WELD%ManagedBean%test.war|test.war.external.file:/tmp/nestedjarloader2449602760983533131.tmp/META-INF/beans.xml|com.xxx.FooImpl|null|false
2017-09-14 23:11:34,315 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001542: Retrieving/generating proxy class com.xxx.FooImpl$Proxy$_$$_WeldClientProxy
2017-09-14 23:11:34,315 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001541: Adding method to proxy: public void com.xxx.FooImpl.registerMessageHandler(com.xxx.MessageHandler)
2017-09-14 23:11:34,315 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001541: Adding method to proxy: public void com.xxx.FooImpl.registerListeners(java.util.EventListener[])
2017-09-14 23:11:34,316 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001541: Adding method to proxy: public void com.xxx.FooImpl.send(com.xxx.MessageHandler,com.xxx.Message) throws java.io.IOException
2017-09-14 23:11:34,316 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001541: Adding method to proxy: public void com.xxx.FooImpl.init()
2017-09-14 23:11:34,316 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001541: Adding method to proxy: public java.lang.String java.lang.Object.toString()
2017-09-14 23:11:34,316 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001541: Adding method to proxy: public abstract void org.jboss.weld.interceptor.proxy.LifecycleMixin.lifecycle_mixin_$$_postConstruct()
2017-09-14 23:11:34,316 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001541: Adding method to proxy: public abstract void org.jboss.weld.interceptor.proxy.LifecycleMixin.lifecycle_mixin_$$_preDestroy()
2017-09-14 23:11:34,317 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001543: Created Proxy class of type class com.xxx.FooImpl$Proxy$_$$_WeldClientProxy supporting interfaces [interface com.xxx.FooService, interface java.io.Serializable, interface org.jboss.weld.interceptor.proxy.LifecycleMixin, interface org.jboss.weld.interceptor.util.proxy.TargetInstanceProxy, interface org.jboss.weld.bean.proxy.ProxyObject]
2017-09-14 23:11:34,317 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001506: Created new client proxy of type class com.xxx.FooImpl$Proxy$_$$_WeldClientProxy for bean Managed Bean [class com.xxx.FooImpl] with qualifiers [@Any @Default] with ID WELD%ManagedBean%test.war|test.war.external.file:/tmp/nestedjarloader2449602760983533131.tmp/META-INF/beans.xml|com.xxx.FooImpl|null|false
2017-09-14 23:11:34,318 TRACE [org.jboss.weld.Bean] (ServerService Thread Pool -- 12) WELD-001507: Located client proxy of type class com.xxx.FooImpl$Proxy$_$$_WeldClientProxy for bean Managed Bean [class com.xxx.FooImpl] with qualifiers [@Any @Default]

The postconstruct interceptor isn't invoked--why? The mystery deepens!
UPDATE 2
Tested this on vanilla wildfly, and the behavior is the same, @PostConstruct method is not called if bean is located in module.

A: I suppose this question and the one in JBoss forums are linked, but in case they aren't...
Probable cause is that your separate module does not declare dependency on <module name="javax.annotation.api"/> which is where @PostConstruct comes from. Adding it, should solve the trouble.
This seems to be expected JVM behaviour (as explained in this SO question) - if you miss the dependency in runtime, the program will still execute but ignore the annotation.
As a way around this (if the above doesn't work or you can't do it) - you may make use of initializer methods. It is a method executed as soon as the object is created by CDI.


text:
Q: Postgres CASE WHEN IN query I've attempted the below query in postgres 11
CASE
           WHEN planning_status::varchar in (('Application Under Consideration'::varchar,'Appeal In Progress'::varchar))  then 'this_label'
           WHEN planning_status::varchar  = 'Approved' and  actual_completion_date is not null then 'that_label'
    ELSE 'reject_label'
    END

I can't get the query to run, initially getting error on mismatching operator to record type. I also attempted IN (VALUES()) method. The below works:
       CASE
          WHEN planning_status = 'Application Under Consideration'  then 'this_label'
          WHEN planning_status = 'Appeal In Progress'  then 'this_label'
          WHEN planning_status = 'Application Received'  then 'this_label'
          WHEN planning_status  = 'Approved' and  actual_completion_date is not null then 'that_label'
    ELSE 'reject_label'
    END

Is it possible to use the IN query within a CASE WHEN query with strings. The strings are categorical but not stored as such

A: The problem are the double parentheses:
-- this doesn't work:
SELECT CASE WHEN 1 IN ((1, 2)) THEN 'works' ELSE 'weird' END;
ERROR:  operator does not exist: integer = record
LINE 1: SELECT CASE WHEN 1 IN ((1, 2)) THEN 'works' ELSE 'weird' END...
                           ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

-- this works:
SELECT CASE WHEN 1 IN (1, 2) THEN 'works' ELSE 'weird' END;

 case
═══════
 works
(1 row)

The reason is that in the first statement, the inner parentheses are forming a composite type (record) with two elements, and PostgreSQL doesn't know how to compare that to the integer 1.

A: If the = version works, then this should work:
  (CASE WHEN planning_status IN ('Application Under Consideration', 'Appeal In Progress', 'Application Received')
        THEN 'this_label'
        WHEN planning_status  = 'Approved' and  actual_completion_date is not null
        THEN 'that_label'
        ELSE 'reject_label'
   END)

There should be no need for an explicit type conversion.  If this doesn't work, what is the type of planning_status?


text:
Q: What are the reference infos when using Eclipse Batch Compiler When reading through the Eclipse Batch Compiler Documentation for Java, I came accross the flag -referenceInfo whichs description is as follows:

Compute reference info. This is useful only if connected to the
  builder. The reference infos are useless otherwise.

What are does reference infos? Are those infos about object references? Is there any documentation available?

A: These reference infos are used when the Eclipse Java Compiler is used as part of the Eclipse Java IDE (as so-called project builder).
Therefore, there will probably be no documentation for this. But in the code you can see which data is gathered with -referenceInfo during compilation (see org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope):
if (compilerOptions.produceReferenceInfo) {
    this.qualifiedReferences = new SortedCompoundNameVector();
    this.simpleNameReferences = new SortedSimpleNameVector();
    this.rootReferences = new SortedSimpleNameVector();
    this.referencedTypes = new LinkedHashSet<>();
    this.referencedSuperTypesSet = new HashSet<>();
    this.referencedSuperTypes = new ObjectVector();
} else {
    this.qualifiedReferences = null; // used to test if dependencies should be recorded
    this.simpleNameReferences = null;
    this.rootReferences = null;
    this.referencedTypes = null;
    this.referencedSuperTypesSet = null;
    this.referencedSuperTypes = null;
}

I guess (but I'm not sure if it's true) that for instance the referenced super types are collected e.g. to be able to quickly display a type hierarchy in the Java IDE.


text:
Q: What exactly is a Redpost collection at surrender@20? I think maybe it is some kind of summary? But on the Red Post Collection Site there are also just news and stuff like that. So what exactly is a Redpost collection?

A: When a RIOT employee posts something in the forums, their name comes up with a red font.
The "Red Posts" are collections of what RIOT employees have posted in the forums, denoting that this information came straight from them.


text:
Q: Applescript array of applications I have a script that reload the active tab of an open browser, but I want it to do with all opened browsers. Is there a way to make a list/array and use it in this code?
This code works with one browser only:
if application "Safari" is running then
    tell application "Safari"
        activate
    end tell
    tell application "System Events"
        tell process "Safari"
            keystroke "r" using {command down}
        end tell
    end tell
end if

I've tried to create an array/list but I think this is no the way because it doesn't work:
set browsers to {"Google Chrome", "Firefox", "Opera", "Safari"}

A: You generally can't substitute a list for a string and have things work without some other changes.
A good way to get around this is to use a repeat with variable in list approach. This lets you go through each item in a list and run your code with each item in the list individually.
Here's how to apply that to your code:
set browsers to {"Google Chrome", "Firefox", "Opera", "Safari"}

repeat with browser in browsers
    if application browser is running then
        tell application browser
            activate
        end tell
        tell application "System Events"
            tell process browser
                keystroke "r" using {command down}
            end tell
        end tell
    end if
end repeat

Everything is the same except that your code is wrapped in a repeat with block and the "Safari" literal is replaced with browser, a reference to the current browser in the list of browsers (the code will be run once for each browser in the list).