text:
Q: Uncompress remote gz geojson file and return array of objects I am trying to use OSM Boundaries to get all US state and territory's boundary polygons in a front end app. It returns a gz archive. I have used axios to get the blob but I can't seem to find a way to extract it. I tried using browserify-zlib.
      const osmBoundURI = `https://osm-boundaries.com/Download/Submit?apiKey=${process.env.REACT_APP_OSM_BOUNDARIES_API_KEY}&osmIds=-148838&recursive&minAdminLevel=4&maxAdminLevel=4`;
      const states = await axios.get(osmBoundURI, {
        responseType: "blob",
        timeout: 30000,
      });


text:
Q: I am applying Max formula of excel using OpenPyXL but it is deleting formula on opening file Please note that I am applying MAX formula in a column through OpenPyXL.
The source data is also coming from Formula applied through OpenPyXL.
Problem is that it is deleting formula.
Some code given below:
#cumm profit
if(wsprofitrowno==2):
    wsprofit.cell(row=wsprofitrowno, column = 3).value = '=SUM(B2)'
else:

    wsprofit.cell(row=wsprofitrowno, column = 3).value = '=B%d+C%d' % (wsprofitrowno, wsprofitrowno-1)

#Peak
if(wsprofitrowno>2):
    wsprofit.cell(row=wsprofitrowno, column = 4).value = '=MAX($C$2:C%d' % (wsprofitrowno)
    wb.save("output.xlsx")
wsprofitrowno = wsprofitrowno + 1

A: You are trying to add this as a formula in the Excel cell '=MAX($C$2:C%d' % (wsprofitrowno) so Excel would see that as an error and the formula would be rejected. The Excel MAX function needs a closing bracket, since you are trying to use the row 'wsprofitrowno' as the row value for the second coordinate of the MAX formula you can do either

*

*Add the close bracket; '=MAX($C$2:C%d)' % wsprofitrowno

*just do '=MAX($C$2:C' + str(wsprofitrowno) + ')'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Having issues with file associations in Win 7 I am trying to link a file type to an app and it's not working. The file type does not show up in the list of known file types and when I go to "Open With" it does not save the app. This issue is not system wide and only happens with an EU's profile.

A: All information on associated file types is stored in the registry under the HKEY_CLASSES_ROOT Key, as described here.
So your file type has to be there, or the association will not work.
If you don't see your file type under this reg key, something is wrong.


text:
Q: Select a random item from a weighted list I am trying to write a program to select a random name from the US Census last name list. The list format is
Name           Weight Cumulative line
-----          -----  -----      -
SMITH          1.006  1.006      1
JOHNSON        0.810  1.816      2
WILLIAMS       0.699  2.515      3
JONES          0.621  3.136      4
BROWN          0.621  3.757      5
DAVIS          0.480  4.237      6

Assuming I load the data in to a structure like
Class Name
{
    public string Name {get; set;}
    public decimal Weight {get; set;}
    public decimal Cumulative {get; set;}
}

What data structure would be best to hold the list of names, and what would be the best way to select a random name from the list but have the distribution of names be the same as the real world.
I will only be working with the first 10,000 rows if it makes a difference in the data structure.
I have tried looking at some of the other questions about weighted randomness but I am having a bit of trouble turning theory in to code. I do not know much about math theory so I do not know if this is a "With or without replacement" random selection, I want the same name able to show up more than once, which ever that one means.

A: I've created a C# library for randomly selected weighted items.

*

*It implements both the tree-selection and walker alias method algorithms, to give the best performance for all use-cases.

*It is unit-tested and optimized.

*It has LINQ support.

*It's free and open-source, licensed under the MIT license.

Some example code:
IWeightedRandomizer<string> randomizer = new DynamicWeightedRandomizer<string>();
randomizer["Joe"] = 1;
randomizer["Ryan"] = 2;
randomizer["Jason"] = 2;

string name1 = randomizer.RandomWithReplacement();
//name1 has a 20% chance of being "Joe", 40% of "Ryan", 40% of "Jason"

string name2 = randomizer.RandomWithRemoval();
//Same as above, except whichever one was chosen has been removed from the list.

A: The "easiest" way to handle this would be to keep this in a list.
You could then just use:
Name GetRandomName(Random random, List<Name> names)
{
    double value = random.NextDouble() * names[names.Count-1].Culmitive;
    return names.Last(name => name.Culmitive <= value);
}

If speed is a concern, you could store a separate array of just the Culmitive values.  With this, you could use Array.BinarySearch to quickly find the appropriate index:
Name GetRandomName(Random random, List<Name> names, double[] culmitiveValues)
{
    double value = random.NextDouble() * names[names.Count-1].Culmitive;
    int index = Array.BinarySearch(culmitiveValues, value);
    if (index >= 0)
        index = ~index;

    return names[index];
}

Another option, which is probably the most efficient, would be to use something like one of the C5 Generic Collection Library's tree classes.  You could then use RangeFrom to find the appropriate name.  This has the advantage of not requiring a separate collection

A: I'd say an array (vectors if you prefer) would be best to hold them.  As for the weighted average, find the sum, pick a random number between zero and the sum, and pick the last name whose cumulative value is less. (e.g. here, <1.006 = smith, 1.006-1.816 = johnson, etc.
P.S. it's Cumulative.

A: Just for fun, and in no way optimal
List<Name> Names = //Load your structure into this

List<String> NameBank = new List<String>();
foreach(Name name in Names)
   for(int i = 0; i <= (int)(name.Weight*1000); i++)
     NameBank.Add(name.Name)

then:
String output = NameBank[rand(NameBank.Count)];


text:
Q: Find sum of radii of possible circles passing through $\left(a, \frac {1}{a}\right)$ Let $r_1$ and $r_2$ represent the radii of the smallest and the largest circle passing through $(a, \frac {1}{a})$
and touching the circle $$4x^2+4y^2-4x-8y-31=0$$ where $a$ is the least possible value of the ratio of sides of the regular $n$ sided polygon($n\ge 3$) inscribed and circumscribed to a unit circle then find the the value of $r_1+r_2$
My work:-
The side of the n sided polygon whose inradius is $1$ is $$\tan {\frac {\pi}{n}}$$ and the side of $n$ sided polygon if the circumradius is $1$ is $$\sin {\frac {\pi}{n}}$$
For the value of $a$ we need to find the minimum value of $$\sec \frac{\pi}{n}$$
Now for the circle to be the largest one, the given circle must touch it internally while the smallest circle must touch it externally.  But using this logic I am getting the wrong answer. Can someone please provide a bit better approach to such problem.

A: $$
{\text{side of the $n$-sided regular polygon inscribed in a unit circle}
\over
\text{side of the $n$-sided regular polygon circumscribed to a unit circle}}
=\cos{\pi\over n},
$$
the minimum $a={1\over2}$ being attained for $n=3$.
As the given circle has center $\big({1\over2},1\big)$ and radius $3$, the smallest and the largest circle passing through $(a,1/a)$ and touching the circle have diameters of $2$ and $4$ respectively.


text:
Q: Call base method from base function pointer with arguments I am using a Visitor pattern to traverse and print the children of the tree I am operating on. To get indented printing, I specify the indentation level in a style like:
printCurrent();
indentLevel();        // increases static variable
Visitor::visit(elem); // which then prints the children's node data
unindentLevel();      // decreases static variable

In order to make this nicer, I want to implement a function that takes the Visitor::visit with the argument elem and automatically handles the pre-action (indentLevel()) and post-action (unindentLevel()).
Before implementing that function, I need to define a function pointer that will be used as argument for the function. However, I am failing at specifying the argument to the pointer. As an example, let's look into the PrintVisitor which is derived from the Visitor:
void PrintVisitor::visit(BinaryExpr &elem) {
    std::cout << formatOutputStr({elem.getNodeName()});
    this->incrementLevel();
    Visitor::visit(elem);    // <-- this is where I want to create a function pointer to
    this->decrementLevel();
}

The idea basically is that the PrintVisitor does everything related to printing and all other logic (e.g., traversal logic) is implemented in the base class Visitor. Hence the PrintVisitor::visit needs to execute its specific action (e.g., printing via formatOutputStr) and then execute the Visitor::visit method:
void PrintVisitor::visit(BinaryExpr &elem) {
    std::cout << formatOutputStr({elem.getNodeName()});

    void (Visitor::*myPt)(BinaryExpr&) = &Visitor::visit;  // declare function pointer
    executeIndented(myPt, elem);  // pass function pointer myPt
}
// ...

void executeIndented("Function f", "FunctionArgs elem") {
   // pre-action
    this->incrementLevel();

   // main action: call function pointer
   (Visitor().*f)(elem);  // call function pointer with arg

   //post-action
   this->decrementLevel();
}

My goal is to somehow achieve that both pre- and post-action always are called in each PrintVisitor::visit method. For that I was thinking it would make sense to encapsulate these pre- and post-actions into another function executeIndented which ensures that.
The syntax of (Visitor().*myPt)(elem); looks a little odd to me, is this really the correct way to call the (base) function Visitor::visit with the argument elem using my function pointer myPt?
// EDIT
Using (Visitor(*this).*myPt)(elem); instead also works. What's the difference between those two ways and is either one of those to be preferred?
// EDIT2
Hope that the description of what I am trying to achieve is more clear now.

A: As I understand, you should have something like:
struct TraversalVisitor : IVisitor
{
    void visit(BinaryExpr &elem) final
    {
        pre_traversal_action(elem);
        visit(elem.lhs);
        action(elem);
        visit(elem.rhs);
        post_traversal_action(elem);
    }
    virtual void pre_traversal_action(BinaryExpr &elem) { /*Nothing */ }
    virtual void action(BinaryExpr &elem) { /*Nothing */ }
    virtual void post_traversal_action(BinaryExpr &elem) { /*Nothing */ }

    void visit(UnaryExpr &elem) final;
    // ...
};

struct PrintVisitor : TraversalVisitor
{
    void pre_traversal_action(BinaryExpr &elem) override {
        std::cout << formatOutputStr({elem.getNodeName()});
        incrementLevel();
    }
    //void action(BinaryExpr &elem) override { /*Nothing */ }
    void post_traversal_action(BinaryExpr &elem) override { decrementLevel(); }
    // ...
private:
    void formatOutputStr(const std::string&);
    void incrementLevel();
    void decrementLevel();
    // ...
};

Whereas you try to implement something like:
struct Visitor : IVisitor
{
    virtual visit(BinaryExpr &elem)
    {
        visit(elem.lhs);
        visit(elem.rhs);
    }
// ...
};

struct PrintVisitor : Visitor
{
private:
    void formatOutputStr(const std::string&);
    void incrementLevel();
    void decrementLevel();

    void executeIndented(Expr& elem) {
        incrementLevel(); // pre-action

        // Traversal
        Visitor::visit(elem);

        decrementLevel(); // post-action
    }

    void visit(BinaryExpr &elem) override {
        std::cout << formatOutputStr({elem.getNodeName()});

        executeIndented(elem);
    }

    // ...
};

Your attempt, IMO, just factorize PrintVisitor, without enforcing some traversal strategy.


text:
Q: "Tell, don't ask" when one class is doing and storing calculations with data from another Please tell me if I'm applying the Tell, dont't ask principle in right way in this example.
I have two classes, CalculationResults has a function calculateMe(), which uses Data to make some calculations. It is important that it stores the results.
class Data {
private:
  int dataForCalculations;
public:
  void calculate(CalculationResults& calculationResults) {
    calculationResults.calculateMe(dataForCalculations);
  }
};

class CalculationResults {
private:
  int calculatedData;
public:
  void calculateMe(int dataForCalculations) {
    calculatedData = someCalculations(dataForCalculations);
  }
};

// somewhere else:
Data data;
CalculationResults calculationResults;
data.calculate(calculationResults);

First version of this code (before applying Tell, don't ask) didn't use Data::calculate function but it has a getter for dataForCalculations, so somewhere I called calculationResults.calculateMe(data.getDataForCalculations()).
Is the new version better?

A:
Is the new version better?

That depends on who you ask.  But to be sure, the new version is 100% tell, don't ask.  It's easy to tell, because your methods return void.
Personally, I have had my run with trying to purely follow the tell, don't ask principle, and have given up on it for a couple reasons.
For one, the tell, don't ask principle can lead to conceptually confusing object interactions.  Take your code for example.  I wouldn't expect a Data object to be able to calculate itself. I would expect Data to be the input of something else.
As another example.  If I were writing a program that modeled making a call to someone, I might have a Phone, and PhoneNumber, and a Person object.  Now, according to tell, don't ask, you are supposed to ask the object with the data to accomplish a certain action.  So, in this case PhoneNumber might have a dial() method on it: phoneNumber.dial().  But does that make sense, conceptually?  Really, a Person dials a PhoneNumber into a Phone.
So, that's my first problem.  I find it harder to understand, and I find it more difficult to come up with natural interactions between object with tell, don't ask, which slows me down.
Secondly, often times it's not clear which object should be called first when two objects need to share data.  Take a Book and a Pen for example.  Do you say book.writeWith(pen) or pen.writeOn(book)?  Maybe an argument can be made with that example, but often times you'll find the difference is arbitrary, and I hate that.
Thirdly, with tell, don't ask, an object will slowly build up more and more responsibilities.  Do you tell the object to save itself?  Do you tell it to display itself?  What if you have more than one view technology?  What if you need to display your object in different formats?  Do you ask your object to email itself?  Having an object with many responsibilities isn't necessarily bad.  It's less flexible to change, but provides an easier to work with API.  However, most people prefer flexibility, and having an object with few responsibilities is part of SOLID code.
Fourthly, what really is the difference between having your object pass it's private's around to other objects by using tell, don't ask (when you need to share data), and having a getter?  Not much, if you ask me.
I know this is very oppinion based, but I prefer your first version better because it it simpler, and clearer. However, I would write it instead as:
calculationResults.calculate(data);

Anyways, just my 2 cents.


text:
Q: Open a SlideView picture with a Markerclicklistener How can i open a slideview picture by clicking on a marker in the map?
I already try to put the viewPager on a popupwindow, but didn't work. please help
MapsActiviy
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {

            LayoutInflater layoutInflater
                    = (LayoutInflater) getBaseContext()
                    .getSystemService(LAYOUT_INFLATER_SERVICE);
            View popupView = layoutInflater.inflate(R.layout.popupwindow, null);

            final PopupWindow popupWindow = new PopupWindow(
                    popupView,
                    LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);

            popupWindow.showAtLocation(findViewById(R.id.map), Gravity.CENTER_HORIZONTAL, 0, 0);

            ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
            ImageAdapter adapter = new ImageAdapter(this);
            viewPager.setAdapter(adapter);

            return false;
        }
    });


text:
Q: What is a Vector2 and Vector3 in Unity? Title says it all. I see them used in movement scripts often, if that helps. What is a Vector2 and a Vector3, the Unity docs are a bit hard to follow for new people.

A: Vector's are mathematical models that model both direction and magnitude. A Vector2 is 2D, and a Vector3 3D.
A vector2(1,5) is a direction with the ratio of 1 part x, and 5 parts y. E.G a line 1/6th to the right, and 5/6th's up. a negative would make the line left and down respectively.
Magnitude show's the "strength" of the direction. E.g when using forces and physics, pushing something in a vector2(1,0) is a much weaker push to the right than a vector2(100,0) even though the direction is identical.
That should be a basic theory introduction for you.

A: A Vector is basically a quantity which has a direction: The quantity is referred to as the magnitude of the vector, the direction is referred to as the normalized vector.
Vector is represented using its components: the projection of the vector on each axis is referred to as the components of the vector.

A Vector1 has a 1D direction, like a point on a line, or the value of a steering wheel, or any real number. e.g. (0) or (-1000). The magnitude of a Vector1 equals the absolute value of the x component of the vector or sqrt(x^2).

A Vector2 has a 2D direction, like a xy point in a 2D space, or the position of a joystick stick, or the uv offset of a point on a 2D texture. e.g. (0,0) or (-1, 100). The magnitude of a Vector2 equals sqrt(x^2+y^2).

A Vector3 has a 3D direction, like a xyz point in a 3D space, or a color in RGB format, or a set of three numbers. e.g. (0,0,0) or (-0.1, 3.14, 30). The magnitude of a Vector3 equals sqrt(x^2+y^2+z^2).

A Vector4 has a 4D direction, like a xyzw point in a 4D space, or a color in RGBA format, or a set of four numbers. e.g. (0,0,0,0) or (0.1, 0.2, 0.3, 0.4). The magnitude of a Vector4 equals sqrt(x^2+y^2+z^2+w^2).

A: Vector2
It is representation of 2D vectors and points, used to represent 2D positions, only two axis x&y.
Code Examples
for Positive values
Debug.log(new Vector2(1, 2) - new Vector2(3, 2));
for Negative values
print(-new Vector2(1, 2));
Vector3
It is representation of 3D vectors and points, used to represent 3D positions,considering x,y & z axis.
Code Examples
Vector3  offset = transform.position - player.transform.position;
1.transform.Translate(Vector3.forward * Time.deltaTime * speed)

*

*Debug.Log(Cube.transform.rotation) //cube is the Gameobject


text:
Q: ionic app unable to connect to localhost I am working on a project that allows Android Built Ionic version 2 app to create user and authenticate to a Django dev site through Django Rest API.
The authentication works when using ionic serve this was achieved through the use of Cross Origin Resource Sharing (installed as google chrome plugin).
As I've tried to run the application on an actual android device, the authentication fails (HTTP 404: URL not found) when using the app but the localhost can be accessed through browser of the same device (through 192.168.22.4:80).
Details:
My current private IP address is 192.168.22.4 and the dev site is currently being served at the localhost port 80 through Wamp Apache Server.
Here is the code fragment of my http request on Ionic App (signup):
let headers = new Headers();
      headers.append('Content-Type','application/json');

      this.http.post("http://192.168.22.4:80/api-user-create", JSON.stringify(this.postData), {headers: headers}).subscribe(res => {
        console.log(res.json());
        this.showAlert();
      }, (err) => {
        console.log(err);
      });

Applied Solutions:
These are the steps that I have tried but still failed to connect to the localhost:

*

*Ensure that the app is allowed to access to WiFi connection, verify whether my IP address is correct, turned off my firewall and even my antivirus. I have also enabled network discovery on my dev server.

*Use proxy server (ngrok) and edit Ionic request

*Enable CORS on Apache Server and edit Ionic request

*Edit Ionic request code. I have tried to changed 192.168.22.4:80 to:

*

*192.168.22.4

*127.0.0.1:80

*127.0.0.1

*localhost:80

*localhost

*10.0.2.2

*10.0.2.2:80
Has anyone encountered this problem and solved it?

A: Problem solved!
I have solved it by:

*

*Make wamp listen to the < ip address >:< port number >. It was initially set to 0.0.0.0:80 by default. To configure, I updated the httpd.conf on my wamp server then added the line:
Listen 192.168.22.4:80

*install cordova-plugin-whitelist on my ionic project. To do this, I have to run:
cordova plugin add cordova-plugin-whitelist --save

*edit my Ionic code and removed the port number to the request:
  let headers = new Headers();
  headers.append('Content-Type','application/json');

  this.http.post("http://192.168.22.4/api-user-create", JSON.stringify(this.postData), {headers: headers}).subscribe(res => {
    console.log(res.json());
    this.showAlert();
  }, (err) => {
    console.log(err);
  });

*rebuild and run the application
Read Ionic App - No Internet Access for more information.


text:
Q: When knitting HTML from Rmd file, datapoints in plot disappear When I put together my Rmd-file for a report and print out the code, the plot appears exactly they I want it. But when I knit it to HTML, the datapoints in the plot disappear. Anyone with a potential idea, why this could be the case?
See my Rmd chunk below:
{r position_per_year, message=FALSE, warning=FALSE, include=FALSE, fig.show='asis'}
# Position reached per year
position_2007 <- gp_2007 %>%
  group_by(location, surname) %>%
  summarise(position = as.numeric(positionText), .groups = "drop") %>%
  ungroup() %>%
  ggplot(aes(
    x = location,
    y = position,
    group = surname,
    color = surname,
  )) +
  geom_point() +
  geom_line() +
  scale_y_reverse(breaks = seq(24, 1), limits = c(24,1)) +
  scale_x_discrete(guide = guide_axis(angle = 90)) +
  xlab("GP Location") +
  ylab("Place reached")

In R-Markdown the plot appearing through
print(position_2007)

is as following:

whereas when the plot is shown in the knitted HTML it looks like this (datapoints simply disappear):

If someone has an idea on what could be the problem, this would be highly appreciated!
Edit (on request):
gp_2007 is the following dataframe:

dput(gp_2007)

delivers the following ouput:
structure(list(positionText = c("9", "3", "4", "R", "1", "3",
"4", "1", "5", "1", "2", "3", "1", "2", "7", "2", "2", "3", "3",
"3", "1", "2", "5", "7", "1", "1", "2", "3", "2", "2", "R", "7",
"1", "2"), positionOrder = c(9L, 3L, 4L, 19L, 1L, 3L, 4L, 1L,
5L, 1L, 2L, 3L, 1L, 2L, 7L, 2L, 2L, 3L, 3L, 3L, 1L, 2L, 5L, 7L,
1L, 1L, 2L, 3L, 2L, 2L, 21L, 7L, 1L, 2L), points = c(0, 6, 5,
0, 10, 6, 5, 10, 4, 10, 8, 6, 10, 8, 2, 8, 8, 6, 6, 6, 10, 8,
4, 2, 10, 10, 8, 6, 8, 8, 0, 2, 10, 8), rank = c("3", "4", "4",
"19", "1", "6", "3", "2", "3", "2", "3", "3", "1", "3", "1",
"2", "2", "4", "3", "3", "1", "2", "4", "2", "2", "2", "1", "4",
"2", "2", "2", "3", "2", "2"), year = c(2007L, 2007L, 2007L,
2007L, 2007L, 2007L, 2007L, 2007L, 2007L, 2007L, 2007L, 2007L,
2007L, 2007L, 2007L, 2007L, 2007L, 2007L, 2007L, 2007L, 2007L,
2007L, 2007L, 2007L, 2007L, 2007L, 2007L, 2007L, 2007L, 2007L,
2007L, 2007L, 2007L, 2007L), round = c(10L, 8L, 14L, 16L, 5L,
17L, 11L, 11L, 12L, 6L, 9L, 4L, 13L, 7L, 6L, 16L, 4L, 9L, 14L,
1L, 15L, 13L, 3L, 17L, 7L, 10L, 2L, 12L, 1L, 5L, 15L, 8L, 2L,
3L), gp = c("European Grand Prix", "French Grand Prix", "Belgian Grand Prix",
"Chinese Grand Prix", "Monaco Grand Prix", "Brazilian Grand Prix",
"Hungarian Grand Prix", "Hungarian Grand Prix", "Turkish Grand Prix",
"Canadian Grand Prix", "British Grand Prix", "Spanish Grand Prix",
"Italian Grand Prix", "United States Grand Prix", "Canadian Grand Prix",
"Chinese Grand Prix", "Spanish Grand Prix", "British Grand Prix",
"Belgian Grand Prix", "Australian Grand Prix", "Japanese Grand Prix",
"Italian Grand Prix", "Bahrain Grand Prix", "Brazilian Grand Prix",
"United States Grand Prix", "European Grand Prix", "Malaysian Grand Prix",
"Turkish Grand Prix", "Australian Grand Prix", "Monaco Grand Prix",
"Japanese Grand Prix", "French Grand Prix", "Malaysian Grand Prix",
"Bahrain Grand Prix"), date = c("2007-07-22", "2007-07-01", "2007-09-16",
"2007-10-07", "2007-05-27", "2007-10-21", "2007-08-05", "2007-08-05",
"2007-08-26", "2007-06-10", "2007-07-08", "2007-05-13", "2007-09-09",
"2007-06-17", "2007-06-10", "2007-10-07", "2007-05-13", "2007-07-08",
"2007-09-16", "2007-03-18", "2007-09-30", "2007-09-09", "2007-04-15",
"2007-10-21", "2007-06-17", "2007-07-22", "2007-04-08", "2007-08-26",
"2007-03-18", "2007-05-27", "2007-09-30", "2007-07-01", "2007-04-08",
"2007-04-15"), gp_place = c("Nürburgring", "Circuit de Nevers Magny-Cours",
"Circuit de Spa-Francorchamps", "Shanghai International Circuit",
"Circuit de Monaco", "Autódromo José Carlos Pace", "Hungaroring",
"Hungaroring", "Istanbul Park", "Circuit Gilles Villeneuve",
"Silverstone Circuit", "Circuit de Barcelona-Catalunya", "Autodromo Nazionale di Monza",
"Indianapolis Motor Speedway", "Circuit Gilles Villeneuve", "Shanghai International Circuit",
"Circuit de Barcelona-Catalunya", "Silverstone Circuit", "Circuit de Spa-Francorchamps",
"Albert Park Grand Prix Circuit", "Fuji Speedway", "Autodromo Nazionale di Monza",
"Bahrain International Circuit", "Autódromo José Carlos Pace",
"Indianapolis Motor Speedway", "Nürburgring", "Sepang International Circuit",
"Istanbul Park", "Albert Park Grand Prix Circuit", "Circuit de Monaco",
"Fuji Speedway", "Circuit de Nevers Magny-Cours", "Sepang International Circuit",
"Bahrain International Circuit"), location = c("Nürburg", "Magny Cours",
"Spa", "Shanghai", "Monte-Carlo", "São Paulo", "Budapest", "Budapest",
"Istanbul", "Montreal", "Silverstone", "Montmeló", "Monza",
"Indianapolis", "Montreal", "Shanghai", "Montmeló", "Silverstone",
"Spa", "Melbourne", "Oyama", "Monza", "Sakhir", "São Paulo",
"Indianapolis", "Nürburg", "Kuala Lumpur", "Istanbul", "Melbourne",
"Monte-Carlo", "Oyama", "Magny Cours", "Kuala Lumpur", "Sakhir"
), country = c("Germany", "France", "Belgium", "China", "Monaco",
"Brazil", "Hungary", "Hungary", "Turkey", "Canada", "UK", "Spain",
"Italy", "USA", "Canada", "China", "Spain", "UK", "Belgium",
"Australia", "Japan", "Italy", "Bahrain", "Brazil", "USA", "Germany",
"Malaysia", "Turkey", "Australia", "Monaco", "Japan", "France",
"Malaysia", "Bahrain"), forename = c("Lewis", "Lewis", "Lewis",
"Lewis", "Fernando", "Fernando", "Fernando", "Lewis", "Lewis",
"Lewis", "Fernando", "Fernando", "Fernando", "Fernando", "Fernando",
"Fernando", "Lewis", "Lewis", "Fernando", "Lewis", "Lewis", "Lewis",
"Fernando", "Lewis", "Lewis", "Fernando", "Lewis", "Fernando",
"Fernando", "Lewis", "Fernando", "Fernando", "Fernando", "Lewis"
), surname = c("Hamilton", "Hamilton", "Hamilton", "Hamilton",
"Alonso", "Alonso", "Alonso", "Hamilton", "Hamilton", "Hamilton",
"Alonso", "Alonso", "Alonso", "Alonso", "Alonso", "Alonso", "Hamilton",
"Hamilton", "Alonso", "Hamilton", "Hamilton", "Hamilton", "Alonso",
"Hamilton", "Hamilton", "Alonso", "Hamilton", "Alonso", "Alonso",
"Hamilton", "Alonso", "Alonso", "Alonso", "Hamilton"), name = c("McLaren",
"McLaren", "McLaren", "McLaren", "McLaren", "McLaren", "McLaren",
"McLaren", "McLaren", "McLaren", "McLaren", "McLaren", "McLaren",
"McLaren", "McLaren", "McLaren", "McLaren", "McLaren", "McLaren",
"McLaren", "McLaren", "McLaren", "McLaren", "McLaren", "McLaren",
"McLaren", "McLaren", "McLaren", "McLaren", "McLaren", "McLaren",
"McLaren", "McLaren", "McLaren")), row.names = c(13L, 41L, 44L,
89L, 132L, 150L, 159L, 231L, 251L, 305L, 314L, 315L, 341L, 361L,
363L, 384L, 387L, 430L, 466L, 486L, 493L, 512L, 581L, 599L, 635L,
649L, 672L, 704L, 759L, 768L, 769L, 801L, 826L, 838L), class = "data.frame")

Edit 2 (on request):
The dataframe "Hamilton_Alonso" looks as following (screenshot only shows first 43 of 668 rows):

A: Without data to test, I'm doing this blindly. The point is to remove the duplication of the same code for each year by using purrr::map() to run the same bit of code for each year.
Then for the chart, I'd recommend using patchwork instead of gridExtra to combine charts together.
library(purrr)

Hamilton_Alonso_plot_dfl <- Hamilton_Alonso |>
  filter(year %in% c(2007:2018, 2021:2022)) |>
  group_split(year) |>
  map(function(x) { x |>
    group_by(location, surname) |>
      summarise(total_points = sum(points),
                position = as.numeric(positionText),
                .groups = "drop")
  })

library(patchwork)

make_charts <- function(x, year) {
  points_chart <- ggplot(x, aes(
      x = location,
      y = total_points,
      group = surname,
      color = surname
    )) +
    geom_bar(aes(fill = surname), position = position_dodge2(width = 0.5, preserve = "single"), stat = "identity", alpha = 0.2) +
    geom_smooth(se = FALSE) +
    scale_y_continuous(breaks = seq(0, 50, 1), limits = c(0,25)) +
    scale_x_discrete(guide = guide_axis(angle = 90)) +
    xlab("GP Location") +
    ylab("Points collected")

 positions_chart <- ggplot(x, aes(
   x = location,
   y = position,
   group = surname,
   color = surname,
 )) +
   geom_point() +
   geom_line() +
   scale_y_reverse(breaks = seq(24, 1), limits = c(24,1)) +
   scale_x_discrete(guide = guide_axis(angle = 90)) +
   xlab("GP Location") +
   ylab("Place reached")

 points_chart + positions_chart + plot_annotation(title = year)
}

map2(Hamilton_Alonso_plot_dfl, c(2007:2018, 2021:2022), make_charts)


text:
Q: How to do a git diff between branches and exclude one file This should be simple for someone, i just can't seem to get the right syntax.   The situation is I have checked out one of my colleagues branches and I want to see the difference between this branch and the dev branch however I don't want to see the changes in one particular file (because it's a huge file).  Here is what I have tried:
git diff origin/dev ':(exclude)package-lock.json'

git diff ':(exclude)package-lock.json' origin/dev

git diff -- . ':(exclude)package-lock.json' origin/dev

I know I'm close...
Note... I have been told that this question is a possible duplicate of this one: Want to exclude file from "git diff"  however this is not the case.  The accepted answer of that question is this:
git diff -- . ':(exclude)db/irrelevant.php'

however when i run this command on my system:
git diff -- . ':(exclude)package-lock.json'

I get nothing.  The reason I get nothing is likely due to the fact that in this command It is never specified that I want a diff between my current branch and origin/dev.  What i want is similar to the above answer but also indicating the difference between the current branch and a remote branch.

A: The following works for me:
git diff branchname -- ':(exclude)filename'

A: You have to list paths last.  You have to have an include path to have exclude paths.  Some of your attempts do each of these, but none do all :)
git diff origin/dev -- . ':!/package-lock.json'


text:
Q: My gravatar disappeared....and cannot be selected in profile picture change area....how can I get it back? This issue seems to be different from others reported previously in the Meta SE (and I have looked at them all).  These things I identify in this message.
Without having changed my profile (or email address) in since I have been a SE member (about 6 years), my gravatar (which I grew attached to) disappeared and something else popped up apparently called an Identicon from my readings here.  I have used my common profile on all SE sites all had identical email addresses.
I understand from reading other meta SE entries that gravatar and identicon apparently are different.  The Gravatar uses email addresses, and the Identicon uses IP addresses.  I can assure you that I have used a fair quantity of IP addresses over the years to access the site for periods of time but the avatar assigned to my name never changed (till now).  Thus I would have expected the Identicon to have changed over these periods of time.
I tried to select my original gravatar under the profile picture option.  As was posted in another Meta SE posting to no avail.  The gravatar was not available as an option when attempting to change it.  The Identicon option was present however.  This is for ALL SE sites not just a single one.  As the postings of the Meta SEs seem to have this isolated to one site being different from another.
The lack of a gravitar under the selection seems puzzling since I have had the same email in my common profile without change.  So one question is why I don't have a gravitar selection but to have an identicon selection under my profile conditions?
I'm confused as my (valid) email address has been previously used in a couple of SE communications and again has not changed since I created my initial Server Fault account over five years ago.  This issue was listed in yet another Meta SE posting but not true.
I tried to set the email address to the same thing that I had it, but the gravatar did not return.
Because I could not return my Gravatar, I uploaded a cute picture until I could get a resolution.
What am I missing here?
NOTE: Remember the question...how can I get it back within the SE framework?
Thanks.

A: Of course the answer is to copy the original one from the TimeMachine and paste that into the profile picture.
My whole goal in writing my problem was to try to get this back using the mechanisms within SE.  The Gravaton was never a selection on the profile change but the Identicon was.
WHY NOT?
I understand why the Identicon would change, but not my Gravaton and why it would not be available to me since it should not have changed, my email has remained static for over 6 years.


text:
Q: SQL Query: Binary Fields on Dates for Time Series I have a table that looks like the following:
ID  |  Date
1   |  2010-01-01
2   |  2010-02-01
3   |  2010-02-15
2   |  2010-02-15
4   |  2010-03-01

I am having trouble creating a table with the IDs as rows, and Time periods as columns.  For a given time period, I would like to place a 1 if that ID has an associated date in that period, and a 0 if not.
So the output might look like:
ID  |  Jan-10  |  Feb-10  |  Mar-10
1   |  1       |  0       |  0
2   |  0       |  1       |  0
3   |  0       |  1       |  0
4   |  0       |  0       |  1

What is the best way to accomplish this?
I have created a new table containing all distinct IDs from the table above in anticipation of a join---but I'm not sure how to handle the 1/0s.

A: You can do this with a simple group by and conditional aggregation:
select id,
       max(case when month(t.date) = 1 and year(t.date) = 2010 then 1 else 0 end) as "Jan-10",
       max(case when month(t.date) = 2 and year(t.date) = 2010 then 1 else 0 end) as "Feb-10",
       max(case when month(t.date) = 3 and year(t.date) = 2010 then 1 else 0 end) as "Mar-10"
from "table" t
group by id;

Because you have so many time periods, I would generate the code for the column using formulas in Excel (or your favorite spreadsheet).


text:
Q: Does it make sense to test with intermediate Ruby versions? If a project passes the tests in Ruby 2.0.0-p648 and Ruby 2.3.1, does it make sense to also test with versions such as 2.1.8 and 2.2.3?
Has there been any language features that worked in Ruby 2.0 and Ruby 2.3 but were temporarily not working or worked differently in for example Ruby 2.2?

A: You should test your code for environments you intend it to be used in. Ruby language version is one thing that can vary. You might also consider testing against JRuby and Rubinius if your code is supposed to support it - e.g. it is provided as a public gem.
Logically, testing on earliest and latest versions should cover most failure scenarios with respect to language features (although not necessarily all language bugs since new ones can be introduced). As far as I know there has not been a Ruby feature that was deliberately added or removed in one version and then that decision reversed in a later version. Unless: Perhaps in your production code you are detecting a feature's existence and then using the feature in full - in which case an intermediate Ruby version which has the feature but not in its latest state could fail.
There may be other caveats too, and philosophically speaking when you start testing you want to avoid too much logical "this should work because . . ." thinking. The point of testing is to demonstrate that your code doesn't fail in ways you have covered (well, there's more depth to it than that, but the answer would get far too long if it dove into test philosophies). If you want to declare "works in all versions of Ruby MRI from 2.0.0 to 2.3.1" then you will feel safer making that statement if you have actually tested it. In fact when making such a statement in a public place, I would usually just say something closer to raw fact - "tested in versions 2.0.0, 2.1.4 and 2.3.1".
Obviously there are diminishing returns. If you have no problem in 2.1.9, it is very unlikely you will have a problem in 2.1.10 - at some point it will cost you more to check every minor variation, even just to look at the test results, than the benefit of extra coverage.
The usual answer to this problem is to test as many variations as your automated test environment can handle and you can be bothered to set up and maintain. If using multiple versions of Ruby is done for you in parallel by your test service provider - e.g. you are using Travis - then it is relatively cheap to test multiple versions. So you may as well get as much coverage on environment variations that you expect to see "in the wild" as you can be bothered to look at.


text:
Q: Tapestry: When should a Session State Object be preferred to a Session Attribute? From the Tapestry doc I seem to understand that a field annotated with @SessionAttribute and a field annotated with @SessionState work in the same way, except that @SessionAttribute stores the value by name (and the name can be specified), which means that different instances of the same class can be stored, while @SessionState stores the value by type so storing different instances of the same class will not work, the new instance will always overwrite the old one (even if the two are different fields with different name and from different classes).
So it seems that @SessionState doesn't offer any advantage over @SessionAttribute, only limitations, but I'm probably missing something. I'm not able to figure out any case where using @SessionState could be more advisable than @SessionAttribute for any reason.
Are there such cases ?

A: @SessionAttribute is largely intended for some interop cases, where some other, non-Tapestry code (another servlet) is expecting the data to be stored using an explicitly specified name.
@SessionState's advantage is that the name is automatically determined from the type ... one less thing to care about, and more amenable to refactoring.


text:
Q: Changing fontsize within soul underline This question is related to How to create a newcommand for fontsize?.
I would like to change the fontsize within \ul of the soul package. For example:
\newcommand{\mycfs}[1]{\fontsize{#1pt}{1.2#1pt}\selectfont}
\soulregister{\mycfs}{1}

\ul{{\mycfs{6} Size 6 font} Normal size font}

This error message occurs: ! Package soul Error: Reconstruction failed.
How can this be fixed?

A: I would change the definition of \mycfs so that it no longer has an argument:
\documentclass{book}
\usepackage{soul}

\newcommand\mycfs{\fontsize{\mysize}{\the\dimexpr \mysize*1.2\relax}\selectfont}
\newcommand\mysetsize[1]{\edef\mysize{#1pt}}
\soulregister{\mycfs}{0}

\begin{document}
\mysetsize{6}

\ul{\mycfs Size 6 font} Normal size font
\end{document}

A: \mbox could already fix it for you:
\documentclass{book}
\usepackage{soul}
\newlength{\mysize}
\newcommand{\mycfs}[1]{\setlength{\mysize}{#1pt}%
  \fontsize{\mysize}{1.2\mysize}\selectfont}
\begin{document}
text

\ul{\mbox{\mycfs{6}Size 6 font} Normal size font}

text
\end{document}

Output:


text:
Q: Prevent Daemon pausing when iPhone locks Developing a daemon for jailbroken iDevices.
It's supposed to run when the iPhone is locked. However, the process seems to be put on hold after a little under a minute when the iPhone is locked (as seen by considering the "Total Process Running Time" given by CocoaTop). How can I prevent this, and make the daemon run all the time?
I'm sure this is possible, since when the phone is charging (plugged in) the daemon is not paused, and I see it working.

A: Wrapped the main method of the daemon in what's described here under Listing 2


text:
Q: how to change Cypher isolation level to uncommitted it seems that neo4j opens a transaction for simple match queries.
for example:
match (h:Event) return min(h.date_time),max(h.date_time)

is it possible to change it, so it will read from uncommitted data?

A: If you use the transactional Cypher HTTP endpoint, you can execute multiple Cypher statements (queries) within the same transaction, and subsequent statements can see the uncommitted data from previous statements.


text:
Q: How to solve "Encountered the symbol "end-of-file" when expecting one of the following: " in sql How should I end the transaction below so that I don't receive anymore the error:

Line/Col: 30/19 PLS-00103: Encountered the symbol "end-of-file" when
  expecting one of the following:
( begin case declare end exception exit for goto if loop mod
  null pragma raise return select update while with
       <<
  continue close current delete fetch lock    insert open rollback
  savepoint set sql execute commit forall    merge pipe purge
  json_exists json_value json_query    json_object json_array

create or replace function ueberweisung (a varchar2, b varchar2,c number)

RETURN varchar2 IS
pragma autonomous_transaction;
k1 number; -- Variablendeklaration
k2 number;

BEGIN

SELECT saldo into k1
FROM konto
WHERE konto_nr=a;

SELECT saldo into k2
FROM konto
WHERE konto_nr=b;

k1:=k1-c;
k2:=k2+c;
begin transaction;
update konto
set saldo = case konto_nr
when a then k1
when b then k2
else saldo
end;
commit;
RETURN (c ||' Eur überwiesen von Konto ' || a || 'auf Konto ' || b);
END ueberweisung;

A: "begin transaction" is t-sql, not Oracle pl/sql.
It is interpreted as "begin" with label "transaction".
There is no matching "end" with this "begin".
Solution: remove this line, since it is unnecessary anyway.


text:
Q: How to correctly solve browser Cache With Gulp-Rev and Gulp-Rev-Collector so that my index.html file is updated I am building an angular2 project using systemJS. I use Gulp to deploy.
I want to avoid making my users click on ( Cntl + R ) to get rid of the cached css files.
To do that, I wanted to make file revision using Gulp.
Knowing that all I need, is changing a css file for the moment. so I am using :

*

*gulp-rev , to rename my files and to create my manifest.json

*gulp-rev-collector , to replace these files name from where we call them using our manifest

*rev-del, to delete the old files.

knowing that my css file is under a folder named : public. and my index.html is also under public/.
    gulp.task("revision:rename", function () {
     return gulp.src(["public/*.css"])
     .pipe(rev())
     // .pipe(revDel())
     .pipe(gulp.dest('public'))
     .pipe(rev.manifest())
     .pipe(gulp.dest("public"))
    });

   gulp.task("revision:updateReferences", ["revision:rename"], function () {
      gulp.src(["public/rev-manifest.json","public/*.css"])
      .pipe(collect({
          replaceReved: true,
          dirReplacements: {
              'css': 'public'
          }
      }))
      .pipe(gulp.dest("public"))
   });

Calling these functions, I get correctly css files renamed, and a correct manifest.json.
But I got two problems,

*

*The collector doesnt replace my html file. And I don't know how to deal with that

*The rev-del, makes an error  when I use it ( I commented it for the moment )

Any help will be appreciated !
Thank you

A: 1) For the delete part:
You can also use this lib
const revDelete = require('gulp-rev-delete-original');
and call it like ".pipe(revDelete())" after calling .pipe(rev())
2) For the reference part (update new hash references):
I use gulp-rev-replace lib
const revReplace = require('gulp-rev-replace');
and call it like ".pipe(revReplace())" after ".pipe(revDelete())"
I see that you found a solution, but, just showing an alternative, maybe it's useful in the future.

A: It appeared I didn't use the collector correctly :
Now it works with :
gulp.task("revision:updateCSS", ["revision:rename"], function () {
   gulp.src(["public/rev-manifest.json","public/index.html"])
   .pipe(collect({
       replaceReved: false
   }))
   .pipe(gulp.dest("public"))
});

I posted the answer in case someone is struggling.


text:
Q: Ionic Android permission always returns false I am using ionic 3.15 and trying to use the permissions plugin.
Using the code in the docs as mentioned here.
I have the code as shown in the docs but will mention it again here.
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.CAMERA).then(
  success => console.log('Permission granted'),
  err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.CAMERA)
);

I always get hasPermission: false.
I do not get any prompt for turning the permissions on.
What is to be done here I am clueless.
Thanks.

A: You need to add something along the lines of:
this.androidPermissions.requestPermissions(
        [
          this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE,
          this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE
        ]
      );

You check to see if you have permissions, if it is false, then execute the above code to prompt the user to allow.

A: It seems like you have to make sure that you are using the permission you requested. Otherwise no prompt will be shown and the androidPermissions.requestPermissions will immediately return false.
From the docs:

Android 26 and above: due to Android 26's changes to permissions handling (permissions are requested at time of use rather than at runtime,) if your app does not include any functions (eg. other Ionic Native plugins) that utilize a particular permission, then requestPermission() and requestPermissions() will resolve immediately with no prompt shown to the user. Thus, you must include a function utilizing the feature you would like to use before requesting permission for it.


text:
Q: error while sendin http PUt to creat a new page in xwiki with REST api i want to send a page to xwiki with
$ curl -u Admin:admin -X PUT --data-binary "@newPage.xml"
-H "Content-Type: application/xml" http://localhost:8082/xwiki/rest/wikis/xwiki/spaces/Main/pages/NewPage
my xml page is like that:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<page xmlns="http://www.xwiki.org">
    <title>Hello world</title>
    <syntax>xwiki/2.0</syntax>
    <content>This is a new page</content></page>

but this commands return a huge code error ,anyone knows thye reason why , just for information sending just the content work without problem
error:
org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException:   Could not convert the message body to a org.xwiki.rest.model.jaxb.Page at org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationExcept ion.object(ConvertRepresentationException.java:58)at org.restlet.ext.jaxrs.internal.wrappers.params.EntityGetter.getValue(EntityGetter.java:115)at org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.get(ParameterList.java:1090)at org.restlet.ext.jaxrs.internal.wrappers.AbstractMethodWrapper.internalInvoke(AbstractMethodWrapper.java:169)at org.restlet.ext.jaxrs.internal.wrappers.ResourceMethod.invoke(ResourceMethod.java:291)at org.restlet.ext.jaxrs.JaxRsRestlet.invokeMethod(JaxRsRestlet.java:1043)
    at org.restlet.ext.jaxrs.JaxRsRestlet.handle(JaxRsRestlet.java:792)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.routing.Router.doHandle(Router.java:500)
    at org.restlet.routing.Router.handle(Router.java:740)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.engine.application.StatusFilter.doHandle(StatusFilter.java:154)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.engine.ChainHelper.handle(ChainHelper.java:114)
    at org.restlet.engine.application.ApplicationHelper.handle(ApplicationHelper.java:75)
    at org.restlet.Application.handle(Application.java:391)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.routing.Router.doHandle(Router.java:500)
    at org.restlet.routing.Router.handle(Router.java:740)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.routing.Router.doHandle(Router.java:500)
    at org.restlet.routing.Router.handle(Router.java:740)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.engine.ChainHelper.handle(ChainHelper.java:114)
    at org.restlet.Component.handle(Component.java:391)
    at org.restlet.Server.handle(Server.java:491)
    at org.restlet.engine.ServerHelper.handle(ServerHelper.java:74)
    at org.restlet.engine.http.HttpServerHelper.handle(HttpServerHelper.java:153)
    at org.restlet.ext.servlet.ServerServlet.service(ServerServlet.java:1031)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:769)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1667)
    at org.xwiki.wysiwyg.server.filter.XWikiContextInitializationFilter.doFilter(XWikiContextInitializationFilter.java:85)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
    at org.xwiki.container.servlet.filters.internal.SetHTTPHeaderFilter.doFilter(SetHTTPHeaderFilter.java:63)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
    at com.xpn.xwiki.plugin.webdav.XWikiDavFilter.doFilter(XWikiDavFilter.java:66)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
    at org.xwiki.container.servlet.filters.internal.SavedRequestRestorerFilter.doFilter(SavedRequestRestorerFilter.java:208)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
    at org.xwiki.container.servlet.filters.internal.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:111)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
    at org.xwiki.resource.servlet.RoutingFilter.doFilter(RoutingFilter.java:137)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1125)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1059)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:497)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:248)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:610)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:539)
    at java.lang.Thread.run(Unknown Source)Caused by: java.io.IOException: Could not unmarshal to org.xwiki.rest.model.jaxb.Page
    at org.restlet.ext.jaxrs.internal.provider.JaxbProvider.readFrom(JaxbProvider.java:197)
    at org.restlet.ext.jaxrs.internal.wrappers.provider.SingletonProvider.readFrom(SingletonProvider.java:304)
    at org.restlet.ext.jaxrs.internal.wrappers.params.EntityGetter.getValue(EntityGetter.java:109)
    ... 75 more

thanks everyone

A: finally done with
$ curl -X PUT -u admin:admin  -T "@newPage.xml" -H "Content-Type: application/xml" http://localhost:8080/xwiki/rest/wikis/xwiki/
spaces/Main/pages/newpPage


text:
Q: Initializing and passing child class types as parameters to function interfaces in Java I want to learn if there's a way to create a method to generalize the way we handle incoming requests by using function variables and reflectivity of classes.
To make things more clear let's say I have the following class and it's children:
public class ParentClassRequest implements Serializable {
    private String name;
}

public class ChildClassOneRequest extends ParentClassRequest implements Serializable {
    private Integer money;
}

public class ChildClassTwoRequest extends ParentClassRequest implements Serializable {
    private Integer candy;
}

public class ParentClassResponse implements Serializable {
    private String name;
}

public class ChildClassOneResponse extends ParentClassResponse implements Serializable {
    private Integer money;
}

public class ChildClassTwoResponse extends ParentClassResponse implements Serializable {
    private Integer candy;
}

And I have the following adapter classes and methods:

@Service
public class PersonSender {

    public ChildClassOneResponse childClassOneSender(final ChildClassOneRequest childClassOne) {

        final ChildClassOneResponse childClassOneResponse = new ChildClassOneResponse();
        childClassOneResponse.setMoney = childClassOne.getMoney;

        return childClassOneResponse
    }

    public ChildClassTwoResponse childClassTwoSender(final ChildClassTwo childClassTwoRequ) {

        final ChildClassTwoResponse childClassTwoResponse = new ChildClassTwoResponse();
        childClassTwoResponse.setCandy = childClassTwo.getCandy;

        return childClassTwoResponse
    }

}

I want to create a service class in a way to generalize the parameters such that:
public class TransportationService {

    // I have a session, I get the request using this
    @Autowired
    private Session session;

    public ParentClassRequest transport(
            Class<? extends ParentClassRequest> childClassRequestClass,
            Class<? extends ParentClassResponse> childClassResponseClass,
            Function<? extends ParentClassRequest, ? extends ParentClassResponse> adapterMethod) {

        //I need to declare the variable with the given type here and initialize it with the function given

        final childClassRequestClass request = session.get(childClassRequestClass);
        request.setName = "Test";

        final childClassResponseClass response = Function.apply(request);

        return response;
    }
}

So I can just call this function and pass the classes and the method as:
TransportationService.transport(ChildClassOneRequest.class, ChildClassOneResponse.class, PersonSender::childClassOneSender)

TransportationService.transport(ChildClassTwoRequest.class, ChildClassTwoResponse.class, PersonSender::childClassTwoSender)

However, there are two problems. First, I think I cannot pass functions with generic types. I get Incompatible types: ParentClassRequest is not convertible to ChildClassOneRequest. Secondly, I cannot declare a new variable of the class type given as a parameter. I want to declare it so I can change some fields and send it to the adapter using the passed-in method. I think I am not able to achieve these. Any help or pointers would be beneficial. If this is not possible, I can try a pattern to solve this issue, but I hope to achieve everything using these.


text:
Q: Yii2: Show field/checkbox after checkbox is selected I have an ActiveForm in my _form view:
<?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'isInternal')->checkbox() ?> <?php ActiveForm::end(); ?>

('isInternal' is a boolean)
If the checkbox is selected I want to show another checkbox:
$form->field($model, 'activateReminder')->checkbox();

Is there a possibility? Maybe with JavaScript like this?
 <?= $form->field($model, 'isInternal')->checkbox(['onclick' =>
 'showInternDetails()']) ?>

<script>
 function showInternDetails() {
 $model->isInternal = 1;
 }
</script>

<?php
if($model->isInternal == true)
{
$form->field($model, 'activateReminder')->checkbox();
}
?>

A: You can do that by JS:
<?php
$this->registerJs(
    "$('#myBox').on('change', function() { if($(this).is(":checked")){// Display your input...}else {// hide it} });",
    View::POS_READY
);

A: You can use the when and whenClient options inside the model rules that you have declared so that it works when creating or updating both on the model end to require and show error to the user that he needs to select the value for the check-box and also to show and hide the activateReminder at the same time.
So go inside the model that you are using with this form and add a rule like below.
public function rules(){
    return [
      [['activateReminder'],'required','when'=>function($model){return ($model->isInternal);},
      'whenClient'=>'function(attribute,value){
           if($("#'.\yii\helpers\Html::getInputId($this, 'isInternal').'").val()===1){
              $("#'.\yii\helpers\Html::getInputId($this, 'activateReminder').'").show();
              return true;
           }else{
              $("#'.\yii\helpers\Html::getInputId($this, 'activateReminder').'").hide();
           }
      }']
    ];
}

A: Thank you for your answers!!
I have solved it as follows:
function isInternalOnClick(){
$('#isInternalCheckbox').on('change',function(){        showOrHideActivateReminder();});
}

function showOrHideActivateReminder() {
    if($('#isInternalCheckbox').is(':checked'))
    {
        $('#hiddenActivateReminder').show()
    }
    else{
        $('#hiddenActivateReminder').hide();
    }
}

$(document).ready(function() {
    <?php
            if($model->isInternal)
            {
                echo "
                showOrHideActivateReminder();
                ";
            }
            ?>
});


text:
Q: Storing objects in JSONB column using Postgres/Knex I created a graphs table on my back end to store graph related data. Here is the schema from the Knex migration file:
exports.up = function(knex) {
  return (
      knex.schema
        .createTable('users', tbl => {
            tbl.increments();
            tbl.string('username', 255).notNullable();
            tbl.string('password', 255).notNullable();
            tbl.string('name', 255).notNullable();
            tbl.string('email', 255).unique().notNullable();
        })
        .createTable('graphs', tbl => {
          tbl.increments();
          tbl.string('graph_name', 255).notNullable();
          tbl.jsonb('graph_info').notNullable();
          tbl
            .integer('user_id')
            .unsigned()
            .notNullable()
            .references('id')
            .inTable('users')
            .onDelete('CASCADE')
            .onUpdate('CASCADE');
        })
  )
};

Here is an example of the type of data that I am trying to store in the jsonb column in my database:
{
  labels: ['Axis1', 'Axis2', 'Axis3'],
  datasets: [
        {
          label: 'Dataset1',
          borderDash: [0, 0],
          backgroundColor: '#fff',
          data: [25, 14, 22],
        },
      ],
  title: 'Graph1',
}

Now here is the request that I tried to send through Postman:
{
    "graph_name": "test10",
    "graph_info": "{
        labels: ['Axis1', 'Axis2', 'Axis3'],
        datasets: [
            {
              label: 'Dataset1',
              borderDash: [0, 0],
              backgroundColor: '#fff',
              data: [25, 14, 22],
            },
                ],
            title: 'Graph1'
        }",
    "user_id": "1"
}

I received the following error: SyntaxError: Unexpected token
 in JSON at position 44. I came across this article when I was trying to figure out what is going on:
sending nested json object using postman
I have my Content-Type header set to application/json, and Postman isn't giving me a signal that I'm sending a bad request. I'm not sure what the problem is.
It's also possible that I'm thinking about this the wrong way. When I was looking at the Postgres docs, it seemed to me that the best way to store the type of object that I'm trying to store would be with a jsonb column. But if that is not the case, I'm open to suggestions. Any help would be greatly appreciated.

A: From the look of graph_info in the result, it is not a valid JSON, but a string that contains js object.
When you saves your data to the JSONB column, you need to apply the JSON.stringify method on the object.
For example like this:
{
    "graph_name": "test10",
    "graph_info": JSON.stringify({
        labels: ['Axis1', 'Axis2', 'Axis3'],
        datasets: [
            {
              label: 'Dataset1',
              borderDash: [0, 0],
              backgroundColor: '#fff',
              data: [25, 14, 22],
            },
        ],
        title: 'Graph1'
    }),
    "user_id": "1"
}


text:
Q: Unable to get chromecast sample ios app to work This is what I have done so far:
1) downloaded the sample ios app from Github (cast-ios-sample)
2) Got my device whitelisted by Google and received App ID, something like this, changed of course, but looks similar to this abcdefgh-1234-5678-abcd-abcdefghijkl.
3) Updated receiver.html file to
// Initialize and start the media playing receiver
var receiver = new cast.receiver.Receiver('abcdefgh-1234-5678-abcd-abcdefghijkl', [cast.receiver.RemoteMedia.NAMESPACE], "", 5);

4)loaded receiver.html in an AWS S3 bucket and made it public (I can download the file from my browser, so I confirmed it is public).
5) In xcode, modified GCKAppDelegate.m as follows:
NSLog(@"Setting receiver url.");
//self.host = @"http://www.yourdomain.com/yourreceiver.html";
self.host = @"http://name_of_bucket.amazonaws.com/receiver.html";

6) In xcode, modified GCKViewController.m as follows:
    NSLog(@"Starting session.");
    [self.mSession startSessionWithApplication:@"abcdefgh-1234-5678-abcd-abcdefghijkl"                                    argument:self.applicationArgument];
7) I am able to run the application and I can see my Chormecast in the app, but when I select it, I get the following errors in the xcode console:
2013-08-09 11:49:20.746 ChromecastDemoApp[16077:c07] executing a GCKStartApplicationRequest with url=http://172.17.1.11:8008/apps/abcdefgh-1234-5678-abcd-abcdefghijkl
2013-08-09 11:49:20.747 ChromecastDemoApp[16077:c07] started POST request for: http://172.17.1.11:8008/apps/abcdefgh-1234-5678-abcd-abcdefghijkl and data: <GCKMimeData: 0xf8089c0>
2013-08-09 11:49:20.748 ChromecastDemoApp[16077:c07] Selected device: ChromecastXXXX
2013-08-09 11:49:20.796 ChromecastDemoApp[16077:c07] httpRequest:didCompleteWithStatusCode:404:data:0 bytes
2013-08-09 11:49:20.796 ChromecastDemoApp[16077:c07] Request failed with error: 5
2013-08-09 11:49:20.796 ChromecastDemoApp[16077:c07] tearDownSessionWithError: Error   Domain=com.google.GCKFramework.GCKApplicationSessionError Code=1 "failed to start application (com.google.GCKFramework.GCKApplicationSessionError)"
2013-08-09 11:49:20.797 ChromecastDemoApp[16077:c07] all teardown steps complete
2013-08-09 11:49:20.797 ChromecastDemoApp[16077:c07] GCK Session failed to start: Error Domain=com.google.GCKFramework.GCKApplicationSessionError Code=1 "failed to start application (com.google.GCKFramework.GCKApplicationSessionError)"

8) I am unable to get my web console working by going to localhost:9222.
Any help in what I am doing wrong would be appreciated it.

A: *

*Sample code appears to have an issue - I'll see if I can get it fixed.  No need to send Receiver URL from client.  You can pass the content you'd like your Receiver to work with.

*To see if your device is whitelisted it should be :9222 from Chrome.  If that doesn't work, then make sure you set up your device to [x] Send serial # to Google. Without that, your device can never be Whitelisted. (we don't know it's you)

A: The mAppDelgate.host is not actually used.  The important piece is app-ID.  Ensure that is entered properly in:
[self.mSession startSessionWithApplication:@"YOUR_APP_ID"
                                      argument:self.applicationArgument];
and that the receiver URL you registered with that app-ID matches your receiver.  The 404 error makes me think that URL we have registered with your app_id might have an error.


text:
Q: Why is 1em shorter than the default font size? I was doing some experiments, and then I ran into this issue. I sat a div's height to 1em, and I expected the div to contain the whole height of the text within, but it did not. 1em is my browser is 16px.
When I did not specify the div's height, it successfully contained the whole height of the text, and when inspected, it turned to be of height 19px.
Is my understanding of em wrong, as I thought it should represent the default font height of the browser.

div {
  margin: 0;
  padding: 0;
}
.first {
  height: 1em;
  background: green;
}
.second {
  background: orange;
}

سلامًا Say I Wantأًّ

سلامًا Say I Wantأًّ

https://jsfiddle.net/9t43kyu2/1/

A: The fact that the second div is higher is because of the default line-height property. It's default value is normal.

normal
  Tells user agents to set the used value to a "reasonable" value
  based on the font of the element. The value has the same meaning as
  . We recommend a used value for 'normal' between 1.0 to 1.2.[...]  [source w3.org]

This makes your second div ~=1.2em high depending on your user agent. You can set it's line-height:1em; to see the difference :

div {
  margin: 0;
  padding: 0;
}
.first {
  height: 1em;
  background: green;
}
.second {
  background: orange;
  line-height: 1em;
}

سلامًا Say I Wantأًّ

سلامًا Say I Wantأًّ

A: The typographical line-height of a text isn't surely the actual height of the rendered text in pixels:

The line-height css parameter of a text contains only the height between "caps height" and the "baseline". It is on most cases 1em on my experience and also on most non-standard sources of the net. But its standardized details are better described in @web-tiki 's answer.
If there are characters which have parts over it or below it, they will result a text whose height (in pixels) is bigger as the line height (in pixels).
The text can have small details which are below or over the standard text line. For example, the lowest part of an y, or the uppest parts of a non-ascii Ű character. These causes continously problems in the positioning.
If you don't set the div height, it will be by default auto, which mean, the whole content will be in it. If you specify the div height to the actual line size, without padding, border and margin, then some pixel of your text will maybe overflow. You only didn't see it, because the default value of the overflow css-parameter is visible.
Best test for that: create a div with the following settings:
#divId {
  height: 1em;
  line-height: 1em;
  overflow: hidden;
}

...and copy-paste an yŰ into its content (but characters are also okay). You will see it clipped on both sides.


text:
Q: Order by Column1 if Column1 is not null, otherwise order by Column2 Is there a way to combine ORDER BY and IS NULL in sql so that I can order by a column if the column isn't null, but if it is null, order by another column?

A: Something like:
ORDER BY CASE
    WHEN Column1 IS NOT NULL THEN Column1
    ELSE Column2
END

Or the corresponding syntactic sugar:
ORDER BY COALESCE(Column1, Column2)

Note that the datatype of the two columns must be comparable (the RDBMS defines the rules).

A: Try this
  ORDER BY COALESCE(fieldA, fieldB);

A: You could try with the following:
ORDER BY ISNULL(firstField, secondField)

A: I dont have any Tables atm where I could test it, but this may work, at least it did without useable data:
SELECT * FROM table1
LEFT JOIN table2 ON table1.id = table2.id
WHERE 1
ORDER BY IF( table2.id, table1.id, table1.name )

Also I don't know how the order would look like if table2.id is null sometimes, seems very instable.


text:
Q: Pubsubio to Bigquery using Dataflow I am getting the error belwo while inserting a message from pubsubio to BigQuery.
How can I insert a record from pubsub to BQ. Can we convert pcollection into a list, or is there another alternate?

AttributeError: 'PCollection' object has no attribute 'split'

Here is my code:
def create_record(columns):
    #import re
    col_value=record_ids.split('|')
    col_name=columns.split(",")
    for i in range(length(col_name)):
        schmea_dict[col_name[i]]=col_value[i]
    return schmea_dict

schema = 'tungsten_opcode:STRING,tungsten_seqno:INTEGER
columns="tungsten_opcode,tungsten_seqno"
lines = p | 'Read PubSub' >> beam.io.ReadStringsFromPubSub(INPUT_TOPIC) |
    beam.WindowInto(window.FixedWindows(15))
record_ids = lines | 'Split' >>
    (beam.FlatMap(split_fn).with_output_types(unicode))
records = record_ids | 'CreateRecords' >> beam.Map(create_record(columns))
records | 'BqInsert' >> beam.io.WriteToBigQuery(
    OUTPUT,
    schema=schema,
    create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
    write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)

A: Needs to be done as a transform, you cant directly access data in a pcollection.
Write a DoFn class to perform the split transform on the record with schema as a side input, and create the dict with column/records eg.
class CreateRecord(beam.DoFn):
  def process(self, element, schema):
    cols = element.split(',')
    header = map(lambda x: x.split(':')[0], schema.split(','))
    return [dict(zip(header, cols))]

Apply transform like:
schema = 'tungsten_opcode:STRING,tungsten_seqno:INTEGER'
records = record_ids | 'CreateRecords' >> beam.ParDo(CreateRecord(), SCHEMA)


text:
Q: Why do we say "a one-legged man", with a final -ed, but also say "a one-person job" without? Why do we say "a one-legged man", with a final "-ed", but also say "a one-person job" without the "-ed"? We also say:

A two-minute walk.
A six-hour flight.

But then we say:

A green-eyed woman
Black-eyed peas

When I think about it, it seems to me the pattern with a final -d/-ed suggests the idea of having, as in having green eyes. But this theory doesn't seem to work with some other compound adjectives like:

A two-storey building

It should be two-storeyed because it means made of or having two storeys.

A: The past participle formed from a part of the body(eye, arm, leg, foot, etc) means "having said body part", as you say; a number in front indicates how many there are:

a three-legged stool
a one-eyed pirate
a four-armed deity
a seven-headed dragon
a three-headed dog

With units of measure we do not do this; rather we use the unit of measure in the singular:

a twelve-inch ruler
a six-hour flight

With buildings, storey can be understood as unit of measure or as a component of the building, so that both are possible:

a ten-storey building
three-storeyed terraces
storeyed dwellings

P.S. In American English, storey can be spelled storey or story.


text:
Q: Evaluation time of bash subcommands I needed to write a bash script to accomplish some task, and found that this code resulted in an infinite loop:
echo "Waiting for job to complete"
until [ "$(curl "$url" -u $CREDENTIALS 2>/dev/null)" == "Idle" ]; do
    echo -n "."
    sleep 30
done

Even after the result of my curl command was equal to "Idle", the loop kept on going, apparently using the old result of the curl command in every comparison.
Extracting the curl command to a temporary variable fixed this problem.
When does bash expand the $'s?  What other "gotcha's" should I watch out for?
EDIT:
In light of how platform specific my example is, I reproduced the example in a cross-platform way:
#!/bin/bash
# This will result in an infinite loop, and I don't know why

i=0
mocked() {
    i=$(($i+1))
    if [ $i -lt 5 ]; then
        echo "Non-Idle"
    else
        echo "Idle"
    fi
}

until [ "$(mocked)" == "Idle" ]; do
    echo -n "."
done

Changing the conditional in mocked to if false will cause the until loop to never run, so I'm sure there's some sort of caching issue.
EDIT 2:
All experimentation indicates that this was some freak accident that never happens under normal circumstances, not a limitation of bash.  Regardless, I'm keeping my curl command in a temporary variable.  (The second reproduction of the issue was a coincidence, scope in bash is messed up.)

A: The command substitution is performed each time the condition is evaluated (i.e. for each loop iteration).
It looks like there's something else going on, which we can't be sure since you don't tell us what $url contains. Simply put, the output of that curl command is never Idle. We could say more if you gave us the result of
 printf '<%s>' $(curl "$url" -u $CREDENTIALS)

For example, this little snippet works in bash quite as intended. It stops when the seconds part of the current time hits 42:
 set -x ; until [ $(date +%S) = 42 ]; do echo -n .; sleep 0.5; done

PS: testing for string equality should be done with the = operator. The == is a non-portable bashism invented for the ignorant. In other shells it may not be recognized. Please unlearn it as soon as you can. Long live POSIX :-)


text:
Q: set comma separated number in phpexcel with number_format() function in PHP I am generating Excel using PHPExcel.
All code working fine. But comma separated number with number_format() function is not working properly.
When i use below code it is working properly.
$val=round($data);
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$rowCount,$val);
$objPHPExcel->getActiveSheet()->getStyle('J'.$rowCount)->getNumberFormat()->setFormatCode("#,##0");

But when i use
$val=number_format($data);

I am not getting proper output. In excel ,cell value is proper (6,000) but input line it displayed

'6,000

So can't do autosum.
I don't want to use round() function, because i am generating pdf ,csv also and i have common function to get values.
Thanks


text:
Q: How to apply time zone on datetime_select in Rails form I have a form that looks like
= form.datetime_select :due_at
= form.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones

When this object is saved, we need it to apply the time zone that was selected. For example if the user selects "03-01-2013 11:00" and "Central Time (US & Canada)", I want the date/time, in this case 11AM to be as 11AM CST instead of our application default time zone of "Pacific Time (US & Canada)".
This is actually nested within another form so we cannot simply change Time.zone in the controller with an around_filter. We are trying to figure out a solution that works during daylight savings time as well.

A: If due_at and time_zone are both attributes of a single model, then you could use a before_save hook to make sure due_at is encoded in the time zone of time_zone before being  stored in the database.
class YourModel < ActiveRecord::Base
  before_save :apply_time_zone

  protected

  def apply_time_zone
    self.due_at = ActiveSupport::TimeZone[time_zone].parse "#{due_at_start.to_s(:db)} UTC"
  end
end

ActiveSupport::TimeZone[t].parse(s) will parse s into time zone t, and .to_s(:db) converts a time to string in UTC.


text:
Q: My phpmailer script goes to spam I know this question has already been asked but no answers help me though.
Here is my code i hope you can find something wrong.
   <?php
    require("phpMailer/class.phpmailer.php");
    require("phpMailer/class.smtp.php");

    $mail = new PHPMailer();

    $mail->IsSMTP();
    $mail->SMTPAuth = true;     // turn on SMTP authentication
    $mail->Host = 'smtp.example.com';
    $mail->Port = 587;
    $mail->Username = "mailer@example.com";  // SMTP username
    $mail->Password = "validpassword"; // SMTP password

    $mail->From = "mailer@example.com";
    $mail->FromName = "Mailer";
    $mail->AddAddress("my.email@gmail.com");
    $mail->AddReplyTo("mailer@example.com", "Mailer");

    $mail->WordWrap = 50;                                 // set word wrap to 50 characters

    $mail->IsHTML(true);                                  // set email format to HTML

    $mail->Subject = "Here is the subject";
    $mail->Body    = "This is the HTML message body <b>in bold!</b>";
    $mail->AltBody = "This is the body in plain text for non-HTML mail clients";

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
    ?>

PS : Funny fact is that my mail doesn't go in spam with the mailer()... But i have to use Phpmailer.

A: To see if the mail server that you are sending these through has a glaring problem that would cause other mail servers to think it's a spammer, try sending a message from your script to check-auth@verifier.port25.com. This service will do a bunch of checks, and you'll get a report back with ton of information, such weather or not your mail server's DNS is setup correctly, whether your mail server's IP is on any black lists, if you have a problem with your SPF records, etc.

A: Your mail is going to spam, ergo your mail is being sent, ergo there is (probably) nothing wrong with your script. There are many reasons why mail is delivered to spam. Most obviously, it might be spam. You should be checking the configuration of your mail configuration, specifically check for correct SPF and DKIM records. If you're using a third-party mailing service check that they haven't themselves been blacklisted. Check your return addresses make sense and are valid. Trace the path from the headers and see where any warnings are added en route. And finally, check your own spam filters.

A:    //servidor smtp
   $mail->Mailer = "smtp";
   //Muy importante para que llegue a hotmail y otros
   $mail->Helo = "localhost";
   //Asignamos a Host el nombre de nuestro servidor smtp
   $mail->Host = "localhost";
   $mail->Port = 25;


text:
Q: curl command behaves differently on Mac and Windows I have some R code that works on a Mac but someone else is trying to run it on Windows and it doesn't seem to work. The code I have been using is:
for(i in 1:length(SNPs.needproxies)){
       print(i)
       system(paste0("curl -k -X GET 'https://ldlink.nci.nih.gov/LDlinkRest/ldproxy?var=",SNPs.needproxies[i],"&pop=MXL&r2_d=r2&token=",token,"' > ", dir,"out.",SNPs.needproxies[i],".txt"))
}

If I try to run this on Windows I get the error

https not supported or disabled'.

We have narrowed done the problem in that it seems to be that single quotes should be replaced with double quotes in the address. However as this is within a paste0() function, it thinks this is something else so we thought escaping the double quotes with a backslash i.e.,
\"https://ldlink.nci.nih.gov/LDlinkRest/ldproxy?var=",SNPs.needproxies[i],"&pop=MXL&r2_d=r2&token=",token,"\"
This kind of works in that it gives the output we want but it is supposed to print this to a file called something like dir/out.file.txt but it does not do this part.
The SNPs.needproxies is:
SNPs.needproxies <- c("rs709692","rs9659182","rs13064990","rs11130017","rs9832922" ,"rs36120363","rs4727815","rs7994762","rs72772387")

I have a token for the website but cannot share that but it is stored in the object called token.

A: Nothing to do with paste0() itself but with the Windows version of curl, which requires the https address to be enclosed within double- instead of single-quotes.
Check here for a complete break down of this issue.

A: 1. system() with curl -o option
After noting that curl on Windows requires the https address to be enclosed within double- instead of single-quotes, I would avoid the remaining piping issue altogether and use the -o option in curl to specify a file to write results to if you insist on writing the command out:
system(paste0("curl -k -X GET \"https://ldlink.nci.nih.gov/LDlinkRest/ldproxy?var=", SNPs.needproxies[i], "&pop=MXL&r2_d=r2&token=", token, "\" -o out.", SNPs.needproxies[i], ".txt"))

2. curl_download()
Alternatively, R has a few curl-based packages that take care of all of these details such as curl:
library(curl)
url <- sprintf("https://ldlink.nci.nih.gov/LDlinkRest/ldproxy?var=%s&pop=MXL&r2_d=r2&token=%s", SNPs.needproxies[i], token)
curl_download(url, sprintf("out.%s.txt", SNPs.needproxies[i]))

3. file.download()
You might also just use file.download() in this case as Konrad suggested:
url <- sprintf("https://ldlink.nci.nih.gov/LDlinkRest/ldproxy?var=%s&pop=MXL&r2_d=r2&token=%s", SNPs.needproxies[i], token)
download.file(url, sprintf("out.%s.txt", SNPs.needproxies[i]))

4. GET()
You could also use GET() in from the httr library:
library(httr)
u <- "https://ldlink.nci.nih.gov/LDlinkRest/ldproxy"
q <- list(var = SNPs.needproxies[i],
          pop = "MXL",
          r2_d = "r2",
          token = token)
f <- sprintf("out.%s.txt", SNPs.needproxies[i])
GET(url = u, query = q, write_disk(f))

5. LDproxy()
Note, there appears to be an R package specifically for connecting to this API here. In your case the code would be:
library(LDlinkR)
LDproxy(snp = SNPs.needproxies[i],
        pop = "MXL",
        r2d = "r2",
        token = token,
        file = sprintf("out.%s.txt", SNPs.needproxies[i]))

A: The standard curl call in Windows is a wrapped version of PowerShell's Invoke-RestMethod, which is why doing system calls will result in different results depending on whether you use Linux or Windows. I would recommend using the httr package in R, though it will require translating the calls.


text:
Q: Given string want to filter out certain part of string into an arraylist I have string:
String s = #Jay125,150012 90,#Jay222,150043 00,

*

*I want to filter out value after jay(125,222) and add that to separate ArrayList.

*I want to filter out 150012, 151243 together add that to separate ArrayList.

*I want to filter out 90,00 together add that to separate ArrayList.

I tried by doing this but it doesn't quite do what I want
Pattern reg = Pattern.compile(",");
ArrayList<String> jay = reg.splitAsStream(s))
                           .filter(role -> role.contains("Jay"))
                           .map(String::trim)
                           .collect(Collectors.toCollection(ArrayList::new));

A: If I have understood correctly your case, you're having a String whose pattern is in the form #Jay<Number>,<Number> <Number> and then it keeps repeating itself. Also, you would like to have every bit of this pattern (jay bit, first number bit and second number bit) stored in three separate lists.
As suggested in the comments, you could achieve this with a regex using capturing groups to identify the three portions and retrieve them at every match.
#(Jay\d+),(\d+) (\d+)
Here is a link to test the regex:
https://regex101.com/r/ULtDTu/1
Here is a code snippet with the implementation:
public class Main {
    public static void main(String[] args) {
        String s = "#Jay125,150012 90,#Jay222,150043 00,";
        Pattern pattern = Pattern.compile("#(Jay\\d+),(\\d+) (\\d+)");
        Matcher matcher = pattern.matcher(s);

        List<String> listJay = new ArrayList<>();
        List<String> listFirstSubNum = new ArrayList<>();
        List<String> listSecSubNum = new ArrayList<>();

        while (matcher.find()) {
            listJay.add(matcher.group(1));
            listFirstSubNum.add(matcher.group(2));
            listSecSubNum.add(matcher.group(3));
        }

        System.out.println(listJay);
        System.out.println(listFirstSubNum);
        System.out.println(listSecSubNum);
    }
}

You can also test the code here:
https://ideone.com/0hwpyl


text:
Q: how can I stream in grayscale? (Android) when I stream from my android smartphone it doesnt capture any color manipulations like grayscale. Because the color inversion is applied too late in the rendering pipeline to be included in a screenshot or video recording.
if there is no app out there I will try to code it myself. Any advice how to do it?


text:
Q: Powershell equivalent of devcon.exe I'm trying to convert this windows .BAT file  into Powershell. so if there is someone who could give me the powershell version of what I need to do would be much appreciated.
Batch File :
for /f "delims=:" %%x in ('%SystemRoot%\Setup\Scripts\NIC_Fix\devcon.exe findall *dev_07B0*') do %SystemRoot%\Setup\Scripts\NIC_Fix\devcon.exe remove "@%%x"
%SystemRoot%\Setup\Scripts\NIC_Fix\devcon.exe rescan

Kind regards,

A: I found something like this somewhere.  It's powershell and at least pnputil comes with windows.
# dell2020vidfix.ps1

# Get-PnpDevice -PresentOnly -Status ERROR,DEGRADED,UNKNOWN

foreach ($dev in Get-PnpDevice -FriendlyName '*Intel(R) UHD Graphics 630*') {
  pnputil /remove-device $dev.InstanceId }
pnputil /scan-devices

Microsoft PnP Utility

Removing device:       PCI\VEN_8086&DEV_3E92&SUBSYS_09361028&REV_00\3&11583659&8&10
Device removed successfully.

Microsoft PnP Utility

Scanning for device hardware changes.
Scan complete.


text:
Q: What is the command to create another column of colour codes to assign the values of the other column? I have a column named Material code which contains different and some repeated values. I want to create another column containing colour codes which assign to the values in the Material code column.
Is there a command which facilitates this process?
This is the colour palette of 20 different colours as in the Material code column there are 20 different values.
["#e45ee0",
"#59ab03",
"#0079f1",
"#a5d32c",
"#96167c",
"#7bdc74",
"#d6a0ff",
"#01a068",
"#dd5609",
"#01afe1",
"#903429",
"#1f5392",
"#cbcb74",
"#763c7c",
"#6a4e0e",
"#ecb2f8",
"#565485",
"#ff7699",
"#ad6e8d",
"#ff91d2"]

The column material code:
URI
TRT
TRT
TRT
CVC
SVP
TRT
TRT
BAL
TRT
TRT
TRT
SCVGSX
BAL
TRT
BAL
BAL
TRT
BAL
TRT
BAL
TRT
TRT
BAL
BAL
TRT
TRT
TRT
BALSX
TRT
TRT
URI
TRT
TRT
BAL
SCVFDX
BAL
TRT
SCVFSX
TRT
SCVGSX
BAL
TRT
SCVGSX
BAL
TRT
SVP
TRT
TRT
SCA
TRT
SCARSX
SCARSX
BAS
TRT
SCARSX
TRT
BAL
BAL
SCVC
TNADX
SVP
BAL
SCDGSX
TRT
BALSX
BAL
SCVGDX
BAL
TRT
BAL
TRT
BAL
TRT
TRT
SCA
BAL
SCAFDX
TRT
BAL
URI
TRT
SCVGSX
URI
BAL
TRT
SCVGDX
TRT
BAL
BAL
CVGSX
TRT
BAS
TRT
TRT
BAL
SCVFDX
TRT
BAS
TRT
TRT
BAL
TRT
BAL
BAL
TRT
SAN
SAN

A: You have tagged your question with both r and python, so it's not clear which you prefer.
There are only 19 unique values in the Material column you provided, but if we take just the first 19 colours, in R we can do:
as.character(factor(Material, labels = colour[1:19]))
#>   [1] "#ad6e8d" "#ff7699" "#ff7699" "#ff7699" "#a5d32c" "#ecb2f8" "#ff7699"
#>   [8] "#ff7699" "#e45ee0" "#ff7699" "#ff7699" "#ff7699" "#6a4e0e" "#e45ee0"
#>  [15] "#ff7699" "#e45ee0" "#e45ee0" "#ff7699" "#e45ee0" "#ff7699" "#e45ee0"
#>  [22] "#ff7699" "#ff7699" "#e45ee0" "#e45ee0" "#ff7699" "#ff7699" "#ff7699"
#>  [29] "#59ab03" "#ff7699" "#ff7699" "#ad6e8d" "#ff7699" "#ff7699" "#e45ee0"
#>  [36] "#1f5392" "#e45ee0" "#ff7699" "#cbcb74" "#ff7699" "#6a4e0e" "#e45ee0"
#>  [43] "#ff7699" "#6a4e0e" "#e45ee0" "#ff7699" "#ecb2f8" "#ff7699" "#ff7699"
#>  [50] "#d6a0ff" "#ff7699" "#dd5609" "#dd5609" "#0079f1" "#ff7699" "#dd5609"
#>  [57] "#ff7699" "#e45ee0" "#e45ee0" "#903429" "#565485" "#ecb2f8" "#e45ee0"
#>  [64] "#01afe1" "#ff7699" "#59ab03" "#e45ee0" "#763c7c" "#e45ee0" "#ff7699"
#>  [71] "#e45ee0" "#ff7699" "#e45ee0" "#ff7699" "#ff7699" "#d6a0ff" "#e45ee0"
#>  [78] "#01a068" "#ff7699" "#e45ee0" "#ad6e8d" "#ff7699" "#6a4e0e" "#ad6e8d"
#>  [85] "#e45ee0" "#ff7699" "#763c7c" "#ff7699" "#e45ee0" "#e45ee0" "#96167c"
#>  [92] "#ff7699" "#0079f1" "#ff7699" "#ff7699" "#e45ee0" "#1f5392" "#ff7699"
#>  [99] "#0079f1" "#ff7699" "#ff7699" "#e45ee0" "#ff7699" "#e45ee0" "#e45ee0"
#> [106] "#ff7699" "#7bdc74" "#7bdc74 "


text:
Q: Including the group name in the map function for xarray in python? I have a workflow using the xarray package where I am grouping an xarray object using groupby() and then applying a function that turns it to a dataframe and performs some calculations using the map() function.
I would like to rename a column in the output dataframe using the name of the group similar to how you would in this example : pandas apply example
Though it appears the xarray groups do not have a 'name' attribute that I can use plug-and-play that examples code. I also tried using the group.labels but that did not work either.
General workflow for xr.groupby.map()
# Dummy Dataset
ds = xr.Dataset(
    {"foo": (("x", "y"), np.random.rand(4, 3))},
     coords={"x": [10, 20, 30, 40], "letters": ("x", list("abba"))}
)

# Dataset as array
arr = ds["foo"]

# User defined function
def standardize(x):
    return (x - x.mean()) / x.std()

# Apply the function to each group
arr.groupby('letters').map(standardize)

Functionality I'm shooting for (does not work as written)
def to_df_and_rename(grouped_array):
    df_out = grouped_array.to_dataframe()
    df_out = df_out[['desired_col']]
    df_out = df_out.rename(columns = {"desired_col" : grouped_array.name})
    return(df_out)

Thanks.


text:
Q: Android studio, set checkbox value from checked to unchecked, in the other activity I have a "save" checkbox in the login activity. If the user check it, next time, when the application going to start , skip the login activity. Although, If User wants to logout, the checkbox in the login activity going to set unchecked. This problem, what I can't solve.
Login Activity the saveing part:
saveLogin = loginPreferences.getBoolean("saveLogin", false);
    if (saveLogin == true) {
        etEmail.setText(loginPreferences.getString("email", ""));
        etPassword.setText(loginPreferences.getString("password", ""));
        saveLoginCheckBox.setChecked(true);
    //    editor.putBoolean("checked", true);

     /*   editor.putString("email", "etEmail"); // Storing string
        editor.putString("password", "etPassword"); // Storing string*/

        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etEmail.getWindowToken(), 0);

        String email = etEmail.getText().toString();
        String password = etPassword.getText().toString();

        if (saveLoginCheckBox.isChecked()) {
            loginPrefsEditor.putBoolean("saveLogin", true);
            loginPrefsEditor.putString("email", email);
            loginPrefsEditor.putString("password", password);
            loginPrefsEditor.commit();
        } else {
            loginPrefsEditor.clear();
            loginPrefsEditor.commit();
        }

        Backendless.UserService.login(email, password, new AsyncCallback<BackendlessUser>() {
            @Override
            public void handleResponse(BackendlessUser response) {
                Toast.makeText(getApplicationContext(),"Sikeres bejelentlezés",Toast.LENGTH_SHORT).show();

                Intent loginIntent = new Intent(LoginActivity.this, CategoryActivity.class);
                LoginActivity.this.startActivity(loginIntent);

            }

            @Override
            public void handleFault(BackendlessFault fault) {
                Toast.makeText(getApplicationContext(),"Sikertelen bejelentlezés",Toast.LENGTH_SHORT).show();
            }
        });
    }

And the User activity.... This part, where is a logout button:
 bLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Backendless.UserService.logout(new AsyncCallback<Void>() {
                    @Override
                    public void handleResponse(Void response) {

                        finish();

                        Intent logoutIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
                        UserAreaActivity.this.startActivity(logoutIntent);
                    }
                    @Override
                    public void handleFault(BackendlessFault fault) {
                        Toast.makeText(getApplicationContext(),"Nem sikerült kijelentkezni!",Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });

A: You can do it by shared preferences.. if user logged in just store the value in the sharedpreference let say
 Sp.putString("userinfo","loggedin");
   Sp.commit();

and whenever you comeback just check the preference if it has the value loggedin then jus go to your main activity.else show login activity
  String data =SpEditor.getString("userinfo", null);
   If(data!= null){
   goto main}
  Else goto login

Hopeit helps!!