INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Confusing algebraic solution...
Hi everyone I'm a bit confused how they got that final value of M. Any ideas?
!enter image description here
|
$$M=e^t-e^tM$$ $$\implies M+Me^t=e^t$$ $$\implies M(1+e^t)=e^t$$ $$\implies M={e^t\over1+e^t}$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "algebra precalculus"
}
|
Simplify function in Sage
In Sage,
simplify(x/(x^2 + x))
gives
x/(x^2 + x)
I would instead expect to get
1/(x + 1)
Is there a way to achieve that?
|
You could do this:
sage: expr = x/(x^2 + x)
sage: expr.simplify_full()
1/(x + 1)
|
stackexchange-math
|
{
"answer_score": 12,
"question_score": 10,
"tags": "sagemath"
}
|
Plot two variables, one versus the other
I have a quick question: I'm trying to plot two lists of numbers called "stress" and "strain", where stress depends on strain, so I want that shown in a graph.
I tried using plot, but I understand that only works for functions of one variable.
Is there any other function I could use to do what I need?
Thanks!
ADDED: Suppose stress = {{a},{b},...}, and strain = {{x},{y},...}, where the numbers in stress depend on the numbers in strain. I'm trying to plot that relationship in order to make a polynomial fit, so I thought about ListPlot, but somehow it does not work.
Listplot[{{a,x},{b,y},...}] doesn't seem to do it, because they show an empty plot, so I'm now trying to determine whether there is an error with the lists or if my syntax is wrong...
|
Note that the format of your data needs to be flattened. As a dummy example, you can do something like:
Strain = Flatten@{{1}, {2}, {3}}
Stress = Flatten@{{10}, {20}, {30}}
data = Table[{Strain[[n]], Stress[[n]]}, {n, 1, Length@Strain}]
ListPlot[data]
` and then if multiple **optimal** solutions exist, minimize `g(x0+..+xn)` from the subset of those optimal solutions.
I am using SYMPHONY to minimize the first function. If i turn it into a bi-criteria problem, i get efficient results which i am not interested in. Is there any technique/solver out there which would allow me to do this ? Or if i can get multiple solutions i would be okay in checking each at a time to minimize `g(x0+..+xn)`
|
May be a lexicographic approach:
1. Solve with obj `f(x0+..+xn)`. Let `f0` be the optimal objective value.
2. Add a constraint `f(x0+..+xn)=f0` to the model. (May be add a little bit of wiggle room).
3. Solve with obj `g(x0+..+xn)`.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "linear programming"
}
|
Assigning Variable String Value to a table name
I am creating a table in a function, so the function outputs a table to the assigned variable name as shown below
[name] = tablefunc(input1, input2)
The thing is I want to be able to have the name be an input that was assigned earlier for example
name = 'dogs'
[something] = tablefunc(input1,input2)
I want to be able to put some code where it says something so that the outputted table for tablefunc is assigned the variable name `dogs`
It might be confusing why I am doing this but it is because I am extracting tables from a txt file in a for loop so I am getting lots of tables generated and I want to be able to give the tables their appropriate names as opposed to just table1, table2 etc.
|
That's not a good idea. As an alternative, you should create a structure:
function t = tablefunc(input1,input2)
t = table(input1,input2);
end
name = 'dogs';
s = struct();
s.(name) = tablefunc(rand(2),rand(2));
You can have one field per `txt` file.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "string, matlab, variables"
}
|
Finding UMVUE of function of poisson parameter
I am to estimate $exp(-\lambda)\lambda^2/2$ from the distribution $Exp(\lambda) \sim \frac{e^{-\lambda}\lambda^x}{x!}$
I used the Indicator function $I_{X_1=2}(X)$ as an initial unbias estimator. statistic $T=\sum{X_i}$. Using Rao-Blackwell, $\hat{W} = E(W|T) = \frac{t(t-1)(n-1)^{t-2}}{2n^t}$
However, when I check $E(\hat{W}) = \sum_{t=0}^{n}\frac{t(t-1)(n-1)^{t-2}e^{-n\lambda}(n\lambda)^t}{2n^tt!}=\frac{1}{2}\exp(-n\lambda)\lambda^2$.
Where is the n coming from and how do i get rid of it? Where did i made a mistake?
|
Sorry but following your procedure (that is correct)
$$W=\mathbb{1}_{\\{2\\}}(X_1)$$
thus using the law of total expectation
$$\mathbb{E}[\hat{W}]=\mathbb{E}[\mathbb{E}[W|T]]=\mathbb{E}[W]=1\cdot \frac{e^{-\lambda}\lambda^2}{2}+0\cdot\left[1-\frac{e^{-\lambda}\lambda^2}{2}\right]=\frac{e^{-\lambda}\lambda^2}{2}$$
* * *
Direct calculation
$$\mathbb{E}[\hat{W}]=\sum_{t=0}^{n}\frac{t(t-1)(n-1)^{t-2}}{2\cdot n^t}\cdot\frac{e^{-n\lambda}(n\lambda)^t}{t!}=$$
$$=\frac{e^{-n\lambda}\lambda^2}{2}\sum_{t-2=0}^{n}\frac{[(n-1)\lambda]^{t-2}}{(t-2)!}=\frac{e^{-n\lambda}\lambda^2}{2}\cdot e^{(n-1)\lambda}=\frac{e^{-\lambda}\lambda^2}{2}$$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "statistics, statistical inference, parameter estimation"
}
|
Nginx reverse proxy: Not setting expires header
I have my static assets configured as
location @upstream {
proxy_pass
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
try_files $uri @upstream;
access_log off;
expires max;
add_header Cache-Control public;
}
The expires max is not respected.
I think its respecting the incoming server header.
How can modify this to set expires header?
|
Nginx only ever applies one location, never more. In your example it will apply the expires header to existing static files, but any files not found and thus coming from the @upstream location will ignore access_log, expires and add_header directives from static location.
If you want to set expires you should duplicate the directive across both locations. Setting proxy_hide_header might also be required.
|
stackexchange-serverfault
|
{
"answer_score": 3,
"question_score": 5,
"tags": "nginx, reverse proxy"
}
|
How to say "Preparation H" in Spanish
i.e. the hemorrhoid cream lol. I'm trying to say: "Has anyone seen my Preparation H?" and so far I have: "Alguien ha visto a mi Preparation H?" . Would that make sense to someone in spanish?
|
How about "¿Alguien ha visto mi Preparado H?".
(Note that if you are talking about an unanimated object, not a living thing, you don't use the "a".)
|
stackexchange-spanish
|
{
"answer_score": 0,
"question_score": 0,
"tags": "traducción"
}
|
bold text (uiwebview) not showing in iphone4
I have html file in resources folder to load in uiwebview. I need to get bold text styling.
iphone4 is not showing bold text at all. it's working fine in iphone 3Gs and ipod. I tried...
<p><strong>bold</strong><br/><br/> <b>bold</b> </p>
both r not woking in iphone4. Did anyone encounter this problem? Thanks for any help...
|
seems like jailbreak is the problem. I restore my iphone4 and can see the text styling now.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "iphone, uiwebview, iphone 4, bold"
}
|
How to use mathematical logic to solve this problem?
Here is a very simple problem for children, and I wonder if we can use mathematical logic(like "propositional logic" or "first order predicate logic", or others) and an automatic solver? Which means: formalize the statement of the problem, enter the formalized statement into the automatic solver, get an answer
* There are 3 teachers, Mike, Jack and John.
* One teaches art, one teaches music, and one teaches writing.
* Mike is older than whom teach music.
* Jack is younger than whom teach art.
* John is older than whom teach art.
Question: What do the 3 teachers teach?
|
Yes, we can do this with formal logic.
The given information can be formalized as follows:
$$\forall x (x = mike \lor x = jack \lor x = john)$$
$$\exists x (Art(x) \land \forall y (Art(y) \rightarrow y=x))$$
$$\exists x (Music(x) \land \forall y (Music(y) \rightarrow y=x))$$
$$\exists x (Writing(x) \land \forall y (Writing(y) \rightarrow y=x))$$
$$\forall x (Music(x) \rightarrow Older(mike,x))$$
$$\forall x (Art(x) \rightarrow Younger(jack,x))$$
$$\forall x (Art(x) \rightarrow Older(john,x))$$
together with some further fundamental truths:
$$\forall x \neg Older(x,x)$$
$$\forall x \forall y \forall z ((Older(x,y) \land Older(y,z)) \rightarrow Older(x,z))$$
$$\forall x \forall y (Older(x,y) \leftrightarrow Younger(y,x))$$
Any decent automated prover will be able to infer the answer from this information.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "logic, propositional calculus, first order logic, logic translation"
}
|
Is it safe to eat non-green tea leaves
I'm trying to understand if it's safe to eat tea leaves. Not as an evening meal, more about if I make a drink with loose leaf tea and leave the leaves in the bottom of the drink and drink some, will it cause any ill effect (drinking 10 cups a day).
My research on Google brings up many results, but everything I've found is about eating green tea leaves (and even that `matcha` is a powder made from green tea for consumption). My question is about white and black tea.
Some sites I've read explain how little difference there is between the teas, and ultimately I can't find anything on non-green teas to confirm that it is safe (despite my instinct saying "hey, it's still tea, yes it's safe").
Is it safe to eat white and black tea (before or after it is used to make tea)?
|
It is safe to drink the tea made from tea leaves and it's safe if you eat the tea leaves themselves at the bottom of the cup. People avoid eating the leaves because they aren't pleasant tasting, the consistency isn't very nice, and they aren't that easy to digest.
|
stackexchange-cooking
|
{
"answer_score": 8,
"question_score": 6,
"tags": "food safety, tea"
}
|
Why is the Gamma function off by 1 from the factorial?
Why didn't they define it as $$ \tilde \Gamma(x) = \int_0^\infty t^x e^{-t} \, dt ?$$ Then the definition would have two less characters than the standard definition of $\Gamma(x)$, and we would have $\tilde \Gamma(n) = n!$ for $n$ a non-negative integer. And this would save a lot of confusion.
|
My opinion is that it's because the "right" way to write the standard definition is $\Gamma(x)=\int_0^\infty t^xe^{-t}\frac{dt}{t}$. Putting in that multiplicative Haar measure makes a lot of other things easier to get straight. Same for a lot of integrals with $t$ to some exponent with a curious $-1$ attached...
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 8,
"tags": "soft question, special functions, math history, gamma function"
}
|
How to add a character to the last third place of a string?
I have a column with numbers with various lengths such as 50055, 1055,155 etc. How can I add a decimal before the last 2nd place of each so that it would be 500.55, 10.55, and 1.55?
I tried using replace by finding the last 2 numbers and replace it with .||last 2 number. That doesn't always work because of a possibility of multiple repetition of the same sequence in the same string.
replace(round(v_num/2),substr(round(v_num/2),-2),'.'||substr(round(v_num/2),-2))
|
You would divide by 100:
select v_num / 100
You can convert this into a string, if you want.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, oracle"
}
|
Pandas validate date format
Is there any nice way to validate that all items in a dataframe's column have a valid date format?
My date format is `11-Aug-2010`.
I saw this generic answer, where:
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
except ValueError:
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
source: <
But I assume that's not good (efficient) in my case.
I assume I have to modify the strings to be pandas dates first as mentioned here: Convert string date time to pandas datetime
I am new to the Python world, any ideas appreciated.
|
(format borrowed from piRSquared's answer)
if pd.to_datetime(df['date'], format='%d-%b-%Y', errors='coerce').notnull().all():
# do something
This is the LYBL—"Look Before You Leap" approach. This will return `True` assuming all your date strings are valid - meaning they are all converted into actual `pd.Timestamp` objects. Invalid date strings are coerced to `NaT`, which is the datetime equivalent of `NaN`.
Alternatively,
try:
pd.to_datetime(df['date'], format='%d-%b-%Y', errors='raise')
# do something
except ValueError:
pass
This is the EAFP—"Easier to Ask Forgiveness than Permission" approach, a `ValueError` is raised when invalid date strings are encountered.
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 13,
"tags": "python, pandas, datetime"
}
|
How to extract first 20 bits of Hexadecimal address?
I have the following _hexadecimal_ 32 bit virtual address address: **0x274201**
> **How can I extract the _first 20 bits_ , then convert them to decimal?**
I wanted to know how to do this by hand.
## Update:
> @Pete855217 pointed out that the address _0x274201_ **is not** _32 bit_. Also **0x** is not part of the address as it is used to signify a hexadecimal address.
Which suggests that I will add 00 after 0X, so now a true 32 bit address would be: **0x00274201**. I have updated my answer!
|
I believe I have answered my own question and I hope I am correct?
> First convert HEX number **0x00274201** to _BIN (this is the long way but I learned something from this)_ :
!enter image description here
However, I noticed the first 20 bits include _00274_ in HEX. Which makes sense because every HEX digit is four BIN digits.
So, since I wanted the first 20 bits, then I am really asking for the
> first **_five_** HEX digits because 5 * 4 = 20 (bits in BIN)
Thus this will yield **00274** in HEX = **_628_** in DEC (decimal).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "hex, extract, 32 bit"
}
|
Calling ASCX control method
I need to call a method from my ascx control called BindTagCloud for the purpose of exporting it to a pdf file. How can I do that?
displaycloud.aspx:
<TagCloud:TagCloudControl ID="TagCloudControl1" runat="server" />
displaycloud.apsx.cs:
if (text.Length.Equals(0)) {
--> BindTagCloud(); <--
using (StringWriter sWriter = new StringWriter(strB)) {
using (HtmlTextWriter htWriter = new HtmlTextWriter(sWriter)) {
TagCloudControl1.RenderControl(htWriter);
}
}
}
|
You simply should add a public method `BindTagCloud` to the Code Behind file of the user control (`ascx` file). Then you can call the method by reference to your user control in your `aspx` page:
TagCloudControl1.BindTagCloud();
If you don't see the method in the IntelliSence window, rebuild the Web Site (in the main menu `Build` -> `Rebuild Web Site`)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, asp.net"
}
|
平方数の判定を、sympyの素因数分解factorintでできますか?
?
print(factorint(9))
{3: 2}
print(factorint(81))
{3: 4}
n
<
:Wolfram|Alpha
81
<
80
<
|
n n n
|
stackexchange-ja_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "アルゴリズム, sympy"
}
|
How can I use an existing S3 bucket in Backup?
I have an existing Amazon S3 bucket in the Oregon region. How can I use it as the backup location in Backup?
## Details
* I've enabled the Amazon S3 backup location, but I don't see a way to specify which bucket to use. When I start backups for the first time, it automatically creates a new bucket with a name I don't want in a region I don't want to use.
|
Yes, you can, but it's a bit hidden. You can do it on the console:
* `gsettings set org.gnome.DejaDup.S3 bucket 'MYBUCKETNAME'`
Or you can do it graphically:
* Install the package 'dconf-tools'
* Run dconf-editor
* Browse to /org/gnome/deja-dup/s3
* Edit the bucket key
|
stackexchange-askubuntu
|
{
"answer_score": 11,
"question_score": 9,
"tags": "deja dup, aws"
}
|
does a positive/negative number cancel itself?
By positive negative I mean the function that looks like an addition sign $(+)$ with a subtraction sign $(-)$ right underneath it.
does a positive/negative number cancel itself? As in $x$ positive/negative 3.
wouldn't that written out look like $x-3+3$? Wouldn't the three's would cancel, therefore liberating the need to do the work out for a more complicated math problem?
|
$x\pm 3$ means $x+3$ or $x-3$ not $x+3-3$, so the $\pm$ doesn't cancel. Are you thinking about simplifying the quadratic formula perhaps?
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "functions"
}
|
Under what assumptions can we split a Hilbert space into subspaces?
I was thinking about an apparently simple question about quantum mechanics, if I am looking at a quantum system described by a Hilbert space $\cal{H}$ under what hypothesis can I define A and B as subsystems whose union gives the full former system and decompose $\cal{H} = \cal{H_A}\otimes \cal{H_B}$. The other way, it is evident, if I join two quantum systems, their state will evolve in the tensorial products of the two, and the states are factorizable if there is no quantum correlation. But starting with the first joined system, I am puzzled by the meaning of this decomposition.
Thank you. And sorry if that question is a no brainer, it's just not that evident to me. =)
|
Without further specifications, you can do it always. Let $\psi_j$ ($j\in N_0$), where $N_0$ denotes the set of nonnegative integers, be a basis of the Hilbert space $H$. Let $I$ be a countable bijection from $N_0\times N_0$ to $N_0$, let $H_A$ be spanned by the $\psi_{I(j,0)}$, and $H_B$ be spanned by the $\psi_{I(0,k)}$. With the identification $\psi_{I(j,0)}\bigotimes\psi_{I(0.k)}=\psi_{I(j,k)}$, $H$ is the tensor product of $H_A$ and $H_B$.
On the other hand, if you have given two subsystems A and B of a bigger system, they are in a tensor product inside the big system if and only if A and B have no common observables (except for the c-numbers). In just this case there is inside the bigger system a subsystem composed of A and B described by this tensor product.
|
stackexchange-physics
|
{
"answer_score": 4,
"question_score": 7,
"tags": "quantum mechanics, quantum entanglement, hilbert space"
}
|
Нужно ли тире перед "попросту невежливо"?
Тире здесь может стоять только факультативно? Т. к. подразумевается, что "ЭТО невежливо"?
> Я прекрасно понимаю, что совать нос в его личные дела (–) попросту невежливо.
|
Да, можно сказать и так – факультативно. Скорее, постановка тире зависит от акцентов, интонации.
В данном случае я бы его поставил, так как предложение не очень короткое, а также будет понятно, к чему относится слово _**попросту**_.
> 5. При наличии паузы между главными членами предложения **тире** ставится между подлежащим, выраженным неопределенной формой глагола, и сказуемым, выраженным предикативным наречием на **-о** (категорией состояния): _Уступить — позорно_ (Тендр.); _Это очень **несносно — переезжать**_ (Гонч.); _Это **ужасно — струсить** в последний момент; Это чертовски **весело — кататься** на лодке_ [ср. без паузы: _**Кататься** на лодке **весело**_ ; _**Судить** человека в немилости очень **легко**_ (Л. Т.)].
>
Источник: **Тире между подлежащим и сказуемым** (Розенталь).
|
stackexchange-rus
|
{
"answer_score": 2,
"question_score": 1,
"tags": "пунктуация, тире"
}
|
Macro for a math map f:A\to B
I want to write a macro for a math map `f:A\to B` when it is in inline math mode and `f:A\longrightarrow B` for displayed math. But I don't know how to check that it is in inline mode or displayed style.
Here is my try:
\documentclass{article}
\newcommand{\map}[3]{#1\mathpunct{:}#2\longrightarrow #3}
\begin{document}
$\map{f}{A}{B}$
\[\map{f}{A}{B}\]
\end{document}
I have tried the following but it produces `Undefined control sequence. $\map`
\makeatletter
\newcommand[3]{\map}{
#1\mathpunct{:}#2
\if@display
\longrightarrow #3
\else
\rightarrow #3
\fi}
\makeatother
|
You can't differentiate displaystyle and text style using a if test since use of the plain TeX `\over` can change the mathstyle after the fact. But you can use `\mathchoice` to provide four expressions (one for each math size (display/text/script/scriptscript)) and only the one for the right size will actually appear:
\documentclass{article}
\newcommand{\map}[3]{#1\colon #2\mathchoice{\longrightarrow}{\to}{\to}{\to}#3}
\begin{document}
$\map{f}{A}{B}$
\[\map{f}{A}{B}\]
\end{document}
|
stackexchange-tex
|
{
"answer_score": 7,
"question_score": 2,
"tags": "math mode, macros, conditionals, displaystyle"
}
|
Two functions intersect,solve the equation.
Given two functions,show where they intersect
$(x^2−5)^2/(x+7)^2=\sqrt{169-x^2}$
I have already tried to square both of them but I get a very complex equation and I can not solve it. I saw a guy who put Ln before and before the two sides of the equation.
|
This equation simplifies to an 8th degree polynomial that can't be solved explicitly. Applying logarithms gives you $2 \log(x^2 - 5) - 2 \log(x+7) = \frac{1}{2} \log(169-x^2)$, but this does not simplify. As always, numerical approximations such as newton's method will get you approximate answers that @JoelReyesNoche gave.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "real analysis, algebra precalculus"
}
|
Extract columns from a csv file with fields containing delimited values
I am trying to extract certain fields from a csv file, having comma separated values. The issues is , some of the fields also contains comma and the fields are not enclosed within quotes. Given the scenario, how can i extract the fields.
also,only one of the field contains comma within values, and i don't need that. e.g: I want to extract the first 2 columns and the last 5 columns from the data set of 8 columns , where the third column contains values with comma
> PS: Instead of down voting i would suggest to come ahead and post your brilliant ideas if you have any.
|
Solution:
$path = "C:\IE3BW0047A_08112017133859.csv"
Get-Content $path| Foreach {"$($_.split(',')[0,1,-8,-7,-6,-5,-4,-3,-2,-1] -join '|')"} | set-content C:\IE3BW0047A_08112017133859_filter.csv
|
stackexchange-stackoverflow
|
{
"answer_score": -2,
"question_score": -7,
"tags": "powershell, csv, batch file, talend"
}
|
Counting unique features of points inside polygon in QGIS
I have a series of points with various fields in the attribute table, including a `car_id`. I also have several polygons in which some of these points are located.
)
public MessageSource<InputStream> sftpMessageSource()
{
SftpStreamingMessageSource source = new SftpStreamingMessageSource(template());
source.setRemoteDirectory(sftpRemoteDirectory);
source.setFilter(abSftpFileFilter());
return source;
}
|
You cannot change the cron expression dynamically; the framework does provide a `DynamicPeriodicTrigger` which can be used to change the fixed-delay or fixed-rate at runtime (but the change doesn't take effect until the next poll).
You might also find that a smart poller might be suitable for your use case - see "Smart" Polling, where the poller can make decisions about whether or not to proceed with a poll.
You could also create your own `Trigger` that wraps a `CronTrigger` and delegate to it; that would allow you to change it at runtime. But, again, changes won't take effect until the next poll.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "spring, spring integration, spring integration sftp"
}
|
Numerical method for a BVP with mixed boundary conditions (MATLAB)
I've been given a second-order non-linear ODE:
$$\frac{d^{2}\theta(s)}{ds^{2}} = sf_{g}\cos{\theta} + sf_{x}\cos{\phi}\sin{\theta}$$
where $f_{g}, f_{x}$ and $\phi$ are constants.
The boundary conditions for $[0,L]$ are:
* $\frac{d\theta}{ds}\Big|_{s=0} = 0 $
* $\theta (L) = \theta_L$
I will be repeating this numerous times for different values of $L$, implementing the solution method as a function. The $\theta_L$ is just a constant assumed known each time.
I am unsure how to proceed with these boundary conditions (are they Neumann, Dirichlet etc.? I don't think so). I struggle when I try to convert the BVP into an IVP for the shooting method and I've read the documentation for bvp4c and ode45 over and over with no progress on this problem. I just can't seem to get started here.
Could anyone give me some pointers or help? Thank you very much in advance.
|
To start you could change it into a system of first-order ODEs $$Y(s) := \left( \begin{split} \theta'(s)\\\ \theta(s) \end{split} \right) = \left(\begin{split} Y_1(s)\\\ Y_2(s) \end{split} \right)\,,$$ $$ Y'(s) = \left( \begin{split} s f_g \cos(Y_2(s)) + s f_x \cos \phi\sin(Y_2(s))\\\ Y_1(s) \end{split} \right)\,.$$
$$Y(0) = \left(\begin{align} 0\\\ t \end{align}\right)\,.$$ Then the shooting method, parametrised by $t$ as initial conditions, that means use different values of $t$ as an initial condition. Approximate value of $t$ can be find in the style taught in this lecture. The easiest root finding method is the bisection method. For that you should know a range in which the value of $t$ lies $[t_a t_b]$. Substitute $t_a$, $t_b$ and $t_c$ (mid point of $t_a$ and $t_b$), as three different I.C and solve that using ode45 then check weather you are getting closer to $Y_2(L)=\theta_L$, then reduce the search range in bisection algorithm algorithm until you get desired accuracy.
|
stackexchange-scicomp
|
{
"answer_score": 3,
"question_score": 2,
"tags": "matlab, boundary conditions, numerical modelling"
}
|
Why do many websocket libraries implement their own application-level heartbeats?
For example socket.io has `pingInterval` and `pingTimeout` settings, nes for hapi has similar heartbeat interval settings. This is ostensibly to prevent any intermediates such as over-zealous proxies from closing what seems to be an inactive connection.
But ping/pong frames are part of the websocket protocol and seem to serve the same purpose. So why do websocket library implementors add another layer of ping/pong at the application level?
If I was pushed to guess it would be in case the websocket server is dealing with a client that doesn't respond/support the websocket protocol level ping-pongs.
|
I did some reading up and made some tests and I think it comes down to this:
* Websocket `ping`s are initiated by the server only
* The browser Websocket API has isn't able to send `ping` frames and the incoming `ping`s from the server are not exposed in any way
* These pings are all about keepalive, not presence
* Therefore if the server goes away without a proper TCP teardown (network lost/crash etc), the client doesn't know if the connection is still open
* Adding a heartbeat at application level is a way for the client to establish the servers presence, or lack thereof. These must be sent as normal data messages because that's all the Websocket API (browser) is capable of.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "node.js, http, websocket, socket.io"
}
|
How can I make a queue in MongoDB?
For context :
In my app Im storing users activities and notifications, similar to what instagram has. (when someone likes your post, when there's a new comment or someone you follow posted a new content).
It will be very space extensive to store all of these activities for every individual user. for example if someone with 3k followers posted; that 3,000 new records added to the database.
Question :
To save space I want to store maximum of 20 records in the collection (Activity).
When inserting new record; if the collection size is 20 the oldest record (index 0) should be removed like a queue.. meaning only storing the 20 latest activities.
is there any easy way to achieve this with mongoose?
thanks.
|
You can use something called "Capped Collections":
* MongoDB documentation \- Please read "Behavior" section in this docs because capped collections have some limitations.
* Mongoose Documentation
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "mongodb, express, logging, mongoose, queue"
}
|
Inability to logout using keyboard
I can't log out using just the keyboard.
On one instance I was using a laptop for which the touchpad was on the blink and I didn't have a mouse handy. Given that the **logout** link is hidden inside the arrow and available only on hover, I could not reach the link by repeatedly pressing `Tab`.
I borrowed a mouse just to log out, but seriously...
|
If you are using a keyboard only, or any other device which you cannot locate the logout link, then simply append `/users/logout` to the exchange.com that you are currently on.
Or, for convenience: **_`logout`_**
Feature-implemented.
|
stackexchange-meta
|
{
"answer_score": 4,
"question_score": 6,
"tags": "feature request, logout, keyboard shortcuts"
}
|
Finding the general term of a sequence (if there's any)
I would like to know if it's possible to find an expression for the following sequence $\;\\{a_n\\},\;n=0,\,1,\,2,\,3,\,\dots\;$
$1, 3 , 7, 13, 21...$
Someone would like to explain me what I have to do to solve it? I can see a pattern on them, it adds two more than the previous term added (2,4,6,8...) (like 2^n).
So I would like to know the general term($a_n\,=...$) solution, but mainly I would like to the explanation.
Edit: Solution: $a_n\,=n^2-n+1$
|
HINT: Compare $a_n$ with $n^2$ for the first few values of $n$.
**Added:**
$$\begin{array}{rcc} n:&1&2&3&4&5&6&7\\\ n^k:&1&4&9&16&25&36&49\\\ a_n:&1&3&7&13&21&31&43 \end{array}$$
What’s the difference between the last two rows of that table?
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 0,
"tags": "calculus, sequences and series, problem solving, pattern recognition"
}
|
GPL code allowing non-GPL local copies of nondistributed code
I have come across a book that claims that alterations and augmentations to GPL works can be kept close-source as long as these are not redistributed into the wild. Therefore, customizations of websites deriving from GPL packages need not be released under the GPL and developers can earn profit on them by offering their services to their clients while keeping their GPL-based code closed source at the same time.
(cf. Chapter 17 of WordPress Plugin Development by Wrox Press).
I've never realized this, but essentially, by putting restrictions on redistributable code the GPL says nothing about what can and cannot be done with code which is kept private in terms of the licensing model.
Have I understood this correctly?
|
Yes, you have understood that correctly. To address this loophole in the GPL license, the Affero GPL licence has been created, which considers using the software as part of a website as being a distribution of that software.
|
stackexchange-softwareengineering
|
{
"answer_score": 5,
"question_score": 5,
"tags": "gpl"
}
|
after using where condition with parameter Css is not working in laravel
I am trying to list database details using where condition with parameter after calling this function CSS not working but all data is list down properly and without parameters, CSS working properly.
**web.php**
Route::get('/viwelist/{id}','Front\SISProfileController@check');
**controller**
class SISProfileController extends Controller
{
public function check($district){
$list = SISAccount::all()->where('District', '==', $district);
//dd($list->all());
return view('Front.listSIS', compact('list'));
}
}
**link**
<a href="{{ URL('/viwelist/'.'districtname')}}">click</a>
->get(); //to get back a Collection with all the records
$list = SISAccount::where('District', '=', $district)->first(); //to get only the first record, like if District is your primary key
The css problem is probably caused by the fact that you have put a relative link on your header as position of the css file, instead you should have something like `/asset/css.css`, so with a `/` at the beginning
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, html, css, laravel, web deployment"
}
|
ExecuteScript doesn't work for localStorage when using variable
I am trying to pass in a variable to use for executeScript as shown below:
var groupScript = '\'' + 'localStorage.setItem("groups", "[' + groupNames + ']"); + '\'''
which when printed to the console gives me:
'localStorage.setItem("groups", "[\\"lunch\\"]");'
If I try to run:
browser.executeScript( groupScript );
It doesn't create the localStorage variable. However, if I run the following (which just has the value of the variable), it does work:
browser.executeScript( 'localStorage.setItem("groups", "[\\"lunch\\"]");');
Can someone let me know what I need to do in order to get it to work with passing in the variable? Trying to create localStorage variable for my protractor test. Thanks!
|
There is a special `arguments` array containing the list of arguments passed into a script:
browser.executeScript('localStorage.setItem("groups", arguments[0]);', groupNames);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, google chrome, browser, local storage, protractor"
}
|
gradient approximation to the change of function
Say $$E = f(X) \\\ \text{when}\ X \to X+\delta \\\\\text{where}\ \|\delta\| \to 0\ \text{is a vector}$$ then $$\Delta E \approx f(X) +\delta^T \nabla_X f(X) $$
Is this correct ? Then my question is , by the definition of gradient, the gradient should be the direction which increases your function value the most. But now I am not moving my X along with that direction. Howcome the equation above is correct ?
Recall from a 1-D derivative, the gradient tells you what increase you will get if you "move in this direction that I tell you"
But now I am not moving along with the gradient direction. Why is this still the approximation for $$\Delta E$$
My thought is that the equation should be $$\Delta E = f(X) +\delta^T \nabla_{\delta}f(X)$$
Am I missing something ?
|
Recall the gradient is defined (for $f: \Bbb R^n \to \Bbb R$) as:
$$\nabla_X f = \nabla f(X) := \begin{pmatrix}\partial_1 f(X) \\\ \vdots \\\ \partial_n f(X)\end{pmatrix}$$
where $\partial_i f := \dfrac{\partial f}{\partial x_i}$ WRT the standard basis on $\Bbb R^n$. It is the transpose of the Jacobian matrix for real-valued functions $f$.
With this in mind, $\delta^T \nabla f(X) = \left<\delta, \nabla f(X)\right>$ is what we obtain by "linearly approximating $f$ in the direction of $\delta$ by the length of $\delta$".
This appears to be a correct first-order approximation of the change if $\|\delta\| \to 0$.
Your confusion seems to arise from the expression $\nabla_X f(X)$, which is not correct.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "multivariable calculus"
}
|
How can I find all duplicate questions of a specific tag?
How can I find all duplicate questions of a specific tag, e.g., all the questions marked as `[duplicate]` for the tag, spring-boot?
|
duplicate:yes [spring-boot]
Here, have fun.
|
stackexchange-meta_stackoverflow
|
{
"answer_score": 6,
"question_score": -6,
"tags": "support"
}
|
How to hide inactive slides on jquery cycle
I am using jquery cycle to cycle through a large number of customer reviews, with a numbered pager and 6 items per page. My code is as follows:
<script type="text/javascript">
$(function() {
$('.reviews')
.before('<div id="banner-nav">')
.cycle({
fx:'fadeout',
timeout: 5000,
pager: '#banner-nav'
});
});
</script>
I need the reviews to be transparent (text only) as there is a background image that needs to be visible. The problem is that since jquery cycle does not hide inactive slides, I get an effect like the following:
!enter image description here
Please see < for an example
Can anyone suggest a fix for this?
|
Remove the `fx:'fadeout',` line from the options.
This options shows all and just hides the active one.
The default ( _when you remove it_ ) is to fade in the active one.
Demo at <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery, css, jquery cycle"
}
|
Left Exclusion Join when data extension has composite primary key
I have a query on writing left exclusion joins when the data extensions has the composite primary key.
I have below two data extensions DE1
ContactID | AccountID | attribute
---|---|---
sksksksk | 111111 | six
DE 2
ContactID | AccountID | Cohort
---|---|---
sksksksk | 111111 | six
Now I want to write a SQL query to get all records from DE1 which are not in DE2. In my case in both the DEs, ContactID and AccountID are composite primary key.
I have done the left exclusion joins before only with one primarykeys.
Thanks
|
You would do it similarly as you would have done it with just one Primary Key, just mentioning in the `INNER JOIN` 2 PKs and then also 2 PKs in the `WHERE` clause -
SELECT
a.ContactID,
a.AccountID,
a.attribute,
b.Cohort
FROM [Data_Extension_1] a
LEFT JOIN [Data_Extension_2] b ON a.ContactID = b.ContactID AND a.AccountID = b.AccountID
WHERE b.ContactID IS NULL AND b.AccountID IS NULL
|
stackexchange-salesforce
|
{
"answer_score": 1,
"question_score": 0,
"tags": "marketing cloud, sql"
}
|
Jquery Validate Plugin to validate seperate sections with controls
I have different div sections with some controls in each. I have a button to navigate from one section to the other. all of the divs are in one single form "form1". Here is the layout:
form id="form1"
div id="section1"
input type="text" id="1">
input type="text" id="2">
input type="text" id="3">
input type="button">
/div>
div id="section2">
input 4>
input 5>
input 6>
button to next section>
/div>
/form>
I am trying to achieve validating controls in each div when the respective button is clicked. clicking button in section 1 should validate all controls 1-3 and then navigate to other section. Let me know how to achieve this.
Thanks.
|
You can easily accomplish something like this using jQuery:
$(document).ready(function() {
//bind click event to section 1's submit button
$('div#section1').children(':button').click(function() {
//validate section 1 controls
});
//do the same for section 2
$('div#section2').children(':button').click(function() {
//validate section 2 controls
});
});
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, jquery validate"
}
|
Yii Framework, path to custom PHP file
I'm using Yii Framework and I have custom **.php** file with `header('Content-type: image/png');` Actually it returns an image.
I want in my **view** see that image this way:
<img src="path/to/custom/image.php"/>
Where should I **put** my custom php file? And how I should **set it's path**?
|
Relative to your controller, example: `../../images/file.php`, or you can do this:
<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/file.php"/>
In this way, the file must be accesible from outside.
Just to clarify, you shouldn't call this from your controller, but from your view.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php, yii, yii extensions"
}
|
LDAP on ec2 - security concerns
I'm new to LDAP and would like to install it on AWS ec2. However, I'm concerned about exposing the required ports to public and was wondering if there is a 'safe' way to go about it. I would figure if I exposed the LDAP port publicly, someone can connect and attempt to read the LDAP database.
What is the best practice for setting up LDAP on ec2? I'm attempting to use FreeIPA on Cent OS.
|
You need set public VPC and private VPC with different security groups (for inbound and outbound ports management). Public VPC for the instances which need face to public, such as web servers. Private VPC are internal servers, such as application and database servers. Your ldap server should be put in private VPC (in fact, it depends on, you need give more details). You need open the inbound port (such as 636/389) from webservers to ldap servers.
You also need install a VPN (such as `openvpn`) to guarantee only users from nominated IPs can login your environment (include public and private VPC).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "security, amazon ec2, ldap"
}
|
Spring Security исключить url из защищенной директории
есть метод
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin*/**")
.access("hasRole('ADMIN')")
.and().formLogin().loginPage("/admin/login")
.loginProcessingUrl("/login").usernameParameter("ssoId").passwordParameter("password").and()
.rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
.tokenValiditySeconds(604800).and().csrf().and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
мне нужно `/admin/login` исключить из защищенной директории, чтоб по этому url можно было обратиться любому пользователю
|
Вам нужно прописать игнорируемые адреса в специальном методе вашей реализации класса `WebSecurityConfigurerAdapter`:
код на kotlin
override fun configure(web: WebSecurity) {
web.ignoring().antMatchers("/admin/login")
}
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, spring"
}
|
incorrect redirect from http to https
trying to go https, but when I use the following in my `.htaccess` I get redirect problem error
here is what I have in my `.htaccess`
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP} on [OR]
RewriteCond %{HTTP:X-Forwarded-Proto} https [OR]
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^(.*)$ [L,R=301,NE]
#Uncomment lines below when uploading to the live server
RewriteCond %{HTTP_HOST} !^(www\.)example\.com$ [NC]
RewriteRule ^(.*)$ [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.*$ index.php [QSA,L,NC]
#Uncomment lines below when uploading to the live server
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^ [NC]
RewriteRule \.(gif|jpg|png|tif|js|css|xls|xlsx|zip|rar|pdf|ods|ots)$ - [F]
Please help
|
Your first rule has many erroneous `[OR]` conditions and that is causing redirect loop.
Change your first rule to this:
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ [R=302,L,NE]
And test after clearing your browser cache.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "apache, .htaccess, mod rewrite, https, http redirect"
}
|
Undefined offset: 1 when checking if isset in function
$s = "text";
$exploded_s = explode('/', $s);
//$s2 = isset_or($exploded_s[1], "empty"); //This shows notice Undefined offset: 1
$s2 = isset($exploded_s[1]) ? $exploded_s[1] : "empty"; //This is ok
echo $s2;
function isset_or($var, $val){
return isset($var) ? $var : $val;
}
Both return "empty" but the first way also shows the notice. Why?
|
You are passing `$var` by value - because it has none (and isn't set) you get the notice. However, if you pass by reference it will work.
function isset_or(&$var, $val){
return isset($var) ? $var : $val;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, isset"
}
|
How to get random key from firebase in android?
.getReference("inspirational");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
First you need to go the dataSnapshot `inspirational`, then iterate inside of it and, this will give you the random keys `String keys=datas.getKey();`
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "java, android, firebase, firebase realtime database"
}
|
Is it possible to extract the music from Chime?
I'm playing Chime (via Steam), and the music (before coverage) seems very soothing.
Is it possible to extract it (in the same way as, say, the Portal soundtrack can be found amongst the application files?
|
I've been looking at some of the files with a hex editor. It appears that there is no single " _soundtrack_ " to the game, but that the game stores the songs in many pieces and assembles them in real-time depending on what's going on in the game. The song **Still Alive** is in 42 parts itself, with all the data in one file (Portal_Backing.xwb), and the allocation table in another (Portal_Backing.xsb). I have no idea what format the actual song parts are stored in.
Sorry but it doesn't look like you'll be able to get the songs extracted.
|
stackexchange-gaming
|
{
"answer_score": 5,
"question_score": 5,
"tags": "chime"
}
|
� IN SQL Server database
in my database I have this char . I want to locate them with a query
Select *
from Sometable
where somecolumn like '%%'
this gets me no result.
I think it is ANSI encoding
|
This is the Unicode replacement character symbol.
It could match any of 2,048 invalid code points in the UCS-2 encoding (or the single character `U+FFFD` for the symbol itself).
You can use a range and a binary collate clause to match them all (demo).
WITH T(N)
AS
(
SELECT TOP 65536 NCHAR(ROW_NUMBER() OVER (ORDER BY @@SPID))
FROM master..spt_values v1,
master..spt_values v2
)
SELECT N
FROM T
WHERE N LIKE '%[' + NCHAR(65533) + NCHAR(55296) + '-' + NCHAR(57343) + ']%' COLLATE Latin1_General_100_BIN
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 15,
"tags": "sql, sql server, tsql"
}
|
What's the meaning of "What time do you call this?"
There is a song which has this phrase:
What time do you call this?
repeated in it. Is this a phrase with special meaning?
Here is a link to song
|
It means: "You are very late!" When a 16 year old girl returns home at 02.00, her parents will say to her: "What time do you call this?!Why are you late?
|
stackexchange-ell
|
{
"answer_score": 3,
"question_score": 0,
"tags": "word usage, phrase meaning"
}
|
How to feed pipe into an inequality?
This has come up in multiple instances, and I do not know if this current instance is generalizable to the many cases where this arises for me, but I'm hoping an answer may shed some light.
The simplest version of this is when I am doing some data processing and want to perform an evaluation on the result of a pipe. A simple example would be:
> seq(9) %>% > 4
Error: unexpected '>' in "seq(9) %>% >"
> seq(9) %>% . > 4
Error in .(.) : could not find function "."
The desired output would be a logical vector
FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
In many circumstances I want to evaluate on some piped output but have to assign it and then perform the evaluation for it to work:
seq(9) -> vec
vec > 4
Is there a way to complete these sorts of evaluations within a pipe chain entirely?
|
You need to use curly braces if you just want to use pipes.
seq(9) %>% {. > 4}
[1] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
I'd recommend using `purrr` if you're going to be piping these kinds of things, as it will result in a bit more readable code.
library(purrr)
map_lgl(seq(9), ~.x > 4)
[1] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "r, piping, magrittr"
}
|
How can I add a callback to a ThreadedKernelClient in IPython?
Currently I'm getting my hands on a `ThreadedKernelClient` by:
kernel_manager = KernelManager(client_class='IPython.kernel.threaded.ThreadedKernelClient')
kernel_manager.start_kernel()
kernel_client = kernel_manager.client()
However, I'm not sure how I can register a callback for incoming messages (after I run `execute`). Can anyone point me in the right direction?
|
What I've done is subclass `ThreadedZMQSocketChannel` and `ThreadedKernelClient`, and overwrote `call_handlers`, eg:
class TestChannel(ThreadedZMQSocketChannel):
def call_handlers(self, msg):
# do something
class TestClient(ThreadedKernelClient):
iopub_channel_class = Type(TestChannel)
shell_channel_class = Type(TestChannel)
stdin_channel_class = Type(TestChannel)
Your manager then looks like:
kernel_manager = KernelManager(kernel_name='python', client_class='__main__.TestClient')
Once you `start_channels`, your `call_handlers` method will be called with results from methods such as `execute`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ipython, jupyter"
}
|
Which collection is better to store data from multi-dimensional array?
I have a `multi-dimensional array of string`. I am willing to convert it into some collection type, so that I can add, remove and insert elements according my wish. In array I can not remove element at particular position.
I need such collection in which I can remove data at particular position, also able to add data at any position.
Also dont forget I have multi-dimension array, so the collection should also able to store multidimensional data.
Which collection will be suitable for my requirments?
|
ArrayList should do what you need. For instance:
List<List<String>> stringList = new ArrayList<List<String>>(); //A List to store a list of strings
or...
List<String[]> myNumberList = new ArrayList<List<String[]>(); //A List to store arrays of Strings.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "java, collections, multidimensional array"
}
|
WordPress 'The following link has expired'
I've got a big problem. I am working on a site within wordpress when I was doing so compressions etc this morning and I go back onto my site to see the theme options have been reset! So I tried to go into change them but every time i try to save it comes up with this.
The Following Link Has Expired
I'm really confused. I think it's more of a database issue because I've contacted my hosting company and they did everything they could but still nothing.
I have followed every single tutorial online and nothing. Can anyone help!
|
I managed to fix my own mistake! - What I had done is while minifying the CSS files I accidentally minified the theme's style.css file. In order for WordPress theme's to work they need the Theme Info at the top. So, just add back in the info and it all works!
Hope this can help to anyone if they're having the same trouble.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "database, wordpress, error handling"
}
|
Are there any Alternatives to using a Refractometer to determine extraction
Wondering if anyone has used a refractometer or knows of any other method to measure a coffee extraction (or dissolved solids)?
|
I guess measure density just like you would in a college-lab? Just use a graduated cylinder.
Extraction is mostly about how efficiently you can extract coffee solubles with an amount of liquid. Since refractometers are pricy, you can use a 0.1g scale and a graduated cylinder, to measure how heavy your shots are. The denser the better, however you also have to be practical with how long your shots take to be pulled.
|
stackexchange-coffee
|
{
"answer_score": 2,
"question_score": 4,
"tags": "extraction"
}
|
Chain Rule For Limits
Given a function $f:\mathbb R^2 \rightarrow \mathbb R$ is continuous and has a limit at $p=\infty$, $\lim_{x\rightarrow p}f(x,y)=b(y)$ and a function $g:\mathbb R \rightarrow \mathbb R$ is continuous and has a limit at $p$, $\lim_{x\rightarrow p}g(x)=c$, is the following statement true? $$\lim_{x\rightarrow p}f(x,g(x))=\lim_{x\rightarrow p}f(x,c)=b(c)$$
|
For $p=\infty$ it is not true. A counterexample: $$ f(x,y)=\frac{1}{x^2|y|+1}\to b(y)=\left\\{ \begin{array}{ll} 0, & \text{if } y\ne 0,\\\ 1, & \text{if } y= 0. \end{array} \right. $$ $$ g(x)=\frac{1}{x^2+1}\to c=0. $$ So we have $f(x,c)=f(x,0)=1$, but $$ f(x,g(x))=\frac{1}{\frac{x^2}{x^2+1}+1}\to \frac12. $$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "limits"
}
|
Does "composer remove drupal/module" actually uninstall the module first?
Does `composer remove drupal/module` actually uninstall the module first, especially in multi-site environments?
On the other hand, does `composer require` "enable" the given module for all sites?
|
No, Composer doesn’t install or uninstall modules in the site itself.
It’s a dependency manager; all it does is compute your requirements, then download them.
You might be able to add a post install/update command to automate it, but trying to make it generic would probably be a pain.
|
stackexchange-drupal
|
{
"answer_score": 9,
"question_score": 13,
"tags": "composer"
}
|
How to get device language in sencha touch or architect
I am developing an app for IOS & Android with Sencha and I was wondering how to retrieve the language the device (regardless of the os) using Sencha touch or architect. Is this possible?
Thanks :)
|
navigator.language
you can also try this on chrome developers tools:
console.log(navigator.language);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "extjs, sencha touch, sencha touch 2, sencha architect"
}
|
Exception: org.exolab.castor.xml.ValidationException was not added to the list of sorted types
I am trying to deploy EAR file on Websphere Application Server but while deploying it's showing an error.
ERROR CODE:
SEVERER: Exception org.exolab.castor.xml.ValidationException was not added to the list of sorted types.
The project was not built since its build path is incomplete. Cannot find the class file for org.exolab.castor.xml.ValidationException. Fix the build path then try building this project.
I am using Castor in my project but it's there in classpath which i am setting through Shellscript.
Thanks for help in advance.
|
Your dependencies need to be expressed to the application server runtime, not added to some shell variable or standalone java invocation. Either package them in your application or create an isolated shared library and associate it with your dependent application.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "websphere, ear, castor"
}
|
ComplexListPlot not complete
This code creates three complex lists. The third list is the `Union` of the other two. There are three plots. When applying `ComplexListPlot` to all three lists I would expect the third plot to be the first two plots combined. But no! Why? What am I missing?
z = Table[{x, I*y}, {x, -2, 0}, {y, -2, 0}]
s = z^3
g = Union[z, s]
ComplexListPlot[#, Joined -> True, PlotRange -> Full] & @@ z
ComplexListPlot[#, Joined -> True, PlotRange -> Full] & @@ s
ComplexListPlot[#, Joined -> True, PlotRange -> Full] & @@ g
 printf("Debug msg\n");
printf("Info msg\n");
|
You can refer the below program where a macro is defined and based on the option passed to the executable logging is enabled.
#include <stdio.h>
#include <string.h>
#define STREQ(a, b) !(strcmp((a), (b)))
#define logmsg(fmt, ...) \
do { \
if (debug) \
printf(fmt, ##__VA_ARGS__);\
}while(0)
char debug;
int main(int argc, char *argv[])
{
if (argc > 1) {
if ( STREQ(argv[1], "debug"))
debug = 1;
}
logmsg("%s\n", "hello_world");
return 0;
}
Pass `debug as the first argument to the executable to enable logging`
Note : This program has been tested `on Linux with gcc compiler`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c, c99"
}
|
LLDB not able to debug application
I currently want to debug my application using the LLDB debugger. I am successfully able to run code in my application if I set a breakpoint on my iPhone app and when I click `build and run`. The problem is if I start my application without Xcode and attach the debugger to my iOS application. Doing it this way means I cannot debug my application.
When I do `build and run` from Xcode along with a breakpoint and run the LLDB command `list`. I can see that it is debugging the `GameViewController.swift` file, however when I attach the debugger to my app after running it normally, the LLDB debugger is now in the AppDelegate file.
How would I get the LLDB debugger to debug the file `GameViewController.swift` instead of `AppDelegate,swift` file?
|
> Bear in mind that the debugger is attached to your entire application, not to a particular file.
When you attach to the program, it stops _wherever_ the program happens to be; and if the program is idling, that will be in the `AppDelegate` more times than not.
To get it to list code in another file, you can use the `list` command, e.g. by using:
list GameViewController.swift:10
It lists the file GameViewController.swift, from line `10`, for `10` lines.
You can add in a breakpoint for a method in GameViewController, e.g. for a method called `onClick` by doing:
breakpoint set --file GameViewController.swift -n onClick
or a line using:
breakpoint set --file GameViewController.swift -l 998
and then continuing, until it stops in the relevant piece of code.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "iphone, xcode, debugging, lldb"
}
|
Printing the return value from inet_aton() function
I have this code which is working fine:
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
struct in_addr addr;
if (argc != 2) {
fprintf(stderr, "%s <dotted-address>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (inet_aton(argv[1], &addr) == 0) {
perror("inet_aton");
exit(EXIT_FAILURE);
}
printf("%s\n", inet_ntoa(addr));
exit(EXIT_SUCCESS);
}
What I want to achieve is print the value of `inet_aton()` function. The description of function says that it returns a number, but when I try to print it, it says "cannot covert from address structure to decimal".
|
Using this instead of your last `printf` worked for me:
printf("%d\n", addr.s_addr);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c, network programming, inet aton"
}
|
Audacity's Export Selection: How can I export a file using the Nero AAC Encoder?
I'd like to use the Nero AAC Encoder to create my lossy files.
Here's what is happening:
1. I open a WAV file in Audacity.
2. I select the portion of the audio I need to export and click **export selection**.
So, I'm never creating an intermediate slice. My problem is that I don't understand what to pass as the input file:
!nero usage
Here's a non-working command line I'm using in Audacity. It fails because Nero complains about the missing input file. Notice that the Audacity dialog mentions **standard in** , can I use that? !audacity CLE
|
Nero AAC Encoder 1.5.3.0 or newer is required.
To specify standard in, use a hyphen (`-`). Depending on how data is piped you may also have to use the `-ignorelength` switch.
Your command line should look like this:
neroAacEnc.exe -ignorelength -q 0.6 -if - -of %f
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "command line, nero, audacity"
}
|
I am unable to instantiate a String array without values temporarily, so that I can add the values at a later stage
my code:
String [] temp;
temp = {"one","two","three"};
I get this error:
Illegal start of expression, ';' expected.
|
Curly braces, the way you have used them, can only be used in array declaration statements. i.e.
String[] temp = {"one","two","three"};
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "netbeans, java me"
}
|
parsing code into components
I need to parse some code and convert it to components because I want to make some stats about the code like number of code lines , position of condition statements and so on .
Is there any tool that I can use to fulfill that ?
|
Antlr is a nice tool that works with many languages, has good documentation and many sample grammars for languages included.
You can also go old-school and use Yacc and Lex (or the GNU versions Bison and Flex), which has pretty good book on generating parsers, as well as the classic dragon book.
It might be overkill, however, and you might just want to use Ruby or even Javascript.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "parsing, parser generator"
}
|
Extension of the series expansion of $\ln(1+x)$ to complex numbers
You can prove, without too much trouble, that : $$\ln(1+x) = x- \frac{x^2}{2} + \frac{x^3}{3} - \frac{x^4}{4} + \cdots = \sum_{n=1}^\infty (-1)^{n+1} \frac{x^n}{n}$$ This is true if $|x|<1$ and $x \in \Re$ but also if $x$ is a complex number. I know how to prove this with real numbers, but how can I extend this definition to the complex plane ? Can I simply say it works the same way, by replacing the real values with complex ones ? Or are there specific things one has to pay attention to ?
I have a start of university math level, by the way.
|
This conditions for $z$ is from this book _Classical Algebra_ , G. Paria, page 221:
The series holds true for complex quantity $z=x+iy$ with following conditions:
I. The modulus of $z$ is less than unity, or
II. The modulus of $z$ is equal to unity but the argument of $z$ is not equal to an odd multiple of $\pi$.
By definition we have: $\operatorname{Ln}(1+z)=2n\pi i+\ln(1+z)$, it follows that:
$$\operatorname{Ln}(1+z)=2n\pi i+z-\frac{z^2}2 +\frac{z^3}3- \cdots,$$
where $n$ is zero or an integer (positive or negative).
Note that $\operatorname{Ln}(1+z)$ is not the same as $\ln(1+z)$ which is:
$$\ln(1+z)=z-\frac{z^2}2+\frac{z^3}3 - \cdots$$
and is called principal value of $\operatorname{Ln}(1+z)$ and results in when $n=0$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "sequences and series, complex numbers"
}
|
Should modules always contain a class?
I'm writing a module which only contains functions. Is it good practice to put these inside a class, even if there are no class arguments and the `__init__` function is pointless? And if so how should I write it?
|
There's no particular reason to force functions to go inside a class if there's no reason to make a class. A python sourcefile already provide a perfectly reasonable _namespace_ for storing similar, related functions. The pypy implementation of the python programming language, for example, has many modules that don't have classes in them (for example, `time`).
You would want a certain data structure as a class, of course, but there are certain behaviors that are entirely independent of data structures, and putting them in a class would just add needless complexity.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, module"
}
|
Can Commerce be setup to skip Cart/Customer
Can the module Drupal Commerce (7.x-1.7) be setup so that a user can just click 'Buy' on an item and then be taken to a payment processor such as Paypal to pay? I've tried to find a way to do this but the Commerce set of modules is just a little overwhelming at the moment. I need to be able to do this as I'm selling a virtual currency to my users and they are used to a quick process and they don't wish to give out billing information.
|
Yes, it's possible but would need testing out and tinkering.
You could disable the checkout pages, other than payment / offsite payment redirect
Either at
* _admin/commerce/config/checkout_ by setting the panes to disabled
* or perhaps with hook_commerce_checkout_page_info_alter and removing the pages.
You could then add a Rule
* _Event: After adding product to cart_
* _Action: Redirect to page "checkout"_
Which will hopefully take the user off to PayPal / offsite payment.
Again, needs testing, but theoretically possible.
|
stackexchange-drupal
|
{
"answer_score": 2,
"question_score": 1,
"tags": "commerce"
}
|
Some exercises about functions
I need some exercises about functions in general to make sure that I understand it, in a book or a material book. Concepts like function in general (the definition of function), concepts like one-to-one, onto and closure.
|
See the section on functions in the first chapter of _Fundamentals of Abstract Algebra_ by Malik, Mordeson and Sen for numerous exercises.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 3,
"tags": "functions"
}
|
How do I replace a word from a string without using .replace() method as I want the word to be removed only once
For example: I have a list `a = ["john", "jack", "mike"]`, and a string like `s = jackmikejohnjackjack"` and I want to append all the names from this string to a new list like `b = ["jack", "mike", "john", "jack", "jack"]`,
as you may have noticed **duplicates** also need to be appended, I have tried someting like :
a = ["john", "jack", "mike"]
s = "jackmikejohnjackjack"
b = []
for item in a:
if item in s:
b.append(item)
but this will only return `b = ['john', 'jack', 'mike']`, Also can't use `s.replace(item, "")` after appending the name to b as it will give same answer
|
If the order doesn't matter, You could use `re.findall`:
import re
a = ["john", "jack", "mike"]
s = "jackmikejohnjackjack"
b = []
for item in a:
result = re.findall(item, s)
for subitem in result:
b.append(item)
print(b)
Which would output:
['john', 'jack', 'jack', 'jack', 'mike']
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, string"
}
|
How to use a common find text box for all tabs in Firefox?
Recent versions of Firefox have introduced a separate find box for each tab.
Is there any config variable in about:config or any addon to disable tab level search in Firefox or use a common find text box for all tabs?
|
GlobalFindBar:
> Since Firefox 25, the FindBar was made independent for each tab. This addon reverts the FindBar to classic/global behavior.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 1,
"tags": "firefox, firefox extensions"
}
|
Subversion Force Refresh
Does such a thing exist in subversion?
In perforce we used to have to do this quite often especially when Perforce got the incremental update wrong - It does not seem possible in Subversion
Is an alternative to delete the .svn file and do an update?
|
`svn up` generally does the trick. Occasionally, your working copy can get into a bad state, requiring `svn cleanup`. Very occasionally, even that doesn't work, and the simplest fix is to `svn co` into a clean directory.
For a prohibitively large working copy, you might be able to avoid `svn co` if you can isolate a subtree causing problems, delete it, then `svn up`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "svn"
}
|
Is there any way to know which collection view cell is at a specific point?
I have a CGPoint and I would like to know which cell from my collection view currently contains that point. Is there any simple way to do this or do I have to write my own method?
|
I haven't used `UICollectionView`s much, but there's a method that seems perfect:
- (NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point;
The point you pass to the method has to be within the coordinate system of the collection view. You can do:
CGPoint convertedPoint = [collectionView convertPoint:point fromView:viewThatYouGotThePointFrom];
to get the correct point, if the point you got isn't from the collection view originally.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 2,
"tags": "objective c, ios, uicollectionview, cgpoint, uicollectionviewcell"
}
|
How to get just numeric part of CSS property with jQuery?
I need to do a numeric calculation based on CSS properties. However, when I use this to get info:
$(this).css('marginBottom')
it returns the value '10px'. Is there a trick to just getting the number part of the value no matter whether it is `px` or `%` or `em` or whatever?
|
This will clean up all non-digits, non-dots, and not-minus-sign from the string:
$(this).css('marginBottom').replace(/[^-\d\.]/g, '');
UPDATED for negative values
|
stackexchange-stackoverflow
|
{
"answer_score": 167,
"question_score": 162,
"tags": "javascript, jquery, css, parsing"
}
|
Скрыть подсказки словаря клавиатуры
Добрый день!
Есть ли возможность задать настройки в поле ввода для клавиатуры, запрещающие отображение словаря/подсказок?
Спасибо!
|
Есть. Поиграйте с флагами TextAutoComplete у того EditText'а, о котором пишете.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "android, клавиатура"
}
|
Examples of exact many-body ground state wavefunction
Is there any non-trivial many-body system for which the exact solution to Schrödinger's equation is known? (By non-trivial, I mean a system with particle-particle interactions.) Perhaps something like positronium, or two electrons in a box.
|
The most elegant example I have found is Hooke's atom, also called harmonium. It consists of two electrons that are trapped in a harmonic well:
$$ H=-\nabla^2_1-\nabla^2_2+\frac{1}{\left|\mathbf{r}_1-\mathbf{r}_2\right|}+\frac{1}{2}k\left(\mathbf{r}_1^2+\mathbf{r}_2^2\right) $$
For certain values of the spring constant _k_ , this Hamiltonian can be solved _exactly_. For example, when _k_ = ¼, the ground state is: $$ \Psi\left(\mathbf{r}_1,\mathbf{r}_2\right)=\frac{1}{2\sqrt{8\pi^{5/2}+5\pi^3}}\left(1+\frac{1}{2}\left|\mathbf{r}_1-\mathbf{r}_2\right|\right)\textrm{exp}\left(-\frac{1}{4}\left(r_1^2+r_2^2\right)\right) $$
Source: Wikipedia
|
stackexchange-physics
|
{
"answer_score": 3,
"question_score": 6,
"tags": "quantum mechanics, schroedinger equation, many body"
}
|
Finding the translation between points
I have a map of the US, and I've got a lot of pixel coordinates on that map which correspond to places of interest. These are dynamically drawn on the map at runtime according to various settings and statistics.
I now need to switch over to a different map of the US which is differently sized, and the top left corner of the map is in a slightly place in the ocean.
So I've manually collected a small set of coordinates for each map that correspond to one another. For example, the point (244,312) on the first map corresponds to the point (598,624) on the second map, and (1323,374) on the first map corresponds to (2793,545) on the second map, etc.
So I'm trying to decide the translation for the X and Y dimensions. So given a set of points for the old and new maps, how do I find the `x' = A*x + C` and `y' = B*x + D` equations to automatically translate any point from the old map to the new one?
|
You have the coordinates of two points on both maps, (x1,y1), (x'1, y'1), (x2, y2) and (x'2, y'2).
A = (x'1 - x'2)/(x1 - x2)
B = (y'1 - y'2)/(y1 - y2)
C = x'1 - A x1
D = y'1 - B y1
**P.S.** Your equations imply a simple scaling/translation from one map to another. If you're worried about using different projections from globe to plane, the equations will be more complicated.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "language agnostic, math, translation, coordinates"
}
|
Multiple input files to CMake execute_process
I want to execute a command in CMake with execute_process(). I have multiple input files in a variable. How can I get all files into the INPUT_FILE section?
using
execute_process(
COMMAND
${Python3_EXECUTABLE}
${CMAKE_SOURCE_DIR}/tools/generator.py
${input_files}
INPUT_FILE ${CMAKE_SOURCE_DIR}/tools/generator.py
INPUT_FILE ${input_files}
OUTPUT_FILE ${output_files})
gives the following message:
CMake Error at /cmake/codegen.cmake:112 (execute_process):
execute_process given unknown argument
"second_file.name"
|
INPUT_FILE and OUTPUT_FILE are not ment to contain one file used or changed by the command. The file listed there are standard input and output to the process.
The file given in OUTPUT_FILE is in fact the logging file for standard output. INPUT_FILE is input a user would give over the console after the execution of the command has been triggered.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "cmake"
}
|
Logarithmic differentiation (how to solve log differentiation with two different term)
f(m)=m log m+(n-m)log (n-m)
f'(m)=log m +1+(-1)log (n-m)+(-1). How to get this line?
f'(n/2)=0
f(n/2) is the minimum point. How to know n/2 is the minimum point?
|
You have, as you wrote, $$f(m)=m \log (m)+(n-m) \log (n-m)$$ $$f'(m)=\log (m)-\log (n-m)$$ $$f''(m)=\frac{1}{n-m}+\frac{1}{m}$$ So, the serivative cancels when $$\log (m)=\log (n-m)\implies m=n-m\implies 2m=n\implies m=\frac n 2$$ Now, using the second derivative test $$f''\left(\frac n 2\right)=\frac{4}{n}>0$$ So, the point is the minimum and $$f\left(\frac n 2\right)=n \log \left(\frac{n}{2}\right)$$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "calculus, sorting"
}
|
Selecting last action from log table
I have some kind of log table which registers every interesting event that an agent has. Basically, if it's logged or busy or whatever.
With that said, imagine this:
agent event dateTime
1 foo logged 2012-03-01 14:23:36
2 foo unlogged 2012-03-01 14:24:36
3 baz logged 2012-03-01 14:25:36
4 bar logged 2012-04-01 08:24:36
6 bar unlogged 2012-04-01 08:25:36
7 foo logged 2012-04-01 08:26:36
I want to retrieve just the ones that are "logged" so, in this example, it would be foo (id 7) and baz (id 3) (obsesive worker here...)
I've been thinking but didn't find the trick.
Does anyone knows?
|
**Updated** * _Updated once again to retrieve last status_ *
SELECT a.*
FROM table1 a
INNER JOIN
(SELECT agent,
MAX(`dateTime`) as lastActionDt,
MAX(CASE WHEN `event`='logged' THEN `dateTime` END) as last_logged_in_event,
MAX(CASE WHEN `event`='unlogged' THEN `dateTime` END) as last_logged_out_event
FROM table1
GROUP BY agent
HAVING last_logged_out_event IS NULL OR last_logged_in_event>last_logged_out_event
) b ON
(b.agent = a.agent AND b.lastActionDt = a.`dateTime`)
I assume it's impossible to have `unlogged` event without corresponding `logged`. If it's possible, then `HAVING` should look `HAVING last_logged_in_event IS NOT NULL AND(last_logged_out_event IS NULL OR last_logged_in_event>last_logged_out_event)`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mysql"
}
|
PayPal Form for every 50 quantity get 5 free
I am having trouble here with my paypal form. What I am trying to do is set it up so for every 50 in quantity, they get 5 free. Is there away to do this with the discounts?
<input type="hidden" name="amount" value="9.00">
<input type="hidden" name="currency_code" value="CAD">
<input type="hidden" name="discount_amount" value="0" />
<input type="hidden" name="discount_rate" value="1" />
<input type="hidden" name="discount_num" value="5" />
|
I'm afraid PayPal Website Payment Standard could not meet your request perfectly. You may have to write some JavaScript to generate the value of discount_amount dynamically.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "paypal"
}
|
Bing Maps WPF Control grey background in Windows Server 2012 R2
I'm having a problem with Bing Maps WPF Control in just one particular customer.
The bing map logo is there and the kilometers scale too but the tiles are grey.
If I type an address to search, it will put a pushpin with the right latitude and longitude but the tiles still grey.
Is working fine everywhere else so the only difference that I can find is that the app is running on a Windows Server 2012 R2.
It's winform app with a WPF control.
The Bing Map Key is correct (checked 5 times!!).
Any ideas, suggestions, pointers?
|
I have configured the Internet gateway not to proxy web traffic coming from the server and the maps feature of the app is working.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "c#, wpf, bing maps"
}
|
PHP validar palavra-passe
Não tenho grandes bases com PHP no entanto, preciso de fazer validações como:
* tamanho de string
* contem letras, maiusculas e minusculas
* contem numeros
* contem caracteres especiais
Neste caso para uma palavra passe, eu tentei fazer com regex, no entanto nao sei como que posso verificar se tem **algum** caracter especial. Qual seria a melhor forma de verificar tudo isso.
Obrigado desde já!
|
A expressão abaixo engloba pelo menos uma letra minuscula, maiuscula, número e simbolo. com um tamanho de 8+ chars:
preg_match('/^(?=\P{Ll}*\p{Ll})(?=\P{Lu}*\p{Lu})(?=\P{N}*\p{N})(?=[\p{L}\p{N}]*[^\p{L}\p{N}])[\s\S]{8,}$/', $entrada, $saida);
Aproveite e leia essa resposta. É bem legal e esclarece algumas coisas: <
_se alguém traduzisse eu "upvotaria" pq é muito detalhada_
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": -3,
"tags": "php, validação, password"
}
|
What is the difference between this, self, window and window.self
If I open an empty page and I run the following command in javascript console I obtain the same result:
>>> this
DOMWindow
>>> self
DOMWindow
>>> window
DOMWindow
>>> window.self
DOMWindow
What do they refer to? ...the same object or what else?
|
`window` is the reference to the current browser’s window the script executes in. `window.self` is obviously a self-reference of that within itself. And since `self` here is a property of the global object `window`, it can also be accessed as if it was a “global” variable itself: just `self`.
So the last three are under most circumstances indeed the same thing.
`this` however is completely different: it’s a variable pointing to the current _scope_. If you execute the following code in the console:
> var myPackage = {}
> myPackage.method = function() {console.log(this)}
> myPackage.method()
`this` will be pointing to the `myPackage` object (the scope of `method`).
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 9,
"tags": "javascript"
}
|
Is there any ax.view_init(elev, azim) equivalent function in plots.jl?
I am using `Plots` for visualizing 3d-plots with Julia, and I am trying to change camera angle of my plot. In `matplotlib` in Python, I know that I can use `ax.view_init(elev, azim)` to change the camera angle, but on `Plot.jl`, I could not find solution to change the angle.
Is there any equivalent function with `ax.view_init(elev, azim)` in Python in Julia ?
**Example of Plot**
using Plots
plot()
for i in 1 : 5
a = rand(10); b= rand(10); c = rand(10);
plot!(a,b,c, seriestype=:scatter)
end
plot!()
|
As you can read in the manual you can use the `camera` keyword argument (aliases are: `cam`, `cameras`, `view_angle`, `viewangle`). This argument sets the view angle for 3D plots. Its value is required to be a tuple `(azimuthal, elevation)` and the default setting is `(30, 30)`.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "julia, plots.jl"
}
|
toLocaleDateString() - issue with Norwegian
I have an issue with getting locale datestring correctly formatted. It suddenly stopped working for Norwegian. I've tried 'no-NO' and 'nb-NO'. Any ideas about what could be causing this? I'm stuck.
Example:
console.log(new Date().toLocaleDateString('no-NO', {month: 'long', day: 'numeric', year: 'numeric'}))
// 2021 M08 10
Other languages work as expected:
console.log(new Date().toLocaleDateString('da-DK', {month: 'long', day: 'numeric', year: 'numeric'}))
// 10. august 2021
|
There is a bug in chrome causing this, hopefully they will fix it soon. <
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "javascript, reactjs, locale"
}
|
Info on ProcMon from SysInternals
I need help. I am reversing `Procmon64.exe` file. It drops `procmon.Sys` filesystem minifilter driver which does monitoring.
Question: I need to know if filtering of events is done in user-mode or kernel-mode.
My hypothesis is that all events are sent to user-mode application and then are filtered and displayed.
For now i breakpointed procedure that calls `FilterGetMessage` but can't figure out if it returns all events or just filtered events.
Thank You.
|
Most likely the driver only monitors events and send messages to user mode. This approach is used in Microsoft driver samples. If I remember correctly - that it is: <
I think it is good example to understand mini-filter driver and user mode app communication.
|
stackexchange-reverseengineering
|
{
"answer_score": 0,
"question_score": 0,
"tags": "windows, driver"
}
|
New OnPlatform/OnIdiom XAML Extension - Usage for Margin Thickness
In Xamarin.Forms 3.2.0, Xamarin Forms introduced new New **OnPlatform/OnIdiom XAML Extension**
As per the blog we can re-write the below code,
<Button Text="Extensions" BackgroundColor="Black" TextColor="White">
<Button.HeightRequest>
<OnPlatform x:TypeArguments="x:Double" Default="40">
<On Platform="iOS" Value="60"/>
<On Platform="Android" Value="80"/>
</OnPlatform>
</Button.HeightRequest>
with the new extension.
<Button Text="Extensions" BackgroundColor="Black" TextColor="White"
HeightRequest="{OnPlatform iOS=60, Android=80, Default=40}"/>
Here my doubt is how I can reuse the same **OnIdiom XAML Extension** for **Margin / Thickness.**
|
You should be able to do it like this: `<Button Margin="{OnPlatform Android='10,5,10,0', iOS='10,20,10,0'}" />`
It's up to you which syntax you like more!
|
stackexchange-stackoverflow
|
{
"answer_score": 38,
"question_score": 14,
"tags": "xaml, xamarin.forms"
}
|
Fine grained permissions for docker registry
I want to setup a private docker registry and need to be able to specify fine grained permissions on repository level e.g. I have repositories
* foo
* bar
* baz
* Developer A can see and pull from all three repositories but cannot push to any of them.
* Developer B can push and pull to/from foo but cannot see any of the other repositories.
* Developer C can push/pull from baz and pull from bar but cannot see foo.
As most of our services are in Azure I would prefer to use Azure Container Registry but it seems I can only assign permissions across the whole docker registry and not for individual repositories.
Is there a way to achieve what I want with Azure Container Registry and if not what are my alternatives (preferably open source)?
|
Just as you know, Azure Container Registry does not have the feature that you need, it just can control the access of all the repositories, not individual. So you cannot achieve your purpose in ACR.
Maybe you can try to create your own private docker registry in the VM, then you can follow the steps in Authentication and authorization in DTR. It seems you can control the access for the individual repository via the teams in docker registry. Hope it helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "azure, docker, docker registry"
}
|
Check if other files were modified in a commit series in git
Suppose I have a file `mocky.cpp`, I would like to list commits that modified the file, and also list another files that were touched by these commits. So I try the following:
git log --name-only -- mocky.cpp
I get a list of commits, that is nice, strangely, however, all the commits do not modify a file except from `mocky.cpp`. I check one of them, say, e013aac, w/ `git show e013aac` and I find out it also changes `testy.hpp`. Moreover, I found that `git show e013aac -- mocky.cpp` only outputs the diff for the `mocky.cpp` but not for the `testy.cpp`
This is most counter-intuitive to me, anyway, how could I achieve what I wanted in the first place?
|
Try:
git log --format=%H -- mocky.cpp | xargs git show --stat
Or modify it for your needs like:
git log --format=%H -- mocky.cpp | xargs git show --name-only
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "git"
}
|
Unit Testing - Workflow Field Update
A SF newbie here.
Is it possible to write a test class that can check WF field updates also ?.
I have a WF update created on a Custom object CaseLog__c.
Is it possible for me to write a Apex Test case to check whether the field update is happening as expected ?.
I know no code will be covered, but can I still a write unit test case and check whether it is working as expected ?.
Any input on it will be appreciated ..tx
|
Definitely. Just write a unit test that creates the CaseLog__c record, then sets whatever criteria are needed to fire off the workflow, then requery the record and do a system.assertEquals() to make sure that the record has the expected value.
You can also do this to check that formula fields, roll-up fields, and validation rules are working correctly.
|
stackexchange-salesforce
|
{
"answer_score": 1,
"question_score": 0,
"tags": "unit test, workflow"
}
|
jquery datatables table breaks when refreshing data
Refreshing data on the fly causes my table to completely break. Imagine stomping on an empty soda can. Then when the data repopulates it goes back to normal size. I am trying to see if anyone has had similar problems and if so what was your solution?
|
The table elements (td, th etc) need to have some fixed width/height/padding/margin settings in the CSS assigned for it. Maybe you should first render your table without any data for testing purposes - empty table. Add min-width or padding or whatever to have the table render the way you want without any data. Once you can do that, then add the data and now if you refresh it, the table may not break any more.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery, datatables"
}
|
Is optional or required the default for protocol methods?
I used to think that the default/implicit specifier for protocol methods is optional. However, in my current project I see a warning if I do not add the @optional specifier specifically. Not a big deal. I am just wondering, was it optional the default for a while, and now it is required? Or maybe I missed something while I was learning Objective-C a while ago.
Thanks in advance!
|
`@required` was always by default to gurantee, that you app won't crash if you inherit protocol and forget to implemet methods. So you should manuall set `@optional`
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "objective c, delegates, protocols"
}
|
Can't re-flag aged-away flag
I flagged this post (as duplicate) 2014-12-05, a few hours after it was posted, and the flag is marked aged away. But I can't re-flag that post for any type of closure, even though Age close votes after 14 days, regardless of views, allowing recasting quite definitely says that I should:
> 2. Allow re-casting votes that've aged away after 14 days. That is, 14 days (use the same site-configurable value used in #1 here) after your vote has aged away, you're free to cast the same vote again.
>
>
> […]
>
> For consistency, both of these changes should be applied to Close Votes, Close Flags, and Reopen Votes.
Why can't I?
|
There was indeed a bug in the logic that renders the flagging options. A fix will be rolled out with the next build (build rev `2015.9.21.3705` on MSE/MSO, `2015.9.21.2835` on sites).
|
stackexchange-meta
|
{
"answer_score": 8,
"question_score": 18,
"tags": "bug, status completed, flags, aged away"
}
|
Cannot display data from table where table column name starts with a number codeigniter
I want to display data from a table where the column name starts with a number, here is the code in view file inside the loop
<?php echo $cus->3rdfloorslab; ?>
it shows me the following error:
> Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' in C:\wamp\www\westlinecrm\application\views\client\addpaymentstatementform.php on line 318
is there any solution to display the data without changing the column name from numeric to string.
|
Yes, you can use the following
<?php echo $cus->{'3rdfloorslab'}; ?>
Here is some documentation on variable parsing. Though it's not the best practice.
If you're getting the data from a database, you could do something like
SELECT 3rdfloorslab AS thirdfloorslab
Which would help keep your code to the same standard.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 1,
"tags": "php, mysql, sql, codeigniter"
}
|
How to use a Result[String] in Scala match expression
In the following code the first expression returns a Result[String] which contains one of the strings "medical", "dental" or "pharmacy" inside of a Result. I can add .toOption.get to the end of the val statement to get the String, but is there a better way to use the Result? Without the .toOption.get, the code will not compile.
val service = element("h2").containingAnywhere("claim details").fullText()
service match {
case "medical" => extractMedicalClaim
case "dental" => extractDentalClaim
case "pharmacy" => extractPharmacyClaim
}
|
Hard to say without knowing what `Result` is. If it's a `case class`, with the target `String` as part of its constructor, then you could pattern match directly.
Something like this.
service match {
case Result("medical") => extractMedicalClaim
case Result("dental") => extractDentalClaim
case Result("pharmacy") => extractPharmacyClaim
case _ => // default result
}
If the `Result` class doesn't have an extractor (the `upapply()` method) you might be able to add one just for this purpose.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "scala, match"
}
|
SQL Join with where clause in joined table
world.
I have two tables here called drivers and checkin. the d_id field of the checkin table is holds the id of an entry in the drivers table.
In my query, im trying to join the tables and do a where condition on the joined table.
So far i have this query(i haven't been able to join the tables, the where part on the joined table comes after i achieve this)
SELECT checkin.id, checkin.d_id, checkin.place, ( 3959 * acos( cos( radians(8.9551889) ) * cos( radians( lati ) )
* cos( radians( longi ) - radians(76.9902276) ) + sin( radians(8.9551889) ) * sin(radians(lati)) ) ) AS distance
FROM checkin WHERE status != 1
INNER JOIN drivers ON drivers.id = checkin.d_id
HAVING distance < 10
ORDER BY distance
LIMIT 0 , 20
This query works without the inner join, but i'm not really sure what im doing wrong here. If anybody can point it out, that'd be helpful. Thanks.
|
You should use `where` clause after `inner join`:
SELECT checkin.id, checkin.d_id, checkin.place, ( 3959 * acos( cos( radians(8.9551889) ) * cos( radians( lati ) )
* cos( radians( longi ) - radians(76.9902276) ) + sin( radians(8.9551889) ) * sin(radians(lati)) ) ) AS distance
FROM checkin
INNER JOIN drivers ON drivers.id = checkin.d_id
WHERE status != 1
HAVING distance < 10
ORDER BY distance
LIMIT 0 , 20;
Alternative query:
SELECT checkin.id, checkin.d_id, checkin.place, ( 3959 * acos( cos( radians(8.9551889) ) * cos( radians( lati ) )
* cos( radians( longi ) - radians(76.9902276) ) + sin( radians(8.9551889) ) * sin(radians(lati)) ) ) AS distance
FROM (select *from checkin where status!=1) checkin
INNER JOIN drivers ON drivers.id = checkin.d_id
HAVING distance < 10
ORDER BY distance
LIMIT 0 , 20;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql, join"
}
|
Need to use body onload event, but third party JavaScript library has hijacked it
I'm using Simile to draw dynamic timelines. I am also using an in-house library to add a comment blog. Our in-house library uses the body element's onload event to initialize.
<body onload="initComments('myID')">
But Simile seems to have hijacked the onload for their own purpose so that i`nitComments('myID')` never executes.
Short of changing the Simile code, how could I get my initializer to run?
I would prefer not to add another library (i.e. jQuery) just to solve the problem.
|
Use jQuery's `$(document).ready` event, which lets you add an arbitrary number of handlers (unlike `onload`).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, dom events, simile"
}
|
Is there a way to communicate between background thread and current viewcontroller in swift?
There are several ViewControllers in my storyboard, and there is a background thread which is used to receive message from a server, the background thread and the ViewControllers are in different classes.
According to message received, i want to transport the message to a specified ViewController, i used to use Handler to do this thing in Android, but how to do this in swift?
|
Depends, you have plenty of options. How did you manage your connection?
1. you can use delegation (paying attention to make the delegate call on the main thread), if you need 1.1 communication
2. you can use `NSNoticationCenter` and register your view controllers to specific notifications that you'll generate based on the server answer, (paying attention to post them on the main thread). Good if you need 1.* communication
3. you can even use `GCD` blocks (paying attention to call them on the main thread)
The suggestion to make the calls on the main thread is pretty general and it depends on your requirements, but mostly correct if need to update your UI.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ios, swift, macos"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.