text:
Q: Проблема с таймером, который через интервал времени вызывает нестатический метод Что уже есть:
#include <functional>
#include <Windows.h>
#include <iostream>
#include <agents.h>
#include <ppltasks.h>

    template <class T>
    void call_after(T& callback, unsigned int timeInMs)
    {
        concurrency::task_completion_event<void> tce;
        auto call = new concurrency::call<int>(
            [callback, tce](int)
        {
            callback();
            tce.set();
        });

        auto timer = new concurrency::timer<int>(timeInMs, 0, call, false);
        concurrency::task<void> event_set(tce);
        event_set.then([timer, call]()
        {
            delete call;
            delete timer;
        });

        timer->start();
    }

Что не получается:
std::function<void()> callback = this->Disconnect; // тут ошибка, C3867 (в вызове функции отсутствует список аргументов)
call_after(callback, 5000);

Метод this->Disconnect() - нестатический метод класса, который имеет возвращяемый тип void и не принимает никаких аргументов.
Вопрос: как решить данную проблему? Как по таймеру, через интервал времени вызвать метод, который является нестатическим членом класса?

A: Какие-то такие варианты:
std::function<void()> callback1 = std::bind(&Foo::Disconnect, this);
std::function<void()> callback2 = [this](){this->Disconnect();};

Написав this->Disconnect, вы не берёте объект типа std::function, а вызываете функцию без аргументов.


text:
Q: IntelliJ IDEA intention actions on Mac with Windows keyboard In my Java source code file, there is a return statement, but the method is void:
public void a() {
    return "x";
}

IntelliJ IDEA shows a red line under return "x";.
I now want to use the "Show Intention Actions" action, to fix this issue. By globally searching for that action, I found out, that the shortcut for to do so is ⌥⏎ (on my Mac, using Mac OS X 10.5+ keymap), in words:
Option+Enter
Since I use a Windows keyboard, I expected this shortcut to be for me:
Alt+Enter
However, this does not trigger anything in IntelliJ IDEA.
How do I show the intention actions on a Mac with a Windows keyboard?

A: On Mac, option is only mapped to alt in some input methods. Choosing British input method works on my machine, choosing Unicode Hex Input fails.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate all the possible combinations of a vector I am interested to generate all the possible combinations of a vector, for example,
v1 <- c("A", "Aa", "B")

and all the possible combinations will be
"A-Aa" "Aa-A" "B-A"  "B-Aa" "A-B"  "Aa-B"

I saw a post- How can I generate all the possible combinations of a vector, but it does not give correct results for v1. The same thing happens to v1 <- c("Testis_NOA_ID","Testis_NOA_IDSt") which returns "Testis_NOA_ID-Testis_NOA_IDSt" only but I am expecting "Testis_NOA_IDSt-Testis_NOA_ID" also.
I checked some other vectors such as v1 <- c("a,"b","c) or v1 <- c("normal", "cancer"), which it gives correct results. The problem comes when the vector content is repeating like v1 <- c("Testis_NOA_ID","Testis_NOA_IDSt"). How to fix it.


text:
Q: What is the visitors' HTTP User Agent stored in log_visitor_info used for? I was wondering, where in Magento the visitors' HTTP User Agent Information is used. The log_visitor_info table is pretty big (and for me it seems the user agent information is useless?).
I grepped through the code and all I found were the following three usages:

*

*Check for ignored user agents (anyway, not the stored user agent data but the one received from the helper) (see Mage_Log_Model_Visitor, _construct())

*Adding the user agent information in (Mage_Log_Model_Visitor, initServerData())

*Saving the visitor information (Mage_Log_Model_Resource_Visitor, _saveVisitorInfo())

Is there any other place (Reports, Menu item in the backend,...) where the HTTP user agent information is shown/needed?

A: So firstly I cannot see anything that directly uses the user agent stored against the visitor log entry.
The package theme exceptions directly use the $_SERVER['HTTP_USER_AGENT'] value as with the other places that check user agent.
My best guess, and sorry that it is a guess, is that someone thought that maybe it might be useful to store this information. A shop owner may want to see how many visitors are using which browser, but I cannot see currently anything that does this.


text:
Q: Question about germs. In Qing Liu's book Algebraic Geometry and Arithmetic Curves, the germs are defined as follows. Let $$ \mathcal{F}_x = \varinjlim_{U \ni x} \mathcal{F}(U). $$
Let $s \in \mathcal{F}(U)$. For any $x \in U$, we denote the image of $s$ in $\mathcal{F}_x$ by $s_x$ and call $s_x$ the germ of $s$ at $x$. My question is: what is the image of  $s$ in $\mathcal{F}_x$? What is the map from $\mathcal{F}(U)$ to $\mathcal{F}_x$ explicitly? Thank you very much.

A: As explained in the wikipedia page about direct limits and as both commentators already pointed out, the direct limit of the $\mathcal F(U)$ will be $\left.\coprod_{U\ni x } \mathcal F(U)\middle/ \sim\right.$ where $f\sim g$ if and only if $f|_W=g|_W$ for some $W$ on which both $f$ and $g$ are defined. The map from $\mathcal F(U)$ to $\mathcal F_x$ maps $f\in\mathcal F(U)$ to its equivalence class.


text:
Q: How to prove Drinker paradox using Resolution? There exists a famous Drinker paradox: $\exists x[P(x)\implies \forall yP(y)]$
How to prove it using resolution?
Here is my attempt:

*

*Negated and Skolemized: $\forall x$ $P(x) \wedge \neg P(f(x))$

*Clausal Form: {P(x)}, {~P(f(x))}

*Stuck at this step. I do not understand how to unify these terms to do resolution and produce an empty clause.

A: Since the $x$ is universally quantified, you can substitute any term for $x$.
In particular, from $P(x)$ and $\lnot P(f(x))$, you can get $P(f(x))$ and $\lnot P(f(x))$, which are contradictory (i.e., resolve to the empty clause).


text:
Q: Strange lag in PS4 Fifa 20 I have normal PS4 and Fifa 20.
I play online every day 2-3 matches 99% with Liverpool.
Problem:
Some days (today is also that day) I see slowness in player, the are slower, their response to pass ball is slower.
For example instead of one touch of ball before shooting they made 2 and I get lost ball of course.
Every player is playing like they are stupid
Passing the ball, shooting, moving.
If I move with player (with ball) in normal speed and I try to stop, he is stopping for some time, like they are all sick and without strength.
After I login into game and before match I can see that 80% of players are in excellent form so that is not problem.
I know when there is internet connection problem because then is blocking, now is not blocking, just player are lazy.
I have two internet providers, tried in short time with both of them and no change there.
Controller settings are all on assisted.
Only thing what I think it could be is that players are tired but then I would see that on every player in color bar how I always do on the end of the match.
Friend played against me in friendly online also with Liverpool and he did not have that problem.
Do you have any idea what could be?

A: This sounds familiar to me. I have lost many games because of disconnection, and something that worked for me:
Never play using wifi, instead you should play using ethernet cable.

A: Can also go into your xbox network settings and do a test there to see the rating for your NAT.  if it shows up as strict, you might get more issues like this.  Ya want it to be Open or Moderate.


text:
Q: Calculate area of MKPolygon in an MKMapView I just don't know how to calculate the area on the MKMapView. Anyone who has solved this problem yet?
This is my code, but it returns way too much:
func ringArea() -> Double{
    var area: Double = 0

    if templocations.count > 2 {
        var p1,p2:CLLocationCoordinate2D

        for var i = 0; i < templocations.count - 1; i++ {
            var loc = templocations[i] as CLLocation
            p1 = CLLocationCoordinate2D(latitude: loc.coordinate.latitude, longitude: loc.coordinate.longitude)

            loc = templocations[i+1] as CLLocation
            p2 = CLLocationCoordinate2D(latitude: loc.coordinate.latitude, longitude: loc.coordinate.longitude)

            var sinfunc: Float = (2 + sinf(Float(degreeToRadiant(p1.latitude))) + sinf(Float(degreeToRadiant(p2.latitude))))

            area += degreeToRadiant(p2.longitude - p1.longitude) * Double(sinfunc)
        }
        area = area * kEarthRadius * kEarthRadius / 2;
    }
    return area
}

A:

#define kEarthRadius 6378137
@implementation MKPolygon (AreaCalculation)

- (double) area {
  double area = 0;
  NSMutableArray *coords = [[self coordinates] mutableCopy];
  [coords addObject:[coords firstObject]];

  if (coords.count > 2) {
    CLLocationCoordinate2D p1, p2;
    for (int i = 0; i < coords.count - 1; i++) {
      p1 = [coords[i] MKCoordinateValue];
      p2 = [coords[i + 1] MKCoordinateValue];
      area += degreesToRadians(p2.longitude - p1.longitude) * (2 + sinf(degreesToRadians(p1.latitude)) + sinf(degreesToRadians(p2.latitude)));
    }

    area = - (area * kEarthRadius * kEarthRadius / 2);
  }
  return area;
}
- (NSArray *)coordinates {
  NSMutableArray *points = [NSMutableArray arrayWithCapacity:self.pointCount];
  for (int i = 0; i < self.pointCount; i++) {
    MKMapPoint *point = &self.points[i];
    [points addObject:[NSValue valueWithMKCoordinate:MKCoordinateForMapPoint(* point)]];
  }
  return points.copy;
}

double degreesToRadians(double radius) {
  return radius * M_PI / 180;
}

A: I used spherical excess to calculate the area.  The article in StefanS's answer has a great explanation on how spherical excess works. It uses triangles, with one edge being the polygon segment, and the other two edges are meridians connecting to a pole. Wikipedia suggested using a "spherical quadrangle" with the same principle's. It uses the polygon segment, the equator, and two edges that are meridians connecting to the equator.
StefanS's answer uses an equation for the approximation of area. I wanted to be more exact.  I implemented 3 different functions.  The approximation, the exact spherical triangles, and the exact spherical quadrangles.
The time was negligible in my use case, but here are the baselines:
0.208- approximation time baseline
0.517- exact spherical quadrangles time baseline
0.779- exact spherical triangles time baseline
As a bonus, the quadrangle solution didn't need any adjustment for the antimeridian, whereas the approximation did.  The quadrangle solution is a lot simpler than the triangle solution. In my tests, the largest difference in results between the quadrangle and triangle solutions were about 0.0000001%.
I used this equation from wikipedia's Spherical Trigonometry, Area and Spherical Excess: https://en.wikipedia.org/wiki/Spherical_trigonometry#Area_and_spherical_excess

And StefanS's article:
"The Spherical Case" equation is detailed in "Some Algorithms for Polygons on a Sphere" by Chamberlain & Duquette (JPL Publication 07-3, California Institute of Technology, 2007)
func areaUsingQuadrilateralSphericalExcess(_ coordinates: [CLLocationCoordinate2D]) -> Double {
// the poles cannot be in the polygon
    guard coordinates.count > 2 else { return 0 }
    let kEarthRadius = 6378137.0
    var sum = 0.0

    for i in 0..<coordinates.count {
        let p1Latitude = coordinates[i].latitude.degreesToRadians
        let p1Longitude = coordinates[i].longitude.degreesToRadians
        let p2Latitude = coordinates[i + 1].latitude.degreesToRadians
        let p2Longitude = coordinates[i + 1].longitude.degreesToRadians

        let sphericalExcess = 2 * atan((sin(0.5 * (p2Latitude + p1Latitude))/cos(0.5 * (p2Latitude - p1Latitude))) * tan((p2Longitude - p1Longitude)/2))
        sum += sphericalExcess
    }
    return abs(sum * kEarthRadius * kEarthRadius)   // if a clockwise polygon, sum will be negative
}

A: Stefan's answer implemented in Swift 5.0 :
import MapKit
let kEarthRadius = 6378137.0

func radians(degrees: Double) -> Double {
    return degrees * .pi / 180
}

func regionArea(locations: [CLLocationCoordinate2D]) -> Double {

    guard locations.count > 2 else { return 0 }
    var area = 0.0

    for i in 0..<locations.count {
        let p1 = locations[i > 0 ? i - 1 : locations.count - 1]
        let p2 = locations[i]

        area += radians(degrees: p2.longitude - p1.longitude) * (2 + sin(radians(degrees: p1.latitude)) + sin(radians(degrees: p2.latitude)) )
    }
    area = -(area * kEarthRadius * kEarthRadius / 2)
    return max(area, -area) // In order not to worry about is polygon clockwise or counterclockwise defined.
}

A: You can still use 2D geometry for calculating surface areas if the dimensions of your area are not so excessive that you need to adjust for the effect of the earth's spheroid.
Assuming that p1 and p2 are less than a few degrees apart and p1 is the centre of the circle and p2 is an arbitrary point on the radius (a radial point), the following function will return the area in square metres.
func findCircleArea(centre: CLLocation, radialLocation: CLLocation) -> Double {
    // Find the distance from the centre to the radial location in metres
    let radius = centre.distanceFromLocation(radialLocation)

    // Apply standard 2D area calculation for a circle
    let area = M_PI * radius * radius

    // Answer is in square metres
    return area
}

If p1 and p2 are both points on the circumference, then use this function instead:
func findCircleAreaBetweenPoints(p1: CLLocation, p2: CLLocation) -> Double {
    // Find the distance from the two points and halve it
    let radius = p1.distanceFromLocation(p2) / 2.0

    // Apply standard 2D area calculation for a circle
    let area = M_PI * radius * radius

    // Answer is in square metres
    return area
}

If you do not use metric measurements, adjust the answer accordingly.
Remember, all surface area calculations are approximations as there are assumptions about the standard WGS84 spheroid as measured at standard sea-level that do not account for variations in elevation at a given location. The distanceFromLocation() calculation uses Great Circle calculations to get the correct distance between points, so the radius reasonably accurate, but when the radius is too large, the error in approximation will also grow.


text:
Q: If $\int_0^1f^k(x)\;dx\le M$, then $m(\{x\in[0,1]:f(x)>1\})=0$. I am having trouble with the following problem from a past analysis qualifying exam:
Let $f(x)$ be a non-negative measurable function defined on $[0,1]$. Suppose there exists a constant $M$ such that
$$\int_0^1f^k(x)\;dx\le M$$ for all $k\ge1$. Prove that $m(\{x\in[0,1]:f(x)>1\})=0$. (Note that $m$ here stands for the Lebesgue measure)
I can't seem to figure out how this bound on the integral helps me. Just following my nose, let $E=\{x\in[0,1]:f(x)>1\}$. Then
$$m(E)=\int\chi_E(x)\;dx<\int f(x)\chi_E(x)\;dx\le\int f^k(x)\chi_E(x)\;dx$$
$$\le\int_0^1 f^k(x)\;dx\le M.$$
Clearly this is not the way to go since I'd like to show that $m(E)=0$. Any help would be very much appreciated.

A: Suppose that $m(E)>0, E=(\{x\in[0,1]:f(x)>1\}$. Let $E_n=m(\{x\in[0,1]:f(x)>1+{1\over n}\})$, $E=\cup_nE_n$ implies that $m(E)=lim_nm(E_n)$ since $E_n\subset E_{n+1}$. This implies that there exists $N$ such that $A=\mu(E_N)>0$.
$\chi(E_N) f^k\leq f^k$  implies that $\int\chi(E_n)f^k\geq A(1+{1\over N})^k\leq M$ for every integer $k$. Contradiction.

A: $$\int f^k(x)dx = \int f^k(x) 1_{\{y:f(y)\leq 1\}}(x) dx+\int f^k(x) 1_{\{y:f(y)>1\}}(x) dx \leq M  $$
From Lebesgue's monotone and bounded convergence theorems we get (applied to second and first integral)
$$m(\{y: f(y) = 1\})+\int\lim_{k\to\infty} f^k(x) 1_{\{y: f(y)> 1\}}(x) dx =\\m(\{y: f(y) = 1\})+ \infty\cdot m(\{y: f(y)> 1\})\leq M \implies m(\{y: f(y)\geq 1\}) = 0  $$ Because otherwise the left hand side of the inequality would be infinity. Note that $m(\{y: f(y) = 1\})<\infty$.


text:
Q: How Heroku dyno hours are calculated? I created a free Hobby account with 550 dyno hours. I'm running a Python script which contains a scheduler to run the program from 9:00 to 10:00 AM daily. For the rest of the time, my script does nothing but Heroku is consuming dyno hours for idle time.
I'm running worker service in Procfile, how to make script sleep other than schedule time? so that dyno hours can be saved. As there are only 550 dyno hours which means my script runs 3 weeks only.
Thanks for your suggestion.

A: One option is to create a Web Dyno together with your Worker.
The Web Dyno sleeps after 30 min inactivity (no web traffic in a 30-minute period), and will also send to sleep the associated Worker.
You can wake up the Web Dyno with a simple HTTP call (an endpoint) at 09:00 which will start the Web and the Worker. Your worker will start the scheduled script and eventually go to sleep again.
You effectively are going to use only few hours a day.
BTW if you add a valid Credit Card you can get an extra 450 hours free, you will not be charged for the entire 1000hrs. Heroku is reliable (in my opinion) you wont get surprise charges unless you start adding plugins or other connectors.


text:
Q: Why do I get "Types of property 'href' are incompatible." issue while building nextJs App written in typescript? import React from 'react'
import Link, { LinkProps } from 'next/link';

interface NavLinkProps extends LinkProps {
  as?: string;
  to: string;
}

const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>((props, ref) => {
 const { as, to, ...rest } = props
 return (
  <Link legacyBehavior href={to} as={as} >
   <a ref={ref} {...rest} />
  </Link>
 )
 })

 NavLink.displayName = 'NavLink'

export default NavLink

Above is my nextJs code written in typescript. During the build it throws below error.
Type error: Type '{ href: Url; replace?: boolean | undefined; scroll?: boolean | undefined; shallow?: boolean | undefined; passHref?: boolean | undefined; prefetch?: boolean | undefined; locale?: string | ... 1 more ... | undefined; ... 4 more ...; ref: ForwardedRef<...>; }' is not assignable to type 'DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement>'.
  Type '{ href: Url; replace?: boolean | undefined; scroll?: boolean | undefined; shallow?: boolean | undefined; passHref?: boolean | undefined; prefetch?: boolean | undefined; locale?: string | ... 1 more ... | undefined; ... 4 more ...; ref: ForwardedRef<...>; }' is not assignable to type 'AnchorHTMLAttributes<HTMLAnchorElement>'.
Types of property 'href' are incompatible.
  Type 'Url' is not assignable to type 'string | undefined'.
    Type 'UrlObject' is not assignable to type 'string'.

I tried to remove the "a" tag and just to pass the {...rest} between Link. But didn't work. What may be the possible solution?


text:
Q: How to create an array of objects from json response I get this error:

undefined method `name' for ["id", "6309"]:Array

I want show league name for each response inplay events
Json Response:
{
    "success": 1,
    "pager": {
        "page": 1,
        "per_page": 50,
        "total": 21
    },
    "results": [
        {
            "id": "222434",
            "time": "1489669200",
            "time_status": "1",
            "league": {
                "id": "4148",
                "name": "Viareggio Cup",
                "cc": null
            },
            "home": {
                "id": "43717",
                "name": "Fiorentina U19",
                "image_id": "42466",
                "cc": "it"
            },
            "away": {
                "id": "159690",
                "name": "Garden City Panthers FC U19",
                "image_id": "320141",
                "cc": null
            },
            "timer": {
                "tm": 86,
                "ts": 4,
                "tt": "1"
            },
            "scores": {
                "2": {
                    "home": "2",
                    "away": "0"
                }
            }
        },
        {
            "id": "223265",
            "time": "1489669200",
            "time_status": "1",
            "league": {
                "id": "1501",
                "name": "Uganda Division 2",
                "cc": "ug"
            },
            "home": {
                "id": "159745",
                "name": "Simba FC",
                "image_id": null,
                "cc": null
            },
            "away": {
                "id": "80323",
                "name": "Busia Fisheries",
                "image_id": null,
                "cc": null
            },
            "timer": {
                "tm": 69,
                "ts": 1,
                "tt": "1"
            },
            "scores": {
                "2": {
                    "home": "1",
                    "away": "2"
                }
            }
        },
    ]
}

module Bapi
  class Inplay < Base
    attr_accessor :id,
                  :time,
                  :time_status,
                  :league

    CACHE_DEFAULTS = { expires_in: 7.days, force: false }

    def self.all(query = {})
      response = Request.where("/v2/events/inplay",query, CACHE_DEFAULTS)
      events = response.fetch('results', []).map { |inplay| Inplay.new(inplay) }
      [ events, response[:errors] ]
    end

    def initialize(args = {})
      super(args)
      league = parse_leagues(args)
    end

     private

    def parse_leagues(args = {})
      args.fetch("league", []).map { |league| League.new(league) }
    end
  end
end

 module Bap
     class Base
        attr_accessor :errors

        def initialize(args = {})
          args.each do |name, value|
            attr_name = name.to_s
            send("#{attr_name}=", value) if respond_to?("#{attr_name}=")
          end
        end
      end
    end

League model
module Bapi
  class League < Base
    attr_accessor :id,
                  :name,
                  :cc
  end
end

Controller :
@events, @errors = Bapi::Inplay.all

views :
<% @events.each_slice(3) do |events| %>
    <% events.each do |event| %>
     <% event.league.each do |leg| %>
            <%= leg.name %>
     <% end %>
    <% end %>
  <% end %>
 <% end %>

[#<Bap::Inplay:0x00007feceede0570 @id="873482", @time="1534143600", @time_status="1", @league={"id"=>"6309", "name"=>"China Super League Reserves", "cc"=>"cn"}>, #<Bap::Inplay:0x00007feceedeb6f0 @id="875996", @time="1534147192", @time_status="1", @league={"id"=>"3653", "name"=>"Indonesia Cup", "cc"=>"id"}>]

When i changed code like this it's work fine

   <% @events.each_slice(3) do |events| %>
        <% events.each do |event| %>
         <%= event.time %>
         <%= event.time_status %>
        <% end %>
      <% end %>
     <% end %>

Edited :
I found this
Now how i can define a variable to convert arguments to (key value), when i use key its return value
    <% @events.each_slice(3) do |events| %>
        <% events.each do |event| %>
     <% event.league.each do |k,v| %>
            <%= k %> <br>
            <%= v %>
       <% end %>
    <% end %>
  <% end %>
 <% end %>

A: I guess the problem is in this method:
def initialize(args = {})
  super(args)
  league = parse_leagues(args)
end

The leagues are parsed and set to a local variable, but is expected to be set to an instance one:
def initialize(args = {})
  super(args)
  @league = parse_leagues(args)
end

Otherwise, the default implementation from Base is called and @league is set to a raw value (to a hash)
And also parse_leagues method should be fixed (and probably renamed to parse_league, since the raw value is not an array, but a hash):
def parse_leagues(args = {})
  League.new(args.fetch("league", {}))
end

And then use it in the view as following:
<% @events.each_slice(3) do |events| %>
  <% events.each do |event| %>
    <%= event.league.name %>
  <% end %>
<% end %>


text:
Q: Remove an element in array based on condition in PostgreSQL Using version 12.
I have a query that returns an array of dates. I'm trying to get a query that returns the array  but removes the first and last dates and any date that is a Tuesday or Thursday.
Here's what it looks like:
select my_dates from my_table

{'2019-11-01','2019-11-02','2019-11-03','2019-11-04','2019-11-05','2019-11-06','2019-11-07','2019-11-08','2019-11-09','2019-11-10','2019-11-11','2019-11-12','2019-11-13','2019-11-14','2019-11-15','2019-11-16','2019-11-17','2019-11-18'}
{'2019-10-09','2019-10-10','2019-10-11'}
{'2019-11-04','2019-11-05','2019-11-06','2019-11-07','2019-11-08','2019-11-09','2019-11-10','2019-11-11','2019-11-12','2019-11-13','2019-11-14','2019-11-15','2019-11-16','2019-11-17','2019-11-18','2019-11-19','2019-11-20','2019-11-21','2019-11-22','2019-11-23','2019-11-24','2019-11-25'}
{'2020-02-06','2020-02-07','2020-02-08','2020-02-09','2020-02-10','2020-02-11','2020-02-12','2020-02-13','2020-02-14','2020-02-15','2020-02-16','2020-02-17','2020-02-18','2020-02-19','2020-02-20','2020-02-21','2020-02-22','2020-02-23','2020-02-24','2020-02-25','2020-02-26','2020-02-27','2020-02-28','2020-02-29','2020-03-01','2020-03-02','2020-03-03'}
{'2020-01-30','2020-01-31','2020-02-01','2020-02-02','2020-02-03','2020-02-04','2020-02-05','2020-02-06','2020-02-07','2020-02-08','2020-02-09','2020-02-10','2020-02-11','2020-02-12','2020-02-13','2020-02-14','2020-02-15','2020-02-16','2020-02-17','2020-02-18','2020-02-19','2020-02-20','2020-02-21','2020-02-22','2020-02-23','2020-02-24','2020-02-25'}

So the query I'm looking for should return the following for the first row:
{'2019-11-02','2019-11-03','2019-11-04','2019-11-06','2019-11-08','2019-11-09','2019-11-10','2019-11-11','2019-11-13','2019-11-15','2019-11-16','2019-11-17'}

where it removed the following date elements from it:
'2019-11-01' -- first element
'2019-11-18' -- last element

'2019-11-05' -- tuesday
'2019-11-07' -- thursday
'2019-11-12' -- tuesday
'2019-11-14'-- thursday

A: You an unnest and re-aggregate.  The dates seem to be ordered, so:
select (select array_agg(dte order by dte)
        from (select dte, min(dte) over () as min_dte,
                     max(dte) over () as max_dte
              from unnest(my_dates) dte
             ) dte
        where dte not in (min_dte, max_dte) and
              extract(dow from dte) not in (2, 4)
       ) as new_my_dates
from my_table;

Note:  If the dates are not ordered and you really want the first and last elements removed, then you can use unnest() with ordinality.


text:
Q: Working with .asp and .aspx pages This may be the wrong place but this is new to me. I did some ASP.NET programming in VS.NET awhile ago and I always did debug in the menu to run and test the site and I always noticed that it compiled ... now I have someone having asking me to work on their ASP.NET website and my question is (new to this type of hosting) do I just edit the files and then upload them via FTP or do I have to ask the host to do a compile or something?

A: I'm assuming you have developed a project in Visual Studio.
If this is a Web Site and not a Web Application:

*

*Right click the project (not the solution) in the Solution Explorer.

*Click "Publish Web Site"

*Set the local location of where you want the Web Site published to.

*Take the local copy and upload it to your web root of your hosting provider

If this is a Web Application, check to see if the hosting provider has a .axd service extension for "One-Click Publishing". If the provider does not have this feature:

*

*Right click the project (not the solution) in the Solution Explorer.

*Click "Publish..."

*Change the Publish method to "File System"

*Set the Target Location and click Publish

*Take the local copy and upload it to your web root of your hosting provider

With Web Applications you also have the ability to upload via FTP, which if you have all of the FTP information at hand it should be easy enough.


text:
Q: how to find minimum element of adjacent elements of a position in a matrix I have a 5x5 matrix and I have to find the minimum of adjacent elements for a position and add that minimum number to that position... this has to be done for all the elements in the matrix except for the 1st row and 1st column.
This  is the matrix
A= [[1 1 2 2 3],[1 1 0 1 0],[2 0 1 0 1],[3 2 1 2 1],[4 0 1 0 1]]

A: import numpy as np
a = [1,2,1,3,1]
b = [2,1,2,1,2]
First Matrix
def get_matrix1(a,b):
d = []
for x in a:
for y in b:
d.append(abs(y-x))
return np.reshape(d,(5,5))
Second Matrix
def get_matrix2():
# Matrix
m1 = get_matrix1(a,b)
print('First Matrix : {}'.format(m1))

# Cumulative Addition
m1[0] = np.cumsum(m1[0])
m1[:,0] = np.cumsum(m1[:,0])
m2 = m1.copy()
print('\nCumulative Addition Matrix : {}'.format(m2))

# Second Matrix
i_rows,j_cols = [0,1,2,3],[0,1,2,3]
edge_rows,edge_cols = [1,2,3,4],[1,2,3,4]

for i,row in zip(i_rows, edge_rows):
    for j,col in zip(j_cols, edge_cols):

        # old
        old = m2[row,col]
        print('\nOld : {}'.format(old))

        # edges
        c,u,l = m2[i,j],m2[i,j+1],m2[i+1,j]
        r = (c,u,l)
        print('Edges : {}'.format(r))

        # new
        new = min(r) + old
        print('New : {}'.format(new))

        # update
        m2[row,col] = new
        print('Updated Matrix :')
        print(m2)

get_matrix2()


text:
Q: Processing a file without an extension on my VPS as a PHP script Good day. I uploaded a file to my Ubuntu OS VPS (/var/www). The file's named 'theyu', without extensions. It's a php script, but for some reasons, I don't want to add the extension.
I'd like to configure Apache to process a request such as say 10.382.234.32/theyu, where 10.382.234.32 is the vps' ip address, as 10.382.234.32/theyu.php
Is this possible? I'd really appreciate answers. I've tried editing the .htaccess file in /var/www using mod_rewrite, and the module is enabled in apache's configuration file. Allow OverWrite is also set to All at /etc/apache2/sites-available/default.
The command I used for rewriting in the .htaccess file was
RewriteRule ^(theyu)$ /$1.php [L]
But all I get when I try acessing the it is a page not found error, cos it's processing theyu as a directory.

A: Do you have MultiViews enabled on your folder? then you can put it as theyu.php and request it as http://example.com/theyu

A: So, I was able to achieve this by turning on MultiViews. Adding Options +MultiViews to my htaccess file.
Though it worked, I still wasn't able to achieve the functionality I wanted with the software.


text:
Q: How to Derive this Formula for Expected n-Way Collisions? I learned from the first answer to https://crypto.stackexchange.com/questions/24660/the-effect-of-truncated-hash-on-entropy (by formidable contributor fgrieu) that when $N$ uniform random selections are made from a finite set of $N$ elements, the probability that any particular element will be selected exactly $j$ times $\displaystyle\approx\frac 1{e\;j!}$, so the expected number of elements selected $j$ times $\displaystyle\approx\frac N{e\;j!}$.
The approximation is very rough for small $N$ and seems to converge gradually.  For sufficiently large $N$ (certainly by $10^9$) it works very well.
Contributor fgrieu even included the results of computational experiments for $N = 2^{35}$, confirming that this formula is very accurate for small $j$, and "breaks down" only when $j$ is near its maximum.
The author wrote that "we can establish" this expression "by counting of the possibilities."
I've been trying to derive the formula myself, and searched for a derivation online, so far without success.
I think I grasp the presence of fundamental constant $e$; for example, a classic gambler's problem asks "if the probability of winning a play is $\frac 1 n$, what is the probability of making $n$ plays without winning?"  The probability of losing each play is $1 - \frac 1 n$, so the probability of losing $n$ in a row is $\left( 1 - \frac 1 n \right)^n$, and $$\lim\limits_{n \to \infty} \left( 1 - \frac 1 n \right)^n = \frac 1 e$$ giving the asymptotic proportion of zero-win outcomes.
This also exactly accords with fgrieu's formula for the case $j=0$.
I've made no progress, however, justifying the formula's divisor $j!$.  I thought about $j!$ as the number of distinct orderings of selections of a given element in the sequence of $N$ selections, but didn't see that leading anywhere.  I enumerated every possible selection sequence for some tiny cases with very small $N$, looking for patterns in those sequences resulting in $j$-way collisions, without seeing the light.  [Exhaustive enumeration is a desperate exercise of size $N^N$; its appeal was that under the premise of uniform random selection every sequence is equally probable, so counting sequences with particular outcomes is a direct measure of probability.]
I've pondered the implicit recurrence that for $j > 0$, the probability a particular element will be selected exactly $j$ times equals $\frac 1 j $ times the probability it will be selected $j-1$ times ... but I have yet to find an explanation of why this must be so.
My intuition is that the derivation is simple, and I'm missing something that's right in front of me.  My thanks to any and all who will help me see it.

A: Yes, you just need to count the possibilities.  There are $N^N$ possible selections. The number of favorable selections, where the distinguished element is chosen $j$ times, is $\binom Nj(N-1)^{N-j}$ because there are $\binom Nj$ ways to select which $j$ choices will be the distinguished element, and for each of the other $N-j$ choices we can choose any of the $N-1$ undistinguished elements.
The probability of success is
$$\begin{align}
\frac {\binom Nj (N-1)^{N-j}}{N^N}
&=\frac{N!(N-1)^{N-j}}{j!(N-j)!N^n}\\
&=\frac{N!}{j!(N-j)!(N-1)^j}\left(\frac{N-1}N\right)^N\\
&=\frac1{j!}\frac{N(N-1)\cdots(N-j+1)}{(N-1)^j}\left(1-\frac1N\right)^N
\end{align}$$
It's easy to see that this goes to $\frac1{j!e}$ as $N\to\infty$.  We have a constant term of $\frac1{j!}$ and you already know that the last term goes to $\frac1e$.  In the middle, we have $j$ terms of the form $\frac{N-k}{N-1}$ and each of these goes to $1$.


text:
Q: SQL: Cleansing dates from OCR'ed documents I have a variety of dates from several .pdf documents that were OCR'ed, the dates have imported in the format DD/MM/YYYY. As the documents are photocopies they are not optimal quality resulting in issues where the dates struggled to distinguish between / and 1 as follows:
Issue: 0110212015
01/0212015
01102/2015
Desired Output: 01/02/2015
As the strings have retained their length of the original dates I was hoping to simply replace the character in Nth position with /. To my knowledge and that gained from searching, SQL does not have a function that simple. Are their substitute or replace functions that can target the exact 1's I need to change? Or can I reconstruct the string using my existing values?

A: SQL Server does have a function to do that... it's called STUFF.
So your expression would look something like:
STUFF(STUFF (DateString , 3, 1, '/'), 6, 1, '/')

A: You can use STUFF function:
select stuff(stuff('0110212015',3,1,'/'),6,1,'/')


text:
Q: The probability that at most 5 goblets must be selected to find 4 that are not seconds, if 10% are seconds A company that produces fine crystal knows from experience that 10% of its goblets have cosmetics flaws and must be classified as "seconds".
If goblets are examined one by one, what is the probability that at most five must be selected to find four that are not seconds?

Progress:   $0.9^4 + 0.4\cdot 0.9^4  = .91854$, is this a correct computation?

A: You approach works though, as David K says, it might be clearer to write  $0.9^4 + 4 \cdot 0.1\cdot 0.9^4  \approx 0.91854$, based on finding four unflawed or on finding three unflawed and one second is some order and then one unflawed.
Another calculation which produces the same answer is $0.9^5 + 5 \cdot 0.1\cdot 0.9^4    \approx 0.91854$, based on looking at five and finding five or four unflawed.


text:
Q: Is there a problem with port parameter on MacOS MySQL CLI? I'm Mac user and I've recently installed MySQL CLI with Homebrew :
brew install mysql-client

Most of time I use it for classic connection on default MySQL port :
mysql -h hostname -P 3306 -uuser -p

And it works great !
Now I need to use it to connect on specific port :
mysql -h hostname -P 44000 -uuser -p

And I get the following message :
ERROR 1045 (28000): Access denied for user 'root'@'ip' (using password: NO)

I've tried with passing password in clear or using a config file but I got the same message. It seems that password isn't send when a port other than default is used.
Anyone has already encountered this problem and know how to solve it please ?


text:
Q: Aragorn's "guise" in the Orthanc Stone In ROTK, Chapter 2 of Book Five, "The Passing of the Grey Company," Aragorn tells Gimli and Legolas that he has looked into the Orthanc stone and had a chat with Sauron.  He says that Sauron "saw me, but in other guise than you see me here."  What was this "guise"?  And why would Aragorn appear in this fashion when he also revealed himself to Sauron as Isildur's heir?

A: Mark's excellent answer points out that Aragorn presented himself to Sauron in the guise of Isildur's heir rather than just a ranger of the north.
However, the word "guise" refers to physical appearance as well as to identity. Aragorn's appearance when he talks to Gimli and Legolas is changed; he appeared older, grim and weary.

The king mounted his horse, Snowmane, and Merry sat beside him on his pony: Stybba was his name. Presently Éomer came out from the gate, and with him was Aragorn, and Halbarad bearing the great staff close-furled in black, and two tall men, neither young nor old. So much alike were they, the sons of Elrond, that few could tell them apart: dark-haired, grey-eyed, and their faces elven-fair, clad alike in bright mail beneath cloaks of silver-grey. Behind them walked Legolas and Gimli. But Merry had eyes only for Aragorn, so startling was the change that he saw in him, as if in one night many years had fallen on his head. Grim was his face, grey-hued and weary.
The Lord of the Rings Book Five, Chapter 2: The Passing of the Grey Company
Page 778 (Houghton Mifflin Harcourt; Single Volume 50th Anniversary Edition)

Aragorn would have shown Sauron a much more imposing appearance. Not only would he not have shown the weariness that Merry saw (which was the result of his struggle with Sauron), he would have shown Sauron the tokens that proved his identity.
The tokens that he had available included the heirlooms of his house

*

*The Ring of Barahir. An heirloom of his house from the First Age.

*His sword Andúril, reforged from the shards of Narsil (that Isildur used to cut the Ring from Sauron's hand).

*The Star of Elendil, which Aragorn also wears at the Battle of the Pelennor.

And then there is that "great staff close-furled in black" that Halbarad carries. Tolkien mentions it several times before finally telling us what it is when Aragorn arrives by ship at the Harlond.

and behold! upon the foremost ship a great standard broke, and the wind displayed it as she turned towards the Harlond. There flowered a White Tree, and that was for Gondor; but Seven Stars were about it, and a high crown above it, the signs of Elendil that no lord had borne for years beyond count. And the stars flamed in the sunlight, for they were wrought of gems by Arwen daughter of Elrond; and the crown was bright in the morning, for it was wrought of mithril and gold.
The Lord of the Rings Book Five, Chapter 6: The Battle of the Pelennor Fields
Page 847 (Houghton Mifflin Harcourt; Single Volume 50th Anniversary Edition)

I think it would have made a great visual if Peter Jackson had included in the film a shot of Aragorn showing himself to Sauron with the Star of Elendil on his brow, Andúril in his hand and the Royal Standard displayed behind him. It would be an interesting contrast with Aragorn's weary appearance afterwards.

A: I think the answer to your question can be found in the context of the words you quoted:

'You have looked in that accursed stone of wizardry!' exclaimed Gimli with fear and astonishment in his face. 'Did you say aught to - him? Even Gandalf feared that encounter.'
'You forget to whom you speak,' said Aragorn sternly, and his eyes glinted. 'Did I not openly proclaim my title before the doors of Edoras? What do you fear that I should say to him? Nay, Gimli,' he said in a softer voice, and the grimness left his face, and he looked like one who has laboured in sleepless pain for many nights. 'Nay, my friends, I am the lawful master of the Stone, and I had both the right and the strength to use it, or so I judged. The right cannot be doubted. The strength was enough - barely.'
He drew a deep breath. 'It was a bitter struggle, and the weariness is slow to pass. I spoke no word to him, and in the end I wrenched the Stone to my own will. That alone he will find hard to endure. And he beheld me. Yes, Master Gimli, he saw me, but in other guise than you see me here. If that will aid him, then I have done ill. But I do not think so. To know that I lived and walked the earth was a blow to his heart, I deem; for he knew it not till now. The eyes in Orthanc did not see through the armour of Théoden; but Sauron has not forgotten Isildur and the sword of Elendil. Now in the very hour of his great designs the heir of Isildur and the Sword are revealed; for l showed the blade re-forged to him. He is not so mighty yet that he is above fear; nay, doubt ever gnaws him.'

and much later, Gandalf says:

' As Aragorn has begun, so we must go on. We must push Sauron to his last throw. We must call out his hidden strength, so that he shall empty his land. We must march out to meet him at once. We must make ourselves the bait, though his jaws should close on us. He will take that bait, in hope and in greed, for he will think that in such rashness he sees the pride of the new Ringlord..."

(My emphasis.)
He must have shown himself as Isldur's Heir. And Sauron had good reason to fear Isildur's Heir: Isildur struck off his hand when Sauron still had the Ring. This heir could control the power (waning though it was) of Gondor. And this heir was a man of great power -- he went mano-a-mano (so to speak) against Sauron and won.
So Sauron knew that the Ring was abroad, that the Heir of Isildur lives, was not a weakling, but could challenge him to a duel of wills and win -- and might soon have the Ring.  By appearing as Isildur's Heir, Aragon showed Sauron his worst nightmare.


text:
Q: Possible UITableViewCell UILabel Compositing Anomaly Consider a UITableViewCell with a style of UITableViewCellStyleDefault, set in tableView:cellForRowAtIndexPath:, and a gradient background, set in tableView:willDisplayCell:forRowAtIndexPath:.
When this is rendered, the textLabel will blend in just fine with the gradient, and highlighting works just as well.
Now, what if we keep everything identical, but change the cell style to UITableViewCellStyleSubtitle? In my case, the textLabel and detailTextLabel no longer blend at all! They take on ... some other color. Not too far off from the colors in the gradient, but it simply doesn't blend. Change the style back to default, and all is well.
Now, I realize I could set the labels to clearColor in ...willDisplayCell... but I've been told over and over again, "Don't do that! Leave them colors alone."
Perhaps I have to do that as a workaround? Or might something else be amiss? Clues welcome/appreciated!

A: A work around would be to use NSString's drawInRect function. You could use the NSString sizeWithFont:forWidth:lineBreakMode: method to calculate the rect size and then draw the strings out that way.
more about string sizes and drawing here on apples docs site.


text:
Q: Cannot read property 'email' of null at HTMLDocument (Firebase) I try to run this firebase function but it returns null every single time
function gen_tell_name() {
      $(document).ready(function() {
        var db = firebase.firestore();
        var email = firebase.auth().currentUser.email;
        var docRef = db.collection("users").doc(email);
        docRef.get().then(function(doc) {
                $("#teller-name").append(doc.data().Name);
         });
      });
    };

I think I need some way to run it after all firebase functions are done but I do not know how.

A: Have a look at the firebase docs:

You can also get the currently signed-in user by using the currentUser
  property. If a user isn't signed in, currentUser is null

In your case, currentUser is null so you can't access the email address (on null)
var user = firebase.auth().currentUser;
if (user) {
  // User is signed in.
  // Continue here
} else {
  // No user is signed in.
}

The recommended way to get the current user:
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    // you can safely access the users properties
  } else {
    // No user is signed in.
  }
});


text:
Q: why this promise then execute twice in codesandbox? why the  console.log(props.name + "  promise" + i); log twice ?
Code is Here
let i = 0;
function CompHook(props) {
  console.log(props.name + " CompHook render" + i);
  Promise.resolve().then(() => {
    i++;
    console.log(props.name + "  promise" + i);
  });

  React.useEffect(() => {
    console.log(props.name + "  useEffect");
    return () => console.log(props.name + "  useEffect destory");
  }, []);
  React.useLayoutEffect(() => {
    console.log(props.name + "  useLayoutEffect");
    return () => console.log(props.name + "  useLayoutEffect destory");
  }, []);

  return props.children || "A";
}

console.log(" start ...");

export default function App() {
  const [show, setShow] = React.useState(false);
  return (

 setShow((t) => !t)}>Hello CodeSandbox

      {show && (
        <>
          <CompHook name="a"></CompHook>
        </>
      )}

  );
}


text:
Q: Moving text from the centre to the left hand side in CSS I want to move my text to the left-hand side from the centre. text-align or float properties don't work.
I know there is a previous question like this but none of the solutions worked. Can anyone see if I am doing anything wrong here? I am using Brackets and here is my code:
.logo {
    color: #0000000
    float: left;
    padding-left: 25px;
    font-size: 16px;
    font-weight: bold;
}

.logo > a {
    text-decoration: none;
    color: #000000;
}

Here is the .html

        LOGO

Here is how the website currently looks
http://prntscr.com/k14jf5
Here is the full coding
http://prntscr.com/k1b1zl and http://prntscr.com/k1b2gn

A: Hex colors contain 6 digits, yours has 7, also do not forget to place a semicolon (;) behind the color and the float: left; See if that works.

A: There are 2 things that I would suggest:

*

*The float is missing the ending semicolon. It should be like this:
float: left;

*What's the width of the unordered list class? Make sure it's sufficient to let your logo to align to the left. If it has a fixed width then make it large.
If you could provide more information then I would be able to help better!

A: try this: To move Left side use
{
 float:right;
 padding-right:50px;
}

To move Right side
{
float:left;
padding-left:50px;
}

A: To get the desired result you should give anchor tag to.
.logo {
    color: #0000000;
    padding-left: 25px;
    font-size: 16px;
    font-weight: bold;
}

.logo > a {
    text-decoration: none;
    color: #000000;
    text-align: left;
}


text:
Q: Semantic UI dropdown change handler I have the following dropdown using Semantic UI:

    <input name="language" type="hidden" value="fr-FR">

French

English

French

And in the jQuery side I init it:
$(".select-language").dropdown()

How can I add the change handler?
The only thing related to this I found in the documentation  is:

onChange(value, text)
Context: Dropdown
Is called after a dropdown item is selected. receives the name and value of selection.

This sounds a little confusing for me. How can I use it?
JSFIDDLE

A: Actually, there are three ways to bind the event:
// globally inherited on init
$.fn.dropdown.onChange = function(){...};

// during init
$('.myDropdown').dropdown({
 onChange: function() {...}
});

// after init
$('.myDropdown').dropdown('setting', 'onChange', function(){...});

A: It seems that onChange setting can be added when creating the dropdown:
$(".select-language").dropdown({
    onChange: function (val) {
        alert(val);
    }
});

JSFIDDLE

A:     jQuery('.ui.ekstensi.fluid.dropdown').dropdown('setting','onAdd',function (val,text,choice) {

    alert(choice);
    }).dropdown('setting','onRemove',function (removedValue, removedText, removedChoice) {
    //your action here
    alert(removedValue);

    });

JSFIDDLE


text:
Q: Re-rendering app with custom hook not working I seek advice regarding a small project I work on. I have a problem with re-rendering/reloading app when my state changes. The issue occurred when I changed useState to custom hook that uses session storage. There is the code of the hook:
const useStateWithSessionStorage = (localStorageKey) => {
  const [value, setValue] = React.useState(
    JSON.parse(sessionStorage.getItem(localStorageKey)) || {
      screen: "signin",
      loading: false,
      user: null,
      response: null,
    }
  );

  React.useEffect(() => {
    sessionStorage.setItem(localStorageKey, JSON.stringify(value));
  }, [value]);

  return [value, setValue];
};

and this is my App.js:
export default function App() {
  const [appState, setAppState] = useStateWithSessionStorage("appState");

  const renderApp = () => {
    if (appState.screen == "signin") return <Signin />;
    if (appState.screen == "hub") return <Hub />;
  };

 return
{renderApp()}
;
}

I also tried to load screen value into another state, which would be re-rendered in useEffect, however, without success.
renderApp function returns either  or . Signin component shows only email and password input, which values are sent do flask endpoint working with sql.
That endpoint updates appState. Concretely it changes appState.screen to "hub".
There's the problem I mentioned. Although state changes (visibly on page displayed by JSON.stringify). The app wont re-render and stays on  component. To work properly and show  I always must refresh the page.
I'm fairly new into this, could anyone give me an advice, please?

A: You will need to listen to Window: storage event to get notified when some component changes the session key value:
const useStateWithSessionStorage = (localStorageKey) => {
  const [value, setValue] = React.useState(
    JSON.parse(sessionStorage.getItem(localStorageKey)) || {
      screen: "signin",
      loading: false,
      user: null,
      response: null,
    }
  );

  React.useEffect(()=> {
    const onStorage = () => {
       const data = JSON.parse(sessionStorage.getItem(localStorageKey)));
       if(data.screen !== value.screen) { /* data changes*/
          setValue(data);
       }
    }
    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);

  React.useEffect(() => {
    sessionStorage.setItem(localStorageKey, JSON.stringify(value));
  }, [value]);

  return [value, setValue];
};


text:
Q: Conga button error: "The name can only contain underscores and alphanumeric characters. …" I'm using Conga to generate documents which are automaticly filled with information from custom objects and fields in SalesForce. To do this I have created buttons and placed them in a custom object. These buttons worked perfectly but when I tried to add one with the same URL in it I received the following error after pressing it:

The name can only contain underscores and alphanumeric characters. It
  must begin with a letter and be unique, and must not include spaces,
  end with an underscore, or contain two consecutive underscores.

While the name of the button contains underscores, it follows the rules. I use the following name:
make_letter

The button uses the following URL & parameters to fill a template.
/apex/APXTConga4__Conga_Composer
?id={!Test_Portefeuille__c.Id}

&QueryID=[B2Cquery]a0DG000000W1Ma6

&TemplateId=a0LG000000UAawA

&DS2=1
&DS3=1
&DS7=3
&BML=Offerte+voor+{!Test_Portefeuille__c.Test_Contract__c}+wordt+gemaakt

&OFN={!YEAR(TODAY())}
{!LPAD(
TEXT(
MONTH(
TODAY(
)
)
)
, 2,'0')}
{!LPAD(
TEXT(
DAY(
TODAY(
)
)
)
, 2,'0')}+{Template.Label} -+{!Test_Portefeuille__c.Klant__c}

I do not understand why the error is shown. Maybe it has to do with the two underscores in the field names?

A: Here's my hypothesis as this used to happen to me. When you copy-pasted from the source button to the new target button, you picked up trailing spaces on one or more lines.
Formatting these Conga buttons onto multiple lines for readability is good practice but cloning via copy-paste adds in hidden spaces at the ends of one or more lines from the source of the copy.


text:
Q: Problem simulating a wave on a string by solving the wave equation as a difference equation. This is a question I posted earlier however the purpose of what I'm doing is going to be expounded much more clearly.
yy[x_, t_] := Which[x == 0, yy[0, t] = 0, x == 1, yy[1, t] = 0, t == 0, yy[x, 0] = Exp[-1000 (x - .3)^2]]

This code is the boundary condition and initial condition for my wave. At x=0 the amplitude equals zero and at x=1 the amplitude is also zero for all times. For t=0 the wave is a Gaussian centered at x=.3
Flatten[Table[yy[x, t + 3./10000.] = yy[x + 1./100., t] + yy[x - 1./100., t], {t,  0, 3./10000., 3./10000.}, {x, 1./100., 99./100., 1./100.}], 1]

This runs my problem and uses the values of yy at t=0 to calculate t=3./10000. later. However when I run this program I get these nulls for the next time step of t=3./10000. This runis the calculation and I cannot get enough good data point for later times.
Help will be very much appreciated. I never had this problem before and I tried everything I know and none of it worked to fix this problem.

A: It may be overkill, but here's a version with everything rounded that gets rid of the extraneous Null.
Clear[yy];
dx = 1./100; dt = 1./10000;
yy[x0_, t0_] := With[{x = Round[x0, dx], t = Round[t0, dt]},
  Which[
   x == 0, yy[0, t] = 0,
   x == 1, yy[1, t] = 0,
   t == 0, yy[x, 0] = Exp[-1000 (x - .3)^2]]
  ]

Table[With[{
   x = Round[x, dx],
   t = Round[t, dt],
   t2 = Round[t + 3./10000., dt]},
  yy[x, t2] = yy[Round[x + 1./100., dx], t] + yy[Round[x - 1./100., dx], t]
  ],
 {t, 0, 3./10000., 3./10000.},
 {x, 1./100., 99./100., 1./100.}]

See Memoization of Rounded inputs for related strategies.

Some explanation
The extraneous values of Null come from Which, not because Which is misused by not having a default case, but because of pattern-matching problems in the memoization of yy.  (The OP seems to have noticed something like this in How to stop Mathematica from turning .02 into 0.019999999999999997`, although it is not remarked upon explicitly in the question.)
The underlying cause is round-off error.  Note, for instance, that 0.01 + 0.01 equals 0.02`, while 0.03 - 0.01 equals 0.019999999999999997`. This is due to numerical round-off error consistent with IEEE 754 binary64 floating-point numbers. Note that 0.02 - (0.03 - 0.01) equals 2^(-58), a one-bit loss of precision.
The problem with the code is subtler, though. While 0.019999999999999997` == 0.02` returns True, as patterns, 0.019999999999999997` does not match 0.02`.  The problem arises specifically in the snippet of the OP's code,
yy[x - 1./100., t]

when x = 0.03.  For t = 3./10000, the value has been memoized as yy[0.02`, 0.0003`]; but code snippet evaluates first as yy[0.019999999999999997`, 0.0003`], which in turn evaluates to Null because it does not match yy[0.02`, 0.0003`] and it falls through the Which cases.  The rounding in the solution I gave, some of which is not strictly necessary, makes the arguments in the memoized definitions and evaluations of yy match each other when they are meant to be equal.


text:
Q: SVD function returns matrices with not compatible dimensions let us consider following matrix
2 4
1 3
0 0
0 0

creation of this matrix in python and corresponding singular value decomposition can be  done in python in  a simple  way
A =np.array([[2,4],[1,3],[0,0],[0,0]])
u,s,v =np.linalg.svd(A)

when i typed  dimensions of corresponding matrix, i got following
print(u)
print(np.diag(s))
print(v)

[-0.57604844  0.81741556  0.          0.        ]
 [ 0.          0.          1.          0.        ]
 [ 0.          0.          0.          1.        ]]
[[5.4649857  0.        ]
 [0.         0.36596619]]
[[-0.40455358 -0.9145143 ]
 [-0.9145143   0.40455358]]

therefore following code for reconstructing original matrix does not work
print(u.dot(np.dot(np.diag(s),v)))

how can i fix this problem? thanks in advance

A: In the formal definition of the SVD, the shape of s should be (4, 2). However NumPy's routine returns an array of singular values of shape (2,). Furthermore, np.diag() doesn't know anything about how big s "should" be in the full decomposition. It just takes an array of shape (n,) and returns a 2D array of shape (n, n). So your inner product ends up with shapes (4, 4) * (2, 2) * (2, 2), which of course fails because sizes of the first product don't make sense.
To fix this, just construct an array of the correct size for s:
>>> u, s, v = np.linalg.svd(A)
>>> true_s = np.zeros((u.shape[1], v.shape[0]))
>>> true_s[:s.size, :s.size] = np.diag(s)
>>> np.allclose(u.dot(true_s).dot(v), A)
True


text: Q: PayFort SDK Integration in iOS (Objective C) I want to integrate Payfort payment gateway in my app and i cant seem to understand the guidelines provided by the sdk... if possible, can anyone provide the steps? to generate the sdk token/signature and the bill? thanks in advance.


text:
Q: Can't check one variable in if I have a one problem.  This is code:
var z = "+"
if (z!="+" || z!="-" || z!="*" || z!="/" || z!="%") document.write("You must give me operator (+ - * / %)");
else
document.write("Yess!");

OUTPUT IS: You must give me operator (+ - * / %)
Why it doesn't work  correctly?
Thank's for help. :)

A: You should not do an OR, but an AND:
var z = "+"
if (z!="+" && z!="-" && z!="*" && z!="/" && z!="%") document.write("You must give me operator (+ - * / %)");
else
    document.write("Yess!");

A: You better check it like this.
var z = "+";
document.write('+-*/%'.indexOf(z) !== -1 ? "Yess!" : "You must give me operator (+ - * / %)");

A: You should be using "AND" not "OR" because with "OR" any one of your conditions being true will make the ENTIRE condition true and since z != "-", that's enough to move you into the true branch of the if.

var z = "+";

if (z != "+" && z != "-" && z != "*" && z != "/" && z != "%") {
  document.write("You must give me operator (+ - * / %)");
} else {
  document.write("Yess!");
}

A: Breakdown the logic.
If z must be equal to "+" and z can not equal "+" || "-" || "*" || "/" || "%" , then z must be true.
This is true because each logical comparison is not conditional to any other comparison when using OR. If any logical comparison is satisfied such as z is not equal to "/" , this statement must be true since z = "+" and not equal to "/" .
*This is why you must use AND in your logical statement to get your desired out come.


text:
Q: Cleancode: try/catch in Promise I am working on redux-form atm and found the piece of code. Its working for me but is there any cleaner way to write this in ES6 style?
const asyncValidate = (values/* , dispatch */) => {
  return new Promise((resolve, reject) => {
    try {
      if (['john', 'paul', 'george', 'ringo'].includes(values.name)) {
        const error = {
          name: 'That username is taken'
        };
        throw error;
      }
      resolve();
    } catch (e) {
      reject(e);
    }
  });
};

I would appreciate your help

Solution
const asyncValidate = (values/* , dispatch */) => {
  return new Promise((resolve, reject) => {
    const errors = {};
    if (['john', 'paul', 'george', 'ringo'].includes(values.name)) {
      errors.name = 'That username is taken';
    }
    reject(errors);
  });
};

probably cleaner way?!

A: try/catch is redundant in promise chains and promise executor functions.
Any error thrown is automatically converted to a rejection of the promise you're supposed to return. The promise code calling your function takes care of this. So just do:
const asyncValidate = values => new Promise(resolve => {
  if (['john', 'paul', 'george', 'ringo'].includes(values.name)) {
    throw { name: 'That username is taken'};
  }
  resolve();
});

and it gets converted to a rejection.

A: You can use Conditional (ternary) Operator to simplify if-statement, also you don't need a catch block here:
//ES5
const asyncValidate = (values) => {
    return new Promise((resolve, reject) => {
        ['john', 'paul', 'george', 'ringo'].includes(values.name) ? reject({ name: 'That username is taken' }) : resolve();
    });
};

//ES6 - using "generators"
const asyncValidate = function* (values) {
    return yield ['john', 'paul', 'george', 'ringo'].includes(values.name) ? Promise.reject('That username is taken') : Promise.resolve();
}


text:
Q: Как получить данные при парсе в python? как сделать запрос, если в одном классе допустим несколько <a href как выбрать тот который мне нужен? Пытаюсь из div класса "content_product_catalog_list_item_picture" забрать ссылку <a href на станицу товара, но необходимо выбрать определенную, так как после div, <a href всречается 3 раза
import requests
from bs4 import BeautifulSoup
import csv

HOST = 'https://happywear.ru/'
URL = 'https://happywear.ru/boys/boy-povsednevnaya-odegda/boy-shtani'
HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'
}

def get_html(url, params=''):
    r = requests.get(url, headers=HEADERS, params=params)
    return r

def get_content(html):
    soup = BeautifulSoup(html, 'html.parser')
    items = soup.find_all('li', class_='js-catalog-item content_product_catalog_list_item')
    cards = []

    for item in items:
        cards.append(
            {

                'title': item.find('a', class_='content_product_catalog_list_item_info_introtext').get_text(strip=type),
                'title_2': item.find('div', class_='content_product_catalog_list_item_picture').find('a').get_text('href'),
                'title_rub': item.find('div', class_='content_product_catalog_list_item_price__block').get_text(strip=type),
                'card_img': item.find('div', class_='content_product_catalog_list_item_picture').find('img').get('src')
            }
        )
    return cards

html = get_html(URL)
print(get_content(html.text))

A: Самым лёгким и быстрым решением в данной ситуации будет спарсить все 3 ссылки и перебрать вам нужную.
Показываю на примере:
Main_hrefs = []
three_hrefs = [fail, fail, true]
# Нам надо забрать True так что для теста выводим весь массив
print(three_hrefs)
# Увидели что наша ссылка в конце и засовываем эту ячейку в нужный нам массив с ссылками
Main_hrefs.append(three_hrefs[2])

Реализация в вашем коде:
Main_hrefs = []
html = BS.find("div", class_="content_product_catalog_list_item_picture")
three_hrefs = html.find_all("a")
print(three_hrefs)
# Нам надо забрать нужную ссылку так что для теста выводим весь массив
print(three_hrefs)
# Увидели где нужная нам ссылка и продолжаем работать с той ячейкой массива в вашем случае она будет вторая по счёту
Main_hrefs.append(three_hrefs[1])


text:
Q: R - Convert a column to single factor level I have the following problem. I have done tests, in this test have a set of samples ("Sample"), different categories ("Individual_class") for which I wrote down a score ("Score_individual_class"), and I also gave a final score("Final_Score_Sample") for each sample. This is an example:
df<-data.frame(Sample = c(1,1,2,2,3,3),
               Individual_class = c("A","B","A","B","A","B"),
               Score_individual_class = c(10,20,50,80, 30,60),
               Final_Score_Sample = c(80,80,90,90,120,120)

)
  Sample       Individual_class   Score_individual_class  Final_Score_Sample
      1                A                     10                 80
      1                B                     20                 80
      2                A                     50                 90
      2                B                     80                 90
      3                A                     30                120
      3                B                     60                120

Now I would like the Final_Score_Sample to be in between the Score_individual_class with Individual_class = C. Like this:
  Sample       Individual_class    Score_individual_class
      1                A                     10
      1                B                     20
      1                C                     80
      2                A                     50
      2                B                     80
      2                C                     90
      3                A                     30
      3                B                     60
      3                C                    120

I've tried this:
df_test<-df[,c("Sample", "Final_Score_Sample")]
df_test<- df_test[!duplicated(df_test), ]
df_test$Individual_class<-"C"
df_test$Individual_class<-as.factor(df_test$Individual_class)
names(df_test)[names(df_test)=="Final_Score_Sample"] <- "Score_individual_class"
df_final<-left_join(df, df_test)

But this didn't work. Could someone help me?

A: Here implemented in base R:
# Your data
df<-data.frame(Sample = c(1,1,2,2,3,3),
               Individual_class = c("A","B","A","B","A","B"),
               Score_individual_class = c(10,20,50,80, 30,60),
               Final_Score_Sample = c(80,80,90,90,120,120))

# Data with correct format
df1 <- df[,1:3]

# Data with incorrect format
df2 <- unique(df[,c(1,4)])
df2$Individual_class <- "C"
colnames(df2)[2] <- "Score_individual_class"

# Gathering data again
df <- rbind(df1, df2)

# Sorting
df <- df[order(df$Sample, df$Individual_class),]

# Result
  Sample Individual_class Score_individual_class
1      1                A                     10
2      1                B                     20
7      1                C                     80
3      2                A                     50
4      2                B                     80
8      2                C                     90
5      3                A                     30
6      3                B                     60
9      3                C                    120

A: Replace last line of your code with a following one:
df <- rbind(df[c(1:3)],df_test)

And then sort df:
df <- df[order(df$Sample,df$Individual_class),]

A:
Result
  Sample Individual_class Score_individual_class
1      1                A                     10
2      1                B                     20
3      1                C                     80
4      2                A                     50
5      2                B                     80
6      2                C                     90
7      3                A                     30
8      3                B                     60
9      3                C                    120

Code
df %>%
    select(1:3) %>%
    bind_rows(df %>%
                  select(1, 4) %>%
                  group_by(Sample) %>%
                  summarize(Score_individual_class = first(Final_Score_Sample)) %>%
                  mutate(Individual_class = "C")) %>%
    arrange(Sample)

Data
library(tidyverse)
df <- data.frame(Sample = c(1,1,2,2,3,3),
                 Individual_class = c("A","B","A","B","A","B"),
                 Score_individual_class = c(10,20,50,80, 30,60),
                 Final_Score_Sample = c(80,80,90,90,120,120),
                 stringsAsFactors = FALSE)

A: Try this:
     library(tidyverse)

     df <- bind_rows(df %>%
            dplyr::select(Sample,Individual_class,Score_individual_class),
           df %>%
           dplyr::select(Sample,Final_Score_Sample) %>%
            mutate(Individual_class = "C") %>%
            rename(Score_individual_class = Final_Score_Sample)) %>%
           arrange(Sample)


text:
Q: Why Google Chrome and XCode shares keyword on their search box? When I search in Chrome by Command+F, the same keyword appears on XCode's search box.
And also when I search in XCode by Command+F, the same keyword appears on Chrome's search box.

Why does that happen?
Is it safe?
Does XCode record my search history on Chrome?

A: This is the "Find pasteboard" in action. Mac OS X has several pasteboards (what are called clipboards on other OSes). The general pasteboard is for cut/copy/paste operations, but there are other pasteboards for fonts and rulers, etc.  One is the Find pasteboard. Apps that support a Find operation can put the searched-for text on the find pasteboard which makes it available to other apps. Effectively, there's one, global "text to be searched for" across all applications (assuming they support the Find pasteboard).
I assume Chrome's Command-F is for searching within a web page, not performing a web search (like a Google search), right?
As far as safety, well, it's intended behavior. I suppose it's a privacy leak of sorts, although you have to trust apps that run on your system, because there are very few protections between them.
Xcode is presumably not recording anything of this sort.


text:
Q: Javascript Date shows the wrong value when using alert
Possible Duplicate:
javascript is creating date wrong month

In my code, I create Date by this line:
var date = new Date('2012', '01', '20')

and then using:
alert(date);

I get the result:

I don't really understand why not Jan instead of Feb?
jsFiddle: http://jsfiddle.net/U5m8N/

A: The "Month" part of var date = new Date('2012', '01', '20'); is zero-indexed.
Start counting at 0, and you got your month. (So, January is 0, Feb 1, etc.)
Also, while JavaScript does accept strings as parameters, you should be using integers, as the documentation suggests:
Date Documentation

A: Javascript Date Object's Month is 0 indexed. http://www.w3schools.com/jsref/jsref_obj_date.asp. put 0 instead of 1 for Jan


text:
Q: Static instance in the class in distributed system i was reading the blogs for "What about the code? Why does the code need to change when it has to run on multiple machines?".
And i came across one line which i am not getting it, can anyone please help me to understand it with simple or any example.
"There should be no static instances in the class. Static instances hold application data and when a particular server goes down, all the static data/state is lost. The app is left in an inconsistent state."

A: Assuming: Stating instance is an instance which can be at most once per process or context - e.g. in java there is at most one copy of a static class, with all data (or state) that the class contains.
So it is very simple memory model for a static class in a single node/jvm/process. Since there is a single copy of data, it is quite straightforward to reason about it. For example, you one may update the data and every next reader will see the updated information. This is a bit more complicated for multithreaded programs, but is still straightforward comparing to distributed systems.
Clearly in a distributed system, every node may have at most one static class with state. Which means if a system contains several nodes - a distributed system - then there are several copies of data.
Having several copies is a problem. It is hard to reason about such system - every node may have some unique data and data may differ on different node. It is very hard to reason about such data: how it is synced? Availability vs consistency?
For example, take a simple counter. In a single node system, a static instance may keep the score. If one writer increased the counter, the next reader will see the increased value (assuming multithreaded part is implemented correctly, which is not that complicated).
Same counter is a distributed system is much more complicated. A writer may write to one node, but a reader may read from another.
Basically, having state on nodes is a hard problem to solve. This is the primary reason to use some distributed storage layer e.g. Hbase, Cassandra, AWS DynamoDB. All these storage systems have predictable behaviour which helps to reason about correctness of programs.

A: For example, there are just two servers which accepts payments from clients.
Then somebody decided to create static class to be friendly with mutli threading:
public static class Payment
{
    public static decimal Amount;

    public static bool IsMoneyReceived;

    public static string UserName;
}

Then some client, let's call him John, decided to buy something in shop. John sent money and static class has data about this purchase. Some service is going to write data into database from
Payment class, however, electicity was turned off. Load balancer knows that the server is not responding and redirects John requests to another server which knows nothing about data in
Payment class.


text:
Q: Function called with no arguments doesn't give error I was coding some problem when i observed this. Since Functions are supposed to be a group of statements that is given a name, which can be called from some point of the program. Consider a simple program that gives the absolute value of an integer :
#include <iostream>
#include <vector>
using namespace std;

int getAbsolute(int x) {
  return x > 0 ? x : -1*x;
}

int main() {
  vector<int> arr;

  for(int i = -5; i < 5; i++)
    arr.push_back(i);

  for(int i = 0; i < arr.size(); i++) {
    cout << "abs(" << arr[i] << ") : "
         << getAbsolute << endl;
  }
}

When i run this program :
rohan@~/Dropbox/cprog/demos : $ g++ testFunction.cpp
rohan@~/Dropbox/cprog/demos : $ ./a.out
abs(-5) : 1
abs(-4) : 1
abs(-3) : 1
abs(-2) : 1
abs(-1) : 1
abs(0) : 1
abs(1) : 1
abs(2) : 1
abs(3) : 1
abs(4) : 1
rohan@~/Dropbox/cprog/demos : $

My question is, Why doesn't this program give me error that i'm supposed to call with arguments, Is something wrong with my g++(-v 4.8.5)? And why does this program output's 1 on each call? Or am i missing something here? I'm really confused.

A: This statement
cout << "abs(" << arr[i] << ") : "
         << getAbsolute << endl;

is correct. The function designator getAbsolute implicitly is converted to the function pointer int (*)( int ) according to the function declaration
int getAbsolute(int x);

and this pointer is outputted using the following operator operator <<
basic_ostream<charT,traits>& operator<<(bool n);

and you get the result like this
abs(-5) : 1

because the function pointer is unequal to zero and this operator is the best overloaded operator operator << for a function pointer of such type.


text:
Q: ¿Cómo accedo a un array en otro método? estoy aprendiendo POO con javascript y para practicar quise codificar un ejercicio que ya había hecho pero ahora con POO, solo que me topé con que no sé cómo usar el array alumnos que creé en el método asignarNombres() en el método tomarAsistencia(), lo cual me tira el siguiente error:

Se me había ocurrido crear el array en el constructor pero me daba undefined al momento de querer usarlo.


text:
Q: Does $R_{\mu \nu \sigma \rho} R^{\mu \nu \sigma \rho} \propto R$ hold? For $R_{\mu \nu \sigma \rho}$ the Riemann-tensor and $R$ the Ricci-scalar:
Does $R_{\mu \nu \sigma \rho} R^{\mu \nu \sigma \rho} \propto R$ hold?
Or is there any way to relate $R$ approximately linear to that contraction?

A: I don't believe there is a general relationship for an arbitrary Lorentzian manifold, such that
$R_{abcd}R^{abcd} \propto R$
The only relationship that I can think of is the Weyl tensor invariant. Let us denote the Weyl tensor $C_{abcd}$.
The quantity you have mentioned above is the Kretschmann scalar, which is denoted:
$K = R_{abcd}R^{abcd}$. One can then write:
$K = C_{abcd}C^{abcd} + \frac{4}{d-2} R_{ab}R^{ab} - \frac{2}{(d-1)(d-2)}R^2$,
where $d$ is the dimension of the spacetime under consideration. Now, it is of interest to note the following theorem:
A manifold of dimension $n \geq 4$ is conformally flat if and only if its Weyl tensor vanishes.
So, for conformally flat spacetimes, such as the FLRW class of metrics, $C_{abcd} = 0$, and we have the main result that you are interested in:
$K =  \frac{4}{d-2} R_{ab}R^{ab} - \frac{2}{(d-1)(d-2)}R^2$,
for $d \geq 4$.
So, consider a 4-D conformally flat metric (such as FLRW), we can write as an example:
$K = 2R_{ab}R^{ab} - \frac{1}{3}R^2$
.
I think this is the closest relationship one can have to what you seek.


text:
Q: Run Python script from php, save process pid, and don't wait it to finish I have a PHP script that runs a python script with shell_exec('myScript.py'). It works nicely, but I don't want to wait that python script to finish. Also I need to know that process pID so I can stop it if I want. How can I do both things? I know that adding "& $!" in the terminal after "myScript.py" gives me the pID, and that I can kill that process with: "kill -SIGTERM pID", but only from terminal.
Thanks in advance.
In more detail, this is what i want to achieve:
I got a raspberry pi. That raspberry pi can control stuff with python scripts (lights, sockets...).
Also, i got a home webserver installed in that raspberry pi. The objective is having a webpage, and being able to run and stop that python scripts from it.

A: you gotta put some bash magic into it.
 $a = exec('python myScript.py > /dev/null 2>&1 & echo $!');
 echo $a;


text:
Q: Load XML file to MySQL database using python with column mapping I have written a code to load data to MySQL table using pymysql library. I'm loading data to mysql table in following manner:
    import pymysql
    con = pymysql.connect(host=host,user=user,password=passwd,db=db,port=int(port),autocommit=True,local_infile=1)
    sql = "LOAD XML INFILE '" + path + "' INTO TABLE "+ ds_name +"."+table_name +" SET dataset="+ds_name+", factor_date="+factor_date+","+column_map+ " ROWS IDENTIFIED BY '<LoanInfo>'"
    cursor.execute(sql)
    cursos.commit()

ds_name and factor_date are not comping from xml file so I'm writing them as static across all the rows.
I have a CSV/excel file which contains mapping between XML file columns and MySQL table column name for 100+ columns. I read somewhere that reference column mapping can be added to SQL query as 'SET ABC_AGE = @Age,UNIQUE_ID= @ID, BALANCE=@Money'. I am creating a list of mapping in following manner:
ls = []
for value in zip(map_df['XML Columns'],map_df['SQL Columns']):
    ls.append(value[0]+"=@"+value[1])
column_map = ",".join(ls)

My Question is, Is there a better way to approach to load XML file to MySQL using python with mapping?

A: I found a way to transform xml file into a pandas dataframe and then load it with executemany to mysql databse. Here is a piece of code to convert xml to dataframe:
#reading mapping file and converting mapping to dictionary
import os
import pandas as pd
map_path = 'Mapping.xlsx'
if os.path.isfile(map_path):
    map_df = pd.read_excel(map_path,worksheet='Mapping')
    mapping_dict = pd.Series(map_df['XML Columns'].values,index=map_df['SQL columns']).to_dict()

#Reading XML file

import xml.etree.ElementTree as ET
xml_path = 'test.xml'
if os.path.isfile(xml_path):
        root = ET.parse(xml_path).getroot()

#Reading xml elements one by one and storing attributes in a dictionary.

missing_col = set()
xmldf_dict = {"df_dicts":[]}
for elem in root:
    df_dict = {}
    for k,v in mapping_dict.items():
        if k in [list of columns to skip]:
            continue
        try:
            df_dict[k] =  elem.attrib[v]
        except KeyError:
            missing_col.add(k)

    xmldf_dict["df_dicts"].append(df_dict)

#Merging missing columns dataframe with xml dataframe

missing_col_df = pd.DataFrame(columns=missing_col)
xml_df = pd.DataFrame(xmldf_dict["df_dicts"])
final_df = pd.concat([xml_df,missing_col_df],axis=1)


text:
Q: How to change background of button on next click Currently I have a list of TextViews whose background get changed when click for the first time. But I also want when user clicks on the second time its background should again change and vice versa.
With my existing code I am only able to change background for the first click, when I am clicking it again its background is not changing.
Here is my code:
 public void onClick(View v) {

        switch (v.getId()) {
            case R.id.goalText1:
                if (count <= 2) {
                    goals.add(mGoal1.getText().toString());
                    mGoal1.setTextColor(getResources().getColor(R.color.black));
                    mGoal1.setBackgroundColor(getResources().getColor(R.color.white));
                    count++;

                } else {
                    Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.goalText2:

                if (count <= 2) {
                    goals.add(mGoal2.getText().toString());
                    mGoal2.setTextColor(getResources().getColor(R.color.black));
                    mGoal2.setBackgroundColor(getResources().getColor(R.color.white));
                    count++;
                } else {
                    Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.goalText3:

                if (count <= 2) {
                    goals.add(mGoal3.getText().toString());
                    mGoal3.setTextColor(getResources().getColor(R.color.black));
                    mGoal3.setBackgroundColor(getResources().getColor(R.color.white));
                    count++;
                } else {
                    Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.goalText4:

                if (count <= 2) {
                    goals.add(mGoal4.getText().toString());
                    mGoal4.setTextColor(getResources().getColor(R.color.black));
                    mGoal4.setBackgroundColor(getResources().getColor(R.color.white));
                    count++;
                } else {
                    Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.goalText5:

                if (count <= 2) {
                    goals.add(mGoal5.getText().toString());
                    mGoal5.setTextColor(getResources().getColor(R.color.black));
                    mGoal5.setBackgroundColor(getResources().getColor(R.color.white));
                    count++;
                } else {
                    Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.goalText6:

                if (count <= 2) {
                    goals.add(mGoal6.getText().toString());
                    mGoal6.setTextColor(getResources().getColor(R.color.black));
                    mGoal6.setBackgroundColor(getResources().getColor(R.color.white));
                    count++;
                } else {
                    Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.goalText7:

                if (count <= 2) {
                    goals.add(mGoal7.getText().toString());
                    mGoal7.setTextColor(getResources().getColor(R.color.black));
                    mGoal7.setBackgroundColor(getResources().getColor(R.color.white));
                    count++;
                } else {
                    Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.btnGoal:
                Intent intent = new Intent(this, fiteness_level_selection.class);

                try {
                    obj.put("SelectedGoal", goals);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                intent.putExtra("GoalJson", obj.toString());
                startActivity(intent);
                break;

        }

So can anybody suggest me any easy way to achieve it.

A: As What I am understand is you want Change background for that you have take bool variable and in Button click you have to check the bool value.
Boolean click_firsttime = false;

Inside your Button click
use this way
If(click_firsttime == false){
//perform task

// and set bool value to true
click_firsttime  = true;
}else{

// perform task and set bool value

click_firsttime  = false;
}

A: First create a boolean :
 private boolean foo = true;

Then change your code like this :
public void onClick(View v) {

    switch (v.getId()) {
        case R.id.goalText1:
            if (foo) {
                goals.add(mGoal1.getText().toString());
                mGoal1.setTextColor(getResources().getColor(R.color.black));
                mGoal1.setBackgroundColor(getResources().getColor(R.color.white));
                count++;
                foo = false;
            } else {
                // set background to another color
                foo = true;
            }
            break;

A: Set a boolean array in your activity.
//suppose you've 3 textviews within listview
public boolean isTransparent[] = {false,false,false};

And then do this in your onClick method.
public void onOnclick(View v){
    switch (v.getId()) {
        //foreach textview do this
        case R.id.textView1 :
            int color;
            if (isTransparent[0])
                color = getResources().getColor(android.R.color.transparent);
            else
                color = getResources().getColor(R.color.white);
            isTransparent[0]=!isTransparent[0];
            textview1.setBackgroundColor(color);
            break;
       case R.id.textView2:
            // now check for isTransparent[1]
            and so on ...
            ...

    }
}


text:
Q: Trying to implement a rotating image on PySide6, the rotation is right but the image is jiggling I'm trying to have an image to be dynamically rotating depending on motors positions as for monitoring purposes and user interface interactions.
I used a sample image and simulated a constant rotation to do some tests.
I could get the signals and the rotation of the Pixmap with Qtransform right, but the image itself giggles a bit.
Resulting rotation: https://ibb.co/pwTjsbb
I did the following : set a fixed size for the Pixmap, aligned the image center, and unchecked scaled contents on QtDesigner.
The following code sample has two classes : the MainWindow with the image that has to rotate, and a "Rotation" class that simulates a constant motor rotation with a thread, because that's how i do the monitoring (check positions every 0.1seconds)
Here is the image 200x200 : https://ibb.co/c6FwB2F
import sys
import threading
import time

from PySide6 import QtCore, QtGui, QtWidgets
from PySide6.QtCore import QTimer, QSize
from PySide6.QtWidgets import QMainWindow, QLabel

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()

        self.setFixedSize(QSize(200, 200))
        self.setStyleSheet("background-color: white")
        self.label = QLabel()
        self.setCentralWidget(self.label)

        self.img = "circle.png"
        pixmap = QtGui.QPixmap(self.img)

        self.label.setMinimumSize(200, 200)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setPixmap(pixmap)

        self.rotation = 0

        self.timer = QTimer()
        self.timer.setInterval(Rotation.thread_refresh)
        self.timer.timeout.connect(self.rotate_pixmap)
        self.timer.start()

    def rotate_pixmap(self):
        pixmap = QtGui.QPixmap(self.img)
        self.rotation = item.position

        transform = QtGui.QTransform().rotate(self.rotation)
        pixmap = pixmap.transformed(transform, QtCore.Qt.SmoothTransformation)
        self.label.setPixmap(pixmap)

class Rotation:
    """
    This class simulates the position received by a motor in constant
    rotation, to get its data and apply it to the image rotation
    """
    break_thread = False
    thread_refresh = 0.1
    delta_angle = 1

    def __init__(self, position, speed):
        self.position = position
        self.speed = speed
        th = threading.Thread(target=self.start_rotation, args=())
        th.start()

    def angle_mapping(self):
        self.position = round(self.position % 360, 2)

    def define_speed(self):
        # speed in degrees/sec
        Rotation.delta_angle = Rotation.thread_refresh * self.speed
        pass

    def start_rotation(self):
        while not Rotation.break_thread:
            self.angle_mapping()
            self.define_speed()
            print(self.position)
            self.position += Rotation.delta_angle
            time.sleep(Rotation.thread_refresh)

if __name__ == "__main__":
    item = Rotation(0, 10)  # Initial angle, speed in degrees/sec

    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()

    window.show()
    app.exec()

    Rotation.break_thread = True

Also it's my first post, please let me know if i can further improve my contributions
Edit : I might just be using the wrong tool to do a dynamic rotation, if you know any better libraries that can be implemented with Pyside6 to answer my purpose, please let me know
Edit 2 : Added a QTimer as recommended, and provided the picture used

A: The given approach is not a good one, because it completely rotates the whole pixmap and, as the documentation explains (emphasis mine):

The transformation transform is internally adjusted to compensate for unwanted translation; i.e. the pixmap produced is the smallest pixmap that contains all the transformed points of the original pixmap.

The result is clear once you remove the setFixedSize() line and use a different color for the background:

Even if you've set the alignment of the label, that cannot completely solve the issue, for the following reaons:

*

*the source image is not perfectly centered;

*since the image is always adjusted to the minimum representation of the source pixels, you get a final image that is a "bounding rectangle" of the rotated square (as the image above, the red square);

*even if the source square uses integer sizes, that bounding rectangle would have floating point coordinates: for instance, a 100x100 square rotated by 1° results in a bounding rectangle that has sides of ~101.73 pixels, for 2° it's ~103.43, about 105 for 3°, etc;

*image sizes are integer values which means that the image will be adjusted to the closest "biggest" bounding rect, which would probably be sized 102 pixels for 1° and 104 for 2° and 105 for 3°;

*like images, widgets also work with integer values for coordinates, and since you used a center alignment for the label, Qt will try to adapt its center by rounding the computation; for obvious reasons, a widget sized with odd coordinates in a container using even sizes (or vice versa) will align it as well as it can, but it will never be perfectly centered, and since the size changes continuously with odd and even values, the alignment continuously changes along with it;

Consider all the above aspects, and you'll get your "giggling".
There are two options, then.
Note that in the following examples I'll use a QThread, which is normally more appropriate and flexible to work with Qt objects
Custom widget
Use a custom widget, override the painting and apply the transformation matrix to the painter; since drawing is always based on floating point coordinates, the rotation will be consistent. Note that in order to align the rotation to the center of the image, three steps are required: first translate to the transformation origin (the center), then apply the rotation, and finally reverse the translation to the beginning:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class RotationWidget(QWidget):
    position = rotation = 0
    def __init__(self, image='circle.png'):
        super().__init__()
        self.image = QPixmap(image)
        self.setFixedSize(self.image.size())
        self.transform = QTransform()
        half = self.image.size() / 2
        self.tX = half.width()
        self.tY = half.height()

    def setPosition(self, pos):
        if self.position != pos:
            self.rotation = pos - self.position
        else:
            self.rotation = 0
        self.position = pos
        self.update()

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setRenderHint(qp.Antialiasing)
        qp.setRenderHint(qp.SmoothPixmapTransform)
        self.transform.translate(self.tX, self.tY)
        self.transform.rotate(self.rotation)
        self.transform.translate(-self.tX, -self.tY)
        qp.setTransform(self.transform)
        qp.drawPixmap(0, 0, self.image)

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()

        self.setFixedSize(QSize(200, 200))
        self.setStyleSheet("background-color: white")
        self.rotationWidget = RotationWidget()
        self.setCentralWidget(self.rotationWidget)

    def positionChanged(self, pos):
        self.rotationWidget.setPosition(pos)

class Rotation(QThread):
    positionChanged = pyqtSignal(object)
    delta_angle = 1
    thread_refresh = 0.1

    def __init__(self, position, speed):
        super().__init__()
        self.position = position
        self.speed = speed

    def run(self):
        while True:
            diff = self.thread_refresh * self.speed
            self.position = round((self.position + diff) % 360, 2)
            self.positionChanged.emit(self.position)
            self.msleep(self.thread_refresh * 1000)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    window = MainWindow()
    item = Rotation(0, 10)
    item.positionChanged.connect(window.positionChanged)

    window.show()
    item.start()
    app.exec()

Use a Graphics Item
While a bit more complex, the Graphics View framework is designed to allow such transformations by default, and with very good performance even with thousands of items.
For very simple cases like this, it's actually quite easy to implement the above, which doesn't even require a subclass:
class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()

        self.setFixedSize(QSize(200, 200))
        scene = QGraphicsScene()
        self.rotationItem = scene.addPixmap(QPixmap('circle.png'))
        # set the origin for the transformation at the center of the pixmap
        self.rotationItem.setTransformOriginPoint(
            self.rotationItem.boundingRect().center())
        # ensure that the transformation is always antialiased
        self.rotationItem.setTransformationMode(Qt.SmoothTransformation)

        self.view = QGraphicsView(scene)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setFrameShape(0)

        self.setCentralWidget(self.view)

    def positionChanged(self, pos):
        self.rotationItem.setRotation(pos)


text:
Q: Getting a single-value estimation of trust in a computed mean Suppose I have a number N of independent ratings of a given item, where each
rating is an integer between 1 and 7 (inclusive).  For simplicity sake,
let us assume the ratings are normally distributed, though the mean and
stddev will be different for each item.
I'm looking for a single number which will reflect how much trust I should
put into the currently calculated mean.  As an example, if I have N=1000
where every single rating is of 4, this trust should be pretty close to 100%.
If on the other hand I have only N=2 where one rating is 1 and the other is 7,
my trust that the mean is 4 should be very low.
I realise that a compute-trust function such as the one I've described
above will likely need further parameterisation beyond the set of ratings.
If you prefer, I can reformulate compute-trust in terms of "with 95%
confidence, what is the probability that the population mean will be found
within a given interval around the sample mean?"
Any thoughts on how I can compute this trust in a manner that is statistically
sound?
Edit: changed 'median' to 'mean'.

A: Practically speaking, the estimate of the standard deviation seems like a reasonable measure of the "trust" you can put in the mean.
Statistically speaking, you could consider the lengths of (say, 95%) confidence intervals to measure that "trust". If the ratings are normally distributed, those lengths are proportional to the estimates of the standard deviation (see this section), so this would actually be the same measure.


text:
Q: Borders of text boxes not getting painted after validation fails I am just following a ASP.NET MVC book example and for validation we have added those [Required] attributes to the model and it works but now it has added a style sheet to highlight the fields that have issues as well.
Here is how it looks in my IE:

Notice the "red" style is being applied but the borders are not red, and this is how the book screen shot says it should look like:

and here is the CSS I have just copied from the book, so why mine doesn't make the text box border red?
.field-validation-error    {color: #f00;}
.field-validation-valid    { display: none;}
.input-validation-error    { border: 1px solid #f00; background-color: #fee; }
.validation-summary-errors { font-weight: bold; color: #f00;}
.validation-summary-valid  { display: none;}

A: For client side validation use jquery and jquery validation. Also enabled client side validation from the web.config:
add key="UnobtrusiveJavaScriptEnabled" value="true"

** Also ensure your styles are being applied using the IE developer toolbar.