text:
Q: Why is the scalar product of four-velocity with itself -1? My GR book Hartle says the scalar product of four-velocity with itself $-1$?
Consider the definition of four velocity $\mathbf{u} = \frac{dx^{\alpha}}{d\tau}$. Suppose I take the scalar product of four-velocity with itself. I then get
\begin{equation}
\mathbf{u}\cdot \mathbf{u} = \eta_{\alpha\beta}\frac{dx^{\alpha}}{d\tau}\frac{dx^{\beta}}{d\tau}\end{equation}
But these aren't numbers. So why would it yield $-1$?
Granted, I suppose I could consider this a unit four-velocity. But I still don't see how that would yield $-1$. It should be
\begin{equation}
\mathbf{u}\cdot \mathbf{u} = -1(1)(1) + (1)(1)(1) + (1)(1)(1) + (1)(1)(1) = 2
\end{equation}
using
\begin{equation}
\eta_{\alpha\beta}=
\begin{bmatrix}
-1 & 0 & 0 & 0\\
0 & 1 & 0 & 0\\
0 & 0 & 1 & 0\\
0 & 0 & 0 & 1\\
\end{bmatrix}
\end{equation}

A: The derivatives with respect to $\tau$ very much are numbers, but they are not all $1$.
Consider your worldline as a curve $\gamma$ parameterized by $\lambda$. We have
\begin{align}
\gamma : \mathbb{R} & \to \mathbb{R}^4 \\
\lambda & \mapsto (x^0, x^1, x^2, x^3).
\end{align}
At any point in your worldline you have a position $(x^0, x^1, x^2, x^3)$, where all components are scalar functions of $\lambda$. You can differentiate these to find your velocity components:
$$ \dot{x}^\alpha \equiv \frac{\mathrm{d}x^\alpha}{\mathrm{d}\lambda}. $$
Again, these are functions of $\lambda$, and each of the four evaluates to a real number at every point on the line.
In the special case where your parameter $\lambda$ is the proper time, then we call $\dot{x}^\alpha$ instead $u^\alpha$, the $\alpha$ component of $4$-velocity.

For an example, if you were not moving with respect to the coordinates, then each spatial $x^i$ would be constant as $\lambda$ varied, so we would have $\dot{x}^i = 0$. We also know
$$ \mathrm{d}\tau = \sqrt{-\mathrm{d}s^2} = \sqrt{-g_{\alpha\beta} \mathrm{d}x^\alpha \mathrm{d}x^\beta} = \sqrt{-g_{\alpha\beta} \dot{x}^\alpha \dot{x}^\beta} \mathrm{d}\lambda = \sqrt{-g_{00}} \, \dot{x}^0 \, \mathrm{d}\lambda, $$
so
$$ u^\alpha \equiv \frac{\mathrm{d}x^\alpha}{\mathrm{d}\tau} = \frac{\mathrm{d}x^\alpha}{\mathrm{d}\lambda} \frac{\mathrm{d}\lambda}{\mathrm{d}\tau} = \dot{x}^\alpha \frac{1}{\sqrt{-g_{00}} \dot{x}^0} = \big((-g_{00})^{-1/2}, 0, 0, 0\big). $$
You can easily check that $g_{\alpha\beta} u^\alpha u^\beta = -1$ in this case.

1 In general relativiy, replace $\mathbb{R}^4$ with some open set $U \subseteq \mathbb{R}^4$ covering the appropriate part of the manifold.

A: First I just want to point out that saying that the four velocity $u_\mu$ satisfies $u_\mu u^\mu=-1$ is a convention, it is not a requirement. It amounts to a choice of the parameterization $\tau$. However, it is a very useful parameterization, it's not common to use other choices.
In this parameterization, the four velocity takes the form
\begin{equation}
u^\mu = \left(\gamma, \gamma v_x, \gamma v_y, \gamma v_z\right)
\end{equation}
where $\gamma=(1-v^2)^{-1/2}$. Then it's easy to explicitly check that
\begin{equation}
u_\mu u^\mu = -\gamma^2 + \gamma^2 \vec{v} \cdot \vec{v} = -\gamma^2\left(1-v^2\right)=-1
\end{equation}
Note that this assumes $|\vec{v}| < 1$, since otherwise $\gamma$ is not a finite real number. So only timelike paths can be paramaterized so that $\eta_{\mu\nu}\frac{dx^\mu}{d\tau}\frac{dx^\nu}{d\tau}=-1$.

A:
Why is the scalar product of four-velocity with itself -1

*

*The scalar product is invariant

*In the coordinate system in which the object is (momentarily) at rest, the only
non-zero component is the temporal component.

See that, in the rest frame, $\gamma = 1$ thus $d\tau = dt$.  Then, (setting $c = 1$) we have
$$\frac{dx^0}{dt} = 1,\,\frac{dx^i}{dt}=0 $$
Thus
$$\eta_{\alpha \beta}\frac{dx^\alpha}{dt}\frac{dx^\beta}{dt} = -1 $$

A: I will consider $c=1$.
We define the interval by $$ds^2=g_{\mu\nu}dx^\mu dx^\nu$$
and the proper time by
$$d\tau^2=-ds^2=-g_{\mu\nu}dx^\mu dx^\nu$$
From here, it's straightforward to show that
$$g_{\mu\nu}\frac{dx^\mu}{d\tau}\frac{dx^\nu}{d\tau}=-1$$
Now, let's take the inner product of the four-velocity $U^\mu=dx^\mu/d\tau$,
$$U=g_{\mu\nu}U^\mu U^\nu=g_{\mu\nu}\frac{dx^\mu}{d\tau}\frac{dx^\nu}{d\tau}=-1$$
for what was said before.
In conclusion, the four-velocity always will be normalized $-1$.

A: From the definition of the spacetime invariant and a 4-displacement vector, we know:
$$ \mathrm ds^2 = \mathrm d\mathbf x\cdot \mathrm d\mathbf x $$
We also know proper time is defined as:
$$ \mathrm d\tau = \sqrt{-\mathrm ds^2} $$
Thus:
$$ \mathrm d\tau^2 = -\mathrm ds^2 $$
Now:
$$ \mathrm d\tau^2 = - \mathrm d\mathbf x\cdot \mathrm d\mathbf x $$
$$ \frac{\mathrm d\mathbf x}{\mathrm d\tau} \cdot \frac{\mathrm d\mathbf x}{\mathrm d\tau}  = - \mathbf U\cdot \mathbf U = -1 $$


text:
Q: set SVG initial width and height So I wanna have this SVG inside a col div but I want it to be the same height of the right column. If the right col is bigger, it's all good but if it's smaller, the SVG column will win and dictate the height of others.
Is there anyway I can set an initial size of the SVG and still have it responsive in terms of height?
In short, I want the right column to dictate the height of others.

.row {
  display: flex;
  width: 90vw;
}

.col {
  flex: 1;
  border: 1px solid lightgray;
}

    <svg xmlns="http://www.w3.org/2000/svg" width="30" height="100%">
      <line
        x1="50%"
        y1="100%"
        x2="50%"
        y2="0%"
        stroke="black"
        stroke-width="2" />

      <circle
        cx="50%"
        cy="10%"
        r="5" />
  </svg>

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad omnis quae expedita ipsum nobis praesentium velit animi minus amet perspiciatis

This is the desired result:

Here is the jsbin if you wanna play around.

A: Alright, seems like I just needed height and a min-height and some adjustments:

.row {
  display: flex;
  width: 90vw;
}

.col {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  align-items: center;
  border: 1px solid lightgray;
}

.col>svg {
  flex-grow: 1;
  flex-shrink: 1;
  min-height: 20px;
  height: 20px;
  width: 30px;
}

    <svg xmlns="http://www.w3.org/2000/svg">
      <line
        x1="50%"
        y1="100%"
        x2="50%"
        y2="0"
        stroke="darkgray" />
      <circle cx="50%" cy="50%" r="3" />
  </svg>

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad omnis quae expedita ipsum nobis praesentium velit animi minus amet perspiciatis

redpajama_set_name: RedPajamaStackExchange


text:
Q: Items with in a div move after JS event I'm having some CSS styling issues.
Firstly, excuse the poor styling - I've just sorted out the logic of the game and am now working on the styling
The game is a simple game of rock paper scissors. And everytime I click on a square (which represents either rock paper scissors), the game logic is run and either you or the computer player get a point. Once both players get their score updated, the items with the div stripe get pushed up in the div.
I'm not sure if this a html/css issue, or an issue with JS - but what I'd like is the items with the stripe div to remain center at all times.
I've included images to show you what I mean - As I'm sure what I said is confusing you all.
Cheers

Code:

body {
  margin: 0;
  font-family: "Montserrat", "Avenir";
}

#header {
  line-height: 1.1;
  text-align: center;
  margin: 0;
  font-weight: normal;
  text-transform: uppercase;
}

#stripe {
  text-align: center;
  width: 100%;
  margin: 0 auto;
  height: 50px;
}

#reset {
  width: 5%;
}

#message {
  display: inline-block;
  width: 10%;
}

#yourScore {
  display: inline-block;
  width: 2%;
}

#compScore {
  display: inline-block;
  width: 2%;
}

.option {
  width: 30%;
  background: steelblue;
  padding-bottom: 30%;
  float: left;
  margin: 1.66%;
  border-radius: 25px;
  transition: background .5s;
  -webkit-transition: .5s;
  -moz-transition: .5s;
}

#buttons {
  margin: 20px auto;
  max-width: 600px;
}

Rock Paper Scissors

  <button id="reset">Reset</button>

0

0

rock

paper

scissors

A: As mentioned in the comments, you are probably loosing the ps when updating the inner html of #message #yourScore and #compScore.
I would suggest you remove all the ps from within the stripe and change the stying to add some top/bottom paddings:
#stripe {
  text-align: center;
  width: 100%;
  padding: 15px 0;
}


text:
Q: Back up uploads folder outside of wp-content? I've changed the default uploads location to mysite/media instead of wp-content/uploads because the url looks better.  That said, backup programs like WP Clone seem only to backup media when it's in wp-content/uploads.
Is it possible to backup the uploads folder wherever it may be within the installation?

A: I use BackWPup « WordPress Plugins and it has an option to backup any folder in root, as well as the database and all other files. But it doesn't produce a one click restore file like some plugins.

A: (Presuming here that you had the default uploads folder when you installed the plugin initially.)
Try deactivating and reactivating the plugin. It creates the backup folder when the plugin initializes. If you've changed the upload folder since installation of the plugin, it doesn't know where to put it.

From: http://plugins.svn.wordpress.org/wp-clone-by-wp-academy/trunk/wpclone.php

register_activation_hook((__FILE__), 'wpa_wpclone_activate');

...<snip>....

function wpa_wpclone_activate() {
    wpa_create_directory();
    wpa_install_database();
}

Alternatively, you can manually create a directory called /yourmediafolder/wp-clone and backups should just work.


text:
Q: Merge b/w two dask data frame giving MemoryError Reading the parquet files
df_ss_parq = dd.read_parquet("trainSearchStream.parquet/")
df_ai_parq = dd.read_parquet("AdsInfo.parquet/")

Merging the two datasets
df_train =(df_ss_parq.merge(df_ai,on="ad_id",how="left")
       ).compute()

RAM: 16 GB
I have tried using an index on column "ad_id" which makes it faster but shows the same error.
trainSearchStream size = 17 GB
AdsInfo size = 17 GB
Anybody have any idea how to solve it?

A: I would suggest using a SQL engine like Impala or Drill to do the join, writing the result out to new Parquet files. The Python data stack is not very well-suited right now for handling joins between large tables in a memory-constrained environment.


text:
Q: Tomcat Active Directry authentication I'm trying to migrate a Tomcat webapp from Tomcat 6 to 9. This app needs to authenticate users against  AD, which it successfully did in the old instance for years. The JNDI realm settings that worked on the old server are:
 <Realm className="org.apache.catalina.realm.JNDIRealm"
        connectionURL="ldap://ourIP:389"
        alternateURL="ldap://ourIP:389"
        connectionName="cn=ourService Account,cn=Users,dc=ourDomain,dc=lan"
        connectionPassword="ourServiceAcctPW"
        referrals="follow"
        userBase="ou=ourOU,dc=ourDomain,dc=lan"
        userSearch="(sAMAccountName={0})"
        userSubtree="true"
        roleBase="dc=ourDomain,dc=lan"
        roleName="name"
        roleSearch="(member={0})"
        roleSubtree="true"
      />

When I apply this config to server.xml in the new version I get the following error:
javax.naming.PartialResultException [Root exception is javax.naming.CommunicationException: ourDomain.lan:389 [Root exception is java.net.ConnectException: Connection refused (Connection refused)]]
It appears that Tomcat is ignoring the connectionURL parameter. I have verified that the new server can authenticate against AD using ldapsearch.
I am thoroughly perplexed and would greatly appreciate some guidance.


text:
Q: How to truncate text but backwards? I want to achieve something like this:

I give function a string that should be trunctated and a maximum number of characters.
local function TruncateBackwards(str, maxChars)
  --Code
end

print(TruncateBackwards("this text should be truncated", 15)) -- ld be truncated

A: You can use string.sub for this:
local function TruncateBackwards(str, maxChars) return str:sub(-maxChars) end
print(TruncateBackwards("this text should be truncated", 15)) -- ld be truncated

this also makes your own function, TruncateBackwards, pretty obsolete:
print(("this text should be truncated"):sub(-15)) -- ld be truncated

no index math is needed as Lua indices are one-indexed and string.sub supports negative indices relative to the end of the string.

A: With gsub() you can do this with the pattern: '..%s%w+%s%w+$'
...or with 15 Dots before the $: '...............$'
...or with 15 repetitions of a dot before the $: ('.'):rep(15) .. '$'
local txt, count = ("this text should be truncated"):gsub('..%s%w+%s%w+$', '')
print(txt)
-- That replaces the capture 'ld be truncated' with nothing
-- Output: this text shou
-- With match() and same pattern you can do the opposite
print(("this text should be truncated"):match('..%s%w+%s%w+$'))
-- Output: ld be truncated

See: https://www.lua.org/manual/5.1/manual.html#5.4.1


text:
Q: Buffering line with flat cap style using GeoPandas? I'm interested in buffering a linestring geometry using a flat cap style rather than the default round cap style using GeoPandas. I see shapely, which geopandas is based off, has the option to do that:
object.buffer(distance, resolution=16, cap_style=2, join_style=1, mitre_limit=1.0)
However, when I try to integrate the cap style into my geopandas script
import geopandas as gp

shp = r'X:\temp\line_shapefile.shp'
outshp =r'X:\temp\buffered_line_shapefile.shp'

df = gp.GeoDataFrame.from_file(shp)
buffer = df.buffer(100, cap_style=2)

buffer.to_file(outshp)

it throws an error
Traceback (most recent call last):

  File "<ipython-input-12-9660d1a63146>", line 7, in <module>
    buffer = df.buffer(100, cap_style=2)

TypeError: buffer() got an unexpected keyword argument 'cap_style'

What is the correct implimentation of the flat cap style buffer in GeoPandas?

A: GeoPandas isn't passing through all arguments to the shapely buffer method. Instead you can use the standard pandas apply method to call buffer on each geometry individually, e.g.:
# Assumes that geometry will be the geometry column
capped_lines = df.geometry.apply(lambda g: g.buffer(100, cap_style=2))

Also, not that this returns a GeoPandas GeoSeries object, so if you need the attributes (and projection for that matter, though that may be an outstanding issue) you'll need to overwite the geometry column in the original GeoDataFrame.

A: GeoPandas now pass kwargs to shapely, so you can do below now:
gdf.geometry.to_crs("epsg:3857").buffer(10, cap_style=2)

PR: https://github.com/geopandas/geopandas/pull/535
Update: reason for change crs to 3857 is control on buffer radius in meter, else geopandas raise below warning:
UserWarning: Geometry is in a geographic CRS. Results from 'buffer' are likely incorrect. Use 'GeoSeries.to_crs()' to re-project geometries to a projected CRS before this operation.


text:
Q: need space between two words in python with two inputs I am trying to put in 2 inputs then get them as an output, but I cant seem to get a space between them at the end . I have tried a + sign, space between x and y, and a comma and none work.

A: A formatted string will work nicely here.
We can provide variables to a string that has special format markers, like so:
print('{0} {1}'.format(word1, word2))

Or, more easily, a string concatenation:
print(word1 + ' ' + word2)


text:
Q: How do you know if "by inspection" is a valid argument? Sometimes while certain deductions may seem obvious, they are only obvious because of much prior work.
For instance, even describing something as simple as $1+1=2$, you would first need to:

*

*define group containing a set of objects $S$,

*define the operation of addition such that $S \times S \rightarrow S$,

*define that the set is closed under this operation $(S_{1},S_{2}) \rightarrow S_{1}+S_{2}$,

*define that addition is associative $(S_{1}+S_{2})+S_{3}=S_{1}+(S_{2}+S_{3})$,
and it even continues on from there.
So, if you can't even argue "by inspection" for something as elementary as $1+1=2$, what exactly makes it valid for more complex derivations dealing with summations or matrices or special functions of a complex variable and etc.?

A: I'll give two explanations, not completely unrelated. In the vein of Sean Roberson's comment, it often is intended in an informal sense that the result can be shown with a bit of thought. To answer your question in that case, you choose to use it by gearing it to your target audience. If you have a subproof (that you've produced yourself and) that is uninteresting and for which you expect the readers to be able to provide themselves, then using "by inspection" may be appropriate.
At the complete opposite end of formality, consider mechanized theorem provers like Coq, Isabelle/HOL, Mizar, and Agda. In at least the ones based on dependent type theory, like Coq and Agda, a potentially huge (but finite) amount of computation can go into verifying a single step of a proof. In Agda, you might define the natural numbers as follows:
data Nat : Set where
    Z : Nat
    S : Nat -> Nat

with addition then defined recursively as follows:
_+_ : Nat -> Nat -> Nat
x + Z = x
x + (S y) = S (x + y)

We can define $1$ and $2$ via:
one : Nat
one = S Z

two : Nat
two = S (S Z)

We can then prove that one + one equals two via:
one_plus_one_equals_two : Id (one + one) two
one_plus_one_equals_two = Refl

where, for completeness, Id is defined as:
data Id {A : Set} (x : A) : A -> Set
    Refl : Id x x

To verify that one_plus_one_equals_two is well-typed, and thus, effectively, a valid proof, we need to know whether one + one is the same as two. To do this, Agda computes one + one and two to normal form. If they have the same normal form, then they are considered the same. In this case, that normal form is S (S Z). Note that it does require some computation via the definition of + to reduce one + one to S (S Z).1
You do not need to justify the steps of computation. A mechanized proof checker for Agda is expected to be able to perform these computations itself. This is one formal perspective on steps which might be said to be show "by inspection". Indeed, often statements that are asserted to be try "by inspection" are straight computations. This is largely consistent with mathguy's comment. In other words, if it is a purely mechanical computation, then "by inspection" would almost certainly be reasonable. For an informal proof, you'd still want to tailor this to your audience. There are a surprisingly large number of things that can be verified purely mechanically. I recommend the book A=B for some non-trivial examples. I probably would spell out some of the details of the equality of two hypergeometric series, even though they are mechanical verifiable.
For example, checking whether two polynomials with rational coefficients are equal is a purely mechanical process. If my proof relied on the fact that two polynomial expressions were equal, I would not painstakingly go through a step by step argument in terms of the axioms of commutative ring theory. I would just throw them into a computer algebra system to make sure, and then just assert that they are equal with little to no argument in the informal proof. With a little care, you can arrange it so that Agda can compute the proof that two polynomials are equal. This is what the RingSolver module does. Doing so leaves a potentially large and non-trivial computation to the proof checker, but it is a completely mechanical process that's completely specified by the computational rules that are part of the definition of Agda itself. This is a formal analogue of leaving it up to the reader to check the equality of two polynomials.
1 Note that Agda can't solve just any equality automatically. If you ask it the equivalent of whether x + Z = x, it will happily immediately say it is via the first line of the definition of +. However, if you ask it the equivalent of whether Z + x = x, it is unable to show this just by computation. The definition of + does not specify how to handle the case where the second argument is a variable.


text:
Q: C# Backgroundworker & event based architecture I'm trying to use a Backgroundworker in an event based architecture.
This is the backgroundworker creation code:
public void CalculateMetrics()
    {
        var bw = new BackgroundWorker
        {
            WorkerReportsProgress = true
        };

        bw.DoWork += CalculateMetricsASync;
        bw.RunWorkerCompleted += OnMetricsCalculated;
        bw.ProgressChanged += MetricsWorkerProgressChanged;

        bw.RunWorkerAsync();
    }

CalculateMetricsASync:
private void CalculateMetricsASync(object sender, DoWorkEventArgs e)
    {
        _feederMetrics = new ReplayFrameFeeder(_skeletonRecordingFilePath);
        _feederMetrics.FrameReady += MetricNewFrameReadyEventHandler;
        _feederMetrics.FeedFinished += MetricFeedFinishedEventHandler;

        _feederMetrics.Start();
    }

_feederMetrics is reading a file which holds information about Kinect skeleton frames, when a frame is ready, FrameReady should be fired and the following code should run.
MetricNewFrameReadyEventHandler:
private void MetricNewFrameReadyEventHandler(object sender, IEnumerable<Skeleton> skeletons)
    {
        foreach (IMetric metric in _metrics)
            metric.AddSkeletons(skeletons);
    }

But MetricNewFrameReadyEventHandler is never run.
I guess I'm only reading the file in the background. How can I use a backgroundworker to run MetricNewFrameReadyEventHandler in the background ?
Thank you


text:
Q: Efficient way to update values in a GeoDataFrame based on the result of DataFrame.within method I have two large GeoDataFrame:
One came from a shapefile where each polygons has a float value called 'asapp'.
Second are the centroids of a fishnet grid with 3x3 meters and a column 'asapp' zeroed.
What I need is to fill the 'asapp' of the second one base where the centroid is within the polygons of the first.
The code below do this but with a ridiculos low rate of 15 polygons per sec (One of the smallest shapefile has more tha 20000 polygons).
# fishnet_grid is a dict created by GDAL with a raster with 3m pixel size
cells_in_wsg = np.array([(self.__convert_geom_sirgas(geom, ogr_transform), int(fid), 0.0) for fid, geom in fishnet_grid.items()])

# transforming the grid raster (which are square polygons) in a GeoDataframe of point using the centroids of the cells
fishnet_base = gpd.GeoDataFrame({'geometry': cells_in_wsg[..., 0], 'id': cells_in_wsg[..., 1], 'asapp': cells_in_wsg[..., 2]})
fishnet = gpd.GeoDataFrame({'geometry': fishnet_base.centroid, 'id': fishnet_base['id'], 'asapp': fishnet_base['asapp']})

# as_applied_data is the polygons GeoDataFrame
# the code below takes a lot of time to complete
for as_applied in as_applied_data.iterrows():
    fishnet.loc[fishnet.within(as_applied[1]['geometry']), ['asapp']] += [as_applied[1]['asapp']]

There is another way to do this with better performance?
Tys!

A: I solved the problem.
I readed about using geopandas.overlay (https://geopandas.org/en/stable/docs/user_guide/set_operations.html) with work with a lot of polygons, but the problem is that it work only with polygons and I had polygons and points.
So, my solution, was to create very small polygons (2cm side squares) from the points and then using the overlay.
The final code:
# fishnet is now a GeoDataFrame of little squares
fishnet = gpd.GeoDataFrame({'geometry': cells_in_wsg[..., 0], 'id': cells_in_wsg[..., 1]})

#intersection has only the little squares that intersects with all as_applied_data polygons and the value in those polygons
intersection = gpd.overlay(fishnet, as_applied_data, how='intersection')

# now this is as easy as to calculate the mean and put it back in the fishnet using the merge
values = fishnet.merge(intersection.groupby(['id'], as_index=False).mean())
#and values has the the little squares, the geom_id and the mean values of the intersections!

Its worked very fine!


text:
Q: getting error "Illegal conversion from List to List" Here is my code
public with sharing class estimatevsPipeline {
    @AuraEnabled
    public static List<Opportunity> getestimatevsPipeline() {
        return [
            SELECT SUM(amount_ge_og__c) sumAmount
            FROM Opportunity
            WHERE
                ((IsClosed != TRUE
                AND ForecastCategoryName IN ('Commit', 'Commit at Risk'))
                OR StageName = 'Closed Won')
                AND RecordType.DeveloperName != 'Targets'
                AND Type IN ('Internal to GE Parent', 'Internal to BHGE', 'External')
                AND forecast_pipeline_exception_ge_og__c != TRUE
                AND CloseDate = THIS_QUARTER
                AND Id IN (
                    SELECT OpportunityId
                    FROM OpportunityTeamMember
                    WHERE
                        (UserId IN ('0051H000009S5D2QAK', '00512000007jB49AAE', '0051H00000Aw9VbQAJ')
                        OR UserId = '0051H00000AwEezQAF')
                        AND TeamMemberRole != 'Following'
                )
        ];
    }
}

A: The issue is that you're using SUM function, this can only be used with Aggregated Queries. If so you should probably GROUP BY result by some field and change return type of the method to List<AggregateResult>.
If you want just a normal query then remove SUM from SELECT.
Here is also docs on how to use Aggregation in SOQL.
Hopefully, this helps


text:
Q: Was Yoda wrong about the limits of telekinesis? In Empire Strikes Back, Yoda tells Luke that an object's size doesn't matter and that the difficulty of levitating an X-Wing was only in his mind. If the upper limits of telekinesis are determined by belief, what's to stop a Jedi/Sith from pulling a moon out of orbit, moving an entire solar system, or splitting an atom with the Force?

A: Yes and No. Yoda may have been being metaphorical in his explanation of size not mattering. He was doing that zen master thing where the master asks or promotes an idea which makes the student think differently about whatever they are discussing. (What is the sound of one hand clapping...)
Size may matter less than one might believe but mass is surely a factor in moving something with Force Telekinesis. All things being equal, Force telekinesis likely has both mass limits and size limitations which vary from Jedi to Jedi. Even all of the greatest Force Telekinesis feats ever performed none have ever tried to move a natural body as large as a moon.
However, there are several examples of Jedi using Force Telekinesis to do amazing feats including pulling starships from the sky, and pushing entire fleets out of starsystems. Without an understanding of the physics of Force Telekinesis, it is impossible for anyone who wants to use physics to understand the physical limits.
Wookieepedia lists several examples of Force Telekinesis, canon and non-canon.

Among the most skilled users of telekinesis were the Zeison Sha. Neither Jedi nor Sith, their skilled use of telekinetic force use was developed over decades of simply surviving their planet's harsh environment, surpassing even some of the most powerful of Jedi in their skills. Their weapon of choice was a discblade, a circular bladed weapon that was thrown and manipulated with the Force and could be recalled. It required great skill in telekinesis to be wielded effectively.
The finest display of telekinesis ever, Jedi Dorsk 81, utilizing the channeled Force powers of all available Jedi of Luke Skywalker's Jedi Praxeum, used telekinesis to push seventeen Imperial I-class Star Destroyers out of the Yavin system. The massive amount of Force energy claimed the Jedi's life.
Perhaps, the most powerful of telekinetics were Galen Marek and Revan. Galen Marek was able to pull up the Imperial Star Destroyer, to himself. Revan broke away a considerable piece of Star Forge and crushed more then a hundred droids and Sith acolytes, by it.

Galen Marek was able to pull up the Imperial Star Destroyer, to himself. How much do those things weigh, anyway?


text:
Q: QGroupBox's child restricts shrink the form I have a multiple screen video player, and I just want to keep 16:9 ratio. There is a qgroupbox as a container of a qwidget which plays video in it. I also use qgroupbox to show selected frame by painting border to green. I can't do this on qwidget because rendered video overlaps that. When I have done with resize, I emit a signal with mouseup event to be able to informed about the resize operation completed. Then I calculate new bounds for qwidget to keep 16:9 ratio and apply this values for qwidget. Here is the image to show you how my app looks like:

And here is the code that I use to resize qwidgets:
void playBack::OnWindowResized()
{
    float ratio = 16.0f / 9.0f;
    float w = playBackplayer_contList.at(0)->size().width(); //qgroupbox's width
    float h = playBackplayer_contList.at(0)->size().height();//qgroupbox's height
    float currentRatio = w / h;
    float newW = 0;
    float newH = 0;
    if (currentRatio > ratio)
    {
        newH = h;
        newW = h*ratio;
    }
    else if (currentRatio < ratio)
    {
        newW = w;
        newH = w / ratio;
    }

    qDebug() << "NEW WIDGET SIZE: " << (int)newW << " x " << (int)newH;

    for (int i = 0; i < playBackplayer_widgtList.count(); i++)
    {
        playBackplayer_widgtList.at(i)->setMinimumSize(newW, newH);
        //playBackplayer_widgtList.at(i)->resize(newW, newH);
    }
}

This code works perfectly when I enlarge form, but When I want to shrink, It doesn't allow me to do that. Because I set a minimum value for qwidgets. If I don't use setMinimumSize, use resize(w,h) instead, than orientation problems occur. And here is a example for this issue:

This code below shows ctor and this is where I set the layout:
playBack::playBack()
{
    playback_player_1_widget = new QWidget;
    playback_player_2_widget = new QWidget;
    playback_player_3_widget = new QWidget;
    playback_player_4_widget = new QWidget;

    playback_player_1_widget_cont = new QGroupBox;
    playback_player_2_widget_cont = new QGroupBox;
    playback_player_3_widget_cont = new QGroupBox;
    playback_player_4_widget_cont = new QGroupBox;

    playBackplayer_widgtList.append(playback_player_1_widget);
    playBackplayer_widgtList.append(playback_player_2_widget);
    playBackplayer_widgtList.append(playback_player_3_widget);
    playBackplayer_widgtList.append(playback_player_4_widget);

    playBackplayer_contList.append(playback_player_1_widget_cont);
    playBackplayer_contList.append(playback_player_2_widget_cont);
    playBackplayer_contList.append(playback_player_3_widget_cont);
    playBackplayer_contList.append(playback_player_4_widget_cont);

    int rowcnt = 0;
    int colcnt = 0;
    for (int i = 0; i < 4; i++)
    {
        playBackplayer_contList.at(i)->setStyleSheet(QString("border:1px solid #000;background-color:#000;"));
        playBackplayer_widgtList.at(i)->setStyleSheet(QString("background-color:#f00;"));
        QGridLayout* layout = new QGridLayout;
        layout->setRowStretch(0, 1);
        layout->setColumnStretch(0, 1);
        layout->setRowStretch(2, 1);
        layout->setColumnStretch(2, 1);
        playBackplayer_widgtList.at(i)->setMinimumWidth(100);
        playBackplayer_widgtList.at(i)->setMinimumHeight(100);
        playBackplayer_widgtList.at(i)->setMaximumWidth(10000);
        playBackplayer_widgtList.at(i)->setMaximumHeight(10000);

        layout->addWidget(playBackplayer_widgtList.at(i),1,1);
        layout->setMargin(0);
        layout->setSpacing(0);

        playBackplayer_contList.at(i)->setLayout(layout);

        mainLayout->addWidget(playBackplayer_contList.at(i), colcnt, rowcnt);

        rowcnt++;
        if (rowcnt % 2 == 0)
        {
            rowcnt = 0;
            colcnt++;
        }

        playBackplayer_widgtList.at(i)->setAcceptDrops(true);
    }
}

I have tried various things, I have tried to set size 0 for qwidget before resize, (in mousedownevent) that didn't work, I have tried deleting layout for qgroupbox, after resize happens, create new layout and set it for groupbox, that didn't work, I have tried layout()->adjustSize(), update(), repaint(), all that stuff didn't work. What am I missing? I need helps from you. Any help would be appreciated. Thank you in advance.

A: Do away with the grid layout inside the container group boxes. Instead, align and resize the video widget with setGeometry
Here is a simple subclass of QGroupBox I made that keeps your desired ratio and always stays in the center:
class RatioGroupBox : public QGroupBox{
    Q_OBJECT
public:
    RatioGroupBox(QWidget *parent = nullptr) : QGroupBox (parent){
        setFlat(true);
        setStyleSheet("border:1px solid #000;background-color:#000;");
        setMinimumSize(100, 100);
        setMaximumSize(10000, 10000);
        ratio = 16.0f/9.0f;
        ratioWidget = new QWidget(this);
        ratioWidget->setStyleSheet("background: #f00;");
        ratioWidget->setAcceptDrops(true);
    }

protected:
    void resizeEvent(QResizeEvent *){//or you can use your own resize slot
        float w = width();
        float h = height();
        float currentRatio = w/h;
        float newW(0);
        float newH(0);
        if (currentRatio > ratio){
            newH = h;
            newW = h*ratio;
        }
        else if (currentRatio < ratio){
            newW = w;
            newH = w / ratio;
        }

        ratioWidget->setGeometry((w-newW)/2, (h-newH)/2, newW, newH);
    }

private:
    QWidget *ratioWidget;
    float ratio;
};

Your entire ctor will become something like:
playBack::playBack()
{
    for(int r=0; r<2; r++){
        for(int c=0; c<2; c++){
            RatioGroupBox* playback_player_cont = new RatioGroupBox;
            mainLayout->addWidget(playback_player_cont, c, r);
            playBackplayer_contList.append(playback_player_cont);
        }
    }
}

You can of course access your video widgets by exposing ratioWidget any way you like. Either by making it public or creating a getter function.


text:
Q: Allowing for mouse right-click Is there a way to allow for the right-click of the mouse? I want a menu to pop up when the right-button is clicked, Currently when the right button is clicked the program will exit. I have found information for keyboard shortcuts but i have not found any information for the mouse. I did look on the android developers site.

A: Depending on which environment you use it is different. But the scenario is the same. You need to create an event for that (extra you can calculate your mouse position to decide where to allow the right click). In Qt You can do something like following :
    void xxx::onRightClick()
{
  QPopupMenu* contextMenu = new QPopupMenu ( this );
  Q_CHECK_PTR ( contextMenu );

  contextMenu->insertItem ( "Copy" , this , SLOT (Copy()) );

  contextMenu->exec ( QCursor::pos() );
  delete contextMenu;
  contextMenu = 0;
}

Or you can just use an event filter. You can find the documentation for doing that in Qt here: Qt documentation for mouse events.
I hope this will help you.
Regards,
Mikael


text:
Q: Java on kill method I have a java program which writes 1 file into multiple files, not all connections are open at the same time.
I want to add an method to remove all of these created files when the program is killed (by using ctrl-c in the command line).
Adding a shutdown hook is always executed when the object is shut down, I only want to remove them if the program is killed.
Is there an RuntimeException I can catch?

A: Take a look at Runtime.getRuntime().addShutdownHook(). Here's an example.


text:
Q: Turn off display in Ubuntu on Wayland I recently installed a program on my Ubuntu 20.04 machine that needs Wayland instead of X11 to work. I also frequently used the command xset dpms force off to turn of my display. However, this command does not work in Wayland and gives the error message : server does not have extension for dpms option. Is there a way to turn off the display in wayland ?

A: In Wayland (and Xorg), you can activate the screensaver if that is set to blank the screen:
dbus-send --session --dest=org.gnome.ScreenSaver --type=method_call \
          /org/gnome/ScreenSaver org.gnome.ScreenSaver.SetActive boolean:true


text:
Q: nested ifelse in R so close to working I'm working with the following four columns of raw weight measurement data and a very nearly-functioning nested ifelse statement that results in the 'kg' vector.
     Id       G4_R_2_4         G4_R_2_5        G4_R_2_5_option2          kg
219 13237       16.0             NA                  NA                16.0
220 139129      8.50             55.70               47.20             8.50
221 139215      28.9             NA                  NA                28.9
222 139216       NA              46.70               8.50              46.70
223 139264      12.40            NA                  NA                12.40
224 139281      13.60            NA                  NA                13.60
225 139366      16.10            NA                  NA                16.10
226 139376      61.80            NA                  NA                61.80
227 140103      NA               48.60               9.10              48.60

The goal is to merge the three 'G4' columns into kg based on the following conditions:
1) If G4_R_2_4 is not NA, print its value
2) If G4_R_2_4 is NA, print the lesser of the values appearing in G4_R_2_5 and G4_R_2_5_option2 (sorry for lame variable names)
I've been working with the following statement (big dataset called 'child'):
> child$kg <- ifelse(child$G4_R_2_4 == 'NA' & child$G4_R_2_5 < child$G4_R_2_5_option2,
   child$G4_R_2_5, ifelse(child$G4_R_2_4 == 'NA' & child$G4_R_2_5 > child$G4_R_2_5_option2,
                          child$G4_R_2_5_option2, child$G4_R_2_4))

Which results in the 'kg' vector I have now. It seems to satisfy the G4_R_2_4 condition (is/is not NA) but always prints the value from G4_R_2_5 for the NA cases. How do I get it to incorporate the greater than/less than condition?

A: It's not clear from your example, but I think the problem is you're handling NA's incorrectly and\or using wrong type for data.frame's columns. Try rewriting your code like that:
#if your columns are of character type (warnings are ok)
child$G4_R_2_4<-as.numeric(child$G4_R_2_4)
child$G4_R_2_5<-as.numeric(child$G4_R_2_5)
child$G4_R_2_5_option2<-as.numeric(child$G4_R_2_5_option2)
#correct NA handling
child$kg<-ifelse(is.na(child$G4_R_2_4) & child$G4_R_2_5 <
   child$G4_R_2_5_option2, child$G4_R_2_5, ifelse(is.na(child$G4_R_2_4) &
     child$G4_R_2_5 > child$G4_R_2_5_option2, child$G4_R_2_5_option2, child$G4_R_2_4))

A: We could do this using pmin.  Assuming that your 'G4' columns are 'character' class, we convert those columns to 'numeric' class and use pmin on that columns.
 indx <- grep('^G4', names(child))
 child[indx] <- lapply(child[indx], as.numeric)
 d1 <- child[indx]
 child$kgN <- ifelse(is.na(d1[,1]), do.call(pmin, c(d1[-1], na.rm=TRUE)), d1[,1])
 child$kgN
 #[1] 16.0  8.5 28.9  8.5 12.4 13.6 16.1 61.8  9.1

Or without using ifelse
 cbind(d1[,1], do.call(pmin, c(d1[-1], na.rm=TRUE)))[cbind(1:nrow(d1),
             (is.na(d1[,1]))+1L)]
 #[1] 16.0  8.5 28.9  8.5 12.4 13.6 16.1 61.8  9.1

Benchmarks
set.seed(24)
child1 <- as.data.frame(matrix(sample(c(NA,0:50), 1e6*3, replace=TRUE),
    ncol=3, dimnames=list(NULL, c('G4_R_2_4', 'G4_R_2_5',
                'G4_R_2_5_option2'))) )
cyberj0g <- function(){
   with(child1, ifelse(is.na(G4_R_2_4) & G4_R_2_5 <
     G4_R_2_5_option2, G4_R_2_5, ifelse(is.na(G4_R_2_4) &
       G4_R_2_5 > G4_R_2_5_option2, G4_R_2_5_option2, G4_R_2_4)))
  }

 get_kg <- function(x){
      if(!is.na(x[2])) return (x[2])
      return (min(x[3], x[4], na.rm = T))}
RHertel <- function() apply(child1,1,get_kg)

akrun <- function(){cbind(child1[,1], do.call(pmin, c(child1[-1],
    na.rm=TRUE)))[cbind(1:nrow(child1),  (is.na(child1[,1]))+1L)]}

system.time(cyberj0g())
#  user  system elapsed
# 0.451   0.000   0.388

system.time(RHertel())
#   user  system elapsed
# 11.808   0.000  10.928

system.time(akrun())
#   user  system elapsed
#  0.000   0.000   0.084

library(microbenchmark)
microbenchmark(cyberj0g(), akrun(), unit='relative', times=20L)
#Unit: relative
#       expr      min       lq     mean   median       uq      max neval cld
# cyberj0g() 3.750391 4.137777 3.538063 4.091793 2.895156 3.197511    20   b
#    akrun() 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000    20   a

A: Here is an alternative version that might be interesting, assuming that the values are stored in numerical form (else the column entries should be converted into numerical values, as suggested in the other answers):
get_kg <- function(x){
 if(!is.na(x[2])) return (x[2])
 return (min(x[3], x[4], na.rm = T))}

child$kg <- apply(child,1,get_kg)

#> child
#        Id G4_R_2_4 G4_R_2_5 G4_R_2_5_option2   kg
#219  13237     16.0       NA               NA 16.0
#220 139129      8.5     55.7             47.2  8.5
#221 139215     28.9       NA               NA 28.9
#222 139216       NA     46.7              8.5  8.5
#223 139264     12.4       NA               NA 12.4
#224 139281     13.6       NA               NA 13.6
#225 139366     16.1       NA               NA 16.1
#226 139376     61.8       NA               NA 61.8
#227 140103       NA     48.6              9.1  9.1

A: I'm pretty sure the problem is that you're not testing whether the values are NAs, you're testing whether they are equal to the string "NA", which they never are. This should work:
child$kg <- ifelse(is.na(child$G4_R_2_4) &
                   child$G4_R_2_5 < child$G4_R_2_5_option2,
                   child$G4_R_2_5,
              ifelse(is.na(child$G4_R_2_4) &
                     child$G4_R_2_5 > child$G4_R_2_5_option2,
                     child$G4_R_2_5_option2,
                       child$G4_R_2_4))


text:
Q: How do I grep output of logs with dynamic columns Log file:
2015-11-29 02:24:14,053 DEBUG ExcludePostalCodesServiceImpl [messageListenerContainer-38] :88 - Postal Code : 5118 is Excluded for country : AU
2015-11-29 02:24:14,077  INFO BatchExecutionListener [messageListenerContainer-35] :29 - ----------FINISH JOB: shipmentJob, JOB_INSTANCE_ID: 121453924, EXIT_CODE: COMPLETED----------
2015-11-29 02:24:14,054  INFO ShipmentRuleRunnerImpl [messageListenerContainer-38] :83 - Shipment is not selected due to exclusion postal code: [awb=40738xxxxx, shp_acct_no=7612xxxxx, rcvr_name=xxxxx, rcvr_org=CAROLxxx, org_ctry=US, dest_ctry=AU, dest_addr=xxxxxxxx,

Say the above file is a huge one. I would like to :
1) grep -B 3 "Shipment is not selected due to exclusion postal code" xxxx.log
 - This is to grep the keyword that I require, and return 3 lines before
2) I would like to then, filter out lines containing [messageListenerContainer-38] , in this example so that output would be as below. Note that the [messageListenerContainer-35] is missing as I only want the the one that is associated with the first keyword grep.
2015-11-29 02:24:14,053 DEBUG ExcludePostalCodesServiceImpl [messageListenerContainer-38] :88 - Postal Code : 5118 is Excluded for country : AU
2015-11-29 02:24:14,054  INFO ShipmentRuleRunnerImpl [messageListenerContainer-38] :83 - Shipment is not selected due to exclusion postal code: [awb=40738xxxxx, shp_acct_no=7612xxxxx, rcvr_name=xxxxx, rcvr_org=CAROLxxx, org_ctry=US, dest_ctry=AU, dest_addr=xxxxxxxx,

grep -B 3 "Shipment is not selected due to exclusion postal code" xxx.log | grep [messageListenerContainer-38]
works if the tag is unique all the time, but if I were to grep from a huge list of logs (returning multiple results), the number in xx [messageListenerContainer-xx] is dynamic.
It will also be reused after some time, hence I would have to restrict the grep -B to 5 to only grep a certain amount of lines before that is relevant. (nature of logs)
Hence, is it possible to grep a few lines before a certain keyword AND then do a further filter to only take ones with the [messageListenerContainer-xx] associated with the first grep?

A: This might work for you (GNU sed):
sed -r ':a;$!N;s/[^\n]+/&/3;$!Ta;/\n[^\n]*Shipment bla bla [^\n]*$/!D;:b;/^[^\n]*(messageListenerContainer -[0-9]+ ).*\n[^\n]*\1[^\n]*$/P;s/^[^\n]*\n//;tb' file

The solution is in two parts. First a rolling window of n lines (in this case 3) is selected and the last (or first depending on your view) line of window is matched with the required string (in this case Shipment bla bla). Having established that the lines in the pattern space meet the required criteria, using pattern matching the first and last lines are compared to see if they meet the second criteria i.e. messageListenerContainer - .... If so the first line is printed and reguardless then deleted. This is repeated until all lines are processed and then the last line is printed.

A: awk to the rescue!
I think you're looking for something like this.
$ awk -v n=4      '{p=p%n;a[p++]=$0}
   /search_pattern/{key=$5;
                    for(i=p;i<p+n;i++)
                      {line=a[i%n];
                       if(line ~ key) print line}}' log

X X X X X-38 XXXX
X X X X X-38 XXXX
X X X X X-38 search_pattern

where
$ cat log
X X X X X-35 XXXX
X X X X X-35 XXXX
X X X X X-35 XXXX
X X X X X-38 XXXX
X X X X X-35 XXXX
X X X X X-38 XXXX
X X X X X-38 search_pattern
X X X X XXXX XXX

for the searched pattern look back for n lines and print the lines that are correlated with the key ($5) field.  For exact match you can change regex match ~ with equality ==.


text:
Q: jquery select an element in a table before another i have an table where i add some rows
....
Connect
Disconnect
....

i need to select .thisState from an click over .buttonDisconnect ....
i try this but didn't work
$('#table').on('click', ".buttonDisconnect", function () {
    .... disconnection code
    $(this).html("Connect");
    $(this).toggleClass("buttonDisconnect is-danger buttonConnect has-text-success");
    // toggle state
    $(this).prev(".thisState").text("Disconnect");
    $(this).prev(".thisState").toggleClass("has-text-danger has-text-success");
});

A: If you pass a selector to .prev, the previous element will be selected only if the previous element matches the selector. But the selector you're passing is for a child of the previous element - it doesn't match the previous element.
Another issue is that the clicked element is the , not the  - navigate to the parent  before going to the previous one.
Navigate to the previous element unconditionally and use .children to go to its child filtering by the selector, then do what you need to do:
const $prevStrongState = $(this).parent().prev().children('.thisState');
$prevStrongState.text("Disconnect");
$prevStrongState.toggleClass("has-text-danger has-text-success");

$('#table').on('click', ".buttonDisconnect", function() {
  $(this).html("Connect");
  $(this).toggleClass("buttonDisconnect is-danger buttonConnect has-text-success");
  const $prevStrongState = $(this).parent().prev().children('.thisState');
  $prevStrongState.text("Disconnect");
  $prevStrongState.toggleClass("has-text-danger has-text-success");
});

    Connect
    Disconnect

A: When you call to prev you are getting the previous element of your current element.
Since your element has no previous siblings, this returns nothing. Instead, you have to go up in the DOM to get the previous td and then look for the thisState children:
$(this).closest('td').prev('td').children(".thisState");


text:
Q: how to set scss dynamic class name of margin values How to set the scss dynamic class name using margin values.
This is what I tried
$spaceamounts: (1, 3, 5, 8, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 110, 120, 130, 140,150,160,170,180,);
$sides: (top, bottom, left, right);

@each $space in $spaceamounts {
  @each $side in $sides {
    .m#{str-slice($side, 0, 1)}-#{$space} {
      margin-#{$side}: #{$space}px !important;
    }
    .p#{str-slice($side, 0, 1)}-#{$space} {
      padding-#{$side}: #{$space}px !important;
    }
  }
}

So I can use margin/padding class name like pt-1, mt-10
But I want to set the $spaceamounts value as  1~999.
Anyone know how to fix the code?

A: If you want to create a class for every values between 1 and 999, you can get rid of $spaceamounts and use a @for loop:
$sides: (top, bottom, left, right);

@for $i from 1 through 999 {
  @each $side in $sides {
    .m#{str-slice($side, 0, 1)}-#{$i} {
      margin-#{$side}: #{$i}px !important;
    }
    .p#{str-slice($side, 0, 1)}-#{$i} {
      padding-#{$side}: #{$i}px !important;
    }
  }
}

For what it's worth, I think that it's not something you should do as it will generate a massive amount of code.


text:
Q: how to restructure date format to another format to get new columns I have such dataset
DT=structure(list(date = c("01.01.2021", "01.01.2021", "01.01.2021",
"01.01.2021", "01.01.2021", "01.01.2021", "01.01.2021", "01.01.2021",
"01.01.2021", "01.01.2021", "01.01.2021", "01.02.2021", "01.02.2021",
"01.02.2021", "01.02.2021", "01.02.2021", "01.02.2021", "01.02.2021",
"01.02.2021", "01.02.2021"), sales_count = c(10L, 4L, 8L, 6L,
4L, 4L, 4L, 3L, 1L, 5L, 2L, 10L, 5L, 9L, 2L, 8L, 5L, 6L, 8L,
3L)), class = "data.frame", row.names = c(NA, -20L))

it looks something like this
         date sales_count
1  01.01.2021          10
2  01.01.2021           4
3  01.01.2021           8
4  01.01.2021           6

How can I remake the dataset so that it has exactly this input format
      sales_count    date_time       date   week_num weekday
   1: 1        2016-05-02 00:00:00 2016-05-02  1     Monday
   2: 10       2016-05-02 00:00:00 2016-05-02  1     Monday
   3: 14       2016-05-02 00:00:00 2016-05-02  1     Monday
   4: 15       2016-05-02 00:00:00 2016-05-02  1     Monday
   5: 20       2016-05-02 00:00:00 2016-05-02  1     Monday

A: Using lubridate. I'm not sure you expect different dates in your expected output compared to your original dataframe.
library(lubridate)

tibble(DT) %>%
  mutate(date = mdy(date),
         date_time = ymd_hms(format(date, "%Y-%m-%d 00:00:00")),
         week_num = week(date),
         weekday = weekdays(date)) %>%
  select(sales_count, date_time, date, week_num, weekday)

# A tibble: 20 x 5
   sales_count date_time           date       week_num weekday
         <int> <dttm>              <date>        <dbl> <chr>
 1          10 2021-01-01 00:00:00 2021-01-01        1 Friday
 2           4 2021-01-01 00:00:00 2021-01-01        1 Friday
 3           8 2021-01-01 00:00:00 2021-01-01        1 Friday
 4           6 2021-01-01 00:00:00 2021-01-01        1 Friday
 5           4 2021-01-01 00:00:00 2021-01-01        1 Friday
 6           4 2021-01-01 00:00:00 2021-01-01        1 Friday
 7           4 2021-01-01 00:00:00 2021-01-01        1 Friday
 8           3 2021-01-01 00:00:00 2021-01-01        1 Friday
 9           1 2021-01-01 00:00:00 2021-01-01        1 Friday
10           5 2021-01-01 00:00:00 2021-01-01        1 Friday
11           2 2021-01-01 00:00:00 2021-01-01        1 Friday
12          10 2021-01-02 00:00:00 2021-01-02        1 Saturday
13           5 2021-01-02 00:00:00 2021-01-02        1 Saturday
14           9 2021-01-02 00:00:00 2021-01-02        1 Saturday
15           2 2021-01-02 00:00:00 2021-01-02        1 Saturday
16           8 2021-01-02 00:00:00 2021-01-02        1 Saturday
17           5 2021-01-02 00:00:00 2021-01-02        1 Saturday
18           6 2021-01-02 00:00:00 2021-01-02        1 Saturday
19           8 2021-01-02 00:00:00 2021-01-02        1 Saturday
20           3 2021-01-02 00:00:00 2021-01-02        1 Saturday


text:
Q: HTML - HR Tag (Horizontal Line) Question 1: How do I remove formatting on HR lines so they are just plain lines? Currently, they look like this: http://i.imgbomb.com/yyEGj.png. As you can see, they have a bit of formatting or style. Almost double layered. I want it to look like this: http://i.imgbomb.com/WtwTB.png

A: I had this problem also and I used this to get it back to just a 1px line:
border: none;
color:#000000;
background-color:#000000;
height:1px;

Fiddle


text:
Q: Search and Sum based on selection I tried Sum, CountIf, Dsum, SumProduct
I have a Userform with a ComboBox "History_Select_Debtor". The RowSource for the ComboBox is "Debtor_list_Debtors" - A Dynamic Named Range on WorkSheet "DebtorList". It consists of Customer Names from A2:A24 but will grow eventually.
The UserForm also Has a Textbox for Total Items Purchased Named "txtPurchased".
With each Transaction a Record is saved on Worksheet "InvoiceList" which consists of 7 Columns.
Each of these Columns have Dynamic Named Ranges
A = "Debtor" (Invoice_list_Debtor)
B = "Item" (Invoice_list_Item)
C = "Price" (Invoice_list_Price)
D = "Date" (Invoice_list_Date)
E = "Time" (Invoice_list_Time)
F = "Balance" (Invoice_list_Balance)
G = "Payed" (InvoiceList_Payed)

The Record Saved in the Item Column is Text;
"Payed Balance","Added Balance","Quarter Item","Half Item","1 Item" - "10 Items"
I need to, "Based on the combo selection (History_Select_Debtor)", Reference that Particilar Debtor with "InvoiceList", sum up the total Number of Purchases and display that Value in "txtPurchased".
I need a specific Value to be assigned to each Item e.g. "Quarter Item" = 0.25 or "5 Item = 5".
If as an example "Adrian" has 7 Transactions recorded on InvoiceList
Added Balance
Quarter Item
Half Item
Quarter Item
10 Items
4 Items
Payed Balance

The Value to be displayed in "txtPurchased" would be "15".
I've a Macro that sums up the total Purchases;
It sums up the Total Row rather than just whichever Debtor is Selected in "History_Select_Debtor"
'-------Total Transactions----------------------------------------------------------------------
Set ws = Worksheets("DebtorList")
    With Me
    'Starting point of lookup data
    Rw = .History_Select_Debtor.ListIndex + 2
    History_Select_Debtor.List = Range("Debtor_list_Debtors").Value
txtTransactions.Value = Application.CountIf(Range("Invoice_list_Debtor"), History_Select_Debtor)
End With
'-----------------------------------------------------------------------------------------------

Another Macro I've made which also won't work;
=SUM(IF(Invoice_list_Item="Quarter Item",0.25,0)+IF(Invoice_list_Item="Half Item",0.5,0)+IF(Invoice_list_Item="1 Item",1,0)+IF(Invoice_list_Item="2 Items",2,0)+IF(Invoice_list_Item="3 Items",3,0)+IF(Invoice_list_Item="4 Items",4,0)+IF(Invoice_list_Item="5 Items",5,0)+IF(Invoice_list_Item="10 Items",10,0))

The Issue with this one is that given I use the Invoice_list_Debtor as the RowSource for my ComboBox I end up with over 170 duplicate Names.
Here is the Source Code to the Page I need to code to work on;
Public ListTable As Long

Private Sub UserForm_Initialize()

    History_Select_Debtor.List = Range("Debtor_list_Debtors").Value
    History_Select_Debtor = ""

Label6.Visible = False
Label7.Visible = False
Label8.Visible = False
Label9.Visible = False
Label10.Visible = False
Label11.Visible = False
Label12.Visible = False

Dim ws As Worksheet

Set ws = Worksheets("InvoiceList")
ListTable = ws.Range("A65536").End(xlUp).Row
Me.ListBox1.List = Range("A2:G" & ListTable).Value
Me.ListBox1.Clear
Me.ListBox1.ColumnWidths = "50;80;70;100;80;80;80"

'-----------Listview--------------------------------------------------------------------------------------------------------------
    'Dim ws As Worksheet
    'Dim lngRow As Long
    'Dim lvwItem As ListItem
    'Dim lngEndCol As Long
    'Dim lngCol As Long
    'Dim lngEndRow As Long
    'Dim lngItemIndex As Long
    'Dim blnHeaders() As Boolean
    'Dim Rw As Long

    'Set ws = Worksheets("InvoiceList")
    'lngEndCol = ws.Range("A1").End(xlToRight).Column
    'lngEndRow = ws.Range("A1").End(xlDown).Row
    'ListView1.Gridlines = True
    'lngRow = 1
    'With ListView1

        '.View = lvwReport
        'For lngCol = 1 To lngEndCol
            '.ColumnHeaders.Add , , ws.Cells(lngRow, lngCol).Text, ws.Columns(lngCol).ColumnWidth + 59.6
        '.BackColor = vbBlack
        'Next
        'For lngRow = 2 To lngEndRow
            'lngCol = 1
            'lngItemIndex = 0
            'Set lvwItem = .ListItems.Add(, , (ws.Cells(lngRow, lngCol).Text))
            'For lngCol = 2 To lngEndCol
                'lngItemIndex = lngItemIndex + 1
                'lvwItem.SubItems(lngItemIndex) = Format(ws.Cells(lngRow, lngCol).Text, ws.Cells(lngRow, lngCol).NumberFormat) 'Adds Value from Current Row and Column 1
            'Next
        'Next

            '.TextBackground = lvwTransparent

    'End With
'-----------Listview--------------------------------------------------------------------------------------------------------------
'-----------ChartSpace---------------------------------------------------
   Dim ChtSpc As OWC11.ChartSpace
   Dim cht As OWC11.ChChart
   Dim Sps As OWC11.Spreadsheet
   Dim owcChart As OWC11.ChartSpace
   Dim Balance As String

   Balance = Range("B1").Value
   Set owcChart = Me.ChartSpace1
   Set ChtSpc = Me.ChartSpace1
   Set Sps = Me.Spreadsheet1
   Set ws = ThisWorkbook.Worksheets("DebtorList")   ' change to you worksheet name

   Sps.Range("A1:B100") = ws.Range("A1:B100").Value   ' Set worksheet range to sheet control range

   Set ChtSpc.DataSource = Sps   ' set sheet control as chart control source

   Set cht = ChtSpc.Charts.Add  ' Add blank chart

   With cht ' Set data for chart
    .SetData chDimCategories, 0, "A2:A25"    ' change to your category range
    .SeriesCollection(0).SetData chDimValues, 0, "B2:B25" ' change to your series 1 range
    '.PlotArea.FlipHorizontal
    '.PlotArea.FlipVertical
    '.PlotArea.RotateClockwise
    '.SeriesCollection.Add
    '.SeriesCollection(1).SetData chDimValues, 0, "A1:A24" ' change to your series 2 range

    'By changing the layout we can control how the charts are presented
    'inside the Chart space.

   .Interior.Color = RGB(0, 0, 0)
   .Border.Color = vbWhite
   .Border.Weight = Thick

   '.Type = chChartTypeColumn3D
   '.Type = chChartTypeAreaStacked

End With

Me.Spreadsheet1.Visible = False     ' hide the sheet control

'Set up the charts and manipulate some of their properties.

With owcChart.Charts(0)

    'The data reference must be of the datatype string.
    'The last parameter specify if each row represent a serie or not.

    '.HasTitle = True

    With .PlotArea
        .Interior.Color = RGB(0, 0, 0)

        '.Border.Color = RGB(255, 255, 255)
        '.Border.DashStyle = chLineSolid
        '.Border.Weight = Thick
    End With

    'With .Title
        '.Caption = Balance
        '.Font.Name = "Verdana"
        '.Font.Size = 10
        '.Font.Bold = True
        '.Font.Color = RGB(50, 205, 50)
    'End With

    With .Axes(0).Font
        .Name = "Verdana"
        .Size = 8
        '.Bold = True
        .Color = RGB(255, 255, 255)
    End With

    With .Axes(1).Font
        .Name = "Verdana"
        .Size = 8
        '.Bold = True
        .Color = RGB(255, 255, 255)
    End With

    'With .Axes(0).MinorGridlines
        '.Line.Color = RGB(255, 255, 255)
    'End With

    'With .Axes(0).MajorGridlines
        '.Line.Color = RGB(255, 255, 255)
    'End With

    'With .Axes(1).MinorGridlines
        '.Line.Color = RGB(255, 255, 255)
    'End With

    'With .Axes(1).MajorGridlines
            '.Line.Color = RGB(255, 255, 255)
    'End With

    With .SeriesCollection(0)
        '.Border.Color = RGB(255, 255, 255)
        .Interior.Color = vbGreen
        .Caption = Balance
        .Line.Color = RGB(255, 255, 255)
    End With

    'With .SeriesCollection(1)
        '.Interior.Color = vbBlue
        '.Caption = Balance
    'End With

    '.HasLegend = True

    'With .Legend
        '.Position = chLegendPositionBottom
        '.Border.Color = vbWhite
        '.LegendEntries(2).Visible = False
    'End With

End With
'------------------------------------------------------------------------

End Sub

Private Sub cmdClose_History_Click()

  Unload Me
  frmMenu.Show

End Sub

Private Sub History_Select_Debtor_Change()

'--------Total Purchased-----------------------------------------------
    'Worksheets("InvoiceList").Rows(1).AutoFilter Field:=1, Criteria1:="=" & Me.History_Select_Debtor
    'Me.txtPurchased = Worksheets("Summary").[C2] 'the cell containing the SUBTOTAL
'-------------------------------------------------------

Label6.Visible = True
Label7.Visible = True
Label8.Visible = True
Label9.Visible = True
Label10.Visible = True
Label11.Visible = True
Label12.Visible = True

FilterList 0, Me.History_Select_Debtor.Text

Me.cmdClose_History.SetFocus

Dim ws As Worksheet
Dim Rw As Long

Set ws = Worksheets("DebtorList")

    'Get row based on ComboBox ListIndex
    With Me
    'Starting point of lookup data
    Rw = .History_Select_Debtor.ListIndex + 2
    'Data to be displayed based on selection
    txtBalance.Value = FormatCurrency(Expression:=ws.Cells(Rw, 2).Value, _
    NumDigitsAfterDecimal:=2)

End With
'-------Total Transactions----------------------------------------------------------------------------------------------------------------------
Set ws = Worksheets("DebtorList")
    With Me
    'Starting point of lookup data
    Rw = .History_Select_Debtor.ListIndex + 2
    History_Select_Debtor.List = Range("Debtor_list_Debtors").Value
txtTransactions.Value = Application.CountIf(Range("Invoice_list_Debtor"), History_Select_Debtor)
End With
'-------Total Payed------------------------------------------------------------------------------------------------------------------------------
txtPayed.Value = FormatCurrency(Expression:=Application.SumIf(Range("Invoice_list_Debtor"), _
History_Select_Debtor.Value, Range("Invoice_list_Price")), _
    NumDigitsAfterDecimal:=2)

End Sub

Private Sub UserForm_QueryClose _
  (Cancel As Integer, CloseMode As Integer)
'   Prevents use of the Close button
    If CloseMode = vbFormControlMenu Then
        Cancel = True
    End If
End Sub

Private Sub FilterList(iCtrl As Long, sText As String)
Dim iRow As Long
Dim ws As Worksheet
Dim sCrit As String
sCrit = "*" & UCase(sText) & "*"
Set ws = Worksheets("InvoiceList")
With Me.ListBox1

ListTable = ws.Range("A65536").End(xlUp).Row
.List = ws.Range("A2:G" & ListTable).Value

For iRow = .ListCount - 1 To 0 Step -1
If Not UCase(.List(iRow, iCtrl)) Like sCrit Then
.RemoveItem iRow
End If
Next iRow

        'Determine number of columns
        .ColumnCount = 7
        'Set column widths
        .ColumnWidths = "50;80;70;100;80;80;80"
        'Insert the range of data supplied
        For x = 2 To 3 'loop the numeric columns - 3 to 4
            For i = 0 To .ListCount - 1 'loop through the rows of columns 3 to 5
                .List(i, x) = Format(.List(i, x), "$#,##")
            Next i
        Next x
                For x = 5 To 6 'loop the numeric columns - 4 to 5
            For i = 0 To .ListCount - 1 'loop through the rows of columns 3 to 5
                .List(i, x) = Format(.List(i, x), "$#,##")
            Next i
        Next x
                For x = 4 To 4 'loop the numeric columns - 3 to 4
            For i = 0 To .ListCount - 1 'loop through the rows of columns 3 to 5
                .List(i, x) = Format(.List(i, x), "[$-409]h:mm AM/PM;@")
            Next i
        Next x
End With

End Sub

A: There is more than one issue here I believe ...
To get the total number of invoiced items for a debtor you can

*

*(auto)filter the InvoiceList for your current Debtor

*display the sum of invoiced items using the =SUBTOTAL(109,InvoiceSheet!$F:$F) worksheet function (asuming the invoice sheet is named [InvoiceSheet] ;-) )

I would even suggest to have that =SUBTOTAL on a seperate sheet (Sheet2), so it's location is constant. Don't use ControlSource() on the text field in the dialog, but set Locked = True
You can set up Autofilter on [InvoiceSheet] once and use the Sub
Private Sub History_Select_Debtor_Change()
    Worksheets("InvoiceSheet").Rows(1).AutoFilter field:=1, Criteria1:="=" & Me.History_Select_Debtor
    Me.txtPurchased = Worksheets("Sheet2").[A1] 'the cell containing the SUBTOTAL
End Sub

to fire the filter and get the value of the SUBTOTAL formula back into the dialog.
For the transition of quantities from text to number I would suggest to create an extra sheet [QTYCode] looking like
         A        B    ...
  +------------+-----+----
1 |Text        |Value|
2 |Quarter item| 0.25|
3 |Half item   |  0.5|
4 |1 item      |    1|
5 |2 item      |    2|
6 |3 item      |    3|
...

where column A (except header row) serves as RowSource() for the QTY selection box, and for each record you create in [InvoiceSheet] you save not only the selected QTYText, but as well an extra column containing a =VLOOKUP() formula that converts text into value (and base your =SUBTOTAL() on that new column - of course)
Hope that helps
Good luck - MikeD


text:
Q: Rotation of the bmp file as a 2d array I have a bmp image and I am trying to rotate it by 180 degrees using c.
Here is the code that I got so far, but it does not rotate the image for some reasons(it does nothing with the image). Here h is the height of a picture and w is a width.
int rotate(int h, int w)
{
    FILE *infile = fopen("in2.bmp", "rb");
    FILE *outfile = fopen("copy3.bmp", "wb");

    char header[HEADER_SIZE];
    unsigned char pixels[h][w * 3];

    fread( header, 1 , HEADER_SIZE , infile);
    fread( pixels, 1 , h * w * 3 , infile);

    int r,c;

    for( r = 0; r < h; r++)
     {

         for ( c = 0; c < w * 3; c+=1)
         {
            char temp = pixels[r][c];
            pixels[r][c] = pixels[h-r-1][(w*3-1)-c];
            pixels[h-r-1][(w*3-1)-c] = temp;

         }
    }

    fwrite( header, sizeof(char)  , HEADER_SIZE  ,  outfile);
    fwrite( pixels, sizeof(char)  , h * w * 3  ,  outfile);

    fclose(infile);
    fclose(outfile);

    return 0;
}

Thank you!


text:
Q: Introduction book for JBoss Application Server I joined a programming competition that requires participant to use JBoss Application Server platform. Do you guys have any recommendation on what books or articles I could use?

A: Master the Boss is the place to start.

A: You can't go past the JBoss Community Documentation, specifically the Getting Started Guide!

A: About books, I was quite satisfied with the JBoss AS 7 Book.
Hope it helps
Linda

A: Just in case you are looking a bit forward the WildFly 8 book has been just published. Best regards.


text:
Q: geom_bar with x and fill aesthetics by one factor and dodge by a second I have this data.frame:
df <- data.frame(id = c("A","A","B","B","C","C"),
                 age = rep(c("young", "old"), 3),
                 value = c(20,15,7,5,2,6))

I'd like to plot it using ggplot2's geom_bar such that the bars are first separated (dodged) by age (but with no gaps between them) and then separated by id (along the x axis, with gaps), and are colored by id.
I'm only familiar with setting either the aes(x) argument to id and the fill argument to age:
ggplot(df, aes(x = id, y = value)) +
 geom_bar(aes(fill = age), position = "dodge", stat = "identity") +
 theme_minimal()

Or the opposite - the aes(x) argument to age and the fill argument to id:
ggplot(df, aes(x = age, y = value)) +
 geom_bar(aes(fill = id), position = "dodge", stat = "identity") +
 theme_minimal()

But what I want is the plot to look like the first one above but only filled by id rather than by age.
There's probably a combination position and/or statvalues that get that. Any idea?

A: You may use the group argument in aes:
ggplot(df, aes(x = id, y = value)) +
  geom_bar(aes(group = age, fill = id), position = "dodge", stat = "identity") +
  theme_minimal()


text:
Q: Find operation in Fibonacci Heap I have this question when teaching myself Fibonacci Heap, which now I know is an efficient data structure to implement priority queue with amortized O(1) time complexity when decreasing priority of an element in the heap.
However, from the CLRS textbook, the priority decreasing operation assumes the node holding target element is pre-known.
I'm curious about how could I get the desired node efficiently if not the minimum node.
A naive implementation and analysis yields O(n) worst-case time complexity to perform the find operation on a Fibonacci Heap, which is less efficient compared to other operations.
So my question is that is there an efficient find operation in Fibonacci Heap, or is it necessary?

A: So first thing: this structure was designed to be an efficient priority queue, not search structure so find operation is O(n). Normally you know exact node you want to change. Let's look on an example - Dijkstra's algorithm.
In every step you push graph vertex to the heap or change its priority so it's natural to hold pointer to the heap node in vertex. This way it works great!
So basically you will store the pointer to a node somewhere (you can store them in a hashmap or AVL tree).

A: By HashMap the problem can be solved . The Integer will hold the key value of Fibonacci heap and the corresponding Node will be its value . So no need to search for the node before deletion . Fibonacci heaps is more efficient than height balanced binary search trees , since Fibonacci heaps require O(1) time for insertion and O(logN) time for deletion . I hope  Fibonacci will replace Redblack trees in linux kernels  and even replace AVL trees in Databases .


text:
Q: Not able to POST data to RESTFul service from AngularJS Hope some one can help me here.
I am trying to POST a JOSN data to restful service. But am getting below error.
Error:
XMLHttpRequest cannot load http://localhost:8080/PortalService/rest/PutService/PutLogicalTeam. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.

This is how i am invoking the service
$http.post('http://localhost:8080/PortalService/rest/PutService/PutLogicalTeam', $scope.strLogiTeam
        ).success(function(data, status, headers, config) {

                console.log("success");
            }).error(function(data, status, headers, config) {
                // Handle error
                console.log(status);
            });

My service.
I am not even trying to pull the data. I am just trying to check whether my service is getting invoked or not.
@POST
    @Consumes("application/json")
    @Path("/PutLogicalTeam")
    public void putNewLogicalTeam(LogicalTeam newLogicalTeam)
    {
        System.out.println("Invoked");
    }

I also tried like below
$http({
            method: 'POST',
            dataType: 'jsonp',
            data: $scope.strLogiTeam,
            url:'http://localhost:8080/PortalService/rest/PutService/PutLogicalTeam',
            headers: {'Content-Type':'application/json'}
        });

Can some one review and help. Also suggest the better way to use the web service


text:
Q: Find the range of $\Lambda(f)=2f(x+1)$ on $L^2[0,\infty)$ Find the range of $\Lambda(f)=2f(x+1)$ on $L^2[0,\infty)$
I think the range is isometric to $L^2[1,\infty]$. The isometry being $\Lambda(f) \to 2f\chi_{[1,\infty]}$
So $\Lambda$ is not injective so the map could be not well defined but no matter the choice of $g$ s.t $\Lambda(f)=\Lambda(g)$ we get $2f\chi_{[1,\infty]}=2g\chi_{[1,\infty]}$. Thus the map is well defined. It is injective as $\Lambda(f)=0$ implies $f=0$ on $[1,\infty)$. Is is also surjective as $f \in L^2[1,\infty)$ implies $f/2\chi_{[1,\infty]} \in L^1[0,\infty)$. Thus the range is isometric to $L^2[1,\infty]$. A nice corollary of this is that $\Lambda$ is not compact.
Is all of this correct?

A: You are supposed to find the exact range of the operator  instead of saying that it is isometric to some space. Actually this operator is surjective! Let $g \in L^{2}([0,\infty)$ and define $f(x) =0$ for $x <1$, $f(x)=\frac {g(x-1)} 2$ for $x \geq 1$. The $g \in L^{2}([0,\infty)$  and $\Lambda f=g$.


text:
Q: Setting throwExceptionIfNoHandlerFound has no effect in Spring 4.2.* Setting throwExceptionIfNoHandlerFound has no effect in Spring 4.2.2. It is important for me since I have to send all responses as JSON.
I'm setting throwExceptionIfNoHandlerFound in my AppInitializer like that:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    [...]

    @Override
    protected void customizeRegistration(Dynamic registration) {
        boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
        if(!done) throw new RuntimeException();
    }
}

It seems to work because DispatcherServlet#noHandlerFound throwing Exception like expected:
// https://github.com/spring-projects/spring-framework/blob/4.2.x/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java#L1013
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (pageNotFoundLogger.isWarnEnabled()) {
        pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" + getRequestUri(request) +
                "] in DispatcherServlet with name '" + getServletName() + "'");
    }
    if (this.throwExceptionIfNoHandlerFound) {
        throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request),
                new ServletServerHttpRequest(request).getHeaders());
    }
    else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

But then (it is very confusing!) EVERY exception get catched and resolved to an error view. So it is not possible to handle the NoHandlerFoundException by using Spring-@ExceptionHandler
Question:
I'm sure, it is very nice and useful feature, but is it any way to detect an 404 error to send a custom response instead of default html error page?

A: It seems to happen when we override to use the default servlet handling.
Answered here


text:
Q: Convert React inline styles to CSS rules Is there a tool, that converts React inline style descriptions to CSS rules?
Example input:
{
    minHeight: 200,
    position: 'relative',
    flexGrow: 1,
    flexShrink: 1,
    display: 'flex',
    flexDirection: 'column',
}

Example output:
{
    min-height: 200px;
    position: relative;
    flex-grow: 1;
    flex-shrink: 1;
    display: flex;
    flex-flow: column;
}

To put it differently, I want a tool that does the exact opposite of this: https://github.com/raphamorim/native-css
I would like to use it manually, so command line or web-based is preferable.

A: Have you tried this "A command line tool for JSS" https://github.com/cssinjs/cli

A:
Is there a tool, that converts React inline style descriptions to CSS
  rules?

There is a tool, yes. It's Regular Expressions (or RegEx).
If you want to transform the following:

*

*nH => n-h (minHeight => min-height)

*xG => x-g (flexGrow => flex-grow)

*xS => x-s (flexShrink => flex-shrink)

*xD => x-d (flexDirection => flex-direction)
This is the same Regex operation each time.
The pattern match is:
/([a-z])([A-Z])/

ie. one lowercase letter followed by one uppercase letter, capturing each.
The replacement is:
$1-\L$2

ie.

*

*keep the captured lowercase letter

*follow the captured lowercase letter with a hyphen

*follow the hyphen with a lowercase version of the captured uppercase letter

A: Yes there's a tool that does just that!
https://glitch.com/~convert-css-js
If you paste your example input into the JS side (has to be in parentheses), you get the CSS output you specified (less the final semi-colon).

A: you can use this tool for converting : https://casbin.org/CssToAndFromReact/


text:
Q: Checking input via a batch file I am doing user input and checking to see if they typed n or y... and it's not working because it says both either way.
Here's what I have:
@echo off
set /P theuserinput="Type your name: "
echo So your name is: %theuserinput%?
set /P isit="Y/N: "
echo You typed: %isit%
if (%isit% == "y") goto :saidyes
if (%isit% == "n") goto :saidno

:saidyes
echo Hooray!

:saidno
echo Aww
PAUSE

A: First you can add a default goto after the two if's.
Then, in both tests you have to add the quotes around %isit% and to remove the parenthesis. You may also add the /I flag to do an insensitive string comparison.
Finally, add goto after each echo to jump over the next one.
@echo off
set /P theuserinput="Type your name: "
echo So your name is: %theuserinput%?
set /P isit="Y/N: "
echo You typed: %isit%
if /I "%isit%" == "Y" goto :saidyes
if /I "%isit%" == "N" goto :saidno
goto :error

:saidyes
echo Hooray!
goto :end

:saidno
echo Aww
goto :end

:error
echo ERROR

:end
PAUSE

A: Need change in syntax
Here is the modified code
    @echo off
set /P theuserinput="Type your name: "
echo So your name is: %theuserinput%?
set /P isit="Y/N: "
echo You typed: %isit%
if "%isit%" == "Y" GOTO saidyes
if "%isit%" == "N" GOTO saidno

:saidyes
echo Hooray!
GOTO paused

:saidno
echo Aww

:paused
PAUSE

....
In above example The Y/N is supposed to be capital letter only.

A: There are a few things I would do differently to this to ensure that it works properly...
First off the corrected code is the following, but at the bottom is my suggested code:
@echo off
setlocal
set theuserinput=
set /P theuserinput="Type your name: "
echo So your name is: %theuserinput%?
set /P isit="Y/N: "
echo You typed: %isit%
if '%isit%'== 'Y' goto saidyes
if '%isit%'=='N' goto saidno

:saidyes
echo Hooray!
goto end

:saidno
echo Aww
goto end

:end
pause
endlocal
exit

However, to make sure that you only get Y or N there are a few things I would put in...
First I would make sure that you only grab the first letter by adding:
IF NOT '%isit%'=='' set isit=%isit:~0,1%

Next I would make sure that you only have Capital letters, so you make the swap if they are lowercase, because this will actually not work in some cases if the CaSe isn't correct:
if '%isit%'== 'y' set isit=Y
if '%isit%'== 'Y' goto :saidyes
if '%isit%'=='n' set isit=N
if '%isit%'=='N' goto :saidno

The final edit for this file could look like the following:
@echo off
:top
set theuserinput=
set /P theuserinput="Type your name: "
echo So your name is: %theuserinput%?
set /P isit="Y/N: "
IF NOT '%isit%'=='' set isit=%isit:~0,1%
IF '%isit%'=='y' set isit=Y
IF '%isit%'=='Y' goto saidyes
IF '%isit%'=='n' set isit=N
IF '%isit%'=='N' goto saidno
goto top

:saidyes
echo You typed: %isit%
echo Hooray!
goto end

:saidno
echo You typed: %isit%
echo Aww
goto end

:end
pause
exit

A: Quotes are commonly misused in DOS batch files. Unlike UNIX shell scripts, the DOS batch language is not thought-out.  For example, when the isit variable contains quotes
set isit="Y"

then the above if-statements expand to
IF ""Y"" == "Y" GOTO saidyes
IF ""Y"" == "N" GOTO saidno

because cmd.exe does not remove the quotes in "%isit%"=="Y" before evaluating the expression.
Quotes in isit shall not occur with the original batch file posted here. But often you process path names in batch files, and Windows passes long file names in quotes to hide blanks. For example, as in "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC". To work around this it is common practice to write if-statements so:
IF ["%isit%"] == ["Y"] GOTO saidyes
IF   [%isit%] == ["Y"] GOTO saidyes
IF   [%isit%] ==   [Y] GOTO saidyes

For set isit="Y" this becomes:
IF [""Y""] == ["Y"] GOTO saidyes
IF   ["Y"] == ["Y"] GOTO saidyes
IF   ["Y"] ==   [Y] GOTO saidyes

and for set isit=Y:
IF ["Y"] == ["Y"] GOTO saidyes
IF   [Y] == ["Y"] GOTO saidyes
IF   [Y] ==   [Y] GOTO saidyes

and for set isit=:
IF [""] == ["Y"] GOTO saidyes
IF   [] == ["Y"] GOTO saidyes
IF   [] ==   [Y] GOTO saidyes

which is far from being elegant, but at least works now for quoted and unquoted variables. It also works when isit is empty.  Oftenly batch files stop because of empty variables:
set x=
REM ...
IF %x% == x GOTO x

because now the if-statement expands to:
IF == x GOTO x

and cmd.exe fails. These errors are usually hard to debug.
The trick is very old; I remember using it already in MSDOS. Note that the square brackets are not evaluated by cmd.exe; they're just some rarely used characters. But it's just a trick. Any advanced batch script needs a dequoting-function:
@echo off
 setlocal EnableExtensions
 setlocal EnableDelayedExpansion
 REM ...
 set /P isit="Y/N: "
 call :dequote isit
 REM ...
 IF "!isit!" == "Y" GOTO saidyes
 IF "!isit!" == "N" GOTO saidno
 REM ...
 goto done

:dequote
 for /f "delims=" %%A in ('echo %%%1%%') do set %1=%%~A
 goto :eof

:done

The deqote-subroutine removes any double quotes around the variable name passed to the function.
After dequoting the []-trick is not required anymore. Note also the use of ! instead of %. The exclamation marks force cmd.exe to reexpand isit.

A: I changed the code somewhat to help fix your problem. Instead of goto :(function) you just say goto (function)
@echo off
set /P theuserinput=Type your name:
echo So your name is: %theuserinput%?
set /p isit=Y/N:
echo You typed: %isit%
if %isit% == "y" goto saidyes
if %isit% == "n" goto saidno

:saidyes
echo Hooray!

:saidno
echo Aww
pause


text:
Q: undefined from arrValue.start_date I am trying to get from my database the start_date and end_date, however, I am getting "undefined" in console from arrValue.start_date or arrValue.(x) regardless of input.
        unavailabletimes = [];
        is_conflict = false

        $.ajax({
          url: '<%= preload_parking_path(@parking) %>',
          dataTyp: 'json',
          success: function(data) {

            $.each(data, function(arrID, arrValue){
              unavailabletimes.push([moment(moment.utc(arrValue.start_date).format('YYYY-MM-DD HH:mm')), moment(moment.utc(arrValue.end_date).format('YYYY-MM-DD HH:mm'))] );
              console.log(arrValue.start_date);
                })

              var prestart_date = $('#reservation_start_date').datetimepicker('viewDate');
              var start_date = moment(moment(prestart_date).format('YYYY-MM-DD HH:mm'));
              var preend_date = $('#reservation_end_date').datetimepicker('viewDate');
              var end_date = moment(moment(preend_date).format('YYYY-MM-DD HH:mm'));

              if(end_date.diff(start_date, 'minutes') < 60){
                var duration = 60;
              }else{
                if((end_date.diff(start_date, 'minutes') % 60) == 0){
                  var duration = end_date.diff(start_date, 'minutes');
                }else{
                  var duration = ((end_date.diff(start_date, 'minutes') - (end_date.diff(start_date, 'minutes') % 60)) + 60);
                }
              }

              unavailabletimes.forEach((unavailabletime)=> {
                // unavailabletime = [moment, moment]
                // check with start time and end time
                if (start_date <= unavailabletime[0] && end_date >= unavailabletime[1]) {
                  is_conflict = true
                }
              });

              if(is_conflict) {
                $('#message').text("Cannot overlap existing bookings!");
                $('#preview').hide();
                $('#btn_book').attr('disabled', true);
              } else {
                var total = duration/60 * <%= @parking.price %>;
                $('#message').text("");
                $('#preview').show();
                $('#btn_book').attr('disabled', false);
                $('#reservation_hours').text(duration/60);
                $('#reservation_total').text(total);

              }
        }

      });

arrValue on itself works and it returns the database entries but adding the .(x) i.e start_date or end_date.
This is my console for arrValue
What could be the cause of this? What I am trying to do is setup a booking system that does not allow overlapped booking down to the hour. I am trying to retrieve the time interval between start_date and end_date. Push it into unavailabletimes to find conflict. I am new to coding so I apologize if its a little messy.


text:
Q: How to print first 5 lines of the file in windows cmd How can I print first 5 lines of the file in windows CMD?
There is a problem that I can't use PowerShell (spicific task) and batch scripts. Can you help me with this?

A: You should be able to use the more command in some regard.
Maybe
"more filename P 5"
see
http://support.microsoft.com/kb/227449

A: Alright, it might be like replying to a very old thread, but still for anyone who would benefit from this.
Use findstr
findstr /n . yourfile.txt  | findstr "^[0-5]:"

The breakdown is-
first findstr prints the line number where it finds any character (denoted by a literal dot), second findstr will print lines that start ( using ^ for this ) with any number ranging from 0 through 5. Also include ":" there to avoid findstr matching with recurring digits like 12,13,14... 21,22,23..., etc.
^[0-5]: will match only for lines starting with-

1:
2:
3:
4:
5:

I tested it on a 250 MB file and it worked within a second.
The same can be achieved in linux using sed-
sed -n '1,5p' yourfile.txt


text:
Q: Balance it out (double factorial problem) Amit was given a balance and n weights (where n is a positive integer) of weight 2^0, 2^1, 2^2,.... 2^(n-1). He is now assigned a task to place the weight that has not been placed on the balance, either on the right pan or the left pan until all of the weights have been placed.But at every step he needs to make sure that the right pan is never heavier than left pan. You have to help him determine the number of ways in which this can be done.
example:
if n=2 so weight will be-1,2
answer is -3
if n=3 so weight will be of 1,2,4
and answer is -15
This problem was in last contest of codechef that is over now, solutions are also available there but i am not getting the algorithm or solution .I dont know but the solution series it similar to double factorial ,i am not familiar with that.Please explain.

A: Hint: Proceed by induction.
Show that if there are $P_k$ ways to arrange the weights $2^0, 2^1, \ldots 2^k$, then there are $(2k+1)$ ways to arrange the weights $2^0, 2^1, \ldots 2^{k+1}$.
Proof: If there are $P_k$ ways to arrange the weights $2^0, 2^1, \ldots 2^k$ according to the conditions, then there are $P_k$ ways to arrange the weights $2^1, 2^2, \ldots 2^{k+1}$.

 Now consider where we place the weight $2^0$. It can be placed in the Left pan at any point in time, giving $k+1$ possibilities.
 When can it be placed in the Right pan? It can't be placed in the Right pan right at the start (since then the right pan will be heavier than the left). However, after the first move, the weight in the Left pan is at least 2 more than the weight in the right pan (Why?). Hence, we can place $2^0$ in the right pan at any other time, giving $k$ possibilities.

Hence $P_{k+1} = (2k+1) P_k$.
Observe that $P_1 = 1$, which proves that $P_n = (2n-1) \times (2n-3) \times (2n-5) \times \ldots \times 1$.


text:
Q: UI rendering inconsistencies in Flex application Has anyone noticed UI rendering inconsistencies within Flex applications. I am having issues with radio buttons and text controls inside a repeater. Below is a sample...
What would cause such inconsistencies? Computer performance, internet speed?
The repeater below has an XML web service acting as a data provider, using Flex's e4x support. Is there a threshold of data that can be rendered in a given Flex app?
Note that most of the time Flex renders the app ok, but most of the time is not good enough in this application.
Thanks.
alt text http://img87.imageshack.us/img87/1435/error3b.jpg
MXML Code below, as requested:

<mx:Repeater id="rpQuestions" width="100%" height="100%" dataProvider="{srv.lastResult..Question}">
    <mx:Box backgroundColor="#FFFF99" width="100%">
        <mx:Text styleName="questionText" text ="{rpQuestions.currentIndex+1 +': ' +rpQuestions.currentItem.@QuestionText}" fontSize ="12" width="100%" selectable="false" />
    </mx:Box>
    <mx:HBox visible="{rpQuestions.currentItem..Image.length() > 0}" includeInLayout="{rpQuestions.currentItem..Image.length() > 0}">
    <mx:Repeater id="rpImages" dataProvider=quot;{rpQuestions.currentItem..Image}" >
        <mx:Image source="{rpImages.currentItem.@Path}" width="350" height="250"  />
    </mx:Repeater>
    </mx:HBox>
    <mx:Repeater id="rpAnswers" dataProvider="{rpQuestions.currentItem..Answer}" width="75%" height="75%">
        <mx:HBox>
            <mx:Spacer width="12" />
            <!-- NOTE: the RadioButton's label property is not used because long text won't  wrap. Instead we use a Text control. -->
            <mx:RadioButton
            groupName="{rpQuestions.currentItem.@QuestionID}"
            value="{rpAnswers.currentItem.@AnswerID}"
            click="_questionAnswerd(event)"
            selected="{rpAnswers.currentItem.@Selected == '1'}"
                        />
        <mx:Text text="{rpAnswers.currentItem.@Answer}" width="600" selectable="false"  />
        <!-- End-->
        </mx:HBox>
    </mx:Repeater>
</mx:Repeater>

A: I would try to make sure that the hbox's inside the repeaters have a percentage set for the height (say 100% for the one with the radio buttons, its repeater which is set to 75%).
Or you could try to invalidate the display/size after the repeaters have finished creating the subcomponents ('repeatEnd' event).

A: This looks like it's related to a reported bug in the Flex SDK 3.3.0:
SDK-198805: Nested Repeater components do not display correctly when there is an intermediate component


text:
Q: How to extract columns which contains lots of 0 value with R? I have a matrix with lots of columns (more than 817.000) and 40 rows . I would like to extract the columns which contain lots of 0 (for example > 30 or 35 , no matter the number) .
That should extract several columns, and I will choose one randomnly which I will use as a reference for the rest of the matrix.
Any idea?
Edit :
              OTU0001 OTU0004 OTU0014 OTU0016 OTU0017 OTU0027 OTU0029 OTU0030
Sample_10.rare       0       0      85       0       0       0       0       0
Sample_11.rare       0      42     169       0      42     127       0      85
Sample_12.rare       0       0       0       0       0       0       0      42
Sample_13.rare     762     550    2159     127     550       0     677    1397
Sample_14.rare     847     508    2751     169    1397     169     593    1990
Sample_15.rare    1143     593    3725     677    2116     466     212    2286
Sample_16.rare    5630    5291    5291    1270    3852    1185     296    2836

It should extract 4 columns, OTU0001 OTU0016  OTU0027 OTU0029 because they got 3 zero each. And if it is possible, I would like to extract the position of the extracted columns.

A: An option with base R
Filter(function(x) sum(x == 0) > 7, df)

A: You could do something like this (Where 7 is the number of relevant zeros):
library(dplyr)
df <- tibble(Col1 = c(rep(0, 10), rep(1, 10)),
                     Col2 = c(rep(0,5), rep(1, 15)),
                     Col3 = c(rep(0,15), rep(1, 5)))

y <- df %>%
      select_if(function(col) length(which(col==0)) > 7)


text:
Q: How to access indexDb varible and access that varible? Need to use async/await for fetching all values from IndexDb
// expecting b to have result-set from index-db
var b ="";
var request = window.indexedDB.open("mydb");
request.onsuccess = function (event) {
 var db = event.target.result;
 var objectStore = db.transaction("mytable").objectStore("mytable");
 allRecords =   objectStore.getAll();
 allRecords.onsuccess=  function(event){
   console.log(event.target.result)
    b = 10;
    b = event.target.result

 }
 console.log(b);
 //b is ""

A: var promise = new Promise( (resolve, reject) => {
   var request = window.indexedDB.open("mydb");
   request.onsuccess = function (event) {
    var db = event.target.result;
    var objectStore = db.transaction("mytable").objectStore("mytable");
    allRecords =   objectStore.getAll();
    allRecords.onsuccess=  function(event){
      console.log(event.target.result)
       b = 10;
       b = event.target.result

    }

}
promise.then((a)=>console.log(a));


text:
Q: Try to make sense of this permutation formula I have to explain this formula tomorrow in class and that catch is, I can't use algebra. I must solely use an "intuitive" explanation. But I don't know how to explain it!
$P(n,k) = C(n,k)k!$
I know that $P(n,k)$ is the # of ways of arrange $k$ objects from $n$ distinct objects with order. How can I "just say" that this equivalent to the # of ways to arrange $k$ objects from $n$ distinct objects without order multiplied by the number of ways to line them up $k$ ways? The people who I am trying to show are my 15-16 year old peers. They won't get this trust me! Any other way to explain it?


text:
Q: Is there a way to place switch in include? I'm working on my PHP project build on Laravel 5.4 framework. I was wondering if there is a way to place a switch statement into an include call.
I'm trying to do something like this:
@include('components/notification_message/_notification_message_html'
        , [ 'notificationType' => $notificationType
          , 'notificationMessage' => $notificationMessage
          , 'iconType' => switch($notificationType){case 'success': 'check'; break; case 'warning': 'warning'; break; default: 'exclamation';break;}])

As you can guess, I got a syntax error after I've tried to run it.
Any idea how I should do this?

A: You cannot use switch statement like this. You could use the ternary operator instead:
@include('components/notification_message/_notification_message_html', [
    'notificationType' => $notificationType,
    'notificationMessage' => $notificationMessage,
    'iconType' => $notificationType === 'success' ? 'check' : ($notificationType === 'warning' ? 'warning' : 'exclamation')
]);

A: There's no way of placing a switch statement inside the include. You can do a straight up switch with includes:
@switch($i)
    @case(1)
        @include('...');
        @break

    @case(2)
        @include('...');
        @break

    @default
        @include('...');
@endswitch

Or You can use some combination of @if directives and/or includeIf and includeWhen:
@includeIf('view.name', ['some' => 'data'])
@includeWhen($boolean, 'view.name', ['some' => 'data'])
https://laravel.com/docs/5.6/blade#including-sub-views


text:
Q: Store and Restore previous userinput texfield I have two Textfields that can be input by user and will be used for calculation later (Number only), lets say InputX and InputY. And two radio button, Rad1 and Rad2.
When user Choose Rad1, Both TextFiled are Input-able by User and Stored to memory/variable when user input in it. But when user choose Rad2, only InputX is available and InputY is InputY.setText("InputX only"). If User choose the Rad1 back, i want to restore the value that user input to the InputY previously, not showing "InputX Only".
So, My Question is: How to get the previous value from userinput when user choose the Rad1 back, since its has been overridden by Rad2 InputY.setText("InputX Only") ?
Please create a full code example with all possible/alternative code, i'm new in java.
Note: Im using Netbeans v8.0.2 and create form using built in form builder/designer

A: public class InputValidator extends javax.swing.JFrame {

private static final String INPUT_X_ONLY = "InputX Only";
private String temp = "";

public InputValidator() {
    initComponents();
    jRadioButton1.setSelected(true);
    buttonGroup1.add(jRadioButton1);
    buttonGroup1.add(jRadioButton2);

    jRadioButton1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            jTextField2.setEditable(true);
            jTextField2.setText(temp);
        }
    });

    jRadioButton2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            jTextField2.setEditable(false);
            temp = jTextField2.getText();
            jTextField2.setText(INPUT_X_ONLY);
        }
    });
}


text:
Q: Redshift IN condition on thousands of values What's the best way to get data that matches any one of ~100k values?
For this question, I'm using an Amazon Redshift database and have a table something like this with hundreds of millions of rows:
--------------------
| userID | c1 | c2 |
| 101000 | 12 | 'a'|
| 101002 | 25 | 'b'|
____________________

There are also millions of unique userIDs. I have a CSV list of 98,000 userIDs that I care about, and I want to do math on the columns for those specific users.
select c1, c2 from table where userID in (10101, 10102, ...)

What's the best solution to match against a giant list like this?
My approach was to make a python script that read in the result of all users in our condition set, then filtering against the CSV in python. It was dead slow and wouldn't work in all scenarios though.
A coworker suggested uploading the 98k users into a temporary table, then joining against in in the query. This seems like the smartest way, but I wanted to ask if you all had ideas.
I also wondered if printing an insanely long SQL query containing all 98k users to match against and running it would work. Out of curiosity, would that even have ran?

A: As your coworker suggests, put your IDs into a temporary table by uploading a CSV to S3 and then using COPY to import the file into a table. You can then use an INNER JOIN condition to filter your main data table on the list of IDs you're interested in.
An alternative option, if uploading a file to S3 isn't possible for you, could be to use CREATE TEMP TABLE to set up a table for your list of IDs and then use a spreadsheet to generate a whole of INSERT statements to populate the temp table. 100K of inserts could be quite slow though.


text:
Q: How can I reset two factor authentication on 2.3.5? I am using Magento 2.3.5. I need to move my 2fa to a new phone. When looking at the docs- https://docs.magento.com/user-guide/stores/security-two-factor-authentication-manage.html (these docs are also for 2.4) it talks about a box on the left panel. I do not have that box and I am admin. Is it different for 2.3.5?

A: Reset authenticator per account
If you need to manually reset a single user configuration, enter the following command. It restarts configuration and 2FA subscription for the user account.
bin/magento msp:security:tfa:reset

A: Reset 2FA Info
bin/magento msp:security:tfa:reset --help

Description:
  Reset configuration for one user

Usage:
  msp:security:tfa:reset <user> <provider>

Arguments:
  user                  Username
  provider              Provider code

List all providers
bin/magento msp:security:tfa:providers

google: Google Authenticator
duo_security: Duo Security
authy: Authy
u2fkey: U2F (Yubikey and others)

Reset 2FA
bin/magento msp:security:tfa:reset YourAdminUsername google

This command will reset your admin user values in the database table msp_tfa_user_config:
MariaDB [magento]> SELECT * FROM msp_tfa_user_config WHERE user_id = 299 \G;
*************************** 1. row ***************************
msp_tfa_user_config_id: 272
               user_id: 299
     encoded_providers: []
        encoded_config: 0:3:xxxxxxxxxxxxxxxxxxxxxxxxx
      default_provider: google
1 row in set (0.00 sec)

https://blog.chapagain.com.np/magento2-reset-admin-2fa-two-factor-authentication/