text
stringlengths 355
41.1k
| meta
dict |
|---|---|
Q:
Find all possible two-way associations/relations between four numbers
Given four numbers {1,2,3,4}, how to find all possible two-way associations/relations between them? I calculate them manually as in below (50 in total) but I would like to know whether a mathematical formula exists to find them? And how about generalizing the formula for n given numbers?
{1} --> {2}, {2} --> {1},
{1} --> {3}, {3} --> {1}
{1} --> {4}, {4} --> {1}
{2} --> {3}, {3} --> {2}
{2} --> {4}, {4} --> {2}
{3} --> {4}, {4} --> {3}
{1} --> {2,3}, {2,3} --> {1},
{1} --> {2,4}, {2,4} --> {1},
{1} --> {3,4}, {3,4} --> {1},
{2} --> {1,3}, {1,3} --> {2},
{2} --> {1,4}, {1,4} --> {2},
{2} --> {3,4}, {3,4} --> {2},
{3} --> {1,2}, {1,2} --> {3},
{3} --> {1,4}, {1,4} --> {3},
{3} --> {2,4}, {2,4} --> {3},
{4} --> {1,2}, {1,2} --> {4},
{4} --> {1,3}, {1,3} --> {4},
{4} --> {2,3}, {2,3} --> {4},
{1} --> {2,3,4}, {2,3,4} --> {1},
{2} --> {1,3,4}, {1,3,4} --> {2},
{3} --> {1,2,4}, {1,2,4} --> {3},
{4} --> {1,2,3}, {1,2,3} --> {4},
{1, 2} --> {3, 4}, {3, 4} --> {1, 2},
{1, 3} --> {2, 4}, {2, 4} --> {1, 3},
{1, 4} --> {2, 3}, {2, 3} --> {1, 4},
A:
Create the set $A$ by choosing at least $1$ element from $\{1, 2, 3, ..., n\}$ and leaving at least one for $B$. Suppose we chose $k$ elements ($1\leq k\leq n-1$). Now, from the remaining elements, we need to choose elements for $B$. There are $n-k\geq 1$ elements left and we must choose at least one of them. Say we choose $\ell\geq 1$ of them. There are $\binom{n}{k}\binom{n-k}{\ell}$ ways to do it as described. Now, we just need to vary $k$ and $\ell$ over the possible values they could take on (keeping in mind that the possibilities for $\ell$ depend on the choice of $k$). We end up with:
$$ \sum_{k=1}^{n-1} \binom{n}{k}\sum_{\ell=1}^{n-k}\binom{n-k}{\ell}.$$
To check that this works with $n=4$ as you gave, we have:
\begin{align*}
&\binom{4}{1}\left(\binom{3}{1}+\binom{3}{2}+\binom{3}{3}\right)+\binom{4}{2}\left(\binom{2}{1}+\binom{2}{2}\right) + \binom{4}{3}\binom{1}{1} \\ &= 4(3+3+1)+6(2+1)+4(1) \\
&=4(7)+6(3)+4 \\
&=28+18+4 \\
&= 50
\end{align*}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Matrix multiplication that includes a tensor
How would I best express the following in Mathematica:
$\begin{pmatrix}2 & 4\end{pmatrix}
\begin{pmatrix}r_1 & r_2\\r_3 & r_4\end{pmatrix}
\begin{pmatrix}6 \\ 8\end{pmatrix}$, where $r_i$ are 3-element vectors?
Is there a more elegant way than this?
r1 := {1, 2, 3}
r2 := {3, 2, 1}
r3 := {2, 3, 1}
r4 := {2, 1, 3}
res := {2, 4} . {{r1//Hold, r2//Hold}, {r3//Hold, r4//Hold}} . {{6}, {8}} // ReleaseHold
res[[1]]
Out= {172, 160, 172}
A:
As it stands, the dimensions of the tensor {{{1, 2, 3}, {3, 2, 1}}, {{2, 3, 1}, {2, 1, 3}}} are compatible with the vector on the left, but not on the right. We thus have
{3, 4}.{{{1, 2, 3}, {3, 2, 1}}, {{2, 3, 1}, {2, 1, 3}}}
{{11, 18, 13}, {17, 10, 15}}
and we now want to form the product of this with {6, 8} in some way. One could certainly do Transpose[{{11, 18, 13}, {17, 10, 15}}].{6, 8}, but the more appropriate way would be to match the dimensions of the original tensor with not only the left vector, but with the right vector as well.
Thus, one might initially do
Transpose /@ {{{1, 2, 3}, {3, 2, 1}}, {{2, 3, 1}, {2, 1, 3}}}
{{{1, 3}, {2, 2}, {3, 1}}, {{2, 2}, {3, 1}, {1, 3}}}
and now it is clear one can take left- and right-products of this tensor with $2$-vectors. A better route, though, is to note that the previous operation was exactly equivalent to swapping out levels $2$ and $3$, and thus we have the more compact
Transpose[{{{1, 2, 3}, {3, 2, 1}}, {{2, 3, 1}, {2, 1, 3}}}, {1, 3, 2}]
{{{1, 3}, {2, 2}, {3, 1}}, {{2, 2}, {3, 1}, {1, 3}}}
With this, we finally have
{2, 4}.Transpose[{{{1, 2, 3}, {3, 2, 1}}, {{2, 3, 1}, {2, 1, 3}}}, {1, 3, 2}].{6, 8}
{172, 160, 172}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Exporting data in grid format splitting the last column
I have a list of lists, and I displayed it in grid format. The grid is huge, so I will show here an example:
list = {{2, 2, 2, {1, 3}}, {2, 1, 2, {1, 2}}, {1, 2, 2, {1, 4}}}
Grid[list, Frame -> All]
Now, I would like to export the data in Csv format, so to have 5 variables. What I did so far is:
Export["list.csv", list, "CSV"]
Problem is that in this way I have only four variables. What I need to do is to "split" the last column in two variables. Indeed, for each row it contains two values.
So, in other words, I need to export a data set with five variables (the first column, the second column, the third column, and the values in the last column).
In another grid I have a similar but more complicated issue. Here it is:
list2 = {{2, 2, 2, {{1, 3} , {1, 2}}}, {2, 1, 2, {{1, 2}, {1, 3}}}, {1, 2, 2, {1, 4}}}
Grid[list2, Frame -> All]
As you can see, here sometimes I have two pairs of solutions in the last columns, sometimes only one. The data set I would like to export from that is similar to the first one. So, the first three variables correspond to the values in the first three columns. Moreover, I would like to extrapolate 4 variables from the last column (if it reports only a pair of solution, the last two variables should have missing values or whatever).
Can someone help me please?
Bonus question: is it possible to name the columns of the grid, so to export a data set with the first row containing the name of the variables?
A:
Is this what you are looking for?
list = {{2, 2, 2, {1, 3}}, {2, 1, 2, {1, 2}}, {1, 2, 2, {1, 4}}};
listf = Flatten /@ list
(* {{2, 2, 2, 1, 3}, {2, 1, 2, 1, 2}, {1, 2, 2, 1, 4}} *)
list2 = {{2, 2, 2, {{1, 3}, {1, 2}}}, {2, 1, 2, {{1, 2}, {1, 3}}}, {1, 2, 2, {1, 4}}};
list2f = Flatten /@ list2
(* {{2, 2, 2, 1, 3, 1, 2}, {2, 1, 2, 1, 2, 1, 3}, {1, 2, 2, 1, 4}} *)
max = Length /@ list2f // Max;
PadRight[#, max, Null] & /@ list2f
(* {{2, 2, 2, 1, 3, 1, 2}, {2, 1, 2, 1, 2, 1, 3}, {1, 2, 2, 1, 4, Null, Null}} *)
To add column headings
listf // Prepend[{"a", "b", "c", "d", "e"}]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fit a function to data so that fit is always equal or less than the data
I have a set of measurement data and I try to fit there a function (a Exp[b x] + c Exp[d x] - o). I have two problems:
The fit function does not converge nor after $500$ iterations.
The fit function always has to be equal or less than the data points.
Thank you for your help!
fitdata = {{-0.826333, 9.72503}, {-0.796121, 9.61975}, {-0.765909, 8.25744},
{-0.735697, 7.40448}, {-0.705485, 5.38543}, {-0.675273, 5.15899},
{-0.645061, 4.9356}, {-0.614848, 4.67804}, {-0.584636, 4.28955},
{-0.554424, 4.73144}, {-0.524212, 4.93957}, {-0.494, 4.80621},
{-0.463788, 5.77301}, {-0.433576, 3.39416}, {-0.403364, 1.73309},
{-0.373152, 1.4862}, {-0.342939, 1.4212}, {-0.312727, 1.49505},
{-0.282515, 1.35071}, {-0.252303, 1.28845}, {-0.222091, 1.25183},
{-0.191879, 1.43158}, {-0.161667, 1.39557}, {-0.131454, 1.40259},
{-0.101242, 1.36108}, {-0.0710303, 1.2265}, {-0.0408181, 1.23474},
{-0.0106061, 1.24481}, {0.0196061, 1.26526}, {0.0498182, 1.32446},
{0.0800303, 1.31866}, {0.110242, 1.35345}, {0.140455, 1.45935},
{0.170667, 1.58142}, {0.200879, 1.64947}, {0.231091, 1.72851},
{0.261303, 1.79931}, {0.291515,1.53534}, {0.321727, 1.76849},
{0.351939, 2.56439}, {0.382152, 3.65875}, {0.412364, 1.30584},
{0.442576, 2.4179}, {0.472788, 3.02307}, {0.503, 1.58539},
{0.533212, 1.45324}, {0.563424, 1.4743}, {0.593636, 1.42791},
{0.623849, 1.44165}, {0.654061, 1.56433}, {0.684273, 1.68152},
{0.714485, 2.1933}, {0.744697, 2.30194}, {0.774909, 2.29156},
{0.805121, 2.62207}, {0.835333, 3.09906}, {0.865546, 3.17169},
{0.895758, 4.08508}, {0.92597, 7.48046}, {0.956182, 4.48303},
{0.986394, 4.11621}, {1.01661, 4.18457}, {1.04682, 4.72107},
{1.07703, 5.77667}, {1.10724, 6.35589}, {1.13745, 6.41082},
{1.16767, 7.43164}, {1.19788, 9.28222}};
@ All - The bigger the choice, the harder it is to choose. Thank you for incredible nice and quick answers!
A:
Let's first solve it without constraints.
Using fitdata from your question one needs to set reasonable starting values.
You may have to experiment (I like to use Manipulate) to get in the ball park.
nlm = NonlinearModelFit[fitdata, a*Exp[b*x] + c*Exp[d*x] + o,
{{a, 0.1}, {b, 3}, {c, 0.3}, {d, -4}, {o, 1}}, x]
yields
nlm["BestFitParameters"]
(* {a -> 0.127629, b -> 3.38374, c -> 0.310767, d -> -4.07292,
o -> 1.02299} *)
Now plot it
Show[ListPlot[fitdata, PlotStyle -> Black],
Plot[nlm[x], {x, -1, 1.5}, PlotStyle -> Red]]
Constrained Solution
In order to implement the constraints we will create a list (one for each point) using Map.
Map[a*Exp[b*#[[1]]] + c*Exp[d*#[[1]]] + o <= #[[2]] &, fitdata]
I won't print the result here but you can see it in your notebook.
Now we want to include those constraints in the optimization. One form is to wrap the model in a list and add the constraints separated by commas. This can be done if we Apply the function Sequence to the list.
nlmConstrained = NonlinearModelFit[fitdata, {a*Exp[b*x] + c*Exp[d*x] + o,
Sequence @@Map[a*Exp[b*#[[1]]] + c*Exp[d*#[[1]]] + o <= #[[2]] &,
fitdata]}, {{a, 0.05}, {b, 4}, {c, 0.1}, {d, -5}, {o, 0.7}}, x]
the result is
nlmConstrained["BestFitParameters"]
(* {a -> 0.0579711, b -> 4.02179, c -> 0.0963365, d -> -5.49028,
o -> 0.725906} *)
and plotting it shows that the constraints are satisfied.
Show[ListPlot[fitdata, PlotStyle -> Black],
Plot[nlmConstrained[x], {x, -1, 1.5}, PlotStyle -> Red]]
I was pleasantly suprised to find that solver was fast despite having 68 constraints imposed.
A:
This answer provides two solutions both use Quantile regression.
The first uses sort of brute force fitting with a family of curves.
The second is similar to the one by Jack LaVigne, but uses QuantileRegressionFit on the second step, which in this case seems to be more straightforward.
This command loads the package QuantileRegression.m used below:
Import["https://raw.githubusercontent.com/antononcube/MathematicaForPrediction/master/QuantileRegression.m"]
1. QuantileRegressionFit only
Generate a family of functions:
funcs = Table[Exp[k*x], {k, -6, 6, 0.002}];
Length[funcs]
(* 6001 *)
Do Quantile regression fit with the family of functions:
qfunc = First@QuantileRegressionFit[fitdata, funcs, x, {0.01}]
(* 0. + 0.0125232 E^(-5.398 x) + 0.0930724 E^(-5.392 x) +
0.232695 E^(0.2 x) + 0.511794 E^(0.214 x) + 0.039419 E^(4.336 x) *)
and visualize:
Show[
ListPlot[fitdata, PlotStyle -> Black, PlotRange -> All],
Plot[qfunc, {x, -1, 1.5}, PlotStyle -> Red, PlotRange -> All]]
The found fitted function satisfies the condition to be less or equal of the data points, but it is made of too many Exp terms. So the next step is to reduce the number of Exp terms to two as required in the question.
We can visually evaluate the contribution of each of the terms in the found fit:
Plot[Evaluate[(List @@ qfunc)/qfunc], {x, -1, 1.5}, PlotRange -> All,
PlotLegends -> (List @@ qfunc)]
We pick two of the terms (plus the intercept) and call QuantileRegressionFit again:
qfunc2 =
First@QuantileRegressionFit[fitdata,
Prepend[(List @@ qfunc)[[{3, -1}]], 1], x, {0}]
(* 0.658637 + 0.105279 E^(-5.392 x) + 0.0414842 E^(4.336 x) *)
Show[ListPlot[fitdata, PlotStyle -> Black, PlotRange -> All],
Plot[qfunc2, {x, -1, 1.5}, PlotStyle -> Red, PlotRange -> All]]
2. NonlinearModelFit model followed by QuantileRegressionFit
First we find a model with the required functions:
nlm = NonlinearModelFit[fitdata,
a*Exp[b*x] + c*Exp[d*x] + o, {{a, 0.1}, {b, 3}, {c, 0.3}, {d, -4}, {o, 1}}, x]
nlm["BestFitParameters"]
(* {a -> 0.127629, b -> 3.38374, c -> 0.310767, d -> -4.07292,
o -> 1.02299} *)
Show[ListPlot[fitdata, PlotStyle -> Black],
Plot[nlm[x], {x, -1, 1.5}, PlotStyle -> Red]]
Using the model functions:
{Exp[b*x], Exp[d*x]} /.
Cases[nlm["BestFitParameters"], HoldPattern[(b | d) -> _]]
(* {E^(3.38374 x), E^(-4.07292 x)} *)
find the quantile regression curve that is below the data points (0. quantile):
qfunc =
First@QuantileRegressionFit[
fitdata, {1, Exp[b*x], Exp[d*x]} /.
Cases[nlm["BestFitParameters"], HoldPattern[(b | d) -> _]],
x, {0.0}]
(* 0. + 0.303621 E^(-4.07292 x) + 0.13403 E^(3.38374 x) *)
Plot the result:
Show[
ListPlot[fitdata, PlotStyle -> Black, PlotRange -> All],
Plot[qfunc, {x, -1, 1.5}, PlotStyle -> Red, PlotRange -> All]]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I save terminal output to a file?
How do I save the output of a command to a file?
Is there a way without using any software? I would like to know how.
A:
To write the output of a command to a file, there are basically 10 commonly used ways.
Overview:
Please note that the n.e. in the syntax column means "not existing".
There is a way, but it's too complicated to fit into the column. You can find a helpful link in the List section about it.
|| visible in terminal || visible in file || existing
Syntax || StdOut | StdErr || StdOut | StdErr || file
==========++==========+==========++==========+==========++===========
> || no | yes || yes | no || overwrite
>> || no | yes || yes | no || append
|| | || | ||
2> || yes | no || no | yes || overwrite
2>> || yes | no || no | yes || append
|| | || | ||
&> || no | no || yes | yes || overwrite
&>> || no | no || yes | yes || append
|| | || | ||
| tee || yes | yes || yes | no || overwrite
| tee -a || yes | yes || yes | no || append
|| | || | ||
n.e. (*) || yes | yes || no | yes || overwrite
n.e. (*) || yes | yes || no | yes || append
|| | || | ||
|& tee || yes | yes || yes | yes || overwrite
|& tee -a || yes | yes || yes | yes || append
List:
command > output.txt
The standard output stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, it gets overwritten.
command >> output.txt
The standard output stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
command 2> output.txt
The standard error stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, it gets overwritten.
command 2>> output.txt
The standard error stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
command &> output.txt
Both the standard output and standard error stream will be redirected to the file only, nothing will be visible in the terminal. If the file already exists, it gets overwritten.
command &>> output.txt
Both the standard output and standard error stream will be redirected to the file only, nothing will be visible in the terminal. If the file already exists, the new data will get appended to the end of the file..
command | tee output.txt
The standard output stream will be copied to the file, it will still be visible in the terminal. If the file already exists, it gets overwritten.
command | tee -a output.txt
The standard output stream will be copied to the file, it will still be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
(*)
Bash has no shorthand syntax that allows piping only StdErr to a second command, which would be needed here in combination with tee again to complete the table. If you really need something like that, please look at "How to pipe stderr, and not stdout?" on Stack Overflow for some ways how this can be done e.g. by swapping streams or using process substitution.
command |& tee output.txt
Both the standard output and standard error streams will be copied to the file while still being visible in the terminal. If the file already exists, it gets overwritten.
command |& tee -a output.txt
Both the standard output and standard error streams will be copied to the file while still being visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
A:
Yes it is possible, just redirect the output to a file:
SomeCommand > SomeFile.txt
Or if you want to append data:
SomeCommand >> SomeFile.txt
If you want stderr as well use this:
SomeCommand &> SomeFile.txt
or this to append:
SomeCommand &>> SomeFile.txt
if you want to have both stderr and output displayed on the console and in a file use this:
SomeCommand 2>&1 | tee SomeFile.txt
(If you want the output only, drop the 2 above)
A:
You can also use tee to send the output to a file:
command | tee ~/outputfile.txt
A slight modification will catch stderr as well:
command 2>&1 | tee ~/outputfile.txt
or slightly shorter and less complicated:
command |& tee ~/outputfile.txt
tee is useful if you want to be able to capture command output while also viewing it live.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why doesn't my d3.js line chart work?
I'm currently learning d3.js, and as a task I am trying to build a line chart using a custom data source. For some reason, I can't get the line generator to work, and it seems like it can't create the d attribute for the path element. I don't seem to get any error messages either. Could someone please take a look?
<!DOCTYPE html>
<meta charset="utf-8">
<style>
rect.bar {
//fill: steelblue;
}
.axis text {
font: 10px sans-serif;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="http://d3js.org/d3.v2.js"></script>
<script>
data = [{
name:'A Negative',
data:[{x:1346103936,y:0.10252502},{x:1346190336,y:0.10838352},{x:1346276736,y:0.11182367},{x:1346363136,y:0.1469633},{x:1346449536,y:0.108044505},{x:1346535936,y:0.10141762},{x:1346622336,y:0.13505103},{x:1346708736,y:0.11661343},{x:1346795136,y:0.09985885},{x:1346881536,y:0.10367505},{x:1346967936,y:0.12067748},{x:1347054336,y:0.1329808},{x:1347140736,y:0.14677866},{x:1347227136,y:0.14087029},{x:1347313536,y:0.13160454},{x:1347399936,y:0.1313771},{x:1347486336,y:0.14144897},{x:1347572736,y:0.15051538},{x:1347659136,y:0.15604788},{x:1347745536,y:0.14364798},{x:1347831936,y:0.12961338},{x:1347918336,y:0.11450371},{x:1348004736,y:0.11712107},{x:1348091136,y:0.12876798},{x:1348177536,y:0.10429894},{x:1348263936,y:0.110398784},{x:1348350336,y:0.10483569},{x:1348436736,y:0.14220005},{x:1348523136,y:0.11701017},{x:1348609536,y:0.12221267},{x:1348696576,y:0.11133491}]},{
name:'A Positive',
data:[{x:1346105088,y:0.20869565},{x:1346191488,y:0.14895636},{x:1346277888,y:0.2819277},{x:1346364288,y:0.19342105},{x:1346450688,y:0.35833332},{x:1346537088,y:0.19473684},{x:1346623488,y:0.23015076},{x:1346709888,y:0.15840708},{x:1346796288,y:0.23293903},{x:1346882688,y:0.21885246},{x:1346969088,y:0.22707888},{x:1347055488,y:0.26593626},{x:1347141888,y:0.22822087},{x:1347228288,y:0.24236642},{x:1347314688,y:0.17460318},{x:1347401088,y:0.19075145},{x:1347487488,y:0.1594203},{x:1347573888,y:0.13432837},{x:1347660288,y:0.0},{x:1347746688,y:0.18100129},{x:1347833088,y:0.1605938},{x:1347919488,y:0.12987013},{x:1348005888,y:0.12683824},{x:1348092288,y:0.15542522},{x:1348178688,y:0.13584906},{x:1348265088,y:0.14351852},{x:1348351488,y:0.1322314},{x:1348437888,y:0.13709678},{x:1348524288,y:0.17438692},{x:1348610688,y:0.0},{x:1348700160,y:0.18169399}]},{
name:'A Uncertain',
data:[{x:1346104576,y:0.04397342},{x:1346190976,y:0.044665344},{x:1346277376,y:0.049782943},{x:1346363776,y:0.051038638},{x:1346450176,y:0.050243802},{x:1346536576,y:0.03118218},{x:1346622976,y:0.04424348},{x:1346709376,y:0.04498049},{x:1346795776,y:0.04105231},{x:1346882176,y:0.04970384},{x:1346968576,y:0.045589853},{x:1347054976,y:0.046243627},{x:1347141376,y:0.05226451},{x:1347227776,y:0.047814183},{x:1347314176,y:0.04413969},{x:1347400576,y:0.03914877},{x:1347486976,y:0.042237047},{x:1347573376,y:0.054126237},{x:1347659776,y:0.04697353},{x:1347746176,y:0.04476943},{x:1347832576,y:0.042521983},{x:1347918976,y:0.05310476},{x:1348005376,y:0.059566505},{x:1348091776,y:0.043783925},{x:1348178176,y:0.043761015},{x:1348264576,y:0.046513315},{x:1348350976,y:0.0384231},{x:1348437376,y:0.04024283},{x:1348523776,y:0.040613018},{x:1348610176,y:0.04732518},{x:1348696576,y:0.06337391}]},{
name:'A Positive',
data:[{x:1346104320,y:0.109645985},{x:1346190720,y:0.092952825},{x:1346277120,y:0.10988262},{x:1346363520,y:0.12258253},{x:1346449920,y:0.12162819},{x:1346536320,y:0.11145041},{x:1346622720,y:0.17937773},{x:1346709120,y:0.1605882},{x:1346795520,y:0.15555955},{x:1346881920,y:0.15066825},{x:1346968320,y:0.17311412},{x:1347054720,y:0.21528025},{x:1347141120,y:0.20169735},{x:1347227520,y:0.15779452},{x:1347313920,y:0.1469917},{x:1347400320,y:0.15995567},{x:1347486720,y:0.17675863},{x:1347573120,y:0.14658852},{x:1347659520,y:0.2049946},{x:1347745920,y:0.15699232},{x:1347832320,y:0.14301357},{x:1347918720,y:0.1457654},{x:1348005120,y:0.1532571},{x:1348091520,y:0.17817244},{x:1348177920,y:0.13126957},{x:1348264320,y:0.12135763},{x:1348350720,y:0.14930858},{x:1348437120,y:0.14171022},{x:1348523520,y:0.12027296},{x:1348609920,y:0.13843122},{x:1348696576,y:0.15421592}]},{
name:'A Uncertain',
data:[{x:1346103936,y:0.046369042},{x:1346190336,y:0.042160377},{x:1346276736,y:0.06631727},{x:1346363136,y:0.043078776},{x:1346449536,y:0.049522486},{x:1346535936,y:0.041241966},{x:1346622336,y:0.041665666},{x:1346708736,y:0.0461979},{x:1346795136,y:0.044713285},{x:1346881536,y:0.041361943},{x:1346967936,y:0.051421918},{x:1347054336,y:0.04684727},{x:1347140736,y:0.048165746},{x:1347227136,y:0.053684916},{x:1347313536,y:0.05550549},{x:1347399936,y:0.05435959},{x:1347486336,y:0.04710294},{x:1347572736,y:0.05433203},{x:1347659136,y:0.06015368},{x:1347745536,y:0.047590178},{x:1347831936,y:0.045565397},{x:1347918336,y:0.056516618},{x:1348004736,y:0.06080917},{x:1348091136,y:0.068452686},{x:1348177536,y:0.049881306},{x:1348263936,y:0.04221391},{x:1348350336,y:0.0484556},{x:1348436736,y:0.0402809},{x:1348523136,y:0.058744337},{x:1348609536,y:0.054147776},{x:1348696576,y:0.056016088}]},{
name:'A Negative',
data:[{x:1346104832,y:0.25386313},{x:1346191232,y:0.14606741},{x:1346277632,y:0.17222223},{x:1346364032,y:0.19863014},{x:1346450432,y:0.17857143},{x:1346536832,y:0.14606741},{x:1346623232,y:0.12448133},{x:1346709632,y:0.12931034},{x:1346796032,y:0.25714287},{x:1346882432,y:0.22222222},{x:1346968832,y:0.1764706},{x:1347055232,y:0.28846154},{x:1347141632,y:0.1826923},{x:1347228032,y:0.2236842},{x:1347314432,y:0.091836736},{x:1347400832,y:0.25},{x:1347487232,y:0.17567568},{x:1347573632,y:0.15384616},{x:1347660032,y:0.0},{x:1347746432,y:0.23584905},{x:1347832832,y:0.13718411},{x:1347919232,y:0.0},{x:1348005632,y:0.13533835},{x:1348092032,y:0.0},{x:1348178432,y:0.06315789},{x:1348264832,y:0.0},{x:1348351232,y:0.14457831},{x:1348437632,y:0.13253012},{x:1348524032,y:0.1},{x:1348610432,y:0.0},{x:1348700160,y:0.29826254}]}];
var x = d3.scale.linear()
.range([0, "100%"])
.domain(d3.extent(data[0].data, function(d) { return d.x }));
var y = d3.scale.linear()
.domain([0, d3.max(data[0].data, function(d) { return d.y; })])
.range([0, "100%"]);
var line = d3.svg.line()
.x(function(d) { return x(d.x)})
.y(function(d) { return y(d.y)})
.interpolate("basis");
var svg = d3.select("body").append("svg")
.attr("width", "100%")
.attr("height", "500px");
var colors = d3.scale.category20().range();
var group = svg.selectAll("g").data(data);
group.enter().append("g")
.attr("fill", function(d, i) { return colors[i % colors.length]; })
.attr("opacity", "0.5").attr("stroke", "black").attr("stroke-width", "2");
group.selectAll("path")
.data(function(d) {return d.data})
.enter().append("path")
.attr("d", line)
.attr("class", "line");
</script>
A:
I see a couple problems. The first is that the width and height attributes of SVG elements should be specified as unit-less numbers—always in pixels. This defines the coordinate space of the SVG element as well as its size on-screen. You can also set width and height style properties using px or percentages, but you should only do this in addition to setting the width and height attributes. The typical pattern is:
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
You might also want to look at the margin conventions example for more information.
The second thing I would change is to use this coordinate space to set the range of your scales, rather than using the percentage positioning:
var x = d3.scale.linear()
.domain(…)
.range([0, width]);
var y = d3.scale.linear()
.domain(…)
.range([height, 0]);
Note that the y-scale's range is inverted, so that y-0 is at the bottom of the chart rather than the default top. Again, see the conventions example for details.
Lastly, it looks like your x-values are seconds since UNIX epoch, so I would recommend converting your data to Date objects and then using a d3.time.scale. This makes it much easier to add an x-axis with date labels in the future. You can convert to dates as a preprocessing step like so:
data.forEach(function(series) {
series.data.forEach(function(d) {
d.x = new Date(d.x * 1000);
});
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MIPS - Simple Addition - Input Storage Issue using Temp registers
this is my first time writing an assembly program. I'm supposed to write a basic addition program using $t0, $t1 and $t2 to store the first two user inputs and the sum. I am having trouble understanding why my user input is always stored as 5.
Might there be an issue with my syscalls?
.data
prompt1: .asciiz "Give me an integer number: "
debug1: .asciiz "The first number inputted was: "
debug2: .asciiz "The second number inputted was: "
prompt2: .asciiz "\nGive me another integer number: "
result: .asciiz "\nThe sum of the two inputted numbers is: "
.text
li $v0, 4 #System call to print a string
la $a0, prompt1 #load prompt1 into address 0 - Give me an integer
syscall
#store first input in $t0
li $v0, 5 #System call code for Read Integer from input
move $t0, $v0 #Move value from $v0 to $t0
syscall
#print the First user input for debugging --> Always prints 5
li $v0, 4 #System call code for Print String
la $a0, debug1 #Print debug1 string
syscall
li $v0, 1 #print int
move $a0, $t0 #move value in $t0 to $a0
syscall
#call prompt 2
li $v0, 4 #Print a string
la $a0, prompt2 # Here is the value to print - "Give me another integer"
syscall
#store second input in $t1
li $v0, 5 #System call code for Read Integer from input
move $t1, $v0 # $t1 = value from input
syscall
#print the second int input for debugging --> Always prints 5
li $v0, 4 #System call code for Print String
la $a0, debug2 #Print debug2 string
syscall
li $v0, 1 #System call code for Print Int
move $a0, $t1 #move value in $t1 to $a0
syscall
#add numbers
add $t2, $t1, $t0 # $t2 = $t1+$t0
li $v0, 4 #System call to Print String
la $a0, result #Print the string result
syscall
li $v0, 1 #System call to Print Int
move $a0, $t2 #Move $t2, which = $t1 + $t0, into $a0
syscall
I appreciate the help in advance.
A:
Found the issue --
#store second input in $t1
li $v0, 5 #System call code for Read Integer from input
syscall
move $t1, $v0 # $t1 = value from input
Should have a syscall after the li line, and not after the move line. Otherwise the value of $v0 gets moved to $t0, which is 5, without waiting for the user input to change the value of $v0. If you have a syscall after the move line, the program will executing another service call based on your user input. See more in the comments here : Service Calls Executing Based on User Input
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Grouping types of bugs by date and priority
I currently have a table Bugs that looks like this:
|ID |Priority |Created |Updated |Status |Category
|X123 |Major |01/01 |01/03 |Open |A
|X145 |Normal |01/01 |01/02 |Closed |B
|X678 |Minor |01/03 |01/03 |Open |C
|X763 |Major |01/02 |01/03 |Closed |C
All columns are varchar(25) except Created and Updated, which are dates.
I need to create a view with the following format:
|Date |Major |Normal |Minor |Category
|01/01 |4 |3 |4 |A
|01/01 |3 |5 |2 |B
|01/01 |2 |4 |7 |C
|01/02 |7 |3 |4 |A
|01/02 |3 |9 |5 |B
|01/02 |1 |6 |3 |C
Where the numbers under Major, Normal, and Minor are the count of CURRENTLY OPEN bugs of that priority on a given date. By currently open, I mean this: open bugs are active on the interval Created-GETDATE(), closed bugs are active on the interval Created-Updated.
I have a list of all the dates I need through this query:
WITH D AS
(
SELECT Dates AS DateValue
FROM DatesTable
WHERE Dates >= '2012-03-23'
AND Dates <= GETDATE()
),
Any ideas of how I might do this? I've played with the idea of a pivot query and grouping, but I've not been able to cover everything I need. Your help is greatly appreciated!
EDIT: The Bugs table with example data
CREATE TABLE [dbo].[Bugs](
[ID] [varchar](25) NOT NULL,
[Priority] [varchar](25) NOT NULL,
[Updated] [date] NOT NULL,
[Created] [date] NOT NULL,
[Status] [varchar](25) NOT NULL,
[Category] [varchar](25) NOT NULL,
) ON [PRIMARY]
INSERT INTO Bugs VALUES (X123, Major, 01/01/12, 01/03/12, Open, A)
INSERT INTO Bugs VALUES (X145, Normal, 01/01/12, 01/02/12, Closed, B)
INSERT INTO Bugs VALUES (X678, Minor, 01/03/12, 01/03/12, Open, C)
INSERT INTO Bugs VALUES (X763, Major, 01/02/12, 01/03/12, Closed, C )
A:
This is what I tested at last:
SELECT d.Dates as Date,
SUM(CASE Priority WHEN 'Major' THEN 1 ELSE 0 END) as Major,
SUM(CASE Priority WHEN 'Normal' THEN 1 ELSE 0 END) as Normal,
SUM(CASE Priority WHEN 'Minor' THEN 1 ELSE 0 END) as Minor,
b.Category
FROM Bugs b
INNER JOIN DatesTable d ON d.Dates >= b.Created
WHERE (Status = 'Closed' AND d.Dates <= Updated OR Status = 'Open')
AND d.Dates <= GETDATE() AND d.Dates >= '2012-01-01'
GROUP BY d.Dates, b.Category
ORDER BY d.Dates
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Можно ли сделать такую выборку?
Есть таблица товары и таблица алиасы. Они ваще никак не связаны. Алиасы как то сопоставляются cms ивыводят информацию о товаре.
Таблица алиасы:
Таблица товары:
Тут как видно в алиасах есть столбец в котором строки типа product_id=3000460 это ссылка на товар, так же есть ЧПУ.
Проблема только в том что это таблицы никакими ключами не связаны, так уже б все сделал.
Мне собственно нужно как то сделать выборку из двух таблиц так что бы вывести название товара и его алиас, но я не пойму как это сделать. Может не стандартными способами mysql возможно это сделать?
A:
Если тупо и просто, то
JOIN table_alias ON table_alias.url = CONCAT('product_id=', table_product.id)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Correct regex for matching the string with max number value
I am trying to figure out a way to match all the strings using regular expressions like below
Input String:
https://subdomain.domain.com/e8cf09b4763e03d208dfd21121baacd4/domain_p6amv8xJVr1qto1_500.txt
https://subdomain.domain.com/e8cf09b4763e03d208dfd21121baacd4/domain_p6amv8xJVr1qto1_400.txt
https://subdomain.domain.com/e8cf09b4763e03d208dfd21121baacd4/domain_p6amv8xJVr1qto1_250.txt
https://subdomain.domain.com/e8cf09b4763e03d208dfd21121baacd4/domain_p6amv8xJVr1qto1_10.txt
https://subdomain.domain.com/163c7b0508062729dsdk1f1e264210/domain_p6amv8xJVr1wvilqto2_640.txt
https://subdomain.domain.com/163c7b0508062729dsdk1f1e264210/domain_p6amv8xJVr1wvilqto2_1280.txt
https://subdomain.domain.com/163c7b0508062729dsdk1f1e264210/domain_p6amv8xJVr1wvilqto2_540.txt
https://subdomain.domain.com/adfd386be957c3247/domain_p6amv8xJVr1wvilqto3_250.txt
https://subdomain.domain.com/adfd386be957c3247/domain_p6amv8xJVr1wvilqto3_100.txt
https://subdomain.domain.com/25e5ccd5e95ca2888a39b939f199b822/domain_p6amv8xJVr1ilqto4_640.txt
https://subdomain.domain.com/25e5ccd5e95ca2888a39b939f199b822/domain_p6amv8xJVr1ilqto4_540.txt
https://subdomain.domain.com/25e5ccd5e95ca2888a39b939f199b822/domain_p6amv8xJVr1ilqto4_980.csv
Expected Output:
https://subdomain.domain.com/e8cf09b4763e03d208dfd21121baacd4/domain_p6amv8xJVr1qto1_500.txt
https://subdomain.domain.com/163c7b0508062729dsdk1f1e264210/domain_p6amv8xJVr1wvilqto2_1280.txt
https://subdomain.domain.com/adfd386be957c3247/domain_p6amv8xJVr1wvilqto3_250.txt
https://subdomain.domain.com/25e5ccd5e95ca2888a39b939f199b822/domain_p6amv8xJVr1ilqto4_980.csv
I am trying the below expression, but it is getting all the urls, how can I limit the results to only what I want?
"https://subdomain.domain.com/([^,:"]+?([_\d]*?)).(txt|csv)"
A:
If your blocks are indeed grouped as in your question, it is easy to do this
using a regex.
@"(?m)(?:^[^\S\r\n]*(https?://\S+?_)(\d+)\.(txt|csv)[^\S\r\n]*$\r?\n)+(?=\s*\r\n|$)"
Explained
(?m)
(?: # Cluster group for block
^ # BOL
[^\S\r\n]* # Optional horizontal whitespace
( https?:// \S+? _ ) # (1), Location
( \d+ ) # (2), Number
\.
( txt | csv ) # (3), Extension
[^\S\r\n]* # Optional horizontal whitespace
$ \r? \n # EOL plus linebreak
)+ # End cluster, 1 to many times
(?= \s* \r \n | $ ) # Lookahead to determine where the end of block is
C# code sample
var str =
" https://subdomain.domain.com/e8cf09b4763e03d208dfd21121baacd4/domain_p6amv8xJVr1qto1_500.txt\n" +
" https://subdomain.domain.com/e8cf09b4763e03d208dfd21121baacd4/domain_p6amv8xJVr1qto1_400.txt\n" +
" https://subdomain.domain.com/e8cf09b4763e03d208dfd21121baacd4/domain_p6amv8xJVr1qto1_250.txt\n" +
" https://subdomain.domain.com/e8cf09b4763e03d208dfd21121baacd4/domain_p6amv8xJVr1qto1_10.txt\n" +
"\n" +
" https://subdomain.domain.com/163c7b0508062729dsdk1f1e264210/domain_p6amv8xJVr1wvilqto2_640.txt\n" +
" https://subdomain.domain.com/163c7b0508062729dsdk1f1e264210/domain_p6amv8xJVr1wvilqto2_1280.txt\n" +
" https://subdomain.domain.com/163c7b0508062729dsdk1f1e264210/domain_p6amv8xJVr1wvilqto2_540.txt\n" +
"\n" +
" https://subdomain.domain.com/adfd386be957c3247/domain_p6amv8xJVr1wvilqto3_250.txt\n" +
" https://subdomain.domain.com/adfd386be957c3247/domain_p6amv8xJVr1wvilqto3_100.txt\n" +
"\n" +
" https://subdomain.domain.com/25e5ccd5e95ca2888a39b939f199b822/domain_p6amv8xJVr1ilqto4_640.txt\n" +
" https://subdomain.domain.com/25e5ccd5e95ca2888a39b939f199b822/domain_p6amv8xJVr1ilqto4_540.txt\n" +
" https://subdomain.domain.com/25e5ccd5e95ca2888a39b939f199b822/domain_p6amv8xJVr1ilqto4_980.csv\n" +
"\n";
// This regex matches a block each time
var RxBlock = new Regex(@"(?m)(?:^[^\S\r\n]*(https?://\S+?_)(\d+)\.(txt|csv)[^\S\r\n]*$\r?\n)+(?=\s*\r\n|$)");
Match M = RxBlock.Match(str);
while (M.Success)
{
CaptureCollection ccFileLoc = M.Groups[1].Captures; // location
CaptureCollection ccFileNum = M.Groups[2].Captures; // number
CaptureCollection ccFileExt = M.Groups[3].Captures; // extension
String Loc = ccFileLoc[0].Value;
String Ext = ccFileExt[0].Value;
int Largest = 0;
bool bValid = true;
if (Int32.TryParse(ccFileNum[0].Value, out Largest))
{
int cur_num = 0;
int cnt = ccFileLoc.Count;
for (int i = 0; bValid && i < cnt; i++)
{
if (!Int32.TryParse(ccFileNum[i].Value, out cur_num) || ccFileLoc[i].Value != Loc)
bValid = false;
else
if (cur_num > Largest)
{
Largest = cur_num;
Ext = ccFileExt[i].Value;
}
}
}
else
bValid = false;
if ( bValid )
Console.WriteLine("{0}{1}.{2} ", Loc, Largest, Ext);
M = M.NextMatch();
}
Output
https://subdomain.domain.com/e8cf09b4763e03d208dfd21121baacd4/domain_p6amv8xJVr1qto1_500.txt
https://subdomain.domain.com/163c7b0508062729dsdk1f1e264210/domain_p6amv8xJVr1wvilqto2_1280.txt
https://subdomain.domain.com/adfd386be957c3247/domain_p6amv8xJVr1wvilqto3_250.txt
https://subdomain.domain.com/25e5ccd5e95ca2888a39b939f199b822/domain_p6amv8xJVr1ilqto4_980.csv
Even if your data is not sorted, you could still use regex this way.
It has to have a line sort done on it first.
Then, it needs a slight modification. If you want to do it this
way, let me know and I might show you how.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Допустимость слишком общих ответов
Хотел бы поинтересоваться мнением сообщества (и, в частности, его администрации) относительно того, допускаются ли ответы, которые чисто технически являются ответами на вопрос, но столь общие, что никак не могут помочь ни автору вопроса, ни человеку, который столкнётся с подобной проблемой / задачей.
Пример такого вопроса в теме / в очереди проверок
Технически это ответ на вопрос, но он настолько очевидный, что буквально взят из тела самого вопроса.
Стоит ли флагать такие ответы / рекомендовать их удаление, или же достаточно просто поставить -1? Если стоит, то с применением какого пункта?
A:
Здесь нет смысла давать ответ или выяснять правильные ли даны ответы, потому что вопрос вида "Нужна помощь в работе со строками в Python3" сам по себе является бесполезным. Необходимо переформулировать вопрос либо закрыть.
Переформулировать вопрос должен сам автор, потому что непонятно, какого плана ответы его интересуют:
на вопрос "как вывести массив строк на питоне" будут одни ответы
на вопрос "почему этот код вызвал такую ошибку" будут другие ответы, при
чем в этом случае правильнее было бы еще уточнить, зачем такой код.
В любом случае, если автор последует справке, то скорее всего он сам закроет свой вопрос в итоге.
Прежде чем задать вопрос, убедитесь, что вы выполнили тщательный поиск ответа. Поделитесь результатом вашего поиска и расскажите, что вы нашли и почему найденные ответы вас не устроили.
A:
Такие ответы допустимы, конечно. Но только до тех пор, пока на него не поставят тревогу (¬‿¬ )
Я такие ответы переношу по тревогам в комментарии, т.к. они ничего нового не привносят в обсуждение вопроса.
Порой замечаю такое за людьми с большой репутацией, которые подобными ответами пытаются показать, что вопрос (якобы) плохой. Работает такое плохо и может оскорбить участника.
Если бы в ответе были бы какие-то пояснения (как в другом ответе), то всё было бы нормально.
Стоит ли флагать такие ответы / рекомендовать их удаление, или же достаточно просто поставить -1? Если стоит, то с применением какого пункта?
Да, пункт "не является ответом".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Автоматическое обновление запросов pandas
Написал бота в телеграме - основная его задача показывать материалы с сайта, которые должен соскрабить (если так можно выражаться) pandas.
Запрос он отправляет только при включении бота, во время запроса он не обновляет эту информацию (т.е. бота нужно выключить и включить снова, чтобы он обновил данные).
Я не понимаю, как сделать так, чтобы скрабил pandas не вначале, а после каждого запроса от пользователя.
UPD: Хорошо, если код нужен, то скину. Заранее извиняюсь, если кого-то стошнит - я пока достаточно коряво пишу =( Сам код -
import telebot
import currency
import datetime
TOKEN = ''
bot = telebot.TeleBot(TOKEN)
now = datetime.datetime.now()
time = str(now.year) + "." + str(now.month) + "." + str(now.day) + " " + str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
@bot.message_handler(commands=['start'])
def start(message):
sent = bot.send_message(message.chat.id, 'Привет, ' + str(message.chat.username) + '! Какая валюта тебя интересует? На данный момент я знаю курс : \n1.Доллара\n2.Евро\n3.Фунта\n4.Франка\n5.Юан\n6.Иен')
@bot.message_handler(content_types=['text'])
def handler_text(message):
if message.text == "Доллар" or "Dollar" or "USD" or "/usd" or "/dollar" or "1" or "/1":
bot.send_message(message.chat.id, "Стоимость Доллара на на момент запроса (" + str(time) + ") - " + str(currency.usd) + " Рублей")
elif message.text == "Евро" or "Euro" or "/euro" or "2" or "/2":
bot.send_message(message.chat.id, "Стоимость Евро на на момент запроса (" + str(time) + ") - " + str(currency.eur) + " Рублей")
elif message.text == "Фунт" or "lb" or "pound" or "/lb" or "/pound" or "3" or "/3":
bot.send_message(message.chat.id, "Стоимость Фунта на на момент запроса (" + str(time) + ") - " + str(currency.gbp) + " Рублей")
elif message.text == "Иена" or "Yen" or "/yen" or "6" or "/6":
bot.send_message(message.chat.id, "Стоимость Иен на на момент запроса (" + str(time) + ") - " + str(currency.jpy) + " Рублей")
elif message.text == "Юань" or "Yuan" or "/yuan" or "5" or "/5":
bot.send_message(message.chat.id, "Стоимость Юаней на на момент запроса (" + str(time) + ") - " + str(currency.cny) + " Рублей")
elif message.text == "Франк" or "Frank" or "/frank" or "4" or "/4":
bot.send_message(message.chat.id, "Стоимость Франков на на момент запроса (" + str(time) + ") - " + str(currency.chf) + " Рублей")
bot.polling(none_stop=True, interval=0)
Файл currency.py -
import pandas as pd
df = pd.read_html('http://www.finanz.ru/valyuty/v-realnom-vremeni', encoding='utf-8')[1] \
.dropna(axis=1)
usd1 = df.loc[df[1].str.contains(r'^USD\/')]
eur1 = df.loc[df[1].str.contains(r'^EUR\/')]
gbp1 = df.loc[df[1].str.contains(r'^GBP\/')]
jpy1 = df.loc[df[1].str.contains(r'^JPY\/')]
cny1 = df.loc[df[1].str.contains(r'^CNY\/')]
chf1 = df.loc[df[1].str.contains(r'^CHF\/')]
usd = int(usd1[2][3]) / 10000
eur = int(eur1[2][2]) / 10000
gbp = int(gbp1[2][1]) / 10000
jpy = int(jpy1[2][4]) / 10000
cny = int(cny1[2][5]) / 10000
chf = int(chf1[2][6]) / 10000
Большое спасибо всем, кто проявляет интерес.
A:
Я бы оформил это в виде функции (как предложил @Anatol), которую можно вызывать в нужные моменты времени:
import pandas as pd
def get_curr_rates(curr_code='RUB'):
# parse rates into Pandas.DataFrame
# remove empty columns
df = pd.read_html('http://www.finanz.ru/valyuty/v-realnom-vremeni',
encoding='utf-8')[1] \
.dropna(axis=1)
# set real column names
df.columns = ['curr_pair','bid','call','close','pct','abs_val','time']
# filter DF: leaving only those currency pairs
# where the second currency == `curr_code`
# for example: ['USD/RUB','EUR/RUB','GBP/RUB', ...]
df = df.loc[df['curr_pair'].str.contains(r'\/{}'.format(curr_code))]
# parse first currency from the [curr_pair] into `curr` column
df['curr'] = df['curr_pair'].str.split('/').str[0]
# convert ['bid','call','close'] columns to numeric dtypes
num_cols = ['bid','call','close']
df[num_cols] = df[num_cols].apply(pd.to_numeric, errors='coerce')
# return a Pandas.Series with the currency as an index
return df.set_index('curr')['bid']
Пример работы с функцией:
In [129]: rub = get_curr_rates()
In [130]: rub
Out[130]:
curr
GBP 781673
EUR 706812
USD 601056
JPY 5464
CNY 89988
CHF 623761
Name: bid, dtype: int64
In [131]: rub['USD']
Out[131]: 601056
In [132]: rub['USD'] / 10**4
Out[132]: 60.105600000000003
In [133]: rub['EUR'] / 10**4
Out[133]: 70.681200000000004
In [134]: uah = get_curr_rates(curr_code='UAH')
In [135]: uah
Out[135]:
curr
EUR 301896
USD 257125
CHF 266838
GBP 334468
Name: bid, dtype: int64
In [136]: uah['USD'] / 10**4
Out[136]: 25.712499999999999
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mathematica List Selection
I have a list which contains these elements :
{{{206.314, 4135.81}, {95.84, 0.}},
{{306.314, 4135.81}, {195.84, 0.}},
{{407.704, 4135.81}, {645.716, 0.}},
{{966.432, 4135.81}, {919.94, 0.}},
{{1116.14, 4135.81}, {1323.13, 0.}},
{{1711.13, 4135.81}, {1697.04,0.}},
{{1785.57, 4135.81}, {2152.23, 0.}},
{{2422.57, 4135.81}, {2314.23, 0.}},
{{2713.03, 4135.81}, {2604.99, 0.}}}
The format of the list is {{{ Point 1, Point 2}, {Point 3, Point 4}}, {{Point 1, Point 2}, {Point 3, Point 4}},.......}
Now I want to make a new list which contains only those elements whose Point 1 elements are at a difference of nearly 580-720 to Point 1 points. So my new list should be:
{ {{407.704, 4135.81}, {645.716, 0.}}, ,
{{1116.14, 4135.81}, {1323.13, 0.}}
{{1711.13, 4135.81}, {1697.04,0.}},
{{2422.57, 4135.81}, {2314.23, 0.}}
How do I do this?
UPDATE
More explanation about the question:-
Suppose we start from 206.314 and find out that there is no other point which is 580-710 more than this. So we now choose 306.314 and now we see that we have 966.432, which is 660 points from 306.314. So we add the two full points {{{306.314, 4135.81}, {195.84, 0.}}, {{966.432, 4135.81}, {919.94, 0.}}} in a new list. Then we find that there is no other point which is 580-710 points more than 966.432. So we drop these two points since we should have a list of minimum 4-5 point set.
So if we take 407 as start we get 4 points:-
1116- 407 = 709
1711- 1116= 595
2422-1711= 711
On the other hand if we take 407 and take 1785 instead of 1711, that is also correct since we will again get 4 points (including 407). So both answers will work in this.
A:
First, I would like to give a very simple example to illustrate what kind of problem I think you want to solve.
Let's have this list of points :
mylist = {21, 23, 26, 31, 31.5, 33, 35, 40.1, 40.4, 42.2, 52.};
The problem is : find all the subsets of points such that the distance between 2 consecutive points in each subset is min<d=(xj-xi)<max.
Here, if min=9 and max=11, these subgroups are :
{21, 31, 40.1}
{21, 31, 40.4}
{21, 31.5, 42.2, 52.}
{23, 33, 42.2, 52.}
For example, if we start from 21, the next points within distance [9,11] from it are 31 and 31.5. In the next move you see that 42.2 is at the required distance from 31.5 (9 < 42.2-31.5= 10.7 <11) but not from 31. (22.2-31=11.2 >11). So we know that {21,31.5} will belong to a different subset than {21,31}. And so on. As each subset grows, it can split to form new subsets as it is the case again here for {21,31}.
So, the problem is more complicated than it seems, because there are a lot of combinations to track.
1. First step : for each point find all the points at the given distance min<d<max
Let's do it for the first point of the list :
testpoint = mylist[[1]]
(*21*)
.
Position[mylist, x_?(9 < # - testpoint < 11 & )]
(*{{4}, {5}}*)
.
mylist[[4]]
mylist[[5]]
(* 31 *)
(* 31.5 *)
As expected 31 and 31.5 were found.
Let's do it for all the points, and have the result in a friendly and useful way :
closePointsPositions = Table[i ->
Flatten[Position[mylist, x_?(9 < # - mylist[[i]] < 11 & )]],
{i, Length[mylist]}] // DeleteCases[#, _ -> {}] &
(*{1 -> {4, 5}, 2 -> {6}, 4 -> {8, 9}, 5 -> {10}, 6 -> {10}, 10 -> {11}}*)
This is actually the solution of the problem but in a condensed form. It shows all the connections found, from which you can build the corresponding paths.
For example here : point 1 (21) of the list is within the required distance from point 4 (31.) and from point 5 (31.5). Next, you see that point 4 (31.) is "connected" to the points 8 (40.1) and 9 (40.4). And so on.
How to extract from this result, the corresponding subsets of "connected" points ?
2. Graph approach
The problem really looks like a network problem so it is suitable to be examined with Graph-tools that Mathematica actually has built-in.
(Actually I am very bad at graph theory but this was time to explore)
Let's slightly modify the previous result so it is compatible with graph tools :
edges = Flatten[Thread /@ closePointsPositions]
{1 -> 4, 1 -> 5, 2 -> 6, 4 -> 8, 4 -> 9, 5 -> 10, 6 -> 10, 10 -> 11}
Let's visualize this as a graph :
mygraph = Graph[edges, VertexLabels -> "Name"]
For the labels, if instead of the positions of the points you want the positions values then :
vertexlist = Union[Flatten[edges /. Rule -> List]]
(*{1, 2, 4, 5, 6, 8, 9, 10, 11}*)
.
mygraph = Graph[edges,
VertexLabels -> (# -> NumberForm[mylist[[#]], {20, 1}] & ) /@ vertexlist]
This graphic shows immediatly the different solutions of the problem (when there are more points it is probably less friendly however.)
But how to automatically extract the best solutions from this ?
I did not find in the documentation a function which is able to answer diretcly the question : "give me the longest path(s) in the graph". (As I said before my knowledge in graph tools is very low so maybe this exists ?).
But I found a function GraphDistanceMatrix to list all the path lengths in the network as a function of the starting and ending points(vertex).
TableForm[GraphDistanceMatrix[mygraph], TableHeadings ->
{c = (Style[#1, Bold, Red] & ) /@ VertexList[mygraph], c}]
You see here that the longest paths are size 3, and correspond to the starting/ending points position {1,11}, and {2,11}
Then to extract the corresponding path, for example :
FindPath[mygraph, 1, 11]
(*{{1, 5, 10, 11}}*)
.
mylist[[FindPath[mygraph, 1, 11][[1]]]]
(*{21, 31.5, 42.2, 52.}*)
You can automatize the results :
maxpathlength = Max[GraphDistanceMatrix[mygraph] /. Infinity -> -1]
(*3*)
For example, we'll be looking for all the path with maximum lengths maxpathlength:
bestpos = Position[GraphDistanceMatrix[mygraph] /. Infinity -> -1,
_?(# >= maxpathlength & )]
(*{{1, 9}, {4, 9}}*)
.
bestvertex = VertexList[mygraph][[#]]& /@ bestpos
(*{{1, 11}, {2, 11}}*)
.
bestpaths = Flatten[FindPath[mygraph, Sequence @@ #]& /@ bestvertex, 1]
(*{{1, 5, 10, 11}, {2, 6, 10, 11}}*)
And finally, as expected, the subsets containing the maximum number of points are :
mylist[[#]]& /@ bestpaths
(*{{21, 31.5, 42.2, 52.}, {23, 33, 42.2, 52.}}*)
3. Approach without graph tools
Actually, before testing the graph tools, I also solved the problem using some common Mathematica functions :
I "just" had to define this nice function :
coolRule[x_ -> y_] := path : {___, x} :>
Sequence @@ (path /. x -> Sequence @@ ## & ) /@ Thread[{x, y}]
Then using the already defined closePointsPositions
closePointsPositions
(*{1 -> {4, 5}, 2 -> {6}, 4 -> {8, 9}, 5 -> {10}, 6 -> {10}, 10 -> {11}}*)
this gives all the starting points of all possible paths :
startpath = Complement[closePointsPositions[[All, 1]],
Flatten[closePointsPositions[[All, 2]]]]
(*{1, 2}*)
this reconstructs the entire paths starting from the previous points :
allpaths = Fold[#1 /. coolRule[#2] & , List /@ startpath, closePointsPositions]
{{1, 4, 8}, {1, 4, 9}, {1, 5, 10, 11}, {2, 6, 10, 11}}
Now, for example I want the paths with more than 3 points :
bestpaths = Select[allpaths, Length[#] > 3 & ]
(*{{1, 5, 10, 11}, {2, 6, 10, 11}}*)
The corresponding positions are as expected :
mylist[[#]]& /@ bestpaths
(*{{21, 31.5, 42.2, 52.}, {23, 33, 42.2, 52.}}*)
4. Application to your problem
I recommend you to start a fresh kernel :
Quit
then as before :
coolRule[x_ -> y_] := path : {___, x} :>
Sequence @@ (path /. x -> Sequence @@ ## & ) /@ Thread[{x, y}]
Your initial group of points :
allgrouppoints = {{{206.314, 4135.81}, {95.84, 0.}}, {{306.314, 4135.81},
{195.84, 0.}}, {{407.704, 4135.81}, {645.716, 0.}},
{{966.432, 4135.81}, {919.94, 0.}}, {{1116.14, 4135.81}, {1323.13, 0.}},
{{1711.13, 4135.81}, {1697.04, 0.}}, {{1785.57, 4135.81}, {2152.23, 0.}},
{{2422.57, 4135.81}, {2314.23, 0.}}, {{2713.03, 4135.81}, {2604.99, 0.}}};
Let's take all the p1 points (as you you defined them in your question) :
mylist = allgrouppoints[[All, 1, 1]]
(*{206.314, 306.314, 407.704, 966.432, 1116.14, 1711.13, 1785.57, 2422.57,
2713.03}*)
Define your distance interval :
min = 580;
max = 710;
then
closePointsPositions = Table[i -> Flatten[
Position[mylist, (x_)?(min < # - mylist[[i]] < max & )]],
{i, Length[mylist]}] // DeleteCases[#, _ -> {}] &;
edges = Flatten[Thread /@ closePointsPositions];
vertexlist = Union[Flatten[edges /. Rule -> List]];
mygraph = Graph[edges, VertexLabels ->
(# -> NumberForm[mylist[[#]], {20, 1}] & ) /@ vertexlist]
startpath = Complement[closePointsPositions[[All, 1]],
Flatten[closePointsPositions[[All, 2]]]];
allpaths = Fold[#1 /. coolRule[#2] & , List /@ startpath, closePointsPositions];
maxpoints = Max[Length /@ allpaths];
Print["The maximum number of points given the distance interval ", {min, max},
" is : ", maxpoints];
(*The maximum number of points given the distance interval {580,710} is : 4*)
Get the points subsets containing more than 3 points :
bestpaths = Select[allpaths, Length[#] > 3 & ];
mylist[[#]]& /@ bestpaths
gives
{{407.704, 1116.14, 1785.57, 2422.57}}
In your case, to extract the corresponding groups points you just input :
allgrouppoints[[#]]& /@ bestpaths
which gives
{{{{407.704, 4135.81}, {645.716, 0.}}, {{1116.14, 4135.81}, {1323.13, 0.}},
{{1785.57, 4135.81}, {2152.23, 0.}}, {{2422.57, 4135.81}, {2314.23, 0.}}}}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the correct definition of $k$-tree?
As the title says, what is the correct definition of $k$-tree? There are several papers that talk about $k$-trees and partial $k$-trees as alternative definitions for graphs with bounded treewidth, and I've seen many seemingly incorrect definitions. For example, at least one place defines $k$-trees as follows:
A graph is called a $k$-tree if and only if either $G$ is the complete graph with $k$ vertices, or $G$ has a vertex $v$ with degree $k − 1$ such that $G \setminus v$ is a $k$-tree. A partial $k$-tree is any subgraph of a $k$-tree.
According to this definition, one can create the following graph:
Start with an edge $(v_1, v_2)$, a $2$-tree.
For $i=1\ldots n$, create a vertex $v_i$ and make it adjacent to $v_{i-1}$ and $v_{i-2}$.
Doing this would create a strip of $n$ squares with diagonals. Similarly, we can start creating a band from the first square in a direction orthogonal to the strip above. Then, we would have the first row and first column of an $n \times n$ grid. Filling in the grid is easy by creating vertices and joining them to the vertices to its above and to its left.
The end result is a graph that contains an $n\times n$ grid, which, in effect, is known to be of treewidth $n$.
A correct definition of $k$-trees has to be the following:
A graph is called a $k$-tree if and only if either $G$ is a complete graph with $k$ vertices, or $G$ has a vertex $v$ with degree $k-1$ such that the neighbor of $v$ forms a $k$-clique, and $G \ v$ is a $k$-tree.
Then, the grid-like graph described as above cannot be created.
Am I correct?
A:
I basically agree with you, with just a tiny modification:
A graph $G$ is a $k$-tree if and only if either $G$ is a complete graph with $k+1$ vertices, or $G$ has a vertex $v$ such that the (open) neighborhood of $v$ forms a $k$-clique, and $G - v$ is a $k$-tree.
In other words, $v$ should have degree $k$, instead $k-1$ in your definition.
I personally prefer the bottom-up definition, but this is just a matter of taste:
The complete graph on $k+1$ vertices is a $k$-tree.
A $k$-tree $G$ with $n+1$ vertices ($n\ge k+1$) can be constructed from a $k$-tree $H$ with $n$ vertices by adding a vertex adjacent to exactly $k$ vertices that form a $k$-clique in $H$.
No other graphs are $k$-trees.
This definition is a slightly modified version of the definition from Pinar Heggernes' lecture notes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Completar valores em uma tabela, com valores da própria tabela?
Eu tenho a tabela
data ativo valor ajuste arquivo
17/07/2020 teste1 4,35 nan 9032800000190015197.txt
16/07/2020 teste1 nan nan 9032800000190015197.txt
15/07/2020 teste1 3,12 nan 9032800000190015197.txt
14/07/2020 teste1 nan nan 9032800000190015197.txt
13/07/2020 teste1 nan 6367.55 9032800000190015197.txt
17/07/2020 teste2 3,7 -1462.825 9032800000190015197.txt
16/07/2020 teste2 nan nan 9032800000190015197.txt
15/07/2020 teste2 nan nan 9032800000190015197.txt
14/07/2020 teste2 nan -235.825 9032800000190015197.txt
13/07/2020 teste2 nan nan 9032800000190015197.txt
17/07/2020 teste3 5 nan 9032800000190015197.txt
16/07/2020 teste3 nan nan 9032800000190015197.txt
15/07/2020 teste3 6,7 nan 9032800000190015197.txt
14/07/2020 teste3 nan nan 9032800000190015197.txt
13/07/2020 teste3 nan nan 9032800000190015197.txt
e preciso obter o seguinte resultado
date ativo valor ajuste arquivo
17/07/2020 teste1 4,35 nan 9032800000190015197.txt
16/07/2020 teste1 4,35 nan 9032800000190015197.txt
15/07/2020 teste1 3,12 nan 9032800000190015197.txt
14/07/2020 teste1 3,12 nan 9032800000190015197.txt
13/07/2020 teste1 3,12 6367.55 9032800000190015197.txt
17/07/2020 teste2 3,7 -1462.825 9032800000190015197.txt
16/07/2020 teste2 3,7 nan 9032800000190015197.txt
15/07/2020 teste2 3,7 nan 9032800000190015197.txt
14/07/2020 teste2 3,7 -235.825 9032800000190015197.txt
13/07/2020 teste2 3,7 nan 9032800000190015197.txt
17/07/2020 teste3 5 nan 9032800000190015197.txt
16/07/2020 teste3 5 nan 9032800000190015197.txt
15/07/2020 teste3 6,7 nan 9032800000190015197.txt
14/07/2020 teste3 6,7 nan 9032800000190015197.txt
13/07/2020 teste3 6,7 nan 9032800000190015197.txt
Tenho valores ausentes no campo valor e preciso preencher com os valores anteriores da mesma tabela, considerando que o valor deve ser do mesmo ativo e data mais baixo. E o valor não é o mais alto nem o mais baixo, mas sim o do dia anterior que tem um valor diferente de zero.
Não consegui uma solução que atendesse a essas condições. Alguém tem ideia de como fazer? Usando pandas.DataFrame.backfill, não consegui.
Tentei em SQL, e não consegui, fiz esse código
select a.dt_data, a.co_ativo,
nullif(a.vr_valor, (select b.vr_valor from tabela b
where b.co_ativo = a.co_ativo and b.dt_data between '2020-07-01' and '2020-07-31' and b.vr_valor is not null order by b.dt_data desc limit 1))
from tabela a
where a.dt_data between '2020-07-01' and '2020-07-31'
order by a.dt_data desc
sem exito.
A:
É possível fazer essa substituição fazendo o agrupamento por ativo com a função groupby juntamente com o ffill, desta forma:
df['data'] = pd.to_datetime(df['data'], dayfirst=True)
df.sort_values(['ativo', 'data'], ascending = [True,False], inplace = True)
df['valor'] = df.groupby(['ativo'])['valor'].ffill()
#ou df = df.assign(valor = df.groupby(['ativo'])['valor'].ffill())
#resultado
data ativo valor
0 2020-07-17 teste1 4,35
1 2020-07-16 teste1 4,35
2 2020-07-15 teste1 3,12
3 2020-07-14 teste1 3,12
4 2020-07-13 teste1 3,12
5 2020-07-17 teste2 3,7
6 2020-07-16 teste2 3,7
7 2020-07-15 teste2 3,7
8 2020-07-14 teste2 3,7
9 2020-07-13 teste2 3,7
10 2020-07-17 teste3 5
11 2020-07-16 teste3 5
12 2020-07-15 teste3 6,7
13 2020-07-14 teste3 6,7
14 2020-07-13 teste3 6,7
Editado
Usando a nova amostragem de dados, o código ainda da a saída esperada:
s = io.StringIO(""" data ativo valor ajuste arquivo
17/07/2020 teste1 4,35 nan 9032800000190015197.txt
16/07/2020 teste1 nan nan 9032800000190015197.txt
15/07/2020 teste1 3,12 nan 9032800000190015197.txt
14/07/2020 teste1 nan nan 9032800000190015197.txt
13/07/2020 teste1 nan 6367.55 9032800000190015197.txt
17/07/2020 teste2 3,7 -1462.825 9032800000190015197.txt
16/07/2020 teste2 nan nan 9032800000190015197.txt
15/07/2020 teste2 nan nan 9032800000190015197.txt
14/07/2020 teste2 nan -235.825 9032800000190015197.txt
13/07/2020 teste2 nan nan 9032800000190015197.txt
17/07/2020 teste3 5 nan 9032800000190015197.txt
16/07/2020 teste3 nan nan 9032800000190015197.txt
15/07/2020 teste3 6,7 nan 9032800000190015197.txt
14/07/2020 teste3 nan nan 9032800000190015197.txt
13/07/2020 teste3 nan nan 9032800000190015197.txt
""")
df = pd.read_csv(s, sep="\s\s+")
df['data'] = pd.to_datetime(df['data'], dayfirst=True)
df.sort_values(['ativo', 'data'], ascending = [True,False], inplace = True)
df['valor'] = df.groupby(['ativo'])['valor'].ffill()
df.head(20)
data ativo valor ajuste arquivo
0 2020-07-17 teste1 4,35 NaN 9032800000190015197.txt
1 2020-07-16 teste1 4,35 NaN 9032800000190015197.txt
2 2020-07-15 teste1 3,12 NaN 9032800000190015197.txt
3 2020-07-14 teste1 3,12 NaN 9032800000190015197.txt
4 2020-07-13 teste1 3,12 6367.550 9032800000190015197.txt
5 2020-07-17 teste2 3,7 -1462.825 9032800000190015197.txt
6 2020-07-16 teste2 3,7 NaN 9032800000190015197.txt
7 2020-07-15 teste2 3,7 NaN 9032800000190015197.txt
8 2020-07-14 teste2 3,7 -235.825 9032800000190015197.txt
9 2020-07-13 teste2 3,7 NaN 9032800000190015197.txt
10 2020-07-17 teste3 5 NaN 9032800000190015197.txt
11 2020-07-16 teste3 5 NaN 9032800000190015197.txt
12 2020-07-15 teste3 6,7 NaN 9032800000190015197.txt
13 2020-07-14 teste3 6,7 NaN 9032800000190015197.txt
14 2020-07-13 teste3 6,7 NaN 9032800000190015197.txt
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dropbox стоит ли доверять и насколько?
Многие начали использовать его для хранения конфигов, паролей (естественно защищенных) и др..
Но меня интересует вопрос доверия и еще один вопрос: если удалю на своем компе папку Dropbox, что будет? Исчезнут ли те 2 гига и у них на сервере? То есть, если у меня рухнет винт и полетят все данные, то останутся ли они в облаке?
A:
Ввиду того, что в облаке хранится копия данных, они не пропадут. Первоначальная задача этого сервиса состояла в онлайн-бэкапе информации. То есть чтобы можно было восстановить её в случае порчи или утери.
Файлы хранятся на сервере даже если вы их удалите у себя. (Хотя есть возможность их удалить совсем)
Насчёт надёжности и защищённости от неправомерного доступа - точно не знаю. Но судя по описанию - подход там вполне серьёзный. (How secure is Dropbox?)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is TensorExpand so slow for vector operations?
I would like to expand the following tensor expression:
$Assumptions = {(a1 | b | c | d | e | f | g | h) ∈
Vectors[3,
Reals], (m | Ε1 | Ε2) ∈
Reals};
exp=-32 I m^2 a1.(-b + d)\[Cross](-b + f) (b + c).(b + e) +
16 I m Ε2 a1.(b + e) (b +
c).(-b + d)\[Cross](-b + f) +
16 I Ε1 Ε2 a1.(b + e) (b +
c).(-b + d)\[Cross](-b + f) -
16 I m Ε2 (b + c).a1\[Cross](-b + f) (-b + d).(b +
e) - 16 I Ε1 Ε2 (b +
c).a1\[Cross](-b + f) (-b + d).(b + e) +
32 I m^2 a1.(b + c)\[Cross](b + e) (-b + d).(-b + f) +
32 I m Ε1 a1.(b + c)\[Cross](b + e) (-b + d).(-b +
f) - 32 I m Ε2 (b + c).a1\[Cross](b + e) (-b +
d).(-b + f) -
32 I Ε1 Ε2 (b +
c).a1\[Cross](b + e) (-b + d).(-b + f) +
16 I m Ε2 (b + c).(-b + f) (-b +
d).a1\[Cross](b + e) +
16 I Ε1 Ε2 (b + c).(-b + f) (-b +
d).a1\[Cross](b + e) +
16 I Ε1 Ε2 (b + c).(b + e) (-b +
d).a1\[Cross](-b + f) +
16 I m Ε2 a1.(b + c) (-b +
d).(b + e)\[Cross](-b + f) +
16 I Ε1 Ε2 a1.(b + c) (-b +
d).(b + e)\[Cross](-b + f) +
16 I m Ε2 (b + c).a1\[Cross](-b + d) (b + e).(-b +
f) + 16 I Ε1 Ε2 (b +
c).a1\[Cross](-b + d) (b + e).(-b + f) +
16 I m Ε2 (b + c).(-b + d) (b +
e).a1\[Cross](-b + f) +
16 I Ε1 Ε2 (b + c).(-b + d) (b +
e).a1\[Cross](-b + f) -
16 I a1.(g + h) (b + c).(b + e) (-g + h).(-b + d)\[Cross](-b + f) -
16 I a1.(-g + h)\[Cross](-b + f) (-b + d).(b + e) (g + h).(b + c) -
32 I a1.(-g + h)\[Cross](b + e) (-b + d).(-b + f) (g + h).(b + c) +
32 I a1.(-g + h) (-b + d).(b + e)\[Cross](-b + f) (g + h).(b + c) +
16 I a1.(-g + h)\[Cross](-b + d) (b + e).(-b + f) (g + h).(b + c) +
16 I a1.(-b + d)\[Cross](-b + f) (-g + h).(b + e) (g + h).(b + c) -
16 I a1.(b + e) (-g + h).(-b + d)\[Cross](-b + f) (g + h).(b + c) +
16 I a1.(-g + h)\[Cross](-b + f) (b + c).(b + e) (g + h).(-b + d) +
16 I a1.(-g + h)\[Cross](-b + f) (b + c).(-b + d) (g + h).(b + e) -
16 I a1.(-g + h)\[Cross](-b + d) (b + c).(-b + f) (g + h).(b + e) +
32 I a1.(-g + h) (b + c).(-b + d)\[Cross](-b + f) (g + h).(b + e) +
32 I a1.(-g + h)\[Cross](b + c) (-b + d).(-b + f) (g + h).(b + e) -
16 I a1.(-b + d)\[Cross](-b + f) (-g + h).(b + c) (g + h).(b + e) +
16 I a1.(b + c) (-g + h).(-b + d)\[Cross](-b + f) (g + h).(b + e) -
16 I a1.(-g + h)\[Cross](-b + d) (b + c).(b + e) (g + h).(-b + f) -
16 I a1.(-b + d)\[Cross](-b + f) (b + c).(b +
e) (Ε1 Ε2 - (g + h).(-g + h));
TensorExpand[exp]
However, it is really slow in my laptop. It takes over 12 hours. I think even if I do it manually, it could be faster.
Does anyone know the reason?
A:
I also don't know the reason for the poor performance of TensorExpand, but as a possible workaround I may suggest using FeynCalc. The package has its roots in the field of the High Energy Physics, that is, it is not a toolbox for tensor algebra like xAct and company. Yet, the current development version already has a built-in support for 3-vectors, which was added there to accomodate for nonrelativistic field theories.
After having installed the development version according to the wiki via
Import["https://raw.githubusercontent.com/FeynCalc/feyncalc/master/install.m"]
InstallFeynCalc[InstallFeynCalcDevelopmentVersion -> True]
we can do the following
vecs = {a1, b, c, d, e, f, g, h};
expTmp = (exp /. Dot -> dot /. Cross -> cross /. {
dot[x_, cross[y_, z_]] /; SubsetQ[vecs, Variables[{x, y, z}]] :>
CLC[][x, y, z],
dot[x_, y_] /; SubsetQ[vecs, Variables[{x, y}]] :> CSP[x, y]
}) // ExpandScalarProduct[#, EpsEvaluate -> True] & // FCE
Here I converted your original expression into the FeynCalc notation using CLC (a shortcut for the Cartesian Levi-Civita tensor) and CSP (a shortcut for the Cartesian scalar product). Mathematically CLC[][a,b,c] corresponds to $\varepsilon^{ijk} a^i b^j c^k$, while CSP[a,b] stands for $a^i b^i$. The explicit Cartesian indices are suppressed for technical reasons, to avoid the expensive canonicalization. However, you can also define a standalone $\varepsilon^{ijk}$ via CLC[i,j,k] and 3-vector $a^i$ as CV[a,i]. ExpandScalarProduct is FeynCalc function for expanding scalar product, while FCE converts the result from the internal notation used by the package (FeynCalcInternal) to the more concise external notation (FeynCalcExternal).
Then we can convert the result back into your original notation via
res = expTmp /. {
CSP[x_, y_] /; SubsetQ[vecs, Variables[{x, y}]] :> dot[x, y],
CLC[][x_, y_, z_] /; SubsetQ[vecs, Variables[{x, y, z}]] :>
dot[x, cross[y, z]]
} /. cross -> Cross /. dot -> Dot
which yields
(16*I)*m*\[CapitalEpsilon]2*(-a1 . Cross[b, e] - a1 . Cross[b, f] - a1 . Cross[e, f])*
(-b . b - b . c + b . d + c . d) + (16*I)*\[CapitalEpsilon]1*\[CapitalEpsilon]2*
(-a1 . Cross[b, e] - a1 . Cross[b, f] - a1 . Cross[e, f])*
(-b . b - b . c + b . d + c . d) + (16*I)*\[CapitalEpsilon]1*\[CapitalEpsilon]2*
(-a1 . Cross[b, d] + a1 . Cross[b, f] - a1 . Cross[d, f])*
(b . b + b . c + b . e + c . e) -
(32*I)*m^2*(a1 . Cross[b, d] - a1 . Cross[b, f] + a1 . Cross[d, f])*
(b . b + b . c + b . e + c . e) +
(16*I)*m*\[CapitalEpsilon]2*(a1 . Cross[b, d] + a1 . Cross[b, e] - a1 . Cross[d, e])*
(-b . b - b . c + b . f + c . f) + (16*I)*\[CapitalEpsilon]1*\[CapitalEpsilon]2*
(a1 . Cross[b, d] + a1 . Cross[b, e] - a1 . Cross[d, e])*
(-b . b - b . c + b . f + c . f) + (16*I)*m*\[CapitalEpsilon]2*(a1 . b + a1 . e)*
(-b . Cross[c, d] + b . Cross[c, f] + b . Cross[d, f] + c . Cross[d, f]) +
(16*I)*\[CapitalEpsilon]1*\[CapitalEpsilon]2*(a1 . b + a1 . e)*(-b . Cross[c, d] + b . Cross[c, f] +
b . Cross[d, f] + c . Cross[d, f]) -
(16*I)*m*\[CapitalEpsilon]2*(-a1 . Cross[b, c] - a1 . Cross[b, f] - a1 . Cross[c, f])*
(-b . b + b . d - b . e + d . e) - (16*I)*\[CapitalEpsilon]1*\[CapitalEpsilon]2*
(-a1 . Cross[b, c] - a1 . Cross[b, f] - a1 . Cross[c, f])*
(-b . b + b . d - b . e + d . e) -
(16*I)*(-a1 . Cross[b, g] + a1 . Cross[b, h] + a1 . Cross[f, g] -
a1 . Cross[f, h])*(b . g + b . h + c . g + c . h)*
(-b . b + b . d - b . e + d . e) -
(32*I)*m*\[CapitalEpsilon]2*(a1 . Cross[b, c] - a1 . Cross[b, e] - a1 . Cross[c, e])*
(b . b - b . d - b . f + d . f) - (32*I)*\[CapitalEpsilon]1*\[CapitalEpsilon]2*
(a1 . Cross[b, c] - a1 . Cross[b, e] - a1 . Cross[c, e])*
(b . b - b . d - b . f + d . f) +
(32*I)*m^2*(-a1 . Cross[b, c] + a1 . Cross[b, e] + a1 . Cross[c, e])*
(b . b - b . d - b . f + d . f) +
(32*I)*m*\[CapitalEpsilon]1*(-a1 . Cross[b, c] + a1 . Cross[b, e] + a1 . Cross[c, e])*
(b . b - b . d - b . f + d . f) -
(32*I)*(a1 . Cross[b, g] - a1 . Cross[b, h] + a1 . Cross[e, g] -
a1 . Cross[e, h])*(b . g + b . h + c . g + c . h)*
(b . b - b . d - b . f + d . f) +
(16*I)*(-a1 . Cross[b, g] + a1 . Cross[b, h] + a1 . Cross[f, g] -
a1 . Cross[f, h])*(b . b + b . c + b . e + c . e)*
(-b . g - b . h + d . g + d . h) + (16*I)*m*\[CapitalEpsilon]2*(a1 . b + a1 . c)*
(-b . Cross[d, e] - b . Cross[d, f] - b . Cross[e, f] + d . Cross[e, f]) +
(16*I)*\[CapitalEpsilon]1*\[CapitalEpsilon]2*(a1 . b + a1 . c)*(-b . Cross[d, e] - b . Cross[d, f] -
b . Cross[e, f] + d . Cross[e, f]) + (32*I)*(-a1 . g + a1 . h)*
(b . g + b . h + c . g + c . h)*(-b . Cross[d, e] - b . Cross[d, f] -
b . Cross[e, f] + d . Cross[e, f]) - (16*I)*(a1 . g + a1 . h)*
(b . b + b . c + b . e + c . e)*(-b . Cross[d, g] + b . Cross[d, h] +
b . Cross[f, g] - b . Cross[f, h] - d . Cross[f, g] + d . Cross[f, h]) -
(16*I)*(a1 . b + a1 . e)*(b . g + b . h + c . g + c . h)*
(-b . Cross[d, g] + b . Cross[d, h] + b . Cross[f, g] - b . Cross[f, h] -
d . Cross[f, g] + d . Cross[f, h]) +
(16*I)*m*\[CapitalEpsilon]2*(-a1 . Cross[b, c] - a1 . Cross[b, d] - a1 . Cross[c, d])*
(-b . b - b . e + b . f + e . f) + (16*I)*\[CapitalEpsilon]1*\[CapitalEpsilon]2*
(-a1 . Cross[b, c] - a1 . Cross[b, d] - a1 . Cross[c, d])*
(-b . b - b . e + b . f + e . f) +
(16*I)*(-a1 . Cross[b, g] + a1 . Cross[b, h] + a1 . Cross[d, g] -
a1 . Cross[d, h])*(b . g + b . h + c . g + c . h)*
(-b . b - b . e + b . f + e . f) +
(16*I)*(a1 . Cross[b, d] - a1 . Cross[b, f] + a1 . Cross[d, f])*
(b . g + b . h + c . g + c . h)*(-b . g + b . h - e . g + e . h) +
(16*I)*(-a1 . Cross[b, g] + a1 . Cross[b, h] + a1 . Cross[f, g] -
a1 . Cross[f, h])*(-b . b - b . c + b . d + c . d)*
(b . g + b . h + e . g + e . h) -
(16*I)*(-a1 . Cross[b, g] + a1 . Cross[b, h] + a1 . Cross[d, g] -
a1 . Cross[d, h])*(-b . b - b . c + b . f + c . f)*
(b . g + b . h + e . g + e . h) -
(16*I)*(a1 . Cross[b, d] - a1 . Cross[b, f] + a1 . Cross[d, f])*
(-b . g + b . h - c . g + c . h)*(b . g + b . h + e . g + e . h) +
(32*I)*(-a1 . g + a1 . h)*(-b . Cross[c, d] + b . Cross[c, f] +
b . Cross[d, f] + c . Cross[d, f])*(b . g + b . h + e . g + e . h) +
(32*I)*(a1 . Cross[b, g] - a1 . Cross[b, h] + a1 . Cross[c, g] -
a1 . Cross[c, h])*(b . b - b . d - b . f + d . f)*
(b . g + b . h + e . g + e . h) + (16*I)*(a1 . b + a1 . c)*
(-b . Cross[d, g] + b . Cross[d, h] + b . Cross[f, g] - b . Cross[f, h] -
d . Cross[f, g] + d . Cross[f, h])*(b . g + b . h + e . g + e . h) -
(16*I)*(-a1 . Cross[b, g] + a1 . Cross[b, h] + a1 . Cross[d, g] -
a1 . Cross[d, h])*(b . b + b . c + b . e + c . e)*
(-b . g - b . h + f . g + f . h) -
(16*I)*(a1 . Cross[b, d] - a1 . Cross[b, f] + a1 . Cross[d, f])*
(b . b + b . c + b . e + c . e)*(\[CapitalEpsilon]1*\[CapitalEpsilon]2 + g . g - h . h)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Почему переполнение стека в дочернем потоке убивает весь процесс?
Отвечая на этот вопрос был удивлен, что переполнение стека в дочернем потоке убивает процесс целиком.
Собственно, вопрос:
А почему так происходит? Ведь каждый поток имеет собственный стек, даже, на сколько я помню, Рихтер писал об этом.
Даже StackTrace().FrameCount показывает различное кол-во фреймов в основном потоке и дочернем.
В С++- это обрабатываемое исключение, если верить комментариям из предыдущего вопроса, а в .NET нет, так как возможно, как я понимаю, что СLR, которой нужно что-то сделать, может повредится из-за не хватки стека.
CLR, по идее, одна на все приложение и она точно не крутится в дочернем потоке.
Получается, что запуская чужой код, к исходникам которого мы не имеем доступа, хоть в отдельном потоке, хоть в отдельном домене, то мы все равно падаем и в .NET никак нельзя предотвратить это при таком типе исключения?
UPD
Есть какие-то "Области с ограничением выполнения" CER, где можно указать, что метод может поверить процесс. Это никак не оказывает влияния на CLR, что бы она подготовилась и не умерла?
A:
По-моему тут накладываются друг на друга две особенности работы CLR.
Необработанные исключения в дочерних потоках убивают процесс
Не только переполнение стека, а вообще любое необработанное исключение в дочернем потоке убивает весь процесс:
static void Main()
{
var thread = new Thread(Recursive);
thread.Start();
while (true)
{
Console.WriteLine("I will live forever!");
Thread.Sleep(1000);
}
}
static void Recursive()
{
throw new Exception("RIP Unnamed Process (2018-2018");
}
Об это говорится в MSDN:
Starting with the .NET Framework version 2.0, the common language runtime allows most unhandled exceptions in threads to proceed naturally. In most cases this means that the unhandled exception causes the application to terminate.
[Спорную] мотивацию такого поведения дает Эрик Липперт:
We cannot easily tell the difference between bugs which are missing handlers for vexing/exogenous exceptions, and which are bugs that have caused a program crash because something is broken in the implementation. The safest thing to do is to assume that every unhandled exception is either a fatal exception or an unhandled boneheaded exception. In both cases, the right thing to do is to take down the process immediately.
This philosophy underlies the implementation of unhandled exceptions in the CLR. Way back in the CLR v1.0 days the policy was that an unhandled exception on the "main" thread took down the process aggressively, but an unhandled exception on a "worker" thread simply killed the thread and left the main thread running. (And an exception on the finalizer thread was ignored and finalizers kept running.) This turned out to be a poor choice; the scenario it leads to is that a server assigns a buggy subsystem to do some work on a bunch of worker threads; all the worker threads go down silently, and the user is stuck with a server that is sitting there waiting patiently for results that will never come because all the threads that produce results have disappeared. It is very difficult for the user to diagnose such a problem; a server that is working furiously on a hard problem and a server that is doing nothing because all its workers are dead look pretty much the same from the outside. The policy was therefore changed in CLR v2.0 such that an unhandled exception on a worker thread also takes down the process by default. You want to be noisy about your failures, not silent.
Это означает что исключения в потоках нужно обрабатывать намертво, например так:
static void SafeRecursive()
{
try
{
Recursive();
}
catch (Exception e)
{
//должная обработка, запись в логи и уведомление администраторам
//ха-ха, так никто не делает, просто глотаем и забываем о потоке
}
}
StackOverflowException нельзя поймать
Но особенность StackOverflowException в том, что его нельзя поймать, ни в дочернем потоке, ни где-либо еще:
static void Main()
{
try
{
Recursive();
}
catch (Exception)
{
//не получится
Console.WriteLine("Catch!");
}
}
О чем сказано в документации исключения:
Starting with the .NET Framework 2.0, you can’t catch a StackOverflowException object with a try/catch block, and the corresponding process is terminated by default. Consequently, you should write your code to detect and prevent a stack overflow.
Документация ясно дает понять, что нигде в процессе переполнение стека возникать не должно, вообще нигде.
Есть вырожденные случаи, в которых StackOverflowException все же можно обработать:
если Вы сами загружаете CLR, то может получится ее восстановить;
если StackOverflowException выбрасывается кодом.
В .Net 1.0 переполнение стека можно было отловить, с версии 2.0 разработчики заняли жесткую позицию: «Переполнение стека — проблема программиста и его кода, а не CLR». Я не смог найти прямых указаний на то, по какой причине потребовалось внести изменения. Предполагаю, что восстановление после SOE было небеспроблемно и разработчики решили не тратить на эту задачу ресурсы.
Вообще, обе эти особенности CLR вполне укладываются в пуританскую философскую позицию «мертвые программы не врут», которую также освещает Эрик Липперт:
I am of the philosophical school that says that sudden, catastrophic failure of a software device is, of course, unfortunate, but in many cases it is preferable that the software call attention to the problem so that it can be fixed, rather than trying to muddle along in a bad state, possibly introducing a security hole or corrupting user data along the way.
Обновление: Constrained Execution Regions
Вопрос в комментариях:
А "Области с ограничением выполнения" CER - это что такое? Вот там можно повесить атрибут, что есть возможность того, что будет поврежден процесс. Это на что-то влияет?
Влияет. CER позволяет защититься от части ошибок, которые могли бы возникнуть при исполнении кода (ошибки загрузки классов, нехватки памяти) и корректно освободить ресурсы.
Тем не менее, переполнение стека с помощью CER обработать не получится. Об этом пишет Рихтер (CLR via C#, Constrained Execution Regions):
Note Even if all the methods are eagerly prepared, a method call could still result in a StackOverflowException. When the CLR is not being hosted, a StackOverflowException causes the process to terminate immediately by the CLR internally calling Environment.FailFast. When hosted, the PreparedConstrainedRegions method checks the stack to see if there is approximately 48 KB of stack space remaining. If there is limited stack space,
the StackOverflowException occurs before entering the try block.
Внимание: Даже если все методы были явно подготовлены, вызов метода все еще может привести к StackOverflowException. Если CLR не загружена извне, то StackOverflowException завершает процесс немедленно, вызывая Environment.FailFast. Если CLR загружена извне, то метод PreparedConstrainedRegions проверяет, осталось ли в стеке примерно 48КБ свободного пространства. Если пространство стека ограничено, то StackOverflowException вызывается перед входом в блок try.
Т.о. отловить переполнение стека с помощью одного CER не получится. StackOverflowException также отдельно упоминается в документации:
CERs that are marked using the PrepareConstrainedRegions method do not work perfectly when a StackOverflowException is generated from the try block. For more information, see the ExecuteCodeWithGuaranteedCleanup method.
Мне никак не удалось заставить метод ExecuteCodeWithGuaranteedCleanup обработать переполнение стека. Судя по обсуждению в вопросе по данному методу он также сработает только если Вы сами захостите CLR.
Ссылки
Catching unhandled exception on separate threads — вопрос об обработке исключений в отдельном потоке
catch exception that is thrown in different thread — еще один.
How do I prevent and/or handle a StackOverflowException? — вопрос о предупреждении SOE, рассматриваются разного рода костыли.
When can you catch a StackOverflowException? — статья о вырожденных случаях, которая только подчеркивает, что SOE поймать нельзя.
Asynchrony in C# 5, Part Eight: More Exceptions — статья Эрика Липперта об исключениях в асинхронных функциях, в которой, между делом, рассказывается об истории обработки исключений в дочерних потоках в .Net 1.0 и, в целом, об отношении авторов C# к обработке исключений.
A:
В С++- это обрабатываемое исключение, если верить комментариям из предыдущего вопроса
На самом деле все немного не так. Стандартными средствами С++, разумеется, нельзя обработать переполнение стека. Однако, в Windows его можно обработать с помощью механизма SEH. И, что бы ни говорил Эрик Липперт, восстановление после переполнения стека - вполне поддерживаемый сценарий, иначе зачем бы существовали функции _resetstkoflw и SetThreadStackGuarantee?
а в .NET нет, так как возможно, как я понимаю, что СLR, которой нужно что-то сделать, может повредится из-за не хватки стека
В .NET StackOverflowException не обрабатывается не потому, что это технически невозможно, а потому, что так решили разработчики. В Windows переполнение стека порождает исключение SEH с кодом STATUS_STACK_OVERFLOW (0xC00000FD). CLR перехватывает SEH-исключения и, если видит этот код, принудительно убивает процесс (будучи загруженной с параметрами по умолчанию). При этом куда более опасное Access Violation .NET почему-то разрешает обрабатывать.
Получается, что запуская чужой код, к исходникам которого мы не имеем доступа, хоть в отдельном потоке, хоть в отдельном домене, то мы все равно падаем и в .NET никак нельзя предотвратить это при таком типе исключения?
Только средствами .NET нельзя. Однако в неуправляемом коде нужно написать, по сути, очень немного.
Один из способов обойти это поведение, это создать специальную неуправляемую DLL, единственной целью которой будет обработать SEH-исключение и поменять его код на тот, который CLR "не напугает" (SEH-исключения с неизвестным кодом CLR преобразует в SEHException, которое можно обработать). В приложении на C# загрузить DLL, установить векторный обработчик исключений и увеличить размер зарезервированной области стека с помощью функции SetThreadStackGuarantee.
Конечно, это не обеспечит полное восстановление стека, т.е., чтобы можно было далее в том же потоке снова словить переполнение стека и обработать его. Но если просто позволить потоку завершиться и забыть про него, это не имеет значения: вновь созданные потоки уже будут иметь корректный стек.
Например, создадим DLL на С++ с таким кодом:
#include <malloc.h>
#include <windows.h>
#ifdef __cplusplus
extern "C"{
#endif
__declspec(dllexport) LONG WINAPI fnCrashHandler(LPEXCEPTION_POINTERS pExceptionInfo)
{
if(pExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_STACK_OVERFLOW){
pExceptionInfo->ExceptionRecord->ExceptionCode = 0x1234;
}
return EXCEPTION_CONTINUE_SEARCH;
}
#ifdef __cplusplus
}
#endif
Назовем ее, допустим, CrashHandler.dll, и поместим в каталог с программой. Тогда в C# можно обработать переполнение стека таким образом:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
namespace ConsoleTest
{
class Program
{
[DllImport("kernel32.dll")]
public static extern IntPtr AddVectoredExceptionHandler(
uint FirstHandler,
IntPtr VectoredHandler
);
[DllImport("kernel32.dll")]
public static extern int SetThreadStackGuarantee( ref uint StackSizeInBytes);
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
static void Recursive()
{
Recursive();
}
static void Test()
{
//увеличим размер зарезервированной области стека (30 KB должно быть достаточно)
uint size = 30000;
SetThreadStackGuarantee(ref size);
try
{
Recursive();
}
catch (SEHException)
{
Console.WriteLine("SEHException. Code: 0x" + Marshal.GetExceptionCode().ToString("X"));
}
}
static void Main(string[] args)
{
//добавим обработчик исключений
IntPtr h = LoadLibrary("CrashHandler.dll");
IntPtr fnAddress = GetProcAddress(h, "_fnCrashHandler@4"); //декорированное имя функции по правилам stdcall
AddVectoredExceptionHandler(1, fnAddress);
//запустим поток
Thread thread = new Thread(Test);
thread.Start();
thread.Join();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
Примечание. Целевая архитектура неуправляемой DLL и приложения должны совпадать. Для AnyCPU-приложений понадобится иметь несколько неуправляемых DLL под каждую архитектуру и загружать нужную в зависимости от текущей архитектуры приложения.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Почему «то́рты», но при этом «мосты́»?
Чтобы понять, как ставить ударение в слове, я обычно подбираю аналогичное — по количеству букв, слогов и по грамматическим категориям. Но почему-то это не всегда помогает. Например, мост и торт — мы говорим то́рты, но мосты́.
Прочитала, что в русском языке вообще не существует правил постановки ударения и все слова нужно просто запоминать. Правда ли это? И если это так, то почему такие жесткие нормы в постановке ударений?
A:
В русском языке существуют правила постановки ударения, но они не так однозначны, как орфографические правила. Для различных частей речи определены акцентные группы - в частности, существительные имеют 6 акцентных групп.
Слова "мост и торт" относятся к разным акцентным группам. Мост - это в основном группа с постоянным ударением на окончании: мостА – мостОв. Торт относится к группе с постоянным ударением на основе: тОрта - тОртов.
А почему так? Это односложные существительные, и фонетически здесь возможны три акцентные группы:
(1)Ударение только на основе: ( знАка - знАков): торт, акт, бланк, вальс, знак, класс, литр, метр, парк, рак, сквер, текст, шанс и др.
(2)Ударение только на окончании: (дворА – дворОв): мост, ёж, жук, зонт, кит, меч, нож, ствол, труд и др.
(3) Переход ударения с основы на окончание (рЯда – рядОв): дар, долг, мир, нос, ряд, сад, суп, сыр, шар и др.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL-Oracle Update table using recursivity
Lets assume we have a table like this one:
+--------+------------+---------------+----------------+
| Name | Position | Initial Date | Final Date |
+--------+------------+---------------+----------------+
| XXX | 1 | 2016/06/07 | 2016/06/08 |
| XXX | 2 | 2016/06/08 | 2016/06/09 |
| XXX | 3 | 2016/06/09 | 2016/06/10 |
| XXX | 4 | 2016/06/13 | 2016/06/14 |
| XXX | 6 | 2016/06/14 | 2016/06/15 |
| YYY | 1 | 2016/06/02 | 2016/06/03 |
+--------+------------+---------------+----------------+
I want to update it adding a new field which indicates the first position of a group.
Forming part of a group means that follows these rules:
Share the same name
Position numbers must be correlatives (Ex: Position 4 and 6 need a number 5 to create a group).
The final date of first row must coincide with the initial date of the second one, and so on.
Having all of this in consideration, this should be the outcome:
+--------+------------+---------------+----------------+------------+
| Name | Position | Initial Date | Final Date | New field |
+--------+------------+---------------+----------------+------------+
| XXX | 1 | 2016/06/07 | 2016/06/08 | 1 |
| XXX | 2 | 2016/06/08 | 2016/06/09 | 1 |
| XXX | 3 | 2016/06/09 | 2016/06/10 | 1 |
| XXX | 4 | 2016/06/13 | 2016/06/14 | 4 |
| XXX | 6 | 2016/06/14 | 2016/06/15 | 6 |
| YYY | 1 | 2016/06/02 | 2016/06/03 | 1 |
+--------+------------+---------------+----------------+------------+
I can make it work only on groups of 2 members, but I do not know how to approach it in a more than 2 members situation.
This is an example code I used, which obviously does not work for big groups.
update table1 f1
set f1.new_field = NVL((select f2.position
from table1 f2
where f1.name = f2.name and
f2.position = f1.position+1 and
f1.final_date = f2.initial_date),f1.position);
Should I use recursive queries to solve this? I don't know how to implement it in SQL in this situation.
Any help is well appreciated!
A:
You can do this using a series of analytic functions, like so:
with sample_data as (select 'XXX' name, 1 position, to_date('07/06/2016', 'dd/mm/yyyy') initial_date, to_date('08/06/2016', 'dd/mm/yyyy') final_date from dual union all
select 'XXX' name, 2 position, to_date('08/06/2016', 'dd/mm/yyyy') initial_date, to_date('09/06/2016', 'dd/mm/yyyy') final_date from dual union all
select 'XXX' name, 3 position, to_date('09/06/2016', 'dd/mm/yyyy') initial_date, to_date('10/06/2016', 'dd/mm/yyyy') final_date from dual union all
select 'XXX' name, 4 position, to_date('13/06/2016', 'dd/mm/yyyy') initial_date, to_date('14/06/2016', 'dd/mm/yyyy') final_date from dual union all
select 'XXX' name, 6 position, to_date('14/06/2016', 'dd/mm/yyyy') initial_date, to_date('15/06/2016', 'dd/mm/yyyy') final_date from dual union all
select 'YYY' name, 1 position, to_date('02/06/2016', 'dd/mm/yyyy') initial_date, to_date('03/06/2016', 'dd/mm/yyyy') final_date from dual)
-- end of mimicking a table called "sample_data" containing your data
select name,
position,
initial_date,
final_date,
min(position) over (partition by name, grp_sum) new_field
from (select name,
position,
initial_date,
final_date,
sum(change_grp_required) over (partition by name order by position) grp_sum
from (select name,
position,
initial_date,
final_date,
case when position - lag(position, 1, position) over (partition by name order by position) != 1
or initial_date != lag(final_date, 1, initial_date - 1) over (partition by name order by position) then 1
else 0
end change_grp_required
from sample_data));
NAME POSITION INITIAL_DATE FINAL_DATE NEW_FIELD
---- ---------- ------------ ---------- ----------
XXX 1 2016/06/07 2016/06/08 1
XXX 2 2016/06/08 2016/06/09 1
XXX 3 2016/06/09 2016/06/10 1
XXX 4 2016/06/13 2016/06/14 4
XXX 6 2016/06/14 2016/06/15 6
YYY 1 2016/06/02 2016/06/03 1
The innermost subquery determines whether the position and dates of the current and previous row are correlated. If they aren't, then it puts 1, otherwise it puts 0.
The next subquery then calculates a running sum across these numbers - this has the effect of creating the same number for correlated rows (eg. 1 for positions 1 to 3, 2 for position 4 and 3 for position 6) which we can then use to group against.
The outer query then simply finds the minimum position number per name and the newly created grouping column.
You could then use this query in your update statement to do the actual update (obviously, you wouldn't need the initial sample_data subquery, as you'd just use your table_name in the rest of the query directly).
A:
You can use the LAG() and LAST_VALUE() analytic function to get the initial position for each group and then use MERGE (instead of UPDATE) to update the table.
Oracle Setup:
CREATE TABLE table_name ( Name, Position, Initial_Date, Final_Date ) AS
SELECT 'XXX', 1, DATE '2016-06-07', DATE '2016-06-08' FROM DUAL UNION ALL
SELECT 'XXX', 2, DATE '2016-06-08', DATE '2016-06-09' FROM DUAL UNION ALL
SELECT 'XXX', 3, DATE '2016-06-09', DATE '2016-06-10' FROM DUAL UNION ALL
SELECT 'XXX', 4, DATE '2016-06-13', DATE '2016-06-14' FROM DUAL UNION ALL
SELECT 'XXX', 6, DATE '2016-06-14', DATE '2016-06-15' FROM DUAL UNION ALL
SELECT 'YYY', 1, DATE '2016-06-02', DATE '2016-06-03' FROM DUAL;
ALTER TABLE table_name ADD new_field INT;
Update Query:
MERGE INTO table_name d
USING (
SELECT LAST_VALUE( start_of_group ) IGNORE NULLS
OVER ( PARTITION BY Name ORDER BY position )
AS new_field
FROM (
SELECT name,
position,
CASE WHEN position - 1 = LAG( position )
OVER ( PARTITION BY NAME
ORDER BY position )
AND initial_date = LAG( final_date )
OVER ( PARTITION BY NAME
ORDER BY position )
THEN NULL
ELSE position
END AS start_of_group
FROM table_name t
)
) s
ON ( d.ROWID = s.ROWID )
WHEN MATCHED THEN
UPDATE SET new_field = s.new_field;
Output:
SELECT * FROM table_name;
NAME POSITION INITIAL_DATE FINAL_DATE NEW_FIELD
---- ---------- ------------------- ------------------- ----------
XXX 1 2016-06-07 00:00:00 2016-06-08 00:00:00 1
XXX 2 2016-06-08 00:00:00 2016-06-09 00:00:00 1
XXX 3 2016-06-09 00:00:00 2016-06-10 00:00:00 1
XXX 4 2016-06-13 00:00:00 2016-06-14 00:00:00 4
XXX 6 2016-06-14 00:00:00 2016-06-15 00:00:00 6
YYY 1 2016-06-02 00:00:00 2016-06-03 00:00:00 1
|
{
"pile_set_name": "StackExchange"
}
|
Q:
reduced image quality / sharpness when texture has opacity / alpha / transparency
The output of Graphics3D looks blunt (polygon borders, arrow) when a polygon primitive is present in the scene with texture that has opacity channel. Also it seems that different kind of texture filtering is applied. I'm on Win10 and tested the code on 2 different PCs with GPUs from different vendors. I'm also interested in boosting the overall image quality like aliasing and texture filtering. Thank you!
SeedRandom[0]
imgData = RandomReal[1, {4, 5, 3}];
Image[imgData]
Graphics3D[{{Texture[Image[imgData]],
Polygon[{{-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}},
VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0,
1}}]}, {GraphicsComplex[{{1, 0, 2}, {0, 1, 2}, {-1, 0,
2}, {0, -1, 2}},
Polygon[{{1, 2, 3}, {3, 4, 1}}]]}, {Arrow[{{0, 0, 0}, {1, 1,
1}}]}}, Boxed -> False, Lighting -> "Neutral",
ViewPoint -> {1/2, -2, 1}]
Graphics3D[{{Texture[Image[Map[Append[#, 0.5] &, imgData, {2}]]],
Polygon[{{-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}},
VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0,
1}}]}, {GraphicsComplex[{{1, 0, 2}, {0, 1, 2}, {-1, 0,
2}, {0, -1, 2}},
Polygon[{{1, 2, 3}, {3, 4, 1}}]]}, {Arrow[{{0, 0, 0}, {1, 1,
1}}]}}, Boxed -> False, Lighting -> "Neutral",
ViewPoint -> {1/2, -2, 1}]
A:
Consider upgrading to version 12.1 which uses Direct3D 11 for 3D graphics rendering on Windows (version 12.0 used Direct3D 9):
Windows 3D graphics rendering updated from Direct3D 9 to Direct3D 11
Here your scene is rendered in both versions on the same machine with Windows 10 (clickable!):
As one can see, there is significant difference for the scene with opacity.
For further improving try changing RenderingOptions. For example (output is rendered by version 12.1):
g = Graphics3D[{{Texture[Image[Map[Append[#, 0.09] &, imgData, {2}]]],
Polygon[{{-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}},
VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0,
1}}]}, {GraphicsComplex[{{1, 0, 2}, {0, 1, 2}, {-1, 0,
2}, {0, -1, 2}},
Polygon[{{1, 2, 3}, {3, 4, 1}}]]}, {Arrow[{{0, 0, 0}, {1, 1,
1}}]}}, Boxed -> False, Lighting -> "Neutral",
ViewPoint -> {1/2, -2, 1}, ImageSize -> Medium];
{g, Style[#, RenderingOptions -> {"3DRenderingMethod" -> "BSPTree"}] &@g}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP Убирать параметры из URL, если содержащие цифры
Ссылки на товары на сайте имеют вид такой
test.ru/catalog/holodilniki/3574/
Если мы добавляем к последнему уровню (где цифры - id товара) какой-то параметр (при том это может быть что угодно и начинаться как угодно:
test.ru/catalog/holodilniki/3574_blabla/
test.ru/catalog/holodilniki/3574&chtoto/
test.ru/catalog/holodilniki/3574?lalala/
То все равно остаемся на странице товара. Если задача поставить на страницы товаров атрибут rel="canonical", а для этого надо знать непосредственно верную ссылку - без параметра.
Вопрос: можно ли как-то "очистить" определенную часть строки, в моем случае /3574/ от всех параметров - от всего, что не цифры?
A:
Если я правильно понял Вашу задачу, то можно использовать это выражение:
'/\d+\K\pP[^\/]+\/$/m'
https://regex101.com/r/rlCIzz/2
На примере возьмем строки, и преобразуем их. На выходе получим нужный результат.
$string = '
test.ru/catalog/holodilniki/3574_blabl232a/
test.ru/catalog/holodilniki/3574&chto2323to/
test.ru/catalog/holodilniki/3574?lalala/
';
echo preg_replace('/\d+\K\pP[^\/]+\/$/m', '/', $string);
// test.ru/catalog/holodilniki/3574/
https://3v4l.org/kFha9
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Seasonal weather data
I have some twenty years of weather data with daily average temperature. I would like to make a histogram with aggregated monthly average for the whole period. I tried to do something like this https://www.wolfram.com/language/11/time-series-processing/trends-and-seasonalities.html?product=language
But it didn’t work since my weights in WeightedData can be positive and negative. My data looks like this:
data = {{"1965-12-01",0.5},{"1965-12-02",-4.1},{"1965-12-03",-0.8},{"1965-12-04",2.},{"1965-12-05",1.3},{"1965-12-06",0.4},{"1965-12-07",-6.6},{"1965-12-08",-3.9},{"1965-12-09",0.3},{"1965-12-10",1.2},{"1965-12-11",-3.},{"1965-12-12",-9.4},{"1965-12-13",-13.},{"1965-12-14",-10.5},{"1965-12-15",-4.6},{"1965-12-16",-6.5},{"1965-12-17",-8.},{"1965-12-18",-2.2},{"1965-12-19",1.7},{"1965-12-20",2.1},{"1965-12-21",-4.6},{"1965-12-22",-2.8},{"1965-12-23",-0.2},{"1965-12-24",-0.1},{"1965-12-25",0.9},{"1965-12-26",0.5},{"1965-12-27",-0.8},{"1965-12-28",-6.5},{"1965-12-29",-5.6},{"1965-12-30",-5.2},{"1965-12-31",-6.9},{"1966-01-01",-8.},{"1966-01-02",-4.2},{"1966-01-03",-7.3},{"1966-01-04",-12.9},{"1966-01-05",-12.},{"1966-01-06",-1.8},{"1966-01-07",-0.1},{"1966-01-08",-3.4},{"1966-01-09",-3.8},{"1966-01-10",-3.},{"1966-01-11",-3.8},{"1966-01-12",-5.3},{"1966-01-13",-5.9},{"1966-01-14",-7.9},{"1966-01-15",-6.2},{"1966-01-16",-8.},{"1966-01-17",-7.5},{"1966-01-18",-4.4},{"1966-01-19",-13.3},{"1966-01-20",-8.2},{"1966-01-21",-6.1},{"1966-01-22",-3.9},{"1966-01-23",-5.6},{"1966-01-24",-8.3},{"1966-01-25",-4.2},{"1966-01-26",-5.2},{"1966-01-27",-3.5},{"1966-01-28",-6.7},{"1966-01-29",-4.1},{"1966-01-30",1.3},{"1966-01-31",2.2},{"1966-02-01",-5.4},{"1966-02-02",-13.9},{"1966-02-03",-11.8},{"1966-02-04",-13.7},{"1966-02-05",-7.4},{"1966-02-06",-9.5},{"1966-02-07",-15.3},{"1966-02-08",-24.4},{"1966-02-09",-23.},{"1966-02-10",-12.8},{"1966-02-11",-19.2},{"1966-02-12",-20.2},{"1966-02-13",-18.1},{"1966-02-14",-11.1},{"1966-02-15",-13.},{"1966-02-16",-14.6},{"1966-02-17",-16.5},{"1966-02-18",-15.5},{"1966-02-19",-17.5},{"1966-02-20",-7.4},{"1966-02-21",0.6},{"1966-02-22",-0.7},{"1966-02-23",-1.1},{"1966-02-24",1.5},{"1966-02-25",0.2},{"1966-02-26",0.4},{"1966-02-27",1.4},{"1966-02-28",1.6},{"1966-03-01",-0.4},{"1966-03-02",-0.5},{"1966-03-03",2.9},{"1966-03-04",1.9},{"1966-03-05",1.1},{"1966-03-06",1.3},{"1966-03-07",2.1},{"1966-03-08",2.8},{"1966-03-09",0.7},{"1966-03-10",-0.2},{"1966-03-11",-0.5},{"1966-03-12",-6.4},{"1966-03-13",-8.2},{"1966-03-14",-7.8},{"1966-03-15",-5.6},{"1966-03-16",0.7},{"1966-03-17",4.},{"1966-03-18",0.4},{"1966-03-19",-1.8},{"1966-03-20",2.6},{"1966-03-21",3.1},{"1966-03-22",1.8},{"1966-03-23",2.},{"1966-03-24",0.3},{"1966-03-25",-3.1},{"1966-03-26",-4.9},{"1966-03-27",-1.5},{"1966-03-28",0.6},{"1966-03-29",0.6},{"1966-03-30",-0.2},{"1966-03-31",0.4},{"1966-04-01",0.9},{"1966-04-02",0.8},{"1966-04-03",4.},{"1966-04-04",2.2},{"1966-04-05",0.8},{"1966-04-06",1.8},{"1966-04-07",2.3},{"1966-04-08",2.2},{"1966-04-09",1.3},{"1966-04-10",-1.3},{"1966-04-11",-3.6},{"1966-04-12",-4.5},{"1966-04-13",-4.6},{"1966-04-14",-4.4},{"1966-04-15",-3.6},{"1966-04-16",-4.5},{"1966-04-17",-3.5},{"1966-04-18",-2.5},{"1966-04-19",0.},{"1966-04-20",0.4},{"1966-04-21",3.3},{"1966-04-22",1.7},{"1966-04-23",1.4},{"1966-04-24",3.8},{"1966-04-25",4.6},{"1966-04-26",4.9},{"1966-04-27",3.1},{"1966-04-28",6.7},{"1966-04-29",7.9},{"1966-04-30",8.5},{"1966-05-01",8.7},{"1966-05-02",8.9},{"1966-05-03",9.5},{"1966-05-04",6.7},{"1966-05-05",4.5},{"1966-05-06",1.7},{"1966-05-07",4.1},{"1966-05-08",6.7},{"1966-05-09",5.9},{"1966-05-10",8.},{"1966-05-11",8.},{"1966-05-12",6.1},{"1966-05-13",6.8},{"1966-05-14",9.4},{"1966-05-15",10.7},{"1966-05-16",9.5},{"1966-05-17",10.7},{"1966-05-18",13.3},{"1966-05-19",10.5},{"1966-05-20",8.3},{"1966-05-21",8.3},{"1966-05-22",8.8},{"1966-05-23",9.},{"1966-05-24",8.9},{"1966-05-25",8.9},{"1966-05-26",8.},{"1966-05-27",9.4},{"1966-05-28",10.7},{"1966-05-29",10.},{"1966-05-30",11.9},{"1966-05-31",12.},{"1966-06-01",10.9},{"1966-06-02",13.},{"1966-06-03",9.5},{"1966-06-04",10.2},{"1966-06-05",12.3},{"1966-06-06",12.8},{"1966-06-07",10.8},{"1966-06-08",11.5},{"1966-06-09",14.3},{"1966-06-10",15.6},{"1966-06-11",17.4},{"1966-06-12",18.3},{"1966-06-13",18.9},{"1966-06-14",18.7},{"1966-06-15",19.1},{"1966-06-16",19.7},{"1966-06-17",21.4},{"1966-06-18",21.5},{"1966-06-19",21.5},{"1966-06-20",19.1},{"1966-06-21",16.7},{"1966-06-22",15.7},{"1966-06-23",17.1},{"1966-06-24",17.2},{"1966-06-25",15.1},{"1966-06-26",15.1},{"1966-06-27",14.7},{"1966-06-28",13.9},{"1966-06-29",18.7},{"1966-06-30",16.5},{"1966-07-01",17.1},{"1966-07-02",17.1},{"1966-07-03",15.2},{"1966-07-04",16.3},{"1966-07-05",15.},{"1966-07-06",16.4},{"1966-07-07",14.2},{"1966-07-08",15.3},{"1966-07-09",17.5},{"1966-07-10",16.5},{"1966-07-11",15.2},{"1966-07-12",15.6},{"1966-07-13",15.2},{"1966-07-14",14.2},{"1966-07-15",13.8},{"1966-07-16",15.3},{"1966-07-17",15.1},{"1966-07-18",17.3},{"1966-07-19",18.8},{"1966-07-20",20.2},{"1966-07-21",21.},{"1966-07-22",22.3},{"1966-07-23",18.9},{"1966-07-24",17.4},{"1966-07-25",17.2},{"1966-07-26",14.6},{"1966-07-27",15.6},{"1966-07-28",15.8},{"1966-07-29",15.4},{"1966-07-30",14.},{"1966-07-31",14.2},{"1966-08-01",14.7},{"1966-08-02",13.7},{"1966-08-03",14.7},{"1966-08-04",13.1},{"1966-08-05",15.},{"1966-08-06",14.2},{"1966-08-07",15.9},{"1966-08-08",15.2},{"1966-08-09",15.7},{"1966-08-10",15.5},{"1966-08-11",15.1},{"1966-08-12",14.9},{"1966-08-13",14.1},{"1966-08-14",15.1},{"1966-08-15",13.9},{"1966-08-16",13.4},{"1966-08-17",15.6},{"1966-08-18",16.},{"1966-08-19",16.1},{"1966-08-20",15.},{"1966-08-21",14.4},{"1966-08-22",13.8},{"1966-08-23",14.4},{"1966-08-24",13.6},{"1966-08-25",14.8},{"1966-08-26",13.},{"1966-08-27",13.5},{"1966-08-28",15.2},{"1966-08-29",15.5},{"1966-08-30",13.8},{"1966-08-31",14.6},{"1966-09-01",14.4},{"1966-09-02",14.1},{"1966-09-03",14.7},{"1966-09-04",14.8},{"1966-09-05",15.6},{"1966-09-06",14.3},{"1966-09-07",15.3},{"1966-09-08",13.6},{"1966-09-09",8.7},{"1966-09-10",10.8},{"1966-09-11",13.6},{"1966-09-12",12.6},{"1966-09-13",14.1},{"1966-09-14",13.5},{"1966-09-15",13.},{"1966-09-16",10.2},{"1966-09-17",12.3},{"1966-09-18",7.8},{"1966-09-19",10.9},{"1966-09-20",14.7},{"1966-09-21",12.2},{"1966-09-22",9.4},{"1966-09-23",9.1},{"1966-09-24",12.5},{"1966-09-25",7.1},{"1966-09-26",10.5},{"1966-09-27",5.3},{"1966-09-28",3.5},{"1966-09-29",7.1},{"1966-09-30",10.5},{"1966-10-01",9.3},{"1966-10-02",11.4},{"1966-10-03",11.6},{"1966-10-04",11.1},{"1966-10-05",4.6},{"1966-10-06",7.5},{"1966-10-07",9.6},{"1966-10-08",11.4},{"1966-10-09",9.1},{"1966-10-10",6.5},{"1966-10-11",7.4},{"1966-10-12",6.},{"1966-10-13",6.1},{"1966-10-14",6.3},{"1966-10-15",8.7},{"1966-10-16",10.5},{"1966-10-17",11.2},{"1966-10-18",10.},{"1966-10-19",9.3},{"1966-10-20",9.6},{"1966-10-21",9.8},{"1966-10-22",9.6},{"1966-10-23",8.8},{"1966-10-24",7.4},{"1966-10-25",1.8},{"1966-10-26",3.4},{"1966-10-27",4.6},{"1966-10-28",0.5},{"1966-10-29",-1.4},{"1966-10-30",2.6},{"1966-10-31",6.5},{"1966-11-01",4.5},{"1966-11-02",3.1},{"1966-11-03",2.8},{"1966-11-04",4.},{"1966-11-05",7.},{"1966-11-06",6.7},{"1966-11-07",6.1},{"1966-11-08",7.6},{"1966-11-09",7.6},{"1966-11-10",3.6},{"1966-11-11",-0.5},{"1966-11-12",1.},{"1966-11-13",4.3},{"1966-11-14",6.4},{"1966-11-15",4.5},{"1966-11-16",3.6},{"1966-11-17",3.1},{"1966-11-18",2.2},{"1966-11-19",0.},{"1966-11-20",0.9},{"1966-11-21",3.1},{"1966-11-22",1.4},{"1966-11-23",1.5},{"1966-11-24",2.8},{"1966-11-25",2.8},{"1966-11-26",3.6},{"1966-11-27",5.},{"1966-11-28",5.4},{"1966-11-29",1.4},{"1966-11-30",1.7}};
Any help would be much appreciated
A:
We need to manually group the data by month and take its mean, like so:
BarChart[GroupBy[data, DateValue[First@#, "MonthNameShort"] &,
Extract[{All, 2}] /* Mean], ChartLabels -> Automatic]
To break this down: First, we GroupBy the month (DateValue[First@#, "MonthNameShort"]). Then we extract the second part of every value: Extract[{All, 2}] and then take the Mean.
We can now extend this to do it over weekdays for example:
BarChart[GroupBy[data, DateValue[First@#, "DayNameShort"] &,
Extract[{All, 2}] /* Mean], ChartLabels -> Automatic]
or any other period really:
Check the documentation for DateValue for the various different groupings. It's perhaps more useful if your data is higher resolution (for instance, down to the hour) but in any case, this is a nice, extensible solution.
Finally, you can modify what function you want to reduce your data by. You initially asked for Mean, but we could do other interesting things like the standard deviation, just by modifying the reduction function:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Баскетбольное кольцо
Разрабатываю 2D игру на unity с баскетбольным кольцом, думаю как осуществить подсчёт очков.
У меня сейчас по одному коллайдеру на мяч и кольцо, но очки прибавляются и без пролёта в кольцо (когда мяч пролетает рядом).
Есть одна идея:
Сделать два коллайдера на кольце, чуть повыше и пониже, и один на мяче. Мяч пролетает верхний коллайдер, потом нижний, и очко засчитывается.
Только не пойму как закодить это. Подскажите, пожалуйста.
A:
Ты можешь сделать 2-а коллайдера на кольце: 1-ый отвечает за столкновения с кольцом (т.е. основной коллайдер (если у тебя 3д игра можно использовать MeshCollider)) и 2-ой внутри этого кольца в форме блина меньшего диаметра чем кольцо и сделать его IsTrigger (если игра 3д)
Затем повесить на кольцо скрипт, назовём его BasketballHoop и вызывать начисление очков в OnTriggerExit c предварительной проверкой прошёл ли шар через кольцо. Например так:
private void OnTriggerExit(Collider other)
{
if (Vector3.Dot(gameObject.transform.up, other.gameObject.transform.position - gameObject.transform.position) > 0)
{
//не прошёл
}
else
{
//прошёл
}
}
То есть я беру скалярное произведение двух векторов
Какие преимущества данного решения:
1. Можно использовать мяч любого размера
2. Очки будут засчитываться только когда мяч попадает в кольцо сверху
и, соответственно, не будут засчитываться если мяч попадает снизу
или вылетает
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Префикс не связан c пространством имён SVG
Хочу сделать текст дугой.
Как видно в данном примере тут все отображается, а вот если в браузере открыть, то получаю вот такую ошибку и в Opera Chrome, FF
А вот в EDGE && IE просто пустота без всяких ошибок.
Не смотря на ошибку, я вопрос в любом случае хотел написать, так как хотел спросить помощи в разъяснении логики построение координат атрибута d элемента path, но тут получается два вопроса в одном...
Коллеги, вопрос, что эта за ошибка у меня и как ее исправить, с утра не могу справиться с ней?
И может кто разъяснить хотя бы приблизительно какая координата атрибута d элемента path за что отвечает?
<svg width="300" height="200" viewBox="0 0 200 200">
<style>
svg{
border:2px solid red;
}
</style>
<defs>
<path id="textpath" fill="none" stroke="none" d="M0.057,0.024c0,0,10.99,51.603,102.248,51.603c91.259,0,136.172,53.992,136.172,53.992" />
</defs>
<use xlink:href="textpath" />
<text x="10" y="10" fill="green">
<textPath xlink:href="#textpath">
Lorem ipsum dolor sit amet consectetur.
</textPath>
</text>
</svg>
A:
#1.
Немного уточню вопрос.
Сообщение об ошибке появляется при открытии файла с расширением *.svg
Если точно такой же код SVG сохранить с расширением *.html то сообщения об ошибке не будет.
В современных браузерах html парсер, если есть ошибки в svg коде пропускает их и выполняет код дальше.
В вашем коде не указано пространство имен XML. Парсер svg считает это ошибкой и останавливает выполнение файла.
Необходимо добавить в шапку svg файла строчки определяющие namespace xml:
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
и тогда ваш код будет работать в любом окружении.
<svg width="300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="200" viewBox="0 0 200 200">
<style>
svg{
border:2px solid red;
}
</style>
<defs>
<path id="textpath" fill="none" stroke="none" d="M0.057,0.024c0,0,10.99,51.603,102.248,51.603c91.259,0,136.172,53.992,136.172,53.992" />
</defs>
<use xlink:href="textpath" />
<text x="10" y="10" fill="green">
<textPath xlink:href="#textpath">
Lorem ipsum dolor sit amet consectetur.
</textPath>
</text>
</svg>
Отсюда вытекает практический совет,- делать отладку svg кода в его родном окружении, то есть в файле с расширением *.svg и только потом добавлять код в html страничку.
#2.
И может кто разъяснить хотя бы приблизительно какая координата
атрибута d элемента path за что отвечает?
d="M0.057,0.024c0,0,10.99,51.603,102.248,51.603c91.259,0,136.172,53.992,136.172,53.992" />
M (moveto) - переместить перо в точку с координатами (X,Y) 0.057,0.024
c с этого символа начинается формула кубической кривой Безье – The cubic Bezier curve
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Создание системы распознавания голоса
Решил сделать что то умное и полезное, а именно систему для распознавания речи. Хочется сделать качественно, так что прошу советов:
На каком языке писать что бы, в дальнейшем можно было бы легко перенести под *NIX и мобильные оси?
Что бы была хорошая библиотека для работы с аудио, а именно она должна:
- Работать со всеми распространёнными аудио форматами
- Работать с микрофоном
- С помощью нее можно было отфильтровать только голос
A:
Я бы разделил работу на два этапа: рисёрч и, собственно, реализация. Рисёрч я бы делал на чём-то вроде Java или C#, так как это очень сильно ускоряет разработку. Вы сможете сравнительно быстро реализовывать свои идеи и проверять их.
В случае, если удастся найти правильные решения, можно уже браться за проектирование реализации. И вот тут-то я бы советова взяться за C++, так как он действительно хорошо переносится. Разве что с iOS не уверен, что там у них.
"- С помощью нее можно было отфильтровать только голос" - если вы ставите такое условие к библиотеке дял работы со звуком, то это значит, что вы ещё ОЧЕНЬ далеки от темы. Ваша система должна уметь самостоятельно опознавать и отсеивать шумы. Никакая библиотека не может сделать это за вас. Единственное, что она могла бы сделать - это выделить определённый частотный диапазон, что, в общем, не гарантирует, что это обязательно голос.
Работать с микрофоном и читать разные форматы.. в Java для рисёрча есть всё необходимое. Уверен, что в C# тоже должно быть. Чтобы читать что-то сложнее, чем WAV, могут понадобиться кодеки. Это всё можно нарыть.
К сожалению, с кодеками могут начаться сложности в тот момент, когда речь пойдёт уже о финальной реализации и о всяких лицензиях. Стоит проявить осторожность в этом вопросе.
UPD
Напомнило старую шутку из абсурдопедии. В категории "как правильно" была старая статья про то, как найти чёрную кошку в тёмной комнате. Среди вариантов, есть способ, использующий нейронные сети:
Обучаем нейронную сеть путём показа кошек, пойманных другими методами. Обученная нейронная сеть будет способна ловить кошек без вмешательства человека непостижимым для него способом. Остаётся разместить сеть в тёмной комнате.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Адаптация сайта под мобильные устройства и плашеты
Добрый день! Пишу Вам форумчане по такому поводу. Начальство поставило задачу адаптировать сайт под всевозможные мобильные устройства и планшеты. Стала задача разработки интерфейса под мобильные устройства. Так вот собственные вопросы:
Есть ли попроще классы на php типа
MobileDetect которые позволяли бы
различать с какого устройства зашел
пользователь? Классификация по
следующим типам: компьютер, телефон,
планшет. Вдаваться в конкретные
модификации телефона или планшета,
не надо.
Есть ли бесплатные сервисы
позволяющие шаблон сайта под ПК
перевести под мобильное устройство с
минимальными затратами?
Сайт разработан на 1с-Битриксе,
соответственно шаблон под мобильные
устройства будет подцепляться как
альтернатива компьютерному шаблону.
Где лучше прописать эти условия
обработки типа юзерского устройства
через которое он вышел на сайт?
Буду благодарен за ответы по всем или некоторым пунктам.
A:
Есть ли попроще классы на php типа
MobileDetect
Есть, но найти их крайне сложно.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как при клике на UI кнопку вызвать методы скрипта?
Я делаю главное меню для игры по видеоролику из ютуба. После того как рассказчик написал скрипты для кнопок — он стал добавлять их в эти кнопки. Я этого сделать по какой-то причине не могу. Я не могу добавить ни старт гейм, ни выход. У меня этого просто нет. В видео отображается контекстное меню и последняя строчка с названием NewBehaviourScript. У меня ее нет.
Подскажите как ее добавить? Я уже обыскал весь ютуб, гугл и сайт юнити, но так и не смог найти решение своей проблемы. Скрипт написан на C#.
A:
В UI у кнопок можно назначить событие OnClick.
Например есть кнопки:
В их свойствах кнопки находим OnClick.
В нем нужно выбрать объект, на котором висит скрипт-обработчик (это может быть и сама кнопка, при желании), а затем в правой части этого выпадающего списка выбрать тот самый скрипт и нужный метод из того самого скрипта:
Всё.
Причем методы должны быть публичными. Пример:
using UnityEngine;
public class SwitchCameras : MonoBehaviour {
private void Start() {
}
public void Switch() {
Debug.Log("Тут какой-то метод вызывался");
}
}
При появлении метода с аргументами - в событии OnClick кнопки можно будет добавить этот самый параметр:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как включить ссылки в TextView?
Всем привет, есть TextView, текст ставится с помощью Html.fromHtml. Проблема в том, что ссылки могут быть как и в HTML тегах, так и просто текстом:
<a href="http://google.com">Google</a>
http://google.com
Включаю ссылки так:
textView.movementMethod = LinkMovementMethod.getInstance()
Ссылки включаются только для первого варианта (в HTML теге). Если использовать Linkify то работает только второй вариантом, если использовать их вместе, то что-то одно.
Как включить ссылки и в HTML и просто текстом?
A:
Html нацелен на обработку тегов и просто url-адреса в тексте не ищет. Но соль в том, что Linkify удаляет все существующие URLSpan'ы, а потом ищет в оставшемся тексте адреса по заданным паттернам.
Варианты навскидку:
обработать текст заранее (обернуть url тегами)
обработать текст после Html.fromHtml спанами самому без Linkify
скопировать спаны из текста, обработанного Html.fromHtml
после обработки Linkify:
TextView tv = findViewById(R.id.tv);
Spanned fromHtml = Html.fromHtml("<a href=\"http://google.com\">Google</a><br>" +
"http://google.com");
SpannableStringBuilder builder = new SpannableStringBuilder(fromHtml);
Linkify.addLinks(builder, Linkify.ALL);
TextUtils.copySpansFrom(fromHtml, 0, fromHtml.length(), URLSpan.class, builder, 0);
tv.setText(builder);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
While loop with conditions using data.table
I am new to loops in R and have a relatively simple dataset to process. My sample dataset consists of timestamps - time, cell phone id: id, and cell phone battery level: level
My objective is to produce an output which takes the rate of battery decline over time, taking account recharge cycles. The beginning of a cycle can be identified where the following record's level is greater than the previous. In other words, while level <= lag(level), the cycle should continue, but as soon as level > lag(level), the cycle should restart
> test
time id level
1: 2017-12-25 14:10:03 1 81
2: 2017-12-25 14:20:03 1 81
3: 2017-12-25 14:30:04 1 81
4: 2017-12-25 14:40:04 1 73
5: 2017-12-25 14:50:04 1 70
6: 2017-12-25 15:00:03 1 70
7: 2017-12-25 15:10:04 1 65
8: 2017-12-25 15:20:04 1 62
9: 2017-12-25 15:30:04 1 61
10: 2017-12-25 15:40:04 1 60
11: 2017-12-25 15:50:03 1 60
12: 2017-12-25 16:00:04 1 60
13: 2017-12-25 16:10:04 1 95
14: 2017-12-25 16:20:03 1 95
15: 2017-12-25 16:30:04 1 95
16: 2017-12-25 16:40:04 1 94
17: 2017-12-25 16:50:04 1 92
18: 2017-12-25 17:00:03 1 90
19: 2017-12-25 17:10:04 1 81
20: 2017-12-25 17:20:03 1 79
21: 2017-12-25 17:30:03 2 100
22: 2017-12-25 17:40:03 2 100
23: 2017-12-25 17:50:03 2 100
24: 2017-12-25 18:00:03 2 90
25: 2017-12-25 18:10:03 2 85
26: 2017-12-25 18:20:03 2 75
27: 2017-12-25 18:30:04 2 65
28: 2017-12-25 18:40:03 2 54
29: 2017-12-25 18:50:03 2 32
30: 2017-12-25 19:00:03 2 11
31: 2017-12-25 19:10:04 2 92
32: 2017-12-25 19:20:04 2 92
33: 2017-12-25 19:30:03 2 91
34: 2017-12-25 19:40:04 2 90
35: 2017-12-25 19:50:04 2 90
36: 2017-12-25 20:00:03 2 81
37: 2017-12-25 20:10:03 2 79
38: 2017-12-25 20:20:04 2 99
39: 2017-12-25 20:30:04 2 96
40: 2017-12-25 20:40:03 2 96
In the sample dataset above, the intended output would look like this, where difftime = the difference in time between where the cycle started and stopped, diffcharge = the difference in battery level between where the cycle started and stopped, and rate = diffcharge/difftime
> outcome
id start recharge difftime diffcharge rate
1 1 2017-12-25 14:10:03 2017-12-25 16:00:04 110.0167 21 0.1908801
2 1 2017-12-25 16:10:04 2017-12-25 17:20:03 69.98333 16 0.2286259
3 2 2017-12-25 17:30:03 2017-12-25 19:00:03 90 89 0.9888889
4 2 2017-12-25 19:10:04 2017-12-25 20:10:03 59.98333 13 0.2167269
5 2 2017-12-25 20:20:04 2017-12-25 20:40:03 19.98333 3 0.1501251
I have tried so far simply to create a while loop that concatenates the levels from each cycle, after which I can take the min, max, etc. with the following code but this does not produce the intended output.
raw_data <- test
unique_id = unique(test$id)
for (id in unique_id)
{
onePhone <- raw_data[ which(raw_data$id == id), ]
onePhone <- onePhone[order(onePhone$time, decreasing = FALSE),]
cycle <- NULL
if(nrow(onePhone) >=2 ){
for(i in 2:nrow(onePhone)) {
while(onePhone[i-1,"level"] >= onePhone[i,"level"])
{
i = i+1
cycle <- c(z, onePhone[i,"level"])
}
print(cycle)
}
}
}
Any advice on how to use data.table, dplyr, or a simple while loop would be appreciated. Here is the sample data:
> dput(test)
structure(list(time = structure(c(1514229003.91212, 1514229603.61297,
1514230204.14629, 1514230804.81938, 1514231404.36784, 1514232003.73393,
1514232604.17933, 1514233204.00143, 1514233804.68755, 1514234404.15599,
1514235003.99419, 1514235604.68204, 1514236204.18828, 1514236803.66526,
1514237404.0434, 1514238004.40609, 1514238604.02003, 1514239203.42238,
1514239804.19495, 1514240403.15927, 1514241003.87092, 1514241603.93167,
1514242203.77223, 1514242803.66758, 1514243403.33705, 1514244003.25017,
1514244604.05367, 1514245203.7921, 1514245803.2651, 1514246403.63888,
1514247004.02684, 1514247604.04009, 1514248203.99929, 1514248804.07401,
1514249404.11004, 1514250003.74613, 1514250603.88962, 1514251204.19115,
1514251804.06932, 1514252403.94181), class = c("POSIXct", "POSIXt"
), tzone = "EST"), id = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2), level = c(81, 81, 81, 73, 70, 70, 65, 62,
61, 60, 60, 60, 95, 95, 95, 94, 92, 90, 81, 79, 100, 100, 100,
90, 85, 75, 65, 54, 32, 11, 92, 92, 91, 90, 90, 81, 79, 99, 96,
96)), .Names = c("time", "id", "level"), class = c("data.table",
"data.frame"), row.names = c(NA, -40L), .internal.selfref = <pointer: 0x102010778>)
A:
Using @Hugh approach in first step and then getting the end result:
test[, cycle := cumsum(level > shift(level, fill = first(level))), by = "id"]
x <- test[, .(start = min(time),
recharge = max(time),
diffcharge = max(level) - min(level)),
by = .(id, cycle)]
x[, difftime := as.numeric(recharge - start)]
x[, rate := diffcharge / difftime]
x
# id cycle start recharge diffcharge difftime rate
# 1: 1 0 2017-12-25 14:10:03 2017-12-25 16:00:04 21 110.01283 0.1908868
# 2: 1 1 2017-12-25 16:10:04 2017-12-25 17:20:03 16 69.98285 0.2286274
# 3: 2 0 2017-12-25 17:30:03 2017-12-25 19:00:03 89 89.99613 0.9889314
# 4: 2 1 2017-12-25 19:10:04 2017-12-25 20:10:03 13 59.99771 0.2166749
# 5: 2 2 2017-12-25 20:20:04 2017-12-25 20:40:03 3 19.99584 0.1500312
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как получить объект который вошел в триггер
Вот есть метод OnTriggerEnter(Collider), он качестве параметра принимает collider того объекта, например в триггер которого он вошел(ну то-есть просто collider в который вошел).
А как получить сам объект, который вошел в collider из самого объекта с триггером.
Надеюсь понятно написал.
Я понимаю что триггер это тот же collider, просто не хотел повторяться.
Кратко: нужен не тригер получить из объекта, а объект который вошел в тригер нужно получить из самого тригера.
A:
В общем нашел решение, получилось так:
foreach (Collider item in Physics.OverlapSphere (transform.position, Radius)) {
if (item.attachedRigidbody && !item.isTrigger) {
//...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Прямая речь и слова автора
Здравствуйте, подскажите пожалуйста относительно прямой речи и слов автора, нигде не смог найти ответ на свой вопрос.
Вопрос следующий. Если после прямой речи идут слова автора, затем точка, может ли после точки идти следующее предложение слов автора?
И правильно ли я понимаю, что слова автора — это конструкция, относящаяся непосредственно к прямой речи, а не к тексту вообще, который не является прямой речью?
Например:
— Ты не прав, — сказал Френк, посмотрев на брата. В глазах Френка читалось презрение.
(Абзац) Повисла напряженная пауза.
В данном примере текст после абзаца не относится к прямой речи и не является словами автора, я правильно понимаю?
И является ли словами автора предложение: В глазах Френка читалось презрение?
A:
В этой теме важно понимать терминологию.
1) Предложения с прямой речью. Предложения с прямой речью состоят из слов автора и собственно прямой речи, причем рассматривают различные варианты их взаимного расположения.
2) Прямая речь — высказывание, дословно введённое в авторский текст . Это точно воспроизведённая чужая речь, переданная от лица того, кто её произнёс или написал.
3) Слова автора ― условное название. Это слова, указывающие на то, кому принадлежит прямая речь (или это слова автора, вводящие прямую речь). Практически слова автора ― это часть авторского текста, примыкающего к прямой речи, так что образуется единая конструкция, оформленная с помощью определенных правил.
— Ты не прав, — сказал Френк, посмотрев на брата. Это предложение с прямой речью, оно состоит из прямой речи и слов автора, вводящих эту прямую речь. Далее следует авторский текст (не слова автора).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Интерактивная схема коммутации
Приветствую!В серверной большая коммутационная панель.В процессе перекоммутации была заполнена рабочая схема на бумаге которая, естественно, про...терялась.Возник вопрос в создании этой же в электронном виде. Но так, как заполнить документ в екселе - это скучно и грустно - хотелось бы веб-мордочку, которая могла бы:1. Отобразить N-патч-панелей 2. Отобразить N-свичей 3. Поиск порта: например вводишь 8-16, а он подсвечивает, сам порт 16 на 8 патч-панели, патч-корд и порт свича, куда он приходит (это баловство... но круто же) 4. Иметь возможность логирования (нужно, что бы была кнопка, которая открывала журнал, где сказано: Иван Факов чеиндж конекшн 8-16 ту свич 2-4) 5. Вы не поверите, но иметь возможность изменять конфиги из консоли :) 6. Возможность на схеме нажать на один порт, потом на другой, и что бы там нарисовался патч-корд, а в журнале написало текст из пункта 4И в догонку: да, я понимаю что это глупости и баловство (и именно поэтому не сел за написание этой фигни сам). Но было бы очень классно, если кто-то встречался с уже написанными такими системами, и может ткнуть в них носом :)Если хотя-бы 2 из 5 пунктов есть в системе, которую Вы знаете - можете ее предлагать. Особенно если она опенсорсовая и есть возможность допиливания.Заранее благодарен.
A:
Я данную проблему решил так:взял мак адреса всех компов в сети, сопоставил их с номерами розеток(номер на розетке у пользователя совпадает с номером на патч-панели), после чего с коммутатора вытащил fdb таблицу с мак адресами и портами, на которых те светятся,и по макам которые у меня есть я сопоставил порт коммутатора с портом патчпанели.А уже все полученные данные можно вывести в html виде(jquery+php).я даже взял схему офиса и расставил все ПК по своим местам, ну дальше можно тварить всё что душа пожелает![alt text][1] [1]: http://i.imgur.com/jyz9ggM.png
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Количество, частота и содержание коммитов
Заметил, что количество моих коммитов сильно превышает количество коммитов других людей в схожих проектах (на один не самый сложный проект на свете ушло больше 300). Это, конечно, не является моей основной проблемой в жизни, но у меня сложилось впечатление, что я делаю что-то не так, и это может затруднить копание в истории проекта.
Я делаю коммит каждый раз, когда в проект добавляется новая фича, и он после этого приходит в работоспособное состояние, причем неважно, какого размера фича - простое выправление грамматики, багфикс, внедрение какого-то нового функционала (последнее может быть разбито и на несколько коммитов, но после каждого из них проект должен быть работоспособным), причем если я поправил css, сменил отвратительно кривой текст на просто кривой и пересобрал в контроллере экшен - это, по моей философии, должны быть три коммита, потому что они затрагивают разные невзаимосвязанные части проекта. В результате, с одной стороны, я могу получить чуть ли не любой слепок проекта и он в любой момент будет работоспособен, с другой - я получаю ворох коммитов типа 'Typo fix', 'CSS fix', 'Microfix', которые, наверное, могли бы и не существовать.
Короче, как правильно делать?
p.s. Одна из вероятных причин ситуации - то, что бранчингом почти не пользуюсь. Сам дурак, знаю.
upd. Если точнее сформулировать вопрос - должны ли вводимые фичи быть атомарными (один коммит - одна фича или багфикс), или на это можно наплевать?
A:
По коммитам у меня такие правила:
Коммит должен компилироваться без ошибок.
Коммит должен обозначать как минимум новую фичу/класс/метод/багфикс.
Или хотя бы коммит должен обозначать конец рабочего дня.
Коммит не должен задерживать остальных членов команды, ибо merge - это зло (иногда необходимое).
Из чего следует, что если я занимаюсь прожектом, то как минимум 1 коммит в день я должен делать. Терпеть не могу коммиты, когда изменения копятся-копятся, потом бабах - глобальный коммит с тучей конфликтов merge. С другой стороны, больше 2-3 коммитов в день - это излишне, ну разве что по просьбе сотоварищей.
Update для фанатов git: в данном контексте коммит имеется ввиду не коммит в локальную репу, а гитовский push в глобальную репу.
A:
Вы все делаете правильно :)
И переходите уже, наконец, на git :]
Хотите новую фичу - делаете ветку, в которой реализовываете фичу, потом мержите ее в дев, тестите, и далее по списку...
Не нужно себя ограничивать в количестве коммитов. Просто у вас будет более детальная история в случае чего :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Кодировка БД и сайта
Знаю что вопросов таких была уйма, но гуляя на стаке не нашел решение своей проблемы, пожалуйста простите.
Из бд , и в бд кирилица попадает как всякие символы, у всех файлов и у всех таблиц и бд кодировка одна и та же utf8_general_ci Только вот "Сопоставление кодировки соединения " в phpmyadmin другая, но я его и изменить не могу.
Хостинг от рег.ру, помогите с проблемой)
И дело точно в бд , так как на странице есть статичные тексты на кирилице, и все нормально отображается, но как только с бд, так символы.
A:
Хочу помочь всем , кто в дальнейшем столкнется с такой же проблемой, пишите поддержке сайта, они умеют исправлять кодировку, если конечно же до того как поставить ваш сайт на их хостинг у вас все работало.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Система личных сообщений
Учусь делать самую простую систему сообщений, между двумя пользователями, где на сообщение можно ответить только 1 раз и это сообщение и ответ, видны у обоих пользователей.
Вот в чём вопрос: если 1 пользователь хочет удалить какое-нибудь сообщение из своего списка всех сообщений и если он его удалит, то оно пропадёт из БД и тогда у другого пользователя оно из списка тоже исчезнет.
Может в таком случае, сначала записать в бд, в какую-нибудь строку этого сообщения, то что 1 пользователь уже не хочет его отображать и записать цифру 1 и потом проверять, если эта цифра есть, то этому пользователю такое сообщение не выводить и когда уже второй пользователь захочет его удалить, то ещё в одну строку записывается цифра 1 и потом уже сравнивается, если цифра 1 есть в обеих строках, то удалить его из базы?
A:
Когда-нибудь вы захотите дать поговорить более чем двоим пользователям, поэтому колонки плодить не получится.
Можно реализовать, например, вот так:
User(id, ...)
Thread(id, title, ...) // разговор
UserThread(user_id, thread_id) // участники разговора
Message(id, author_id, thread_id, text, ...) // сообщения
UserMessage(user_id, message_id) // что видит пользователь
Удаляете только связку пользователя с сообщением, оригинальные сообщения оставляете даже если его больше никто не видит, пригодятся.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Рационально ли использование фреймфорка при разработке одностраничника на PHP?
Добрый день!
Недавно освоил PHP. Сейчас есть заказ на разработку лендинга.
Рационально ли было бы применять какой-либо фреймворк, вроде Yii или Symfony.
Или все пишется спокойно на обычном PHP
A:
Все зависит от задач, которые хочется решить на стороне бэкэнда. Скорее всего, вам хватит всего функционала фреймворка. Я работал с Yii и знаю, что в нем уже есть масса хэлперов, позволяющих формировать красиво даты, суммы и прочее. Так же, имеется функционал защиты от csrf и инъекций.
Я не вижу ничего плохого в том, что в одностраничнике кто-то использует фреймворк для экономии времени на разработку и тестирование. Как минимум, вы не потратите время на создание базовой структуры, фильтры и валидаторы входящих данных (заполнение форм).
Если использовать кэширование при наличии выборки из sql, то можно легко и быстро сэкономить ресурсы.
Однако, нет никакого смысла в использовании фреймворка, если вы пишете на серверной стороне только какой-нибудь render('template') и больше ничего.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Внешние ключи и FileTables
Есть первая таблица people, в ней есть столбец photo - uniqueidentifier.
Вторая - FileTable photo.
Первая таблица связана (photo) со второй (stream_id), и в случае, если фотография будет удалена, столбцу photo будет присвоен NULL.
А как сделать, чтобы в случае удаления человека из таблицы people удалялась и фотография? Пытался присвоить внешний ключ обычным способом, но не хочет.
A:
Первая таблица связана (photo) со второй (stream_id), и в случае, если
фотография будет удалена, то столбцу photo будет присвоен Null.
В таком случае обычный AFTER DELETE триггер должен сработать
CREATE TRIGGER people_afterDelete
ON people
AFTER DELETE
AS
BEGIN
SET NOCOUNT ON;
DELETE PH
FROM photo PH
JOIN DELETED D on D.photo = PH.stream_id;
END;
И то, что таблица photo является FileTable, никакой роли в данном случае не играет.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Статический метод класса
Для чего может понадобиться обьёвлять метод класса, используя спецификатор static? Переменные в этом методе так же будут static? Что будет происходить при создании нескольких экземпляров класса? Как в памяти всё это дело будет храниться?
A:
Статический метод может работать со статическими переменными класса и с объектами класса.
Он может выполнять какие-то действия общие для всех объектов данного класса или для указываемой группы объектов, изменение общих параметров, что-то вроде сборки мусора и т.д.
Переменные внутри метода не обязательно будут static.
Создание и уничтожение экземпляров класса никак не затронет статический метод, его можно вызывать независимо от существования объектов класса. Это аналог обычной функции, только имя у неё необычное и область видимости.
Существование статического метода никак не отражается на том, как будет храниться объект класса.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WordPress вывод постов состоящих в двух категориях
На главной странице сайта свой уникальный дизайн. Для его функциональности на главной нужно вывести популярные или важные(featured) посты из каждой категории, лежащей в родителе, который я указываю.
Хочу заранее сказать что я ищу совет, а не решение. На какие функции стоит обратить внимание? Как это сделать иначе? Что не так? И т.д.
Дам пример:
- Родитель 1
- Потомок1
- Потомок2
- Потомок3 ...
- Featured
То есть нужно что бы посты, выведенные на главной одновременно состояли в 'Родитель 1' и Featured и выводились не более 6-ти штук на категорию.
Это еще не все. Так же я предполагаю создать приоритет. Под каждым постом в featured будет указан приоритет(от 1-6) и в зависимости от этого будет выбираться очередность выводимых в блоке постов. Это будет реализовано через дополнительные поля (get_post_meta).
На данный момент код простой:
$prt=get_categories(array('hide_empty'=>0,'child_of'=>12,'orderby'=> 'id','title_li'=>''));
...
$query = new WP_Query(array('cat'=>$tid,'showposts'=>'6'));
Вся его задача вытащить все категории из родителя, после чего следующая строчка вытащит из каждой по 6 постов. Дело в том что 6 последних постов и сортировки по приоритетам у них нет.
Я боюсь что нужно будет писать очень большой и громоздкой код с проверками на посты и дополнительными запросами для такой задачи, может вы знаете примеры попроще? Может можно/нужно составить вовсе чистый SQL запрос где это можно сделать?
A:
Еcли я правильно понял:
foreach ($cat_ids as $cat_id) {
$query = new WP_Query(array(
'category__and' => array($cat_id, $feature_id),
'showposts' => '6',
'orderby' => 'meta_value_num',
'meta_key' => 'priority'
));
// Дальше Loop по сценарию
}
В ролях:
$cat_ids - массив с ID подкатегорий категории "Родитель 1";
$feature_id - ID категории "Featured";
'priority' - ключ дополнительного поля приоритета поста.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Django. Увеличения значения поля в модели
Застрял вроде на таком простом моменте, но тем не менее. В гугле ничего не нашел. Ситуация такая, нужно чтобы пользователь вводил некое число и это значение, что он ввел прибавлялось к уже имеющему значению некоторому полю в модели.
Из кода, что приведен ниже необходимо, что когда пользователь вводит в поля development и testing цифры, эти цифры не обновлялись, а прибавлялись к уже имеющим значениям в базе, которые были до них.
Пример: в базе в полях development и testing хранятся значения 10 и 15, пользователь вводит в одно поля 5, в другое 3, и тогда в базе обновляются значения до 15 и 18 соответственно.
Скажем, так, вот модель:
Class Project(models.Model):
company = models.ForeignKey('projects.Company', on_delete=models.PROTECT, related_name='projects')
title = models.CharField('Project title', max_length=128)
development = models.DecimalField('development hours', default=0, decimal_places=2, max_digits=6)
testing = models.DecimalField('testing hours', default=0, decimal_places=2, max_digits=6)
Вот форма:
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['development', 'testing']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Submit('submit', 'UPDATE'))
View:
class ProjectUpdateView(LoginRequiredMixin, UpdateView):
model = Project
form_class = ProjectForm
success_url = reverse_lazy('home')
html
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card bg-light">
<div class="card-body">
{% crispy form %}
</div>
</div>
</div>
Спасибо.
A:
Вам нужно переопределить один из методов в UpdateView. Наверное это должен быть form_valid(). То есть на этапе, когда форма валидная, мы берем существующие данные из объекта и добавляем их в соответствующие поля экземпляра формы.
Я не проверял работает код или нет, но вы хотя бы будете знать в каком направлении двигаться.
class ProjectUpdateView(LoginRequiredMixin, UpdateView):
model = Project
form_class = ProjectForm
success_url = reverse_lazy('home')
def form_valid(self, form):
form.instance.development += self.object.development
form.instance.testing += self.object.testing
return super().form_valid(form)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как выровнять высоту 3 блоков по родительскому контейнеру?
Вот конкретный раздел сайта над которым я работаю:
Вот сайт
У меня есть 3 блока с услугами. В данный момент все они имеют высоту в зависимости от контента. Мне необходимо выровнять их высоту по самому большому из этих блоков, а также разместить кнопку "Узнать прайс" внизу блока с отступом в 20 пикселей от нижней части. Помогите пожалуйста это сделать. Уже пол дня играюсь с position:relative, absolute для родителей и child блоков и никак не могу получить нужный результат.
A:
Как вариант, использовать flexbox для раздела и position:absolute - для кнопки:
.row {
display: flex;
justify-content: space-between;
}
.block {
width: calc((100% - 126px) / 3);
border: #ccc solid 1px;
padding-bottom: 50px;
position: relative;
}
.btn {
position: absolute;
width: 50px;
bottom: 10px;
left: 50%;
margin-left: -25px;
border: #ccc solid 1px;
text-align: center;
}
<div class="row">
<div class="block">
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div class="btn">Кнопка</div>
</div>
<div class="block">
<br /><br /><br /><br /><br /><br />
<div class="btn">Кнопка</div>
</div>
<div class="block">
<br /><br /><br /><br /><br /><br /><br /><br />
<div class="btn">Кнопка</div>
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как сделать тест, в конце выводился бы правильный результат в виде профессии?
Хочу сделать тест на профориентацию, в котором были бы вопросы и в конце в виде результата выводилась бы профессия. Я хочу выводить профессии в соответствии с максимальным из тех шести значений. Но проблема заключается в том, что мне нужно найти максимальное значение из шести значений. Но я не знаю, как можно сравнить и найти максимальное значение из этих шести, если они находятся в разных активити. Вместе с этим, эти значения всегда разые, то есть изменяемые.
A:
Для того чтобы получить данные по итогу, я могу предложить использование синглтона. Создаете объект:
object GeneralClass {
var answers:ArrayList<Int> = ArrayList()
}
в этом классе будет массив с вашими цифрами. Другой вариант это использовать HashMap где ключ это будет активность, а значение это результат вашего ответа:
var answers = HashMap<Int, Int>()
Для записи используем:
GeneralClass.answers.add(ваш ответ)
Дальше используя Collections можно извлечь максимальное значение из сохраненного массива:
Collections.max(GeneralClass.answers);
P.S. Чтобы людям было проще дать вам ответ, предоставляйте хоть какой-то код. Например что и как вы делаете в активности.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linear Dependence Using Gaussian Elimination
Let $$\left\{\begin{pmatrix} 1\\ 2 \end{pmatrix},\begin{pmatrix} 4\\ 1 \end{pmatrix},\begin{pmatrix} 1\\ 1 \end{pmatrix}\right\}$$
Find if there are linear independent or not, if so show a vector that is linear dependent
I know that the row rank is equal to the column rank so I can look on the matrix of the vectors as is meaning
\begin{pmatrix} 1& 4 &1\\ 2 &1&1 \end{pmatrix} or
\begin{pmatrix} 1& 2 \\ 4 &1 \\ 1&1 \end{pmatrix}
In the first case I am looking at $$\alpha \begin{pmatrix} 1\\ 4\\ 1 \end{pmatrix}+ \beta \begin{pmatrix} 2\\ 1\\ 1\end{pmatrix}= \begin{pmatrix} 0\\ 0\\ 0\end{pmatrix}$$
So the only solution is $\alpha=\beta=0$ so I know it is linear dependent, but I do not know how to generate one vector from the two others.
Unlike
$$\alpha \begin{pmatrix} 1\\ 2 \end{pmatrix}+ \beta \begin{pmatrix} 4\\ 1\end{pmatrix}+\gamma \begin{pmatrix} 1\\ 1 \end{pmatrix}= \begin{pmatrix} 0\\ 0\\ 0\end{pmatrix}$$
In one case I am looking at the $\ker(T)$ and the other $\text{Im}(T)$?
A:
With the matrix
$$
\begin{pmatrix}1&2\\4&1\\1&1\end{pmatrix}
$$
you're looking at two vectors in $\mathbb{R}^3$; doing row reduction will only show that the original vectors in $\mathbb{R}^2$ are linearly dependent.
With row reduction on the other matrix
$$
\begin{pmatrix}
1 & 4 & 1 \\
2 & 1 & 1
\end{pmatrix}
\to
\begin{pmatrix}
1 & 4 & 1 \\
0 & -7 & -1
\end{pmatrix}
$$
you get that the third vector is in the span of the first two. If you also find the reduced row echelon form
$$
\to
\begin{pmatrix}
1 & 4 & 1 \\
0 & 1 & 1/7
\end{pmatrix}
\to
\begin{pmatrix}
1 & 0 & 3/7 \\
0 & 1 & 1/7
\end{pmatrix}
$$
you also prove that
$$
\begin{pmatrix} 1 \\ 1 \end{pmatrix}
=
\frac{3}{7}\begin{pmatrix} 1 \\ 2 \end{pmatrix}
+
\frac{1}{7}\begin{pmatrix} 4 \\ 1 \end{pmatrix}
$$
because row operations don't change linear relations between the columns.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Куда девается значок программы в панели задач?
Вот какой вопрос. Создал программу с двумя окнами. При работе программы открывается первое окно, затем если нажать на кнопку на этом окне, то открывается другое окно. Вроде ничего необычного. Первая проблема: после того, как открылось второе окно пропадает значок программы на панели задач. Как сделать чтобы он сохранился? И как раз из-за этой проблемы, второе окно не сворачивается нормально. Тупо просто в угол рабочего стола уходит. В чем дело?
Например вот такой код:
Первое окно:
from PyQt5 import QtCore, QtGui, QtWidgets
class Window_1(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(300, 146)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(40, 30, 221, 41))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 300, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Нажми"))
Второе окно:
from PyQt5 import QtCore, QtGui, QtWidgets
class Window_2(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(290, 143)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(80, 30, 171, 71))
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Тут что-то написано"))
И главное которое запускает:
import sys, os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import QtWidgets, QtGui
from Window1 import Window_1
from Window2 import Window_2
class Window(QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.Win = Window_1()
self.Win.setupUi(self)
self.Win.pushButton.clicked.connect(self.check)
def check(self):
des = Window2(parent=self)
self.hide()
class Window2(QMainWindow):
def __init__(self, parent=None):
super(Window2, self).__init__(parent)
self.Win_2 = Window_2()
self.Win_2.setupUi(self)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
A:
Замените:
des = Window2(parent=self)
На:
self.des = Window2()
Дело в том, что у объекта-виджета не было связи с каким-либо объектом, поэтому после завершения функции он был удален. А self.des привязывает объект, что защищает его от уничтожения.
Кст, правильно будет сделать так (нет смысла создавать каждый раз виджет):
...
class Window(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.Win = Window_1()
self.Win.setupUi(self)
self.Win.pushButton.clicked.connect(self.check)
self.des = Window2()
def check(self):
self.des.show()
self.hide()
class Window2(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.Win_2 = Window_2()
self.Win_2.setupUi(self)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Согласование в числе
Половина его волос были золотыми, а половина – серебряными
или Половина его волос была золотой, а половина – серебряной?
Вернул народу все, что у них отобрали или Вернул народу все, что у него отобрали?
A:
Половина его волос были золотыми, а половина – серебряными.
Половина, часть – это лишь существительные с собирательным значением, поэтому именно волосы были золотыми или серебряными.
У Розенталя есть подобные примеры (использование мн. числа при согласовании): http://www.evartist.narod.ru/text1/64.htm
...при обратном согласовании, если именная часть составного сказуемого имеет форму множественного числа, например: Большинство людей, встретившихся мне здесь, были оборванные и полураздетые... (Л. Толстой);
2) Вернул народу все, что у него отобрали.
Местоимение у него соответствует существительному народ в значении трудовая масса, а не в значении люди.
НАРОД, -а; м. 3. только ед. Основная трудовая масса населения страны. Трудовой н. Борьба народа за свои права. 4. только ед.; род.: -а (-у). Люди. Огромная толпа народу. В театре было мало народа.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I match a column entry from one df to a different df; and if they're the same, append another column's entry from the first df to the 2nd df?
CONTEXT:
I have two dataframes that have the following set up:
df1 looks like this...and goes on for about 3500 rows:
| id1 | id2 |
|:----|------:|
| a | name1 |
| b | name2 |
| c | name3 |
| d | name4 |
| e | name5 |
| f | name6 |
df2 looks like this...and goes on for about 4000 rows and about 8 columns
| id1 | ranktrial1 | ranktrial2 | ...
|:----|-------------:|-------------:| ...
| a | rank1 |rank1 | ...
| b | rank2 |rank2 | ...
| c | rank3 |rank3 | ...
| d | rank4 |rank4 | ...
| e | rank5 |rank5 | ...
| f | rank6 |rank6 | ...
NOTE1: some of the id1s, do not have id2s. Meaning they'll be NaNs when they're mapped; and I'll just drop them whenever I get to that step. I don't know if this is relevant, but I just wanted to add it in case it was.
QUESTION:
I need to append/join/place (don't know correct jargon here) the corresponding id2 names to the second dataframe, iff the id1 entry == id1 entry of df2. How do I do this?
The desired dataframe would look like this:
| id1 | id2 | ranktrial1 | tranktrail2 | ...
|:----|------:|-------------:|-------------:| ...
| a | name1 | rank1 | rank1 | ...
| b | name2 | rank2 | rank2 | ...
| c | name3 | rank3 | rank3 | ...
| d | name4 | rank4 | rank4 | ...
| e | name5 | rank5 | rank5 | ...
| f | name6 | rank6 | rank6 | ...
I feel as if this is probably really simple and I'm being a bit of a doofus, as I am a novice Pythoner. However, I have not been able to use similar question's responses to achieve my goal. It is quite likely my fault though :p
Thanks in advance for your help!
edits changed 4000 entries --> 4000 rows. LIkewise for 3500 entries
A:
Given you are dropping the missing bits afterwards, this is an inner join and can be accomplished with merge. By default, merge uses all commonly named columns. In this case, the only commonly named column is id1. Also, how='inner' si also the default.
df1.merge(df2)
id1 id2 ranktrial1 tranktrail2
0 a name1 rank1 rank1
1 b name2 rank2 rank2
2 c name3 rank3 rank3
3 d name4 rank4 rank4
4 e name5 rank5 rank5
5 f name6 rank6 rank6
You could be more explicit with
df1.merge(df2, how='inner', on='id1')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Неосознанная грамотность
Вопрос, наверное, не по теме, но захотелось это обсудить. Я заметила, что при быстром наборе текста на клавиатуре делаю ошибки. Причем не просто "опечатки", когда палец попадает на соседнюю клавишу или правая рука обгоняет левую. "Настоящие" ошибки, т.е., например, "а" вместо "о". А ведь эти буквы на клавиатуре не рядом!
При писании рукой этого не наблюдается. Конечно, этот процесс более медленный и есть время "подумать". Но ведь на самом деле рукой я пишу тоже автоматически, не обращаясь мысленно к правилам! Получается, что есть как бы разная глубина усвоения навыка.
Замечал ли кто-либо за собой такую "неграмотность"? Если да, что, по-вашему, может быть ее причиной?
A:
Разумеется. Это один из известных видов дисграфии (под которой я разумею письменную дислексию, тут разнобой в терминологии).
Типичные ошибки: замена букв по омофоническому признаку (безударных гласных и оглушаемых согласных) и замена на парные по глухости-звонкости согласные даже в сильных позициях.
Всё это наблюдается при общей грамотности, т.е. о незнании правил речи не идёт.
Обычно проявляется либо при рукописном письме, либо при наборе, редко - одновременно. Связано с тем, что в этих случаях задействованы разные психомоторные навыки.
Но общая схема дисфункции состоит в том, что пищущий проговаривает "про себя" текст - и поскольку в описанных случаях возбуждаются одни и те же зоны, происходит смешение сигнала.
Говорю как человек, сам этим расстройством страдающий, по счастью - не в самой сильной степени.
Кстати насчёт "сиводня". Насколько понимаю, такое написание для рассматриваемого синдрома нехарактерно. Скорее уж "секодня". Тут не просто фонетическое соответствие, а сходность психомоторики.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get number of days between two entries with mongodb
I would like to get number of days between my two last entries with mongoDb grouped by number of days. Here is my table :
-------------------------------------------------
| mac address | date |
-------------------------------------------------
| aa:bb:cc:dd:ee:ff | 2016-11-15 |
| aa:bb:cc:dd:ee:ff | 2016-11-19 |
| aa:bb:cc:dd:ee:ff | 2016-11-20 |
| ff:ee:dd:cc:bb:aa | 2016-11-19 |
| ff:ee:dd:cc:bb:aa | 2016-11-28 |
| aa:aa:aa:aa:aa:aa | 2016-11-21 |
| bb:bb:bb:bb:bb:bb | 2016-11-22 |
| bb:bb:bb:bb:bb:bb | 2016-11-25 |
| cc:cc:cc:cc:cc:cc | 2016-11-20 |
| cc:cc:cc:cc:cc:cc | 2016-11-23 |
-------------------------------------------------
And here what I want to get :
-------------------------------------------------
| Number of days | count |
-------------------------------------------------
| 1 day | 1 |
| 2-7 days | 2 |
| 8-30 days | 1 |
| > 30 days | 0 |
-------------------------------------------------
Is there any possibility to do it in one request using mongodb ?
Thanks a lot.
A:
you can do it in a single query with something like this
db.date.aggregate([
{
$sort:{
date:-1
}
},
{
$group:{
_id:"$mac",
date:{
$push:"$date"
}
}
},
{
$project:{
_id:"$mac",
laps:{
$subtract:[
{
$arrayElemAt:[
"$date",
0
]
},
{
$arrayElemAt:[
"$date",
1
]
}
]
}
}
},
{
"$group":{
"_id":null,
"1_day":{
"$sum":{
"$cond":[
{
"$lte":[
"$laps",
(1000 *60 * 60 * 24)
]
},
1,
0
]
}
},
"2_7days":{
"$sum":{
"$cond":[
{
$and:[
{
"$gt":[
"$laps",
(1000 *60 * 60 * 24*2)
]
},
{
"$lte":[
"$laps",
(1000 *60 * 60 * 24*7)
]
},
]
},
1,
0
]
}
},
"8_30days":{
"$sum":{
"$cond":[
{
$and:[
{
"$gt":[
"$laps",
(1000 *60 * 60 * 24*8)
]
},
{
"$lte":[
"$laps",
(1000 *60 * 60 * 24*30)
]
},
]
},
1,
0
]
}
},
"30+days":{
"$sum":{
"$cond":[
{
"$gte":[
"$laps",
(1000 *60 * 60 * 24*30)
]
},
1,
0
]
}
}
}
}
])
it will return somthing like this:
{
"_id":null,
"1_day":1,
"2_7days":3,
"8_30days":0,
"30+days":0
}
you may need to adjust bounds to better fit your needs
try it online: mongoplayground.net/p/JqolUAp2lfk
|
{
"pile_set_name": "StackExchange"
}
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 5