INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Simple (?) augmented reality app for iPhone
I need to develop an iOS app that implements this simple (I hope) functionality: fire up camera mode, let the user (who's standing in a well known point in a room) point a marker in a room, then adding some AR info localized within the room.
For instance, I stand at the entry door of my lab, I point a marker on the opposite wall (in order to fine calibrate my iPhone's position), I start moving the phone to point different zones of the room and AR info panels appear showing where tools in the lab are (of course i'm assuming I already have some location based inventory data of the tools in the room).
I'm totally new to AR so I'd just need some (not completely general) startup tips... | ARKit is the one you have to refer. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "iphone, augmented reality"
} |
Antonym of hagiography
Is there a one word antonym of "hagiography"? A word which means "a piece of writing that paints a biography in the most negative light possible"? | > hatchet job
is a written attack, often but not exclusively ad hominem, that emphasizes the poor quality of the object of the attack.
> obloquy
is a fancy word for the same.
> calumny
is the same with the expectation of falsehood. They all have the same notion of strong bias by the author that hagiography does. | stackexchange-english | {
"answer_score": 4,
"question_score": 1,
"tags": "single word requests, antonyms"
} |
MongoDB _id beyond 9999999
I have a collection with more then 10M documents. I am trying to get the biggest _id form that Mongo collection with PHP
$cursor = $collection->find(array())->sort(array('_id'=>-1))->limit(1);
foreach ($cursor as $doc)
{
echo $doc['_id'];
}
I am getting 9999999 as the answer every time.
This also doesn't work
$cursor = $collection->find(array('_id'=>array('$gte'=>'5000000')))->sort(array('_id'=>-1))->limit(1);
I also tried with the Aggregate
$query = array(
array('$match'=>array('_id'=>array('$gte'=>'5000000'))),
array('$group'=>array('_id'=>'','max_id'=>array('$max'=>'$_id'))),
);
$res = $collection->aggregate($query);
print_r($res);
Same 9999999 pops up but this time it takes 6-7 seconds to compute.
It seems to me that there is a limit in MongoDB which prevents me from doing beyond 9999999 | You don't directly show it, but it appears that your `_id` values are numeric strings, not numbers. Strings sort alphabetically, so `'9999999'` (and even `'9'`) would come before `'10000000'` in your descending sort.
Your best option is probably to update your docs to use a numeric data type for `_id` and then they will sort as you're expecting. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "mongodb"
} |
How to print first or second word in a string with awk?
So I have a string which consists of two words, where I want to print the two words separately in awk (actually gawk).The string may look like this,
str="ab cd"
So I have searched the web and all I come up with is examples how to parse this from a file. However, this does not work in my case. It would be quite easy to do in perl; Something like this,
my $str="ab cd";
$str =~/(.+)\s(.+)/;
print "$1 and $2\n";
However, awk does not have this grouping. The problem is that I need to preserve the input, so `split()`, `sub()`, ... will not help. It would probaby work with `match()`, but this is not so pretty.
Anyone that sits with a better idea?
Sample input: str="ab cd"
Sample output: "ab and cd"
Note that the "and" is not a part of the matching, but it should be possible to print that string.
BR Patrik | idk what you mean by any of `However, awk does not have this grouping. The problem is that I need to preserve the input, so split(), sub(), ... will not help. It would probaby work with match(), but this is not so pretty.`
The gawk equivalent of the perl code in your question:
my $str="ab cd";
$str =~/(.+)\s(.+)/;
print "$1 and $2\n";
line for line, would be:
str="ab cd"
match(str,/(.+)\s(.+)/,a)
print a[1], "and", a[2]
e.g.:
awk 'BEGIN {
str="ab cd"
match(str,/(.+)\s(.+)/,a)
print a[1], "and", a[2]
}'
ab and cd
I don't know if that's the best way to do whatever it is you're really trying to do though since I don't know what it is you're really trying to do! | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "awk"
} |
First INSERT, then - if OK - DELETE
This SQL SERVER 2005 statement first deletes 18 record ordering them by `FIELD1 ASC`, then inserts the same 18 records in a clone table:
WITH q AS
(
SELECT TOP 18 *
FROM pippo
ORDER BY FIELD1 ASC /* You may want to add ORDER BY here */
)
DELETE
FROM q
OUTPUT DELETED.* INTO TableNew
Please help me to convert the previous statement in order to first `INSERT`, and `THEN` \- `IF INSERT` HAS BEEN OK - delete the same 18 records; I've just tried but the following code gives the error,
`Msg 102, Level 15, State 1, Line 7 Incorrect syntax near 'INSERTED'.`
WITH q AS
(
SELECT TOP 18 *
FROM pippo
ORDER BY ID_OL ASC /* You may want to add ORDER BY here */
)
insert into tablenew select * from q OUTPUT INSERTED.* INTO TABLENEW
Thank you in advance for your kind help. | declare @some_temp_table table (ID_OL int)
WITH q AS
(
SELECT TOP 18 *
FROM pippo
ORDER BY ID_OL ASC /* You may want to add ORDER BY here */
)
insert into minnie
OUTPUT INSERTED.ID_OL INTO @some_temp_table
select * from q
delete from pippo where ID_OL in (select ID_OL from @some_temp_table)
another version
set xact_abort on
declare @filter table (ID_OL int primary key)
insert into @filter (ID_OL)
SELECT TOP 18 ID_OL
FROM pippo
ORDER BY ID_OL ASC
begin transaction
insert into minnie
select * from pippo where ID_OL in (select ID_OL from @filter)
delete from pippo where ID_OL in (select ID_OL from @filter)
commit transaction | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "sql, sql server 2005"
} |
linear-algebra- basis of $M_{22}$ subspace
$S$ is a two rows and two column matrix where $a_{11} =a, a_{12} = b, a_{21} = c, a_{22} = d$ which is an element of $M_{22}$
I am given $a=b$ and $b+2c=0$
How do I prove that $S$ is a subspace of $M_{22}$, when there is no value of $d$? | $S = \left\\{\begin{pmatrix} -2c & -2c\\\ c & d \end{pmatrix}:c,d \in \mathbb{R}\right\\}$. We have:
$\begin{pmatrix} -2x & -2x \\\ x & y \end{pmatrix} + \begin{pmatrix} -2u & -2u \\\ u & v \end{pmatrix} = \begin{pmatrix} -2(x+u) & -2(x+u) \\\ x+u & y+ v \end{pmatrix} \in S$,
and
$r\begin{pmatrix} -2x & -2x \\\ x & y \end{pmatrix} = \begin{pmatrix} -2rx & -2rx \\\ rx & ry \end{pmatrix} \in S$.
Thus $S$ is a subspace of $M_2(\mathbb{R})$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra"
} |
How to speed-up the time waiting for my unicorn to finish its race?
In "Secret of the Magic Crystals", I try to earn some money by signing my unicorn in races. My problem is I have to wait for 35 seconds for each race, and there is no interactivity during this event. Is there a way to speed things up?
! | Several horses can run at the same time. Plus, you can train a horse while another races. Unfortunately, it is impossible to speed-up the time and would be considered a design flaw. | stackexchange-gaming | {
"answer_score": 0,
"question_score": 1,
"tags": "secret of the magic crystals"
} |
Is there a way to find hotels along a subway/metro line?
Is there a way (app or website) to find hotels along a subway or metro line if I don't really care about which station?
For example, if I need to get to Heathrow airport in London, I would like to find a cheap hotel somewhere along the Piccadilly or Elizabeth lines but without searching station by station. Is there a way? | I tried a Google search using
* london hotels near a metro station
and got many surprisingly useful _looking_ hits.
Too many to list - here are a few that looked highly apposite.
The search itself here
Hotels near the metro.com ! here
You can select within 250 or 500 metres, and choose one of 12 lines, or all lines at once.
Hotels near London underground \- Trip advisor.
Each listing shows distance to underground.
Optional map - hover over hotel listing and it shows location on map. | stackexchange-travel | {
"answer_score": 6,
"question_score": 11,
"tags": "trains, public transport, hotels"
} |
How to use chrono::microseconds with Pybind11?
The error boils down to this snippet.
#include <chrono>
#include <pybind11/chrono.h>
#include <pybind11/pybind11.h>
namespace chr = std::chrono;
namespace py = pybind11;
struct Time {
chr::microseconds elapsed;
Time(const chr::microseconds& elapsed) : elapsed(elapsed) {}
};
PYBIND11_MODULE(CppModule, m) {
py::class_<Time>(m, "Time")
.def(py::init<const chr::microseconds&>())
.def("elapsed", &Time::elapsed);
}
When I try to build it, I get the following error.
'pybind11::cpp_function::cpp_function': no overloaded function takes 4 arguments
What should I do to read `Time::elapsed` on the Python side? | Method `def` binds functions. Methods `def_readwrite` and `def_readonly` bind fields.
`Time::elapsed` is a field. That's why `def` cannot be used.
PYBIND11_MODULE(CppModule, m) {
py::class_<Time>(m, "Time")
.def(py::init<const chr::microseconds&>())
.def_readwrite("elapsed", &Time::elapsed);
}
Note that on Python side type `chr::microseconds` is converted to `datetime.timedelta`. To get the total number of microseconds divide it by 1 microsecond.
import CppModule as m
import datetime
t = m.Time(datetime.timedelta(minutes=10, seconds=5))
print(t.elapsed)
print(t.elapsed // datetime.timedelta(microseconds=1))
Output.
0:10:05
605000000 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c++, python 3.x, c++ chrono, pybind11"
} |
If X has a dense subset, does that imply that X is closed?
Assume X has a dense subset Y. Then every point in X is a limit point in Y, and so the union of Y and it's closure contains X. Therefore X must be closed. Is this correct? | No, it is not correct. The interval $]0,1[$ has a dense subset, for instance $]0,1[ \cap \mathbb{Q}$, but is not closed. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "real analysis"
} |
How should text wrap in a code block?
I am working on an application where code will be shown on a mobile device. This gives us a constrained width as horizontal scrolling isn't a desired choice for code with long lines. So we have to force the text to wrap in the code block. We have two options:
**Break word** \- where only whole words break. This has the advantage of easily seeing whole words, but has situations (as shown here) where it is visually less than ideal.
!break word example
**Break all** \- where it breaks in any point regardless of whether this is in the middle of a word or not. This tends to look better (subjective), but it could be problematic with longer words (as shown here)
!break all example
Which option is better for **programmers** , and why? | As a programmer, I prefer the line breaking to happen at the boundaries of words (assuming your assessment that line breaking is needed is correct).
However, I would change the way you break. Instead of continuing at column 0, I think you should continue at the same column as the line you are breaking, and you should indicate somehow that it is not a real line on its own, but a continuation of a previous line very clearly. Just the line numbers don't quite cut it, I think. Something like:
!mockup
download bmml source - Wireframes created with Balsamiq Mockups
A remaining problem is that a symbol like a space is going to be very hard to spot at a line break. I think that needs thought, because such a symbol may be very relevant in code. Perhaps if a space was used as a position to break at, it should get some special symbol as well so it stays visible at either the end or the beginning of the line. | stackexchange-ux | {
"answer_score": 0,
"question_score": 0,
"tags": "layout, code, text editor, programming, wrapping"
} |
Expand yasnippet only when it's at beginning of the line
How to write snippet condition to expand it only when it's positioned at the beginning of the line? | Say your snippet has the key `mysnippet_`, you can use the following condition:
# condition: (looking-back "^mysnippet_" nil)
Speaking of use cases, it could make sense to have snippets for inserting org-mode headers only available when the cursor is in the first line and column:
# condition: (and (looking-back "^mysnippet_" nil) (eq 1 (line-number-at-pos)))
**Comment**
I first proposed to use `(eq 0 (current-column))`, but that's of course nonsense because the cursor is after the snippet key. | stackexchange-emacs | {
"answer_score": 5,
"question_score": 6,
"tags": "yasnippet"
} |
How do I sqlmock an empty set using golang go-sqlmock
I want to test some SQL like:
select name from user where uid = ?
This is ok, I can mock it like this way:
rows := sqlmock.NewRows([]string{“name"}).AddRow(“info")
did = "1234"
mock.ExpectPrepare(“select name from user where uid = ?").ExpectQuery().
WithArgs(uid).
WillReturnRows(rows)
But I want to mock the testing in which the user table does not have this uid — the select will return a Empty set
mysql> select * from user where uid = “887";
Empty set (0.00 sec)
mysql>
How can I mock an empty table? | rows := sqlmock.NewRows([]string{“name"})
not addRow | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 4,
"tags": "mysql"
} |
1 question in Theorem 10 of section Spectral Theory of Hoffman Kunze
I am self studying Linear Algebra from Textbook Hoffman and Kunze and I have a question in Theorem 10 of Chapter 9 .
Adding it's image:
![enter image description here](
> How it's clear that for every $\alpha$ in $E_{j}V $ f(T) $\alpha$ = f($c_{j} $) $\alpha$ ? Can anyone please tell reasoning behind it. | If $\alpha\in E_jV$, then $\alpha=E_jv$ for some vector $v$. Therefore $$ f(T)\alpha=\sum_if(c_i)E_iE_jv=f(c_j)E_j^2v=f(c_j)\alpha. $$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra, inner products, spectral theory"
} |
Web Services development using C# .NET - Compatibility Check
I would like to get some information on list of points that needs to be taken care of while developing Web Services on .NET platform using WCF to make sure it is compatible with majority of the clients out there (Java, .NET etc...).
Earlier I have seen cases where we developed services which was easily consumed by .NET clients , however the moment we tested the service with other platforms, service broke.
I have few points with me as mentioned below:
1. Always use POCO data types
2. Stick to BasicHttpBinding unless WSHttpBinding is required
My main concern is about the Data Contract objects that are serialized and sent over the wire.
Thanks in advance. | My suggestion would be to use WS-I Compliance Test once you build you service.
Check: <
WS-I stands for Web Services Interoperability, if your services pass almost all the tests you can be 100% sure that they work with various clients. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "c#, .net, wcf, web services"
} |
How to hide form on submit button in shiny?
I have created one absolutepanel in shiny. I have created on submit button and selectInput pane.
selectInput("Customer", "Customer",groupcustomer),
submitButton("Submit",icon("refresh"))
Above code is in div tag. I want to collapse i.e. hide particular div or hide form on submitButton. How can I do this? | The following will toggle hiding of the input form when the submit button is pushed:
library(shiny)
library(shinyjs)
ui <- basicPage(
useShinyjs(),
tags$div(id="hideme",
selectInput("Customer", "Customer", c("bill","bob","bozo"))
),
actionButton("doSubmit", "Submit", icon("refresh"),
style="color: #fff; background-color: #337ab7; border-color: #2e6da4")
)
server <- function(input, output) {
observeEvent(input$doSubmit, {
toggle("hideme")
})
}
shinyApp(ui, server)
It replaces the submitButton with an actionButton as recommended in the help page and duplicates the style of submitButton.
> The use of submitButton is generally discouraged in favor of the more versatile actionButton (see details below). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "r, shiny, leaflet"
} |
Is it possible to access freeform programatically?
I'd like to be able create/read boards in the new app freeform which is included with iPadOS and iOS 16.2 for collaboration.
Is this API provided by Apple or a third party tool? | The Freeform app does not provide an AppleScript dictionary, nor any Siri Shortcuts.
Therefore the only programatic control is through UI scripting:
* Automating the User Interface - Mac Automation Scripting Guide
For example, to create a new board from the command-line using applescript UI scripting:
osascript -e 'tell application "Freeform" to activate' \
-e 'tell application "System Events" to tell process "Freeform" to click menu item "New Board" of menu 1 of menu bar item "File" of menu bar 1' | stackexchange-apple | {
"answer_score": 2,
"question_score": 3,
"tags": "ios"
} |
retrofit 2.3.0 how to handle nested json?
I am kinda of new to retrofit and i am not sure how to handle a nested json structure like this. if any one can help how to parse this type of structure . i would really i appreciate it . i have been stuck for days
{
"status": "ok",
"totalResults": 20,
"articles": [
{
"source": {
"id": null,
"name": "Bradenton.com"
},
"author": "By EILEEN NG Associated Press",
"title": "Malaysia says search for missing plane to end in June",
"description": "An official says the search for Malaysia Airlines Flight 370 by a U.S. company will likely end in June, as families of passengers marked the fourth anniversary of the plane's disappearance with hope that the world's biggest aviation mystery will be solved.",
"url": "
"urlToImage": "
"publishedAt": "2018-03-03T09:42:00Z"
}
]
} | the < to convert your json to POJO and use that for retrofit 2.3 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java, android, retrofit"
} |
Lebesgue Measure on (a,b) and (a,b]
For an exercise I want to show that $\lambda((a,b))=\lambda((a,b])$ where I write $(a,b) = (a_1,b_1)\times(a_2,b_2)\times\dots\times(a_d,b_d)$ and $\lambda$ is the Lebesgue measure on $\mathscr{B}(\mathbb{R^d})$. I tried using a theorem that we proved earlier.
Let $A_n = (a,b_n]$ with $b_n=(b_1-\frac{1}{n},b_2-\frac{1}{n},\dots,b_d-\frac{1}n)$ so that $A_n\uparrow(a,b)$. Using the theorem we would find $$\lim\limits_{n\rightarrow\infty}\prod\limits_{k=1}^d\left(b_1-a_1-\frac{1}{n}\right)=\lim\limits_{n\rightarrow\infty}\lambda(A_n)=\lambda((a,b)).$$
This is almost equal to what we want, but we have that nasty fraction in the product. How can I justify saying the product is equal to $\lambda((a,b])$? Just for clarification, we have as definition: $$\lambda((a,b])=\lim\limits_{n\rightarrow\infty}\prod\limits_{k=1}^d(b_1-a_1).$$ | So $(b_{k}-a_{k}-1/n)\rightarrow b_{k}-a_{k}$ as $n\rightarrow\infty$. Apply successively the product rule of limits: $(b_{1}-a_{1}-1/n)(b_{2}-a_{2}-1/n)\rightarrow(b_{1}-a_{1})(b_{2}-a_{2})$, do it in this way up to $d$, we get $(b_{1}-a_{1}-1/n)\cdots(b_{d}-a_{d}-1/n)\rightarrow(b_{1}-a_{1})\cdots(b_{d}-a_{d})$ as $n\rightarrow\infty$. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "real analysis, lebesgue measure"
} |
skipping reCaptcha multiple image selections
I have included a google recaptcha in my website. But, I want to skip the multiple image selections . I mean no puzzle should appear to the user. He should be able to directly tick the recaptcha. Is this possible. If so how? Thanks in advance | The ReCaptcha from Google need to use this _puzzle_ to determine whether the user is a robot or not.
If your really want to remove this part you should think about using another CAPTCHA. Find the one that fit your technology.
**_Here_** is a link that provide different other solution. Some of them use the old _number_ or _text_ to rewrite.
_NOTE_ : It would be better to use the Google ReCaptcha as it is reliable. Tell your users that the Captcha has a security purpose and it is important | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, recaptcha"
} |
jQuery doesn't work with elements created after document load
I created two elements dinamically with jQuery:
a picture and a Close button
I wrote the code to remove both in doument.ready function:
$( ".deletepreview" ).click(function() {
code = $(this).data("prevcode");
$('#'+code).remove();
$(this).remove();
});
But it doesn't work, and I think this is because the code doesn't search in the code created after the document load.
How can I solve this problem? | You need to use delegated events via `on()` if you want events to be handled on dynamically added elements:
$(document).on("click", ".deletepreview",function() {
var code = $(this).data("prevcode");
$('#'+code).remove();
$(this).remove();
});
I slightly modified your example: always declare variables with `var` in closures except when you need to. | stackexchange-stackoverflow | {
"answer_score": 32,
"question_score": 15,
"tags": "javascript, jquery, html"
} |
¿Cómo puedo probar un servicio en SoapUI que reciba como parámetro un archivo (MultipartFile)?
¿Cómo puedo probar en SoapUI este servicio?
@RequestMapping(value = "/cargarArchivo", method = RequestMethod.POST, consumes = "multipart/form-data")
public void cargarDatos(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
//
}
He estado buscando por Internet y por la misma aplicación la forma de adicionar el parámetro File pero no lo logro encontrar la opción. | Estos son los pasos a seguir para enviar un archivo a un servicio web con el SoapUI v.5.2.1:
1. Seleccionar POST como método de la petición.
2. Escoger multipart/form-data como Media Type.
3. Clic en la pestaña Attachments.
4. Clic en el símbolo + verde y seleccionar el archivo.
5. Este paso es opcional. Marcar si es necesario el check Post QueryString.
Si se necesita indicar el id con el que se enviará el archivo, se puede indicar en la pestaña "Attachments" en la columna "ContentId".
![Captura de pantalla SoapUI cómo enviar un archivo a servicio web]( | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, spring, soapui"
} |
using copy() and move_uploaded_file() error message: failed to open stream - php
I am using `copy` and `move_uploaded_file()` copy(/tmp/phpJ0lg4r.jpeg) [function.copy]: it gives me the error **failed to open stream: No such file or directory in**
I do not think there is an error in the code, but its the image temp path somewhere the error.
Any ideas to why?
\--EDIT--
1. The file permission is :777
2. Using only move_uploaded_file
\---CODE--
<form method="post" enctype="multipart/form-data" action="">
<INPUT NAME="u" TYPE="file" size="90">
<input type="submit" value="submit">
</form>
move_uploaded_file($HTTP_POST_FILES['u'.$i]['name'],"Path_Of_Directory");
Though there are several checks of the type of file, this is the basic. It just does not copy or move the file. | Try
`move_uploaded_file($_FILES["u"]["tmp_name"], "Path_Of_Directory");` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "php"
} |
Why cannot I create a file in a folder I own with chmod 655, but 755 works?
I have a backup folder owned by a system user (mongodb) and chmoded 655. When I try to create files in it, it raises a permission issue:
root@maquina:/var/backups/mongodb# su -s /bin/bash mongodb -c "/usr/bin/touch test.txt"
/usr/bin/touch: cannot touch `test.txt': Permission denied
Chmoding to 755 enables me to create the file.
I guess I probably need to tweak the privileges (+X ?) but cannot find how.
Can anyone shed some light on this ?
Thank you! | You need to have execute permissions in the directory in order to do seeks there. Without being able to do a seek, you can't create a file
sudo chmod u+x /var/backups/mogodb | stackexchange-serverfault | {
"answer_score": 4,
"question_score": 1,
"tags": "ubuntu, chmod"
} |
Oracle DB : java.sql.SQLException: Closed Connection
Reasons for java.sql.SQLException: Closed Connection from Oracle??
> java.sql.SQLException: Closed Connection at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208) at oracle.jdbc.driver.PhysicalConnection.commit(PhysicalConnection.java:1131) at oracle.jdbc.OracleConnectionWrapper.commit(OracleConnectionWrapper.java:117)
We are getting this error from the fail over database connection. We use the same code for other databases as well. But seeing this issue with only one of the databases. Is this because the connection might have timeout due to long inactivity period and we are trying to use that? Pls let me know if you need more details...
AbandonedConnectionTimeout set to 15 mins InactivityTimeout set to 30 mins | It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool. | stackexchange-stackoverflow | {
"answer_score": 55,
"question_score": 39,
"tags": "java, sql, jdbc, oracle10g"
} |
Select mysql query between date?
How to select data from mysql table past date to current date? For example, Select data from 1 january 2009 until current date ??
My column "datetime" is in datetime date type. Please help, thanks
Edit:
If let say i want to get day per day data from 1 january 2009, how to write the query? Use count and between function? | select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()
or using `>=` and `<=` :
select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate() | stackexchange-stackoverflow | {
"answer_score": 92,
"question_score": 56,
"tags": "mysql, select, date"
} |
Backbone collection's URL depends on initialize function
I have a Backbone collection whose URL depends on the initialize function. When I create an instance of this Backbone collection, I pass in an ID to filter which instances of the model appear. Here is what the collection's code looks like:
var GoalUpdateList = Backbone.Collection.extend({
// Reference the Goal Update model
model: GoalUpdate,
// Do HTTP requests on this endpoint
url: " + this.goal_id + "&format=json",
// Set the goal ID that the goal update list corresponds to
initialize: function(goal_id) {
this.goal_id = goal_id;
console.log(this.goal_id);
console.log(this.url);
},
});
Of course, this doesn't work. `this.goal_id` is seen as being undefined. I guess because the URL is set before the initialization function is run. | You can use a function for `url` that dynamically builds the URL.
url: function() {
return " + this.goal_id + "&format=json";
}, | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript, backbone.js"
} |
Hitting escape to continue does not work in Suggested Edit Dialog
!Hit esc to continue
As you can see from this image, there is a message:
> This suggestion still needs 2 approve votes from other reviewers. Close this popup ( **or hit Esc** ) to continue.
Emphasis is obviously mine.
However no matter how many times I hit `Esc`, it didn't close. I made sure that the modal had priority. I dragged it a round a little and hit `Esc` a few more times to make sure, but it just sat there. I then had to click the 'X' to close it.
Not a massive problem, but either the text should be removed or the bug should be fixed.
Hitting `Esc` only won't work on this type of model. @FrédéricHamidi has tested and found out that it still works in the `Close Vote` popup. | Fix is rolling out with build `2015.1.30.3034` on meta and `2015.1.30.2257` on sites.
All it took was the removal of the `.no-esc-remove` class from the popup's lightbox - which actually only started to behave correctly after the batch of fixes concerning the stacking of popups we can have due to the markdown editor & rejection reason popup inside the suggested edit popup. That class turned out to be just a dirty hack, introduced to prevent the whole stack of popups to close when esc is pressed. | stackexchange-meta_stackoverflow | {
"answer_score": 3,
"question_score": 24,
"tags": "bug, status completed, keyboard shortcuts"
} |
do diesel engines have Idle Air Control Valve?
My problem is that sometimes when my Astra G tdi 1.7 2002 is idling (is not in gear) the RPM will go to 5000-6000 with out me stepping on the gas pedal. The engine accelerates on its own while idling. I tried reading online and found a post that this could be because of the Idle Air Control Valve. I told this to my mechanic and he told me that my car and diesel engines don't have Idle Air Control Valve. My question is first do diesel engines have an Idle Air Control Valve and where can I locate it on my Astra G?
This is an image of the engine:
![enter image description here](
BTW, the mechanic has no idea what the problem is. | it turned out that the car was tuned and it had some extra electronic that was connected to the computer and the fuel pump. This wasn't a native part of the car and it was hidden. We founded after expecting the electric installation and searching for problems there. After removing it there are no problems and the car runs great. Ill try to post pictures from the model later. Thanks all | stackexchange-mechanics | {
"answer_score": 3,
"question_score": 2,
"tags": "diesel, opel, astra"
} |
how can I generate Java/JSP forms (to work on database data)?
I'm searching for good tools to build jsp forms for DB transactions (new, edit, delete of records) I want to use the simliest tool available. I don't want to write setters/getters for each single record field and for each single table and for each kind of access (read / change). Do I need to learn Wicket or JSF to handle this approach? | Your keyword is CRUD (Create, Read, Update, Delete). Netbeans has a CRUD generator which can autogenerate JPA 2.0 entities and JSF 2.0 CRUD forms based on just a SQL database table.
Or, if you're more from Eclipse (like me), then try the CRUDO plugin (I've never tried it though). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "java, jsp, frameworks, jdbc, crud"
} |
Problem with loading huge excel file(100mb) when using read_xlsx. Returns wrongly "TRUE" in some cells
I am working with a huge dataframe and had some problems loading it from the excel file. I could only load it using read_xlsx from the readxl package. However i have now realized that some of the cells contains "TRUE" instead of the real value from the excel file. How can it load the file wrongly and is there any solution to avoid this? | Following this advice solved the problem.
> JasonAizkalns: Hard to tell, but this may be caused from allowing read_xlsx to "guess" the column types. If you know the column type beforehand, it's always best to specify them with the col_types parameter. In this case, it may have guessed that column type was logical when really it's supposed to be something else (say, text or numeric)
Cleaning the dataset from columns with none numeric values and then using `x<-read_xlsx(filename, skip = 1, col_types = "numeric")`. Hereafter i `y<- read_xlsx(filename, skip = 1, col_types = "date")` on the column containing dates. I used cbind(y,x) to complete the dataset with the none numeric column. It seems that read_xlsx misinterprets the columns with numeric values if there is a lot of values missing. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "r, readxl"
} |
Jech Set Theory: Proof that the separative quotient of a generic set is generic
Jech's Set Theory, 3rd edition, has the following result:
> Lemma 14.13: (i) In the ground model M, let Q be the separative quotient of P and let h map P onto Q such that (14.5) holds. If $G \subset P$ is generic over M then $h(G) \subset Q$ is generic over M
The (14.5) condition referenced is i: $x \leq y$ implies $h(x) \leq h(y)$ and ii: $x$ and $y$ are compatible in $P$ if and only if $h(x)$ and $h(y)$ are compatible in $Q$.
In particular, since every generic set over a model $M$ is a filter, this implies that $h(G)$ must be a filter as well, and hence that it's closed above in the partial ordering on $Q$. But I can't for the life of me figure out how to prove this.
In other words: given $p \in h(G), p \leq q$, how can we verify that $q \in h(G)$? Thanks in advance for any help! | To solve this we will prove something stronger:
If $[p] \in h(G) \wedge [p] \le [q] \rightarrow q \in G$ this is stronger than the main statement because this actually implies that every representative of $[q]$ lies in $G$. Now it follows from the definition that $[p] \le [q]$ implies that for all $r$, $r$ is compatible with $p \rightarrow r$ is compatible with $q$. Now consider the set $D = \\{r \in P: r$ is incompatible with $p$ or $r \le q\\}$. You can easily check that $D$ is dense in $P$ and so $G \cap D \neq \emptyset$. Then there exists $r$ such that $r\in G$ and notice that $r$ can't be incompatible with $p$ so $r \le q$ and lastly we have $q \in G$ as needed. | stackexchange-math | {
"answer_score": 0,
"question_score": 1,
"tags": "set theory, order theory, forcing"
} |
Pipe Command To PowerShell from Shell Script
I have some Windbg script where I can call out to a cmd shell via the .shell command. Now I want to execute some Windbg command and pipe the output to the shell script which should start powershell.exe to process the input data. So far I did fail.
In principle it should be possible to pass data from stdin to powershell pipes?
echo C: | powershell.exe -Command "| dir"
I do not want to create an extra powershell script because that would complicate the windbg script further and create external dependencies. | You can use the predefined `$input` variable to use the text you echo into powershell. In conjunction with the pipeline, this works perfectly:
echo C:\ | powershell.exe -command "$input | dir"
Edit: You also need to use `echo C:\`. I'm not sure of the reasoning, but simply writing `Get-ChildItem 'C:'` defaults to the current directory. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "powershell"
} |
Who are all these superheros in Avengers: Endgame poster?
Recently I got my hands on IGN's _Avengers: Endgame_ poster, which they made themselves:
![enter image description here](
I can identify majority of them but not all. Who are all these 13 superheroes? | ![enter image description here](
1. Maria Hill
2. Winter Soldier
3. Nick Fury
4. Scarlet Witch
5. Groot
6. Black Panther
7. Gamora ( kid version)
8. Spider-Man
9. Dr. Strange
10. Mantis
11. Star-Lord
12. Drax
13. Wasp | stackexchange-scifi | {
"answer_score": 30,
"question_score": 16,
"tags": "marvel, marvel cinematic universe, character identification, avengers endgame"
} |
Concatenate and flat two nested python list
I have two vectors in the form
a = [[1,2,3],[1,2,3],[1,2,3]]
b = [[5,6,7],[5,6,7],[5,6,7]]
I want the output to be
c = [[1,2,3,5,6,7],[1,2,3,5,6,7],[1,2,3,5,6,7]]
I got this line
c = [[a[i],b[i]] for i in range(len(a))]
but my output is
[[[1, 2, 3], [5, 6, 7]], [[1, 2, 3], [5, 6, 7]], [[1, 2, 3], [5, 6, 7]] | _zip_ and _concatenate_ each pairing:
a = [[1,2,3],[1,2,3],[1,2,3]]
b = [[5,6,7],[5,6,7],[5,6,7]]
print([i + j for i,j in zip(a, b)])
Which would give you:
[[1, 2, 3, 5, 6, 7], [1, 2, 3, 5, 6, 7], [1, 2, 3, 5, 6, 7]]
Or using your own logic:
[a[i] + b[i] for i in range(len(a))]
_concatenating_ with + is the key. If you were going to index I would use _enumerate_:
[ele + b[i] for i, ele in enumerate(a)] | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "python, list, nested"
} |
PHP function to identify and parse unusual time format?
I'm currently working with weather data feeds to assemble some accurate data. This particular feed is being pulled from Norway and has a format of 2012-01-13T19:00:00. The "T" is what throws me off.
Does anyone know if PHP will recognize this format and/or provide a function to parse this particular timestamp?
I would have thought a combo of strtotime() and date(), but apparently it only accepts English formats? I would prefer to avoid doing a regex to strip out the T but if it's necessary I'll work with it.
Many thanks for the help. | Yes, PHP will recognize it, because that's a standardized format.
$timestamp = strtotime('2012-01-13T19:00:00'); | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 1,
"tags": "php, strtotime"
} |
Does $\int1+\sin^2x+\sin^4x+\sin^6x+...\text{dx}=\tan{x}$?
I want to find $$\int1+\sin^2x+\sin^4x+\sin^6x +...\text{dx}$$ My method was to interpret the integrand as a geometric series with first term $1$ and common ratio $\sin^2x$. Assuming $\sin x\ne1$, I reasoned the integrand should converge.
So the integrand should be equal to $$\frac{1}{1-\sin^2x}=\frac{1}{\cos^2x}=\sec^2{x}$$ $$\implies \int1+\sin^2x+\sin^4x+\sin^6x +...\text{dx}=\int\sec^2{x}~\text{dx}=\tan x$$ I would just like to know, is this right? If it is, it seems to me a rather beautiful result. | HINT: For any nonnegative $a <1$ the sum $1+a+a^2+ \ldots = \frac{1}{1-a}$. So setting $a=\sin^2x$, we note: $1+\sin^2 x+\sin^4 x + \ldots = \frac{1}{1-\sin^2 x} = \sec^2 x = \frac{d(\tan x)}{dx}$.
Can you finish from here.
ETA: Nevermind just reread you already got this. YES you are correct. | stackexchange-math | {
"answer_score": 2,
"question_score": 5,
"tags": "calculus, integration, solution verification, indefinite integrals, trigonometric integrals"
} |
Asp.Net notification application using signalR to send notification to only one client
I am trying to make a notification application using SignalR in which only one specific user gets the notification. How do I do this using SignalR? Or is there another way to make a similar feature with any other technology? | Yes you can. See the link here SignalR wiki - Hub
public class MyHub : Hub
{
public void Send(string data)
{
// Similar to above, the more verbose way
Clients[Context.ConnectionId].addMessage(data);
}
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "asp.net mvc 3, notifications, signalr"
} |
Django dictionary not passed?
Trying to pass python dictionary to my django template. But it seems to not be passed while rendering. I have read documentation and few sites, but can't find solution. It must be simple...
#views.py
def home(request):
context = {}
links = getLinks()
for link in links:
splited = getRate(link).split()
# print(splited)
key = splited[1]
context[key] = float(splited[0])
print(context)
return render(request, 'home.html', context)
home.html:
{% for key, value in context.items %}
<a href="{{key}}">{{value}}</a>
{% endfor %}
I print dictionary in my terminal, so it definitely exists and contains everything I need. But can't refer to it in my template. | The reason is that the template does not know about the name `context`, so in `{% for key, value in context.items %}`, `context.items` does not refer to anything.
That means you need to pass the correct dictionary to the template:
# views.py
def home(request):
data = {}
links = getLinks()
for link in links:
splited = getRate(link).split()
key = splited[1]
data[key] = float(splited[0])
return render(request, 'home.html', {'context': data})
# Now, 'context' will actually mean something to the template.
Now that you know where the mistake is, I suggest that you not name your template variable `context`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, django, django templates, django views"
} |
Linking javascript file with your jquery in it
There doesnt seem to be a definitive answer anywhere online to this. I understand that you can put:
<script type="text/javascript" src="
<script type="text/javascript">
$(document).ready(function() {
Your code here.....
});
</script>
to link your downloaded jquery file. But what code do you have to add so that it works from a javascript file that you have writting your jquery code into?
I like to work from 3 documents (as that is how ive learn on codeacademy) html, css, js. But all i can find online is how to attach the downloaded jquery and then work your jquery code into the html file. So is this possible?
any help would be much appreciated | Put this code in your `script.js`
$(document).ready(function() {
//Your code here.....
});
and then include your `.js` file like this ( _after jQuery_ ) -
<script type="text/javascript" src="
<script type="text/javascript" src="script.js"></script> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery"
} |
Model a function with specific shape
I need a function with a specific shape:
* Quadratic/gaussian concave shape ($-x^2$ like)
* Centered in $\frac{1}{2}$ where it reaches the max value 1
* On `0` and `1` to become null
I first tried using a second-degree polynomial function and I failed.
By repeated tries on `graph.tk`, after I deduced on paper that $c=0$, I got $-4x^2+4x$ to be what I need.
Then I found the function $e^{-x^2}$ which have a very nice shape.
But now I have to span it in $[-0.5, 0.5]$ and add an offset.
$e^{-(x-0.5)^2}$ is centered in $\frac{1}{2}$ where it reaches 1, but it does not descend down to zero in `0` and `1`.
I'm interested in either the solution to this problem and in the process of reaching that solution. How is this usually done?
* * *
If Q above is unclear:
How do I model $e^{-x^2}$ to meet the requirements in bullets above? | Well you're almost there. You have your nice function centered on $x=\frac{1}{2}$:
$$f(x)=e^{-(x-\frac{1}{2})^2}$$
Now you can compute $f(0)$ and $f(1)$ which will be equal because $f$ is symmetric around $x=\frac{1}{2}$:
$$\large f(0)=f(1)=e^{-\frac{1}{4}}$$
If you want $f(0)=f(1)=0$ you just have to write:
$$f(x)=e^{-(x-\frac{1}{2})^2}-e^{-\frac{1}{4}}$$
But now for $x=\frac{1}{2}$, your function is equal to $\large1-e^{-\frac{1}{4}}$
Just multiply it by $\large\frac{1}{1-e^{-\frac{1}{4}}}$ and here you go:
$$\large f(x)=\frac{e^{-(x-\frac{1}{2})^2}-e^{-\frac{1}{4}}}{1-e^{-\frac{1}{4}}}$$
Here's the plot of this function:
!enter image description here | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "functions, graphing functions"
} |
Get Reference to Currently Displayed Card
Let’s say I have a `JPanel` named `cards` and it has a layout type of `CardLayout`. Each card in the layout is also of class`JPanel`. How do I get a reference to the `JPanel` that’s currently being displayed in the layout?
Thanks. | > How do I get a reference to the JPanel that’s currently being displayed in the layout?
There is nothing in the API that allows you to do this, that I'm aware of. So,I extended the CardLayout to provide this information.
Check out Card Layout Focus for my implementation that allows you to get this information among other things. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, swing, cardlayout"
} |
Python, How to pass function to a class method as argument
I am trying write a signal processing package, and I want to let user creates a custom function without needing to access the class file :
class myclass():
def __init__(self):
self.value = 6
def custom(self, func, **kwargs):
func(**kwargs)
return self
c = myclass()
def add(**kwargs):
self.value += kwargs['val']
kwargs = {'val': 4}
c.custom(add, **kwargs )
print (c.value)
I got name 'self' is not defined. Of course because func is not a method to the class. But I am not sure how to fix it. Please advice.
Thanks | You need to pass the class instance into the method too, do this :
class myclass():
def __init__(self):
self.value = 6
def custom(self, func, **kwargs):
func(self, **kwargs) ## added self here
return self
c = myclass()
def add(self, **kwargs): ## added self here
self.value += kwargs['val']
kwargs = {'val': 4}
c.custom(add, **kwargs )
print (c.value)
**output :** `10` | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 7,
"tags": "python"
} |
SendMail using outlook credits Java
I am wondering how to send mail using outlook credits without entering additional details like host, port, username, pass in the java program. I used desktop.mail() but it opens the mailInterface which I doesnt want to. | Using the libraries like
JWS,Jacob | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "jakarta mail"
} |
Is this a valid haiku?
A friend showed me a website for an artist. There is a page filled with haikus he's written. Can someone verify the validity of the following haiku:
> i don’t really
>
> want to do
>
> that | No. There is a distinct pattern that is required. To wit:
> a Japanese poem of seventeen syllables, in three lines of five, seven, and five, traditionally evoking images of the natural world.
>
> * A poem in English written in the form of a haiku.
>
>
> Oxford Dictionaries
What you presented does not fit the pattern. | stackexchange-writers | {
"answer_score": 4,
"question_score": 2,
"tags": "haiku"
} |
Retrieving .txt file contents in Google AppEngine
I'm trying to Upload a text file using :
<input type="file" name="file">
and this file is retrieved using:
class UploadHandler(webapp2.RequestHandler):
def post(self):
file=self.request.POST['file']
self.response.headers['Content-Type'] = "text/plain"
self.response.write(file.value)
my output is:
Content-Type: text/plain MIME-Version: 1.0 Content-Length: 312 Content-MD5: MDIzYzM5YmNmOWRmMzY5Zjk2MTYzZTUzNjYwMTg5YjM= content-type: text/plain content-disposition: form-data; name="file"; filename="blah.txt" X-AppEngine-Upload-Creation: 2013-04-24 07:57:23.729774
Is there any way i could retrive the file content instead of above headers. ?? | The following seems to work, so there must be something else that is happening (live example):
import webapp2
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = "text/html"
self.response.write('''
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit">
</form>
''')
class UploadHandler(webapp2.RequestHandler):
def post(self):
file = self.request.POST['file']
self.response.headers['Content-Type'] = "text/plain"
self.response.write(file.value)
app = webapp2.WSGIApplication([
('/', MainHandler),
('/upload', UploadHandler)
], debug=True) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 4,
"tags": "python, google app engine, text, blobstore"
} |
1em is not set as 16px
i'm working on a website where the client wants some titles at 0.875em.
I checked online, and the base em unit should be 16px for modern browsers. Well, if I set the text-size to 1em in chrome developer, it's set at 12px instead of 16px.
Tried setting `body{font-size:100%}` at the beginning. No luck.
How do I put it back at 16px base? | That is because Chrome's default font-size is 12px. You should set the body and/or html element's font-size to 16px, like so:
html, body {
font-size: 16px;
}
This is assuming that there's no parent elements that change this font-size though, as em is a relative size to the nearest parent that sets a size. Check into rem if you want an absolutely sized font, however this isn't supported in older browsers so you'll need to provide a fallback. | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 6,
"tags": "css, font size"
} |
Check if the first element of an array is a digit in C
I was making a program to take a list of data and separate it by the "," in the file. However, some items had multiple commas.
Is there any _efficient_ way of checking the first character of an array? For example:
char *array = {'1','A','C','D','5'};
Now, I want to only do `somefunction(array)` if `array` starts with a digit, even if it is in char format. So in this example, let `somemethod` be the way of determining if the first element is an integer:
char *array = {'1','A','C','D','5'};
if( somemethod ) someaction(array);
How could I do this efficiently? | The standard function `isdigit` from `<ctype.h>` could be also efficient:
#include <ctype.h>
if (isdigit((unsigned char)array[0])) someaction(array);
You can also define your own, with just two comparisons:
#if (!defined __STDC_VERSION__) || (__STDC_VERSION__ < 199901L)
# undef inline
# undef bool
# define inline
# define bool int
#endif
inline bool somemethod(const unsigned char c) { return c >= '0' && c <= '9'; }
However, thinking about performances here looks like premature optimization. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "c, arrays, string"
} |
Root directory shows 404 in nginx
I am new to nginx server. I tried to set a new url "/images/" for serving images. I edited the bi.site file in site-enabled folder.
server {
listen *:80;
access_log /var/log/myproject/access_log;
location / {
proxy_pass
proxy_redirect off;
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 /images/ {
root /www/myproject/files_storage;
}
}
And in /www/myproject/files_storage location i put a temp.txt file.
When i put ` it shows 404 not found. What am i doing wrong ? Did i miss something important ? | this:
location /images/ {
root /www/myproject/files_storage;
}
results in /www/myproject/files_storage/images path, it would be obvious if you setup error_log. So use "alias" directive instead of "root"
< | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 7,
"tags": "nginx"
} |
Как работать с полем типа Array в Doctrine 2
Имеется , пока пустое, поле в таблице(сущности)
/**
* @var array
*
* @ORM\Column(name="options", type="array", nullable=true, unique=false)
*/
private $options;
/**
* Set options
*
* @param array $options
*
* @return Config
*/
public function setOptions($options)
{
$this->options = $options;
return $this;
}
/**
* Get options
*
* @return array
*/
public function getOptions()
{
return $this->options;
}
при выборе поля
$record = $this->entityManager->getRepository(Config::class)->findOneBy(['...' => '...']);
получаю
Could not convert database value "" to Doctrine Type array
Подскажите как работать через Doctrine с такими полями (выборка, сохранение и т.д.) | Поля типа `array` Doctrine хранит в базе в виде массива, сконвертированного функцией `serialize()`. Делать выборку по отдельно взятому элементу массива — не самый правильный путь. Но если вам нужно сравнить массивы целиком, то вот:
$arr = array(); // Массив для сравнения
$record = $this
->entityManager
->getRepository(Config::class)
->findOneBy(['options' => $arr]);
То есть, при формировании запроса в конструкторе вам нужно предоставлять ему данные для полей в том виде, в котором они объявлены. Если поле является массивом, конструктор запросов не примет ничего, кроме массива. | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, mysql, массивы, doctrine2"
} |
UNNotification delegate function not being called when clicking on Push Notification
Whenerver I clicked on the push notification its not being called the delegate function and gives a warning as:
Warning: UNUserNotificationCenter delegate received call to -userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called.
I couldn't able to find out the real reason behind that as I done all the research about that.
I'm testing this on swift 4.2 & ios 12.1 | I was using ClaverTap SDK that throws a warning while clicking on notification. It fixed after changing its instance method before assigning Notification delegate function. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "ios, swift, push notification, apple push notifications"
} |
Can declarative authorization be used to hide/show certain fields?
I'm trying to figure out the best way to hide certain fields in user profile based on user's preference. So far I'm using a boolean field and an if, then statement.
<% if @user.show_email == 'true' -%>
<%=h @user.email %>
<% else -%>
hidden
<% end -%>
I was wondering if I could use declarative_authorization or some other better method that is more DRY. I prefer to have in a way like if @user.role == "admin" show all, if @user.role == "regular" show only non-hidden fields. etc
Thanks | Have you considered using a helper function? In your case, I would do something like this on app/helpers/user_helper.rb:
def show_attribute(user, attribute_name)
preference = "show_#{attribute_name}"
if current_user.has_role?(:admin) or
!user.respond_to?(preference) or
(user.respond_to?(preference) and user.send(preference))
return user.send(attribute_name)
else
return "hidden"
end
end
You can use it in your views like this:
<%=h show_attribute(@user, :email) %>
<%=h show_attribute(@user, :address) %>
Best regards. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, authorization"
} |
Help with the Inductive step in mathematical Induction?
I just started working on Induction, and I have one particular problem that I don't understand:
Prove that $1+3+5+...+(2n−1)=n^2$ for any integer $n≥1.$
* $n = 1$ :
$1 = 1^2$
* $n = k$ :
$1+3+5+...+(2k−1)=k^2$
* $n = k+1$ : (this is where I have a problem)
I thought that you simply substitute k+1 for n, yielding $1+3+5+...+(2k+1)$, but the correct equation is actually $1+3+5+...+(2k−1)+(2k+1)$. Where did that extra term $2k-1$ come from?
My apologies if this is a simple answer, but this is all new to me. Thanks in advance | Don't get confused. For example, if I write the expression $2+4+6+\cdots +10$, isn't it the same as $2+4+6+\cdots 8+10$? (the sum of even integers from $2$ to $10$, inclusive). They're just including the second last term, that's all. This will be needed in order to apply the induction hypothesis (from the case $n=k$, you need the sum $1+3+5+\cdots +(2k-1)$ to appear somewhere).
This is a very common idea when trying to prove identities involving sums (or products) of $n$ terms by induction on $n$: Isolate the $n+1$ term and notice that the remaining part will be the induction hypothesis. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "induction"
} |
Issue with modifying array by reference
In PHP, I have the following code (whittled down, to make it easier to read):
class Var {
public $arr;
function __construct($arr) {
$this->arr = $arr;
}
function set($k, $v) {
$this->arr[$k] = $v;
}
}
class Session extends Var {
function __construct() {}
function init() {
session_start();
parent::__construct($_SESSION);
}
}
$s = new Session();
$s->init();
$s->set('foo', 'bar');
var_dump($_SESSION);
At this point, I want $_SESSION to contain `'foo' => 'bar'`. However, the $_SESSION variable is completely empty. Why is this the case? How can I store the $_SESSION variable as a property in order to later modify it by reference?
I have tried replacing `__construct($arr)` with `__construct(&$arr)`, but that did not work. | You needed to take care of reference on **every** variable re-assignment you have.
So the first place is `__construct(&$arr)`
The second is `$this->arr = &$arr;`
Then it should work.
If you didn't put the `&` in the latter case - it would "make a copy" for the reference you passed in constructor and assign "a copy" to the `$this->arr`.
PS: It's really weird to call parent constructor from non-constructor method | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "php, session, reference, pass by reference"
} |
Check if Twitter API is down (or the whole site is down in general)
I am using the Twitter API to display the statuses of a user. However, in some cases (like today), Twitter goes down and takes all the APIs with it. Because of this, my application fails and continuously displays the loading screen.
I was wondering if there is a quick way (using PHP or JS) to query Twitter and see if it (and the API) is up. I'm thinking it could be an easy response of some sort.
Thanks in advance, Phil | Request ` or `test.json`. Check to make sure you get a 200 http response code.
If you requested XML the response should be:
<ok>true</ok>
The JSON response should be:
"ok" | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "php, javascript, twitter"
} |
debugging Android UDP listening
I want to get in my `Android` emulator some incoming data sent by remote computer on my local network. So first,
InetAddress[] inetAddress = InetAddress.getAllByName(android_emulator_ip);
s = new DatagramSocket();
s.connect(inetAddress[0], some_udp_port);
I got the `android_emulator_ip` running `adb shell;ifconfig eth0`. This `IP` is the one used by the remote computer.
The weird thing is that if I change this `ip` to a random one, I get in my break point debugger for the DatagramSocket object, the value `isConnected =true`
By the way, I can't catch any error in the following. If I log after `s.receive(p);` in the following `try` block, it seems not to be read
byte[] message = new byte[300];
DatagramPacket p = new DatagramPacket(message,message.length);
try{
s.receive(p);
}catch{...} | I get it debugged setting a timeout this way
s = new DatagramSocket(some_udp_port);
s.setSoTimeout(3000);
and then this worked
byte[] message = new byte[256];
DatagramPacket p = new DatagramPacket(message,message.length);
try{
s.receive(p);
}
The issue was related to use `connect`and so to put the emulator in a position of server rather than listener | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, android, sockets, udp"
} |
Javascript Array delete or pop causing race condition with console.log?
On the current Google Chrome (Version 22.0.1229.79, on an iMac with Mountain Lion), the following code
var arr = [1, 3, 5];
console.log(arr);
delete arr[1];
console.log(arr);
console.log(arr.pop());
console.log(arr);
will show
[1, undefined × 2]
[1, undefined × 2]
5
[1, undefined × 1]
there are also other situation that caused Firefox to behave similarly as well. Are they bugs on Chrome and Firefox -- but it would seem strange that both Firefox and Chrome are susceptible to similar bugs -- or is it some behavior with array delete and `console.log`? Supposedly, `console.log` should not be running on a separate thread. | It is due to queued up `console.log` processing, so the printing is delayed, and it shows a later version of the object or array: Is Chrome's JavaScript console lazy about evaluating arrays?
My answer there has 5 solutions and `JSON.stringify()` was the best one. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 5,
"tags": "javascript"
} |
How can I find out if boost::any contains a literal string?
I have this code
#include <boost/any.hpp>
std::vector<boost::any> a( {1,2,3,"hello",3.0});
for (int i = 0; i < a.size();i++)
{
if (a[i].type() == typeid(int)) // this works
{
std::cout << "int";
}
if (a[i].type() == typeid(char*)) // this does not work I know why
{
std::cout << "char*";
}
}
What `if` statement should I use to detect `"hello"`, or any sized literal string? | > How can I find out if Boost any contains a literal string?
String literals are arrays of `const char`. `boost::any` stores decayed types, so string literal will be a `const char*`.
Note that there is no guarantee for the `const char*` to be a string literal. It can be a pointer to any character, not just the first character of a string literal. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c++, boost"
} |
Having multi lines in bash command substitution
I have a very long bash command inside a command substitution like following:
$( comaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaand )
I want to know if there is a way to break this command into shorter lines for the sake of readability like following:
$( com
aaaaaaaaaaaaaa
aaaaaaaaaaaaaa
nd ) | You can mask the newline with `\`.
$( com\
aaaaaaaaaaaaaa\
aaaaaaaaaaaaaa\
nd )
The `\` tells the shell to ignore the newline. | stackexchange-unix | {
"answer_score": 15,
"question_score": 7,
"tags": "bash, shell script"
} |
Add webapi Header in a DelegatingHandler
I am trying to add a header to the request within a Delegating Handler of a webapi project like this:
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var corGuid = CommonBaseController.CreateSafeCorrelationId(string.Empty);
cor = corGuid.ToString();
request.Content.Headers.Add("correlationId", cor);
var response = await base.SendAsync(request, cancellationToken);
}
Once inside the controller I want to be able to get the header like this:
var cor = request.Headers["correlationId"];
However the header is not there. | I was using the wrong Request Object. The Headers do not show up in the HttpContext.Current.Request but in the base.Request object in the Controller.
Thanks | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, asp.net web api, asp.net web api2"
} |
How do I show a youtube video on full screen when a link is clicked?
In one of my web app I am showing a youtube videos thumb nails like
<img height="150px" id="youtubeImage" src=" href="">
I am fetching the video id from database. I want to show a full screen if this video while clicking on this link. I showed this in a iframe using jQuery. But how to show this in full screen ?
Please help Thanks | Not really a jQuery answer, but this can almost be achieved by using the URL:
>
This will redirect to
>
Which has the video taking up the full browser tab. Not strictly fullscreen as it won't hide the player components but I'm not sure you can do it any other way. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery, youtube api"
} |
What are Dangling Images in Docker/How they created/How to remove them
How do dangling images get created? Whenever I tried to create them it is not happening.
I had used the same concept as mentioned in docker docs. If my DockerFile contains `FROM alphine:3.4` then I build the image as `docker build -t image1 .`
After some time I update it as `FROM alphine:3.5` and again building it as `docker build -t image1 .`
But it is showing me three images no dangling one??
![enter image description here]( | If you _really_ want to create a dangling image, simply interrupt the build process before it's finished.
Honestly don't understand why you want to though; they are a by-product of a failed build, that's all. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "docker, dockerfile"
} |
Detect if Windows Service is running of remote machine
> **Possible Duplicate:**
> Check status of services that run in a remote computer using C#
Is it possible to check if a given windows service is running on a remote machine using C#?
This is assuming that I have the correct login credentials for that machine. | WMI, if you're using C# or VB.Net
Otherwise, "SC" is probably the best tool to use from a command line or .bat file. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 7,
"tags": "windows, service"
} |
Etimología de "piragua"
La palabra "piragua" parece ser de esas cuya etimología parece obvia en un principio: una embarcación, vehículo capaz de navegar por el agua, que contenga la misma palabra "agua" en su nombre no puede ser casualidad. ¿O sí? Resulta que según el diccionario, la palabra _piragua_ se originó en el caribe, y más concretamente, según Etimologías de Chile, viene del taíno. No da más información, más que mencionar que los taínos fueron los habitantes precolombinos de las Bahamas, las Antillas Mayores y el norte de las Antillas Menores.
La conclusión con tan poca información parece ser que el hecho de que se llame _piragua_ no es más que una curiosa coincidencia. ¿Es esto así? ¿Existe más información al respecto que pueda confirmar esto? | Según todas las fuentes habituales, _piragua_ viene de _piraua_ , que significa canoa hecha con un tronco ahuecado y es una palabra de la lengua caribe insular o iñeri, "lengua arawak del grupo caribeño hablada en las Antillas Menores y relacionada filogenéticamente con el taíno de las Antillas Mayores" (el caribe propiamente dicho no tiene relación con esta lengua, pese a su nombre). La palabra aparece por primera vez en castellano alrededor de 1530, pasando al francés como _pirogue_ en 1660 y de ahí al inglés.
Curiosamente hay en Puerto Rico un tipo de helado que se llama _piragua)_ , pero sin relación con la canoa (según Wikipedia, viene de _pirámide_ y _agua_ , ya que es un raspado helado con forma de pirámide o cono). | stackexchange-spanish | {
"answer_score": 6,
"question_score": 3,
"tags": "etimología, sustantivos"
} |
Can "mdfind" search for phrases and not just unordered words?
Is there a way to search for an exact phrase using the `mdfind` utility? For example, I created two text documents titled "test1" and "test2". The contents of "test1" are:
> I love Apple
And the contents of "test2" are:
> Apple love I
When I type this in terminal (I placed both files in ~/Documents):
> mdfind "I love Apple" -onlyin ~/Documents
I get:
> ~/Documents/test1.txt
> ~/Documents/test2.txt
How would I search for the exact phrase "I love Apple" so `mdfind` only returns results containing those words in that order (in this case only "test1.txt")? | You need to escape your quotes like so:
mdfind \"I love Apple\" -onlyin ~/Documents
This results in just the one document being found:
~/Documents/test1.txt
Without escaping them, I don't think the quotes actually get passed to the `mdfind` command, they're just interpreted by your shell to say that `I love Apple` is a single argument. With the backslash-escaping, the argument then includes the quote characters. | stackexchange-apple | {
"answer_score": 8,
"question_score": 5,
"tags": "terminal, search, spotlight"
} |
Given that $\cos\left(\dfrac{2\pi m}{n}\right) \in \mathbb{Q}$ prove $\cos\left(\dfrac{2\pi}{n}\right) \in \mathbb{Q}$
Given that $\cos\left(\dfrac{2\pi m}{n}\right) \in \mathbb{Q}$, $\gcd(m,n) = 1$, $m \in \mathbb{Z}, \, n \in \mathbb{N}$ prove that $\cos\left(\dfrac{2\pi}{n}\right) \in \mathbb{Q}.$
I know nothing about how to attack the problem. I believe I need to suppose that $\cos\left(\dfrac{2\pi}{n}\right) \not \in \mathbb{Q}$ and somehow show that $\cos\left(\dfrac{2\pi m}{n}\right) \not \in \mathbb{Q}$ what would have been a contradiction. Could you give me some hints? | **HINT:**
* For all $\theta\in\mathbb R, m\in\mathbb N$, $\cos(m\theta)$ can be expressed as a polynomial of $\cos(\theta)$ (with rational coefficients), so if $\cos(\theta)$ is rational, so is $\cos(m\theta)$.
* If $m,n\in\mathbb Z$ and $\gcd(m,n)=1$, there exists $k\in\mathbb N$ such that $mk\equiv 1 \bmod n$.
* The cosine function is periodic modulo $2\pi$, that is, $\cos(\theta + 2\pi) = \cos(\theta)$ for all $\theta\in\mathbb R$.
Can you combine these facts to come up with a proof of the desired result? | stackexchange-math | {
"answer_score": 7,
"question_score": 4,
"tags": "abstract algebra, trigonometry, rational numbers"
} |
shindig error: At least 1 ModulePrefs is required
I have Shindig 2.0.2 server running. When I'm trying to render the following local gadget spec XML:
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Calendar">
<Require feature="opensocial-0.7" />
</ModulePrefs>
<Content type="url" href='../../Base/content/calendar/index.html'>
</Content>
</Module>
I get this error:
> At least 1 ModulePrefs is required.
Does anyone knows this error?
Also when I run my server localy, there is no problem. The error occurs only when my app and Shindig are deployed on cloud (under https).
Thanks! | The problem was that Shindig got the SAML redirection HTML page so it could not be parsed correctly. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "opensocial, apache shindig"
} |
Is there any way to persist files for a web application using Amazon AWS without a full VM?
I would like to migrate an web application to Amazon AWS.
The application stores and retrieves small persistent data from a `content/` directory. I tried Amazon Elastic Beanstalk to deploy the application however it does not allow persistent storage.
The Amazon solution to use beanstalk is to create a s3 bucket and use Amazon APIs to store data.
I rather not modify our code and create total dependency to Amazon Services.
Is there any way to migrate my application **without** change the code to amazon services. I would like to do not create a full VM just to run the application. | A good way to persist data in AWS is Elastic File System, you can mount your folder "content". | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "asp.net, amazon web services, amazon s3, amazon ec2"
} |
rails skip records that are addressed by named scope
I have a scope which uses a where clause to narrow the results down to records where a specific parameter is defined.
In Post.rb
scope :nav, where( "priority IS NOT NULL" )
Im using this scope to populate the site navigation with specific Posts. However, the index controller action needs to omit these records. Is there a way I can use the same named scope to omit these records from my index action? Or do I need to write a second scope which is the inverse of the first?
def index
@posts = Post.order('created_at DESC')
end | In Post.rb
scope :nav, ->(not_null = true) { not_null ? where.not(priority: nil) : where(priority: nil) }
In controller:
def index
@posts = Post.order(created: :desc).nav(false)
end
Work in Rails 4. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, scope"
} |
Is it possible to write a getter that takes a parameter?
I've found two very strange pieces of code in PureMVC's documentation:
public function get resultEntry( index:int ) : SearchResultVO
{
return searchResultAC.getItemAt( index ) as SearchResultVO;
}
and bit later:
var item:SearchResultVO = searchProxy.resultEntry( 1 );
(found in [Best Practices [English]]( bottom of page 38 and top of page 39)
I've always thought that getters must not accept a parameter (and FDT indeed tells me that _"Parameters for getters are not allowed"_ ), so I wonder what's going on here.
Is that just an unfortunate typo (meant to be simply a normal function without the "get") or some hidden feature/voodoo? | Normally the only way to achieve this is as follows:
public function getResultEntry( index:int ) : SearchResultVO
{
return searchResultAC.getItemAt( index ) as SearchResultVO;
}
The reason is because **get** is reserved ActionScript keyword. It will in fact expose your function as a public property and expects a predefined format.
It occurs in both strict an non strict type checking modus, so I am guessing that it is a typo in the PureMVC documentation :)
I suggest that you write an email to Cliff Hall then :P
Cheers | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 4,
"tags": "actionscript 3, puremvc"
} |
Find the peak values from data
I plot the frequency on x-axis and intensity on y-axis via matplotlib.
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import argrelmax, argrelmin
data = np.loadtxt('pr736024.dat')
z=np.array(data[:,1])
y = (z-z.min())/(z.max()-z.min()) #for normalization
x = np.loadtxt('frq.txt')
plt.plot(x,y, linewidth = 0.2, color='black')
plt.plot(x,indexes, "o")
plt.show()
![enter image description here](
I want to get the intensity value at the peaks (there are 6 peaks which can be seen in plot). How can I achieve this? | This answer is an adaptation of my answer in here.
Here you have a numpythonic solution (which is much better than doing a loop explicitly).
You have to define a threshold where where above this value the maxima are detected, that in your case can be 0.2.
I use the roll function to shift the numbers +1 or -1 in the position. Also a "peak" is defined as a local maximum, where the previous and posterior number are smaller then the central value.
The full code is below:
import numpy as np
import matplotlib.pyplot as plt
# input signal
x = np.arange(1,100,1)
y = 0.3 * np.sin(t) + 0.7 * np.cos(2 * t) - 0.5 * np.sin(1.2 * t)
threshold = 0.2
# max
maxi = np.where(np.where([(y - np.roll(y,1) > 0) & (y - np.roll(y,-1) > 0)],y, 0)> threshold, y,np.nan) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, numpy, matplotlib"
} |
How to use jquery to bind ctrl+enter to ajax form submission
The following code will submit an ajax form when the user hits ctrl+enter while in the feedback input area. It works fine - but only once. I need to bind this function to the comment form so it persists and allows multiple submissions. In other words - the form is cleared and represented to the user after each submission. However, the following code only works for the first submission and thus ctrl+enter doesn't work for the second submission.
$('#comment_body').keydown(function(e) {
if (e.ctrlKey && e.keyCode === 13) {
return $('#comment_submit').trigger('submit');
}
});
I've tried .live and .bind but can't get the syntax right to allow resubmission.
Thanks | This does it. I need .live to get it to persist for future events. I just got the syntax wrong multiple times.
$('#comment_body').live('keydown', function(e) {
if (e.ctrlKey && e.keyCode === 13) {
$('#comment_submit').trigger('submit');
}
}); | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 5,
"tags": "javascript, jquery, ajax, forms"
} |
Testers unable to install application
I've sent my iphone application to my testers and all but one complain that the get error OxE8003FFE when they sync their devices. They are not able to install and run the application. I'm using an ad hoc distribution provisioning profile and all of the testers devices are included in the profile. I'm not sure how to proceed and would really appreciate any help you might be to give.
One more interesting bit of information: The program is a universal iPad/iPhone application. My testers are able to install it on their iPads but not their iPhones. | After some back and forth with DTS I managed to fix this issue.
The problem was that I was compiling for armv7 only which caused the installation to fail on armv6 machines.
Another interesting bit, the default universal project template and iphone projects converted to universal will compile for both architectures by default, this didn't happen for me bacause my project was initially an iPad only project which I converted manually (since there are no automatic tools for this) to be iPhone/iPad universal, this is the probable reason for this setting being incorrect in my project. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "iphone, ios provisioning"
} |
Sequencing logic per entity while threading in Biztalk
I have messages that have to be published to a JMS Queue. The messages are identified by an item id and the messages having the same item id should be published in a certain sequence.
I'm considering to use threads and worried that multiple threads would not care about the sequencing logic. Is it possible to run threads so that only one thread takes care of messages with the same item id? | You will probably need to enable the **Ordered delivery** on the send port to the JMS Queue and ensure that the messages for that port are published to the message box in the order you want them put onto the queue.
By enabling Ordered delivery you are basically making it into a single thread and that does have some performance implications, although they have improved on that in the latest versions of BizTalk. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "multithreading, biztalk"
} |
Where can I find a Bluetooth chip capable of shipping in bulk?
Why is it that places like Newegg can sell consumer Bluetooth products for less than $10, but the only Bluetooth modules I can find on Mouser or Digikey cost close to $20?
I am looking for the cheapest way to support bidirectional communication via Bluetooth SPP. Does anyone know why these chips are so expensive? | In mass production a BT chip costs less than 75 cents. The problem is none of the vendors will work with you, you need to find a module maker who can support you. In MP (Mass Production) you can reach to 5$ level with module including antenna etc. good luck.
The key vendors to look at are CSR and BRCM (Broadcom). We use a Taiwanese module maker with one of their solutions. APMComm is the vendor, there are tons of others just look around. | stackexchange-electronics | {
"answer_score": 2,
"question_score": 0,
"tags": "bluetooth"
} |
DDR3 RAM and speeds
I bought some computer parts to build my first system. The mobo was DOA and I RMAed it. They were supposed to send me a replacement but instead just refunded the money on CC. Um, ok, but I still need a mobo! So I decided I want to get a different mobo instead. I was looking at them and one I'm interested in says "Memory Standard: DDR3 2200/1333/1066/800." but the RAM I bought is DDR3 1600Mhz. Can I still use it with this mobo just at lower speeds? Since shipping and RMAing the board took forever I don't want to send another board back. If the processor matters I got a Core i7-920. | FWIW, I have DDR3 1600 which is running just fine at 1333. Including running a full set of memory tests for an extended period (3 or 4 days) when I built the system. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 1,
"tags": "memory, ddr3"
} |
C# selecting an image and drawing it in a panel
I have a simple list of filenames of (supported) images in a listbox. When I select a filename I want to have the image drawn in a panel (like a preview).
How do I access the panel to actually load the image? | Add this to the SelectedIndexChanged event handler of your listbox. You can find this by clicking on your listbox, looking in the properties pane, clicking on the lightning bolt and double clicking the blank space beside `SelectedIndexChanged`:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var currentImageLocation = listBox1.SelectedItem.ToString();
Image myImage = Image.FromFile(currentImageLocation);
panel1.BackgroundImage = myImage;
}
You obviously need to update the generic names above to the ID's of your listbox and panel | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, .net"
} |
Prove sum of $\cos(\pi/11)+\cos(3\pi/11)+...+\cos(9\pi/11)=1/2$ using Euler's formula
Prove that $$\cos(\pi/11)+\cos(3\pi/11)+\cos(5\pi/11)+\cos(7\pi/11)+\cos(9\pi/11)=1/2$$ using Euler's formula.
Everything I tried has failed so far.
Here is one thing I tried, but obviously didn't work. $$\Re e \\{e^{\frac{\pi}{11}i}(1+e^{\frac{2\pi}{11}i}+e^{\frac{4\pi}{11}i}+e^{\frac{6\pi}{11}i}+e^{\frac{8\pi}{11}i}) \\}=\frac{1}{2}$$ $$\Re e \\{e^{\frac{\pi}{11}i}(1+\sqrt[11]{e^{2\pi i}}+\sqrt[11]{e^{4\pi i}}+\sqrt[11]{e^{6\pi i}}+\sqrt[11]{e^{8\pi i}}) \\}=\frac{1}{2}$$ $$\Re e \\{e^{\frac{\pi}{11}i}(1+\sqrt[11]{1}+\sqrt[11]{1}+\sqrt[11]{1}+\sqrt[11]{1}) \\}=\frac{1}{2}$$ $$\Re e \\{5e^{\frac{\pi}{11}i} \\}=\frac{1}{2}$$ $$5\cos(\frac{\pi}{11})=\frac{1}{2}$$ Which isn't true :D
Thanks in advance | HINT:
First of all, $$e^x=1\iff x=2n\pi$$ where $n$ is some integer
$\sum_{r=0}^5\cos\frac{(2r+1)\pi}{11}$ =Re[$\sum_{r=0}^5\left(e^{\frac{\pi i}{11}}\right)^{2r+1}$]
Now $\sum_{r=0}^5\left(e^{\frac{\pi i}{11}}\right)^{2r+1}$ is a Geometric Series | stackexchange-math | {
"answer_score": 0,
"question_score": 1,
"tags": "trigonometry, power series"
} |
Redirect using mod_rewrite issue
I'm trying redirect all requests from `domain.com/sign-up/*`. to domain.com/sign-up/ In addition, I would like to know if my code can be improved, see below.
Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteRule ^sign-up/(.*)\.php$ public/register.php [NC]
RewriteRule ^sign-up/(.*) /sign-up/ [R]
RewriteRule ^sign-up/\??lang=([a-zA-Z][a-zA-Z][a-zA-Z])$ public/register.php?lang=$1 [NC]
RewriteRule ^sign-up/?$ public/register.php [NC,L]
Why no redirect takes place? | Try this, and let me know if it works. If not, please let me know for which URL it's not working.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteBase /
# sign-up/xxx.php -> public/register.php
RewriteRule ^sign-up/.*\.php$ public/register.php [L]
# sign-up/xxx -> /sign-up/
RewriteRule ^sign-up/.+ /sign-up/ [R=301,QSA,L]
# sign-up/?lang=xxx -> public/register.php?lang=xxx
RewriteCond %{QUERY_STRING} .*lang=([a-z]{3}).* [NC]
RewriteRule ^sign-up/$ public/register.php?lang=%1 [L,NC]
# /sign-up/ -> public/register.php
RewriteRule ^sign-up/?$ public/register.php [NC,L]
</IfModule> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "apache, mod rewrite"
} |
Arba'a Asar Ushlosh Meyot - mi yodeya?
## Who knows three hundred fourteen?
## ?ארבעה עשר ושלוש מאות - מי יודע
In the spirit of the song "Echad - mi yodeya", please post interesting and significant Jewish facts about the number 314.
Lazy gematria has to be stopped, lest it grow indefinitely.
Check out mi-yodeya-series for the previous three hundred thirteen entries in this ongoing series.
Please include sources for your information wherever possible, as with all other answers on this site. | According to Yalkut:
ר' ינאי אומר לא העבידו המצריים את ישראל אלא שעה אחת מיומו של הקב"ה - שמונים ושש שנה`
So 314, out of the promised 400, Am Yisrael was under the impression of the _Galus_ but not under hard oppression.
(From) | stackexchange-judaism | {
"answer_score": 7,
"question_score": 4,
"tags": "number, mi yodeya series"
} |
Regarding convergence of improper integral to be used in Analytic number theory
I am self studying Tom M Apostol Introduction to Analytic number theory.
> In theorem 4.12 Apostol uses that improper integral $\int_x^{\infty} \frac {1} { t (logt) ^2 } \ , dt $ converges, x>2 .
I tried using comparison test by comparing with $t^{3/2} $ and $ t^2 $ but I don't get non-zero finite limit of there ratios as t tends to $\infty $ .
Can someone please tell how to prove this integral to be convergent . | The integrand has a simple antiderivative:
$$\int_x^{\infty} \frac{dt}{t (\log{t})^2} = \left [ -\frac1{\log{t}} \right ]_x^{\infty} = \frac1{\log{x}}$$
Note that the integral converges because $\log{t} \to \infty$ as $t \to \infty$. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "number theory, improper integrals, analytic number theory"
} |
Upload File Size Limit: Symfony Admin Generator Module
I have form created by the admin generator in the backend of a website. It allows the upload of a video to the site.
It works fine but strangely, the upload fails for files of 10mb or over. However, I have not set any file limits in my form.
Are there Symfony/PHP/Apache/web browser settings regarding this type of behaviour that I can look into?
Or is there a way I can inform Symfony that I'd like to permit larger files? | Even I haven't ever worked with Symfony I expect the problem due to limitations on your Web-Server.
If you have the possibility to edit or add your .htaccess file then the following line of code will probably help you:
php_value upload_max_filesize 100M
the 100M in example is for 100 Megabyte. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, apache, file, upload, symfony1"
} |
Finding a limit or solving with a limit?
I have a complicated equation that has a lot of terms with squareroots. I am simplifying that complicated function with assumption of that x << y , so that later I can use that solution to solve it for x. Here is how the equation looks like approximately (just for illustration purpose):
$ f(x)=\sqrt{y^2 - (x + z)^2} + x*cos(\phi)+x+z$
My manual answer is:
$f(x)=\sqrt{y^2 - z^2} + x*cos(\phi)+x+z$
I tried in Mathematica but it does not solves it. I am doing this limit to make f(x) simpler so that Mathematica can solve it for f(x)=0.
> Limit[f,x/y -> 0]
The limit does not work so I did not continue with solve. I also tried,
> Solve[f==0 && x/y->0,x] | If you want to do this in a mathematically consistent manner you need to specify exactly what is the small parameter that you expand with. It seems from your question that you want to expand assuming the ratio $x/y$ is small. You can do that by defining `ϵ=x/y` and replacing that throughout your expression:
f = Sqrt[y^2 - (x + z)^2] + x Cos[φ] + x + z
f2 = f/. x-> ϵ y
Then you can expand consistently to linear order in `ϵ`:
f3=Normal@Series[f2,{ϵ,0,1}]
and finally replace back to eliminate `ϵ`:
f4=Simplify[f3 /. ϵ -> x/y]
Note, however, that the result is different from your "manual" result, which is mathematically inconsistent.
Finally, you can solve using `Solve[f4==0,x]`. | stackexchange-mathematica | {
"answer_score": 4,
"question_score": 0,
"tags": "equation solving, calculus and analysis, assumptions"
} |
C# ODP.NET Load file or assembly
I recently started testing on a C# (4.0) app that uses ODP.NET (Oracle.DataAccess 4.112.3)
I set this project to target any platform and publish the app.
When I run the program on the client machine I receive:
Could not load file or assembly 'Oracle.DataAccess, Version=4.112.3.0,Culture=neutral,
PublicKeyToken=89b483f429c47342' or one of its dependencies. An attempt was made to load
a program with an incorrect format.
Like I said I've targeted 'Any CPU' and I've also embedded the Oracle.DataAccess assembly with the app.
I get this error on machines that have the Oracle client installed as well as machines that do not.
Any help is appreciated. | > Like I said I've targeted 'Any CPU'
This is likely the problem.
The Oracle.DataAccess has separate versions for 32bit and 64bit systems. If you are developing on a 32bit machine, and then deploying on a 64bit OS, you will receive this message.
You could easily work around this by building your application to target x86, and deploying the 32bit version of the data access components. | stackexchange-stackoverflow | {
"answer_score": 18,
"question_score": 11,
"tags": "c#, .net, oracle, odp.net"
} |
Casting character varying field into a date
I have two tables,
details
id integer primary key
onsetdate Date
questionnaires
id integer primary key
patient_id integer foreign key
questdate Character Varying
Is it possible to make a SELECT statement that performs a JOIN on these two tables, ordering by the earliest date taken from a comparision of onsetdate and questdate (is it possible for example to cast the questdate into a Date field to do this?)
Typical format for questdate is "2009-04-22"
The actual tables have an encyrpted BYTEA field for the onsetdate - but I'll leave that part until later (the application is written in RoR using 'ezcrypto' to encrypt the BYTEA field). | something like
SELECT...
FROM details d
JOIN quesionnaires q ON d.id=q.id
ORDER BY LEAST (decrypt_me(onsetdate), questdate::DATE)
maybe? i'm not sure about the meaning of 'id', if you want to join by it or something else
By the way, you can leave out the explicit cast, it's in ISO format after all. I guess you know what to use in place of decrypt_me() | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "postgresql"
} |
Please help me solve this complex integral.
$$\oint_C \frac{\cos(z-a)}{(z-a)}\mathrm{d}z$$
Such that $a\in \Bbb R^2$ and $C$ is a single closed curved defined by $|z-a|=\frac{|a|}{2}$
Here $z=x+iy$ is a complex number. Please solve the above integral. Thanks | Let $$f(z) = \cos(z - a)$$
Then you use the Cauchy Integral Formula:
$$f(z_0) = \frac1{2 \pi i}\oint_C \frac{f(z)}{(z-z_0)}dz$$
Let $z_0 = a$. Therefore this becomes:
$$f(a)=\frac1{2 \pi i}\oint_C \frac{\cos(z-a)}{(z-a)}dz = \cos(a-a) = \cos(0) = 1$$
Rearranging for your integral:
$$\oint_C \frac{\cos(z-a)}{(z-a)}dz = 2 \pi i \cos(0) = 2 \pi i$$ | stackexchange-math | {
"answer_score": -1,
"question_score": 0,
"tags": "integration, complex analysis"
} |
jqGrid HOWTO: Get the value of specific cell upon double click on row
I'd like to be able to double click on any part of a given row and open a new html page (based on specific cell value/content). Basically I have all NY counties, each in one row:
County - City - State
Manhatan - New York - NY
Brooklyn - New York - NY
Bronx - New York - NY
Westchester - New York - NY
etc.
I need to be able to get the cell value in the County column and use it to run a function. Example: if I double click on the first row, that should open a new html page about Manhattan. I tried some answers that were posted for a kind of similar question (about editing) but they didn't work. | Ondoubleclick of a row in grid call a function.
Use the below lone of code to get the selected row id (primary key of row) and then get the row contents using that id and then get the column content using the column name. Once you have the country name, open whatever page you want based on country.
selId = jQuery("#myGrid").jqGrid('getGridParam','selarrrow');
alert("Selected Id is ->"+selId);
var data = jQuery("#myGrid").jqGrid('getRowData',selId);
alert("Status ->"+data.country); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, jqgrid"
} |
View Weblogic Logs from Console
We deployed an app in a remote weblogic server. They gave us access to the console of the weblogic. But due to security reasons, we are not allowed to remote connect to the server and view the files.
Question, is there a way from the weblogic console for us to see the logs generated by my application? I am actually investigating a problem and I think a log from the weblogic can help me see the reason.
Thanks. | Yes you can view the Weblogic logs from the console
See the Oracle docs on how to do this. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "weblogic11g"
} |
Optional Character in PHP Regular Expression Replace
I have data in this format coming from a database...
BUS 101S Business and Society
or
BUS 101 Business and Society
Notice the optional "S" character (which can be any uppercase character)
I need to replace the "BUS 101S" part with null and here is what I have come up with...
$value = "BUS 101S Business and Society";
$sub = substr($value, 0, 3); // Gives me "BUS"
$num = substr($value, 4, 3); // Gives me "101"
$new_value = preg_replace("/$sub $num"."[A-Z]?/", null, $value);
The value of `$new_value` now contains `S Business and Society`. So I'm close, Just need it to replace the optional single uppercase character as well. Any ideas? | Assuming the pattern is 3 uppercase letters, 3 numbers and then an optional uppercase letter, just use a single `preg_match`:
$new = preg_replace('/^[A-Z]{3} \d{3}[A-Z]?/', '', $old);
The `^` will only match at the beginning of a line/string. The `{3}` means "match the preceding token 3 times exactly". The `?` means "match the preceding token zero or one times" | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 4,
"tags": "php, regex"
} |
URL CNAME Limitation?
We have a domain CNAME pointing to our Amazon load balancer, however the URL's that Amazon provides are longer than 32 characters and one of our clients DNS providers limits CNAME's to 32 characters.
Aside from moving to a diff DNS, any suggestions to get around this? HTTP redirect not an option for the URL either....
Cheers, Chad | I assume this is 1and1? I don't know of any workaround that doesn't involve using a different DNS provider. I don't know of anything in the RFC or related specs that call out a 32 char limit. Have you asked the ISP with the limit why it's 32 chars? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "dns, cname, amazon web services"
} |
Iterate the input step over different number of files in Pentaho
I have a `get file names` step with a Regular expression that gets 4 csv files. After that I have a `text file input` step which sets the fields of the csv, and read these files.
Once this step is completed a `Table output` step is executed.
The problem is that the `text file input` seems to read all 4 files in a single statement, so the `table output` statement inserts the rows of the 4 files. So my output table has 20 rows (5 per each file)
The expected beahivour is read one file, insert the 5 rows of the file in the output table and execute sql script which moves this table to a final table and truncate temp table. Now repeat the process for the second, third and last file.
The temporary table is deleted in every step of load a file, but final table not, it is incremental.
How can I do that in pentaho? | Change your current job to a subjob that executes once for each incoming record.
In the new main job you need:
* a transformation that runs Get Filenames linking to Copy Rows to Result
* a Job entry with your current job. Configure it to execute for each row.
In the subjob you have to replace Get Filenames with Get Rows from Result and reconfigure the field that contains the filename. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "pentaho, pentaho spoon, pentaho data integration"
} |
In GitAhead, is there a way to delete a remote branch when I already deleted the corresponding local branch?
I've already deleted a local branch without deleting its upstream branch on a GitHub. Is there a way to delete the remote branch in a GitAhead?
In Sourcetree you just right click on the remote branch and choose _delete_. | Unfortunately no, GitAhead doesn't have an easy way to push a delete except for the little convenience checkmark when you delete the local branch. You would have to resort to the command line or doing it on your remote host. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "gitahead"
} |
Unity generic overload of Resolve
When I look at version 3.0 of `IUnityContainer` it only has:
object Resolve(Type t, string name, params ResolverOverride[] resolverOverrides);
Where do I find the generic version so I can do:
container.Reslove < IDoStuff>()
Latest version on _nuget_ hasn't got it or what am I missing? | `IUnityContainer.Resolve<T>()` is an extension method. Add
using Microsoft.Practices.Unity;
to the source file where you want to call `Resolve<T>()` | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "c#, .net, dependency injection, unity container"
} |
data structure bind conversion c++
I think this is a classical question but I did not manage to find a clear answer (maybe my keywords are not the good one).
Let's say I have a structure of the form (this is a recurrent situation in my programming practice):
std::vector< pair<unsigned int, double> > pairAgeSize;
and I have a function of the form :
double getMean(const std::vector<double> & sample);
What is the "best" way to call getMean on the elements [pairAgeSize[0].first,...,pairAgeSize[n].first] ? or even on [pairAgeSize[0].second,...,pairAgeSize[n].second] ?
More generally, is there any pragmatical practice rules that can prevent this kind of situation ? | `getMean` should take iterators as inputs to it to be fully general, and you should write a custom iterator that will return `pair.first`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "c++, binding, type conversion"
} |
Conflicting steps on how to solve $x'=Ax$.
I was taught that when we had a 2 dimensional system of the form $$x'=Ax$$
With repeated eigenvalues, I'd need to find an eigenvector, $v_1$ and another vector such that:
$$(A-\lambda I)v_2=v_1$$
The solution would then be given by $x=c_1e^{\lambda t}+c_2e^{\lambda t}(v_1 t+v_2)$.
But today I encountered an exercise in which we had $A=2I$. And thus, the last equation can't be satisfied unless $v_1=0$, which shouldn't happen as $v_1$ is supposed to be an eigenvector.
What's wrong? How do I solve this? | You get the solution with the $t$ if you have a _defective_ eigenvalue. In general these are eigenvalues whose algebraic multiplicity is strictly larger than their geometric multiplicity. You get that one in particular if you have an eigenvalue with algebraic multiplicity $2$ and geometric multiplicity $1$.
However, it is possible to have an eigenvalue of algebraic multiplicity strictly higher than $1$ which is still not defective. In this case you still get essentially the same solution as when the eigenvalues are distinct. In your case where $A=2I_2$, the solution is $c_1 e^{2t} v_1 + c_2 e^{2t} v_2$, where $v_1,v_2$ are two linearly independent eigenvectors for the eigenvalue $2$.
However, in 2D, this can only happen if $A$ is a multiple of the identity. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra, ordinary differential equations"
} |
Regular expression from 00001 to 99999
I'm using regex and I want the number from `00001` to `99999`. It should have 5 digits.
I know I can use `[0-9]{5}`, but then I have the number `00000`, but it should begin at `00001`. | (?!00000)[0-9]{5}
Prefixing `(?!00000)` ensures you don't match it; it's called negative lookahead. Live demo here. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, regex"
} |
Файлы в python. Количество строк в файле
Значит у меня есть код:
studentsfile = open('dataset_3363_4.txt')
q = 0
for i in studentsfile:
q+=1 #посчитали количество строк в файле
lines = studentsfile.readlines()
for k in range(0,q):
print(lines[k].split(';'))
studentsfile.close()
В нем мне нужно посчитать кол-во строк и в дальнейшем это использовать. Но второй цикл _for_ не работает и выдает ошибку:
File "students.py", line 9, in <module>
print(lines[k].split(';'))
IndexError: list index out of range
Еще одно НО в том, что этот цикл работает если убрать счетчик строк. Не понимаю в чем дело. Помогите. | В этой строке вы из файла вычитали все строки из файла и указатель позиции в файле достиг конца:
for i in studentsfile:
Тут вы снова обращаетесь к тому же файловому объекта, чей указатель в конце, поэтому `lines` будет пустым
lines = studentsfile.readlines()
* * *
Решения на месте. Перед `.readlines()`:
* Переоткрыть файл, снова вызвав `open`: `studentsfile = open('dataset_3363_4.txt')`
* Или переместить указатель в начало: `studentsfile.seek(0)`
* * *
**PS.**
Весь ваш код можно описать так:
with open('dataset_3363_4.txt') as f:
for line in f.readlines():
print(line.split(';'))
Или так:
with open('dataset_3363_4.txt') as f:
for line in f:
print(line.split(';')) | stackexchange-ru_stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "python, файлы"
} |
Does JVM loads all used classes when loading a particular class?
When JVM loads a class A, does it load all of the classes used within A?
And I'm wondering if import declarations are matter somehow to the loading process?
The link to JLS would be appreciated. | Import and class loading are unrelated. The former just saves typing: it allows you to use the short class name rather than the fully-resolved class name in your code.
Classes are loaded by the JVM when they're used for the first time. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "java, classloader, jls"
} |
CodeIgniter giving a 404 not found on public server only
**Description**
I have a site "searchnwork.com". It uses CodeIgniter. Every page **except** the home page loads fine.
If you go to searchnwork.com, it shows the CI 404 error page.
If you go to searchnwork.com/index.php/users, it shows the UserSignUpController page, which is good.
If I set the `$route['404_override'] = 'UserSignUpController'`, I still get a 404.
Everything works fine on my local server.
* * *
**Question**
Why am I getting a 404 for searchnwork.com despite the override?
Why am I getting a 404 for searchnwork.com in the first place instead of my default controller?
* * *
**Code**
$route['users'] = "UserSignUpController"; // This loads fine.
$route['default_controller'] = "UserSignUpController"; // This gives a 404...
$route['404_override'] = 'UserSignUpController'; // This doesn't redirect... | Case sensitive file names.
On MAMP it doesn't seem to care about capitalization. When I uploaded to an actual linux server, CapitalizedFileNames started to fail, since it only searchs for lowercasefilenames. I guess you should use underscores.
Weird that it only fails for index.php. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "codeigniter, codeigniter 2"
} |
Making Ext Js Ext.Tip resizable
I have a UI tip component in my code, I want to make this component resizable
I am currently using Ext Js 3.2 library | You can bind a resizer to it:
var resizer = new Ext.Resizable(tip.id, {
handles: 'all',
pinned: false
});
resizer.on('resize', function() {
tip.syncShadow();
});
Unfortunately, it seems that the tip component has not been developed with arbitrary sizing in mind, so you'll have to hack the CSS... | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "extjs, extjs3"
} |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 45