INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Remove Header indicatore in flutter web
check this image, how to remove a blue indicator from a header from flutter web
!n^k}$. For large $n$, the expression is said to be approximately equal to $\exp\left(\dfrac{-k(k-1)}{2n}\right)$, which works out to probability of collision of about $\dfrac{k^2}{2n}$ for $1 \ll k \ll n$. How does one derive the former approximation? Apparently the Stirling formula first, and then I see some terms that remind me of $\left(1+\dfrac1x\right)^x \approx e^x$, but it doesn’t quite work out for me.
|
The probability of choosing different items is
$$ \left(1-\frac0n\right)\left(1-\frac1n\right)\left(1-\frac2n\right)\cdots\left(1-\frac{k-1}n\right)\;. $$
For $n\gg k^2$, we can keep only the terms up to first order in $\frac1n$ to obtain
$$ 1-\frac1n\sum_{j=0}^{k-1}j=1-\frac{(k-1)k}{2n}\;. $$
To get the exponential form, you can either approximate this directly as $\exp\left(\dfrac{-k(k-1)}{2n}\right)$ or first approximate the factors in the product:
$$ \exp\left(-\frac0n\right)\exp\left(-\frac1n\right)\exp\left(-\frac2n\right)\cdot\exp\left(-\frac{k-1}n\right)=\exp\left(-\frac1n\sum_{j=0}^{k-1}j\right)=\exp\left(-\frac{(k-1)k}{2n}\right)\;. $$
The error in the exponential form is $O\left(k^3/n^2\right)$, whereas the error in the first form is $O\left(k^4/n^2\right)$, since the exponential form only has incorrect $\frac1{n^2}$ terms for each factor individually, whereas the first version drops an $\frac1{n^2}$ term for each pair of factors.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 2,
"tags": "approximation theory"
}
|
diagonal MatrixXd with concatenated repeats of a VectorXd
I need to create a diagonal MatrixXd in C++ using Eigen library in which the elements on the diagonal are N replication of a shorter VectorXd.
VectorXd R; // a vector of size n
VectorXd V; // a vector of size n*N corresponding to N concatenated replicate of R, i don't khow how to create
MatrixXd D=MatrixXd(V.asDiagonal()); //my diagonal matrix on size n _N x n_ N
thanks.
|
something along the lines of
VectorXd V(N * R.innerSize()); // construct vector of size N * n
for(size_t i = 0; i < n; ++i)
for(size_t j = 0; j < R.innerSize(); ++j)
V[i * R.innerSize() + j] = R[j];
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "c++, eigen3"
}
|
Greatest lower bound of $\{x+k\mid x\in A\}$
We let $A$ be a nonempty bounded set and define $B=\\{ x+k\mid x \in A\\}$, where $k$ is a fixed real number.
I'm trying to show that $\operatorname{glb}B = \operatorname{glb}A + k$.
Thanks in advance.
|
Since ${\sf glb}(A)$ is a lower bound for $A$, ${\sf glb}(A)+k$ is a lower bound for $A+k$. As ${\sf glb}(B)$ is the greatest of those lower bounds, we deduce
$${\sf glb }(A)+k \leq {\sf glb }(A+k) \tag{1} $$ . Replacing $(A,k)$ with $(A+k,-k)$, we also have
$${\sf glb }(A+k)-k \leq {\sf glb }(A) \tag{2} $$
Then (1) and (2) give that ${\sf glb }(A+k)={\sf glb }(A)+k$ as wished.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "real analysis"
}
|
Future raising TypeError after wait
I'm trying to optimise an expensive operation in some existing code using parallel processing. I've used `concurrent.futures` to do so in the past but only when they didn’t return anything.
This time I want to marshall the results, but when printing my collection I'm getting every future's status as something like `<Future at 0x... state=finished raised TypeError>`. Can anyone explain what I'm doing wrong?
import concurrent.futures
with concurrent.futures.ProcessPoolExecutor() as executor:
def _future(self) -> None:
print("here")
futures = []
for number in list(range(0,100)):
future = executor.submit(_future)
futures.append(future)
finished = concurrent.futures.wait(futures, 5)
print(finished)
|
Your `_future` function takes one parameter, and yet your `executor.submit` is passing no argument to it. You should pass, for example, `number`, as an argument to it instead:
for number in list(range(0,100)):
future = executor.submit(_future, number)
futures.append(future)
On the other hand, since you're naming `_future`'s one parameter as `self`, it implies you intend it to be an instance of a class, in which case you should pass to it the proper instance object in your original, non-minimized code.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 10,
"tags": "python, concurrent.futures"
}
|
selenium Android driver - can i run 2 tests simultaneously
Is it possible run 2 test simultaneously in actual device? using android driver.i want to run 2 browser (test) at same time.
|
I would think yes. Try running 2 of the emulators but make sure you change the line:
adb forward tcp:8080 tcp:8080
To use another port for the second emulator. eg.
adb forward tcp:8090 tcp:8090
For the second one you will have to change the constructor of AndroidDriver since it uses 8080 by default. So something like this:
WebDriver driver = new AndroidDriver( new URL(" );
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "android, selenium, webdriver"
}
|
setTimeout в цикле
Как я понял, `setTimeout` запускает функции через нужное нам время. Т.е. в цикле каждая итерация задерживается на наш timeout.
Исходя из этого моего знания вопрос: Почему работает как задумано только первая итерация цикла и как исправить?
for (var i = 0; i < 10; i++) {
setTimeout(function() {console.log("sample");}, 4000);
};
Скорее всего я неверно понял как пользоваться `setTimeout`
|
Код практически одновременно заказывает 10 таймаутов. В Вашем примере все они - через 4 секунды. Вот они все 10 и выполнятся практически одновременно. В моем они заказаны через одну, две, три и т.д. секунды.
for (var i = 0; i < 10; i++) {
setTimeout(function() { console.log("sample"); }, 1000 * (i + 1));
}
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "javascript, settimeout"
}
|
Add artifact to repository in gitlab-ci.yml
I have a multi-project pipeline. Project B depends on Project A. Inside Project B pipeline I am able to get my desired artifacts. Problem is that I am in the Runner's directory, The root path is `CI_PROJECT_DIR`, something like `buildMachine/builds/build#/0/groupname/project`.
I'm not sure what the path to the actually repository should be but it's not this. I need to take these files and add them to the gitlab repository..any advice?
|
I was able to commit the artifacts to my Project B using a variation of this answers...
How do you push to a gitlab repo using a gitlab-ci job?
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "git, gradle, gitlab, gitlab ci runner, gitlab api"
}
|
"Lest" or "Or?"
Colloquially, I would always use _or_ where I would formally use _lest_. For example, "go to sleep, or you'll be tired" versus "go to sleep, lest you be tired."
Has this usage of _or_ been around for a while, or have people phrased sentences like this differently? Perhaps "If you don't go to sleep, you'll be tired."? Is it acceptable to use _or_ this way in formal English?
|
'Lest' is an old word - OED citations begin around 1000AD. It is a more concise way of saying "to avoid the possibility that". As such it is still a perfectly good word introducing a clause expressive of something to be prevented or guarded against, although this fineness of expression is not commonly communicated in this way today.
Ordinary speech today often uses a less nuanced vocabulary and communicates the additional meaning using prosody.
_**" Go to sleep, lest you be tired"**_ \- is a suggestion that you should try to sleep because otherwise it is likely you will be tired.
_**" Go to sleep, or you'll be tired"**_ \- is an unambiguous assertion. Unless you go to sleep you _will_ be tired.
And, of course, symbols and places of remembrance often explain their purpose, explicitly, by saying 'Lest we forget'.
|
stackexchange-english
|
{
"answer_score": 1,
"question_score": 0,
"tags": "etymology, word usage, formality"
}
|
Pandas DataFrame Display Without Dimensions
When I print a `DataFrame` it displays the dimensions of the object (n rows by k columns) at the bottom of the printout. So, for example:
import pandas as pd
df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
print(df)
will display:
A B C
0 10 20 32
1 20 30 234
2 30 10 23
3 40 40 23
4 50 50 42523
[5 rows x 3 columns]
Is there a way to turn off the display of that final line `[5 rows x 3 columns]`?
|
Yes! Use `pd.options.display.show_dimensions = False`:
Here is the original repr:
In [118]: df
Out[118]:
A B C
0 10 20 32
1 20 30 234
2 30 10 23
3 40 40 23
4 50 50 42523
[5 rows x 3 columns]
After setting show_dimensions = False:
In [119]: pd.options.display.show_dimensions = False
In [120]: df
Out[120]:
A B C
0 10 20 32
1 20 30 234
2 30 10 23
3 40 40 23
4 50 50 42523
See the `pd.get_option` docstring (`print(pd.get_option.__doc__)` for more on all the options.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, printing, pandas"
}
|
How do I set the flags/switches for the aspnet_compiler in Visual Studio 2010?
I'm having some trouble with namespacing for a web application project - front-end files are being compiled into separate assemblies under the `ASPX.directory1_director2_directoryn_filename` namespace format and I want everything in one dll.
I found this question and setting the `-o` flag would appear to be exactly the solution I'm looking for. However I build my code in VS2010 using the standard `Build` menu option and I can't find anywhere I can set it. Can anyone point me in the right direction?
|
I suppose you meant aspnet_compiler. Here is a tutorial. It's related to Visual Web Developer 2008. But the basic idea is the same - use the External Tools dialog to create you desired action.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "c#, visual studio 2010, build, csc"
}
|
How to insert data into JSON line by line?
I have a json file `data.json` and a text file `values.txt` with line by line aligned data
data.json
{"_id": 1, "content": "apple"}
{"_id": 2, "content": "banana"}
values.txt
red
yellow
My desired output looks something like follows, where I want to insert a new field `color` into `data.json` into each line with values from `values.txt`.
output.json
{"_id": 1, "content": "apple", "color": "red"}
{"_id": 2, "content": "banana", "color": "yellow"}
What would be the fastest and easiest shell tool to do this?
|
Interlace data with values and stream to JQ, there you can add each pair together.
$ paste -d '\n' data.json values.txt | jq -Rc 'fromjson + {color: input}'
{"_id":1,"content":"apple","color":"red"}
{"_id":2,"content":"banana","color":"yellow"}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "json, bash, sed, jq"
}
|
Large gap at bottom of webpage
What usually causes a large gap in excessive whitesapce on webpage like this one:
<
|
#sidebar-sm #blog span, #sidebar-sm #facebook span, #sidebar-sm #twitter span, #sidebar-sm #linkedin span, #sidebar-sm #quote span {
left:-999em;
position:absolute;
top:999em;
}
It's the top:999em. I think you were supposed to specify negative for the top, not positive ( eg `top:-9999px` or `top:-999em` )
Even if validating doesn't resolve the issue you should strive to make your page valid before asking to save time.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "css, xhtml"
}
|
How to simply load List<string> to table in SQL Server Compact 2008?
Is there any way to load (insert) List into SQL Server Compact 2008 table in simpler way than via looping each record in List and inserting it into database?
|
You could generate a single query to do what you want and run the whole query (which will save you from having n calls to ExecuteNonQuery() ), but that still requires looping to generate the query (and a bunch of string building which is just not fun :( )...
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sql server"
}
|
How to grow width of an element to fit window's width?
I want to show an image in a `WebBrowser`
<html>
<body style="margin:0px;padding:0px;border:0px">
<img src="
</body>
</html>
I want width of `image` grow and be the same as width of visible window (it's not full screen). it's height should grow too without loosing its shape.
var htmlString = "<html><body style="margin:0px;padding:0px;border:0px"><img src=" //It's missing some backslashes, you got the idea.
webBrowser.NavigateToString(htmlString);
currently it just appears at the corner of the page, and this is not what I want.
How can I achieve that? thanks.
|
<img src="image.jpg" width="100%" />
By default in HTML if you specify either height OR width (but not both) for an image, the other attribute will be scaled automatically to keep the same aspect ratio.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, xaml, windows phone 7, windows phone 8, windows phone"
}
|
How can I display the footcites in 2 columns?
I saw some PDF-files, where citations are shown in the footnotes in 2 columns.
I use the `jurabib` package. Is this possible there, too? I don't know, wether the PDF files are coded with LaTeX or not.
I use the `\foocite` to cite some text in my seminar work.
|
Because you gave no MWE I can not test if it compiles with your code.
The one possibility I knew is to add
\usepackage{dblfnote}
to your preamble (before `\begin{document}`). This packages sets footnotes with double columns. You can read the documentation with `texdoc dblfnote` from console/terminal.
|
stackexchange-tex
|
{
"answer_score": 2,
"question_score": 1,
"tags": "citing, footnotes, jurabib"
}
|
How to convert numeric string from a sublist in Python
I'm a freshie. I would like to convert a numeric string into int from a sublist in Python. But not getting accurate results.
countitem = 0
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
for list in list_samp:
countitem =+1
for element in list:
convert_element = int(list_samp[countitem][0])
list_samp[countitem][1] = convert_element
|
You can do it like this:
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
me = [[int(u) if u.isdecimal() else u for u in v] for v in list_samp]
print(me)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, list, integer, numeric, sublist"
}
|
haskell type signatur for returning type constructor
Is it possible to give a type signature for this `getConstructor` function? The function works but i can't find out the way to write the return type.
module Main where
data Letter a =
A a
| B a
| C String
deriving (Show)
-- getConstructor :: String -> (a -> Letter ?) -- <==
getConstructor x
| x == "a" = A
| x == "b" = B
| otherwise = C
main = print $ theType
where theType = (getConstructor "b") "its b!"
Main prints `B "its b!"`
|
Let's take a look:
getConstructor x
| x == "a" = A
| x == "b" = B
| otherwise = C -- <= Let's inspect this line
That line returns `C :: String -> Letter a`. The previous line returns `B :: a -> Letter a`. These types must be equal, so `a ~ String`. Hence, the function becomes:
getConstructor :: String -> (String -> Letter String)
There is no way to dynamically choose the type at runtime with a function like this, since in Haskell, all types are known at compile-time. Hence, it's restricted to working on `String`s only.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "haskell, types, constructor, return type"
}
|
Save as CSV with semicolon separator
I'm currently use this function for saving, but I have a problem with it:
Private Sub spara()
ActiveWorkbook.SaveAs Filename:="T:\filepath+ ActiveWorkbook.Name", _
FileFormat:=xlCSV, CreateBackup:=False
End Sub
It automatically saves with `,` but I need it to save with `;` in its file. Is it possible to change how it saves somehow?
I've tried googling around for this issue, but all macros regarding .csv file saving are just how to save in .csv and how to split multiple sheets to .csv .
|
Which language does your Excel use? If your native language uses ";" as default, you can pass the parameter "local:=True"
ActiveWorkbook.SaveAs Filename:="C:\Temp\Fredi.csv", FileFormat:=xlCSV, CreateBackup:=False, local:=True
If not, your only choice is searching and replacing afterwards...
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 11,
"tags": "excel, csv, locale, vba"
}
|
How to create x264 RTSP server with OpenCV Python with GStreamer backend
My goal is to create a RTSP server using OpenCV Python using the GStreamer backend. I have RGB images stored as OpenCV `Mat`, and I would like to create a `VideoWriter` which can write to a RTSP sink. The output video must be x264 encoded.
I believe this can be easily achieved using a GStreamer pipeline and providing the pipeline arguments to the `VideoWriter` constructor and then later pushing frames to the VideoWriter, but the issue is I have no experience working with GStreamer and I find it very confusing.
The answers I have found on SO are incomplete, use specific hardware decoders (ex for NVIDIA Jetson), or are overly complex. I'd like to find a more generic solution which works on CPU.
|
I have created a project something related to your requirement sometime ago. This could be a kickstarter and customize it based on your need. I'm attaching my github repository link below.
OpenCV RTSP Server
Any issues related to the project can be raised in the github itself and doubts can be cleared here.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "python, opencv, gstreamer, rtsp"
}
|
how to use javascript to get jsf h:outputText value?
I have a button has action which can set myBackingBean.myString, and onclick event calls js method to alert that value. I just want to get the value of myString from backing bean by using javascript.
I have a hidden output which has value from backing bean:
h:outputText id="myOutput" rendered="false" value="#{myBackingBean.myString}"
then I need to alert this value in javascript fxn which triggered by a button:
function myFunction() {
var outPut= document.getElementById("myForm:myOutput").value;
...
}
but i got `Object required` error. How can i fix this? thanks in advance.
|
Make you sure that the h:outputText is rendered (rendered="false" could just not add it to the DOM. If it does not render, it can't be accessed. If you need it hidden, use h:inputHidden instead).
Then make sure that it renders an HTML tag as or acting like a container with the id attribute as "myForm:myOutput".
Also, the .value javascript accesor is used for input tags, so use inerHTML instead.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jsf 2, backing beans"
}
|
Using electromagnetic fields to achieve an unbreakable blade
A while ago I stumbled upon the idea of a stasis field, which shined the light in the tunnel for a question I have. Let's assume that a character has the magical ability to control electricity, could he then achieve a stasis-like effect where the object he is manipulating will become almost indestructible? Are there any smarter ways on going about this?
I do not necessarily wish for the accompanying time-stopping and reflecting properties.
Edit: Excuse if it isn't clear. I am talking about the plausibility of the question within the limitations of the physical laws (obviousky excluding the electrokinesis part).
|
Matter is kept together by electromagnetic fields.
Diamonds are so though because of the electromagnetic fields resulting from the spatial arrangement and mutual interaction of all the carbon atoms and their electrons in the diamond crystal lattice.
But diamonds get broken at a certain point. So does any material, simply because any force can be overcome by a greater one.
The only thing which we know it can't be broken is black holes, but they are held together by gravity and they can't be broken because somehow there is a speed limit in the fundamental laws of our universe (nothing can travel faster than light).
The above if you want to stay within science. If you want to use magic, magic can do anything, even turning a toad into a charming prince.
|
stackexchange-worldbuilding
|
{
"answer_score": 3,
"question_score": 2,
"tags": "internal consistency, magic, science fiction"
}
|
Qual è il senso di "conto" in questo brano?
Nel romanzo _La malora_ , di Beppe Fenoglio, ho letto:
> I due maschi, uno è un po’ piú vecchio di me e l’altro un po’ piú giovane. Con loro ci facevo quattro parole a testa al giorno, ma nessuno dei due m’ha mai trattato con prepotenza, forse perché sapevano bene che bastava una tempesta un po’ arrabbiata e un piccolo **conto** nella testa di loro padre per spedirli tutt’e due a far la mia medesima fine lontano da casa.
Ho cercato il vocabolo "conto" in parecchi dizionari ma, ce ne sono tante accezioni, che non sono sicura di aver capito qual è l'adatta al contesto del testo. Quindi la domanda sarebbe: nel brano sopra citato, "conto" sta per "racconto"?
|
No, nel brano sopra citato, "conto" NON sta per "racconto" ma significa letteralmente "conto" nella piú comune accezione di sequenza di operazioni aritmetiche.
> _"[...] bastava una tempesta un po’ arrabbiata e un piccolo **conto** nella testa di loro padre per spedirli tutt’e due a far la mia medesima fine lontano da casa."_
Una _tempesta un po’ arrabbiata_ produce un buco nel bilancio dell'azienda agricola familiare e un piccolo _conto_ (letteralmente) potrebbe poi indicare al padre la opportunità di avere due bocche in meno da sfamare o, in altri termini, di mandare i due uomini a lavorare sotto padrone lontano dalla loro casa, così come successo alla voce narrante.
|
stackexchange-italian
|
{
"answer_score": 2,
"question_score": 1,
"tags": "word meaning"
}
|
Office 365 API / delegate and login
I have read a lot of articles about Office 365 API but I need additionnals informations. My goal (MVC Projet) is to collect some data (read only) of my tenant (and customers tenants) like licences subscription (like csp), user informations (like affected , affected licenses), ... I think to use Microsoft Graph .Net Library.
1. Is it possible to interact by the api with tenant of my client (I'm Office 365 Partners) by login in my tenant (as the delegate permission in the admin portal) ?
2. Is it possible to have only an application authentication without requierd an additionnal MS account to login to the api.
Thanks for help, Regards, Yannick
|
Using the CSP/partner model to call Microsoft Graph (and either have your app pre-consented for application permissions/auth OR for your Agents to log in using delegated admin privileges to your customer tenants) is NOT yet supported, but is coming soon.
Please take a look at < for what is supported (Directory features) in Microsoft Graph. This article was updated very recently.
Hope this helps,
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "c#, model view controller, microsoft graph api, office365api"
}
|
Allow space in .htaccess url redirect
I have redirected url with special characters to 400 error page using .htaccess which is working fine.
I am redirecting this way.
RewriteCond %{QUERY_STRING} [^\w+=&/.()-] [OR]
RewriteCond %{REQUEST_URI} [^\w+=&/.()-]
RewriteRule .? /site/error/400/? [L,B,R]
I want to allow spaces in query too, I am trying this way but its not working.
RewriteCond %{QUERY_STRING} [^\w\s+=&/.()-] [OR]
RewriteCond %{QUERY_STRING} [^\w+=&/.()-\s] [OR]
RewriteCond %{QUERY_STRING} [^\w+=&/.()\s-] [OR]
RewriteCond %{QUERY_STRING} [^\w\d\s+=&/.()-] [OR]
Please see and suggest any possible way to do this.
Thanks.
|
You can use `%20` for space:
RewriteCond %{QUERY_STRING} [^\w=+&/.%20()-] [OR]
RewriteCond %{REQUEST_URI} [^\w+=&/.()-]
RewriteRule ^ /site/error/400/? [L,B,R]
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "regex, apache, .htaccess, mod rewrite, redirect"
}
|
How to Validate if the input Text in ComboBox was on the list?
How to assure if the inputted text in the ComboBox was on the list?
|
You could use the `Leave` event which will check the value when focus is lost on the `ComboBox`
private void comboBox1_Leave(object sender, EventArgs e)
{
if (!comboBox1.Items.Contains(comboBox1.Text))
{
throw new EndOfWorldException();
}
}
or use the `TextUpdated` event to set the text color red if the item does not exist when the user enters the text
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
comboBox1.ForeColor = comboBox1.Items.Contains(comboBox1.Text)
? Color.Black : Color.Red;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c#, combobox"
}
|
I would like to rewrite an URL in php (.htaccess)
This question might be a duplicate, but I didn't find any answer that helped me. I would like to rewrite this url : into < And this url : into <
|
Try this .htaccess rules
redirectMatch 301 ^example.com/mobilier.php?is=24&s=tables$
redirectMatch 301 ^example.com/product.php?id=110&nom=table-de-nuit$
if you want to do this for a lot of urls, reconsider your way of doing things
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, html, url rewriting, get"
}
|
Error pages in .htaccess - find the requested page?
I use my .htaccess file to redirect visitors with errors to my custom error pages.
The server is an Apache with PHP 5.2 so I code in PHP.
I wish to know, on my PHP error pages, what page did the visitor request and gave an error?
|
$_SERVER['REQUEST_URI']
or
$_SERVER['REDIRECT_URL']
should give you the information.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, .htaccess"
}
|
When do we write "we are done"?
This may seem like a bit of a silly question, but I notice that in some proofs (a remarkable amount), the author writes: "We are done." after completing a proof. Is this the equivalent of writing one of those black boxes to separate the proof from the rest of the educational text?
|
We are done $\iff$ $\square$ $\iff$ QED
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 4,
"tags": "soft question, proof writing"
}
|
Optimizing SUM MDX
I have a large MDX query that has historically ran in 25 seconds; this has been fine. I have recently made the change outlined below, and the run time now exceeds 90 seconds.
I am worried that if I need to perform similar filters, this is only going to exacerbate the problem. Any recommendations on how to perform this sort of a filter more efficiently for MDX?
// My simple aggregation of all hours runs in 25 seconds
MEMBER [Measures].[Calc_TotalHours] AS
([Measures].[PostedHours] + [Measures].[UnpostedHours])
// The same aggregation that excludes a certain type of hours
MEMBER [Measures].[Calc_TotalHours] AS
SUM ( -{ [Activity].[ProjectCategoryName].&[Overtime] }
, ([Measures].[ActualHours] + [Measures].[TimeSheetHours_Unposted])
)
I am wondering if SUM is the wrong function to use here?
|
You are right, the Sum() function is heavy against big sets. Try to reuse pre-aggregated All member:
([Activity].[ProjectCategoryName].[All],[Measures].[ActualHours])
+ ([Activity].[ProjectCategoryName].[All],[Measures].[TimeSheetHours_Unposted])
- ([Activity].[ProjectCategoryName].&[Overtime],[Measures].[ActualHours])
- ([Activity].[ProjectCategoryName].&[Overtime],[Measures].[TimeSheetHours_Unposted])
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "optimization, mdx"
}
|
Boost.Regex expression build
I need to build an expression which matches generic `#include "file.h"` code line.
Is the following correct for that purpose?
([[:blank:]]*#include[[:blank:]]*")([[:print:]]*\.h)([[:print:]]*)
The expression should match for the followings:
#include "header.h" //first include
#include "header2.h" //second include
#include "header3.h"
I use boost regex library.
|
Boost Regex can use Perl, Or POSIX regular expression syntax : <
So you can check and test your regex here: <
Just set to preg (perl) if you are using the default behaviour of boost (See above).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c++, regex, boost"
}
|
Check if an object literal is an 'object'
Why does the `if statement` not work, `typeof` says obj is an object.
var obj = {};
console.log(typeof obj);
if(obj === 'object') { console.log('working');}
|
Try:
if (typeof obj === 'object')
or
if (typeof obj == 'object')
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "javascript"
}
|
How do I add horizontal margins to my WPF TabItems without cutting off the tab?
My TabItems before attempting to apply a left margin of 10 look like:
!alt text
After attempting to apply the left margin of 10 to the blue tab, the blue tab gets cut off like:
!alt text
How do I do this properly?
|
There are a few ways to go about this but easiest thing to do is to simply customize the TabItem.Header content like so:
<TabControl Margin="29,29,25,23" Name="tabControl1">
<TabItem Name="tabItem1">
<TabItem.Header>
<TextBlock Margin="20,0,20,0">tabItem1</TextBlock>
</TabItem.Header>
</TabItem>
<TabItem Name="tabItem2">
<TabItem.Header>
<TextBlock Margin="20,0,20,0">tabItem2</TextBlock>
</TabItem.Header>
</TabItem>
<TabItem Header="tabItem3" Name="tabItem3">
<Grid />
</TabItem>
</TabControl>
If you were planning on doing this for every tab, and you probably should, I'd consider using a style to apply these margins.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 5,
"tags": "wpf, wpf controls"
}
|
using CGRectIntersectsRect for updating score of my game
I am trying to update my score using `CGRectIntersectsRect` and I want to increment in my score every time two images collide with each other. But, my score does not show periodicity some times it increases by one unit but it increases randomly when two UIimages collide with higher speed. Here is my code:
-(void)Collision{
if (CGRectIntersectsRect(Ball.frame, Player.frame)) {
PlayerScoreNumber = PlayerScoreNumber + 1;
PlayerScore.text = [NSString stringWithFormat:@"%i", PlayerScoreNumber];
Y = arc4random() %5;
Y = 0-Y;
}
The two `UIImages` are 'ball' and 'racket' , I want to increment in my score every time the ball strikes the racket. Please help...
|
I suspect you are counting the same collision twice (or more) and so you are going to have to keep _state_ about the collision and remember when you've already seen the current collision:
Create a new instance variable in your implementation file, something like:
@interface MyClass ()
{
BOOL _ballCollidedWithPlayer;
}
and manage the state like this:
-(void)Collision{
BOOL collided = CGRectIntersectsRect(Ball.frame, Player.frame);
if (collided) {
if (_ballCollidedWithPlayer)
return; // Nothing to do; we already know about this collision
PlayerScoreNumber = PlayerScoreNumber + 1;
PlayerScore.text = [NSString stringWithFormat:@"%i", PlayerScoreNumber];
Y = arc4random() %5;
Y = 0-Y;
}
_ballCollidedWithPlayer = collided;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "ios, objective c, xcode, uiimage"
}
|
Randomly choose an instance from union in F#
In F#, given
`type MyType = A | B | C | D | E | F | G`
How do I randomly define an instance of MyType?
|
Select a random number, then pattern match that number with different branches returning a different instant?
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 6,
"tags": "f#, union"
}
|
Сайт не обновляется в браузере
Прошу помощи!Делал сайт в Studio Visual Code, всё проверял в брузере, через расширение openserver. Всё работало, дошёл до определённого этапа, как будто вёрстка зависла, меняю, что-то всё по прежнему в браузере видно.Я даже удалил файл со стилями.Всё равно блок который удалил отображается. Подскажите как можно исправить? Предполагаю произошло некое кэширование с которым я никогда до этого не сталкивался или что-то ещё.
|
Спасибо большое, проблема заключалась в том,что Sass не успевал обрабатывать и добавлять в CSS, видимо мой компьютер не тянет 10 SASS файлов с итоговыми CSS 500 строчек кода)))) Удалил файл SASS создал новый, потихоньку из старого файла скопировал код,нашёл баги в коде и всё заработало. А насчёт раскэширования, спасибо за комбинацию буду применять, когда снова заподозрю неладное.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "вёрстка, кэширование"
}
|
Why is intellisense in visual studio not showing method overloads any longer?
Does anyone know why my Visual Studio has suddenly stopped allowing me to select between different method overloads via intellisense? Instead it just seems to let me choose between a lot of different unrelated classes.
I can still select if I click the arrows though.
See example here: : Ectognatha
> Class: Insecta
(from Wikipedia)
Many people have the attitude "if something has to die for me to eat it, I don't want to eat it", so they say no to insects also.
However, since insects don't feel pain the same way other animals do, some people are perfectly fine with eating them.
It's really comes down to what you consider an animal to be, and whether your stance is not to eat animals or not to eat things that don't like being eaten. (i.e. plants don't know and therefore don't care about being eaten)
|
stackexchange-vegetarianism
|
{
"answer_score": 8,
"question_score": 6,
"tags": "lacto ovo vegetarianism, is it vegetarian, entomophagy"
}
|
About the definition of axiomatizable theory and consistency
> Definition: If $A$ is a theory and $B \subseteq A$ then $B$ is a set of axioms for $A$ iff 1) B is recursive and 2) $B \models C$ for all $C \in A$. We say $A$ is axiomatizable iff $A$ has a set of axioms.
How can any theory be axiomatizable with this definition? If both theories prove the same set of sentences then wouldn't those sentences belong in both theories and $B = A$?
> Definition: A theory $A$ is consistent iff it's not equal to the set of sentences in the Language of Arithmetic (with no free variables).
I thought that a consistent set is just one that doesn't have any contradictions. Does this definition relate to that? Thanks.
|
1) Note that a set of sentences is not the same as the set of sentences that can be derived from the given set oif sentences.
2) Once your theory contains _any_ contradiction, you can prove _anything_ ( _ex falso quodlibet_ \- with mild assumptions about the allowed rules of inference)
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "logic"
}
|
How have more people edited their profiles on main sites than on per-site metas?
Look here at Autobiographer on main OR Stack Exchange:
> Complete "About Me" section of user profile.
>
> Awarded 484 times.
Look at the meta site's equivalent of the badge:
> Awarded 166 times.
This same thing happens on other sites.
Looking at my other account that can't participate in the meta on one site, its bio on meta certainly exists. **How are there users who have edited their main but not meta profiles?**
|
A meta site profile is created only when the user visits meta.
So, it's not that they edited main but not meta -- it's just that they don't have a meta profile.
|
stackexchange-meta
|
{
"answer_score": 13,
"question_score": 5,
"tags": "support, badges, profile page, per site meta"
}
|
what's this python syntax dict(name=name)?
I've encounter this syntax in the srapy documentation.
>>> abc = ['a', 'b', 'c']
>>> dict(abc=abc)
{'abc': ['a', 'b', 'c']}
There doesn't seem to have this syntax mentioned in the python dict documentation. What is this syntax called?
|
This use keyword arguments.
It is roughly the same as:
def make_dict(**kwargs):
return kwargs
In your case,
abc = ['a', 'b', 'c']
dict(abc=abc)
means:
dict(abc=['a', 'b', 'c'])
which is the same as:
{'abc': ['a', 'b', 'c']}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "python, dictionary, syntax, parameter passing, keyword argument"
}
|
Stop focus event adding the stopPropagation method issue
I want to show only one alert when i focus on this textbar, i'm using the JS stop.Propagation() method to stop the event listener, this don't seems to work, i also want to avoid adding the html attribute "onFocus='' ". Thank you.
const textbar = document.querySelector('#search');
textbar.addEventListener('focus', (event) => {
alert("hi");
event.stopPropagation();
});
<input type="text" name="search" id="search" placeholder="Search Employee Details" class="form-control" />
|
You can try to use a boolean variable to achieve that. ~~Not sure it will work as you wish for the next focus (after you leave the input and focus it again).~~
const textbar = document.querySelector('#search');
let focused = false
textbar.addEventListener('focus', (event) => {
if(!focused) {
alert("hi");
focused=true
} else {
focused=false
}
});
<input type="text" name="search" id="search" placeholder="Search Employee Details" class="form-control" />
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript"
}
|
Path Combine of Url in Html
I built items with image the `src` of image combine with path than in server and image name that in db .I need to combine them but in the HTML .
This is my code
<asp:ListView ID="ul_LeftMenu" runat="server" ClientIDMode="Static">
<ItemTemplate >
<li class="li-LeftMenu">
<img src="<%=Path %><%# Eval("Image") %>" /><a href="../<%# Eval("Url") %>"><%#Eval("Name") %></a></li>
</ItemTemplate>
</asp:ListView>
`<%=Path %>` from server Side
`<%# Eval("Image") %>` from database
How to make some think like this
<img src=" Url.Combine(<%=Path %> ,<%# Eval("Image") %>)"/>
Server code
public string Path { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Path = "/Master/Images/";
}
|
<img src='<%# new Uri(new Uri(Path), Eval("Image")).AbsoluteUri %>' />
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, html, asp.net"
}
|
Parent child relation query in SOQL
I am trying to run this query:
SELECT Id, Account.Primary_Email__c, Email FROM Contact where Primary_Indicator__c = true AND LastActivityDate = Last_week AND Email != Account.Primary_Email__c LIMIT 200
I am getting the following error:
> Bind variables only allowed in Apex code
I would really appreciate if any one can explain why this query works in apex and cannot be run directly in SOQL editor.
|
The error thinks you are attempting to use a bind variable, from the docs...
> SOQL and SOSL statements in Apex can reference Apex code variables and expressions if they’re preceded by a colon (:). This use of a local code variable within a SOQL or SOSL statement is called a bind.
Which is allowed in apex but using another field as a value is not as Keith pointed out in his answer.
Instead what you can do is create a formula on the Contact object that compares the email to the account primary email then use that comparison field in your query.
There is an idea for this type of comparison in reports that is under consideration out on the idea exchange here, but it looks like it may be a few releases out yet.
|
stackexchange-salesforce
|
{
"answer_score": 1,
"question_score": 3,
"tags": "apex, soql"
}
|
Convert html entities to UTF-8, but keep existing UTF-8
I want to convert html entities to UTF-8, but `mb_convert_encoding` destroys already UTF-8 encoded characters. Whats the correct way?
$text = "äöü ä ö ü ß";
var_dump(mb_convert_encoding($text, 'UTF-8', 'HTML-ENTITIES'));
// string(24) "äöü ä ö ü ß"
|
`mb_convert_encoding()` isn't the correct function for what you're trying to achieve: you should really be using html_entity_decode() instead, because it will only convert the actual html entities to UTF-8, and won't affect the existing UTF-8 characters in the string.
$text = "äöü ä ö ü ß";
var_dump(html_entity_decode($text, ENT_COMPAT | ENT_HTML401, 'UTF-8'));
which gives
string(18) "äöü ä ö ü ß"
Demo
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "php, utf 8, html entities, mb convert encoding"
}
|
MATLAB- updating an edit text with the mouse
I built a GUI using GUIDE, it is pretty simple, it has two axes an edit text and a push button
I want that, when clicking the mouse over axes_1, I get the position and update the edit text with the X position.
In the opening function I put the following
set(handles.axes_1, 'ButtonDownFcn', @axes_1_ButtonDownFcn);
and in axes_1_ButtonDownFcn i put
pos=get(hObject,'CurrentPoint');
disp(['You clicked X:',num2str(pos(1)),', Y:',num2str(pos(2))])
handles.value= pos(1);
set(handles.edit1,'String',handles.value);
but is giving me the following error
Reference to non-existent field 'edit1'. Error in trytool>axes_1_ButtonDownFcn (line 198) set(handles.edit1,'String',handles.value);
Error while evaluating axes ButtonDownFcn
edit1 is the tag name of the edit text, is not a typo or anything like that, why is the function not recognizing the edit text?
Thank you so much!
|
I tried to build a GUI with your code, and it works well if you comment the code you added to the opening function:
%set(handles.axes_1, 'ButtonDownFcn', @axes_1_ButtonDownFcn);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "matlab, user interface, matlab guide"
}
|
XNA 4.0 free e-books
Does anybody know some XNA 4.0 papers. I'm interested in e-books and other documents/papers. Preferably free....
Non-common websites are also welcome :) (Not returned from google search)
|
Charles Petzold's new Windows Phone 7 book covers XNA on the phone, that might be useful.
Free download from his site here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c#, wpf, xna"
}
|
windows mobile Technologies
I want to do a sample application to send/receive SMS using mobile 5. Can any one give me suggestions for doing this or pls give any links for geting help is there any option to do it using MS Visual studio 2005
|
you can use sms.dll library to manipulate SMS in Windows mobile
Check the following link <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "c#"
}
|
Python ImportError: No module named
I try to run django project, which has this kind of structure: 2 apps in one project:
projectx
apps
app1
| | __init__.py
| | ...
app2
| __init__.py
| ...
project
settings.py
urls.py
__init__.py
| ...
manage.py
...
It has two apps in one project. Well, while running `python manage.py runserver` I get `ImportError: No module named apps`
`$ echo $PYTHONPATH` gives
/home/alexander/Work/projectx
Django version 1.9.8
INSTALLED_APPS = [
...
'apps.app1',
'apps.app2'
]
|
You should add `__init__.py` inside your `apps` directory
apps
__init__.py
app1
| | __init__.py
| | ...
app2
| __init__.py
| ...
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "python, django"
}
|
Tips on creating a C# WPF application to track my work hours
I'm trying to write a simple WPF application in C#. Coming from a primarily front-end web dev background, I'm sort of new to this, and I'd really like tips on where to start. :) I've searched the internet for resources, but haven't found anything yet which gives a more solid sense of direction in how I should approach the problem.
Basically, I'd like an application where I can click one button to "Check In" and save a timestamp, then another button to "Check Out" that saves another timestamp. I'd then like to be able to calculate how many total hours I've worked based on these timestamps.
Right now, I think the biggest problem I have is figuring out how/where to save the timestamp information. I've read stuff online on using a database, like SQLite, or something else called IsolatedStorage...
Any tips on how to tackle this would be super appreciated.
|
If you want to do it in WPF, which I don't think is necessary (You can achieve the same thing with WinForms if it doesn't need to look so nice), you can use one of these classes:
1. `DateTime`
2. `StopWatch`
As for the gui, well this is simple enough. Just add two buttons to the window.
Finally for storage, if you can store the data on your HD it will be simple to save it. Otherwise SQL is an option:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "c#, wpf"
}
|
Probability of obtaining a specific string, Bernoulli trials
In a book I found this:
$\omega=$ "$k$ ones followed by $n-k$ zeroes"
$A_i$ = success on trial $i$ = the set of all sequences with a one in the $i$th coordinate.
$P\\{\omega\\} = P(A_1 \cap A_2 \cap ...\cap A_k \cap A_{k+1}^c \cap ... \cap A_{n}^c) = P(A_1)P(A_2)...P(A_k)P(A_{k+1}^c)...P(A_n^c) = p^kq^{n-k}$
I don't understand this reasoning. Can someone please explain?
In particular, I dont get why the complements appear.
I assume it has something to do with independence of trials, but why include complements only for $k+1$ onwards?
Thanks.
|
It seems that your possible events are binary strings of length $n$, and you want to find the probability that you draw the string $\omega$, which is $k$ ones followed by $n-k$ zeroes.
You let $A_i$ be the event that you obtain a success in the $i$th trial, which means that the $i$th entry in the string is a $1$.
Notice that this means that the complement $A_i^c$ signifies that the $i$th entry in the string is a $0$, so since only the last $n-k$ entries are $0$, you want to use the complements for the last $n-k$ entries.
You are right about the independence, by the way.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "probability"
}
|
Can someone please explain this CMD batch file?
set SourceSCMPasswd=abc
set HATCONTESTING=yes
for /f %%a in ('dir /AD /b') do VssConverter.exe analyze %%a\settings.xml & move VSSAnalysisReport.xml %%a & move usermap.xml %%a
I know that it does the following commands: 1) Run VssConverter.exe analyze on %%a\settings.xml 2) Move VSSAnalysisReport.xml to %%a 3) Move usermap.xml to %%a
The problem is that when a folder in the directory has a space in its name, like AMEX Mailer for example, the variable %%a only contains AMEX but excludes the second part. How do I make it include the whole name?
|
The default token delimiter for FOR /F is `<tab>` and `<space>`. You want to preserve the entire string as a single token, so you want no delimiter ("DELIMS=") The default EOL option is `;`. Any line that begins with `;` will be ignored. Though unlikely, it is possible for a file name to begin with `;`. You want to set EOL to some character that cannot appear in a name. Good candidates are `:`, `*`, and `?`.
for /f "eol=: delims=" %%A in ...
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "batch file, cmd"
}
|
Python: BaseHTTPRequestHandler - Read raw post
How do I read the raw http post STRING. I've found several solutions for reading a parsed version of the post, however the project I'm working on submits a raw xml payload without a header. So I am trying to find a way to read the post data without it being parsed into a key => value array.
|
I think `self.rfile.read(self.headers.getheader('content-length'))` should return the raw data as a string. According to the docs directly inside the BaseHTTPRequestHandler class:
- rfile is a file object open for reading positioned at the
start of the optional input data part;
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 14,
"tags": "python, httpserver, basehttpserver, basehttprequesthandler"
}
|
Proof of inequalities using binomial theorem
!answer to inequality proof using binomial theorem
How do they achieve $$1+1+\frac{1}{2}\left(1-\frac{1}{n}\right)?$$ If I consider the first three terms of the binomial expansion, I get the first two terms, but can't factor the third to match this.
|
\begin{align} & \frac{n(n-1)}{2}\left(\frac1n\right)^2 \\\ =& \frac{n(n-1)}{2} \; \frac1{n^2} \\\ =& \frac12\;\frac{n-1}{n} \\\ =& \frac{1}{2}\left(1-\frac{1}{n}\right) \end{align}
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "inequality, proof explanation, binomial theorem"
}
|
Is there a difference between "eatable" and "edible"?
I thought only _edible_ was correct, even Google suggested _edible_ when I did a search to see which one was more popular on the internet:
* _Edible_ : 17.2 million
* _Eatable_ : 2.2 million
The first results are from dictionaries, the meaning being "that can be eaten".
What's the difference between them?
|
I think eatable is more often used to mean palatable.
eatable sample usage
Whereas edible is more often used in relation to plants etc that are not poisonous.
edible sample usage
But there is an overlap.
(I learnt the sample usage trick from Anthony Quinn)
|
stackexchange-english
|
{
"answer_score": 13,
"question_score": 13,
"tags": "differences, adjectives"
}
|
How can i show the Count of Contributions in a give time period?
I checked the awesome Summary Fields extension and the Advanced Fundraising Reports one but neither seem to quite offer this.
I could do this as a Drupal View but that won't give me the full suite of 'Actions' that might be required.
|
We did create additional Summary Fields to cover 1 Apr - Mar 31, and for July 1 - June 30. We then found out that by setting the Financial Year field in civicrm/admin/setting/date?reset=1 to the correct date had the desired outcome.
We therefore made a PR for the extension to improve the documentation to avoid this catching out others unaware.
|
stackexchange-civicrm
|
{
"answer_score": 0,
"question_score": 0,
"tags": "civicontribute"
}
|
Sign .mobileconfig on a PHP server
Could anyone please tell me how to use `openssl smime -sign -signer cert.pem -inkey key.pem -certfile ca-bundle.pem -nodetach -outform der -in profile-uns.mobileconfig -out profile-sig.mobileconfig` this within PHP (this one worked properly!)?
I tried
$path = __DIR__ . DIRECTORY_SEPARATOR; // my actual directory
$infilename = $path . 'profile.mobileconfig'; // my unsigned profile
$outfilename = $path . 'profile-sig.mobileconfig'; // my signed profile
$signcert = file_get_contents($path . 'cert.pem'); // my certificate to sign
$privkey = file_get_contents($path . 'key.pem'); // my private key of the certificate
$extracerts = $path . 'ca-bundle.pem'; // the cert chain of my CA
echo openssl_pkcs7_sign($infilename, $outfilename , $signcert, $privkey, array(), PKCS7_NOATTR,$extracerts);
without success. I also tried all of the PKCS7 attributes...
|
Calling `openssl smime` with `exec` works fine:
exec('openssl smime -sign -signer cert.pem -inkey key.pem -certfile ca-bundle.pem -nodetach -outform der -in profile.mobileconfig -out profile-sig.mobileconfig');
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "php, ios, openssl, sign, ios provisioning"
}
|
apt-get install is not working in WSL
Windows 10 Ubuntu bash failing to install packages. Whenever I try install new package with below command, getting same error.
root@VASI-HOME-PC:/mnt/c/Users/vadap# apt-get install atom
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package atom
This is not just with atom pacakge but i tried installing other packages like pip as well and received same error.
|
Executed below 2 commands and then I was able to install the packages.
sudo apt update
sudo apt install python3-pip
Source - <
|
stackexchange-superuser
|
{
"answer_score": 55,
"question_score": 34,
"tags": "ubuntu, bash, windows subsystem for linux, apt, ubuntu 18.04"
}
|
Show options on dropdown menu from a column - PHP MYSQL
I have a following code:
<?php
session_start();
include("control/connect.php");
$query = NULL;
$query= "select * from category";
$result = mysql_query($query);
?>
.....
<select name="categoryname" id="">
<option value="">Select</option>
<?php
while($row=mysql_fetch_array($result)) {
?>
<option value="<?php echo $row['categoryid']; ?>">
<?php echo $row['categoryname']; ?></option>
<?php } ?>
</select>
But then, here's the problem:
!enter image description here
An the other 3 options (The data has 3 rows in the table): !enter image description here
What's wrong and what should I do?
|
Simply ensure that you have typed `categoryname` correctly. It should be the same as you have column name in database. And it is case sensitive. So, if column is called categoryName, `$row['categoryname']` will throw a notice
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, mysql, drop down menu, indexing"
}
|
first row VS Next row VS rownum
Those 3 queries return the same result set but use 2 different technics. Is there an advantage using one over the other? The plan and the execution time are in the same cost range.
Select *
from user_tab_columns
order by data_length desc,table_name, column_name
fetch first 5 rows only
Select *
from user_tab_columns
order by data_length desc,table_name, column_name
fetch next 5 rows only
select *
from (
Select *
from user_tab_columns
order by data_length desc,table_name, column_name
)
where rownum <=5
|
The keywords `first` and `next` as used in the `fetch` clause are perfect substitutes for each other, they can be used interchangeably - this is stated clearly in the documentation. So you really only have two queries there, not three. (The first two are really identical.)
The first query is easier to write and maintain than the last query. On the other hand, it is only available in Oracle 12.1 and later versions; in Oracle 11.2 and earlier, the only option is your last query.
The `fetch` clause is more flexible, for example it allows you to specify `with ties` (to include more than 5 rows if rows with rownum 4, 5, 6 and 7 are tied on the `order by` criteria, for example).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "oracle"
}
|
How to find week number of 4 week rolling cycle by given date in Power Query M
I have a calendar table build with Power Query and I need to use this to add a column for a 4 week cycle I can track a weekly task.
example
Column A is all dates in sequence from 01/01/2019 up to 31/12/2022
Column B is the week sequence e.g.
01/01/2019 -> 07/01/2019 is 1
08/01/2019 -> 14/01/2019 is 2
04/10/2021 -> 10/10/2021 is 145
If I start from week 145 how would I work out the week number in a 4 week cycle given any date. So if
Week 145 is Task A
Week 146 is Task B
Week 147 is Task C
Week 148 is Task D
Week 149 is Task A and so on.
If I asked for the Task in the 4 week period for Week 158 I would get Task B as it is the second week in the repeating cycle.
|
I am not sure if I understood properly what you need. Do you need an additional column indicating the task of the week based on that cycle of 4?
If that is the case I think what you might be looking for is the mod function: <
Create a new column using mod and dividing by 4. Then create a if-column based on the result of the Mod-column. If 0 --> "Task A", 1 --> "Task B", etc.
Regards!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "date, math, powerbi, powerquery, m"
}
|
Install a Apache/MySQL/PHP web application locally
We have a web application that is based on Apache, MySQL and PHP. I want to make that available as a desktop application for windows also, installed via MSI. A small .NET application starts a modified xampp package that we deploy and then opens an embedded Chromium-based browser.
Questions:
* How do I ensure that I am able to modify the Apache/MySQL/PHP config on run time? The files are stored in Program Files, and UAC of course does not allow me to change them without "Run as administrator". Is there a way to make these files editable during setup? Otherwise I would have to figure out how to start Apache/MySQL with custom config files from a temp directory.
* How do I tell the installer to add Apache & MySQL to the firewall exception list, or how do I tell the firewall that applications that listen only locally are not a threat?
|
I realized I do not want a dirty hack here and tried to do it "right":
* I modified the configuration of Apache and MySQL so that everything that changes lies in %APPDATA%. The configuration files are passed as command line arguments.
* The current version of Advanced Installer allows Firewall rules to be set on installation.
Actually it wasn't that hard to change the config as I thought it would be and I learned some bits in the process...
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "windows, apache, installation, uac, windows firewall"
}
|
Concat multi-index data based on inner level
I have a multi-index dataframe of the form below():
key nm c0 c1 c2 c3
bar one -0.42 0.56 0.27 -1.08
two -0.67 0.11 -1.47 0.52
baz one 0.40 0.57 -1.71 -1.03
two -0.37 -1.15 -1.34 0.84
I want to concatenate the numbers in the df based on the inner level index i.e. **nm** separated by \n (assuming the numbers are represented as strings) and get rid of that level **nm** ;like this below:
key c0 c1 c2 c3
bar -0.42\n-0.67 0.56\n0.11 0.27\n-1.47 -1.08\n0.52
baz 0.40\n-0.37 0.57\n-1.15 -1.71\n-1.34 -1.03\n0.84
Please guide on how it can be achieved.
|
You can `groupby` on "key" and join with "\n". NB. You first need to cast your data as string:
df.astype(str).groupby(level=0).agg('\n'.join)
output:
c0 c1 c2 c3
key
bar -0.42\n-0.67 0.56\n0.11 0.27\n-1.47 -1.08\n0.52
baz 0.4\n-0.37 0.57\n-1.15 -1.71\n-1.34 -1.03\n0.84
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, pandas, dataframe, multi index"
}
|
How to have text between a top border line in flutter
How can I do something like this with flutter
|
You can use a row with expanded and a text between them
Row(
children: [
Expanded(
child : Container(
height: 2,
color: Colors.black
)
),
Text('some text here'),
Expanded(
child : Container(
height: 2,
color: Colors.black
)
),
]
)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, flutter, dart, mobile, cross platform"
}
|
How to count value by type and convert column to row
I have a table "tbTest1" like this:
q1 | q2 | q3 | type
---+----+----+-----------
3 | 2 | 2 | Student
2 | 2 | 3 | Student
3 | 1 | 1 | Alumni
1 | 1 | 3 | Student
1 | 3 | 2 | Alumni
Now I want to convert "tbTest1" into like this where how many 1's,2's or 3's had given by Student for 'q1', 'q2' & 'q3' :
q | 1 | 2 | 3
---+---+---+---
q1 | 1 | 1 | 1
q2 | 1 | 2 | 0
q3 | 0 | 1 | 2
|
You can use conditional aggregation:
select v.q,
sum(case when val = 1 then 1 else 0 end) as val_1,
sum(case when val = 2 then 1 else 0 end) as val_2,
sum(case when val = 3 then 1 else 0 end) as val_3
from tbTest t cross apply
(values ('q1', t.q1), ('q2', t.q2), ('q3', t.q3)) v(q, val)
where t.type = 'student'
group by v.q;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -2,
"tags": "sql, sql server"
}
|
Why Did Microsoft Create its Own SQL Extension (T-SQL)?
What are the reasons behind Microsoft implementing its own SQL extension as Transact SQL (T-SQL)? What are its advantages over the normal SQL?
|
Everybody extends SQL.
SQL isn't procedural, it's declarative. You describe what you want, and it figures out how to retrieve it using whatever indexes or hashes or whatnot is available.
But sometimes, that's not sufficient. T-SQL gives syntax to run procedural code inside of your queries. This lets you do control structures (begin-end, if-then-else), iteration and move values between local variables, temporary tables and other sources.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "sql server, tsql"
}
|
python xmpp wokkel JID escaping
After a painful search for Python XMPP library to use for XEP 060 I finally decided on wokkel and twisted.
However, they cannot understand the simple JID escaping of XEP-106
I am trying to pass username as an email address so I escape it like this admin\[email protected] where the username is [email protected]
The program complains about invalid character in username Should I try another library that does work? and has documentation. I would really appreciate the help.
|
This is just a guess, but if you have the username or JID in a string, and are specifying it like:
"admin\[email protected]"
If so, Python treats backslash escape codes specially. Change it to a double backslash to actually insert a single backslash into the string:
"admin\\[email protected]"
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python, xmpp, wokkel"
}
|
Unity .desktop Actions internationalization and localization?
How can we translate Desktop Action Names? Is it supported by quickly, launchpad?
|
You should be able to translate the Action's Name property just like you can elsewhere in the .desktop file. Usually this means using _Name with the untranslated string in yourapp.deskop.in, then using whatever tool it is that applies translations to .desktop files.
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 4,
"tags": "application development, quickly, launchpad, internationalization, localization"
}
|
Summation change of index and limits
My brain isn't working today (I thought this would be simple) but I can't figure out how to change from this summation equation
$ \sum _{n=1}^N a^n$
to this one
$ \sum _{j=1}^? [a^{2j-1} + a^{2j}] $
As an example, lets assume N=5. The first equation gives
$ \sum _{n=1}^5 a^n = a^1+a^2+a^3+a^4+a^5$
The second equation should give the same equation with odd-even pairs
$ \sum _{j=1}^? [a^{2j-1} + a^{2j}] = [a^1+a^2]+[a^3+a^4]+[a^5+0]$
I'm not sure what the upper limit on the summation of the second equation should be and how it is related to N? I feel like I need to introduce some kind of conditional coefficients in the second equation as well? The equation should hold for any value of N (odd or even) and NOT be cluttered with conditionals. I feel like there is a "text book" answer to this. Any thoughts?
|
Take it to the ceiling and floor it. $$\sum_{k=1}^n a_k = \sum_{k=1}^{\lceil n/2\rceil} a_{2k-1} + \sum_{k=1}^{\lfloor n/2\rfloor} a_{2k}$$
To test, this gives $$\sum_{k=1}^5 a_k = \sum_{k=1}^{3} a_{2k-1} + \sum_{k=1}^{2} a_{2k} = (a_1 + a_3 + a_5) + (a_2+a_3)$$
$$\sum_{k=1}^6 a_k = \sum_{k=1}^{3} a_{2k-1} + \sum_{k=1}^{3} a_{2k} = (a_1 + a_3 + a_5) + (a_2+a_3+a_6)$$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "sequences and series, discrete mathematics, summation"
}
|
how to run sites remotely on tfs server
How to run ASP.NET sites remotely on tfs server?
|
To clarify: you have created a custom ASP.Net website. You want to deploy this to a remote machine. If that is what you want, you can use MSDeploy for that purpose: <
Or do you want something else?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "tfs"
}
|
How to retrieve the text using protractor's getText API?
I am using protractor for my test framework and I need to get the value by using the getText method and store it in another value. I have problem in extracting the value from getText method. I do understand that I need to resolve the promise but it didn't work for me.
I have the page object like this. (Emp.js)
this.getID = async()=>{
await empID.getText();
}
and in the test.spec.js. This is how I have my test to retrieve the file.
var emp = new emp();
let empID = await emp.getID();
//When I do console.log(empID) it returns undefined. not sure why ?
|
Please try this:
this.getID = async() => {
return await empID.getText();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, protractor"
}
|
Protein PTM site prediction
Is there any in silico analysis method to predict post-translational modification sites on a given protein?
|
There are actually a lot of these sites available, I have used some of the one listed below. Additionally there are some huge list of other services available in this field from ExPASy, you can find it here and the Center for Biological Sequence Analysis, which can be found here.
* ExPASy - FindMod
* The Eukaryote Linear Motif resource for Functional Sites in Proteins
* Phosida
|
stackexchange-biology
|
{
"answer_score": 3,
"question_score": 2,
"tags": "bioinformatics, proteins"
}
|
What's wrong with my way of using filter_input?
I am told that I should use filter_input rather than accessing $_SERVER directly
So I made this simple 2 line of code
echo "filter:input " . filter_input(INPUT_SERVER,'REMOTE_ADDR');
echo "SERVER:" .$_SERVER['REMOTE_ADDR'] ;
Very simple. I expect they both produce the exact same thing.
This is what I got
filter:input SERVER:202.80.212.17
Clearly filter_input(INPUT_SERVER,'REMOTE_ADDR') produces empty string.
Why?
|
It has been a bug in older versions of php. You can either use
echo "filter:input " . filter_input(INPUT_ENV, 'REMOTE_ADDR', FILTER_VALIDATE_IP);
Or use
echo "filter:input " . filter_input($_SERVER['REMOTE_ADDR']);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php"
}
|
Best way for incremental load in ssis
I am getting 600,000 rows daily from my source and I need to dump them into the SQL Server destination, which would be an incremental load.
Now, as the destination table size is likely to be increase day by day which would be the best approach for the incremental load. I have few options in my mind:
1. Lookup Task
2. Merge Join
3. SCD
etc..
Please suggest me the best option which will perform well in incremental load.
|
Look at Andy Leonard's excellent Stairway to Integration Services series or Todd McDermid's videos on how to use the free SSIS Dimension Merge SCD component Both will address how to do it right far better than I could enumerate in this box.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "sql server 2008, ssis"
}
|
onclick= copyToClipboard: for php variable using JavaScript
So I use the following code in php to copy any div, but how can I edit the js code to copy a php variable in the page, like `$bookid` or `$row[1]` (or copy/echo two strings like `$bookid . $row[1]` with one click) etc.?
<button onclick="copyToClipboard('#div1')\">Copy</button>
js code:
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
|
The text that gets copied here, is the content of the dynamically created input field. Currently that gets set by reading the text content of `element` \- so that is the part that needs replacing.
function copyToClipboard(textToCopy) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val(textToCopy).select();
document.execCommand("copy");
$temp.remove();
}
<script src="
<button onclick="copyToClipboard('hello world')">Copy</button>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, php, variables, copy"
}
|
Finding the Eclipse Project file location
I have an android project running in Eclipse IDE. Lets say it is 'ABC Project'. Some of my collieges have made number of copies of this project, so the project files can be seen in desktop, C://, D:// and even in eclipse work space. Now I don't know project in which location I am running because they have deleted and imported the project folder to eclipse using this copies and they can't remember whether they selected the option 'make a copy to the workspace'.. How can I get this location? I tried to right click on the project and see any option is there but no. Manually finding it using java code (getAbsolutePath()) will return no good, it will return the path in the phone.
Please help.
|
Did you try right click on project ->Properties->Resources ? You will be able to see the Project path there.
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 8,
"tags": "java, android, eclipse, ide"
}
|
Wordpress title reverse
Currently using last version of wordpress. For now my titles like this:
Home page -> SiteName - Just another wp site
Books -> Books - SiteName
Contacts -> Contact - SiteName
The question is how to reverse title tag using function.php filter? I need: Books - SiteName to be changed to SiteName - Books
Thank you!
|
You can reverse it by using **document_title_parts** filter
add_filter('document_title_parts', 'reverse_title_on_page');
function reverse_title_on_page($title)
{
if (is_page() && !is_front_page()) { // check what you need
$title = array_reverse($title);
}
return $title;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "php, wordpress"
}
|
How to flatten exactly two dimensions of the nested list?
Suppose I have a list `a` built as follows:
a1<-list(1,2,list("X",10))
a2<-list("A",list("B"),"C")
a3<-list(list("D",list("E")),3.14)
a<-list(a1,a2,a3)
How can I transform `a` into this:
list(1,2,list("X",10),"A",list("B"),"C",list("D",list("E")),3.14)
I want a solution that works for arbitrary number of `a1, a2, a3... an`, not only for `a1, a2` and `a3` as in example above.
In Mathematica I would simply use `Flatten[a,1]`, but how does one do it in R?
|
Use `unlist` with `recursive=FALSE`:
dput(unlist(a,recursive=FALSE))
list(1, 2, list("X", 10), "A", list("B"), "C", list("D", list(
"E")), 3.14)
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "r, list, flatten"
}
|
How to find a root field of $x^4-2$
> Find the root field of $x^4-2$ first over $\mathbb Q$ then $\mathbb R$.
I am struggling to understand root fields and how to form them. I thought we took the root of a polynomial if it is reducible, and then if the root is irreducible among the field then we adjoin the two (field extension). However, I am not understanding the formation part.
For example, the root field of $a(x)=(x^2-3)(x^3-1)$ is $\mathbb Q(\sqrt{3},i)$ because $\pm \sqrt{3}, 1, \frac{1}{2}(-1\pm\sqrt{3}i)$ are the roots. How did they take the roots and find that field?
|
_Hint:_ The roots of $x^4-2$ in $\mathbb C$ are $\omega\sqrt[4]{2}$, where $\omega$ is a complex number such $\omega^4=1$.
Solution:
> The splitting field of $x^4-2$ is $\mathbb Q(\pm \sqrt[4]{2},\pm i \sqrt[4]{2})=\mathbb Q(\sqrt[4]{2},i)$.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "abstract algebra"
}
|
Google Pub/Sub + Cloud Run scalability
I have a python application writing pubsub msg into Bigquery. The python code use the google-cloud-bigquery library and the `TableData.insertAll()` method quota is 10,000 requests per second per table.Quotas documentation.
Cloud Run container auto scaling is set to 100 with 1000 requests per container.So technically, I should be able to reach 10 000 requests/sec right? With the BQ insert API being the biggest bottleneck.
I only have a few 100 requests per sec at the moment, with multiple service running at the same time.
CPU and RAM at 50%.
|
Now confirming your project structure, and a few details given in the comments; I would then review the Pub/Sub quotas and limits, especially the Quota and the Resource limits, both tables where you can check this information depending on the size and the Throughput quota units sections tells you how to calculate quota usage.
I would answer your question as a yes, you are able to reach 10,000 req/sec. And as in this question depending on the byte size you can have 10,000 row inserts unless the recommendation is 500.
The concurrency in Cloud Run can be modified in case you need to change it.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "google bigquery, google cloud pubsub, google cloud run"
}
|
How do I press "Up" if I do not have an "Up" button?
Hi all I'm using a Samsung Galaxy Ace S5830 and I wanted to test a "Snake (Game)" app.
When I launched the app, this is what I have:
!enter image description here
Samsung Galaxy Ace does not have an "Up" button, I was wondering what are the steps I'd have to take to simulate one?
|
GO keyboard also has an up button.
You'll just need to launch the editor.
|
stackexchange-android
|
{
"answer_score": 3,
"question_score": 4,
"tags": "keyboard"
}
|
Hadoop: How to unit test FileSystem
I want to run unit test but I need to have a org.apache.hadoop.fs.FileSystem instance. Are there any mock or any other solution for creating FileSystem?
|
Take a look at the `hadoop-test` jar
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-test</artifactId>
<version>0.20.205.0</version>
</dependency>
it has classes for setting up a `MiniDFSCluster` and `MiniMRCluster` so you can test without Hadoop
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 17,
"tags": "unit testing, hadoop"
}
|
TightVnc change theme when disconnected
Every now & then i use Tightvnc to connect to the desktop from the laptop(Windows 7) The desktop pic on the (Windows 10) PC goes black as normal but then it loses the theme settings & creates a new unsaved theme with just one desktop picture (the one that was on at the time) I then have to go & select the theme i was using & delete this newly created " **unsaved theme** ". i already tried to change the configuration->server->Hide desktop wallpaper, but no work. Any idea?
|
After last (features) updates in both PCs, Seems to be solved. specific after 2017-05 updates from Microsoft.!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "tightvnc"
}
|
pattern if fail 1 try 2 if fail try 3 for nodejs
hello im finding a pattern for a specific job;
lets say im finding a title in a page with DOM
if there is found title then put it to var title if var title is still empty then try the next function if var title is still empty then try the next function
is there a better way then
// Find Title
output.title = $('title').text();
if (null(output.title)) {
output.title = second try
};
if (null(output.title)) {
output.title = 3rd try
};
etc ?
|
My version makes it much more scalable and logical. Use an array and a while loop (Using the async module):
var functions = [function1, function2, function3]
var i = 0
var output.title // to deal with scope issue of output.title only being defined inside whilst. Could have put output.title as argument for callback
async.whilst(
function () { return i < functions.length && !output.title },
function (callback) {
output.title = functions[i]
i++
callback()
}, function () {
if (output.title) {
//have title
}
else {
// no title was found
}
})
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "node.js"
}
|
Java - possible lossy conversion from double to int
I am attempting to write a program that pick s a random value that the user inputs and I am getting the error - possible lossy conversion from double to int. Here is my code. Any help is appreciated.
public class Driver
{
public static void main(String [] args)throws IOException{
int random;
int options;
Scanner input = new Scanner(System.in);
int randy;
System.out.print("Please enter the number of options you would like to use: ");
String [] choices = new String [input.nextInt()];
int min = 1;
int max = choices.length;
random = (Math.random() * ((max - min) + 1)) + min;
for(int i = 0; i < choices.length; i++){
System.out.print("Enter option " + (i+1) + ": ");
choices[i] = input.next();
}
System.out.print("The random option chosen is: " + choices[random]);
}
}
|
The reason you are getting that error is because `Math.random()` returns a double. Therefore the line
(Math.random() * ((max - min) + 1)) + min;
would try to assign a double to `random` which is an `int`. The compiler does not like seeing this, so you won't get passed through it. There is a solution to this. You could cast it to an `int`, giving you
(int)((Math.random() * ((max - min) + 1)) + min);
This would just round the value down. Note that doing this will never get you the value of `max`, so you don't need to worry about an `IndexOutOfBoundsException`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "java, arrays, random"
}
|
Suggested edit rejection reason is not validated by the server
If I go to the suggested edits page, press reject on one of them, it shows up a dialog asking for the rejection reason. Then I run this in my browser's Javascript console
$("input").each(function(){$(this).removeAttr("disabled");});
It enables the reject button and I can press the reject button and it successfully rejects the edit without me actually having to give a rejection reason.
The rejection should be validated by the server so that a rejection reason is actually required in order to successfully reject a suggested edit.
|
!You seem to be using JavaScript to avoid clicking a button, are you sure that is what you want to do?
|
stackexchange-meta
|
{
"answer_score": 10,
"question_score": 15,
"tags": "bug, status completed, suggested edits"
}
|
Difference between two c++ programs
I have one C++ program with two versions, one version the feature is working but in other isn't. Is there a way to debug the difference between this two versions? Specifically, I'm using Linux and g++. Is there a way to use something like KCachegrind to view the difference Call graph? Or is something in gdb to view these function calls difference in a faster way?
Updating... The program is to big to view all the differences. Firstly i would like to know the path between function calls difference to after that i will have an option to do a diff command just in this functions.
|
Have you considered using gprof? Once you have it installed (I believe most majors distros have it by default) compile your code with the '-pg' option. When you run your executable, it will generate a gmon.out file that contains profiling information including a call graph.
Have a look at this tutorial to get a better idea of how it works.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "c++, debugging, gdb, valgrind, kcachegrind"
}
|
SharePoint app cross domain call using javascript - object doesn't support property or method ProxyWebRequestExecutorFactory
I'm creating an SharePoint app (add-in?). Now I'd like to get data from a list in my host web using CSOM/JavaScript:
var context = new SP.ClientContext(appWebUrl);
var factory = new SP.ProxyWebRequestExecutorFactory(appWebUrl);
context.set_webRequestExecutorFactory(factory);
var appContextSite = new SP.AppContextSite(context, hostUrl);
Problem is my SP object doesn't support the method ProxyWebRequestExecutorFactory (or so the debugger says)? SP.js is loaded and my client context object is initialized. Any ideas what is wrong?
My environment: SharePoint 2013 on-premise
|
dstarkowski got me on track, sp.requestexecutor.js had not been initialized properly. This worked out for me:
$(function () {
$.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
});
function execCrossDomainRequest() {
var context = new SP.ClientContext(appWebUrl);
var factory = new SP.ProxyWebRequestExecutorFactory(appWebUrl);
[...]
}
|
stackexchange-sharepoint
|
{
"answer_score": 2,
"question_score": 2,
"tags": "javascript, sharepoint addin, csom, cross domain"
}
|
"Member" won't recognize the members of a list
I'm experiencing a very curious problem. I have a list named "theorems" that has exactly one item. Here's proof:
[]> theorems
(((ROSES ARE RED) ^ (~ (ROSES ARE RED))))
[]> (car theorems)
((ROSES ARE RED) ^ (~ (ROSES ARE RED)))
Clearly ((ROSES ARE RED) ^ (~ (ROSES ARE RED))) is a member of the list "theorems." But when I test it for membership, it fails:
[]> (member '((ROSES ARE RED) ^ (~ (ROSES ARE RED))) theorems)
NIL
But if I call it explicitly, it works:
[]> (member (car theorems) theorems)
(((ROSES ARE RED) ^ (~ (ROSES ARE RED))))
Why is this happening, and how can I fix it?
|
Common Lisp uses `EQL` as the default test function. `EQL` checks whether the items are the same identical items. You want to test whether the items have the same structure. So you need to use `EQUAL` or `EQUALP`.
CL-USER 11 > (setf theorems '(((ROSES ARE RED) ^ (~ (ROSES ARE RED)))))
(((ROSES ARE RED) ^ (~ (ROSES ARE RED))))
CL-USER 12 > (member '((ROSES ARE RED) ^ (~ (ROSES ARE RED))) theorems)
NIL
Tell `MEMBER` to use `EQUAL`:
CL-USER 13 > (member '((ROSES ARE RED) ^ (~ (ROSES ARE RED)))
theorems
:test 'equal)
(((ROSES ARE RED) ^ (~ (ROSES ARE RED))))
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "lisp, common lisp, clisp"
}
|
Regex (Notepad++) to search and replace content
I'm not too familiar with the Notepad++ regex option for search and replace, and in need for a little help.
Parsing from one sql syntax to another, I would like to do the following. For all lines with the "pattern" `ADD FOREIGN KEY "**********" ("**")`, I would like to insert som text at section 3 (where the whitespace is)
From
( 1 )( 2 )(3)(4)
ADD FOREIGN KEY "FK_MY_ACCOUNT_PROJECT" ("id")
to
ADD FOREIGN KEY "FK_MY_ACCOUNT_PROJECT" [new text] ("id")
|
Try this find and replace in regex mode:
**Find:**
(ADD FOREIGN KEY "[^"]+" )(\("[^"]+"\))
**Replace:**
$1[new text] $2
Here is a demo showing that the two groups in fact are getting matched correctly.
## Demo
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "regex, replace, notepad++"
}
|
Mysql Join multiple Table error: not unique table/alias
Joins have always been touchy for me. I am trying to grab multiple columns from multiple tables. My left join for `product p num` table causes error: `Error Code: 1066. Not unique table/alias: 'product p num'`
I've seen this error show up for other stackoverflow examples. I tried modifying various versions but not sure what piece I am missing.
SELECT tbls.SNum,tblmar.AssemPart, tblmar.wifi, `product p num`.`Customer Name`
FROM floor.tbls, manu.tblmar, def.`product p num`
LEFT JOIN tblmar ON tbls.PartNum = tblmar.AssemPart
LEFT JOIN `product p num` on tblmar.AssemPart = `product p num`.`product p`
WHERE tblmar.AssemPart IS NOT NULL
AND `product p num`.`Customer Name` = 'Google'
AND tblmar.wifi = 1
ORDER BY `product p num`.`product p`;
|
The problem is because you're joining the same tables multiple times without aliasing any of them. Did you mean to join them twice? I can't see why you would have intentionally done that here.
The logic you want is likely this:
SELECT
tbls.SNum
, tblmar.AssemPart
, tblmar.wifi
, `product p num`.`Customer Name`
FROM
floor.tbls
LEFT JOIN tblmar
ON tbls.PartNum = tblmar.AssemPart
LEFT JOIN `product p num`
on tblmar.AssemPart = `product p num`.`product p`
WHERE
tblmar.AssemPart IS NOT NULL
AND `product p num`.`Customer Name` = 'Google'
AND tblmar.wifi = 1
ORDER BY
`product p num`.`product p`;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, left join"
}
|
How to pops last list?
How to pops last list in list 2d Because I try **A[].pops** it's not working.
Before I pops:
*A[[1],[2],[3]]*
After I pops:
*A[[1],[2]]*
|
Just use normal `pop`
A = [[1],[2],[3]]
A.pop()
print(A)
[[1], [2]]
A = [[1],[2],[3]]
A[-1].pop()
print(A)
[[1], [2], []]
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "python, list"
}
|
Cannot hide UIDatePicker
For my app, I've attempted to make a UIDatePicker appear when the textfield called time is clicked.
In my viewDidLoad, I initialize it like this:
- (void)viewDidLoad {
time.delegate = self;
[time setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
datepicker = [[UIDatePicker alloc] init];
datepicker.datePickerMode = UIDatePickerModeCountDownTimer;
dateformatter= [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"HH:mm:ss"];
}
Then, in the textFieldShouldBeginEditing method, I have this:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if (textField == time){
button.hidden = NO;
datepicker.hidden = NO;
}
return NO;
}
However, my UIDatePicker still stays hidden, and I am sure the outlets are connected
|
remove this line from your code and check ,if your picker is placed in Xib.
datepicker = [[UIDatePicker alloc] init];
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "ios, objective c, uidatepicker"
}
|
Vuetify v-btn — wrap text
With Vuetify v-btns, how can I wrap text that overflows? I've tried:
.button {
white-space: normal;
display: inline-block;
word-wrap: break-word;
}
which didn't work. The text is just centred and overflows both sides.
Someone here asked about it and the answer was "it's important to note that the Material Design spec is against this", but how can this be achieved if we disregard the proper Material Design spec? My use case sometimes requires long strings of text on buttons (an educational app with sentences on buttons for a user to select). So, these are sometimes long and require text-wrapping.
|
After speaking with a Vuetify core team member on discord, it turns out it's just not possible with `v-btn`.
However, he informed me that I can use `v-ripple` on other components, standard buttons included. Combine that with css `:hover`, and it's easy to recreate a material design button that allows word-wrap, e.g:
<button v-ripple style="background-color: #ffbe0b;" class="materialDesignButton pl-6 pr-6 pa-4 ma-2">Привет</button>
.materialDesignButton {
color:#fff;
border-radius:5px;
font-family: Avenir, Helvetica, Arial, sans-serif;
font-size:1.04em;
letter-spacing: 0.05em;
width: auto;
transition: 0.3s;
}
.materialDesignButton:hover {
opacity: 0.7;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "css, vuetify.js"
}
|
Hide Safari's default elements like headerbar and status bar in iphone devices without scrolling the page
I'm working on a web application where the layout has three sections like Header, Middle Section and Footer. The Layout height is fix as per device screen and scroll will be in middle section only if the content will have more height than middle section's height. So I've applied this **meta tags** for hiding safari's default elements:
* `<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">`
* `<meta name="apple-mobile-web-app-title" content="BestForming">`
* `<meta name="apple-mobile-web-app-capable" content="yes">`
* `<meta name="apple-mobile-web-app-status-bar-style" content="black">`
But after applying this and when I'm checking in real device I can't find any change in layout it's still display the default elements.
Thanks In Advance...
|
These metatags are for progressive web apps. You can see the change of these tags only when you do the following steps,
1. Click options and select, 'Add to Homescreen'.
2. Provide a name and save.
3. Exit the browser
4. Click the new icon which is now available in the menu
Now you can see your web app in home screen without the address bar.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 5,
"tags": "html, ios, css"
}
|
Ubuntu wifi doesnt work
I can't use my wifi as when I click enable wifi it stays disabled.
Here's all the info you might need to help me <
|
You have a module that should not be there
echo "blacklist acer_wmi" | sudo tee -a /etc/modprobe.d/blacklist.conf
Reboot and check `rfkill list all` if it still shows the soft block then `rfkill unblock all`
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 0,
"tags": "networking, wireless"
}
|
Unable to match date with datetime
I wanted to convert a date from git log but I'm trying to match the date from the documentation of datetime but it never matches.
from datetime import datetime
receivedDate = (commits[0]['Date']) #receiving date
print(receivedDate) #e.g Thu Jan 14 12:47:30 2016 +0100
receivedDate = ' '.join(receivedDate.split(' ')[:-1]) #removing +0100
date = datetime.strptime(receivedDate,'%a %b %d %H:%M:%S %Y')
> ValueError: time data 'Thu Jan 14 12:47:30 2016' does not match format '%a %b %d %H:%M:%S %Y'
I've also tried by keeping '+0100' and added %z, but it doesn't work either. It runs with python 3.6.
* * *
Thanks for help or any idea :)
|
You can use python-dateutil where you don't need to provide a format string.
from dateutil import parser
print(parser.parse('Thu Jan 14 12:47:30 2016'))
#2016-01-14 12:47:30
Also I am able to use your datetime format as well.
import datetime
print(datetime.datetime.strptime('Thu Jan 14 12:47:30 2016', '%a %b %d %H:%M:%S %Y'))
#2016-01-14 12:47:30
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python"
}
|
Lotus Notes/Domino Designer 8 - Disable shared action refresh
I am working in Lotus Notes 8 using the Domino Designer to update a shared action under:
Shared Code >> Actions
Every night when the database refreshes my changes are being wiped out. Other files have a do not refresh option in them but, the actions do not. Does anyone know how I can update the file to not be over-written (without updating the database file name to a non-existing one and leaving the nightly refresh on)?
|
You can select the design properties of the entire list of Shared Actions and turn off design refresh/replace, but it doesn't appear you can control this on an individual action
I clicked Shared Code > Actions > and then right-clicked on "Shared Actions" in the designer, and clicked Design Properties. There I saw the "Do not allow design refresh/replace to modify"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "lotus notes, lotus domino"
}
|
Temperature limit of the increase in heat
If the sun is the hottest known thing to humans is it possible to have a temperature greater than the sun?.
|
The sun isn't the hottest known thing. We can make hotter temperatures than even the center of the sun in the lab. It's just a matter of putting a lot of energy into a small space.
You might be getting confused with the physical law that you cannot concentrate heat from a black body to a higher temperature than the source. So you cannot focus sunlight onto a spot and get a higher temperature than the surface of the sun - since otherwise the heat would flow from your hotspot back to the sun and heat it!
edit: the lab record is something like a few million-million degrees, a million times hotter than even the center of the sun (15 Million deg). Although at this point the definition of temperature gets a bit tricky.
|
stackexchange-physics
|
{
"answer_score": 4,
"question_score": -3,
"tags": "experimental physics, temperature"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.