INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Where to find the tex web output documenting the original tex implementation in pascal
I recently read a blog post on literate programming and that tex was written using this paradigm. So I thought it might be a good idea to read the original tex program's source, by Knuth himself (the pascal version) in the literal programming style. However, having downloaded the distribution, I only find the raw file `tex.web` in the directory, and the tooling available via package managers (`ctangle`, `cweb`) only works with C files.
So I was wondering whether a PDF file with the literate programming output was available on line, yet an hour of searching online did not yield a result. So: Is there the literate programming output for humans available for the tex processor?
|
If you have `tex.web`, you can do
weave tex.web
and then
tex tex.tex
(or `pdftex`). This is the first page:
, или apt-get (Debian, Ubuntu), можно воспользоваться следующими командами, чтобы разрешить все зависимости:
Команда:
apt-get install libcurl4-gnutls-dev libexpat1-dev gettext \
libz-dev libssl-dev

df_new=df_old
df_new['c']=[5,6]
print('Old:')
print(df_old)
print('New:')
print(df_new)
Output:
Old:
a b c
0 1 3 5
1 2 4 6
New:
a b c
0 1 3 5
1 2 4 6
In fact, I need to preserve the original dataframe as it was:
a b
0 1 3
1 2 4
Thanks in advance,
|
Use `assign` which creates a copy of the old dataframe:
df_old = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
df_new = df_old.assign(c=[5,6])
print(df_old)
print(df_new)
Output:
a b
0 1 3
1 2 4
a b c
0 1 3 5
1 2 4 6
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "python 3.x, pandas, dataframe"
}
|
What is the best way to use IndexedDB?
What is the best way to use IndexedDB with ease?
Some library, than allow to use IndexedDB like locaLStorage.
|
Try to use localForage library from Mozilla.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "indexeddb"
}
|
Why are my two tuples containing strings, created the same way, not equal?
I'm compiling the following program using Microsoft Visual C++, as a C++20 program:
#include <iostream>
#include <tuple>
int main()
{
auto t1 = std::make_tuple("one", "two", "three");
auto t2 = std::make_tuple("one", "two", "three");
std::cout << "(t1 == t2) is " << std::boolalpha << (t1 == t2) << "\n";
std::cout << "(t1 != t2) is " << std::boolalpha << (t1 != t2) << "\n";
return 0;
}
When I run it, I see the following output:
(t1 == t2) is false
(t1 != t2) is true
The tuples are identical, so why does it have wrong comparison results? How do I fix this?
|
You are comparing pointers to buffers of characters, not strings.
Sometimes the compiler will turn two different `"one"`s into the same buffer, sometimes it will not.
In your case, it isn't. Probably a debug build.
Add `#include <string_view>`, then
using namespace std::literals;
auto t1 = std::make_tuple("one"sv, "two"sv, "three"sv);
auto t2 = std::make_tuple("one"sv, "two"sv, "three"sv);
and you'll get what you expect. (In pre-c++17 compilers, use `<string>` and `""s` instead of `<string_view>` and `""sv`).
|
stackexchange-stackoverflow
|
{
"answer_score": 65,
"question_score": 55,
"tags": "c++, visual c++, tuples, string literals"
}
|
Pointers and Reference issue in LuaJIT FFI
I have this function (written in C++ here):
GameSession *theSession = NULL;
...
...
startSesion(&theSession)
I have managed to get this running properly using the LuaJIT FFI here:
local session = ffi.new("GameSession*[1]", {})
myDLL.startSession(session))
However, I now need this function in LuaJIT (written in C++ here):
setTimeout(theSession, 3000);
How can this be achived in LuaJIT? Basically how can I declare theSession* from theSession** using the FFI?
|
As per FFI Tutorial, you dereference pointers like this:
theSession[0];
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, c, lua, ffi, luajit"
}
|
Clickhouse: how to find indexed field in clickhouse SQL?
I have existing table in ClickHouse. I want to find which field is an index field. How do I do it?
|
You can use `SHOW CREATE TABLE my_table;` to see the primary key (index) and other settings.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "sql, indexing, clickhouse"
}
|
php browser back after post
I have php page where I used a form to submit messaage. It submits to itself :
action="<? php echo $_SERVER['PHP_SELF'];?>"
Then it sends email, and I have a javascript function that uses jnotify, to alert whether message is sent successfully or not. This function checks if php variable $sent=='yes' then notify about sucessful message else notify about error.
The problem is that when user sends message and goes to another page and comes back by using browsers back button, it is displaying notification. I want it to show notification once only and forget about notification when browsers back or refresh used.
What is the best solution for it?
|
Try something like this:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (form_is_valid()) {
$_SESSION['form_success'] = true;
} else {
$_SESSION['form_success'] = false;
}
header('Location: ' . $_SERVER['PHP_SELF'];
exit;
} else if (isset($_SESSION['form_success'])) {
if ($_SESSION['form_success'])) {
// insert success javascript
} else {
// insert failure javascript
}
unset($_SESSION['form_success']);
}
// display_form
This should make it so they only see the success/failure message once, and if they use the back button at a later time, they will not receive a warning about re-submitting post data, and they also won't see a success/failure message twice. The only time that javascript should show is if they just submitted the form in the last request.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, browser, notifications, back"
}
|
UILocalNotification - mutable copying
**Overview:**
* I am copying an instance of `UILocalNotification` and making changes to it to the newly created instance
* Then I schedule the newly created instance of `UILocalNotification`
**How I am copying**
* I am copying the instance of `UILocalNotification` by invoking the method `copy`
**Question**
1. Am I doing the correct thing or should I be using a different method to create a mutable copy. (`mutableCopy` is not implemented for `UILocalNotification`
2. Does copy actually do a mutable copy ?
3. Is it necessary to create a copy at all, will `scheduleLocalNotification:` create a new copy anyway ?
|
1. Yes, `copy`'s fine.
2. `mutableCopy` generally applies to types which distinguish immutable and mutable flavors. since the type does not make that distinction, `copy` is 'mutable'.
3. typically, you would assume that you should need to copy the argument. in this case, the docs specify that `scheduleLocalNotification:` creates a copy of the parameter. explicitly copying is not strictly necessary.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "ios, uilocalnotification, nscopying"
}
|
Changing Key (PK, FK) properties in DROP/Add column statements
I want to change a table by adding a column. So far nothing to see here, BUT I would like to make this column part of a composite key, i.e., I now have a layout
table_name( Field_1 datatype PK, Field_2 datatype,....)
and I want the inserted column, say Field_k to be part of a PK jointly with the existing single-field PK.
I haven't found any source for how to do this or for whether it is possible or not. Any advice, please?
|
You need to drop the FKs that reference it, then drop the PK and re-create it, then re-create the FK. There's no magic syntax for this, but you can get some ideas here for how to generate the drop/create scripts for the FKs:
* Why dropping all foreign keys from a script is not working?
> would I get a warning if I am (unknowingly, of course) violating some constraints in the process, i.e., if I forget to drop some referenced table? Just curious as to how SQL server handles integrity/constraint violations.
You won't be able to drop the PK while any FK still references it. And of course you won't be able to re-create the FK until those other tables also have a column that can fill in for the new column you're adding to the PK.
|
stackexchange-dba
|
{
"answer_score": 6,
"question_score": 1,
"tags": "sql server, database design, foreign key, alter table, ddl"
}
|
Reading textfile parsing rows into a Datatable
I want to read a text file and parse each row into a datable.
The way I'd like the data stored in datatable is with the type for each column set as well i.e. int, varchar, date etc.
DataTable data = new DataTable();
data.Columns.Add("code", typeof(int));
data.Columns.Add("description", typeof(string));
data.Columns.Add("value", typeof(decimal));
but then when I am reading the textfile with columns tab delimited, how could I ensure the correct columns in the text file go into the right columns in the datatable.
Because my ultimate aim is to get this datatable into a sql server table with the same columns and types using sqlbulkcopy.
|
Don't reinvent the wheel, use an available CSV-parser like this.
DataTable data = new DataTable("CSV");
var fileInfo = new System.IO.FileInfo("Path");
using (var reader = new System.IO.StreamReader(fileInfo.FullName, Encoding.Default))
{
// use reader.ReadLine(); to skip all lines but header+data
Char quotingCharacter = '\0';//'"';
Char escapeCharacter = quotingCharacter;
using (var csv = new CsvReader(reader, true, '\t', quotingCharacter, escapeCharacter, '\0', ValueTrimmingOptions.All))
{
csv.MissingFieldAction = MissingFieldAction.ParseError;
csv.DefaultParseErrorAction = ParseErrorAction.RaiseEvent;
//csv.ParseError += csv_ParseError;
csv.SkipEmptyLines = true;
// load into DataTable
data.Load(csv, LoadOption.OverwriteChanges, csvTable_FillError);
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, datatable"
}
|
How does ReflectionFunction's isDeprecated work?
I'm trying to use the following function to loop through loaded files and find depreciated functions.
//loads all files
include dirname(__FILE__) . '/loader.php';
$functions = get_defined_functions();
foreach ($functions['user'] as $func) {
$rf = new ReflectionFunction('$func');
var_dump($rf->isDeprecated());
}
Some functions have markup like the following, yet it's still return `false`. In fact every single function returns `false` yet there are a lot with markup stating `@deprecated`.
**
*
* @since 0.71
* @deprecated 1.5.1
* @deprecated Use get_post()
*
* @param int $postid
* @return array
*/
ref: <
|
`ReflectionFunction::isDeprecated` does not check documentation comments; it only checks an internal flag that can be set by PHP extensions on the functions they expose.
For example, here is the part of the source for the `ereg` extension where its functions are declared and marked as deprecated (the `DEP` part in `PHP_DEP_FE` stands for "deprecated").
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "php, reflection"
}
|
Subversion / Tortoise / asp.net - Ignore and Non-versioned
I'm probably reading too much into ignore, but other than not showing up in the list when you commit, are there any other feature/benefits associated with ignoring a file?
|
It also doesn't clutter your `svn status` list. But anyway, not commiting files to the repo that don't need to be versioned (e.g. because they are created by the application, or they are settings files) is a pretty useful feature by itself, I'd think.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "asp.net, svn, version control, tortoisesvn"
}
|
Can't see cursor in 13.10
I'm trying out Ubuntu 13.10 but I can't see the cursor.
Can anybody help me? I'm a total newbie in the whole Linux thing and I would like some help.
|
I had the same problem and for me this command:
gsettings set org.gnome.settings-daemon.plugins.cursor active false
made the trick.
To actually type it without a working mouse, type `ctrl`-`alt`-`t` \--- you should have a (focused) terminal where you can type in.
The main reference is here: <
|
stackexchange-askubuntu
|
{
"answer_score": 4,
"question_score": 5,
"tags": "mouse, cursor"
}
|
JQuery append to map pane
I'm switching one of my projects over to use googles maps api v3 from v2.
In v2 I had a div appended to the map pane with the following code:
$("#marker_popup").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));
Is there any simple way to do that with v3? I've been searching around and I've found some things relating to implementing draw and onAdd, but I figure there has to be an easier way to do it than that.
|
Have a look at the answer to this question (and the corresponding v3 API documentation): google maps v3 translate map.getPane(G_MAP_FLOAT_SHADOW_PANE)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, jquery, google maps, google maps api 3"
}
|
Overwrite initial value from redux-form
I am initializing values in Field using initialValues. Although I would like to overwrite one of the Field with another defaul value. Is this possible? I was trying with defaultValue etc but I doesnt work. This is the part of code I want to change:
<Field
type="text"
name={`${some}.url`}
component={renderField}
label="URL"
defaultValue={some.url + ':' + some.port}
/>
Its initialized with url, but I would like to change it to url:port
|
Before passing `initialValues` prop down to your `redux-form` component, you can modify it.
**Something like that:**
const mapStateToProps = state => ({
// Here's how to set a default value and overwrite the API initial data.
// Let's say your form is editing an User.
// And if the User, returned by the API, doesn't have a name,
// then we set a default value.
initialValues: {...state.user, name: state.user.name || 'Default name'}
)}
// `connect` is part of `react-redux`.
// If you don't use `react-redux`, then just modify the `initialValues`
// before passing it down to the form.
export default connect(mapStateToProps)(reduxForm({
form: 'formName',
})(Component))
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "reactjs, redux form"
}
|
Get last <li> element from a string
I have a string variable that contains a lot of HTML markup and I want to get the last `<li>` element from it. Im using something like:
$markup = "<body><div><li id='first'>One</li><li id='second'>Two</li><li id='third'>Three</li></div></body>";
preg_match('#<li(.*?)>(.*)</li>#ims', $markup, $matches);
$lis = "<li ".$matches[1].">".$matches[2]."</li>";
$total = explode("</li>",$lis);
$num = count($total)-2;
echo $total[$num]."</li>";
This works and I get the last `<li>` element printed. But I cant understand why I have to subtract the last 2 indexes of the array `$total`. Normally I would only subtract the last index since counting starts on index 0. What im i missing?
Is there a better way of getting the last `<li>` element from the string?
|
HTML is not regular, and so can't be parsed with a regular expression. Use a proper HTML parser.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "php, html"
}
|
Checking if a download link is working without downloading the file
Is there a way in Javascript (and jQuery) to check if a URL is status 200 (specifically not 404) without downloading it's contents if it is in fact status 200?
For example, I want to check if a download link to a video works before executing some code. The issue when I use `$.ajax()` is that when the link does in fact work, it will only notify me AFTER the download has finished. In a way is there a way to just "ping" the url to see if it works without getting it's contents?
|
You can try a HEAD request, which should accomplish what you are trying to do:
jQuery.ajax({type: "HEAD", url: "
This type of request is mainly used by browsers to check cache validity, but it also should work here.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 4,
"tags": "javascript, jquery, ajax"
}
|
What's the difference between differences? 差 and 違い
What's the difference between and ? When would I use each?
Which (if either) would I use for describing the difference between something like sample data and the best fitting equation?
|
`` simply means "difference". `` means difference in the sense of a margin or gap, and seems to relate to things that are calculable.
> []{} → Margin of error
> []{} → Difference in time - ( → Jet lag)
It seems like you could replace most instances of `` with ``, but not the other way around. `` is definitely more appropriate when talking about sample data, etc.
However, there might be times when the two have distinct meanings. For example, say you have a boy who is 10 years old, and another who is 20. `` would be "10 years", but `` might describe how the characteristics of their ages differs; like "10-year-olds have more energy, but 20-year-olds are smarter." Not sure if this is correct, but seems different to me.
|
stackexchange-japanese
|
{
"answer_score": 11,
"question_score": 11,
"tags": "kanji, word choice"
}
|
How to calculate number of days in each month in php
need to calculate the number of days from current date to 27th of each month in PHP In below code, it's calculating correctly for current month but if the current date is 28th it should calculate for next month.
$year = date("y");
$month = date("m");
$day = '27';
$current_date = new DateTime(date('Y-m-d'), new DateTimeZone('Asia/Dhaka'));
$end_date = new DateTime("$year-$month-$day", new DateTimeZone('Asia/Dhaka'));
$interval = $current_date->diff($end_date);
echo $interval->format('%a day(s)');
|
I wrote this script quick, because I don't have the time to test it yet.
**EDIT:**
$day = 27;
$today = date('d');
if($today < $day){
$math = $day - $today;
echo "There are " . $math . " days left until the 27th.";
} else {
$diff = date('t') - $today;
$math = $diff + $day;
echo "There are " . $math . " days left until the 27th of the next month.";
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 5,
"tags": "php"
}
|
Intersection of a sequence of closed intervals
Is it possible to have a sequence of bounded closed intervals $I_{1},I_{2},...$ which are not necessarily nested, such that $$\bigcap_{n=1}^{N}I_{n}\neq\emptyset$$ for every $N\in \mathbb{N}$ and $$\bigcap_{n=1}^{\infty}I_{n}=\emptyset$$
|
For completeness, the OP (originally) did not specify if some $I_n$ is compact. If some $I_n$ is compact, see Jose's answer.
Otherwise, $$ I_n=[n,\infty) $$ is a set of closed intervals satisfying the given condition since $$ \bigcap_{n=1}^NI_n=I_N\not=\emptyset, $$ but whose intersection is empty.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "real analysis, proof writing"
}
|
Add a class to a navigation item once it is selected
I have navigation set up like so:
<ul class="nav nav-pills">
<li><a href="/questions/all">All</a></li>
<li><a href="/questions/popular">Popular</a></li>
<li><a href="/questions/fun">Fun</a></li>
</ul>
When one of these is clicked, it maps to my Sinatra route (i.e. `get '/questions/:filter' do...`). Clicking on any of them updates the page, but they all still use the same `.erb` view.
I'm trying to figure out how I can apply the class "`active`" to the `<li>` navigation item that is currently being viewed. This way, the nav item will be highlighted so users will know what view they are on (without having to look at the actual URL).
Any help would be much appreciated. I have access jQuery if needed.
|
You can use the `window.location.pathname` variable to select the anchor tag.
$('a[href="' + window.location.pathname + '"]').addClass('active')
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "javascript, jquery, css, sinatra"
}
|
gitignore not working - want to ignore everything but gitignore file to keep an 'empty' directory
I have a `.gitignore` file in a few directories (ex. `log/`) with the following contents:
* " Ignore everything in this directory
!.gitignore " Except this file
Nonetheless, if there is a file in that directory, `git status` shows it to me saying it's new but untracked.
# On branch master
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# log/blah.log
nothing added to commit but untracked files present (use "git add" to track)
I have found other posts on stackoverflow suggesting putting a comment on the first line and various other forms or random voodoo, but nothing has worked.
Simply, I want a `tmp/` and `log/` directory to exist in my repo, but empty. I don't want anyone to be harassed to add their log and tmp files to these directories.
|
Are you expecting the double-quote to act like a comment in your `.gitignore` file? You've got this...
* " Ignore everything in this directory
!.gitignore " Except this file
...but that's doing what you want. If you replace it with simply:
*
!.gitignore
It will work just fine. Watch:
$ ls -A
dir1 .git
$ ls -A dir1
.gitignore
$ cat dir1/.gitignore
*
!.gitignore
$ git status
# On branch master
nothing to commit (working directory clean)
$ touch dir1/file{1,2,3}
$ ls -A dir1
file1 file2 file3 .gitignore
$ git status
# On branch master
nothing to commit (working directory clean)
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "git, gitignore"
}
|
C++ Double Linked List, should I delete the nodes after dynamically allocating them?
void addEnd(T data) {
if (head == NULL) {
Node<T> *temp = new Node<T>(data);
head = temp;
tail = temp;
temp = NULL;
delete temp;
++size;
} else {
Node<T> *temp = new Node<T>(data);
tail->LinkToNext(temp);
temp->LinkToPrev(tail);
tail = temp;
temp = NULL;
delete temp;
++size;
}
}
In the addEnd function above, should I delete temp after I used it to allocate new Node on heap because it may cause memory leak or it doesn't matter.
|
You must not delete the newly created node in the `addEnd` function because it will be used later. The nodes should be deleted when the list is thrown away. (maybe in the destructor and/or something like `clear()` function).
Also note that the `delete temp;` in your code is meaningless (no gain, no harm) because `temp` is set to `NULL` before that and `delete NULL;` is defined to do nothing.
The variable `temp` itself is typically allocated on the stack and automatically deleted on returning from the function, so you need not delete it explicitly.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c++, memory management, memory leaks, linked list"
}
|
Sinch, is there any limitation on instant messages?
Is there any limitation on Sinch instant messaging, e.g. total size, frequency? Can I send json?
Besides, how instant is it? is it implemented in websocket, or webRTC, or hybrid? thanks!
|
We recommend that you only send messages that are at most a couple of kilobytes in size. You can send JSON in the message itself. There's no frequency limit.
How instant it is depends on network connection on each side - it's transmitted over HTTP.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "sinch"
}
|
What bonuses are gotten from Mass Effect: Infiltrator?
I recently got Mass Effect: Infiltrator, Mainly waiting for ME3 to come out, I haven't completed it yet, nor do I have ME3, but I would like to know what weapons you get from beating the campaign....
I know about the Intel (as it is mentioned everywhere I look).
However when I look for information on the 'exclusive weapons' all I can find is that there are some ... not which ones they are.
I'm not looking for a detailed description, heck I would settle for "You get a sniper rifle", I just wanna know more than what I currently do....
Can someone help?
|
There are no weapon unlocks for Mass Effect 3, that was misinformation. All you can earn for Mass Effect 3 are War Assets for completing Infiltrator and points toward your Galactic Readiness rating by uploading Cerberus intel.
Source: Video interview with Mass Effect Infiltrator design director Jarrad Trudgen. Relevant information at 3:04.
|
stackexchange-gaming
|
{
"answer_score": 7,
"question_score": 10,
"tags": "mass effect 3, mass effect infiltrator"
}
|
How to solve the trouble with running javascript in asp.net app (WebForms) after postback?
I have javascript, that scrolled floating block on my web page in asp.net app. After postback script doesn't work. How to solve the problem?
|
You can call your java script function after postback
Page page = HttpContext.Current.Handler as Page;
ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "Your Function Name()");
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, asp.net, webforms"
}
|
Question about the Cameron-Martin-Girsanov (CMG) theorem
Within my lecture notes, the following definition of the CMG theorem is given:
> Under the probability measure $\mathbb{\tilde{P}}$ with density $\gamma_T = \exp(cW_T - \frac{c^2}{2}T)$, the process $W_t$, $0 \leq t \leq T$ is a Wiener process with drift $+ct$, while the process $$ \tilde{W}_t := W_t - ct \hspace{10mm} (*) $$ is a new Wiener process.
My question is, should $(*)$ not be $$ \tilde{W}_t := W_t \mathbb{+} ct $$ since we are talking about a new Wiener process with drift $\mathbb{+} ct$?
|
According to CMG theorem, if $W_t$ is a Wiener process under the old measure, then under the new measure $\tilde{W_t}$ is a Wiener process, where: $$\tilde{W_t} = W_t + \langle cW, W \rangle_t = W_t - ct$$
Both statements express this same idea:
* Moving from the old measure to new one adds a drift $ct$, so if you take a Wiener process (under the old measure) and express it under the new measure, you will get a Wiener process with a drift term $ct$.
* So, if you want to get back to a Wiener process (i.e. drift = 0) under the new measure, then you have to remove this $ct$ term.
|
stackexchange-quant
|
{
"answer_score": 3,
"question_score": 2,
"tags": "brownian motion, risk neutral measure, girsanov"
}
|
send email to multiple email address rails 3
I am a user model and in my view I have:
@user = current_user
User model have an attribute with name " **email** ".
and I want send one e-mail to multiple email address with a subject.
I have a form like:
<%= form_for (Email.new), :method => :post, :remote => true, :url => { :controller => "users", :action => "invite_friends" } do |f| %>
<%= f.text_field :address1 %>
<%= f.text_field :address2 %>
<%= f.text_field :address3 %>
<%= f.text_field :address4 %>
<%= f.text_area :subject_email %>
<% end %>
Have I that create a **"email model"** with attributes **address** and **subject_email**?
|
Check section 2.3.3 Sending Email To Multiple Recipients from the Rails Guide
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "ruby on rails, actionmailer"
}
|
lost access to executable file (file not found)
I am trying to execute a file that I have recently run. However the system says file is not found?
The file was taking a long time to execute and in the end I had to close the Terminal window that was executing the file, and then reopen it and this problem occured.
Previously I was in the directory `~/poky/build-atmel $` and simply executed the command
$ bitbake
but the system does no longer recognizes the command.
However, if I try
$ ~/poky/bitbake/bin/bitbake
the file is recognised OK.
What could have happened to the ability of the system to know where the file was and how do I resurrect it. I could add the directory to the `$PATH` variable but there is some other issue here .
I would appreciate any insight into this problem. At present I have just added the directory to the `PATH` statement to solve the problem.
Thanks Lachlan
|
Maybe you had the command in your `PATH` after the setup, but a setup can not make the change to your `PATH` permanent.
Edit `.bashrc` in your home directory and add the following line:
export PATH=~/poky/bitbake/bin:$PATH
This will add that directory to the `PATH` environment variable permanently.
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 0,
"tags": "command line, execute command"
}
|
Farkas keeps talking to me
So one day I was at the Skyforge to craft some draugr armor [I completed the Companions Questline so this isn't a mod for draugr armor]. I noticed Farkas, one of the Companions, ran up to me and started to talk to me. I exited his dialogue but then he keeps talking to me all over again. I don't have any followers with me. Farkas keeps talking to me at the same time. I can acces the Skyforge so he won't talk to me, but when I exit and smithing menu, Farkas keeps talking to me and I keep exiting the conversation. I noticed this is a bug and I don't know how to fix this. He even keeps following me in Whiterun. This is more weird I have no bounty in any of the holds, neither a Companions bounty so paying the fine doesn't work even if I commit a crime, and pay the fine.
Since this only happened in Whiterun, and not the other holds; and I don't have bounties on the holds or Companions, it isn't a duplicate of this.
|
Okay so the only solutions I had are:
* Killing Farkas [I want a solution without death].
* Leaving a town for a few days [This should reset some things]. .
* Paying the Companions bounty [I have no bounty in the Companions which is more weird].
I tried doing all the methods. Method 1 and 2 worked, but I'm more satisfied with 2. Once I did it, Farkas was back to normal going back into the mead hall.
|
stackexchange-gaming
|
{
"answer_score": 0,
"question_score": 4,
"tags": "the elder scrolls v skyrim"
}
|
How to order the data back from Amazon simpleDB int specific column order
I'm using Amazon's SimpleDB Java client to read data from SimpleDB. The problem I have is even though I specified the columns in the some order in the SelectRequest like the following:
SelectRequest req = new SelectRequest("SELECT TIMESTAMP, TYPE, APP, http_status, USER_ID from mydata");
SElectResult res = _sdb.select(req);
..
It returned data in following column order:
APP, TIMSTAMP, TYPE, USER_ID, http_status,
It seems it automatically reordered the columns in ascend order. Is there any way I can force the order as I specified in the select clause?
|
The columns returned are not an ordered _list_ but an unordered _set_ of attributes. You can't control the order they come back in. SELECT is designed to work even in cases where some of the attributes in your query don't exist for every (or any) returned items. In those cases specifically you wouldn't be able to rely on order anyway. I realize that's small consolation if you have structured your data set so that the attributes are always present.
However, since you know the desired order ahead of time, it should be pretty easy to pull the data out of the result in the proper order. It's just XML after all, or in the case of the Java client, freshly parsed XML.
> The Select operation returns a set of Attributes for ItemNames that match the select expression.
SimpleDB docs for SELECT
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "amazon simpledb"
}
|
Access an index for a Set collection?
Is it possible to access the index inside a set?
E.g. here's a set
`Set <integer> numbers = new Set(){1,2,3,4,5,6,7,8};`
Is there a way to access the index of the set like so ?
`numbers[0]`
|
You can't index a Set like you can a List/Array. You can perform typical set operations - such as check if the Set contains an element by value, or remove an element by value. They are typically used for checking membership of data, not retrieving key/value pairs or values by index.
<
Just curious, what is your requirement where you would like to index a Set? I think a Map or List may be a more appropriate collection to use. If you were using a Set to eliminate duplicates, you could use a List to perform whatever index operations you desired, and then construct a set from the List:
List<Integer> ls = new List<Integer>();
ls.add(1);
ls.add(2);
Set<Integer> s1 = new Set<Integer>(ls);
System.debug(s1); // DEBUG|{1, 2}
|
stackexchange-salesforce
|
{
"answer_score": 14,
"question_score": 11,
"tags": "apex"
}
|
Kohana V3 return query result as object
In Kohana V3 is it possible to return result set as an array() or any method exists?
For example:
$user = DB::select('*')->from("users")->where('username', '=', $username);
If method is there,then it is possible to get password like
echo $user->password;
Is it possible without ORM? Please suggest.
|
I think the following would give you all results:
$user = DB::select('*')->from("users")->where('username', '=', $username)->as_object()->execute();
Whereas the following here, would give you the first item:
$user = DB::select('*')->from("users")->where('username', '=', $username)->as_object()->execute()->current();
Try: KO3 Database Wiki
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, frameworks, kohana, kohana 3"
}
|
how to find Taylor series of $\cos(x^2 +y^2)$
Compute the degree ten Taylor polynomial of $\cos(x^2 +y^2)$ based at the origin.
|
We have that
$$\cos t = 1-\frac12 t^2+\frac1{24}t^4 +O(t^6)$$
then by $t=x^2+y^2$
$$\cos (x^2+y^2) = 1-\frac12 (x^2+y^2)^2+\frac1{24}(x^2+y^2)^4 +O((x^2+y^2)^6)$$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "taylor expansion"
}
|
What is the function of "ingenti" in Apocolocyntosis 12, 3?
What is the function of "ingenti" in Apocolocyntosis 12, 3?
> Claudius, ut vidit funus suum, intellexit se mortuum esse, Ingenti enim megaloi xorikoi nenia cantabatur (anapaestis).
My understanding is Harvard Prof. G. Schmeling's translation: "For with a great song and dance a dirge was being sung." That would make "nenia" the nom. sing. subject of "cantabatur". But ingenti is probably abl. so.....
|
Here's the Loeb text:
> Ingenti enim μεγάλωι χορικῶι nenia cantabatur.
Note that the Greek words end in ωι, which is a dative singular ending in Greek. Since the Greek dative can be used in similar ways to the Latin ablative, I suppose you could also consider these words to be in the "ablative"; Greek doesn't have that case, but you have to make compromises when you're mixing forms between languages like this.
_Ingenti_ then goes with these: the song and dance is so great it's not just μεγάλωι, it's also _ingenti_. _Nenia_ is, as you surmise, nominative singular: the subject of _cantabatur_.
|
stackexchange-latin
|
{
"answer_score": 4,
"question_score": 3,
"tags": "classical latin"
}
|
Understanding $@ in bash or zsh
`myFun1` and `myFun2` below don't produce the same output. Why?
#!/bin/bash
myFun1() {
local item
IFS=:
for item in "${@}"; do
echo "->${item}<-"
done
}
myFun2() {
local items="${@}";
local item
IFS=:
for item in "${items}"; do
echo "->${item}<-"
done
}
Invoking
myFun1 "a=b" "c='d 1'" "e"
produces
->a=b<-
->c='d 1'<-
->e<-
whereas
myFun2 "a=b" "c='d 1'" "e"
produces
->a=b c='d 1' e<-
|
This behavior is defined by POSIX, which both Bash and Zsh make an effort to adhere to.
> `@`
> Expands to the positional parameters, starting from one. When the expansion occurs within double-quotes, and where field splitting (see Field Splitting) is performed, each positional parameter shall expand as a separate field, ...
However, this behavior only applies to `$@` itself. Assigning its value to another variable causes the meaning of the individual fields to be lost, and it's then treated as a single string (just as if you used `$*`).
I'm not certain about Zsh, but if in Bash you want to save `$@` to another variable and be able to take advantage of field separation, you need to use an array.
myFun2() {
local -a items=("${@}");
local item
IFS=:
for item in "${items[@]}"; do
echo "->${item}<-"
done
}
In Bash, array expansion of the form `"${array[@]}"` has the same behavior as `"$@"`.
|
stackexchange-unix
|
{
"answer_score": 4,
"question_score": 3,
"tags": "bash, shell script, shell, zsh"
}
|
ng-focus custom directive not working
I have the following code which displays a textbox along with the possible character limit:
<input id="noteAbstract" ng-model="abstract" max-length="{{abstractCharacterLimit}}" ng-trim="false" ng-focus="displayCounter=true" />
<span ng-show="displayCounter" id="noteAbstractCounter">{{abstractCharacterLimit - abstract.length}}</span>
I need to display the counter only when the focus is on the textbox. So I have set a scope variable 'displayCounter' to true on focus. However, the code is not working and the 'span' of counter is always hidden. What am I doing wrong?
Note: I tried invoking another method on ng-focus and that is working fine. So ng-focus is supported in my angular version
|
Can check the angular version you are using? I tried with 1.1.1 it didnt work but with 1.2.1 version it works. Hence it would be better to user versions which later than 1.2.1
Here's the working jsfiddle link < As the version is 1.2.1 `ng-focus` is working.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "angularjs, angularjs directive"
}
|
SVN / Subversion 1.7 and Eclipse Subversive & JavaHL
I have just upgraded to TortoiseSVN 1.6.99, Build 21709, (Subversion 1.7.0, -dev). I am having problem in my Eclipse Subversive 0.7.9.I20100512-1900 & JavaHL 1.6.15. Have tried to update my Eclipse plugins. Anyone have an solution?
Error at Eclipse:
> Share project was failed. Unsupported working copy format svn: The path 'XXX' appears to be part of a Subversion 1.7 or greater working copy. Please upgrade your Subversion client to use this working copy.
|
You are aware of the Subversion 1.7 state? It is currently a beta-2 state and not intended for production? Furthermore it couldn't work with the working copy, cause the working copy format of 1.7 has changed and it will not upgrade your working copy automatically. If you like to use 1.7-beta-2 you have to use the JavaHL version of Subversion 1.7-beta-2 instead of 1.6.X. The above mentioned is also true for TortoiseSVN, cause the version you mentioned is a BETA! (as explained on the TortoiseSVN site.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 34,
"tags": "svn, eclipse plugin, version, subversive"
}
|
Lotus NotesSQL - "Joining" a child document to a parent when querying
I'm querying the back end of a customer complaint system build in domino using the NotesSQL driver.
My issue is I have a overall reference for the complaint (agent generated but unique) but there is also a "contact" table (table probably isn't the right word, I'm unfamiliar with Notes terminology) tracking customer calls etc against each complaint. This table does not have the reference contained it it, so I cannot join in a normal SQL fashion (I believe this is referred to as "application-linked". Is there anyway (e.g. using Notes implicit fields, etc.) to join these within the SQL query?
Essentially the result required is a record set of the complaint reference with the fields from "contact" against each.
Many thanks.
|
Notes is not relational. NotesSQL does not support JOIN operations. If there is a parent-child form relationship between your complaint and contact, then you can do a NotesSQL query against multiple forms with the WHERE clause using NoteUNID and NoteRefUNID as described here: link. That's the only type of implicit relationship that Notes maintains.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "lotus notes, lotus domino, lotus"
}
|
Visual studio bad autocomplete
I'm using VS2013, I have situation in function for example:
void fun(const A &a)
{
//here I write
}
When I start typing 'a', '.', then instead of '.' i get '->' :-/ Do you know how can I fix it ? Turn of intelisense not help.
A is a struct.
|
I'm guessing you're using visual assist by whole tomato. You can disable that in its options.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++, pointers, struct, visual studio 2013"
}
|
Minimal polynomial substitution
This is probably a very easy question, I'm just not strong at the concept.
Let $ A $ be an $ n \times n $ matrix with coefficient in a field $ F $. Then $ A $ determines a linear map $ T: F^n \to F^n $ and gives $ F^n $ a $ F[x] $-module. The characteristic polynomial of $ A $ is $ \text{det}(xI - A) $, while the minimal polynomial is defined to be the monic polynomial generating $ \text{Ann}(F^n) $ as the above $ F[x] $-module.
When finding the invariant factors, the method I see is to calculate the minimal polynomial by using the determinant formula. For example, say it is $ (x-2)^2(x-3) $. Now the minimal polynomial is either $ (x-2)(x-3) $ or $ (x-2)^2(x-3) $. But in the next step, the book substitutes in $ (A- 2I)(A-3I) $ and check if it's zero. Why is this possible? This looks like the Cayley-Hamilton theorem, but isn't that only for characteristic polynomials?
|
This is the most convenient way. The minimal polynomial is the monic polynomial of minimum degree (on the given field) which vanishes at the endomorphism ($A$ in your example). Certainly the polynomial you found (the characterisic one) vanishes at $A$ but you don't know if it is also the minimal polynomial, so you must check if its proper divisors (with all irreducible factors) vanish at the matrix.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "minimal polynomials, cayley hamilton"
}
|
Oracle SQL : remove a string from an existing string value
I have string in stored in the oracle database that looks like below
IDS
---
121,223,423,322
What I need is, when an user enters a value, eg. `121`, then it will be remove from the existing string. See sample output below
Scenario 1 : Given : 121 Output : 223,423,322
Scenario 2 :
Given : 223
Output : 121,423,322
How can I do it in SQL statement? I am looking into using REGEXP_SUBSTR, but not sure how to do... :(
Kindly help. Thanks in advance.
|
You can use expression
replace(regexp_replace (column, '(,<value>$)|(^<value>,)|(^<value>$)', ''), ',<value>,', ',')
For example for value 121:
select
replace(regexp_replace ('1121,121,223,423,322', '(,121$)|(^121,)|(^121$)', ''), ',121,', ',')
from dual;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sql, oracle"
}
|
Word for feeling for movie characters
I watch many movies these days, and I often feel happy when the main character gets what they want in the end or sad otherwise. Is there an adjective to describe this? It appears to me that _vicarious_ is not the right word because it applies only to people watching other people in real life, but I might be wrong. For example,
> I am so _____. I always feel good when the protagonist wins and bad when he loses.
Phrases and other parts of speech are also welcome.
|
You are "identifying" with the character and placing yourself into his or her situation in the work of fiction. Having empathy for the character is one-step removed from this since it still connotes distance, emotionally, from the actual character. I hope this helps. For more words of interest to you, check out
Jack's Handy List of Words
607 Words That You Can't (or Shouldn't) Live Without by Jack Forbes
It's funny and incredibly useful in expanding one's vocabulary in English beyond the usual limited vocabulary. Available on barnesandnoble.com and amazon.com in soft cover and epub.
|
stackexchange-english
|
{
"answer_score": 3,
"question_score": 3,
"tags": "single word requests, phrase requests, adjectives"
}
|
How do I perform a SHA512 hash in C++ WinRT?
What is the equivalent of the C# method SHA512CryptoServiceProvider.ComputeHash() in C++ WinRT?
|
See `Windows.Security.Cryptography.Core.CryptographicHash` and friends. There is an example on that page demonstrating one usage, and the documentation for related classes and functions have examples as well.
For a "complete" example, you can take a look at the `compute_sha1_hash` function from my Boost-licensed CxxReflect library. It computes an SHA1 hash; computing an SHA512 hash should simply require changing the requested hash algorithm from "SHA1" to "SHA512". Note that this function is written using WRL, not C++/CX, though converting the code to C++/CX should be straightforward and would result in much more succinct code.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, windows runtime"
}
|
Convert dataframe columns to named number vector
I have a dataframe `blah`:
blah <- data.frame(x=c("Red", "Blood Red", "Crimson", "Maroon"), y=c(20, 1, 14, 13))
I want to convert `blah` into a named number/member vector:
blah <- c(`Red` = 20, `Blood Red` = 1, `Crimson` = 14, `Maroon` = 13)
Where `x` is the name and `y` is the value.
How can I make this happen?
|
Just use `setNames`
setNames(blah$y, blah$x)
# Red Blood Red Crimson Maroon
# 20 1 14 13
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "r"
}
|
How to avoid JQuery class selector?
I just started learning JQuery.
My code:
$(document).ready( function(){
$('.img').click(function(){
$('.img').animate({
opacity: 0.25,
left: "+=50",
height: "toggle"
}, 5000, function(){
// Animation complete.
});
})
});
here .img is an image and I am doing an animation on that. But what I want is I don't want to specify each class type like `.img`. All elements I have on the page(images, p,border) can go through the same animation. so I expect something like
`$(this).click( function{ $(this).animate(.........`
Is it possible by putting something like `this` we don't have to specify the exact class? I tried with this, it is not working.
|
$(".img").click(function(){
$(this).animate( ... );
});
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "jquery, animation"
}
|
set the maximum processor state to 99%
I have a Lenovo y50-70 with the screen flickering issue and I fixed it in Windows by set the max processor state to 99% in Advanced Power Management Advanced Power Manager
is there anyway to do the same in Ubuntu?
|
Thought the solution sounds a bit odd to me _(if demanded the processor will normally go to 100%)_ , but you might want to take a look at `cpu freq` from `Ubuntu Software` center.
It is a GUI over cpufreq, which can be used to set the CPU frequency profile.
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 0,
"tags": "power management, lenovo, intel, cpu"
}
|
CreateStreamedFileFromUriAsync: How can i pass a IRandomAccessStreamReference?
I am trying to download a file using `StorageFile` method `CreateStreamedFileFromUriAsync` but i am confused with `IRandomAccessStreamReference` parameter. How can I pass a IRandomAccessStreamReference? It is an interface. What sould I do?
public static IAsyncOperation<StorageFile> CreateStreamedFileFromUriAsync(
string displayNameWithExtension,
Uri uri,
IRandomAccessStreamReference thumbnail
)
|
I have found the answer:
IRandomAccessStreamReference thumbnail =
RandomAccessStreamReference.CreateFromUri(new Uri(remoteUri));
IAsyncOperation<StorageFile> file1 =
StorageFile.CreateStreamedFileFromUriAsync("duyuru.pdf", new Uri(remoteUri), thumbnail);
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "c#, uri, storagefile"
}
|
Create ADF schedule running from 6:00 to 20:00
I have built a package for ADF IR. Cool. Proud of it. Now I want to schedule it for every hour between 06:00 and 20:00. I can see no way in ADF to schedule it as such. What I did now is schedule the package for hourly execution. The IR is started at 06:00 and stopped at 20:00, effectively running hourly between 06:00 and 20:00.
However, in the near future I will be running other packages at night so I will be needing my runtime at night. And then it will run my package that should only run between 06:00 and 20:00.
Am I missing something in the schedule options? How can I run my package run hourly between 06:00 and 20:00 without having to start and stop my runtime?
|
ADF's recurrence pattern is not that robust, but you can leverage Logic Apps to manage the trigger. Here is another answer where I discussed this recently.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "azure, ssis, azure data factory, azure data factory 2, azure scheduler"
}
|
How to retrieve Title of image url
I'm collecting images for a UITableView where I use a custom url depending on the item code
var itemCode = prodCode
var strCode1 = Array(itemCode)[0]
var strCode2 = Array(itemCode)[1]
var strCode3 = Array(itemCode)[2]
urlStr = "
With the url I then retrieve the image with the code below
var image = UIImage(named: "Blank.png")
if let url = NSURL(string: urlStr) {
if let data = NSData(contentsOfURL: url) {
image = UIImage(data: data)
}
}
self.imageView.image = image
The images come in all shapes and sizes but when displayed in a browser using the custom url, each image has a title displaying the size of the image (i.e.: Image310xMAX.jpg 310x83 pixels). I need to get this title, how can I obtain it?
|
I managed to get the dimensions of the image using sizeof to help me size the rest of the form
let sizeOfImage = mainImage?.size
let h = sizeOfImage?.height
imgHeight = CGFloat(h!)
let w = sizeOfImage?.width
imgWidth = CGFloat(w!)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, xcode, swift, url"
}
|
Is there something I should know about the jquery .text method?
I'm learning about the .data method and saw this in the code:
$("span").text("" + value);
Q: Is there a reason why the author put ("" + value) instead of simply (value)?
|
Why does it happen in this particular demo? because these differ:
$("span").text(undefined); //empty string set
$("span").text("" + undefined); //"undefined" set
Before `.data()` is set, the value is `undefined`, and it needs to be converted to a string to see anything in the output.
* * *
_More generally:_ Yes, there _are_ cases where it matters, let's take a quick example that fails:
$("span").text([1, 2, 3, 4]);
This will fail because it's a different overload of `.text()` ( _many_ things have array overloads) rather than this:
$("span").text("" + [1, 2, 3, 4]);
Which _does_ work, it's effectively:
$("span").text("" + "1,2,3,4");
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "javascript, jquery"
}
|
Can I set the origin of rotation when rotating an view with CGAffineTransformMakeRotation()?
I have an UIImageView which I want to rotate a little bit, but I need to define an special origin for rotation. How could I do that? More precisely, I have an image of a goblet, and I want it to wiggle on a table. It's socket is quadrate. So when wiggeling to left, then my rotation origin has to be the left corner of that quadrate. And when wiggeling to right, the rotation origin has to be the right corner of that quadrate.
How could I do that? I already have this:
myView.transform = CGAffineTransformMakeRotation(.25);
|
There was a similar question on how to achieve this here.
The best answer was to change the `anchorPoint` property of the underlying layer of the `UIView`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "iphone, cocoa touch, uikit"
}
|
Continuous uniform random variables convergence question
Let $X_1, X_2, \ldots$ be independent $U(0,2)$ random variables and let $$Y_n = \prod_{i=1}^n \, X_i \;.$$
How do I prove or disprove that that **$Y_n$ converges to $0$ almost surely** ?
|
**Use the fact that $-\log(X_i/2)$ has an Exponential distribution.** (This is easily proven.) The reasoning will proceed as follows. Justify each step:
* $-\log(Y_n) + n \log(2)$ is the sum of $n$ independent Exponential distributions,
* which therefore has a Gamma$(n)$ distribution,
* whose mean and variance are both $n$,
* whence (use Chebyshev's Inequality, for instance) most of the probability of $Y_n$ eventually is focused near zero.
Incidentally, it is insightful to contemplate the role played by the upper limit of $2$ in this question. When you have worked through the details, you will be able to see how the answer changes when $2=\exp(\exp(-0.3665129))$ is replaced by any value of $e = \exp(\exp(0))$ or greater.
|
stackexchange-stats
|
{
"answer_score": 7,
"question_score": 4,
"tags": "probability, convergence, uniform distribution"
}
|
working with maven to run java class files
I am new to Maven My question is where does maven download the external dependency jars in the local machine.
Basically my application uses a lot of external dependencies and i am able to compile the application using maven
But is there a way to run the application from commandline with Java without having to create a Jar-with-dependencies, basically by just using all the class files and specifying my main class. For that i will have to set the classpath to the directory where my external jars are located. How do i do that?
Thanks in advance!!
|
You can also use the exec maven plugin to run your application inside the maven lifecycle. In its simplest form the command would be
mvn exec:java -Dexec.mainClass=com.example.Main
The full set of configuration options are described on the exec:java page. The `classpathScope` option might be especially interesting.
The advantage of this method would be that you can configure any command line arguments and system properties in your pom file.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "java, maven 2, compilation"
}
|
How do I export a function from an imported module?
module Hart
( module Hart
)
where
import Control.Monad.Trans.Reader (runReaderT, ReaderT, ask)
import Control.Monad.Trans (lift)
I currently have the above defined. How can I export **only** the `ask` function from `Control.Monad.Trans.Reader` in addition to the `Hart` module?
I was thinking I could do the below - but it generates an error:
module Hart
( module Hart
, module Control.Monad.Trans.Reader (ask)
) where
|
As @leftaroundabout mentioned in the comments, to re-export functions, you simply include that function in your export list:
module Hart
( module Hart
, ask
) where
...
import Control.Monad.Trans.Reader (ask)
This will also work for qualified imports with the caveat that the namespace is not captured in the export.
module Hart
( module Hart
, ask
, T.null
) where
...
import Control.Monad.Trans.Reader (ask)
import qualified Data.Text as T
And in some other file:
module Other where
import Hart (ask, null)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "haskell, module"
}
|
Trigger phone call with Javascript
I would like to trigger a `tel:12345` HREF using only Javascript, not with an anchor. I simply want to grab the value of an input field and use JS to prompt the user to call the number typed in. My trigger will be a button located next to the field.
Suggestions?
|
Use:
window.open('tel:12345');
|
stackexchange-stackoverflow
|
{
"answer_score": 22,
"question_score": 12,
"tags": "javascript, tel"
}
|
How to interpret and use generic vector?
Can any body explain this generic vector `Vector<? super Object> list = ...` and where to use it?
|
Here you are defining the **lower bound** of your unknown object `?`. So the `Vector<? super Object` can contain only `Object` and any super class of `Object`. But since `Object` does'nt have a super class it has no sense. It behaves same as `Vector<Object>`.
Refer this sample.
The counterpart for this is **upper bound** `Vector<? extends Object>` where you can add any object that extends `Object`.
You should be able to avoid using `Object` as the generic type is most cases.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "java, generics, vector"
}
|
Fastest way to identify differences between two tables?
I have a need to check a live table against a transactional archive table and I'm unsure of the fastest way to do this...
For instance, let's say my live table is made up of these columns:
* Term
* CRN
* Fee
* Level Code
My archive table would have the same columns, but also have an archive date so I can see what values the live table had at a given date.
Now... How would I write a query to ensure that the values for the live table are the same as the most recent entries in the archive table?
PS I'd prefer to handle this in SQL, but PL/SQL is also an option if it's faster.
|
SELECT term, crn, fee, level_code
FROM live_data
MINUS
SELECT term, crn, fee, level_code
FROM historical_data
Whats on live but not in historical. Can then union to a reverse of this to get whats in historical but not live.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 7,
"tags": "sql, performance, oracle, plsql"
}
|
C++ VS2010 Linker error regarding namespace variables
**MyNamespace.h:**
namespace MyNamespace{
int a
}
**MyNamespace.cpp:** some function that uses a
**main.cpp**
#include "MyNamespace.h"
>
> main.obj : error LNK2005: "class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> >
> FileNamespace::m_rootDirectoryPath"
> (?m_rootDirectoryPath@FileNamespace@@3V?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@A)
> already defined in FileNamespace.obj
> 1>main.obj : error LNK2005: "struct FileNamespace::FileTree FileNamespace::m_dataFileTree"
> (?m_dataFileTree@FileNamespace@@3UFileTree@1@A) already defined in
> FileNamespace.obj
>
|
You are _defining_ a global variable (with external linkage) in multiple translation units, which results in duplicate definition errors (since you are violating the ODR).
What you should do, instead, is to _declare_ it in the header with an `extern` declaration
namespace MyNamespace{
extern int a;
}
and define it in a _single_ .cpp file (probably in `MyNamespace.cpp`)
int MyNamespace::a;
This way, the compiler will create only one instance of this variable in a single object module, and the linker will link all the references to it made in other object modules to this single instance.
It may help you to understand the problem noticing that this is the exact equivalent of _declaring_ functions in headers (writing there only the prototype) and _defining_ them in a single `.cpp`.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "c++, linker"
}
|
$a + b + c = ab$ and $a$, $b$, and $c$ are numbers different from zero
Suppose $a+b+c = ab$, and $a,b,c$ are nonzero. Then
$$\frac{ab + ac + bc + c^2}{abc}$$ is equal to what? I've found an answer: $\frac ba$.
|
$$\frac { ab+ac+bc+c^{ 2 } }{ abc } =\frac { a\left( b+c \right) +c\left( b+c \right) }{ abc } =\frac { \left( a+c \right) \left( b+c \right) }{ abc } =\\\ =\frac { \left( a+c \right) \left( ab-a \right) }{ abc } =\frac { \left( a+c \right) \left( b-1 \right) }{ bc } =\frac { \left( ab-b \right) \left( b-1 \right) }{ bc } =\\\ =\frac { b\left( a-1 \right) \left( b-1 \right) }{ bc } =\frac { ab-a-b+1 }{ c } =\frac { a+b+c-a-b+1 }{ c } =1+\frac { 1 }{ c } $$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": -1,
"tags": "algebraic curves"
}
|
How to handle java.lang.OutOfMemoryError
I am running a makefile and after a while I get the following error:
java.lang.OutOfMemoryError
I am wondering whether there is a command that allows me to increase the Java Heap Space. I dont want to change the makefile itself, so I need some kind of "global" command that allows me to reset the Java Heap Space.
Many thanks, Patrick
EDIT: Thanks for your answers. But I am looking for a more global command, that allows me to specify to set the Heap space once and for all like:
SET JAVA_HEAP_SPACE = 5GB
Thanks
|
* You can set java heap space from command line: `java -Xmx1600m program` Now your heap space is 1600 MB.(Assuming your hardware can already afford 1600MB.)
* For Windows platforms, you can set it from **_Java Runtime Environment Settings_** as well. Follow _Control Panel => Programs => Java_. Navigate to Java tab. View Java Runtime Environment Settings. Add `-Xmx1600m` to Runtime Parameters. Save and go on.
* For Linux platforms, you can launch Control Panel and edit runtime parameters. It can be run from something like `/usr/j2se/jre/bin/ControlPanel`. Find your own directory. Read here please: <
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "java"
}
|
What happens when the kernel memory required exceeds 1 GB
I am trying to understand 'Memory Management' in Linux as a part of the course in 'Understanding the Linux Kernel' by Daniel and Marco. Below is my understanding of the Kernel space
1. On a 32-bit machine, each process has 4GB virtual address space. 3GB - User and 1GB - Kernel space.
2. The 1 GB is shared among processes and directly mapped to 1 GB of RAM. This space is used to store kernel code, Page tables etc.
3. The 1 GB cannot be swapped out. Although, it can be freed.
My question is, what if the total kernel space required by processes exceeds 1 GB?
|
First, a correction - the (almost) 1Gb the kernel has mapped in a 1:1 is not used exclusively by the kernel. It's just that the kernel has the easiest access to that memory. it does hold the kernel code and static data.
The kernel virtual space actually has something like 256 Mb (the number is dynamic) at the top of the virtual address space (top of the 1Gb the kernel uses) that is not mapped 1:1 like the rest of the kernel linear addresses, but instead mapped dynamically to various pages - either in to get a virtual continuous region out of non contiguous physical memory by vmalloc, or to map memory mapped IO by ioremap or to get access to higher then 1Gb pages via kmap.
So to sum up - when the kernel needs access to more memory then the (almost) 1Gb it has always mapped in a 1:1 setting it uses dynamic memory just like user space.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "memory management, linux kernel"
}
|
JavaScript: Проверка CSS стиля и переключение его по клику на ссылку
Доброго времени суток. Прошу помощи с js. Есть код:
<a class="default">111</a>
<a class="red">222</a>
<a class="default">333</a>
<a class="default">444</a>
<a class="red">555</a>
Есть два стиля:
.default{
border: 1px solid lightgray;
color:gray;
}
.red {
background-color: red;
color: blue;
}
Необходимо при клике на ссылку применять ей противоположный стиль css, то есть, если у ссылки задан стиль "default", то при клике заменить его на "red" и наоборот. Заранее спасибо!
|
Если вы используете jQuery, то вот такой код может подойти
$('a').click(function (event) {
event.preventDefault(); // что бы не было перехода по ссылке
$(this).toggleClass('default red');
})
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript, html, css"
}
|
Concatenate Label Values Fails to Calculate Aggregate
I'm trying to do what seems like a very simple operation (It's SUPER easy in ArcMap...). I'm kind of a novice with QGIS, so it's probably something really simple that I'm doing incorrectly. The release is 2.18.12. Basically, I want to create concatenated labels with values from three separate fields, separated in the text by a comma and a space. The fields I'm trying to concatenate are numeric and have no null values (unless zero is considered null). Here is my expression:

The concat version is a bit safer, since it will automatically treat NULL values like an empty string.
* Note use of "concat", not "concatenate" (which is a different function)
|
stackexchange-gis
|
{
"answer_score": 4,
"question_score": 1,
"tags": "qgis, labeling, qgis 2.18, concatenation"
}
|
Access files stored on Android smartphone from Windows
Is there any way to get access to files that are stored within the memory of an Android-based smartphone (HTC Wildfire; Android 2.2.1) using Windows 7? After connecting the phone to computer, I'm only able to see files stored on the memory card. If possible, I'd prefer not to install anything on the phone.
|
MyPhoneExplorer is the answer. The file-manager isn't the best one, but still allows to view files. I had to install not only PC-app, but also an app from Google Play, but still it did give me what I needed.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 0,
"tags": "windows, android"
}
|
Flash swf to play PCM WAV files?
I am in need of a Flash swf that is capable of loading PCM WAV files via a url passed to it.
An example of the file can be found here: <
The swf does not need a visible interface, as it is meant for audio playing only and not user interaction.
The swf should have a simple javascript interface for page-level interactions. These include:
load(url): loads a PCM WAV file over the internet using the url that is passed through it. play(): Should play the PCM WAV file that was loaded stop(): Should stop playing the current file.
I can provide a sample audio file that matches the specifications if the developer is unable to obtain a url from the link posted above.
|
Flash does not natively support run-time playback of PCM encoded audio. This means that you'll need to parse the WAV container to get at the audio and feed it in (flash 10+).
<
Somewhat more significantly, you'll require crossdomain permission to be able to do so, because you need programmatic access the wave data.
Another option is to use some code I wrote a while back to bake the wave data into an in-memory swf, load it and extract a valid Sound object back out.
<
The article is quite old now, and the the silent-sound technique should be avoided, but you may be able to repurpose the code to do your bidding. Using this method will work with Flash 9+.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "flash, wav"
}
|
Conditional element replacement using cellfun
vec = randi(10,10,1)
vec(vec < 5) = 0
func = @(x) x(x < 5) = 0 % This isn't valid
How am I supposed to translate the second line of code into a function handle that I can use in conjunction with `cellfun`?
|
You can use multiplication, since if your condition is satisfied you have `1` and `0` otherwise.
Multiplying by the inverse of the condition therefore gives you either an unchanged value (if condition is not satisfied) or your desired substitution of `0`!
func = @(x) x .* (~(x < 5)) % Replace values less than 5 with 0
If you had a different substitution, you could expand the same logic
func = @(x) x .* (~(x < 5)) + 10 * (x < 5) % replace values less than 5 with 10
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 6,
"tags": "matlab, anonymous function, cell array, function handle, elementwise operations"
}
|
Save date array to db
So, I have this element in my form:
<?php
$form['order']['date'] = array(
'#type' => 'date',
'#title' => 'Order date',
);
In the form submit function I have got such array:
[values] => Array
(
[date] => Array
(
[year] => 2010
[month] => 11
[day] => 27
)
)
I am looking for a simple way to save this array in database and then I want to be able to extract this date from the database for that would be substituted back into the edit form.
Are there drupal api functions for this?
|
I think I found a simple way to do it, but it does not use Drupal api.
$date = implode($form_state['values']['date']); // $date = 20101127;
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 3,
"tags": "drupal, date, drupal 6, drupal fapi"
}
|
Se pueden hacer interfaces graficas en C?
desde hace un tiempo he estado programando en C y me preguntaba si era posible hacer interfaces graficas en C, o de alguna manera crear una interfaz grafica con alguna herramienta, pero que el codigo "cerebro" de la aplicacion este en C, quiero ampliar mi conocimiento e ir mas alla de las aplicaciones por consola, agregarle mas emocion a mi aprendizaje, agradezco sus aportes, Gracias :3.
|
Sí, se puede hacer una aplicación con interfaz gráfica en C. Y de tres formas diferentes, además.
La primera es realizar llamadas al sistema para controlar la pantalla directamente desde tu programa (es posible, pero absolutamente nadie lo hace).
La segunda opción es hacer una aplicación híbrida si quieres usar un framework para hacer GUI en otro lenguaje, como por ejemplo una aplicación con interfaz gráfica Java Swing, pero con la lógica de negocio programada en C (raro).
La tercera es utilizar algún framework C que te facilite conceptos como paneles, botones, etiquetas, selectores, y demás elementos típicos de una interfaz gráfica, pero que no los tengas que programar desde cero tú.
De estos existen muchos, como GTK, por ejemplo.
|
stackexchange-es_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c, interfaz gráfica"
}
|
How to count how many Integer numbers are in a certain Range of Cells
I used `=INT(H4:I15)=H4:I15` to return a table of TRUE and FALSE if a number is an integer or not And `=COUNTIF(J4:K15,TRUE)` to count how many return TRUE
I was wondering if there's any way around this so I don't have 2 columns with TRUE and FALSES in my sheet
|
You can `SUM` across Boolean responses which can help to simplify the equation using the logic you already created to identify ints
=SUM(--(INT(A1:A12)=A1:A12))
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "excel, vba"
}
|
Does anyone have a Windows "at /every:" example to explain how to setup a batch file to run every day?
Microsoft documentation for the "AT" scheduler command shows that it has an /every: switch to schedule a script to reoccur on specified days. I've done it before, but I can't remember the syntax for that switch. The documentation does not include an example that uses the /every: switch.
So, can you help me write an example "AT" scheduler command to run a batch file on the local machine daily, monday through friday?
Example:
c:\at 12:01am /every: updatestats.bat
|
Running every day:
AT 3:00AM /EVERY:M,T,W,Th,F,S,Su c:\foo.bat
|
stackexchange-serverfault
|
{
"answer_score": 3,
"question_score": 1,
"tags": "windows server 2003, windows server 2008, command line interface, batch file"
}
|
Service Application Fail-over
I am not seeing in the technical docs about how to deploy redundant service applications for a farm. I am seeking confirmation about my idea of having two web servers responsible for cross-farm application services with a load balancer in front. The other farms would access those services through the load balancer.
Can anyone tell me about the feasibility of this idea or documentation the describes SP 2010 Service Application Fail-over strategies?
Thanks!
|
The Service Applications are redundant if you make sure that you install and start the services on multiple load balanced application servers. SharePoint 2010 handles the load balancing for you.
Regarding the fail-over strategies you have to look into the different services and if they use a database for storage or not. The databases that the SA uses must be made redundant using normal strategies (clustering, mirroring or by configuring a fail-over server for the SA). You might get some data loss with SAs that do not use SQL for storage such as Excel services and Access services.
When it comes to the actual service applications they normally work using timer jobs, these timer jobs are executed on the first available server and if it fails it will run on the next server serving that SA during next execution.
|
stackexchange-sharepoint
|
{
"answer_score": 2,
"question_score": 2,
"tags": "architecture, infrastructure"
}
|
rails records push
**Controller.rb**
@payments = PaymentDetail.joins(:project)
in view file @payments.count is equal to 550
When I change my controller like this
@payments = PaymentDetail.joins(:project)
@payment_errors = PaymentError.joins(:project)
@payment_errors.each {|payment_error| @payments << payment_error}
Still in view file @payments.count is equal to 550 while it have to be (550+@payment_errors.count)
Why I can't push @payment_error records into the @payments ?
|
You are trying to add `PaymentError` data into `PaymentDetail` table which is wrong. If you need it in array use `to_a`.
You can do like this:
@payments = PaymentDetail.joins(:project).to_a + PaymentError.joins(:project).to_a
To use `will_paginate` for arrays. Add this line in your controller:
`require 'will_paginate/array'`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails"
}
|
Probably of revealing 3-same, in a set of 9, composed of 3 sets of 3, by selecting 4.
First - thanks for helping. I'm admittedly a bit rusty in probability. University is so far back!
In what looks like a traditional lotto game; I have a grid of 9 circles. On this grid, there are 3 blue, red, and white circles -- each covered with that silvery scratch-off stuff that gets all over the place!
I fervently scratch 4 circles at random, hopeful to reveal 3 identical circles.
What is the probability that I win?
Thanks for helping!
|
There are $\binom{9}{4}$ possible ways to pick $4$ circles in general, so this is the denominator of our probability. The numerator is the number of ways to pick a winning set of $4$ circles.
There are $3$ ways to pick which color we win with. After picking those three circles with the same color, that leaves us with $6$ circles where the color won't match anything.
All in all, the probability is:
$$P = \frac{3 \cdot 6}{\binom{9}{4}} = \frac{1}{7}$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "probability"
}
|
Performance issue with too many css files in rails 4 app?
I am building an app in Rails 4 and am using asset pipeline. For my workflow, I've split my css into 10+ separate sheets. Should I combine them for deployment or does it not matter as long as they're minified? I'm wondering how much performance will be affected with separate stylesheets.
|
Have a look here:
<
The default behavior is to combine your CSS files for you in production, into one asset with a hash on the end to make sure it updates when you change the files.
For example, here is my company's css file:
<
but in our `assets/stylesheets` folder we have 20+ individual files to keep ourselves organized.
Combining and minifying your CSS _is_ important though, as it can significantly reduce the bytes needed to be sent over the wire to the browser.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "css, ruby on rails, performance"
}
|
Question history doesn't show change of title
Yesterday, I saw this question pop up on Stack Overflow. At the time, the question's title was something about "zero-width lookahead not working".
An hour later, it had a new title. The question's history doesn't reveal any edits to that effect. At first I thought the question was deleted and then re-posted with a new title. So I searched my browser's history, found the original question and made sure it had the same ID.
Is there a way to hide edits from others? Is this a bug?
(Yes, I am 100% sure that the question initially had a different title and no, I cannot provide any screenshots with freehand cirlces.)
|
It's very possible that you spotted the original title before it was reworded within the 5 minute rule for edits.
If that was the case, you wouldn't have been able to see any difference in the edit if made inside the window of dressing time.
|
stackexchange-meta
|
{
"answer_score": 3,
"question_score": 1,
"tags": "support, specific question, revisions list"
}
|
Mysql stored procedure error
I'm trying to add the following stored procedure to my mysql database:
CREATE PROCEDURE logmsg ( _Username VARCHAR(50), _Message VARCHAR(80) )
BEGIN
INSERT INTO chatlogs (sender, message) VALUES (_Username, _Message);
END;
But its failing the query and returning:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
I've been searching for about 2 hours on google and cannot find any answer at all.
Any help is greatly appreciated!
|
While I'm not 100% sure because I can't test on a MySQL server at the moment, I think the problem is in the semicolon. On the line with `INSERT` you basically end the `CREATE PROCEDURE` statement, which has incorrect syntax this way. You have to set the delimiter to something else (e.g. `//`), to be able to use the semicolon in the body of the procedure:
delimiter //
CREATE PROCEDURE logmsg ( _Username VARCHAR(50), _Message VARCHAR(80) )
BEGIN
INSERT INTO chatlogs (sender, message) VALUES (_Username, _Message);
END//
delimiter ;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "mysql"
}
|
How to Sort By Frequency And Then Filter Repeats in JavaScript - Solution
I got one question during an interview. The question was to sort the array based on repeat char count.
**Question** :
['#','$','#','?','?','#','#','#']
**Output** :
[#,#,#,#,#,?,?,$]
So I tried to write a solution and it is working as expected. Please see my solution in the comment and let me know if there is a scope of optimization available.
Please let me know if any suggestions or concerns
|
Well, how about
q = ['#','$','#','?','?','#','#','#']
a = q
.sort()
.join('')
.match(/(.)\1*/g)
.sort((x, y) => y.length - x.length)
.join('')
.split('')
console.log(...a)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "javascript, arrays, sorting"
}
|
Verifying significance level for hypothesis test functions
> Let $X$ and $Y$ be independent $N(\mu, 1)$ r.v's such that $$ H_0: \mu=0, ~~~H_1:\mu \neq 0$$ where the tests are as follows$$f_1(x,y) = \begin{cases} 1,&|x+y|>a\\\ 0, &|x+y|\le a \end{cases}$$ and $$f_2(x,y) = \begin{cases} 1,&|x+2y|>b\\\ 0, &|x+2y|\le b \end{cases}$$ 1\. Find $a$ and $b$ so that the size is $\alpha=5\%$ for both tests.
1. Since the size of the test is the probability of incorrectly rejecting the null, then we need to find $$P(Reject H_0|\mu=0)=0.05$$ $$ \iff P(\frac{(X-\mu_0)\sqrt{n}}{\sigma}~~|~\mu=0)=0.05$$ $$ \iff P(X\sqrt{n})=0.05$$ I am unsure how to implement the function into this so that I can find $a,b$?
|
Note that $f_{1}$ and $f_{2}$ are test functions. A test function $f$, rejects $H_0$ if and only if $f=1$. That is, you want to find $a$ and $b$ such that that \begin{align*} \begin{cases} P(f_1=1|\mu=0) &= \alpha \\\ P(f_2=1|\mu=0) &= \alpha \end{cases} \end{align*} Note that \begin{align*} P(f_1=1|\mu=0) &= P(|X+Y|>a|\mu=0) \\\ &= P\left(\bigg|\frac{X+Y}{\sqrt{2}}\bigg| > \frac{a}{\sqrt{2}}\right) \end{align*} Since, under $\mu=0$, $X$ and $Y$ are independent standard normals, $Z=\frac{X+Y}{\sqrt{2}}$ is a standard normal. Therefore, you wish $P\left(|Z| > \frac{a}{\sqrt{2}}\right)=\alpha$. This happens if $\frac{a}{\sqrt{2}}=\Phi^{-1}(1-2^{-1}\alpha)$, where $\Phi$ is the cdf of the standard normal. Conclude that $a=\sqrt{2}\Phi^{-1}(1-2^{-1}\alpha)$.
Can you use the same reasoning to find $b$?
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "probability, statistics, hypothesis testing"
}
|
Turn flat list into two-tuples
Is there a single line expression to accomplish the following:
input = ['this', 'is', 'a', 'list']
output = [('this', 'is'), ('a', 'list')]
My initial idea was to create two lists and then zip them up. That would take three lines.
The list will have an even number of elements.
|
This is quite short:
zip(input, input[1:])[::2]
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 6,
"tags": "python"
}
|
Including variables in jekyll from given file
I want to have my variable assignments placed in a single txt file or similar in jekyll, and have them included in my Front Matter for assignment. So instead of this:
---
variable1: abc
variable2: 123
---
I can have this:
---
{% include variables.txt %}
---
The purpose of this is to have a website that is editable by a technologically inexperienced client. I want to abstract out the core site structure from the things that need to be edited as much as possible - without setting up a CMS, or moving into a dynamic site (so it can still be hosted on github pages)
|
You could just throw all of your variables into your `_config.yml` file and then they can be accessed like this:
{{ site.variable1 }}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "yaml, jekyll, github pages"
}
|
Getting index of a certain element in a 2D numpy array
I'm new to python so I need some help with this:
I have 2D array of numbers that represent density of a circle of material in a space and I want to locate the centre. So I want to get the index of the numbers representing the diameter and then the middle index will be the centre. In this code I only store the value of the density : tempdiameter.append(cell) I want the index of the cell itself. How can I do that. Also I don't want to use lists for diameter. so how can I create a dynamic 1D np array? Thanks
for row in x:
for cell in row:
if cell!=0:
tempdensity+=cell
tempdiameter.append(cell)
if tempdensity>maxdensity:
maxdensity=tempdensity
if len(tempdiameter)>=len(diameter):
diameter=tempdiameter
tempdensity=0
tempdiameter=[]
|
To get the row with the highest number of non-zero cells and the highest sum you can do
densities = x.sum(axis=1)
lengths = (x > 0).sum(axis=1)
center = x[(densities == densities.max()) & (lengths == lengths.max()]
Try to avoid using loops in `numpy`. Let me know if this isn't what you want and I'll try to answer it better. You should provide sample input/output when asking a question. You can also edit your question rather than adding comments.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "python, numpy, multidimensional array, indexing, dynamic arrays"
}
|
UPDATE SET values WHERE data from another table
UPDATE kid_progress_Backup
SET level = 9 (column in kid_progress_Backup)
FROM users1
WHERE birthyear_string = 01/01/2001 (column in users1)
So basically all the questions in this forum I have looked at were about setting one columns value = to the value in another column from another table. BUT mine is not. I want
kid_progress_Backup.level = 9
IF
users1.birthyear_string = 01/01/2001
AND
kid_progress_Backup.level = 8
IF
users1.birthyear_string = 01/01/2002
WHERE
id>270
|
You should maintain one foreign key between two tables. In your case
kid_progress_Backup,users1 tables
Suppose `uid` is foreign key then you can write query as
UPDATE kid_progress_Backup
SET level = '9' where uid In(Select uid from users1
WHERE birthyear_string = '01/01/2001')
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql, sqlite, set"
}
|
Windows Service need to monitor error logging? Ideas?
I have a windows service that runs 24/7 on one of our servers.
It connects to an external company as of late that company has been going down a lot.
I need to set something up that will essentially monitor when we have had 25 errors in the last minute within the error logs for this service.
I am guessing that I will have to create a table and insert these errors into the table as they are being logged and then set up something that checks via a tsql query whether or not 25 have occurred in the last minute? (then send out an email or update a dashboard monitoring page for support)
Really my question is does anyone have a better idea than this? Someone must have done something better than this in the past. I guess I have never attempted to read straight from logs. Maybe that would be a better route.
Any ideas direction are greatly appreciated on this one. Thanks.
|
Logging is fun. :/
Your options are essentially:
1. Log to a database server - Advantage: easy to read from other locations. Disadvantage: you need a database server. If the project doesn't already include one, might be a pain. Also, logging fails if problem is in network connectivity.
2. Log to the Event Log - Advantage: fast to write locally. Can be read remotely.. with the correct user permissions. Disadvantage: You'll be querying this a lot and the event log isn't exactly built for that.
3. Log to a file - Advantage: extremely fast write. Disadvantage: Requires a lot of permission setup for remote code to access. May be corrupted/lost/deleted etc.
4. Use additional software such as System Center Operations Manager. Advantage: this is exactly the type of thing that was built for. Disadvantage: cost/setup.
* * *
Those are in my order of preference.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, logging, windows services"
}
|
Dynamically Adjusting the Height of an iFrame Based on Submit Click
I have a form I'm pulling in that generates an iFrame for the Payment portion of things. The height is fine, but when you click "submit" and the form has errors the error message(s) push the submit below the iframe's height, causing it to disappear. I've been playing around with some JavaScript to dynamically adjust the height by binding the event, but no luck thus far, thanks.
var iframe = document.getElementById("embedded123frm757809").contentWindow;
iframe.$(".submit").bind("click",
function(){
$("#embedded123frm757809").css({height: iframe.$("body").outerHeight()
});
|
Instead of using
$("#embedded123frm757809").css({height: iframe.$("body").outerHeight()
Use:
$("#embedded123frm757809").attr('height',iframe.$("body").outerHeight());
Recommend to use:
iFrame = document.getElementsByTagName('iframe')[0];
Assuming that your `iFrame` is the first `iFrame` of the page, or the only one.
Because your ID is weird and seems to be generated.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "javascript, jquery, iframe"
}
|
Public debt and GDP in post-socialistic countries
Why is public debt in % of GDP in post-socialistic countries of Eastern Europe is less than in countries of Western Europe.
Some arguments, opinions or articles?
|
The statement is not generally true. If you look at gross debt, the Western countries of Finland, Denmark and Norway have lower debt ratios (53%,50%,34%) than post-socialistic Croatia (80%) and Hungary (79%). If you look at net debt, these Western countries have even better numbers.
So right now the correct answer is that your premise is not true.
Your statement is probably true in some form (e.g. on 'average', whatever that would mean in this context, or given some specific Western countries), but please make it exact and back it up with a source. (Perhaps in a new question, seeing that I put effort into answering your current one. Changing it post-answer would be somewhat unsporting.)
|
stackexchange-economics
|
{
"answer_score": 1,
"question_score": 1,
"tags": "gdp, debt"
}
|
how to get My phone number in Android 2.2
I'm programming Apps in Android 2.2. I tried to get my phone number in Android but can't... As below , this is my code for get phone number : ( device for Apps - SamSung Galaxy Plus )
public static String getMyPhoneNumber(Context aContext){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) aContext
.getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
String phone = getMyPhoneNumber(getApplicationContext());// return "" in here
I have added the "android.permission.READ_PHONE_STATE" in Androidmanifest.xml but when I run apps, the Phone is EMPTY...
I don't know why , although I get the " g`etSimSerialNumber(), getSimOperatorName(),getSimOperator()`,..." is OK !
The method "`getLine1Number()`" always return "" value. If you known that , please help me !
|
Try using getSubscriberId() which is the IMSI for the phone.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "android, phone number, sim card"
}
|
The graph of $e^z$ for $|z|=1$
When $|z|=1$(unit circle in complex plane), what is the graph of $e^z$? I know that this transformation makes a band into a angle area, but I have no idea about this .
|
Write $z=x+iy$ and the condition $|z|=1$ becomes $x^2+y^2=1$.
Now $e^z=e^{x+iy}=e^x e^{iy}=e^x(\cos y+i\sin y)=(e^x\cos y)+i(e^x\sin y)$. Put $x=\pm\sqrt{1-y^2}$ for each $-1\le y\le 1$ (two times, once with $+$, the other with $-$) and your graph becomes
$$f(y)=(e^{\pm\sqrt{1-y^2}}\cos y)+i(e^{\pm\sqrt{1-y^2}}\sin y)$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 4,
"tags": "complex analysis"
}
|
Does $\int_0^1 \frac{x \ln x}{1+ x^2}dx$ converge?
$\int_0^1 \frac{x \ln x}{1+ x^2}dx$ converges?
Kinda stuck doing this problem. I just need a hint on what to start with. I know that it is an improper integral and I have to use limits but I need to evaluate the integral first.
Thanks in advance for any help.
|
Yes, it converges. Use these facts:
1. Note that:
$$\frac{|x \ln (x)|}{1+x^2}<|x \ln x|$$
2. Prove that:
$$\lim_{x \to 0}x \ln(x)=0$$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "integration, self learning"
}
|
Trundle Pillar(E) and Tahm Kenchs Ult?
What happens when Trundle puts a pillar on Tahm Kenches ult destination, before the latter appears there?
|
This is Valid for not only Trundle's Ice Pillar but also Anivia's Wall. It works on not only Tham Kench, but also on Pantheon (when he uses Skyfall), Vladimir (When he uses his blood pool) and Fizz (When he uses Playful - Without the second activation).
* * *
Trundle's Ice Pillar creates terrain which functions like a wall. When any champion is placed on the same place he is bumped into the easiest path. Tham Kench will still be slowed and pushed aside (if the pillar is directly on top of the zone he's coming in).
There's however an exception, when Tham Kench uses his ultimate on an already bad spot (Close to walls or next to a lot of minions), if you manage to place it at the right spot, you can trap Tham Kench, making him unable to move (or rather, he can move but he will be glitched out because the pathing system will just make him walk around himself).
|
stackexchange-gaming
|
{
"answer_score": 7,
"question_score": 4,
"tags": "league of legends"
}
|
Truffle -- Microsoft JScript runtime error
Running truffle from command line gives me this Windows 7 popup message:
; in this way, as you said, avoid confusion with microsoft command lines.
**Update (12.07.2018)**
It is a known problem and now also part of the official truffle-documentation. They provide 4 different solutions:
* Call the executable file explicitly using its `.cmd` extension (`truffle.cmd compile`)
* Edit the system `PATHEXT` environment variable and remove `.JS;` from the list of executable extensions
* Rename `truffle.js` to something else (`truffle-config.js`)
* Use Windows PowerShell or Git BASH, as these shells do not have this conflict.
|
stackexchange-ethereum
|
{
"answer_score": 7,
"question_score": 5,
"tags": "truffle"
}
|
Knockout.js: make id based on text binding
I want to have something like following code:
<!-- ko foreach: subTopics -->
<div id='subtopic-name-here'>
<!-- /ko -->
That is I want to have id of my div as the name of subtopic(`data-bind="text:name"`).How can I do that ?
|
You should be able to use the `attr` binding for this:
<!-- ko foreach: subTopics -->
<div data-bind="attr: {'id': name}"></div>
<!-- /ko -->
<
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, jquery, knockout.js"
}
|
Using appsettings.json in .Net 6 Worker service
Is I wanted to add a singleton service that is dependent on appsettings.
How would I do this in the .Net 6 worker service startup?
using AutoMapper;
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mapperConfig.CreateMapper();
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
services.AddSingleton(mapper);
services.AddSingleton<IOrderNumberGenerator, OrderNumberGenerator>();
services.AddSingleton(new ServiceIwantToCall(<--I need too use apsettings here-->));
})
.Build();
await host.RunAsync();
|
At the moment you're trying to register an instance of `ServiceIwantToCall`. You can instead register a factory method to resolve one, and once it's resolved it will be a singleton. For example, this anonymous method:
services.AddSingleton(serviceProvider => {
// resolve the configuration provider from the container
IConfiguration config = serviceProvider.GetRequiredService<IConfiguration>();
// get the config value and instantiate a ServiceIwantToCall
// return the instantiated service
string someValue = config["myValueKey"];
return new ServiceIwantToCall(someValue);
});
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, worker, .net 6.0"
}
|
Redis: Publish pipelined/batched messages - Get pipelined/batched messages
I'm using redisson as a java redis client.
When I send a batch with multiple .publish(msg) commands to redis, does redis send these messages as a "batch/pipeline" back to the subscribers in ONE network connection so that redisson handles them all at once?
Regards, RoboFlax
|
mrniko, a worker on redisson, answered with no. <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "redis, publish subscribe, redisson"
}
|
How to open URL in flutter app with url_launcher?
I use the package url_launcher to open url, here is the code:
Future <void> _openURL(String url) async{
if(await canLaunch(url)) {
await launch(
url,
forceSafariVC: false,
forceWebView: true,
);
}
else{
throw 'Cant open URL';
}
}
ListTile(
title: Text('Google'),
onTap: () {
_openURL('
}),
But no matter what url i want to open, i get the error 'Cant open URL'
|
> I get the same error: Unhandled Exception: Could not launch
As you can see here < you have to put the following snippet at your AndroidManifest.xml
<queries>
<!-- If your app opens https URLs -->
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https" />
</intent>
</queries>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "flutter, dart, url, url launcher"
}
|
Data inconsistency between "recent replies" and one question view
I posted a question on SO. At this time, I am seeing two answers to it. However, when I click on my "envelope" icon in the top navigation bar (next to my name) and look at the "Most Recent Responses" section, I see three responses. There is a response there that I do not see in the "one topic" view, and it has been like this for several minutes. What gives?
|
Please look very, very closely at the date and times at the top of the /users/recent page.
Edit: one of the answers was deleted by the owner. C'est la vie.
Edit 2: OK, I finally fixed that long standing bug, so deleted answers should not show up in your /user/recent
|
stackexchange-meta
|
{
"answer_score": 2,
"question_score": 1,
"tags": "bug, status completed, recent activity"
}
|
Two masses connected by a string in horizontal frictionless table
Suppose that two masses with different mass are connected by a string in horizontal frictionless table. Then when there is equal acceleration for two masses, string force would extend in some direction. My question here, why don't two boxes create canceling effect for string's stretching? (Often, in we just calculate one box's force opposite to the direction of acceleration and equals to kx, which solves the problem. But why?)
|
If I understood your question correctly, you are asking why does the spring stretch when it is attached from both sides to two different masses having the same acceleration moving in the same direction.
The reason is that there is a net force exerted on the spring. Newton’s second law states that the force is equal to the mass multiplied by the acceleration. Since the two bodies have different masses and same acceleration, that means one of them is exerting a larger force on spring than the other. This net force causes the string to stretch/compress depending whether the leading mass or the lagging mass has a larger mass.
|
stackexchange-physics
|
{
"answer_score": 1,
"question_score": 0,
"tags": "homework and exercises, newtonian mechanics"
}
|
What shape results from this deformation of a circle?
Let's say we have a circle, but I want to "squish" the bottom half somehow. I decided to do it by altering the distance from the horizontal diameter to the bottom perimeter, by making it 2/3rds of what it would be if it was a perfect circle.
What shape results? Would it be an ellipse? (or half an ellipse since it's only the bottom half).
In case you're wondering, I came up with the idea when thinking about lifting bodies. This is supposed to be the cross section of a fuselage, and I wanted to make it look more like a simple airfoil.
|
You are making the transformation $(x,y)\to (x,2/3y).$ Thus, the original circle $x^2+y^2=R^2$ is transformed to $$x^2+\frac{4}{9}y^2=R^2,$$ that is the equation of an ellipse. Since you are considering only the bottom half you get half of an ellipse. But, since the top half is not changed you get a figure that is half a circle and half an ellipse.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "geometry"
}
|
Уникальные значения в списке Python
Задача: случайным образом получить 5 чисел в диапазоне от 1 до 75, занести их в список, проверить чтобы среди этих 5 чисел не было совпадений и результат вывести на экран.
Мой код:
my_list = []
for i in range(5):
numbers = random.randrange(1, 75)
my_list.append(numbers)
my_list.sort()
i += 1
print(my_list)
Как сделать проверку, чтобы программа удаляла совпадения и заменяла их уникальными значениями?
|
Встроенными средствами генерируем список нужного диапазона, перемешиваем его, и берем любой кусок длиной 5
import random
rn = [x for x in range(1,76)]
random.shuffle(rn)
print(rn[:5])
Того же самого можно добиться вручную с использованием алгоритма тасования Фишера-Йетса.
Для малой выборки подход с множествами пригоден, но по мере увеличения выборки проверка очередного элемента может занимать всё большее количество времени (главное - непредсказуемое)
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 10,
"question_score": -3,
"tags": "python, list, случайные числа"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.