source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"tex.stackexchange",
"0000532555.txt"
] | Q:
posting url in bibliography in overleaf as reference
I have to post a link to this website https://docs.microsoft.com/en-us/cloud-app-security/tutorial-shadow-it
as a reference, I am using in my documentation. I see in my template in overleaf I wrote in the file
BIBeusflat2019.bib
@misc{microsoft,
author =
title =Discover and manage shadow IT in your network
url ="https://docs.microsoft.com/en-us/cloud-app-security/tutorial-shadow-it"
}
but then when I compile the pdf I do not get the url as reference link in pdf . I am using a template here
https://www.overleaf.com/latex/templates/eusflat-2019-template/jmqvcrhkqhgx
So how do I post a link to URL in this case?
A:
Go the .cls file of the template
and change
\RequirePackage{graphicx}
to
\RequirePackage{graphicx, hyperref, url}
this adds the required packages. Now go to the .bib file an add your entry as
@misc{microsoft,
author = {Microsoft},
title = {Discover and manage shadow IT in your network},
howpublished = "\url{https://docs.microsoft.com/en-us/cloud-app-security/tutorial-shadow-it}"
}
now you can cite this ref in your .tex using
\cite{microsoft}
|
[
"stackoverflow",
"0052728601.txt"
] | Q:
Improving a dplyr solution -- Create a variable by conditional ordering (position) based on other information
I'm working on a dataset where every participant (ID) was evaluated 1, 2 or 3 times. It's a longitudinal study. Unfortunately, when the first analyst coded the dataset, she/he did not assign any information about that.
Because all participant have age information (in months), it's easy to identify when was the first evaluation, when was the second and so on. In the first evaluation, the participant was younger than the second and so on.
I used tidyverse tools to deal with that and everything is working. Howerver,I really know (imagine...) there is many other (much more) elegant solution, and I came to this forum to ask for that. Could someone give me thoughts about how to make this code shorter and clear?
This is a fake data to reproduce the code:
ds <- data.frame(id = seq(1:6),
months = round(rnorm(18, mean=12, sd=2),0),
x1 = sample(0:2),
x2 = sample(0:2),
x3 = sample(0:2),
x4 = sample(0:2))
#add how many times each child was acessed
ds <- ds %>% group_by(id) %>% mutate(how_many = n())
#Add position
ds %>% group_by(id) %>%
mutate(first = min(months),
max = max(months),
med = median(months)) -> ds
#add label to the third evaluation (the second will be missing)
ds %>%
mutate(group = case_when((how_many == 3) & (months %in% first) ~ "First evaluation",
(how_many == 3) & (months %in% max) ~ "Third evaluation",
TRUE ~ group)) -> ds
#add label to the second evaluation for all children evaluated two times
ds %>% mutate_at(vars(group), funs(if_else(is.na(.),"Second Evaluation",.))) -> ds
This is my original code:
temp <- dataset %>% select(idind, arm, infant_sex,infant_age_months)
#add how many times each child was acessed
temp <- temp %>% group_by(idind) %>% mutate(how_many = n())
#Add position
temp %>% group_by(idind) %>%
mutate(first = min(infant_age_months),
max = max(infant_age_months),
med = median(infant_age_months)) -> temp
#add label to the first evaluation
temp %>%
mutate(group = case_when(how_many == 1 ~ "First evaluation")) -> temp
#add label to the second evaluation (and keep all previous results)
temp %>%
mutate(group = case_when((how_many == 2) & (infant_age_months %in% first) ~ "First evaluation",
(how_many == 2) & (infant_age_months %in% max) ~ "Second evaluation",
TRUE ~ group)) -> temp
#add label to the third evaluation (the second will be missing)
temp %>%
mutate(group = case_when((how_many == 3) & (infant_age_months %in% first) ~ "First evaluation",
(how_many == 3) & (infant_age_months %in% max) ~ "Third evaluation",
TRUE ~ group)) -> temp
#add label to the second evaluation for all children evaluated two times
temp %>% mutate_at(vars(group), funs(if_else(is.na(.),"Second Evaluation",.))) -> temp
Please, keep in mind I used search box before asking that and I really imagine other people can figure the same question when programing.
Thanks much
A:
There you go. I used rank() to give the order of the treatments.
ds <- data.frame(id = seq(1:6),
months = round(rnorm(18, mean=12, sd=2),0),
x1 = sample(0:2),
x2 = sample(0:2),
x3 = sample(0:2),
x4 = sample(0:2))
ds2 = ds %>% group_by(id) %>% mutate(rank = rank(months,ties.method="first"))
labels = c("First", "Second","Third")
ds2$labels = labels[ds2$rank]
|
[
"serverfault",
"0000199858.txt"
] | Q:
how to find all registry symbolic links?
There is a method to see if a registry key is a symbolic link?
A:
http://www.sepago.de/e/helge/2008/05/04/free-tool-list-registry-links-reglink
|
[
"math.stackexchange",
"0000574580.txt"
] | Q:
Understand a matrix expression
Here is something I read and I didn't understand :
Let $n \in \mathbb{N}^{\ast}$ and $\Gamma$ be a $n \times n$ positive definite matrix. Let $X \in \mathbb{R}^{n}$, $X \neq 0$ and $\big(X, \varepsilon_{2}, \ldots, \varepsilon_{n}\big)$ an orthogonal basis of $\mathbb{R}^{n}$ such that, in this basis, $\Gamma$ writes :
$$\begin{pmatrix} x_{0} & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & S & \\ 0 & & & & \end{pmatrix}$$
Then, the matrix $\Gamma$ is :
$$ \Gamma = x_{0} \frac{X X^\top}{\Vert X \Vert^{2}} + \Big(\mathrm{I}_{n} - \frac{X X^\top}{\Vert X \Vert^{2}} \Big) \begin{pmatrix} \ast & \ast & \ldots & \ast \\ \ast & & & \\ \vdots & & S & \\ \ast & & & & \end{pmatrix} \Big( \mathrm{I}_{n} - \frac{X X^\top}{\Vert X \Vert^{2}} \Big)^\top \tag{$\clubsuit$}$$
where $\ast$ represents some real coefficients.
I don't understand why the expression $(\clubsuit)$ is true. Here is what I tried :
Let $B_{\mathrm{can}}$ be the canonical basis of $\mathbb{R}^{n}$ and $B=\big(X,\varepsilon_{2},\ldots,\varepsilon_{n}\big)$. Let $P$ be the matrix of change of basis from $B_{\mathrm{can}}$ to $B$. Then :
$$ \Gamma = P \begin{pmatrix} x_{0} & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & S & \\ 0 & & & & \end{pmatrix} P^{-1} $$
and :
$$ \frac{X X^\top}{\Vert X \Vert^{2}} = P \begin{pmatrix} 1 & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & \mathbf{0} & \\ 0 & & & & \end{pmatrix} P^{-1} \quad \mathrm{and} \quad \Big(\mathrm{I}_{n} - \frac{X X^\top}{\Vert X \Vert^{2}} \Big) = P \begin{pmatrix} 0 & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & \mathrm{I}_{n-1} & \\ 0 & & & & \end{pmatrix} P^{-1} $$
Therefore, $\Big(\mathrm{I}_{n} - \frac{X X^\top}{\Vert X \Vert^{2}} \Big) \begin{pmatrix} \ast & \ast & \ldots & \ast \\ \ast & & & \\ \vdots & & S & \\ \ast & & & & \end{pmatrix} \Big( \mathrm{I}_{n} - \frac{X X^\top}{\Vert X \Vert^{2}} \Big)^\top$ is equal to :
$$
\begin{eqnarray*}
& & P \begin{pmatrix} 0 & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & \mathrm{I}_{n-1} & \\ 0 & & & & \end{pmatrix} P^{-1} \begin{pmatrix} \ast & \ast & \ldots & \ast \\ \ast & & & \\ \vdots & & S & \\ \ast & & & & \end{pmatrix} P \begin{pmatrix} 0 & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & \mathrm{I}_{n-1} & \\ 0 & & & & \end{pmatrix} P^{-1} \\[3mm]
& = & P \begin{pmatrix} 0 & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & \mathrm{I}_{n-1} & \\ 0 & & & & \end{pmatrix} \begin{pmatrix} \diamond & \diamond & \ldots & \diamond \\ \diamond & & & \\ \vdots & & \tilde{S} & \\ \diamond & & & & \end{pmatrix} \begin{pmatrix} 0 & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & \mathrm{I}_{n-1} & \\ 0 & & & & \end{pmatrix} P^{-1} \\[3mm]
& = & P \begin{pmatrix} 0 & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & \tilde{S} & \\ 0 & & & & \end{pmatrix} P^{-1}
\end{eqnarray*} $$
So, in the end I get :
$$ \Gamma = P \begin{pmatrix} x_{0} & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & \tilde{S} & \\ 0 & & & & \end{pmatrix} P^{-1} $$
which is not the expected expression. Where am I wrong ?
A:
Considering that $(X,\epsilon_2,\dots,\epsilon_n)$ forms an orthogonal basis, we have direct sum decomposition of $V=\mathbb R^n$. We write
$$V=\mathrm{span}\{X\}\oplus\mathrm{span}\{\epsilon_2,\dots,\epsilon_n\}=\mathrm{span}\{X\}\oplus\mathrm{span}\{X\}^\perp$$
It's not hard to write down the projection operator $\mathcal P_X=\frac{XX^T}{||X||^2}$ on subspace $\mathrm{span}\{X\}$ and the rejection operator $\mathcal R_X=I-\mathcal P_X=I-\frac{XX^T}{||X||^2}$. Now the decomposition becomes
$$V=\mathrm{Im}\mathcal P_X\oplus\mathrm{Im}\mathcal R_X$$
Next your question is readily followed by direct computations.
$$\begin{align}&x_0\frac{XX^T}{||X||^2}=x_0\mathcal P_XI_n\\
=&x_0\begin{pmatrix} 1 & 0 \ldots & 0 \\ 0 & & \\ \vdots & \mathbf O_{n-1} \\ 0 & \end{pmatrix}=\begin{pmatrix} x_{0} & 0 & \ldots & 0 \\ 0 & & & \\ \vdots & & \mathbf O_{n-1} \\ 0 & & & \end{pmatrix}\end{align}\\$$
$$\begin{align}&\Big(I_n-\frac{X X^T}{\Vert X \Vert^{2}} \Big) \begin{pmatrix} \ast & \ast & \ldots & \ast \\ \ast & & \\ \vdots & & S \\ \ast & & & \end{pmatrix} \Big(I_n-\frac{X X^\top}{\Vert X \Vert^{2}} \Big)^T\\
=&\mathcal R_X\begin{pmatrix} \ast & \ast & \ldots & \ast \\ \ast & & \\ \vdots & & S \\ \ast & & & \end{pmatrix}\mathcal R_X^T
=\begin{pmatrix} 0 & 0 & \ldots & 0 \\ \ast & & \\ \vdots & & S \\ \ast & & & \end{pmatrix}\mathcal R_X^T\\
=&\begin{pmatrix} 0 & 0 & \ldots & 0 \\ 0 & & \\ \vdots & & S \\ 0 & & & \end{pmatrix}\end{align}$$
Hence
$$\Gamma=x_0\mathcal P_XI_n+\mathcal R_X\tilde S\mathcal R_X^T$$
|
[
"webmasters.stackexchange",
"0000017296.txt"
] | Q:
Google, SEO and 301 redirects on root / top folder
I've got a pretty unusual problem. A client has their site hosted on a friend's server that is basically misconfigured to redirect http://clientname.com/ to http://clientname.com/clientname. After this 301 redirect, the site works fine and subpages can be accessed via http://clientname.com/clientname/subpage.
However, the whole site is not indexed on Google and my FTP root folder resembles http://clientname.com/clientname/ which means I cannot put a robots.txt file on the top level. Moving to a different hoster is out of question for the client.
What can I do? I'm desperate.
A:
If the whole site is not indexed a robots.txt isn't going to help you as that is used to stop the search engines from indexing your content. Not help them do it.
Sign up for a Google Webmaster Tools account and add their site. Then submit an XML sitemap to Google. That will tell them where all of their pages are. Also, get some links to their pages from other sites. That helps the search engines finds them and links can increase the importance of those pages in Google's eyes giving them more incentive to index them.
|
[
"mathematica.stackexchange",
"0000074020.txt"
] | Q:
Center column heading in TableForm
I have a TableForm as follows:
cosine[r_, theta_] := Sqrt[2 r^2 (1 - Cos[theta/360 * 2*Pi])];
rows = Range[1000, 10000, 1000];
cols = Prepend[Range[.5, 2, .5], ""];
TableForm[m, TableHeadings -> {rows, Rest@cols}, TableAlignments -> "."]
which produces:
However, I would like to center the column headings and remove all the trailing decimal points. I have not found any way to center just the column headings while keeping the values decimal/right aligned. I have seen some complicated methods of removing the decimal point by converting the values to a string and then doing string manipulations to remove the decimal point, which seems like a hack to me, so I am hoping there is a straightforward way.
A:
Of OP's two requirements
center the column headings and
remove all the trailing decimal points.
@bbgodfrey's answer addresses the second.
Unfortunately, getting both requirements, i.e.,
to center just the column headings while keeping the values decimal/right aligned.
using TableForm is impossible since TableAlignments is not flexible enough to align individual rows, columns or items separately. That is, aligments can only be specified for each dimension (rows and/or columns), and row (column) headers inherit the alignment settings of the rows (columns). This can be seen by modifying the input matrix m in bbgodfrey's answer:
m = Table[IntegerPart[cosine[r, t]], {r, 1000, 10000, 1000}, {t, 0.5, 2., .5}];
mb = RandomChoice[{1, 100, 10000}] # & /@ m;
rows = 1000 Range[10]; cols = .5 Range[4];
Column[Table[Labeled[Grid[{Table[TableForm[i, TableHeadings -> {rows, cols},
TableAlignments -> j], {i, {m, mb}}]}, ItemSize -> All, Dividers -> All],
Style[TableAlignments -> j, 16], Top], {j, {Right, Center}}], Spacer[15], Dividers -> All]
A work-around is to wrap column headings with Pane or Framed:
TableForm[mb, TableHeadings -> {rows,
Pane[#, ImageSize -> {Scaled[.1], Automatic}, Alignment -> Center] & /@ cols},
TableAlignments -> Right]
Using Grid:
A much more flexible approach is to use Grid. To useGridwe need to add row and column headers to the input matrixmb`. This can be done in a number of ways using any of the methods suggested in this answer to the OP's related question. For example,
hF = Fold[Prepend[Transpose@#, #2] &, #, {#2, Join @@ {{""}, #3}}] &;
mb2 = hF[mb, rows, cols];
Now, we can use Item with the option Alignment->Center to modify the the first row of mb2
mb3 = mb2;
mb3[[1]] = Item[#, Alignment -> Center] & /@ mb3[[1]];
Grid[mb3, Dividers -> {2 -> True, 2 -> True}, Alignment -> Right]
Alternatively, we can use the third element of the Alignment option settings for Grid to set the alignments for the elements in the first row:
Grid[mb2, Dividers -> {2 -> True, 2 -> True},
Alignment -> {Right, Center, MapIndexed[{1, 1 + First@#2} -> Center &, cols]},
ItemStyle -> {{Directive[Red, 20, Italic, "Panel"]}, {Directive[Blue, 20, Italic, "Panel"]}}]
A:
Is this what you had in mind?
cosine[r_, theta_] := Sqrt[2 r^2 (1 - Cos[theta/360*2*Pi])];
m = Table[IntegerPart[cosine[r, t]], {r, 1000, 10000, 1000}, {t, 0.5, 2., .5}];
rows = Range[1000, 10000, 1000];
TableForm[m, TableHeadings -> {rows, {"0.5", "1.0", "1.5", "2.0"}}, TableAlignments -> Right]
Note that m is undefined in your question, but I surmise that my definition is close to what you intended.
|
[
"physics.stackexchange",
"0000458309.txt"
] | Q:
How to distinguish between angular frequency $\omega$ and frequency $f$
The relation between the "regular" frequency $f$ and the angular frequency $\omega$
($\omega = 2\pi f$) is clear to me. However, every time I see "rotations per second" I really get confused as to what is meant there. How do I know whether the author means frequency or angular frequency, if "rotations per minute" can refer to both the frequency of rotations and the angular frequency of rotations as they both have the exact same unit $1 \over s$?
Before you mark this question as a duplicate, I've seen many questions regarding the differences between $f$ and $\omega $ but that's NOT what I'm asking here. I just want to know how to distinguish them when I come across a problem involving rotations and waves.
A:
“Rotations per second” always means regular frequency.
“Radians per second” always means angular frequency.
A “rotation” always means a full rotation, which is through $2\pi$ radians.
|
[
"stackoverflow",
"0003346199.txt"
] | Q:
Is there a way to not use the traditional .config files for ASP.NET?
I find Web.config xml pretty verbose.
Do you know any initiative made in the way to enable cleaner config files, using YAML, or .rb files, anything that could suck less?
EDIT: I already know that FubuMVC web framework, built on top of ASP.NET, tries to reduce a lot the amount of XML you need to put in that file in order to work properly. But it is still pretty ugly, I find it unnecessary:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<authentication mode="None" />
<customErrors mode="RemoteOnly"/>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpModules>
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</httpModules>
<httpHandlers>
</httpHandlers>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4"
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="UrlRoutingModule" />
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>
<handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
</system.webServer>
</configuration>
This is the bare minimum amount of XML you need to make things run, really bad. Many things above could just be the default.
A:
My recommendation would be to leave Web.config alone as much as possible, and split your own configuration settings off into separate files.
e.g.
<connectionStrings configSource="Configs\ConnectionStrings.config"/>
<appSettings configSource="Configs\AppSettings.config"/>
Instead of having your connection strings and app settings inside Web.config.
|
[
"stackoverflow",
"0060872653.txt"
] | Q:
Update Function not returning value correctly
I have two tables that I am concatenating fields from. The first table (tbl1Artwork) primary key (ID), has a data type of AutoNumber and a format of "SA"0000. The second table (tbl0Artist), field (ArtistSKU) is formatted as ShortText. I am running the code shown as an AfterUpdate in a form. The expected result is "SA0008DL1" (the DL1 is concatenated from the ArtistSKU field). The actual result is 8DL1. This is confusing as SA0008 is properly stored in the ID field of table tbl1Artwork.
Option Compare Database
Private Function UpdateArtworkSKU()
Me.ArtworkSKU = Me.txtArtworkID & Me.cboArtistID.Column(3)
End Function
A:
Although you have formatted the primary key field to look like "SA0008", the actual value being stored is just 8. You would therefore need to amend the code to read:
Me.ArtworkSKU = "SA" & Format(Me.txtArtworkID,"0000") & Me.cboArtistID.Column(3)
As an aside, using the primary key when it is an autonumber for anything other than joining data behind the scenes is normally a bad idea.
Regards,
|
[
"stackoverflow",
"0047065739.txt"
] | Q:
How to calculate anomalies of Geopotential Height in Matlab?
I am interested in calculating GPH anomalies in Matlab. I have a 3D matrix of lat, lon, and time. Where time is a daily GPH value for 32 years (1979-2010). The matrix is 95x38x11689. How do I compute a daily average across all years for each day of data, when the matrix is 3D?
I am ultimately trying to compute the GPH anomaly from the difference of the daily value and the climatological mean of that given day.
In other words, how do I compute the average of Jan. 1st dates for all years to compute the climatological mean of all Jan. 1st's from 1979-2010? And so forth for each day after. The data also includes leap years. How do I handle that?
Thanks!
UPDATE: The 3rd dimension is the GPH data NOT time. It's just the data for every day time step from 1979 to 2011.
A:
Try something like this:
%Using your dimensions make up some fake data
GPH = rand(95,38,11689)
%Get an index into the 3rd dimension for your desired dates
dateIdx = datenum(1979:2010,1,1)-datenum(1979,1,1) + 1;
%Take the mean along the 3rd dimensions
mean_of_all_Jan_1 = mean(GPH(:,:,dateIdx ),3);
An example of getting another arbitrary date say every March 15th. Note that I only changed the first call to datenum and not the second.
dateIdx = datenum(1979:2010,3,15)-datenum(1979,1,1) + 1;
mean_of_all_March_15 = mean(GPH(:,:,dateIdx ),3);
I am assuming that along the 3rd dimension index 1 is Jan 1 1979 & progresses at 1 index per day.
EDIT to get every day
This will return a dailyMeanGPH that is 95x38x366. Such that dailyMeanGPH(:,:,1) is the mean for every Jan 1st, dailyMeanGPH(:,:,2) = Jan 2nd ...
Note that for Feb 29th there will be less days averaged since it will occur 1/4th as often.
Alternative you if comment/uncomment the lines noted in the code below your output can be returned in a cell array. That way if you wanted Jan 1 mean you would do dailyMeanGPH{1,1} then Jan 2nd dailyMeanGPH{1,2} etc. Where the index into the cell is {month,day} of interest.
function dailyMeanGPH = getDailyMeanGPH(GPH)
daysInMonth = [31 29 31 30 31 30 31 31 30 31 30 31]; %inlcude 29 for Feb
dailyMeanGPH = zeros(size(GPH,1),size(GPH,2),sum(daysInMonth)); %COMMENT OUT IF YOU WNAT OUTPUT IN CELL
% dailyMeanGPH = cell(12,31); %UNCOMMENT IF YOU WANT OUTPUT IN CELL
k = 1;
for m = 1:12
for d = 1:daysInMonth(m)
%Get an index into the 3rd dimension for your desired dates
dateIdx = datenum(1979:2010,m,d)-datenum(1979,1,1) + 1;
if m==2 && d ==29 %Purge Feb 29 from non-leap years.
checkIdx = datenum(1979:2010,3,1)-datenum(1979,1,1) + 1;
dateIdx = setdiff(dateIdx,checkIdx);
end
%Take the mean along the 3rd dimensions.
dailyMeanGPH(:,:,k) = mean(GPH(:,:,dateIdx ),3);%COMMENT OUT IF YOU WNAT OUTPUT IN CELL
k = k+1;
% dailyMeanGPH{m,d} = mean(GPH(:,:,dateIdx ),3);%UNCOMMENT IF YOU WANT OUTPUT IN CELL
end
end
|
[
"stackoverflow",
"0011669945.txt"
] | Q:
R : Tick data adding value when tick data is missing
I'm working on tick data and want to aggregate my xts irregularly spaced series into a 1 second homogeneous one. I thus use the xts package function to.period :
price_1m <-to.period(price,period="seconds",k=1,OHLC=FALSE)
here is what I get :
2010-02-02 08:00:03 2787
2010-02-02 08:00:04 2786
2010-02-02 08:00:05 2787
2010-02-02 08:00:06 2787
2010-02-02 08:00:07 2786
2010-02-02 08:00:08 2786
2010-02-02 08:00:09 2786
2010-02-02 08:00:10 2787
2010-02-02 08:00:11 2786
2010-02-02 08:00:14 2786
2010-02-02 08:00:16 2786
2010-02-02 08:00:18 2787
My series is aggregated but for example tick data is missing at times 08:00:13 and 08:00:15. What I want is to fill those blanks with previous tick data knowing that the 08:00:13 and 08:00:15 prices are missing in the tick-by-tick xts series.
Any idea?
thanks
A:
You can merge price_1m with an "empty" xts object that contains an index with the regularly-spaced intervals you want, use na.locf on that. For example:
onemin <- seq(start(price_1m),end(price_1m),by="1 s")
Price_1m <- na.locf(merge(price_1m, xts(,onemin)))
|
[
"tex.stackexchange",
"0000111672.txt"
] | Q:
In LyX with classicthesis.sty, cross-references to Chapters don't work
I am using classicthesis with some minor (I think) edits.
I have child documents for each chapter. Everything renders fine apart from cross references to chapters which pdflatex renders as ??
A:
I add the same problem but I find a way to make it working.
Let's say I have :
Chapter 3
Test of chapter
If I put the label here :
Chapter 3
Test of chapterLABEL
it doesn't work.
But, putting it here :
Chapter 3
LABELTest of chapter
seems ok.
Hope it will help.
Nico
|
[
"serverfault",
"0000443339.txt"
] | Q:
Azure load-balancing strategy
I'm currently building out a small web deployment using VM instances on MS Azure. The main problem I'm facing at the moment is trying to figure out how to get the load-balancing to detect if a particular VM has failed and not route traffic to that VM.
As far as I can tell, there are only only two load-balancing options:
Have multiple VMs (web01, web02, web03 etc.) within the same 'cloud service' behind a single VIP, and configure the endpoints to be load balanced.
Create multiple 'cloud services', put a single web VM in each and create a traffic manager service across all these services.
It appears that (1) is extremely simplistic and doesn't attempt to do any host failure detection.
(2) appears to be much more varied, but requires me to put all my webservers in their own individual cloud service. Traffic manager appears to be much more directed at a geographic failover scenario, where you have multiple cloud services across different regions. This approach also has the disadvantage in that my web servers won't be able to communicate with my databases on internal IP addresses, unlike scenario (1).
What's the best approach here?
A:
Each cloud service VM has a Guest Agent (GA) installed which monitors the health of the VM. If a GA fails to respond, the Fabfic Controller (FC) will reboot the VM. In the case of hardware failure, the FC will move the role instance to a new hardware node and reprograms the network configuration for the service role instances to restore the service to full availability.
Edit: Guest Agents are only used on PaaS. IaaS (your VMs on Azure) do not have Guest Agents.
|
[
"stackoverflow",
"0048835626.txt"
] | Q:
Mongodb aggregation filter lookup on parent property
Given an object like this, how can I make it lookup users info only if the isAnonymous field is false?
{
"_id" : ObjectId(""),
"user" : ObjectId(""),
"title" : "This is an idea",
"shortDescription" : "Pretty cool stuff",
"downVoteCount" : NumberInt(0),
"upVoteCount" : NumberInt(12),
"voteTotalCount" : NumberInt(12),
"deleted" : false,
"ideaNumber" : NumberInt(5),
"isAnonymous" : false,
"created" : ISODate("2018-01-19T23:37:10.949+0000")
}
Here is my current query:
db.ideas.aggregate(
{
$match: { "deleted": false }
},
{
$lookup: {
"from" : "users",
"localField" : "user",
"foreignField" : "_id",
"as" : "user"
}
},
{
$unwind: {
path : "$user",
includeArrayIndex : "arrayIndex", // optional
preserveNullAndEmptyArrays : false // optional
}
},
{
$project: {
"ideaNumber": 1,
"title": 1,
"isAnonymous": 1,
"shortDescription": 1,
"upVoteCount": 1,
"created": 1,
"user.email": 1,
"user.name": 1,
"user.createdAt": 1
}
},
);
Yields an object like this:
{
"_id" : ObjectId(""),
"user" : {
"createdAt" : ISODate("2018-01-19T21:50:02.758+0000"),
"email" : "blah",
"name" : "Foo Bar"
},
"title" : "This is an idea",
"shortDescription" : "Pretty cool stuff",
"upVoteCount" : NumberInt(12),
"ideaNumber" : NumberInt(5),
"isAnonymous" : false,
"created" : ISODate("2018-01-19T23:37:10.949+0000")
}
I'd like to see the object like this instead
{
"_id" : ObjectId(""),
"user" : {
"createdAt" : "anonymous",
"email" : "anonymous",
"name" : "anonymous"
},
"title" : "This is an idea",
"shortDescription" : "Pretty cool stuff",
"upVoteCount" : NumberInt(12),
"ideaNumber" : NumberInt(5),
"isAnonymous" : false,
"created" : ISODate("2018-01-19T23:37:10.949+0000")
}
A:
Indeed you can use conditionals in aggregation pipeline to alter projection.
Following query should project in desired format.
db.T.aggregate([
{
$match: { "deleted": false }
},
{
$lookup: {
"from" : "users",
"localField" : "user",
"foreignField" : "_id",
"as" : "user"
}
},
{
$unwind: {
path : "$user",
includeArrayIndex : "arrayIndex", // optional
preserveNullAndEmptyArrays : false // optional
}
},
{
$project:{
"ideaNumber": 1,
"title": 1,
"isAnonymous": 1,
"shortDescription": 1,
"upVoteCount": 1,
"created": 1,
user : {$cond: [{$eq:["$isAnonymous", true]},
{
"createdAt" : "anonymous",
"email" : "anonymous",
"name" : "anonymous"
},
{
"createdAt" : "$user.createdAt",
"email" : "$user.email",
"name" : "$user.name"
}]}
}
}]);
Above query leads to result as:
{
"_id" : ObjectId("5a876fae304c013cbf854766"),
"title" : "This is an idea",
"shortDescription" : "Pretty cool stuff",
"upVoteCount" : NumberInt(12),
"ideaNumber" : NumberInt(5),
"isAnonymous" : false,
"created" : ISODate("2018-01-19T23:37:10.949+0000"),
"user" : {
"createdAt" : ISODate("2018-01-19T23:37:10.949+0000"),
"email" : "[email protected]",
"name" : "user A"
}
}
|
[
"stackoverflow",
"0021405457.txt"
] | Q:
Autoincrement VersionCode with gradle extra properties
I'm building an Android app with gradle. Until now I used the Manifest file to increase the versionCode, but I would like to read the versionCode from an external file and depending if it is the release flavor or the debug flavor increase the versionCode. I tried the extra properties, but you can't save them, which means that next time I build it I'm getting the same versionCode.
Any help would be very much appreciated!
project.ext{
devVersionCode = 13
releaseVersionCode = 1
}
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
dependencies {
compile project(':Cropper')
compile "com.android.support:appcompat-v7:18.0.+"
compile "com.android.support:support-v4:18.0.+"
compile fileTree(dir: 'libs', include: '*.jar')
}
def getReleaseVersionCode() {
def version = project.releaseVersionCode + 1
project.releaseVersionCode = version
println sprintf("Returning version %d", version)
return version
}
def getDevVersionCode() {
def version = project.devVersionCode + 1
project.devVersionCode = version
println sprintf("Returning version %d", version)
return version
}
def getLastVersioName(versionCode) {
return "0.0." + versionCode
}
android {
compileSdkVersion 19
buildToolsVersion "19.0.0"
defaultConfig {
minSdkVersion 9
targetSdkVersion 19
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
buildTypes {
release {
runProguard true
proguardFile getDefaultProguardFile('proguard-android-optimize.txt')
proguardFile 'proguard.cfg'
debuggable false
signingConfig null
zipAlign false
}
debug {
versionNameSuffix "-DEBUG"
}
}
productFlavors {
dev {
packageName = 'com.swisscom.docsafe.debug'
versionCode getDevVersionCode()
versionName getLastVersioName(project.devVersionCode)
}
prod {
packageName = 'com.swisscom.docsafe'
versionCode getReleaseVersionCode()
versionName getLastVersioName(project.releaseVersionCode)
}
}
}
task wrapper(type: Wrapper) {
gradleVersion = '1.8'
}
A:
I would like to read the versionCode from an external file
I am sure that there are any number of possible solutions; here is one:
android {
compileSdkVersion 18
buildToolsVersion "18.1.0"
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def code = versionProps['VERSION_CODE'].toInteger() + 1
versionProps['VERSION_CODE']=code.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
versionCode code
versionName "1.1"
minSdkVersion 14
targetSdkVersion 18
}
}
else {
throw new GradleException("Could not read version.properties!")
}
// rest of android block goes here
}
This code expects an existing version.properties file, which you would create by hand before the first build to have VERSION_CODE=8.
This code simply bumps the version code on each build -- you would need to extend the technique to handle your per-flavor version code.
You can see the Versioning sample project that demonstrates this code.
A:
Here comes a modernization of my previous answer which can be seen below. This one is running with Gradle 4.4 and Android Studio 3.1.1.
What this script does:
Creates a version.properties file if none exists (up vote Paul Cantrell's answer below, which is where I got the idea from if you like this answer)
For each build, debug release or any time you press the run button in Android Studio the VERSION_BUILD number increases.
Every time you assemble a release your Android versionCode for the play store increases and your patch number increases.
Bonus: After the build is done copies your apk to projectDir/apk to make it more accessible.
This script will create a version number which looks like v1.3.4 (123) and build an apk file like AppName-v1.3.4.apk.
Major version ⌄ ⌄ Build version
v1.3.4 (123)
Minor version ⌃|⌃ Patch version
Major version: Has to be changed manually for bigger changes.
Minor version: Has to be changed manually for slightly less big changes.
Patch version: Increases when running gradle assembleRelease
Build version: Increases every build
Version Number: Same as Patch version, this is for the version code which Play Store needs to have increased for each new apk upload.
Just change the content in the comments labeled 1 - 3 below and the script should do the rest. :)
android {
compileSdkVersion 27
buildToolsVersion '27.0.3'
def versionPropsFile = file('version.properties')
def value = 0
Properties versionProps = new Properties()
if (!versionPropsFile.exists()) {
versionProps['VERSION_PATCH'] = "0"
versionProps['VERSION_NUMBER'] = "0"
versionProps['VERSION_BUILD'] = "-1" // I set it to minus one so the first build is 0 which isn't super important.
versionProps.store(versionPropsFile.newWriter(), null)
}
def runTasks = gradle.startParameter.taskNames
if ('assembleRelease' in runTasks) {
value = 1
}
def mVersionName = ""
def mFileName = ""
if (versionPropsFile.canRead()) {
versionProps.load(new FileInputStream(versionPropsFile))
versionProps['VERSION_PATCH'] = (versionProps['VERSION_PATCH'].toInteger() + value).toString()
versionProps['VERSION_NUMBER'] = (versionProps['VERSION_NUMBER'].toInteger() + value).toString()
versionProps['VERSION_BUILD'] = (versionProps['VERSION_BUILD'].toInteger() + 1).toString()
versionProps.store(versionPropsFile.newWriter(), null)
// 1: change major and minor version here
mVersionName = "v1.0.${versionProps['VERSION_PATCH']}"
// 2: change AppName for your app name
mFileName = "AppName-${mVersionName}.apk"
defaultConfig {
minSdkVersion 21
targetSdkVersion 27
applicationId "com.example.appname" // 3: change to your package name
versionCode versionProps['VERSION_NUMBER'].toInteger()
versionName "${mVersionName} Build: ${versionProps['VERSION_BUILD']}"
}
} else {
throw new FileNotFoundException("Could not read version.properties!")
}
if ('assembleRelease' in runTasks) {
applicationVariants.all { variant ->
variant.outputs.all { output ->
if (output.outputFile != null && output.outputFile.name.endsWith('.apk')) {
outputFileName = mFileName
}
}
}
}
task copyApkFiles(type: Copy){
from 'build/outputs/apk/release'
into '../apk'
include mFileName
}
afterEvaluate {
assembleRelease.doLast {
tasks.copyApkFiles.execute()
}
}
signingConfigs {
...
}
buildTypes {
...
}
}
====================================================
INITIAL ANSWER:
I want the versionName to increase automatically as well. So this is just an addition to the answer by CommonsWare which worked perfectly for me. This is what works for me
defaultConfig {
versionCode code
versionName "1.1." + code
minSdkVersion 14
targetSdkVersion 18
}
EDIT:
As I am a bit lazy I want my versioning to work as automatically as possible. What I want is to have a Build Version that increases with each build, while the Version Number and Version Name only increases when I make a release build.
This is what I have been using for the past year, the basics are from CommonsWare's answer and my previous answer, plus some more. This results in the following versioning:
Version Name: 1.0.5 (123) --> Major.Minor.Patch (Build), Major and Minor are changed manually.
In build.gradle:
...
android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def value = 0
def runTasks = gradle.startParameter.taskNames
if ('assemble' in runTasks || 'assembleRelease' in runTasks || 'aR' in runTasks) {
value = 1;
}
def versionMajor = 1
def versionMinor = 0
def versionPatch = versionProps['VERSION_PATCH'].toInteger() + value
def versionBuild = versionProps['VERSION_BUILD'].toInteger() + 1
def versionNumber = versionProps['VERSION_NUMBER'].toInteger() + value
versionProps['VERSION_PATCH'] = versionPatch.toString()
versionProps['VERSION_BUILD'] = versionBuild.toString()
versionProps['VERSION_NUMBER'] = versionNumber.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
versionCode versionNumber
versionName "${versionMajor}.${versionMinor}.${versionPatch} (${versionBuild}) Release"
minSdkVersion 14
targetSdkVersion 23
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def fileNaming = "apk/RELEASES"
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
output.outputFile = new File(getProject().getRootDir(), "${fileNaming}-${versionMajor}.${versionMinor}.${versionPatch}-${outputFile.name}")
}
}
}
}
} else {
throw new GradleException("Could not read version.properties!")
}
...
}
...
Patch and versionCode is increased if you assemble your project through the terminal with 'assemble', 'assembleRelease' or 'aR' which creates a new folder in your project root called apk/RELEASE so you don't have to look through build/outputs/more/more/more to find your apk.
Your version properties would need to look like this:
VERSION_NUMBER=1
VERSION_BUILD=645
VERSION_PATCH=1
Obviously start with 0. :)
A:
A slightly tightened-up version of CommonsWare's excellent answer creates the version file if it doesn't exist:
def Properties versionProps = new Properties()
def versionPropsFile = file('version.properties')
if(versionPropsFile.exists())
versionProps.load(new FileInputStream(versionPropsFile))
def code = (versionProps['VERSION_CODE'] ?: "0").toInteger() + 1
versionProps['VERSION_CODE'] = code.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
versionCode code
versionName "1.1"
minSdkVersion 14
targetSdkVersion 18
}
|
[
"meta.stackexchange",
"0000087739.txt"
] | Q:
Clarification regarding cross-posting rules
I asked one question over on skeptics.stackexchange.com about empirical evidence for programmer productivity. One user then prompted me that I'd have more luck over on programmers.stackexchange.com, so I cross posted there as it clearly fits both sites.
I thought until very recently that it's not encouraged to cross post until Robert Cartaino stated:
There is no concept of closing as a duplicate on another site. Each site is autonomous. This is a rare case of where the question might actually be appropriate on BOTH sites-- one set of answer from the point of view of an expert on the subject, the other from a skeptic challenging the science.
Which seem to say that each site is autonomous and there are cases where one question might be appropriate on both sites such as the question on skeptics.SE Is stretching beneficial after exercise? and the question over on fitness.SE Should I stretch after exercise?.
So I referenced the above reason for cross posting when I was challenged by moderator ChrisF on programmers.SE. Then later moterator Sklivvz over on skeptics.SE challenged me linking to an older statement by Jeff Atwood that says this is probably not okay and that you should ask, delete and re-ask questions, citing that it's a slippery slope to allow such a thing:
Allowing cross-posting is a slippery slope.
If you might have slightly better odds of getting an answer by posting it on two sites, well, by gum, why not maximize your odds by posting it on twenty sites!
There are some questions which fall into grey areas between sites, and I think it's OK to ask and delete, then re-ask if you feel you have asked on the wrong site.
But as a general rule, do not cross-post questions, please. Pick a site and go with it.
I'd like to point out that I did pick one site first and only cross-posted when prompted. Is it acceptable in this case to cross point, and what is the rule in general? Perhaps the greater Stack Exchange community could benefit from examples of when it's appropriate (if ever) and when it's not. Most relevant to my case Jeff Atwood recently said:
It is considered outright abuse to copy and paste questions across the network.
If you tailor your question to adapt it to the different audiences on a site -- and genuinely make an effort to to so -- then it can be allowed. But copying and pasting is indefensible.
And Robert Cartino said:
There are somewhat rare cases where you may benefit by asking different groups of users a similar question, because the context of their expertise will provide a different perspective.
But if you are asking the same question of two different groups simply to reach a larger audience, I would frown upon that. Ask the question first on the site you feel will most likely provide the best answer. If you do not receive an adequate answer, then it might be okay to ask your question again to another group of users — as long as the question is on topic and appropriate for that second site.
But cutting-and-pasting between two sites is never okay. If you want a different perspective, you should phrase the question specifically for that group.
A:
I think it's pretty clear when cross-posting is becoming abusive.
If you are posting to two sites because you're not sure which site is more on-topic, that will sort itself out naturally, via the usual close mechanisms. It will either get closed on one or both sites, or it will not, in which case it apparently is on-topic for both sites.
If you are posting on twenty sites to maximize your odds, then you are clearly a spammer, and should receive the spammer treatment. Common sense rules here.
Robert Cartaino is right; there's no concept of closing as a duplicate on another site. Down that road lies madness.
|
[
"stackoverflow",
"0022358998.txt"
] | Q:
Video with timed image overlay
I was wondering if anyone could help me with HTML5 video with image overlays that are timed. I want the images to display and disappear at certain times, which will make the video pause and resume on the click of a button. I want to know the best approach to this in regards using HTML5, javascript etc.
I am using the video tag in HTML5 with Dreamweaver CS6 at the moment and I have full screen video working, with an image overlaid using the z-index, but I can't get it to display and disappear at a certain time.
Any ideas?
A:
probably you have to add some event listener to your video:
timeupdate , loadstart, ect to manage the visibility of your image in overlay
|
[
"judaism.stackexchange",
"0000094339.txt"
] | Q:
Sheilos U'Tshuvos on Gemara
I'm preparing classes on the beginning of Bava Metziah and I would like to present the information through the lens of the Rabbonim that used the Gemara to answer Sheilos. Does anyone know of a Sefer that compiles Sheilos U'Tshuvos through that lens?
A:
I don't know if any of these three is exactly what you are looking for, but I'm sure that they would be extremely helpful for your purposes.
A Sefer that often quotes various Teshuvos and their explanations of the Gemara is Daf Al Hadaf (edited by R. David Abraham Mendelbaum, R. Joshua Lefkowitz, and R. Abraham Noah haLevi Klein).
A list of Shu"t organized in the order of the Gemara, although not necessarily quoting from earlier sources, is Chashukei Chemed, by Rav Yitzchak Zilberstein.
As DoubleAA mentioned above, for Bava Metzia, you have the Frankel Raza Deshabsi, which is an index of a huge amount of Jewish literature, including Shu"t, organized according to the Gemara.
A:
Hebrewbooks.org is available to everyone who is on the web. When you open the 'shas' tab, There a Sefer on the mefarshim list called שדה צופים which quotes many Sheilos Uteshuvos the likes of the Radvaz, Chavos Yair, Rambam and many more. I was recently learning Nazir which has very little Mefarshim and I found a wealth of information from the above which I quoted on the daf, absolutely recommend.
Thanks to wfb, here is the PDF on Bava Metzia.
A:
A popular set of seffarim written explicitly for this purpose is שערים מצויינים בהלכה by Rabbi Shlomo Zalman Brown.
His son Rabbi Chaim Elazar finished off many of the Tractates that his father left in manuscript form. The volume on Bava Metzia was one of those.
|
[
"stackoverflow",
"0039347856.txt"
] | Q:
Remove gradient when color is less than 50%
I made a program that generates a HTML document with divs that have 2 background colors, based on some numerical values. I found out about linear-gradient, and my code looks like this:
div {
width: 100%;
height: 5%;
}
<div style="background: linear-gradient(to right, red 40%, green 60%);">.</div>
<div style="background: linear-gradient(to right, red 60%, green 40%);">.</div>
How should I rewrite my code so I can get rid of that gradient look when red is below 50%? I don't want to make 2 different div for each color, and I guess that linear-gradient it's not the best solution for me. I want all my divs to look like the second one, regardless of the percentage of colors.
A:
The percentage isn't the space that the color occupy, is the position of each color in the element. You have to set the same percentaje in the two colors to get a solid colors:
div {
width: 100%;
height: 5%;
}
<div style="background: linear-gradient(to right, red 40%, green 40%);">.</div>
<div style="background: linear-gradient(to right, red 50%, green 50%);">.</div>
<div style="background: linear-gradient(to right, red 30%, green 30% ,green 60%, blue 60%);">.</div>
|
[
"stackoverflow",
"0027206758.txt"
] | Q:
Export multiple Lotus Notes Documents to RTF
in Notes after opening a document I am able to Export it as RTF via File -> Export -> As RTF.
If I mark multiple documents instead of opening one after another that option is missing.
Is there any way to call the internal Export function with a Notes Agent?
I know about this Export script but the built-in function is a lot better.
A:
Considering that it's a repetitive task and you don't want to use that script to export the documents, I would suggest an outside-the-box solution: you can use a software like AutoHotkey to simulate the keystrokes and clicks.
You will have to write the macro but it should work. I use it myself to do similar tasks as replicate a Lotus Notes app (Key Alt + F, Key R, Key R, wait, Keys SERVER03, wait, Enter, wait, Enter)
|
[
"academia.stackexchange",
"0000116589.txt"
] | Q:
What's the point in waiting 6 or 12 months before allowing researchers to make their Belgium-funded article open access?
Belgium recently passed a law allowing researchers to make any of their article open access if the majority of the research funding came from Belgium public funding
Here is the law:
Art. 29. Dans l’article XI.196 du même Code, inséré par la loi du
19 avril 2014, il est inséré un paragraphe 2/1 rédigé comme suit:
“§ 2/1. L’auteur d’un article scientifique issu d’une recherche
financée pour au moins la moitié par des fonds publics conserve, même
si, conformément à l’article XI.167, il a cédé ses droits à un éditeur d’un
périodique ou les a placés sous une licence simple ou exclusive, le droit
de mettre le manuscrit gratuitement à la disposition du public en libre
accès après un délai de douze mois pour les sciences humaines et
sociales et six mois pour les autres sciences, après la première
publication, dans un périodique, moyennant mention de la source de la
première publication.
Le contrat d’édition peut prévoir un délai plus court que celui fixé à
l’alinéa 1er.
Le Roi peut prolonger le délai fixé à l’alinéa 1er.
Il ne peut être renoncé au droit prévu à l’alinéa 1er. Ce droit est
impératif et est d’application nonobstant le droit choisi par les parties
dès lors qu’un point de rattachement est localisé en Belgique. Il
s’applique également aux œuvres créées avant l’entrée en vigueur de ce
paragraphe et non tombées dans le domaine public à ce moment.”.
Google translate:
"§ 2/1. The author of a scientific article from a research
financed for at least half by public funds, even
if, in accordance with Article XI.167, he has assigned his rights to a publisher of a
periodical or has placed them under a single or exclusive license, the right
to make the manuscript freely available to the public for free
access after twelve months for the humanities and social sciences
and six months for other sciences, after the first
publication in a periodical, subject to mentioning the source of the
first publication.
The publishing contract may provide for a shorter period than that set
paragraph 1.
The King may extend the period laid down in paragraph 1.
The right provided for in paragraph 1 can not be waived. This right is
imperative and applies notwithstanding the law chosen by the parties
since a point of attachment is located in Belgium. he
also applies to works created before the entry into force of this
paragraph and not fallen into the public domain at that time. "
What's the point in waiting 6 or 12 months before allowing researchers to make their Belgium-funded article open access?
A:
I think you are reading this wrong. It's not that you are not allowed to make something open access before this time span, it's that you have to after it when public money has been used. This is called Delayed Open Access (thanks to Anyon, who mentions this in a comment).
Specifically note that the journal is free to open up the paper earlier:
The publishing contract may provide for a shorter period than that set paragraph 1.
(for instance, if you paid the open access fee). I think the most salient point is this:
The right provided for in paragraph 1 can not be waived.
That is, you cannot sign a copyright transfer to a closed-access journal that gives them the right to not make it open access even after the closing period is over.
If you are asking why they don't require immediate open access, you are back at Najib's answer - publishing is a business, and presumably the Belgian legislation has decided that Delayed Open Access is an acceptable compromise between the publisher's interests and the public's interest in free access to scientific information.
A:
Because publishers lobby governments too. If the rule had been immediate open access, this would have had the potential of wrecking commercial publishers' margins. Who would subscribe to expensive journals when all the papers are open access anyway?
But note that this will soon be obsolete thanks to the new EU-wide "Plan S", which requires full and immediate open access (among other things, such as authors retaining copyright on what they have written). The plan is slated to come into effect in 2020. See https://www.scienceeurope.org/coalition-s/
(However, Belgium is not yet part of the plan. But the ERC is, so all EU-funded projects will have to apply the rules above. And it's not unlikely that the Belgian funding agencies would join the plan too. If I had to guess, I would say that the Belgian agencies aren't part of the plan yet because there are several of them and it was harder to coordinate a simultaneous press release.)
A:
Requiring open access after some period of time is a compromise.
On one hand, the government wants research done using public money to be public. I.e., taxpayer-funded research should be open access. The argument is that it's unfair to require taxpayers to pay a third party to view things that they have already paid for with their taxes. It's the same spirt as freedom of information laws.
On the other hand, publishers want people to pay to see "their" articles. They want to profit from the publishing of science and they have a lot of power by owning established journals.
So the compromise is to give publishers a fixed period of time to profit and then require it to be open access.
Note that this compromise is "future-proof". If the government later decides to demand immediate open access for research it funds, then within 6-12 months all prior work is also open access, so everything is open access. This overcomes one of the big challenges for the open access movement -- university libraries may be obliged to continue subscriptions to journals to retain access to decades-old research even if all the recent research in the area is available on arxiv.
|
[
"stackoverflow",
"0037808677.txt"
] | Q:
Web security: reasons to not display row ID
Question. Is it bad for security to display a database table row ID for all users? If so, why?
Background. I am thinking of using the database table row ID in my application url, like this: www.mysite.com/product/45/tshirt_blue, where 45 is the row ID. I get the feeling this is bad for security, but I keep wondering why?
A:
Referencing the primary key from your database poses a few issues, both in the security realm and the maintainability realm.
Security: Referencing your row id directly can make it quite easy to guess other products, and possibly bypass Authorization checks (AuthZ). While you should never rely on security through obscurity to protect a system, that does not mean you have to leave instructions for regression testing your AuthZ controls all over your web app.
Maintainability: If you ever plan to have a logical entity, "Blue Seahawks T-shirt" be the same logical product, but a different db entry, 45 -> 145 for instance, this will be difficult to maintain. All links to that product will now be changed, and bookmarks and possibly search engines will be broken, unless you always map 45 -> 145, and then something else down the road. Having an intermediary ID of some sort that you map to the appropriate DB entry in the background will allow your links to be consistent.
|
[
"stackoverflow",
"0012364233.txt"
] | Q:
ASP.NET MVC, display text just next to the Text Box
How can I display a text just next to the Text Box using jQuery, like if Name is not entered in the Form, so after clicking the Submit Button it will show the Text just next to the Name Text Box and I don't want to use the validation for this, I am checking the Text Box value using simple jQuery coding..?
Here is my Code..
$('#btnAddContact').click(function () {
if ($("#name").val().length <= 0) {
$("#name").val("");
$("#name").focus();
});
A:
Will add a new div after the name if it do not exist.
$('#btnAddContact').click(function () {
var msg = $('#name-message');
if (msg.length == 0) {
msg = $('<div id="name-message"></div>')
$('#name').after(msg);
}
msg.html('Opps. Error!');
});
|
[
"stackoverflow",
"0028644467.txt"
] | Q:
Check if the input matches the data in mySQL
I have 2 inputs.
<input maxlength="40" type="text" style="width:250px;height:50px;font- size:20px;margin: 0 auto;margin-top:5px;" name="usernameInput" />
<input maxlength="40" type="text" style="width:250px;height:50px;font-size:20px;margin: 0 auto;margin-top:5px;" name="passwordInput" />
<input type="submit" />
And I have a mySQL database called log.
In log I have username and password.
What I want to do is that when a person tries to "login" then php checks if the username matches the input and then checks if in the same row the password matches the input.
How do I do it?
A:
The simple thing is that you're going to have to search this up. There are many, many articles on how to get something from a MySQL database using PHP. Once you know how to retrieve something from a database, look up how to get things from POST.
Once you know that, there should be no problem for you to find this out for yourself.
|
[
"cs.stackexchange",
"0000022725.txt"
] | Q:
Merge-by-weight to solve reachability problems in trees and DAGs
Let $T = (V, E)$ be a tree with a designated root $r \in V$. The fact that the tree is rooted allows us to speak of "subtrees of $T$ rooted at some node $x \in V$". Let's say we have a (not necessarily injective) function $c: V \rightarrow \mathbb{N}$ that assigns a color to every node.
We want to find for every node $x \in V$ the number of distinct colors in the subtree rooted at $x$. So if $A(x)$ is the set of children of $x$, we want to find for every node $x$, the cardinality of the set
$S(x) = \bigcup_{y\in A(x)} S(y) \cup \{c(x)\}$
There is a rather simple algorithm that solves this problem offline in $O(n \log^2 n)$:
Process the nodes in depth-first order
Represent the sets $S(x)$ as a persistent, self-balancing binary search trees
For every node $x$, let $y \in A(x)$ be the child of $x$ that maximizes $|S(y)|$. Now we just merge for every other child $z \in A(x) \setminus {y}$ the set $S(z)$ into the set $S(y)$ via insertion. We also insert $c(x)$ and now have $S(x)$ as a binary search tree and can give the answer for node $x$
We can even avoid the persistent trees by mutating the subresult for the heaviest child instead of creating a new set.
The typical argument I have seen to justify the bound is the following:
A "move" consist of taking an element from a set and inserting it in another set.
Let's prove that there's at most $O(n \log n)$ moves, each move can be done in $O(\log n)$, the total complexity is $O(n \log^2 n)$.
When you are merging two sets you move all elements from smaller set (assume its size is $k$) to the bigger one, so every element in the smaller set now is in a set with at least size $2k$. In other words every element that has been moved $t$ times is in a set with at least size $2^t$, thus every element will be moved at most $O(\log n)$ and we have $n$ elements so in total there will be at most $O(n \log n)$ move operations.
(Quote from a Codeforces comment).
While this is a beautiful argument, it's not quite correct, because usually we remove duplicates, so sets don't in fact grow exponentially (for example if every node has the same color).
I am convinced that the bound holds, because I can prove it using structural induction. What I want to know is the following:
Is there a way to prove the $O(n \log^2 n)$ bound using an argument similar to the above, by bounding the number of "moves" of the color of a node? In other words, can the proof be "fixed" easily?
The argument from above would also hold in DAGs, not only in trees. However it seems unlikely that we could achieve a runtime better than $O(n \cdot m)$ to solve this problem in a DAG, so I guess there is no fix for the proof idea in this case. Am I right? Is there a good intuition for that?
A:
There are two (equivalent) ways to fix the argument:
Start by not eliminating duplicates. Then the argument works. Then argue that removing duplicates can only decrease the running time.
Count elements with multiplicity, that is, consider each set $S(x)$ as a multiset.
Both of these arguments require a slight modification of the algorithm: for each vertex $x$, you keep track of the size of the subtree, and use this to select the heaviest child rather than the number of distinct colors.
This argument breaks down for a DAG since a vertex can have multiple parents.
|
[
"arduino.stackexchange",
"0000060021.txt"
] | Q:
How to assign two or more variables incoming from app
I'm really new to Arduino and have some doubts about how Arduino reads data. Lets suppose I have 3 variables a,b,c. I need these variables in my Arduino to make whatever. Since all variables are read using Serial.read() how can I distinguish between them in my Arduino?
Example:
Variable a: 2
Variable b: 3
Variable c: 4
Arduino example code:
void loop() {
int a = Serial.read();
int b = Serial.read();
int c = Serial.read();
if(a == '0'){
digitalWrite(yellowLed, HIGH);
}
if(b == '0'){
digitalWrite(blueLed, HIGH);
}
if(c == '0'){
digitalWrite(redLed, HIGH);
}
In every loop, my Arduino does serial.read() 3 times, if I only send value b from my app, since int a = Serial.read() executes first, will my b value be assigned to a? If yes, how can I avoid that problem and force the correct assignment? Aditionally, in every loop, if Serial.read() doesnt read anything, will my values be changed to null or zero?
A:
This is a classic problem that is solved either by uniquely identifying each value or by agreeing on a pre-defined sequence of data. However, it can be said that many solutions exist for this problem & that these are only 2 examples.
In the first case, the sender and receiver need to agree that all data will be sent in pairs. A pair of bytes, for example, where the first identifies the data and the second is the data. In this case the order of data does not matter. And much more of one type of data can be sent than another. This is good to use when the data rate is irregular and does not need to be fast. Stock prices for example.
In the second case, the sender and receiver need to agree that all data will be sent in the same sequence even if there is no data to be sent. Such a scheme may employ a special synchronizing bit to identify the beginning of a sequence of data. Usually, when there is no data to be sent, a zero is sent. But if zeros are significant, then special null characters will have to be agreed upon. This is good when the data rate is regular and needs to be fast. Digitized audio for example.
|
[
"security.stackexchange",
"0000001624.txt"
] | Q:
How much protection does the Kill-Bit provide for ActiveX controls?
I have some ActiveX controls that are not supposed to run in the browser but only in my particular Front-End. I know that by setting the Kill-Bit I disable their execution in Internet Explorer and MS Office applications.
That is following the FAQ given by MS Part 1, Part 2 and Part 3.
Now, I was assuming that ActiveX controls work only in Microsoft environments, as reported by Mozilla, but i noticed that I there are plugins Ex1, Ex2,... in the wild that let customers use ActiveX in Mozilla.
Therefore the question: Does the Kill-Bit cover these plugin cases as well? If not, what would be an alternative?
A:
To my understanding the Kill-Bit mechanism is an opt-in mechanism for ActiveX. Programs have to explicitly support them. Microsoft's own documentation (link) states that the only way to blanket-kill an ActiveX control is with a Software Restriction Policy. Such a policy will restrict the execution of the ActiveX control by any process.
|
[
"math.stackexchange",
"0001361953.txt"
] | Q:
Plugging a random variable into a probability function?
I have attempted to "prove" some basic results in probability and I was wanting to know whether my "proofs" are sound without getting more involved than undergraduate multivariate calculus. I attempted to demonstrate that $\mathbb{E}(X + Y | Z) = \mathbb{E}(X|Z) + \mathbb{E}(Y|Z)$ as follows
\begin{align*}
\mathbb{E}(X + Y | Z) &= \sum_{i}\sum_{j} (x_i + y_j) f_{X,Y|Z}(x_i,y_j|Z) \\
&= \sum_{i}\sum_{j} x_i f_{X,Y|Z}(x_i,y_j|Z) + \sum_{i}\sum_{j} y_j f_{X,Y|Z}(x_i,y_j|Z) \\
&= \mathbb{E}(X|Z) + \mathbb{E}(Y|Z)
\end{align*}
where $X, Y$ and $Z$ are discrete random variables. I am particularly unsure about plugging a random variable into a probability mass function, should I be summing over all possible values of $Z$ instead?
A:
If $A\in\sigma(Z)$, then $1_A$ is $\sigma(Z)$-measurable, so by linearity of expectation and iterated expectation
\begin{align}\mathbb E[X1_A] + \mathbb E[Y1_A] &= \mathbb E[(X+Y)1_A]\\ &= \mathbb E[\mathbb E[(X+Y)1_A\mid Z]]\\ &= \mathbb E[\mathbb E[X+Y\mid Z]1_A], \end{align}
and
\begin{align}\mathbb E[X1_A] + \mathbb E[Y1_A] &= \mathbb E[\mathbb E[X1_A\mid Z]] + \mathbb E[\mathbb E[Y1_A\mid Z]]\\ &= \mathbb E[\mathbb E[X\mid Z]1_A] + \mathbb E[\mathbb E[Y\mid Z]1_A].\end{align}
Hence
$$\mathbb E[\mathbb E[X+Y\mid Z]1_A] = \mathbb E[\mathbb E[X\mid Z]1_A] + \mathbb E[\mathbb E[Y\mid Z]1_A], $$
and by definition of conditional expectation,
$$\mathbb E[X+Y\mid Z] = \mathbb E[X\mid Z] + \mathbb E[Y\mid Z]. $$
As @user190080 pointed out, here I used two properties of conditional expectation. The first is that if $S$ and $T$ random variables with finite mean, then
$$\mathbb E[S] = \mathbb E[\mathbb E[S\mid T]].$$
This is what I meant by "iterated expectation." In the case where $S$ and $T$ are discrete random variables, this follows from
\begin{align}
\mathbb E[\mathbb E[S\mid T]] &= \mathbb E\left[\sum_s s\mathbb P(S=s\mid T) \right]\\
&= \sum_t\left(\sum_s s\mathbb P(S=s\mid T=t)\right)\mathbb P(T=t)\\
&= \sum_t\sum_s s \mathbb P(S=s\mid T=b)\mathbb P(T=t)\\
&= \sum_t\sum_s s \mathbb P(S=s, T=t)\\
&= \sum_s s\sum_t \mathbb P(S=s, T=t)\\
&= \sum_s s\mathbb P(S=s)\\
&= \mathbb E[S],
\end{align}
where the interchange in order of summation is justified by Fubini's theorem (as by definition of conditional expectation, $\mathbb E[|\mathbb E[S\mid T]|]<\infty$).
The second one is that if $A\in\sigma(T)$, i.e. $A=T^{-1}(\{t\})$ for some $t$ with $\mathbb P(T=t)>0$ where
$$T^{-1}(\{t\}) = \{\omega:T(\omega)=t\}, $$
then
$$\mathbb E[S1_A\mid T] = \mathbb E[S\mid T]1_A, $$
where $$1_A(\omega)= \begin{cases}1,&\omega\in A\\0,&\omega\notin A.\end{cases}$$
This follows from
$$\mathbb E[S1_A] = \mathbb E[\mathbb E[S\mid T]1_A] $$
(by definition of conditional expectation).
|
[
"stackoverflow",
"0026638808.txt"
] | Q:
Tug Of War: Divide set of n objects int to subsets
I found a problem of Tug Of War while doing some algorithm practice on Internet:
Statement:
Given a set of n integers, divide the set in two subsets of n/2 sizes each such that the difference of the sum of two subsets is as minimum as possible. If n is even, then sizes of two subsets must be strictly n/2 and if n is odd, then size of one subset must be (n-1)/2 and size of other subset must be (n+1)/2.
For example, let given set be
{3, 4, 5, -3, 100, 1, 89, 54, 23, 20}
the size of set is 10. Output for this set should be
{4, 100, 1, 23, 20}
and
{3, 5, -3, 89, 54}
Both output subsets are of size 5 and sum of elements in both subsets is same (148 and 148).
Let us consider another example where n is odd. Let given set be
{23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4}
The output subsets should be
{45, -34, 12, 98, -1}
and
{23, 0, -99, 4, 189, 4}
The sums of elements in two subsets are 120 and 121 respectively.
I found a knapsack kind of approach on Internet while looking for solution here:
I'm not getting this part of the solution:
for (int i = 1; i <= N; ++i)
for (int j = sum; j >= 0; --j)
if (dp[j])
dp[j + W[i]] |= dp[j] << 1;
I understand that we are trying to find the number of objects that have accounted for a sum of i. But doing dp[i] << 1 is something I'm not getting properly:
Also, why are we iterating the j variable backwards, starting from sum to 0? Why not 0 to sum ?
Can someone please tell me underlying logic in more simple and generalized way ?
Thanks
A:
I think the comment makes it pretty clear, actually.
// If (dp[i] << j) & 1 is 1, that means it is possible
// to select j out of the N people so that the sum of
// their weight is i.
You start with the initial condition dp[0] = 1 << 0, meaning "it's possible to select 0 people such that the sum of their weight is 0".
Then for each entry in dp that's nonzero (that's the if (dp[j]) part), you update dp for the current person in the list.
Now, you're specifically asking "why dp[j] << 1"? Well, imagine the first 3 elements are 1, 2, 3.
Then dp[3] will be 110 in binary, meaning "you can make a sum of 3 using 1 person (3), OR two people (1 and 2).
If the next number is 10, then when we come to dp[3], we do dp[3+10] |= dp[3] << 1, making dp[13] 1100. Meaning "since we can make 3 with either 2 people or one person, with an extra 10 in the mix, we can make 13 with either 3 people (1, 2, 10) or 2 people (3, 10)"
Then at the end, all you need to do is look for the entry in dp which is closest to half of the total sum. And of course, the other team's sum will be the total sum minus this value.
Note that this algorithm will NOT tell you which numbers you need to pick to get that sum; that information is lost. It will only tell you what the best two sums are. Though it would not be hard to modify the algorithm slightly and use some data structure to retain that information (such that each entry in dp says "I can make this sum from 3 numbers, and these numbers are...").
Oh, and about the iterating backwards: that's to prevent us from counting the same number twice. If the first entry was 1, we'd say "I can make 0 from 0 numbers; now I can make 1 from 1 number". Then immediately afterwards, "I can make 1 from 1 number; now I can make 2 from 2 numbers". And so on.
EDIT: since you asked, here's one way of doing this (note that it will break if you enter non-positive numbers, I'll leave it to you to fix that):
int N;
int W[100 + 5];
std::map<int, std::vector<int>> dp[450 * 100 + 5];
void solve()
{
int sum = accumulate(W + 1, W + N + 1, 0);
// If (dp[i][j]) contains a nonempty vector, that means it is possible
// to select j out of the N people so that the sum of
// their weight is i, with those people's indices being the values of said vector
dp[W[1]][1].push_back(1);
for (int i = 2; i <= N; ++i)
{
for (int j = sum; j >= 0; --j)
{
for (std::map<int, std::vector<int>>::iterator it = dp[j].begin(); it != dp[j].end(); ++it)
{
dp[j + W[i]][it->first+1] = it->second;
dp[j + W[i]][it->first+1].push_back(i);
}
}
}
std::vector<int> selected;
int minDiff = 450 * 100;
int teamOneWeight = 0, teamTwoWeight = 0;
for (int i = 0; i <= sum; ++i)
{
if (!dp[i].empty())
{
int diff = abs(i - (sum - i));
if (diff < minDiff)
{
minDiff = diff;
teamOneWeight = i;
teamTwoWeight = sum-i;
selected = dp[i].begin()->second;
}
}
}
cout << "Team 1, sum of " << teamOneWeight << ": ";
for (int i = 1; i <= N; ++i)
{
if (std::find(selected.begin(), selected.end(), i) != selected.end())
cout << W[i] << ' ';
}
cout << endl << "Team 1, sum of " << teamTwoWeight << ": ";
for (int i = 1; i <= N; ++i)
{
if (std::find(selected.begin(), selected.end(), i) == selected.end())
cout << W[i] << ' ';
}
cout << endl;
}
|
[
"stackoverflow",
"0019020101.txt"
] | Q:
Controlling CSS using AngularJS
I am trying to control CSS through AngularJS. I am using ng-class and ng-click for this purpose ..... I have made two function showError and showWarning for this purpose. I am try to change CSS through setting their properties true and false respectively
--------CSS---------
.error {
background-color: red;
}
.warning {
background-color: orange;
}
-------HTML---------
<div>
<h2> {{ message }} </h2>
<ul>
<li class="menu-disabled-{{ isDisabled }}" ng-click="stun()"> Stun</li>
</ul>
<div class='{ warning : {{ isWarning }}, error : {{ isError }} }'>
{{ messageText }}</div>
<button ng-click="showError()"> Simulate Error</button>
<button ng-click="showWarning()">Simulate Warning</button>
</div>
-------JS-----------
$scope.isError = false;
$scope.isWaring = false;
$scope.showError = function(){
console.log("error here");
$scope.messageText = "This is an error";
$scope.isError = true;
$scope.isWaring = false;
}//showError
$scope.showWarning = function() {
console.log("warning here");
$scope.messageText = "Just a Warning, Carry ON !!!";
$scope.isError = false;
$scope.isWaring = true;
}//showWarning
I am successful to access the function and printing the messageText using ng-click but can't change the CSS properties////
A:
Angular way is making that in template:
<div>
<h2> {{ message }} </h2>
<ul>
<li ng-class="{'menu-disabled': isDisabled}" ng-click="stun()"> Stun</li>
</ul>
<div ng-show="isError" class="error">{{ errorMessage }}</div>
<div ng-show="isWarning" class="warning">{{ warningMessage }}</div>
<button ng-click="isError=true;isWarning=false"> Simulate Error</button>
<button ng-click="isWarning=true;isError=false">Simulate Warning</button>
</div>
No javascript code is needed and advisely, you shouldn't use javascript for that kind of view manipulations.
EDIT: You can use scope variables for message texts instead of static texts.
|
[
"stackoverflow",
"0035329281.txt"
] | Q:
php (empty($_GET)) transient errors
I am getting an transient error which I think is linked to this statement
$rs = (empty($_GET["rs"])?0:$_GET["rs"]);
Could someone explain this notation please
Is there a better way of writing this statement to include the trim function (as is suspect this may be an issue)?
A:
This is a ternary expression that does exactly this:
if (empty($_GET["rs"]))
{
$rs = 0;
}
else
{
$rs = $_GET["rs"];
}
To trim the results, you can do
$rs = (empty($_GET["rs"])?0:trim($_GET["rs"]));
Or if you wish to use the expanded expression,
if (empty($_GET["rs"]))
{
$rs = 0;
}
else
{
$rs = trim($_GET["rs"] );
}
|
[
"stackoverflow",
"0006857205.txt"
] | Q:
How can i stop all audio file with single button?
I am making a quiz app and i have set different background music in two UIView.
Now i have created button for stop the bachgrond music.
IBOutlet UIButton *soundoffbtn;
I stop the background music for firstview by
-(Void)SoundBtn{
[Avbackmusic stop];
}
It just stop in one view.
When i entered in secondView , background music for that view is started as it should be.
What i want is to stop the background music for whole app (both view) by just tapping the firstview's soundoffbtn
What should i do for that?
I am new to this..
Any help will be appreciated..
Thanks.
A:
I didn't fully understand a question. But if you want the second view not to start playing sound after you switch off sound on first view then create an indicator variable in applicaton delegate that will indicate the sound on/off status for your app. Access that indicator before playing a sound. If it shows on, then play, if off, do not play.
For example in your app delegate create a variable
int soundIndicator;
@property (nonatomic) int soundIndicator;
@synthesize soundIndicator;
Then in your View controllers you can access that variable, it will be common for all application:
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
if (appDelegate.soundIndicator == 0){ ... }
|
[
"stackoverflow",
"0058530434.txt"
] | Q:
How to detect missing sequence and display the step?
I have a standard sequence {"base", "stem", "backboard", "rim"}
I have a process that returns a list like {"stem", "base"}, {"stem", "backboard", "base", "rim"} ....
I need to detect if the sequence is going wrong by comparing the values of the returned list to the standard one.
Examples:
{"base"} - should return true
{"base", "stem"} - should return true
{"base", "backboard"} - should return false
{"stem", "base"} - should return true
{"backboard", "base", "stem"} - should return true
The order doesn't matter
I have tried putting in several if statements but nothing seemed right to me.
Here's my code:
if (tagList.Contains("base"))
{
// do nothing
if (tagList.Contains("stem"))
{
// do nothing
if (tagList.Contains("bb"))
{
// do nothing
if (tagList.Contains("rim"))
{
//do nothing
}
}
else if (tagList.Contains("BB") && tagList.Contains("rim"))
{
// do nothing
}
else
{
// step -3 bb faulty
}
}
else if (tagList.Contains("stem") && tagList.Contains("BB"))
{
//do nothing
}
else if (tagList.Contains("stem") && tagList.Contains("BB") && tagList.Contains("rim"))
{
//do nothing
}
else if (tagList.Contains("stem") && tagList.Contains("rim"))
{
// step-3 BB faulty
}
else
{
// step-2 stem faulty
}
}
else if (tagList.Contains("base") && tagList.Contains("stem"))
{
// do nothing
}
else if (tagList.Contains("base") && tagList.Contains("stem") && tagList.Contains("BB"))
{
// do nothing
}
else if (tagList.Contains("base") && tagList.Contains("stem") && tagList.Contains("BB") && tagList.Contains("rim"))
{
// do nothing
}
else if (tagList.Contains("base") && (tagList.Contains("BB") || tagList.Contains("rim")))
{
// step-2 stem faulty
}
else
{
// step-1 base faulty
}
A:
You (apparently) just want to know if a process result has all the elements up to the same number of elements in standard, in any order.
So, take the first n elements from the standard, and see if the result contains each one:
var okay = standard.Take(result.Count()).All(s => result.Contains(s));
To find out which are missing, use
var missing = standard.Take(result.Count()).Where(s => !result.Contains(s)).ToList();
|
[
"stackoverflow",
"0061158239.txt"
] | Q:
Can I assign 2 different types to typescript interfaces?
I have following interface structure to store travelers.
interface Person: {
age: number,
name: string
}
interface TravelersDirectory {
[country: string]: Person[]
}
example:
travelersDirectory = {
'India': [
{
age: 30,
name 'X'
},
{
age: 35,
name 'Y'
},
]
}
With the new change I am going to decouple persons from the travelers directory
to Persons and references will be stored in Travelers directory. The new interface will be :
interface Persons extends Array<Person>
But due to the business requirement travelersDirectory can keep either index (to Persons) or Person object
example:
const persons = [
{
age: 30,
name 'X'
},
{
age: 35,
name 'Y'
},
];
const travelersDirectory = [
'India': [
0,
{
age: 35,
name 'Y'
},
]
]
Is this possible? can both types(index and Person object) coexist? I tried to work out by making changes to travelersDirectory interface but it didnt work.
Attempt 1:
interface TravelersDirectory {
[country: string]: Person[] | number[]
}
Attempt2 :
interface Persons extends Array<Person | number>
interface TravelersDirectory {
[country: string]: Persons
}
How can I do it?
Note: The data structure used is symbolic and I can't redesign it. Only can workaround by playing with the interfaces
Check this link for exact problem https://stackblitz.com/edit/typescript-ypc59j
A:
The second attempt in the question is a correct way to type this, but it can be simplified to this:
interface TravelersDirectory {
[country: string]: Array<Person | number>;
}
After some back-and-forth with OP, I found out the issue was somewhere else, ie this code:
function getName(travelersDirectory: TravelersDirectory, country: string, index: number) {
return travelersDirectory[country][index].name;
}
This is because travelersDictionary[country][index] can be either a Person or a number, so the property name is not guaranteed to exist. To fix this, we need to guard against this and define what should happen if the result of travelersDictionary[country][index] is a number. We can do this by saving the result into a variable, and using typeof to check if the result is a number before we tell it what will happen if it's a Person.
function getName(travelersDirectory: TravelersDirectory, country: string, index: number) {
const person = travelersDirectory[country][index];
if (typeof person === "number") {
// getName was called referencing a number instead of a Person.
// Throw Error? Do nothing? Up to you
throw Error("Can't get name of a number");
} else {
// Typescript is smart enough to understand that the variable `person` can't be a number
// (because we guarded against it in the previous if-expression)
// so now we can do person.name
return person.name;
}
}
Here's a Stackblitz demonstrating this
|
[
"stackoverflow",
"0036158971.txt"
] | Q:
mySQLi insert error - Call to a member function bind_param
I got this very simple mysqli query that fails and returns this message:
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in M:\xampp\htdocs\insert\form-handler.php:17 Stack trace: #0 {main} thrown in M:\xampp\htdocs\insert\form-handler.php on line 17
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="form-handler.php" method="POST">
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="submit">
</form>
</body>
</html>
PHP:
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$mysqli = new mysqli('localhost', 'root', '', 'firstlast');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare('INSERT INTO users (id, firstname, lastname) VALUES ("", ?, ?');
$stmt->bind_param('ss', $firstname, $lastname);
$stmt->execute();
$stmt->close();
Is there anything that I have missed? Thanks.
A:
$stmt = $mysqli->prepare('INSERT INTO users (id, firstname, lastname) VALUES ("", ?, ?)');
Removed ! in from of $stmt and you were missing a ) to close the VALUES
|
[
"pt.stackoverflow",
"0000287913.txt"
] | Q:
Expressões regular não dá match no trecho de texto desejado
Estou precisando que meu programa capture um item de um determinado texto, mas ele não está fazendo isso, pelo contrário, está capturando tudo que vem depois disso.
Código que estou utilizando, ex:
String html = "ItemPago12.569,00DeducoesPagas36.567,52ItensQnt6DeducoesRetidas21.354,11";
Pattern conteudo = Pattern.compile("ItemPago([^<]+)Deducoes");
Matcher match = conteudo.matcher(html);
match.find();
System.out.println(match.group(1));
Programa rodando: https://ideone.com/JwFxu2
Preciso pegar o que está no meio, entre: ItemPago e Deducoes. Gostaria de exemplos e explicações de como utilizar esse método de maneira correta. Obrigado.
A:
Há três possíveis comportamentos em expressões regulares: Guloso, relutante e possessivo. O que você quer é o comportamento relutante. Você pode usar o .*?, onde .* significa pegar qualquer coisa e o ? significa relutante.
O comportamento relutante diz para que o analisador de expressão regulares se contente com a primeira possibilidade de match, não tentando nada além disso.
Eis o código completo:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Ideone {
public static void main(String[] args) {
String html = "ItemPago12.569,00DeducoesPagas36.567,52ItensQnt6DeducoesRetidas21.354,11";
Pattern conteudo = Pattern.compile("ItemPago(.*?)Deducoes");
Matcher match = conteudo.matcher(html);
match.find();
System.out.println(match.group(1));
}
}
Eis a saída:
12.569,00
Veja aqui funcionando no ideone.
|
[
"stackoverflow",
"0029585849.txt"
] | Q:
How do I remove focus from a button, so that pushing the spacebar or Enter doesn't trigger the button?
When you click or tap a button, it gives it focus, so that when you push the spacebar or Enter, it triggers the button again. I don't want that to happen.
I tried this: button1.Focus(Windows.UI.Xaml.FocusState.Unfocused);
But the unwanted behavior still happens (pushing the spacebar or Enter triggers the button again). I also tried setting focus to another button using the Programmatic and Keyboard FocusStates but that doesn't fix it either.
Any help, especially an explanation of why this is happening, would be greatly appreciated.
A:
You can set the TabStop property to False, but be aware that doing this disallows user from using the button by keyboard.
<Button Content="Click Me By Pointer!" IsTabStop="False"/>
Update
As msdn states:
You can't remove focus from a control by calling this method with FocusState.Unfocused as the parameter. This value is not allowed and causes an exception. To remove focus from a control, set focus to a different control.
So another way to achieve this, is setting focus to previously focused element when the button is about to get focus by pointer. Unfortunatly the GettingFocus event is not working for the Button class (maybe because final version is not released yet?) so we should use GotFocus event, it's ugly it but works.
bool moveFocus = false;
public MainPage() {
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e) {
if (moveFocus) {
UIElement focusedElement = FocusManager.FindNextFocusableElement(FocusNavigationDirection.Right);
if (focusedElement is Control) {
((Control)focusedElement).Focus(FocusState.Programmatic);
}
}
}
private void Button_GotFocus(object sender, RoutedEventArgs e) {
Button button = (Button)sender;
moveFocus = (button.FocusState == FocusState.Pointer);
}
Note that I passed FocusNavigationDirection.Right to FocusManager.FindNextFocusableElement to get an element in right, I should have used FocusNavigationDirection.Previous instead to get previous element but it returns null for unknown reason.
|
[
"stackoverflow",
"0038334896.txt"
] | Q:
Persist values across the lifetime of an app - Pause / resume countdown timer
I want to create a countdown such that when the app is completely closed, the countdown timer is paused and saved. When the app is opened again, the countdown resumes where it left off.
My idea was to save the value "millisUntilFinished" in the "onStop" when the app is closed and in the "onResume" continue the countdown when the app is opened.
The problem is that I don't know how to do it, someone help me?
The code of my countdown:
public class MainActivity extends Activity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.b1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
// this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void a(View view){
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
tv1.setText("La cuenta llega a 0 en: " + millisUntilFinished / 1000);
}
public void onFinish() {
tv1.setText("Listo!");
}
}.start();
}
A:
Use SharedPreferences.
onResume(){
SharedPreferences prefs =
getSharedPreferences("PREF_NAME", MODE_PRIVATE);
int startTime = prefs.getInt("PAUSED_TIME", 0); //0 is the default value.
}
onPause(){
SharedPreferences.Editor editor =
getSharedPreferences("PREF_NAME", MODE_PRIVATE).edit();
editor.putInt("PAUSED_TIME", time);
editor.commit();
}
|
[
"reverseengineering.stackexchange",
"0000018627.txt"
] | Q:
Why would an ELF SHT_REL section contain relocations outside the section its sh_info refers to?
I have a .so from an Android JNI/NDK application. Here are two of its sections:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[10] .rel.plt REL 001c9034 1c9034 00c928 08 AI 3 11 4
[11] .plt PROGBITS 001d595c 1d595c 012dd0 00 AX 0 0 4
Based on the Info parameter of .rel.plt, I would expect the relocations it contains to affect the contents of the .plt section. However, the addresses in the relocations are all to much higher addresses:
Relocation section '.rel.plt' at offset 0x1c9034 contains 6437 entries:
Offset Info Type Sym. Value Symbol's Name
00e1bb6c 00000216 R_ARM_JUMP_SLOT 00000000 __cxa_atexit@LIBC
00e1bb70 00000116 R_ARM_JUMP_SLOT 00000000 __cxa_finalize@LIBC
00e1bb74 00000316 R_ARM_JUMP_SLOT 00a0f8c5 _Znwj
00e1bb78 00000416 R_ARM_JUMP_SLOT 00a0f941 _ZdlPv
00e1bb7c 00000516 R_ARM_JUMP_SLOT 00a1886d __gxx_personality_v0
00e1bb80 00000716 R_ARM_JUMP_SLOT 00000000 __stack_chk_fail@LIBC
00e1bb84 00000b16 R_ARM_JUMP_SLOT 009ed201 _ZNSt6__ndk16chrono12system_clock3nowEv
Those addresses fall into the range of the .got and .data sections. This is a shared object, so the offsets should be virtual address based rather than section based, and the ELF for the ARM Architecture says:
The ELF standard requires that the GOT-generating relocations of the PLT are emitted into a contiguous sub-range of the dynamic relocation section. That sub-range is denoted by the standard tags DT_JMPREL and DT_PLTRELSZ. The type of relocations (RELor RELA) is stored in the DT_PLTREL tag.
Am I misunderstanding what the offset of these relocations applies to? Or perhaps what "GOT-generating relocations" means?
A:
My mistake was in treating the addresses in the relocations' addresses based on the sections' offsets (sh_offset) and not their addresses (sh_addr) to determine where they pointed. Correcting this misunderstanding, the relocations all address entries in the GOT which address the PLT, as expected.
|
[
"stackoverflow",
"0002748187.txt"
] | Q:
Best windows text editor with SVN integration?
I wasn't sure if this is SuperUser or StackOverflow material, but since the end result is for programming I'll start here. I'm looking for a lightweight editor with svn support. What is your favorite?
A:
NotePad++, TortoiseSVN, non-Integrated.
Or, if you really need integration, it looks like somebody wrote a plugin:
http://www.switchonthecode.com/tech-news/notepadplusplus-subversion-plugin
And if you are using Delphi, and/or want an easy way to add basic SVN to Delphi, use this method to add SVN commands to the TOOLS menu:
http://delphi.wikia.com/wiki/Adding_TortoiseSVN_to_the_Tools_menu
ALSO - I think the trick for adding SVN to Delphi via the Tools menu, would work for notepad++ also - it's a very generic approach.
|
[
"stackoverflow",
"0003740021.txt"
] | Q:
How to dynamic new Anonymous Class?
In C# 3.0 you can create anonymous class with the following syntax
var o1 = new { Id = 1, Name = "Foo" };
Is there a way to dynamic create these anonymous class to a variable?
Example:
var o1 = new { Id = 1, Name = "Foo" };
var o2 = new { SQ = 2, Birth = DateTime.Now };
Dynamic create Example:
var o1 = DynamicNewAnonymous(new NameValuePair("Id", 1), new NameValuePair("Name", "Foo"));
var o2 = DynamicNewAnonymous(new NameValuePair("SQ", 2), new NameValuePair("Birth",
DateTime.Now));
Beacuse I need to do:
dynamic o1 = new ExpandObject();
o1."ID" = 1; <--"ID" is dynamic name
o1."Name" = "Foo"; <--"Name" is dynamic name
And Scene1:
void ShowPropertiesValue(object o)
{
Type oType = o.GetType();
foreach(var pi in oType.GetProperties())
{
Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null));
}
}
if I call:
dynamic o1 = new ExpandObject();
o1.Name = "123";
ShowPropertiesValue(o1);
It can't show the result:
Name = 123
And also I how to Convert the ExpandoObject to AnonymouseType ?
Type type = o1.GetType();
type.GetProperties(); <--I hope it can get all property of o1
Last, I modify ShowPropertiesValue() method
void ShowPropertiesValue(object o)
{
if( o is static object ) <--How to check it is dynamic or static object?
{
Type oType = o.GetType();
foreach(var pi in oType.GetProperties())
{
Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null));
}
}
else if( o is dynamic object ) <--How to check it is dynamic or static object?
{
foreach(var pi in ??? ) <--How to get common dynamic object's properties info ?
{
Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null));
}
}
}
How to implement DynamicNewAnonymous method or how to modify the ShowPropertiesValue()?
My motivations is:
dynamic o1 = new MyDynamic();
o1.Name = "abc";
Type o1Type = o1.GetType();
var props = o1Type.GetProperties(); <--I hope can get the Name Property
If i can hook dynamicObject's GetType Method, and Compel convert to strongly-typed Type.
The above Seamless code can work fine.
A:
Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic.
Now, if you were to use an ExpandoObject and reference it through a dynamic variable, you could add or remove fields on the fly.
edit
Sure you can: just cast it to IDictionary<string, object>. Then you can use the indexer.
You use the same casting technique to iterate over the fields:
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
foreach (var property in (IDictionary<string, object>)employee)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33
The above code and more can be found by clicking on that link.
A:
You can create an ExpandoObject like this:
IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;
And after casting it to dynamic, those values will look like properties:
dynamic d = expando;
Console.WriteLine(d.Name);
However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:
d.GetType().GetProperty("Name")
|
[
"stackoverflow",
"0002992898.txt"
] | Q:
PHP HTML to PDF free convertor Resources
What is the best PHP HTML to PDF free converter around, not just in terms of functionality but also in terms of resource usage and speed
Thanks
A:
Have a look at open-souce fpdf library.
A:
Check dompdf, an HTML to PDF converter written in PHP. No external dependencies, it supports complex tables, images and even external style sheets.
http://www.digitaljunkies.ca/dompdf/
|
[
"stackoverflow",
"0032383336.txt"
] | Q:
Shiny scoping error with observeEvent
I have the following in server.R in a shiny application...
shinyServer(function(input, output, session) {
observeEvent(
input$goButton, #dependency
{
Predictores<-reactive({
test<-input$LUNES*20
test2<-input$LUNES*30
data.frame("one" = test,
"two" = test2)
})
output$productos<-renderTable({as.data.frame(Predictores())},
include.rownames = FALSE )
}
)
})
When I try the ui.R, this works fine and the app is running, but nothing happens when I click the "goButton". The desired output would be a table with a data frame (for now i'm testing).
This works fine with a reactive function like this:
shinyServer(function(input, output, session) {
Predictores<-reactive({
test<-input$LUNES*20
test2<-input$LUNES*30
data.frame("uno" = test,
"dos" = test2)
})
output$productos<-renderTable({as.data.frame(Predictores())},
include.rownames = FALSE )
})
But because the real app will calculate a computing-intensive model based on the inputs, I want the calculation to be done only after the user presses "go", not everytime an input changes.
I've looked at the shiny docs and this seems to be the way but maybe i'm missing some scoping rules? Which could be the reason it runs but I don't see anything...
A:
isolate your button by doing something like this:
rm(list = ls())
library(shiny)
ui =(pageWithSidebar(
headerPanel("Table output"),
sidebarPanel(
sliderInput("LUNES", "LUNES", 100, 500, 2000, sep = ""),
actionButton("goButton","GO")
),
mainPanel(tableOutput("productos"))
))
server = function(input, output, session){
Predictores<-reactive({
if (is.null(input$goButton) || input$goButton == 0){return()}
isolate({
input$goButton
test<-input$LUNES*20
test2<-input$LUNES*30
data.frame("uno" = test, "dos" = test2)
})
})
output$productos<-renderTable({as.data.frame(Predictores())},include.rownames = FALSE )
}
runApp(list(ui = ui, server = server))
Sample Output is below
EDIT - your personal example
I can see that you got your brackets mixed up a bit, have a look at the solution below:
(list = ls())
library(shiny)
ui = (
fluidPage(
title = 'Modelo de Caídas en Venta',
## --------- titulo
titlePanel("Modelo de Caídas en Venta"),
## --------- barra lado de inputs
sidebarPanel(
## ----- tabs
tabsetPanel(type = "tabs",
# tab 1 -------------------------
tabPanel("Mes",
selectInput(inputId = "MES",label = "Mes a predecir",selectize = TRUE,choices = "201508"),
selectInput(inputId = "MES_APERTURA",label = "Mes Apertura",selectize = TRUE,choices = "201508"),
sliderInput(inputId = "LUNES",label = "Lunes en mes a predecir", value = 4,min = 2, max = 6),
sliderInput(inputId = "VIERNES",label = "Viernes en mes a predecir",value = 4,min = 2, max = 6),
sliderInput(inputId = "FINDE",label = "Dias de fin en mes a predecir",value = 8, min = 6, max = 10)),
# tab 2 -------------------------
# tab 2 -------------------------
tabPanel("Mes Antes",
helpText("Todos los indicadores en esta sección se refieren
a un mes anterior al que se va predecir por el modelo"),
checkboxInput(inputId = "EVENTO_PREVIO",
label = "Caída un mes antes",
value = FALSE),
numericInput(inputId = "CLIENTES",
label = "Clientes",
value = 2900,
min = 1400, max = 9500),
# UNIDADES
numericInput(inputId = "U_FARMAMP",
label = "Unidades Farma MP",
value = 7900,
min = 900, max = 29500),
numericInput(inputId = "U_OTCMP",
label = "Unidades OTC MP",
value = 7900,
min = 900, max = 29500),
numericInput(inputId = "U_BEBE",
label = "Unidades Bebé",
value = 2900,
min = 1400, max = 9500),
numericInput(inputId = "U_CONV",
label = "Unidades Conveniencia",
value = 2900,
min = 1400, max = 9500),
numericInput(inputId = "U_RECETA",
label = "Unidades Receta",
value = 2900,
min = 1400, max = 9500),
# YOY DE UNIDADES
numericInput(inputId = "Y_FARMAMP",
label = "Unidades Farma MP (mes año pasado)",
value = 7900,
min = 900, max = 29500),
numericInput(inputId = "Y_OTCMP",
label = "Unidades OTC MP (mes año pasado)",
value = 7900,
min = 900, max = 29500),
numericInput(inputId = "Y_BEBE",
label = "Unidades Bebe (mes año pasado)",
value = 2900,
min = 1400, max = 9500),
numericInput(inputId = "Y_CONV",
label = "Unidades Conveniencia (mes año pasado)",
value = 2900,
min = 1400, max = 9500),
numericInput(inputId = "Y_RECETA",
label = "Unidades con Receta (mes año pasado)",
value = 2900,
min = 1400, max = 9500),
#OTROS DE MES ANTES
numericInput(inputId = "PROD",
label = "Productos únicos",
value = 2900,
min = 1400, max = 9500),
#PORCENTAJES DE CAÍDAS
sliderInput(inputId = "P_PLAZA",
label = "Porcentaje de sucursales en plaza con caídas",
value = 30,
min = 0, max = 100),
sliderInput(inputId = "P_ESTADO",
label = "Porcentaje de sucursales en estado con caídas",
value = 30,
min = 0, max = 100),
sliderInput(inputId = "P_ZONA",
label = "Porcentaje de sucursales en zona con caídas",
value = 30,
min = 0, max = 100),
sliderInput(inputId = "P_CIUDAD",
label = "Porcentaje de sucursales en ciudad con caídas",
value = 30,
min = 0, max = 100)
),
# tab 3 -------------------------
tabPanel("Sucursales",
sliderInput(inputId = "SUCURSALES",
label = "Sucursales en total (mismas tiendas)",
value = 990,
min = 300, max = 3000),
numericInput(inputId = "DISTANCIA_MIN",
label = "Distancia con sucursal más cercana (en metros)",
value = 850,
min = 200, max = 240000),
numericInput(inputId = "DISTANCIA_PROM",
label = "Distancia con promedio contra otras sucursales (en metros)",
value = 18500,
min = 1500, max = 1000000),
sliderInput(inputId = "SUC_PLAZA",
label = "Sucursales en plaza (incluyendo esta)",
value = 20,
min = 0, max = 900),
sliderInput(inputId = "SUC_ESTADO",
label = "Sucursales en estado (incluyendo esta)",
value = 55,
min = 0, max = 900),
sliderInput(inputId = "SUC_ZONA",
label = "Sucursales en zona (incluyendo esta)",
value = 30,
min = 0, max = 900),
sliderInput(inputId = "SUC_CIUDAD",
label = "Sucursales en ciudad (incluyendo esta)",
value = 15,
min = 0, max = 900))
), #fin tabs
hr(), # soy un delimitador
helpText("Para consultas: [email protected]"),
actionButton("goButton","GO")
), #fin de sidebar
mainPanel(
helpText("Predicción del Modelo"),
hr(), # soy un delimitador
tableOutput("productos")
) #- mainpanel
)
)
server = function(input, output, session){
Predictores<-reactive({
if (is.null(input$goButton) || input$goButton == 0){return()}
isolate({
input$goButton
test<-input$LUNES*20
test2<-input$LUNES*30
data.frame("uno" = test, "dos" = test2)
})
})
output$productos<-renderTable({as.data.frame(Predictores())},include.rownames = FALSE )
}
runApp(list(ui = ui, server = server))
Solution to your particular dropbox code
|
[
"stackoverflow",
"0033607555.txt"
] | Q:
Subtracting depending on an if function in python
Convert the character into its ASCII code
Add the ASCII code to the offset factor calculated in Task 4.
If the result is bigger than 126 then subtract 94 so it is a valid ASCII code.
Convert the result into its equivalent ASCII character.
I need to subtract 44 from an if function but I'm not really sure how to do it. My code so far is:
a = text
sev=[ ord(x) for x in a ]
sev= sev + offsetFactor
if sev>126
next sev-44
Would I use the next function and if not what function would is use?
A:
a = "Kitty Bates"
sev=[ ord(x) for x in a ]
S= sum(sev)
while(1):
try:
print chr(S)
break # will break on valid ASCII
except:
S= S-44
output
Click here
Ф
As per your req
a = "Kitty Bates"
sev=[ ord(x) for x in a ]
S= sum(sev)
while(1):
try:
if(S>126):
0/0
print chr(S)
break #will break if ASCII is below 126
except:
S= S-44
output
\
|
[
"stackoverflow",
"0045340699.txt"
] | Q:
In PHP, how can I just create the conn to database once and use it many times from JavaScript through Ajax?
I use Ajax to request remote PHP file for database accessing. Every time I request, the conn will be re-created. How can I just create it once and use it many times?
The PHP file:
db.php
<?php
$conn = new PDO('mysql:host=localhost;dbname=db1', 'webuser', 'secret');
$query = 'SELECT * FROM `table1`';
$stmt = $conn->query($query);
echo $stmt->fetchAll();
?>
The JavaScript File (in Angular):
user.js
$http.get('localhost')
.success(function (data) {
// to process the data...
});
Can I share the conn object to all the requests? How can I preserve the conn object? I think the re-creating in every time is a waste of resource.
A:
This question has got answers. Please refer to the above comments. In PHP, it's not easy and not necessary to do so.
|
[
"physics.stackexchange",
"0000178719.txt"
] | Q:
Point charges in a sphere
If we put N point charges (with charge +q) in a sphere with radius R and the charges can move freely in the sphere but can't get out of it, where will the charges go to and what will be the electrostatic energy in the cases that N=2,3,4?
I thought that the charges would go to the surface of the sphere, but I don't really know why.
Also for N=5 there are two configurations of where the charges will go, which one will have the lowest energy (without calculating this)?
A:
The charges will tend to be as far from each other as possible as this would minimize the energy of the system
$$
U = \sum_{ij} \frac{q_i q_j}{4\pi\epsilon_0 r_{ij}}
$$
So you call understand their tendency to go to the surface, for the same reason that if there was no sphere they would fly off to infinity.
For $N$ charges on the sphere, this becomes the old Thompson problem. For $5$ it is visually challenging but recently shown to be a triangular dipyramid, see http://en.wikipedia.org/wiki/Thomson_problem
|
[
"stackoverflow",
"0025009556.txt"
] | Q:
Display inline two p tag
I want to display two p tags in same line, one left and one right as below :
<p >This is a paragraph.</p>
<p style="text-align : right">This is a paragraph.</p>
In the CSS, I am doing below :
p {display: inline-block;}
But this is not giving me the desired output. Instead its showing both the sentences together like below :
This is a paragraph. This is a paragraph.
A:
Use float:left on the first p and float:right on the second.
HTML
<div>
<p class="pull-left">Text in left paragraph</p>
<p class="pull-right">Text in right paragraph</p>
</div>
CSS
.pull-left {float:left;}
.pull-right {float:right;}
JSFiddle
|
[
"vi.stackexchange",
"0000002725.txt"
] | Q:
How to force quit if input was stdin?
I have
q mapped to :qenter
Q mapped to <esc>:qa!enter
which means
quit, unless something needs to be saved
just quit
My meanings for these keys clashes with vim's idea that stdin needs to be saved, e.g.
$ git log | vim -
q
vim says No write since last change ...
Look at keyboard, find shift
Q
And I can then quit.
How can I tell vim to ignore file saving when using "-" to read for input from stdin?
A:
I would start vim with a command that tells it the current file is a scratch buffer (which vim will not prompt you to save):
git log | vim -c "setlocal buftype=nofile bufhidden=hide noswapfile" -
Because I do this a lot, I save the scratch buffer settings to a command in my .vimrc
":ScratchBuffer makes current buffer disposable
command! ScratchBuffer setlocal buftype=nofile bufhidden=hide noswapfile
I also add a bash function in my .bashrc
v() {
vim -c ScratchBuffer -
}
This means I can type git log | v to achieve the desired effect
A:
You can run vim in read-only mode (as you're not opening a proper file):
git log | vim -R -
Then standard q should work, without asking you to save your changes.
|
[
"stackoverflow",
"0039894174.txt"
] | Q:
mule web service cxf client call , hot to increase timeout?
I am calling the external web service from the Java Component by using the CXF Client Proxy, as described in: https://docs.mulesoft.com/mule-user-guide/v/3.7/consuming-web-services-with-cxf#building-a-client-proxy
The default execution time is set to 10 seconds, but the web service sometimes may require more time to complete. I tried increasing the time with:
ClientBuilder.newClient().property("http.receive.timeout", 600000);
, but it didn't help. Using the example from the above link, how to increase the timeout?
A:
sun.net.client.defaultConnectTimeout (default: -1 (forever))
sun.net.client.defaultReadTimeout (default: -1 (forever))
this will apply to all calls done.
or you can try to set the timeout in context.
Map<String, Object> requestContext = (BindingProvider)myInterface).getRequestContext();
requestContext.put(BindingProviderProperties.REQUEST_TIMEOUT, 3000); // Timeout in millis
requestContext.put(BindingProviderProperties.CONNECT_TIMEOUT, 1000); // Timeout in millis
|
[
"stackoverflow",
"0004584833.txt"
] | Q:
Hiding NSMenu while the dock remains active
I want my app to show his menu on launch only if the user didn't open a file. Now I can't seem to make it work. Hiding the menu makes the dock and the status bar invisible. I want them to still be there, but not with my own menu (e.g. if you open a file from finder, the finder menu is still visible, but my app opens a window that handles the file, and quits if the user cancels or on completion).
A:
I probably didn't explain it well enough, but here's what I did to solve it :
Add this line to the plist of my app (this produces an app without dock icon or menu), the dock and the menu bar will still be there, but won't be changed by the app :
LSUIElement
(And set the checkbox to true).
This makes your app UI-only (it doesn't show his NSMenu nor does it add an icon to the dock, but just shows your GUI.
|
[
"stackoverflow",
"0006424775.txt"
] | Q:
Multiple page orientation in SSRS 2008
I'm preparing a series of reports in ssrs 2008. In order to comply with the requirements the first page of the report has to be in portrait orientation, while the rest of the document must use landscape orientation. I know there is no way to do this OOTB ( or perhaps you can prove me wrong :P ). I was wondering if there was a way to implement a custom renderer that could play with Page Orientation based on page breaks, or any other solution you knew of. I was reading through the questions and found this one Different orientation in a Multiple page PrintDocument (How to) Dunno if it could help me out with my reports. Any help will be greatly appreciated.
A:
Maybe a workaround could be to create the report in landscape and for the header page, use vertical text.
|
[
"stackoverflow",
"0020725742.txt"
] | Q:
Using Karma to scenario test an AngularJS controller?
Here is what I have tried:
$ git clone https://github.com/angular/angular-seed my_project && cd my_project
$ rm -rf app update_angular.js test/e2e/scenarios.js
$ touch test/e2e/scenarios.js
I then pasted code from AngularJS's official ngMock.$httpBackend docs into:
test/e2e/scenarios.js
'use strict'; // Line 1
function MyController($scope, $http) {...} // Lines 3-22
describe('MyController', function() {...} // Lines 24-87
Error
Unfortunately when I run the tests using config/karma-e2e.conf, I get:
ReferenceError: inject is not defined at
http://localhost:9876/base/test/e2e/scenarios.js?1387679134000:31
A:
inject is defined in angular-mocks file, and is intended for unit tests only. If you're using Karma just add it to the files array.
e2e tests are on top of the browser, and run by angular-scenario. you can't inject any Angular components there.
BTW the Angular team are in the process of migrating their functional testing to protractor which is based on Selenium. I'd catch up with that instead of the angular-scenario testing framework. Protractor is a lot better.
|
[
"stackoverflow",
"0062377345.txt"
] | Q:
JS Optimization - constantly setting variables on fast fire events
I am working on a script using Three.js where a lot a variables depend on mouse position. Does it matter if I am constantly setting variables to their same value each time the move event fires, or should I only set a variable when a change is detected?
Let's say I want to set a variable "quadrant" to 1,2,3 or 4 depending upon which part of the screen the mouse is over... should I use this :
var quadrant;
function mouseMove(e){
var mouse;
mouse.x = e.clientX;
mouse.y = e.clientY;
if(mouse.x < window.innerWidth / 2){
if(mouse.y < window.innerHeight / 2){
quadrant = 1;
} else {
quadrant = 3;
}
} else {
if(mouse.y < window.innerHeight / 2){
quadrant = 2;
} else {
quadrant = 4;
}
}
};
window.addEventListener('mousemove', mouseMove);
Which will reset the variable every time the event fires. Or should I only be setting variables when a change is detected, like this :
var quadrant;
function mouseMove(e){
var mouse;
mouse.x = e.clientX;
mouse.y = e.clientY;
if(mouse.x < window.innerWidth / 2){
if(mouse.y < window.innerHeight / 2){
if(quadrant != 1){
quadrant = 1;
}
} else {
if(quadrant != 3){
quadrant = 3;
};
}
} else {
if(mouse.y < window.innerHeight / 2){
if(quadrant != 2){
quadrant = 2;
};
} else {
if(quadrant != 4){
quadrant = 4;
};
}
}
};
window.addEventListener('mousemove', mouseMove);
Does the act of setting a variable to the memory (even if it's to the same value) cost more than it takes to read the extra lines of code necessary to add the conditions? I instinctively do the latter as it seems tidier and like less work at runtime, but I really have no idea how this actually translates to performance. I seem to remember reading that each time a variable is set in js that it's actually creating an instance of itself, which seems like work... but maybe I misunderstood.
A:
As noted in the comments, the simpler version is very likely to be faster - and it's easier to read and less error-prone too.
While I've got you, let me suggest a completely different approach: calculate the quadrant instead of using a bunch of if statements.
// Calculate the quadrant for a given x and y and width and height.
// The quadrants are defined like this:
//
// +---+---+
// | 1 | 2 |
// +---+---+
// | 3 | 4 |
// +---+---+
function getQuadrant( x, y, width, height ) {
return 1 +
( x >= width / 2 ) +
( y >= height / 2 ) * 2;
}
console.log( getQuadrant( 25, 25, 100, 100 ) ); // 1
console.log( getQuadrant( 75, 25, 100, 100 ) ); // 2
console.log( getQuadrant( 25, 75, 100, 100 ) ); // 3
console.log( getQuadrant( 75, 75, 100, 100 ) ); // 4
This code works because when you use an arithmetic operator on a boolean value, it converts a false value to 0 and a true value to 1.
I don't know if this will be faster or slower (you would have to benchmark it to find out) but since you are looking at different approaches to solving the problem, I thought you might find it interesting.
You may wonder "aren't those multiplies and divides slow?" But modern JavaScript engines, like most optimizing compilers, can convert multiplies or divides by a power of 2 into a very fast bit-shifting operation.
Let's take a look at the machine code that V8 generates for the getQuadrant function (just showing the core part of the code, not the function setup and teardown).
When we enter this code, the four function parameters are stored in these registers:
r8 is x.
r11 is y.
rdx is width.
rdi is height.
And here's the compiled code:
; Divide height and width by 2 for the comparisons below
sarl rdi, 1
sarl rdx, 1
; Compare y with half the height and set rcx to 0 or 1
cmpl rdi,r11
setlel cl
movzxbl rcx,rcx
; Compare x with half the width and set rdx to 0 or 1
cmpl rdx,r8
setlel dl
movzxbl rdx,rdx
; Set rdx to the final result, calculated in a single instruction
leal rdx,[rdx+rcx*2+0x1]
One likely performance advantage is that this code avoids the branches used by the if statements. On modern CPUs, when you can avoid branches, it is often a performance win.
But again, any of these approaches will likely be more than fast enough! Just posting this alternative method in case it is of interest to you.
If you're curious how I got that machine code listing, I created a standalone JavaScript file called quadrants.js with this content:
function getQuadrant( x, y, width, height ) {
return 1 +
( x >= width / 2 ) +
( y >= height / 2 ) * 2;
}
// We need to actually do something with the result returned by getQuadrant,
// otherwise the JavaScript engine may notice that the result is unused and
// it may skip compiling the function body entirely.
quadrants = [];
for( let i = 0; i < 1000000; ++i ) {
quadrants.push( getQuadrant( 25, 25, 100, 100 ) );
quadrants.push( getQuadrant( 75, 25, 100, 100 ) );
quadrants.push( getQuadrant( 25, 75, 100, 100 ) );
quadrants.push( getQuadrant( 75, 75, 100, 100 ) );
}
// Log the first few results as a sanity check
console.log( quadrants.length );
for( let i = 0; i < 16; ++i ) {
console.log( quadrants[i] );
}
Then I ran it with this command:
node --print-opt-code --code-comments quadrants.js >code.txt
And then I looked through the generated code.txt file to find the code for the getQuadrant function.
|
[
"stackoverflow",
"0003749504.txt"
] | Q:
Which thread pool manager is recommended for Perl?
I only know of Thread::Pool which is apparently not supported in recent Perl versions, and Thread::Pool::Simple which lacks almost any documentation.
So which thread pool manager can I use under Perl v5.10.1 or and higher?
A:
See How can I install `Thread::Pool` from CPAN?.
|
[
"ell.stackexchange",
"0000132659.txt"
] | Q:
Is my correction of the sentence is correct?
I think Raveena is the most talented of the two.
Actual answer is Only one error i.e Most must replaced with More.
But I find another error is of the must replaced with than
My Sentence:
I think Raveena is the more talented than two.
Is my sentence correct?
A:
The second correction is not needed.
When you use a comparative or superlative, you have a few options:
(1) X is more talented (than Y).
(1) is a direct comparison between two entities.
(2) X is the most talented (in the group).
(2) picks out one person as more talented than everyone else in the group.
Then we have the structure that was on your assignment:
(3a) X is the more talented (of the two).
(3b) X is the most talented (of the three / of all).
(3) is very much like (2). It picks out one person as more talented than everyone else in the group. Here, "of the three" means something like "when considering the three (people)".
But when the group consists of exactly two people, you change "the most" into "the more".This is what you see in your sentence.
|
[
"stackoverflow",
"0015578194.txt"
] | Q:
How to pass Perl variable into Javascript function?
I have a Perl script which prints out of html page. I want to use javascript to pop alert msg. The alert message is defined as string in the perl variable. I am trying to pass the perl variable value to javascript function as argument but it's not working. Please help.
$perl_variable = "Welcome"; # alert msg
print <<START
<HTML>
some html code....
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction('$perl_variable')">Try it</button>
<script>
function myFunction(var message){
setTimeout(function(){alert(message)},3000);
}
</script>
</HTML>
START
A:
NB: The first half of this answer refers to the code that originally (before edits) appeared in the question.
You need to:
Use the right variable name
Generate a JavaScript string literal (by quoting the data)
Such:
myFunction('$perl_variable')
Note that if your data might include characters that are not allowed in a JavaScript string literal (such as a new line), characters that have special meaning in a string literal (such as the quote mark that delimits it) or characters that have special meaning in HTML (such as the quote mark that delimits the attribute value) then you will also need to perform suitable escaping (in two steps, first for JS, then for HTML).
As an aside, your function definition in JS is also wrong:
function myFunction(var path){
The var keyword may not be used in the FormalParameterList. That should read:
function myFunction(path){
|
[
"stackoverflow",
"0021963468.txt"
] | Q:
php Regular Expression Issues - Can't remove/strip out and replace a string within a string
I have never worked with regular expressions before and I need them now and I am having some issues getting the expected outcome.
Consider this for example:
[x:3xerpz1z]Some Text[/x:3xerpz1z] Some More Text
Using the php preg_replace() function, I want to replace [x:3xerpz1z] with <start> and [/x:3xerpz1z] with </end> but I can't figure this out. I have read some regular expression tutorials but I am still confused.
I have tried this for the starting tag:
preg_replace('/(.*)\[x:/','<start>', $source_string);
The above would return:<start>3xerpz1z
As you can see, the "3xerpz1z" isn't getting removed and it needs to be stripped out. I can't hard code and search and replace "3xerpz1z" because the "3xerpz1z" chars are randomly generated and the characters are always different but the length of the tag is the same.
This is the desired output I want:
<start>Some Text</end> Some More Text
I haven't event tried processing [/x:3xerpz1z] because I can't even get the first tag going.
A:
You must use capturing groups (....):
$data = '[x:3xerpz1z]Some Text[/x:3xerpz1z] Some More Text';
$result = preg_replace('~\[x:([^]]+)](.*?)\[/x:\1]~s', '<start>$2</end>', $data);
pattern details:
~ # pattern delimiter: better than / here (no need to escape slashes)
\[x:
([^]]+) # capture group 1: all that is not a ]
]
(.*?) # capture group 2: content
\[/x:\1] # \1 is a backreference to the first capturing group
~s # s allows the dot to match newlines
|
[
"stackoverflow",
"0057729295.txt"
] | Q:
how to get os.getenviron.get variable with space in it?
So i've created an enviroment variable for a specific path on my MacOS computer. The path has a space in it and looks like this /Users/myUser/Library/Application Support . I can get this path successfully from my terminal by wrapping quotation marks around it like "$variable".
However if I from terminal type it without the quotation marks $variable then it just returns /Users/myUser/Library/Application which is an issue, because then it doesn't find the folder I need.
This is what I have an issue with in python3 also.
datadir_path = os.environ.get("variable")
returns /Users/myUser/Library/Application , which is again an issue because it's missing the last part of the path due to the space in it.
How do I overcome this and get the correct path with os.environt.get?
A:
You need to include quotes around $variable when you export it, and remember to source your .bash_profile, or restart your terminal before you can access $variable from python.
So add export variable="/Users/myUser/Library/Application Support" to .bash_profile then run:
$ source .bash_profile
$ python
>>>import os
>>> os.environ.get("variable")
"/Users/myUser/Library/Application Support"
>>>
|
[
"stackoverflow",
"0013277339.txt"
] | Q:
adding a second 3dplot
I have a 3d scatterplot produced as follows:
library(rgl)
N <- 10000
X <- rnorm(N,0,1)
Y <- rnorm(N,0,1)
Z <- X * Y
want <- Z >0 & X>0
palette <- colorRampPalette(c("blue", "green", "yellow", "red"))
col.table <- palette(256)
col.index <- cut(Z, 256)
plot3d(X,Y,Z, col=col.table[col.index])
grid3d(c("x", "y", "z"))
This works fine. Now I want to overlay another plot, so I tried this:
par(new=F)
plot3d(X[want],Y[want],Z[want], col="black")
However this fails - it just overwrites the old plot. Is there a way to overlay the new plot ?
A:
Although I haven't tested it, I think you should start by trying points3d instead of plot3d ... and FYI par(new=FALSE) doesn't have any effect on rgl plots at all, only base plots.
A:
A very simple solution is to use the add = TRUE argument:
plot3d(X[want], Y[want], Z[want], col = 'black', add = TRUE)
|
[
"gamedev.stackexchange",
"0000099175.txt"
] | Q:
Given a constant rotation and target point, find position so that point will be in camera center
Given a fixed rotation and a target "center" point, how to I find the position the camera should be in so that that point is the center? LookAt changes the rotation keeping the position constant. Basically, I'm trying to do the reverse, but the math escapes me :-). Thanks!
Camera is currently psuedo-isometric (orthographic with rotation from Euler angles [X:35.264389683ish°, Y:45°, Z:0°]). Might want to change these a bit or allow rotation though, so ideally a solution would work for any rotation. Can easily get the projection matrix.
EDIT: thinking about it, there would be infinite such positions that satisfy this constraint. I would want to fix the Y component of the position (camera height) and find only an X/Z.
Thanks to Mokosha's answer below, here's the final code I'm using:
private static Vector3 reverseLookAt(Quaternion cameraRotation, float cameraHeight, Vector3 targetPosition)
{
Vector3 d = cameraRotation * Vector3.forward;
Plane plane = new Plane(Vector3.up, -cameraHeight);
Ray ray = new Ray(targetPosition, d);
Vector3 pos = UnityUtils.intersect(ray, plane);
return pos;
}
A:
Let's rephrase your question:
Given a rotation R, and a position p, we would like the rotated point p' to lie along the Z-axis (also known as the center of the camera). For this, we can use linear algebra:
Compose the rotation matrix R from your euler angles.
Solve problem (1) which we can rewrite as (2):
$$\begin{align}Rd&=\begin{vmatrix} 0 & 0 & 1 \end{vmatrix}^T \tag 1\\
\\
d &= R^{-1}\begin{vmatrix}
0 \\
0 \\
1
\end{vmatrix}\tag 2\end{align}$$
d is now the direction in world space that corresponds to the Z-axis of the camera in eye space. Construct p' by translating p by d: p' = p + d.
Using p and p', construct a line P.
Compute the intersection of P with the plane whose normal is [0 1 0] at D distance away from the origin where D is the desired Y value of your camera in world units.
The code for this in Unity's C# would look something like this:
Quaternion rot = ...
Vector3 p = ...
float desired_y = ...
Vector3 d = rot * (new Vector3(0, 0, 1)); // Perhaps Camera.forward...?
Vector3 camPos;
if (Mathf.Abs(d.y) < Mathf.epsilon) {
Log.Error("Camera direction parallel to XZ plane");
} else {
Plane y_plane = new Plane(new Vector3(0, 1, 0), desired_y);
float dist;
y_plane.Raycast(new Ray(p, p + d), dist)
camPos = r.GetPoint(dist);
}
|
[
"stackoverflow",
"0042764102.txt"
] | Q:
CNTK (Microsoft Cognitive Toolkit) in python incurs ImportError
Code:
import cntk
n = cntk.minus([1, 2, 3], [4, 5, 6]).eval()
print(n)
Problem:
If run the code line by line in python command line, it's ok.
If run "Python main.py", it's also ok.
But if run the code in PyCharm or Visual Studio Code, error occurs, PyCharm error dump:
Traceback (most recent call last):
File "D:\Apps\Anaconda3\envs\Python3.53\lib\site-packages\cntk\cntk_py.py", line 18, in swig_import_helper
return importlib.import_module(mname)
File "D:\Apps\Anaconda3\envs\Python3.53\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'cntk._cntk_py'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/Dev/machine_learning/Test_CNTK/main.py", line 1, in <module>
import cntk
File "D:\Apps\Anaconda3\envs\Python3.53\lib\site-packages\cntk\__init__.py", line 11, in <module>
from .core import *
File "D:\Apps\Anaconda3\envs\Python3.53\lib\site-packages\cntk\core.py", line 10, in <module>
from . import cntk_py
File "D:\Apps\Anaconda3\envs\Python3.53\lib\site-packages\cntk\cntk_py.py", line 21, in <module>
_cntk_py = swig_import_helper()
File "D:\Apps\Anaconda3\envs\Python3.53\lib\site-packages\cntk\cntk_py.py", line 20, in swig_import_helper
return importlib.import_module('_cntk_py')
File "D:\Apps\Anaconda3\envs\Python3.53\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: DLL load failed: The specified module could not be found.
Environment:
Anaconda: 4.3.1
Python: 3.5.3 (virtual environment in anaconda)
CNTK: 2.0beta12 for windows amd64 GPU
PyCharm: 2016.3.2
Visual Studio Code: 1.10.2
A:
Solved
Because it can't find the DLL files with CNTK (e.g. CNTKLibrary-2.0.dll, EvalDll.dll), these DLLs are in the same directory of "python.exe" after installation of CNTK.
There are 2 solutions:
(suppose the PYTHONDIR is the directory where python.exe is in)
change the system environment PATH to include PYTHONDIR
add the following code before "import cntk":
import os; os.environ['PATH'] = PYTHONDIR + ';' + os.environ['PATH']
|
[
"stackoverflow",
"0035403463.txt"
] | Q:
How to install KDevelop 5 on Red Hat 7
I'd like to see how KDevelop 5 works. I have a RedHat 7 machine where I am a regular user (not root) and try to build KDevelop from sources. I've looked at the list of required software and found that I need kdelibs-devel as one of dependencies. Unfortunately, I cannot find such a packages. There are too many small bundles on the KDE site and nothing named kdelibs-devel. Can anybody advise? Is there a simpler way to build KDevelop5?Regards, Michael
A:
For the final 5.0 release, we now provide an AppImage which you can just download and run without compiling anything. It should work, if not, let us know.
Check out: https://www.kdevelop.org/download
|
[
"stackoverflow",
"0017502946.txt"
] | Q:
Is it possible to write fizzbuzz using only 2 checks?
the obvious solution is something like:
if (x % 15 == 0) println("fizzbuzz");
else if (x % 3 == 0) println ("fizz");
else if (x % 5 == 0) println ("buzz");
then you could say that the trick is to concatenate fizz and buzz:
if (x % 3 == 0) print("fizz");
if (x % 5 == 0) print("buzz");
if (x % 15 == 0) println();
or
print("%s%s%s", x % 3 == 0 ? "fizz" : "", x % 5 == 0 ? "buzz" : "", x % 15 == 0 ? "\r\n" : "");
so the problem is the line break, and in all of the above cases we are performing 3 checks.
assuming that there needs to be a line break after either "fizz", or "buzz", how can it be done using only 2 checks?
A:
How about no checks?
string[] output = { "fizzbuzz", "", "", "fizz", "", "buzz", "fizz", "", "", "fizz", "buzz", "", "fizz", "", "" };
print("%s", output[x % 15]);
Note that this of course only removes if statements from this code. The underlying code will most likely contain a jump instruction or two.
If you want to make it a bit clearer what is happening you can create two arrays:
string[] fizz = { "fizz", "", "" };
string[] buzz = { "buzz", "", "", "", "" };
print("%s%s", fizz[x % 3], buzz[x % 5]);
Note that both of these implementations will not handle negative numbers, here's a version that does:
string[] fizz = { "fizz", "", "" };
string[] buzz = { "buzz", "", "", "", "" };
print("%s%s", fizz[((x % 3) + 3) % 3], buzz[((x % 5) + 5) % 5]);
Note that I have neatly skipped over the newline you added in your code. If you want that, I'm sure you can figure out how to modify the above code in the same manner to add it :)
More importantly: Note that this does in fact not pass the "official" fizzbuzz test, it only answers your question.
The fizzbuzz test is this:
Write out all numbers from 1 to 100, except that numbers that are multiplies of 3 you should instead of the number write out "fizz", and that for numbers that are multiplies of 5 you should instead of the number write out "buzz". If a number is a multiple of both 3 and 5 at the same time, write out "fizzbuzz" instead of the number.
Since your question did not in any way handle the "instead of the number" part, my answer did not either.
So, if we skip the fact that a loop usually entails a "check", can we write the entire fizzbuzz test without if-statements?
With a bit of magic, yes we can, here's the loop in C# code, you can verify this using LINQPad or Ideone:
void Main()
{
string[] fizzbuzz = new[]
{
"fizzbuzz", "{0}", "{0}", "fizz", "{0}", "buzz", "fizz",
"{0}", "{0}", "fizz", "buzz", "{0}", "fizz", "{0}", "{0}"
};
for (int index = 1; index <= 100; index++)
{
Debug.WriteLine(string.Format(fizzbuzz[index % 15], index));
}
}
Here I'm relying on the fact that the format string sent to string.Format does in fact not have to contain any references to the arguments.
Edit: As stated in the comments, I had used ?? to get the "{0}" in the string.Format parameter and leaving the entries in the array at null, but ?? is indeed an if-statement in disguise, so edited it out.
|
[
"stackoverflow",
"0061240463.txt"
] | Q:
Angular 8/9 and Virtual folder (IIS and localhost) issue
I have created a virtual folder in Angular 8/9 under assets folder to store some of my mp4 videos. My environment is Windows 10 and VS2019 and my project has been create using Microsoft Angular template (Angular and MVC integrated).
The issue is that I can not play the mp4 file if the folder is the virtual folder. However, if it is a real folder, then I can play the mp4 file fine. I already set up permission to the virtual folder and it is still not working. I did search for solutions and suggestions but I don't see any one has the issue.
The other thing I have looked is that if i type full address to the browser (for example https:\localhost\assets\videos\myvideo.mp4), the browser directs me to the home page instead. Do you think it is router issue?
If it is router issue, how do I correct it?
Please advise.
Thank you
A:
This is what I have to do to make it to work (just in case that someone may run into this issue like me -- it saves a lot of times).
The url https:\\localhost\assets\videos\myvideo.mp4 is not working if the videos folder is a virtual folder (note: it works if it is real folder).
This 'https:\\localhost\clientapp\dist\assets\videos\myvideo.mp4' is WORKING if videos folder is a virtual folder.
Thank you.
|
[
"stackoverflow",
"0039337066.txt"
] | Q:
Super simple framework 301 redirect from Symfony routes
I try to build super simple framework. I don't want to use constrollers... basicly everything works good and this is great start for simple websites but I want one more feature that I have problems with.
I try to achieve as simple as possible solution to add in routes pages with 301 redirect. For example I want /facebook with 301 to http://facebook.com/example.
Here is my code... index.php below:
<?php
require_once __DIR__.'/../vendor/autoload.php';
$dotenv = new Dotenv\Dotenv(__DIR__.'/../');
$dotenv->load();
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing;
$request = Request::createFromGlobals();
$routes = include __DIR__.'/../routes/web.php';
$context = new Routing\RequestContext();
$context->fromRequest($request);
$matcher = new Routing\Matcher\UrlMatcher($routes, $context);
try {
extract($matcher->match($request->getPathInfo()), EXTR_SKIP);
ob_start();
include sprintf(__DIR__.'/../resources/views/%s.php', $_route);
$response = new Response(ob_get_clean());
} catch (Routing\Exception\ResourceNotFoundException $e) {
$response = new Response();
$response->setStatusCode(404);
include __DIR__.'/../resources/views/errors/404.php';
} catch (Exception $e) {
$response = new Response();
$response->setStatusCode(500);
include __DIR__.'/../resources/views/errors/500.php';
}
$response->send();
And my routes.php code:
<?php
use Symfony\Component\Routing;
$routes = new Routing\RouteCollection();
// 200
$routes->add('index', new Routing\Route('/'));
$routes->add('index', new Routing\Route('/about'));
$routes->add('index', new Routing\Route('/contact'));
// 301
// redirect from /facebook to -> http://facebook.com/example
// redirect from /twitter to -> http://twitter.com/example
return $routes;
Now I can make specific file for that route just like for the others and inside that file I can add header php redirect... but this is tedious approach. What can I do to define that redirect inside routes directly?
A:
In your case you can do the following:
//routes.php
use Symfony\Component\HttpFoundation\RedirectResponse;
$permanentRedirect = function ($url) {
return new RedirectResponse($url, 301);
};
//...
$routes->add('facebook', new Routing\Route('/facebook', array(
'_controller' => $permanentRedirect,
'url' => 'http://facebook.com/example',
)));
//...
return $routes;
Next, in your index.php:
//...
try {
extract($matcher->match($request->getPathInfo()), EXTR_SKIP);
if (isset($_controller) && isset($url)) {
$response = call_user_func($_controller, $url);
} else {
ob_start();
include sprintf(__DIR__.'/../resources/views/%s.php', $_route);
$response = new Response(ob_get_clean());
}
} catch (Routing\Exception\ResourceNotFoundException $e) {
//...
} catch (Exception $e) {
//...
}
|
[
"stackoverflow",
"0010906289.txt"
] | Q:
Is this shuffling algorithm sufficiently random for an iOS card game?
Didn't wanna just post, "Hey, guys, can you come up with an awesome randomization method for me?" so I've been studying algorithms for shuffling a deck of cards, creating truly random permutations, etc., ALL DAY LONG and it's been rrrrrrrreally daunting. Finally settled on a simpler approach, shown below. While I do want to create a quality game, of course, I'm not going to be using this algorithm in an online casino or anything. It's just an iOS game. So, is this random/memory-efficient enough? Or should I be giving this even MORE time and effort? TIA
Aside: Whenever I write "TIA," I think, "This is Africa," not "Thanks in advance."
@implementation NSMutableArray (Shuffle)
-(void)shuffle
{
for (int i = [self count] - 1; i > 0; i--) {
[self exchangeObjectAtIndex:(arc4random() % ([self count] - 1))
withObjectAtIndex:i];
}
}
@end
EDIT:
Ok. Wanted to run some test code so I don't post something dumb. :) In response to Adam and Nielsbot, you're recommending something more like this?
-(void)shuffle
{
for (int i = [self count] - 1; i > 0; i--) {
[self exchangeObjectAtIndex:(arc4random_uniform([self count] - 1))
withObjectAtIndex:i];
}
}
Is that right?
Would there be any benefit to repeating it, like so?
-(void)shuffle
{
for (int i = [self count] - 1; i > 0; i--) {
[self exchangeObjectAtIndex:(arc4random_uniform([self count] - 1))
withObjectAtIndex:i];
}
for (int i = [self count] - 1; i > 0; i--) {
[self exchangeObjectAtIndex:(arc4random_uniform([self count] - 1))
withObjectAtIndex:i];
}
}
A:
That's almost the so called Fisher-Yates algorithm, it's O(n) as time complexity and memory efficience is not considerable since you don't allocate anything.
The only thing I'd change is the randomly chosen index that would be in range [0, i] for i-th iteration instead that the whole range (to avoid just swapping two elements twice), then it would become the algorithm I linked.
|
[
"stackoverflow",
"0028166777.txt"
] | Q:
mongodb unwind aggregate result?
So I'm trying to produce some statistics in my database using aggregation
My current script looks like this:
db.posts.aggregate( [
{ $group: {_id : "$domain", "counter" : {$sum : 1}}},
{ $sort : { counter : -1}},
{ $match : { counter : {$gt : 10} } }
])
and produces result like this:
{
"result" : [
{
"_id" : "i.imgur.com",
"counter" : 1220
},
{
"_id" : "imgur.com",
"counter" : 459
}
],
"ok" : 1
}
Quite satisfactory, but I want to move further. I'm using robomongo (more comfortable to me) and this appears like single document to me:
I want to have each result to be a separate document like this:
| _id | counter
---+-------------+--------
1 | i.imgur.com | 1220
---+-------------+--------
2 | imgur.com | 459
I assumed I needed to use $unwind, but failed miserably: adding { $unwind : "$result"} to aggregate chain produces this output:
/* 0 */
{
"result" : [],
"ok" : 1
}
What have I done wrong and how to do it right?
A:
I don't use robomongo, but it seems like you could tack on .result to your script to get the results output you want.
db.posts.aggregate( [
{ $group: {_id : "$domain", "counter" : {$sum : 1}}},
{ $sort : { counter : -1}},
{ $match : { counter : {$gt : 10} } }
]).result
I've done some looking into this and it appears that the return output you are getting is a consequence of robomongo using db.posts.runCommand("aggregate", {pipeline: [<array of pipeline operators>]}) and then not "instantiating a cursor" rather than the aggregate() helper which creates a cursor.
I don't think there's much you can do on this outside of filing a ticket.
|
[
"stackoverflow",
"0031426130.txt"
] | Q:
Linode VPS storage capacity
I recently uploaded my site(a voters registration app) to a LINODE VPS 1 Gig, with 98304 MB total storage.I am expecting for a maximum of 50 million voters (maybe less for that) to register in this site until next year.My concern is, is this storage is enough to hold that number of data?Every voter is required to fill up minimal information in the form for their complete name, age, address and profession.
A:
The size to store the requested information (name, age, address, profession) in text format for my personal information was about 100 Bytes. Using this as a very rough average, we can calculate the total size to store 50 million:
50,000,000 * 100 B = 5,000,000,000 B / 1024 B/KB / 1024 KB/MB / 1024 MB/GB = 4.66 GB
If you have 96 GB of storage, and if you are expecting to store only the above mentioned data, that will be more than enough even if the estimate of 4.66 GB is off by double or more.
One great advantage of Linode is that you can adjust the size of your VPS to scale with demand. So if it turns out that you do need more storage capacity after launching the app, you can upgrade seamlessly using Linode's management dashboard. Here are the instructions on Resizing a Linode:
https://www.linode.com/docs/migrate-to-linode/disk-images/resizing-a-linode
|
[
"security.stackexchange",
"0000133476.txt"
] | Q:
Ransomware encrypted first 64 kB of file
I heard about a ransomware virus going around that encrypts only the first 64 kB of a file. If I was infected with this, would it be realistically possible to retrieve my files?
A:
Not really. If the files had a very large common header (64kb or more), you might be in luck, else you're essentially trying to guess 64,000 "characters". Assuming the file used only 64 characters (e.g. it was a Base64 encoded file), for example purposes, that would be 64^64000 possibilities. That's a number with over 100,000 digits in.
Given that guessing a 12 character long password is considered "hard", and that only has 64^12 (4,722,366,482,869,645,213,696 - only 22 digits!) possibilities, you can see the issue. Guessing a 64kb "string" is over 4500 times harder, and that's ignoring that files aren't restricted to 64 characters in reality.
In practice, a lot of file types wouldn't require all the bytes to be guessed, but most file headers are much smaller than 64kb, so there will be quite a lot of unknown data even so.
|
[
"math.stackexchange",
"0001569348.txt"
] | Q:
Software where I can numerically evaluate multivariable integrals over a region?
I need, for example, to evaluate:
$$\iiint(x-1)\,dx\,dy\,dz$$
over the region:
$$y=0,\, z=0,\, y+z=5,\, z=4-x^2$$
but I have no ways to verify if I did it right. I needed a form of numerical evaluation. Can I do it in wolfram alpha?
A:
Here's one way to compute the integral:$$\iiint_D(x-1)\,\mathrm{d}x\,\mathrm{d}y\,\mathrm{d}z=\int_{-2}^2\int_0^{4-x^2}\int_0^{5-z} (x-1)\,\mathrm{d}y\,\mathrm{d}z\,\mathrm{d}x$$
where $D$ is the region defined by the limits. I've included a plot of the region bounded by the surfaces below.
The integral can indeed be computed with software (I'm using Mathematica). There are several ways to do it via Integrate. Here's one using the standard Integrate form.
In[32]:= Integrate[x - 1, {x, -2, 2}, {z, 0, 4 - x^2}, {y, 0, 5 - z}]
Out[32]= -(544/15)
And here's another that integrates over the region.
In[36]:= Integrate[(x - 1) Boole[0 <= y <= 5 - z && 0 <= z <= 4 - x^2 && -2 <= x <= 2],
{x, -Infinity, Infinity}, {z, -Infinity, Infinity}, {y, -Infinity, Infinity}]
Out[36]= -(544/15)
Edit: Mathematica code for graphics.
surfaces = ContourPlot3D[{y == 0, z == 0, y + z == 5, z == 4 - x^2},
{x, -4, 4}, {y, -1, 6}, {z, -1, 5},
AxesLabel -> {x, y, z}, ContourStyle -> Opacity[0.25], Mesh -> False];
region = RegionPlot3D[0 <= y <= 5 - z && 0 <= z <= 4 - x^2 && -2 <= x <= 2,
{x, -4, 4}, {y, -1, 6}, {z, -1, 5}, MaxRecursion -> 3, PlotPoints -> 50, Mesh -> False];
Show[surfaces, region]
|
[
"math.stackexchange",
"0000739476.txt"
] | Q:
The Identity Theorem for real analytic functions
What is the condition for two real analytic functions to be identically equal? We know that there is a nice condition (Identity Theorem) for holomorphic function to check if they are the same. What is its version for real analytic functions?
A:
As a reference, I suggest A Primer of Real Analytic Functions by Krantz and Parks.
The two versions of the Identity Theorem stated by Daniel Fisher can be unified at the expense of more complicated statement.
If $U$ is a domain, and $f,g$ are two real-analytic functions defined on $U$, and if $V\subset U$ is a nonempty open set with $f\lvert_V \equiv g\lvert_V$, then $f \equiv g$. If the domain is one-dimensional (an interval in $\mathbb{R}$), then it suffices that $f\lvert_M \equiv g\lvert_M$ for some $M\subset U$ that has an accumulation point in $U$.
Claim. If $f,g$ are real analytic and there is a point $p\in \mathbb R^n$ such that the set of all limits
$$ \left\{\lim_{n\to \infty} \frac{x_n-p}{|x_n-p|} : \qquad f(x_n)=g(x_n),\ x_n\to p, \ x_n\ne p\right\} \tag{1}$$
has an interior point in the topology of the sphere $S^{n-1}$, then $f\equiv g$.
Indeed, suppose $f-g$ is not identically zero. Express its Taylor series at $p$ as the sum of homogeneous polynomials $P_d$. Let $d$ be the smallest degree for which $P_d$ is not identically zero. Then the set defined by (1) can be shown to be precisely
$$
S^{n-1} \cap \{ P_d =0\}
\tag{2}$$
Since the zero set of a polynomial has empty interior in $\mathbb R^n$, it follows that (2) has empty interior in $S^{n-1}$. $\quad \Box$
When $n=1$, the sphere $S^0$ is a two-point set, so any nonempty subset of it has nonempty interior. We thus recover the one-dimensional result.
|
[
"stackoverflow",
"0051345615.txt"
] | Q:
trying to use the "search" method but I still have an error
Hi this is my first time trying to use the search method, I am using the Search Bar Guide on Apple Developer website but I have this issue and can't seem to figure it out. I have my Data stored in a Class DataServices and I have my tableView cells working just perfect in my ViewController, but I can't seem to figure out what I am supposed to return in the search method to complete the method, When I do it just as the search Guide instructions Xcode screams at me. Can you bless me with your knowlegde
class ListVC: UIViewController,UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
var filteredData: [List]!
let data = DataServices.instance.getList()
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
tableView.dataSource = self
tableView.dataSource = self
filteredData = data
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataServices.instance.getList().count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ListingCell") as? ListCell {
let listing = DataServices.instance.getList()[indexPath.row]
cell.updateView(lists: listing)
return cell
}else {
return ListCell()
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = searchText.isEmpty ? data: data.filter({ (List: String) -> Bool in
return List.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
> Value of type 'List' has no member 'range' is the error I get
})
tableView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.searchBar.showsCancelButton = true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
searchBar.text = ""
searchBar.resignFirstResponder()
}
}
class DataServices {
static let instance = DataServices()
private let currentList = [
List(firstText: "Name", secondText: "Shannon"),
List(firstText: "Car", secondText: "Infinity"),
List(firstText: "City", secondText: "Brandon"),
List(firstText: "Wife", secondText: "Naedra"),
List(firstText: "Child", secondText: "Shantae"),
List(firstText: "Job", secondText: "Driver"),
List(firstText: "Cell", secondText: "iPhone"),
List(firstText: "Computer", secondText: "Imac")
]
func getList() -> [List] {
return currentList
}
}
struct List {
private (set) public var toptitle: String
private (set) public var bottomtitle: String
init(firstText: String, secondText: String) {
self.toptitle = firstText
self.bottomtitle = secondText
}
}
A:
Closure parameters represent instances not types and the filter closure applied to an array takes only one argument. The checking for empty string is redundant.
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = data.filter ({ (list) -> Bool in
return list.firstText.range(of: searchText, options: .caseInsensitive) != nil ||
list.secondText.range(of: searchText, options: .caseInsensitive) != nil
})
tableView.reloadData()
}
or with simplified syntax
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = data.filter { $0.firstText.range(of: searchText, options: .caseInsensitive) != nil ||
$0.secondText.range(of: searchText, options: .caseInsensitive) != nil }
tableView.reloadData()
}
I recommend to declare filteredData as non-optional empty array to avoid unnecessary unwrapping
var filteredData = [List]()
and force downcast the cell, if the code crashes it reveals a design mistake.
let cell = tableView.dequeueReusableCell(withIdentifier: "ListingCell", for: indexPath) as! ListCell
If you want constants in your List struct simply write
struct List {
let toptitle: String
let bottomtitle: String
}
you get the initializer for free. private (set) var is very objective-c-ish
Finally getting the same (static) list on each call of cellForRow is unnecessarily expensive, get the item from data
let listing = data[indexPath.row]
|
[
"stackoverflow",
"0031151249.txt"
] | Q:
celery worker only work once
full steps:
start django
start a celery worker
python manage.py celery worker --app=celery_worker:app -Ofair -n W1
upload a url list file, loop url list send each url to a task fetch_article
worker works
upload another url list file
worker no actions
views.py:
@csrf_exempt
def upload(request):
job_name = request.POST.get('job_name')
if not job_name:
return JsonResponse(JsonStatus.Error)
if len(request.FILES) == 1:
yq_data = request.FILES.values()[0]
else:
return JsonResponse(JsonStatus.Error)
job = Job.objects.create(name=job_name)
reader = csv.reader(yq_data, delimiter=',')
task_count = 0
next(reader)
for row in reader:
url = row[0].strip()
fetch_article.delay(job.id, url)
# fetch_article.apply_async(args=[job.id, url], queue=job.queue_name)
task_count += 1
# print 'qn%s' % job.queue_name
# rp = celery_app.control.add_consumer(queue=job.queue_name, reply=True)
# print rp
job.task_count = task_count
job.save()
return JsonResponse(JsonStatus.OK, msg=task_count)
tasks.py
@shared_task()
def fetch_article(job_id, url):
logger.info(u'fetch_article:%s' % url)
Processer = get_processor_cls(url)
a = Article(job_id=job_id, url=url)
try:
ap = Processer(url)
title, text = ap.process()
a.title = title
a.content = text
except Exception as e:
a.status = 2
a.error = e
logger.error(u'fetch_article:%s error:%s' % (url, e))
a.save()
A:
OK, I found the problem.
Because I set CELERY_ALWAYS_EAGER = True in settings.
The task run in django main process, so worker no actions
from doc:
CELERY_ALWAYS_EAGER If this is True, all tasks will be executed
locally by blocking until the task returns. apply_async() and
Task.delay() will return an EagerResult instance, which emulates the
API and behavior of AsyncResult, except the result is already
evaluated.
That is, tasks will be executed locally instead of being sent to the
queue.
For the worker work first time, I am still confuse, may be there are some urls in previous job's queue.
|
[
"security.stackexchange",
"0000187779.txt"
] | Q:
Need of scope in OAuth Client Credentials Flow
For me, Client Credential flow is like client is asking access token for itself - not on behalf of some user.
Then, why would client like to limit its own scope? What is the benefit of scopes in client credential flow?
A:
In case a client is requesting the access token for just a specific use case for which only a subset of scopes is required it could make sense that the client narrows down the scope. In case the access token is leaked an attacker would have access to only this use case.
|
[
"math.stackexchange",
"0002850288.txt"
] | Q:
Area of a line - $\infty$ or $0$
So today read something about two and three dimensional co-ordinate system and also about infinity and something came to me that I have been since pondering on.
So my question is, what is the area of an infinite line? Is it $\infty$ or is it$0$??.
Well if we consider the fact that it is one-dimentional, then of course area is $0$. But since we are mentioning it to be an infinite line, then area should be $\infty$, as it can be making a circle of infinite radius. Can anyone give me a technical explanation for this hypothetical question. Thanks, cheers!!
A:
It really depends on the limiting process. Say you have a rectangle with length $x$ and width $1/x.$ You take $x\to \infty$ and this starts to look more and more like an infinite line since the length gets infinitely long and the width goes to zero. However, at all times the area is $1,$ which is neither zero, nor infinity.
On the other hand, you could take length $x^2$ and width $1/x$ and then the area would go to to infinity. Or you could take length $x$ and width $1/x^2$ and the area would go to zero. You could also take length $ax$ and width $1/x$ and make the area limit to $a$ for any $a>0.$
|
[
"stackoverflow",
"0029742876.txt"
] | Q:
AngularJS - JSON string to select
Beginner in AngularJS. I have a JSON string that has only dates which needs to be populated in html select. Below is what I tried.
JSON string would look like
[{"Dates":"04/10/2015"},{"Dates":"04/03/2015"},{"Dates":"02/20/2015"},{"Dates":"02/13/2015"},]
My JS would look like
<script>
var app = angular.module('myApp', []);
app.controller('dvDates', function ($scope, $http) {
$scope.Dates = [];
$http.post("Basics1.aspx/GetDates", { data: {} })
.success(function (data, status, headers, config) {
var results = JSON.parse(data.d);
$scope.Dates = results;
})
.error(function (data,status,headers,config) { });
});
</script>
HTML Code:
<div ng-app="myApp" ng-controller="dvDates">
<select ng-model="Dates" ng-options="item.Dates as item.Dates for item in Dates">
<option value=""> Select From Date</option>
</select>
</div>
The result is as below. Dropdownlist is shown properly.
<select class="ng-pristine ng-valid ng-touched" ng-options="item.Dates as item.Dates for item in Dates" ng-model="Dates">
<option value=""> Select From Date</option>
<option value="0" label="04/10/2015">04/10/2015</option>
<option value="1" label="04/03/2015">04/03/2015</option>
<option value="2" label="02/20/2015">02/20/2015</option>
<option value="3" label="02/13/2015">02/13/2015</option>
<option value="4" label="02/06/2015">02/06/2015</option>
<option value="5" label="01/30/2015">01/30/2015</option>
</select>
But when I select any value for this, the HTML changes as below and all the values wipes out.
<select class="ng-valid ng-dirty ng-touched" ng-options="item.Dates as item.Dates for item in AsOf" ng-model="Dates">
<option value="? string:01/30/2015 ?"></option>
<option value=""> Select From Date</option>
</select>
Please let me know what I'm doing wrong. The issue happens only with Dates. When I try with normal string to populate in Select, everything works as expected.
A:
You need to change your model in select from
ng-model="Dates"
for somthign different ie
ng-model="selected.Date"
otherwise every time when you choose something from your select box, you overwrite your $scope.Dates model
angular.module("app", [])
.controller('homeCtrl', function($scope) {
$scope.Dates = [{
"Dates": "04/10/2015"
}, {
"Dates": "04/03/2015"
}, {
"Dates": "02/20/2015"
}, {
"Dates": "02/13/2015"
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="homeCtrl">
<select ng-model="selected.Date" ng-options="item.Dates as item.Dates for item in Dates">
<option value="">Select From Date</option>
</select>
Selected : {{selected.Date}}
</div>
</body>
|
[
"stackoverflow",
"0000223832.txt"
] | Q:
Check a string to see if all characters are hexadecimal values
What is the most efficient way in C# 2.0 to check each character in a string and return true if they are all valid hexadecimal characters and false otherwise?
Example
void Test()
{
OnlyHexInString("123ABC"); // Returns true
OnlyHexInString("123def"); // Returns true
OnlyHexInString("123g"); // Returns false
}
bool OnlyHexInString(string text)
{
// Most efficient algorithm to check each digit in C# 2.0 goes here
}
A:
Something like this:
(I don't know C# so I'm not sure how to loop through the chars of a string.)
loop through the chars {
bool is_hex_char = (current_char >= '0' && current_char <= '9') ||
(current_char >= 'a' && current_char <= 'f') ||
(current_char >= 'A' && current_char <= 'F');
if (!is_hex_char) {
return false;
}
}
return true;
Code for Logic Above
private bool IsHex(IEnumerable<char> chars)
{
bool isHex;
foreach(var c in chars)
{
isHex = ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F'));
if(!isHex)
return false;
}
return true;
}
A:
public bool OnlyHexInString(string test)
{
// For C-style hex notation (0xFF) you can use @"\A\b(0[xX])?[0-9a-fA-F]+\b\Z"
return System.Text.RegularExpressions.Regex.IsMatch(test, @"\A\b[0-9a-fA-F]+\b\Z");
}
A:
You can do a TryParse on the string to test if the string in its entirity is a hexadecimal number.
If it's a particularly long string, you could take it in chunks and loop through it.
// string hex = "bacg123"; Doesn't parse
// string hex = "bac123"; Parses
string hex = "bacg123";
long output;
long.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out output);
|
[
"stackoverflow",
"0039214408.txt"
] | Q:
Register a cell in programmatically instanciated Table View Controller
I am getting this error:
'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier NavigationNodeCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
I am using two cells with the same class "NavigationItemCell" and two identifiers "NavigationNodeCell" and "NavigationLinkCell".
And I create a cell with e.g.:
let cell: NavigationItemCell = self.tableView.dequeueReusableCellWithIdentifier("NavigationNodeCell", forIndexPath: indexPath) as! NavigationItemCell
This problem has been there before me, e.g. Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:
As I understand (e.g. the anser of Sebastian Borggrewe) it should be enough to register a UITableViewCell in the story board with its custom class and an identifier.
That's exactly what I did and I am still getting this error.
I tried to use two different classes but it did not solve the error.
I also tried to register my cells with nib but there I am running into other issues (label is nil).
I've found that this problem probably occures because I instanciate a new table view controller programmatically.
var newController = MyTableViewController()
Does it mean I will have to register nibs anyway? Is it a problem that I will have to register the same class twice? And how do I avoid the problem of the nil label?
A:
You should create an instance of your view controller with storyboard ID.
Replace the line var newController = MyTableViewController() with the following code
let storyboard = UIStoryboard(name: "YOUR_STORYBOARD_NAME", bundle: nil)
let newController = storyboard.instantiateViewController(withIdentifier: "VIEWCONTROLLER_ID_FROM_STORYBOARD")
Edit:
It's also possible to use:
self.storyboard!.instantiateViewControllerWithIdentifier("VIEWCONTROLLER_ID_FROM_STORYBOARD")
if the view controller is instantiated from the storyboard, and second view controller is in the same storyboard
|
[
"stackoverflow",
"0029676359.txt"
] | Q:
Is there a way to force a newline in Puppet log messages?
When I output an error message in puppet, such as with Puppet.err (from a Ruby module), it is displayed in the Puppet Enterprise console log in a difficult to read fashion, because in HTML, newlines are ignored. If I try to insert line breaks (HTML <br/> tags) before each newline, Puppet escapes them by turning the angle brackets into HTML entities.
Is there a way to tell Puppet to include newlines or not escape the br tags? Perhaps a place in the puppet source code that I can change to get this behavior? For example, I call Puppet.err. Where is this function defined?
A:
The logging methods are created in a bit of a mystical fashion.
For what it's worth, I disbelieve that core Puppet is escaping the HTML, it's more likely a commodity feature of the Console itself.
You could try and hook your reports up to Puppet Explorer or puppet-board, see if you fare better with either of those. But I'm not sure how well this will play with PE.
|
[
"stats.stackexchange",
"0000104819.txt"
] | Q:
Best metric for evaluation of mixture-of-Gaussian clusters on big-data
I have made a new algorithm that is specifically crafted for clustering very large datasets. In order to document it as a research paper, I have to choose one or two internal (no-label) cluster evaluation measures to evaluate my algorithm. Which algorithm do you think is generally the best choice for big datasets? And why?
EDIT:
My algorithm is a modified version of Expectation-Maximization Gaussian mixture models. In other words, the whole data is described by
$$P_(x) = \sum_{k=1}^{K}\pi(c_k)\mathcal{N}(\mu_k,\Sigma_k)$$
where $\pi(c_1),\ldots,\pi(c_K)$ are mixture weights. The main difference between my algorithm and regular EM is that it uses some sampling and approximation tricks that accelerate EM. The objective function is the same (the log-likelihood which is to be maximized).
Should I use log-likelihood as the evaluation metric? or use other (which?) internal measures for such task? Is it rational?
A:
No measure will work well for big data.
Every measure is an aggregation, say an average.
By adding more data, this aggregation will only change at the very last digit(s).
In most cases, a sample will already yield a result of the same quality; by the law of large numbers.
But on the other hand, you'll quickly run into the situation where your numerical precision is an issue. Unless you have a very good implementation, chances are that numerical issues with your "big data" implementation will actually make the result worse than one on a sample, where these effects did not yet occur.
For EM type of algorithms, starting values will likely have much more influence than different algorithms. Same for k-means: adding more data doesn't really improve results. Because the algorithm only computes a rough aggregation of your data; and aggregating more data doesn't change the outcome a lot anymore.
|
[
"stackoverflow",
"0044628539.txt"
] | Q:
Vagrant: Make up two identical machines
We have two folders:
folder1
folder2
Inside them we've located two identical Vagrantfile(s).
Once we've vagrant(ed) up one vm, we are not able to set the other one up. We are gettin gthis error:
Machine already provisioned.
So, we are trying to vagrant up two vms. Nevertheless vagrant deals both as one single machine and we're not able to make up two identical vms...
Any ideas?
A:
You probably have identical .vagrant folder within folder 1 and 2.
Inside the .vagrant folder there is the id of the machine so if you have the same id file, the 2 folders will reference and operate the same VM.
You need to remove the .vagrant folder from folder2 and run vagrant up again, it will create a new VM from this folder.
|
[
"stackoverflow",
"0018247606.txt"
] | Q:
Exporting Matlab data to excel, 2003 2010
I am attempting to export data from Matlab to excel, I know to do this you use xlswrite and I have managed to get this to work but when I increase the number of rows/lines of data I get the following error Excel returned: Error: Object returned error code: 0x800A03EC. I know that this error is because I am exceeding the limits of excel 2003 but I am trying to export my data to excel 2010 and my data size is not exceeding the limits of excel 2010. Matlab saves the data as a 97-2003 Worksheet which explains why I am confined to the limits of 2003. Is there a way to save the data as a 2010 worksheet so I can write all of my data to excel?
Part of my code:
xlswrite(test_1,Data_1,1)
xlswrite(test_1,Data_2,2)
xlswrite(test_1,Data_3,3)
Data_1 & 2 & 3 are all 3 columns by any number of rows defined by the user
A:
Excel 2003 files have the .xls extension. For a long time now (like 2009 or 2007) Matlab's xlswrite has supported the new 2007 .xlsx format so long as your files name specifies this. So if your file name was "test_1.xls" then it will save as an .xls file i.e. 2003. So to get the new format all you have to do is name it "test_1.xlsx".
|
[
"stackoverflow",
"0005731572.txt"
] | Q:
Error while running OpenCV based C# code
An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
This is the error I got, on this line:
videoCapture = highgui.CvCreateCameraCapture(0);
The project shows no warnings or compilation errors so what can be the problem?
A:
What this almost certainly means is that your application is being compiled as 64-bit, whereas the code in OpenCV is 32-bit, or vice-versa.
In Visual Sudio:
Right click on your project in Solution Explorer and choose "Properties"
Choose the "Build" tab in the project properties that open
Look at the "Platform Target" option about a quarter of the way down
Set it to x86 if it's currently set to x64 or Any CPU
Now try re-running your application, the error should no longer occur.
Note: The download page for OpenCV states that "It does not contain 64-bit binaries"
|
[
"sitecore.stackexchange",
"0000005476.txt"
] | Q:
SPE prevent Get-Item from throwing error if no item found
I'm writing a script to show the missing/new items between two content branches. For the target of the comparison, I build an item path and then call Get-Item on that path to see if there is an equivalent item. The problem is that Get-Item throws an exception if no item is found - I would just like to handle a case of a 'null' item in my script.
#$source is the root path of the source branch
$localPath = $sourceItem.Paths.FullPath.SubString($source.Length)
$targetPath = "master:" + $target + "/" + $localPath
$targetItem = Get-Item $targetPath
The script works in that $targetItem is null if no item is found using $targetPath but I would like to suppress the error message in the script.
A:
Just use the standard PowerShell error handling parameters:
$localPath = $sourceItem.Paths.FullPath.SubString($source.Length)
$targetPath = "master:" + $target + "/" + $localPath
$targetItem = Get-Item $targetPath -ErrorAction Ignore
Sounds like in your case this would be more than enough. But if you want the ability to check for other potential errors, you could combine the SilentlyContinue action with the ErrorVariable option, and then act out based on what's in the variable. For instance:
# ...
$targetItem = Get-Item $targetPath -ErrorAction SilentlyContinue -ErrorVariable myError
if ($myError.Count -gt 0 -and
!($myError[0].FullyQualifiedErrorId.Contains("ItemDoesNotExist"))) {
Write-Warning $myError[0]
}
Lots more details in this blog post: https://blogs.technet.microsoft.com/heyscriptingguy/2014/07/09/handling-errors-the-powershell-way/
|
[
"aviation.stackexchange",
"0000031553.txt"
] | Q:
With helicopters, is normal landing or auto-rotation landing any different when landing on water?
I noticed something from investigating my other answer to a not-really-related question.
A wiki article here says:
The "water bird" emergency landing is a technique developed by the Canadian Forces to safely land the Sikorsky CH-124 Sea King helicopter when one engine fails while flying over water. The emergency landing technique allows the boat-hull equipped aircraft to land on the water in a controlled fashion.[37]
Which leads me to the obvious question: Is landing any different for water landings? If so, how?
I don't know much about helicopters. For a normal landing, I assume they just hover down and I thought the same thing would be done for a water landing. But the wiki article I read implies that something is different.
For auto-rotation without any engine power, apparently there is a flare at the end. Is this flare done any differently when landing on water?
Basically, the spirit of the question is, how is landing different (if at all) on the water, whether powered or not?
A:
As a helicopter pilot, I've never made a water based landing, so I'm not speaking directly from experience, only from my training, but there are a couple things that are missed in the discussion here that I would certainly worry about.
If I had a real engine failure, and was forced to perform an auto-rotation, in all likelihood, I would not end the auto-rotation with zero forward velocity, I would probably perform a running landing (where you slide on your skids). This, of course, is assuming I'm landing on a flat surface where I'm not likely to roll over (such as a street, parking lot, or runway). Holding the flare to bring the helicopter to a complete standstill has a few risks for me, the biggest one being that if I flare and stop my descent while I still have forward velocity, holding the flare will start to increase my altitude again. Higher inertia (heavier) rotors in small helicopters will suffer from this problem, for example, in training, a Robinson R-22 will generally not have this issue, but an R-44 has much heavier rotors, and we get trained to anticipate a flare at the end of the auto-rotation. Depending on the helicopter, weather, and how I've performed my auto-rotation, if I'm in a real emergency, I would rather put the helicopter down on the ground and slide a little bit than suffer a rotor stall at 50 feet, but a running landing is clearly not an option in a water based landing.
Once I've performed an auto, and the helicopter is on the ground, I'd apply the rotor brake to get the rotors to stop moving before I exited the aircraft, and generally speaking, won't have to worry about the rotors any longer at that point.
If I am performing a water based auto-rotation, there is quite a bit more to worry about. The first thing I have to worry about is that I won't be able to perform a running landing. This means that I'll have less margin for error in my auto-rotation. The second problem is that as soon as I set the helicopter down into the water, it's going to start sinking, and I'll still be strapped in. If I jump out, I'll have to worry about hitting the rotors (or the rotors hitting me) as the helicopter sinks. This means that as soon as I hit the water, I have to remain in the aircraft, and I'll pitch the cyclic over in the opposite direction from the side I'm sitting on, so that I can stop the rotors and still exit the aircraft on the surface side rather than underneath the sinking helicopter. This gets more complicated in the case of passengers, I would encourage them to jump out before the helicopter hits the water, but after my flare, so that they can clear the aircraft and I don't have to worry about them. I only mention it as an additional complication I'd potentially have to deal with.
All of this complexity is a large reason why most of the helicopter pilots I know really do not like flying very far over water. When I'm flying over the water, I tend to stick to an area near the coastline specifically for this reason.
A:
Let's separate the terns you've used in your question and comments.
Emergency descent
This is a very ambiguous phrase and doesn't really describe a flight phase or operation whereas auto-rotation and water landing do. The pilots operational manual will simply say something like "land as soon as possible".
An emergency descent means that you have a problem which requires you to get on the ground as fast as possible, not including all engine failure since that is an auto-rotation.
The fastest way of getting any helicopter down is to enter auto-rotation and if I really had to get down fast, that's what I would do. In the last few feet though, I'm going to get the engine(s) driving the rotor again so I can make a normal landing.
Auto-rotation
A true auto-rotation does not have an option of a powered landing, since by definition you have no engine(s). If you have power, then it's training, practice, testing or precautionary. Everything you do until the last fifty feet or so is making sure that you manage the rate of descent and airspeed to keep the rotor in the operating range. The end goal is to arrive at fifty foot with enough airspeed to be able to flare so that you can trade your kinetic energy from airspeed to kinetic energy in rotor rotation so that you can increase pitch and therefore lift and therefore drag in the flare, whilst feeding in kinetic energy to stop the drag from stalling the rotor.
It's all about energy conservation and conversion. You start off with some potential energy (height and mass) and some kinetic energy (airspeed and rotor RPM). An auto-rotation instantly starts converting potential energy into kinetic energy - you start going down.
Take two identical helicopters flying in identical conditions except one is at minimum weight and one at maximum weight. The one at maximum weight has more potential energy since:
PE=MxGxH
Where M is mass, G is the acceleration due to gravity and H is height.
Both helicopters enter auto-rotation. Quite soon, both will stop accelerating downwards and become stabilised with a constant rate of descent. The heavier helicopter though needs more lift to support it's weight. The airflow in auto-rotation always comes up through the disc from below. You can gain the extra lift by allowing the rotor RPM to increase or you can increase the angle of attack of the blades by raising the collective. The rotor RPM always have an upper fixed limit so in practice, the only way to gain the lift, and support the extra weight, is to raise the collective to prevent the rotor from over-speeding. You also have a limit to how much pitch you can use as the angle of attack must remain positive to the relative airflow from below. If you try to reduce rate of descent by continuing to raise the collective, you will lose lift as the angle of attack moves towards the critical angle so eventually, you reach a steady rate of descent, greater than that of the lighter helicopter.
Since the heavier helicopter is now generating more lift, it is also now generating more drag which can only be overcome by converting more potential energy into kinetic energy. Therefore, the heavier helicopter will use up it's potential energy faster and, since the rotor cannot be 100% efficient, this means that the rate of descent will be higher than in the lighter helicopter.
(It's a very complex topic beyond either the scope of this answer or, to be honest, my complete understanding but some helicopters, in some weight ranges in some flight conditions can descend more slowly when heavier due to rotor efficiency and the size and location of the "auto-rotative driven region" vs the stalled region of the disc).
So, when you arrive at the bottom of the auto and it's time to flare, you have a high rate of descent in a heavy helicopter and the only way to arrest this is to increase collective pitch, to increase lift and increase drag. The only power available to you is in your kinetic energy so you must trade airspeed for rotor RPM in the flare. So a higher rate of descent means you need a higher airspeed to make a controlled power-off landing.
All of that explanation was only to explain that a heavy helicopter arrives at the bottom of an auto-rotation with a high rate of descent and high airspeed.
I couldn't find a video of a Sea King auto-rotating, probably because heavy helicopter pilots don't practice auto-rotations like private and sports pilots do. But here is a heavy helicopter coming in to land. Notice how fast it's going when the flare starts, how high it is and for how the long the flare is held. Even after that, it still lands with a significant rate of descent and airspeed.
S-92 helicopter autorotation (power off landing)
In a light helicopter, especially with some wind on the nose, a good pilot can land with zero airspeed and just enough rate of descent to gently touch down. You could not do that in a heavy without a lot of wind.
Water Landing
Now for the unclear bit.
If you mean landing on water at the end of an auto-rotation from normal flight, then clearly, a heavy is not going to fare well with that arrival so unless you have no choice, you're going to go for firm ground.
If you mean a hovering auto-rotation, assuming that you are within the limits of the height-velocity curve, then you have no choice and it's not going to end well unless you have flotation devices which are deployed and you make a really good touchdown.
If you mean the "water bird", then this is neither an emergency descent or an auto-rotation but is a single engine landing, therefore powered, where you use the boat hull shape of the fuselage to arrive at a precise speed and pitch angle to allow the hull to plane and cushion the landing to enable the helicopter to settle into a float.
What a long way of saying that emergency descents, auto-rotations and water bird landings are very different things and therefore not analogous.
Phew.
|
[
"stackoverflow",
"0023012795.txt"
] | Q:
why is html in java not working?
when i use this code it does not work; the text does not become bold. Why?
label1 = new JLabel();
label1.setText("Welcome, <html><strong>Hussein</strong></html>.");
A:
Your HTML syntax is bad, since your String does not start with the html DOM root.
Try something in the lines of:
label1.setText("<html>Welcome <strong>Hussein</strong>.</html>");
Find a tutorial here.
|
[
"stackoverflow",
"0048177292.txt"
] | Q:
Function for tap on showsUserLocation-dot
In a map I show the user location like this:
map.showsUserLocation = true
I want to do something if the user taps on the dot. Are there any ways to do that?
A:
Assuming you are using MapKit, in your MKMapViewDelegate methods you can react to a user tapping on MKAnnotationViews.
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let userLocation = view.annotation as? MKUserLocation {
print("The user tapped on their user location annotation")
} else {
print("This is not the user location")
}
}
|
[
"stackoverflow",
"0019118258.txt"
] | Q:
same method for instance and Class method. Possible?
I have a class with a function that needs to be called from inside and outside the class. The next code works fine but I was wondering, is there a way to have only one lowerKeyboard method instead of two methods with - and + ?
If i'll keep just the + method I'll get an error unrecognized selector sent to instance when trying to call the method from inside the class
From inside the class:
-(void)someOtherMethod
{
UIBarButtonItem *infoButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(lowerKeyboard)];
}
from outside the class:
[myClass lowerKeyboard];
myClass:
-(void)lowerKeyboard
{
//do something
}
+(void)lowerKeyboard
{
//do the exact same thing
}
A:
Say you have the following:
- (void)doFoo
{
NSLog(@"Foo");
}
+ (void)doFoo
{
NSLog(@"Foo");
}
You can refactor this to either do both implementations like so:
- (void)doFoo
{
[[self class] doFoo];
}
+ (void)doFoo
{
NSLog(@"Do Foo!");
}
However, it is worth pointing out that having two similarly named methods like this is asking for trouble. You'd be far better off removing one of the two interfaces to avoid confusion (especially as you only need one copy of the implementation anyway!).
Bad advice follows - do not actually do this unless you really know how to mess with the run-time (I don't.)
Technically, you can duplicate a class implementation and an instance implementation by editing the run-time like so:
// Set this to the desired class:
Class theClass = nil;
IMP classImplementation = class_getImplementation(class_getClassMethod(theClass, @selector(doFoo)));
class_replaceMethod(theClass, @selector(doFoo), classImplementation, NULL)
This should ensure that calling +[theClass doFoo] calls exactly the same implementation as calling -[theClass doFoo]. It completely removes the original instance implementation from the class's implementation stack (so handle with a lot of caution). I can't think of any really legitimate cases for doing so however, so treat this with a pinch of salt!
|
[
"stackoverflow",
"0002883404.txt"
] | Q:
Java date processing
Given an instance of java.util.Date which is a Sunday. If there are 4 Sundays in the month in question, I need to figure out whether the chosen date is
1st Sunday of month
2nd Sunday of month
2nd last Sunday of month
Last Sunday of month
If there are 5 Sundays in the month in question, then I need to figure out whether the chosen date is
1st Sunday of month
2nd Sunday of month
3rd Sunday of month
2nd last Sunday of month
Last Sunday of month
I've had a look in JodaTime, but haven't found the relevant functionality there yet. The project is actually a Groovy project, so I could use either Java or Groovy to solve this.
Thanks,
Donal
A:
Solutions given so far will tell you 1st, 2nd, 3rd, 4th, or 5th. But the question said he wanted to know "last" and "second to last". If the questioner really needs to know "last" etc, there's a little extra complexity. You have to figure out how many Sundays are in the month to know whether or not the 4th Sunday is the last. The first way to figure that out that occurs to me is:
GregorianCalendar gc=new GregorianCalendar();
gc.setTime(mydate);
gc.set(Calendar.DAY_OF_MONTH,1); // Roll back to first of month
int weekday=gc.get(Calendar.DAY_OF_WEEK); // day of week of first day
// Find day of month of first Sunday
int firstSunday;
if (weekday==Calendar.SUNDAY)
firstSunday=1;
else
firstSunday=weekday-Calendar.SUNDAY+6;
// Day of month of fifth Sunday, if it exists
int fifthSunday=firstSunday+7*4;
// Find last day of month
gc.add(Calendar.MONTH,1);
gc.add(Calendar.DATE,-1);
int lastDay=gc.get(DAY_OF_MONTH);
int sundays;
if (fifthSunday<lastDay)
sundays=4;
else
sundays=5;
That seems like rather a lot of work. Anybody see an easier way?
|
[
"serverfault",
"0000210776.txt"
] | Q:
SharePoint 3.0 Migration to SharePoint Server 2010
We're just using SharePoint Services 3.0 for maybe a year. Now we want to upgrade this server to actual SharePoint 2010.
Is there a solution for upgrading the Database?
A:
Take a look HERE.
|
[
"stackoverflow",
"0047434319.txt"
] | Q:
Perform a task on Azure batch
I am new to Azure batch. I have to perform a task on nodes in the pool.
The approach I am using is that I have the code that I want to run on the node. I am making a zip of the jar of the .class file and uploading to my Azure storage account and then getting the application Id and putting it in ApplicationPackageReference and adding to my task in job.
String applicationId= "TaskPerformApplicationPack";
ApplicationPackageReference reference = new ApplicationPackageReference().withApplicationId(applicationId);
List<ApplicationPackageReference> list = new ArrayList<ApplicationPackageReference>();
list.add(reference);
TaskAddParameter taskToAdd = new TaskAddParameter().withId("mytask2").withApplicationPackageReferences(list);
taskToAdd.withCommandLine(String.format("java -jar task.jar"));
batchClient.taskOperations().createTask(jobId, taskToAdd);
Now when I run this, my task fails giving an error that
access for one of the specified Azure Blob(s) is denied
How can I run a particular code on a node using azure batch job tasks?
A:
I think a good place to start is: (I have covered most of the helpful links along with the guided docs below, they will elaborate the use of environment level variable etc, also I have included few sample links as well.) hope material and sample below will help you. :)
Also I would recommend to recreate your pool if it is old which will ensure you have the node running at the latest version.
Azure batch learning path:
Samples & demo link or look here
Detailed walk through depending on what you are using i.e. CloudServiceConfiguration or VirtualMachineConfiguration link.
Further to add from the article: also look in here: Application Packages with VM configuration
In particular this link will take you through the guide process of how to use it in your code: Also be it resource file or package you need to make sure that they are uploaded and available for use at the batch level.
along with sample like: (below is a pool level pkg example)
// Create the unbound CloudPool
CloudPool myCloudPool =
batchClient.PoolOperations.CreatePool(
poolId: "myPool",
targetDedicatedComputeNodes: 1,
virtualMachineSize: "small",
cloudServiceConfiguration: new CloudServiceConfiguration(osFamily: "4"));
// Specify the application and version to install on the compute nodes
myCloudPool.ApplicationPackageReferences = new List<ApplicationPackageReference>
{
new ApplicationPackageReference {
ApplicationId = "litware",
Version = "1.1" }
};
// Commit the pool so that it's created in the Batch service. As the nodes join
// the pool, the specified application package is installed on each.
await myCloudPool.CommitAsync();
For the Task level form the link above a sample is: (make sure you have followed the steps correctly mentioned here.
CloudTask task =
new CloudTask(
"litwaretask001",
"cmd /c %AZ_BATCH_APP_PACKAGE_LITWARE%\\litware.exe -args -here");
task.ApplicationPackageReferences = new List<ApplicationPackageReference>
{
new ApplicationPackageReference
{
ApplicationId = "litware",
Version = "1.1"
}
};
further to add: be it CloudServiceCOhnfiguration or VirtualMachineConfiguration, An application package is **a .zip file** that contains the application binaries and supporting files that are required for your tasks to run the application. Each application package represents a specific version of the application. from reference: 4
I gave it a shot and tried and was successful, so I am not able to replicate the error above and seems like you might be missing something.
|
[
"stackoverflow",
"0015055496.txt"
] | Q:
How to Accept Generics Argument of Any Type?
Let's say I have a generic class.
public class PagerInfo<T>
{
// ...
}
And I want to pass an instance of this class to a method in another class.
public void Pagination(PagerInfo pagerInfo)
{
// ...
}
The method above won't compile because I didn't provide a type argument. But what if I want this method to work regardless of the type. That is, I want this method to operate on a PagerInfo instances regardless of the type. And my method will not access any type-specific methods or properties.
Also, note that my actual method is in an ASP.NET MVC cshtml helper method and not a regular cs file.
A:
If the method does not access the members of the type that use the generic type parameter, then it's common to define a non-generic base type from which the generic type derives:
public abstract class PagerInfo
{
// Non-generic members
}
public class PagerInfo<T> : PagerInfo
{
// Generic members
}
public void Pagination(PagerInfo pagerInfo)
{
// ...
}
|
[
"stackoverflow",
"0032342627.txt"
] | Q:
Add a panel to a fxml pane
I am new to JavaFX and I am trying to do an app that will show several panels from the same class: The class PacienteGUI creates a panel, and I want to show 5 of this PacienteGUI panels in my main FXML, which has a panel itself. I´ve tried to add it through the controller by
@FXML Pane principal;
@Override
public void initialize(URL url, ResourceBundle rb)
{
PacienteGUI paciente = new PacienteGUI(1);
principal.getChildren().add(paciente);
}
Part of the PacienteGUI:
public class PacienteGUI extends javax.swing.JPanel {
public PacienteGUI(int num) {
chairNum = num;
initComponents();
}
private void initComponents() {
..
..
..Creates JPanel with all its components
..
}
The problem is that it says that PacientesGUI cannot be converted to node. How can I solve this??
Thanks
A:
Your Paciente class is a Swing JPanel, which cannot be placed in a JavaFX Pane directly.
You either need to make Paciente a subclass of a JavaFX Pane, or you need to wrap the Paciente instance in a SwingNode. The latter (SwingNode) is tricky, because you will need to use two different threads to create the different components: swing components need to be created and accessed on the AWT event dispatching thread, and JavaFX components need to be created on the FX Application Thread. I strongly recommend not mixing JavaFX and Swing if you can do so.
|
[
"stackoverflow",
"0038300723.txt"
] | Q:
Contains doen't check in the date range
I have a date range come like this,
string ActualReleaseDates ="7/8/2016, 7/9/2016, 7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate ="07/11/2016";
I want to check NewsReleaseDate is inside the ActualReleaseDates
But in the following code it return as a false.
if (ActualReleaseDates.Split(',').Contains(NewsReleasedDate.TrimStart(new Char[] { '0' })))
{
//some code here
}
A:
The immediate problem is that after splitting your ActualReleaseDates string, there isn't an entry of "7/11/2016"... instead, there's an entry of " 7/11/2016"... note the space.
But more fundamentally, just trimming the start of NewsReleasedDate won't help if the value is something like "07/08/2016"... what you should be doing is handling these values as dates, rather than as strings:
Split ActualReleaseDates by comma, then parse each value (after trimming whitespace) in an appropriate format (which I suspect is M/d/yyyy) so that you get a List<DateTime>.
Parse NewsReleasedDate in the appropriate format, which I suspect is MM/dd/yyyy, so you get a DateTime.
See whether the parsed value from the second step occurs in the list from the first step.
(I'd personally recommend using Noda Time and parsing to LocalDate values, but I'm biased...)
Fundamentally, you're trying to see whether one date occurs in a list of dates... so make sure you get your data into its most appropriate representation as early as possible. Ideally, avoid using strings for this at all... we don't know where your data has come from, but if it started off in another representation and was converted into text, see if you can avoid that conversion.
A:
The white space problem. You can use trim() and ' 7/11/2016' will be '7/11/2016'
var ActualReleaseDates = "7/8/2016, 7/9/2016, 7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
var NewsReleasedDate = "07/11/2016";
var splitActualReleaseDates = ActualReleaseDates.Split(',').Select(x => x.Trim());
if (splitActualReleaseDates.Contains(NewsReleasedDate.TrimStart(new Char[] { '0' })))
{
}
|
[
"stackoverflow",
"0060357571.txt"
] | Q:
Use BeautifulSoup to extract text under specific header
How do I extract all the text below a specific header? In this case, I need to extract the text under Topic 2. EDIT: On other webpages, "Topic 2" sometimes appears as the third heading, or the first. "Topic 2" isn't always in the same place, and it doesn't always have the same id number.
# import library
from bs4 import BeautifulSoup
# dummy webpage text
body = '''
<h2 id="1">Topic 1</h2>
<p> This is the first sentence.</p>
<p> This is the second sentence.</p>
<p> This is the third sentence.</p>
<h2 id="2">Topic 2</h2>
<p> This is the fourth sentence.</p>
<p> This is the fifth sentence.</p>
<h2 id="3">Topic 3</h2>
<p> This is the sixth sentence.</p>
<p> This is the seventh sentence.</p>
<p> This is the eighth sentence.</p>
'''
# convert text to soup
soup = BeautifulSoup(body, 'lxml')
If I extract text only under '''Topic 2''', this is what my output would be.
This is the fourth sentence. This is the fifth sentence.
My attempts to solve this problem:
I tried soup.select('h2 + p'), but this only got me the first sentences under each header.
[<p> This is the first sentence.</p>,
<p> This is the fourth sentence.</p>,
<p> This is the sixth sentence.</p>]
I also tried this, but it gave me all the text, when I only need text under Topic 2:
import pandas as pd
lst = []
for row in soup.find_all('p'):
text_dict = {}
text_dict['text'] = row.text
lst.append(text_dict)
df = pd.DataFrame(lst)
df
| | text |
|---|-------------------------------|
| 0 | This is the first sentence. |
| 1 | This is the second sentence. |
| 2 | This is the third sentence. |
| 3 | This is the fourth sentence. |
| 4 | This is the fifth sentence. |
| 5 | This is the sixth sentence. |
| 6 | This is the seventh sentence. |
| 7 | This is the eighth sentence. |
A:
Try:
target = soup.find('h2',text='Topic 2')
for sib in target.find_next_siblings():
if sib.name=="h2":
break
else:
print(sib.text)
Output (from you html above):
This is the fourth sentence.
This is the fifth sentence.
|
[
"stackoverflow",
"0036113417.txt"
] | Q:
How to use http in cloud9 ide?
I use python manage.py runserver $IP:$PORT, then start this page. As you can see, clound9 uses https, which causes a problem - some css or js files can't be load from other sites via http.
the browser console shows:
Mixed Content: The page at 'https://py3-pronan.c9users.io/' was loaded over HTTPS, but requested an insecure stylesheet 'http://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.min.css'. This request has been blocked; the content must be served over HTTPS.
This site is nothing special, I'm totally ok with http, so is there a way to configure cloud9 ide to use http?
A:
Cloud9 routes both HTTPS and HTTP traffic to your server listening on 0.0.0.0:8080.
Therefore, all you need to use HTTP is to use http://... instead of https://... in your browser :)
|
[
"worldbuilding.stackexchange",
"0000112764.txt"
] | Q:
Can Zeppelins and Blimps replace cars in the future?
It would be cool if this entire planet could use zeppelin roadways instead of tarmac roads. Especially for countryside transport away from cities. A zeppelin for one person is about the size of a lorry, and with future materials, we can have fold-up, safe zepellins, with safety sensors, weather prediction, solar conversion. Negative buoyancy air transport will always use noisy big engines and fall down too fast, too noisy to replace cars and would disturb the forests.
Can zeppelins replace cars one day?
A:
Whilst the sci-fi "sky full of zeppelins" is awesome, I highly doubt lighter-than-air (LTA) craft are going to replace the automobile on a day-to-day transport level. They have several key disadvantages:
Helium is really expensive - and only likely to get more so. You could switch to hydrogen, but then everyone is driving around highly explosive pockets of gas. Fun, but no.
They are much more vulnerable to weather - even a stiff breeze can severely impact their performance and they have extreme issues in storms.
Even though they are fair simpler than normal aircraft, they still take quite a bit of skill to fly reliably, predictably and safely, so you're not going to want Joe Average careening around a city in a Mini-Hindenburg.
Things can still go wrong with the balloon, and then you're back to plummeting out of the sky.
While a one person blimp may be the size of a lorry, that's still pretty big, and it's not going to have room for cargo or haulage. I can fill my car to the gunnels, then attach a trailer and quite comfortably haul over a ton and a half of stuff, if I don't mind chewing though gas.
That's not to say that LTA craft won't have their roles in futuristic travel.
High altitude reconnaissance and experimentation
Advertising; the Goodyear blimp is an incredibly successful advert
Luxury travel through the skies
Weather monitoring - they are still the best at stationary hovering at high altitudes. Can quite happily stay up there for days.
There may also be a role for fast overland bulk transport that could be filled by super-blimps carrying cargo.
A:
We have more than 100 years of zeppelins under humanity belt. We made quite a technology leap with materials. Yet there are no smallish ones filled with hydrogen. And hydrogen is so easy to get that we have car engines producing it in cars that use hydrogen.
EDIT - why use Hydrogen and not helium. Helium is produced from natural gas. So in a plant that need to bottle it up and ship. Kind like fuel but you can drive on one gallon of fuel while you cannot fly with only one gallon of helium. You need to fill blimp to the brim. So no folding-up, either it need to stay blowed or you need to park next to station. Hydrogen can be made from glass of water. You know, the stuff that fall from sky. Taken that whole world helium production would suffice for 6 millions "uses" of lorry size blimp, ignoring other needs for helium, It's quite small compared to other means of transportation. Also helium have around 8% smaller buoyant lift.
Now for the math:
Cubic size of lorry - 30,10 m^3 (Vauxhall/Opel Monavo).
Gross buoyant lift of hydrogen 1,1399 kg/m^3
That give you 34 kilograms of lift. Even when you neglect the weight of blimp itself (assume the material and engine as 0) all you could carry is small child.
Great for late term abortion, not so good for traveling.
Also the size of the lorry is the size of the lorry. That equal 3 regular city cars. Equip those three cars with same hydrogen plants and you have very cheap means of travel that don't go sideways when wind blows.
I just had a vision of tragic yet hilarious balloons that go up in the air and bop each other in the air. Like a slow motion pinball.
Also for hot air balloon requirement for the balloon to take of are
In brief, the perfect weather conditions our hot air balloons need to
fly are: ◾Dry ◾Good visibility ◾Light winds of less than 10-12 miles
per hour.
Now TA in radio are "the roads are slippery, be careful". With blimps, it would be "the wind is 15 mph so stay home and don't travel"
Extra science. From this paper about fuel economy hydrogen engines take around 70 miles per gallon. From this conversion table one m^3 of hydrogen is 2,9 gallons. So what would you take 30 m^3 just to have the blimp would equal 2100 miles/3380 kilometres on the road. So a trip from New York to Chicago through Columbus and Indianapolis and back.
Or Chicago - Denver twice if you want that countryside transport.
So to quote some old guy from 1880 about flying balloons shaped like cigars:
It will never stick. Carriages without horses are the future.
A:
It would be cool if this entire planet could use zeppelin roadways instead of tarmac roads.
I agree with the cool factor! However, the problem is with the where. It isn't likely to happen in our planet's future, because dirigibles have terrible density. If anything, our world's future will probably see more boxy city cars.
However, there is another way. Humans have demonstrated the ability to breathe gas mixes that are about 6 times denser than air at atmospheric pressure, and function continuously. More than 6x increases the work of breathing too much for our physiology. This has been demonstrated in technical and commercial diving and the Sealab experiments.
A planet with 6x the atmospheric density would make LTA craft about twice smaller in every dimension - the volume improvement is better than 6x due to improved structural efficiency. If you want to create a world where LTA transport is more feasible, try looking in that direction.
The abundance of room, the lack of legacy infrastructure (we still use some Roman roads), low population density, and possibly difficult terrain on a colonized planet would also work strongly in LTA crafts' favor. Colonization is likely to focus on the most favorable region, making flight distances short enough for LTA. Adding a lack of fossil fuels could be the tipping point - kerosene is very convenient for heavier-than-air craft, while dirigibles are easy and practical to electrify.
P.S. Keep in mind that real-life air traffic is anything but unregulated. The planes mostly fly alongside designated airways and air corridors, on predefined flight levels, maintaining a lot of separation. That's what it takes, with ATC assistance, to keep just the 23,600 commercial and ~400,000 other aircraft in the world right now from colliding. Think for a moment about how small that number is for a 7-billion planet.
|
[
"stackoverflow",
"0040091425.txt"
] | Q:
WooCommerce cart page returns empty if user is not logged in
I am in a serious problem about the cart page. I can do everything when I am logged in. But if I am not logged in , I can add products to cart , success message is there BUT the cart returns empty.
I tried a few solutions. What I have done so far is:
// Hook after add to cart Added by Atiqur
add_action( 'woocommerce_add_to_cart' , 'repair_woocommerce_2_2_8_session_add_to_cart');
function repair_woocommerce_2_2_8_session_add_to_cart( ){
if ( defined( 'DOING_AJAX' ) ) {
wc_setcookie( 'woocommerce_items_in_cart', 1 );
wc_setcookie( 'woocommerce_cart_hash', md5( json_encode( WC()->cart->get_cart() ) ) );
do_action( 'woocommerce_set_cart_cookies', true );
}
}
Your help is appreciated. Thanks
A:
The site was hosted on WP Engine. It was a problem of caching. I asked them to disable caching on the shop and other product pages. Once they did , the problem was solved.
|
[
"stackoverflow",
"0032174954.txt"
] | Q:
Submitting App from building in Xcode 6.4
I previously built my app in an Xcode 7 beta as my testing device is an iOS 9.0 device. I recently deleted Xcode 7 and began working on my app in Xcode 6.4 (not a beta). 6.4 does not support iOS 9 but my iPhone on an iOS 9 Beta is not uneligible (as it should because 6.4 doesn't support 9.0). Are there some files I can remove so that my device is ineligible? I believe once I fix this problem, I can finally submit a new build for review to iTunes Connect because I shouldn't get this error message when submitting my app:
New apps and app updates submitted to the App Store must be built with public (GM) versions of Xcode 6 or higher and iOS 8 SDK. Do not submit apps built with beta software for store review.
Also, my app is not written in Swift so I cannot do the Swift 2.0 conversion to Swift 1.2.
A:
Apps that you submit should be developed using the latest version of Xcode from the Mac App Store and should be built for publicly available versions of iOS, OS X, and watchOS — except when GM seeds are available.
Now Mac App Store's Xcode is 6.4 and OS X Yosemite is Build 14F27.
If you user xcode 6.4 on OS X El Capitan, you should follow the steps:
Using Xcode, then archive your project
Open organizer, find your .xcarchive file
Right click the xcarchive file, choose [Show package Contents]
Find Products/Applications/XXX.app/Info.plist
then change [BuildMachineOSBuild] value to 14F27, just like this:
Now, you can go to Xcode->organizer, then 【Submit to App Store】
|
[
"askubuntu",
"0000539352.txt"
] | Q:
Where is appletouch.c stored in lubuntu?
I upgraded my lubuntu 14.04 32 bit to a 64 bit version, so needed to reinstall the drivers. When trying to make the touchpad work, I changed the synaptic's file as answered here and wanted to change the appletouch file as mentioned here. I can't seem to find the appletouch.c file though.
user@MacBook:~$ sudo find / -type f -name "appletouch.*"
/lib/modules/3.13.0-37-generic/kernel/drivers/input/mouse/appletouch.ko
/usr/src/linux-headers-3.13.0-37-generic/include/config/mouse/appletouch.h
The header file is empty and the ko-file is an executable file, so can't seem to change much to these files. So anybody know where I could find the appletouch.c file and why it isn't there?
A:
appletouch.c is included in the kernel source code (under drivers/input/mouse).
You can view it online using the Ubuntu kernel git repo here.
To modify appletouch.c you'll have to recompile the 14.04 kernel (or at least this kernel module).
To get the 14.04 kernel source, you can use this command: apt-get source linux-source-3.13.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.