INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Divisibility by 7 of pascals numbers.
This is more of a discussion question than anything but how do you tell $\frac{n!}{k!(n-k)!}$ is dividable by a prime p. I started playing around with the $\frac{n!}{k!(n-k)!}$ and came to a fairly obvious conclusions about divisibility.
> If $k\geq p^\alpha$ where $p^\alpha$ is the largest power of p less than n, then $p\nmid \frac{n!}{k!(n-k)!}$(The same conclusion can be drawn for $(n-k)\geq p^\alpha$).
So all that needs to be considers are the $k\in \\{a\in Z_n\mid a,(n-a)\geq p^\alpha \\}$. But that is about it.
Do you guys have any ideas? | It is well known that the exponent $e_p(n!)$ of the prime $p$ in the prime factorization of $n!$ is given by $$e_p(n!)=\sum_{k=1}^{\infty}\left\lfloor{\frac{n}{p^k}}\right\rfloor$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "number theory"
} |
Is it wrong for a Muslimah to address her husband by his name?
Here, in the Indian sub-continent, it is considered wrong for a Muslim woman to address her husband by his name. So she may _not_ address him by his name like, say (assuming the man's name is Abdullah), "Ya Abdullah," though she may call him by his kunniyat like "Ya Abu Ammar" (assuming that their son's name is Ammar). Personally, I don't think there's anything wrong with a woman addressing her husband by his own name, rather than his kunniyat.
I assume that the Umm-ul-Momineen may have addressed the Messenger of Allah (SAWS) by his title and not his name owing to his status. Therefore, that leaves us with the practice of the Companions (RAA). Is there any proof for either argument from the Companions (RAA) of the Messenger of Allah (SAWS)? | It's fine for a woman to call her husband by his name as long as he approves it. But of course, if the husband wants the wife to call him by any other name that he likes, then the wife should do so.
Source: <
> There is nothing wrong with a woman calling her husband by his name, because there is no evidence to indicate that that is not allowed. But people’s customs and traditions should be taken into account in this matter. If the custom in some land is that a woman should call her husband by his kunya (Abu So and so) for example, and they think that calling him by his name is ill-mannered, or if the husband does not like to be called by his name, then the women should pay attention to that, because she is required to treat her husband well and it is not good treatment to call him in a manner that he dislikes or that is regarded by people as not good.
>
> Each spouse should address the other by the name that he or she likes best, because that brings about love and affection. | stackexchange-islam | {
"answer_score": 2,
"question_score": 4,
"tags": "sharia, family"
} |
Spoke nipple broke, should I replace more than one?
I had a spoke nipple break on my rear wheel, the threaded part broke off right where it enters the wheel.
The nipples appear to be aluminum alloy, which I believe are not as durable as brass nipples.
Since I have to replace the failed nipple anyway, is it likely that others were overly stressed after the first one failed and should I replace more than one (or all of them)? Is there any issue with having some brass nipples and some aluminum?
It's a rear wheel with 32 spoke, 3 cross lacing. | I would just replace the single nipple that is broken with a new brass nipple. It sounds like these wheels are not very expensive so I wouldn't want to invest a whole lot more time and money in replacing something that may or may not be a problem in the future. | stackexchange-bicycles | {
"answer_score": 4,
"question_score": 4,
"tags": "wheels, spokes, nipples"
} |
Lock screen without using physical button Android 10
I am looking for a good way to lock the screen on my phone without using a physical button (the botton is on the edge of dying so I am preserving it for turning the phone on).
I would like to lock the phone by movement or tapping somewhere on the touch screen.
(I prefer it if this can be done without using external apps but if necessary I prefer free ones without ads.)
The f-Droid app FLock seems like it would have been ideal, but it crashes before I even have the chance to test it (). | There's a built-in option that comes with Android 10 which allows you to lock the screen without using the bottom.
In your phone settings, go to "Accessibility" and enable "accessibility menu".
This will now put an icon on the the right side of your navigation bar. Pressing on the icon will bring up a menu, with one of the options as "lock screen". Pressing on that will lock your screen just like pressing the power button would. You also have the option to power off the phone in that same menu.
See screenshot below.!enter image description here | stackexchange-android | {
"answer_score": 4,
"question_score": 2,
"tags": "lock screens"
} |
Why does sympy.init_printing change set notation?
When I call `sympy.init_printing()`, set notation changes from `{a, b, c}` to `set([a, b, c])`. Why does this happen?
In [1]: import sympy
In [2]: (x, y, z) = sympy.symbols("x y z")
In [3]: x+y**z
Out[3]: x + y**z
In [4]: (x+y**z).free_symbols
Out[4]: {z, y, x}
In [5]: sympy.init_printing()
In [6]: x+y**z
Out[6]:
z
x + y
In [7]: (x+y**z).free_symbols
Out[7]: set([x, y, z])
In [8]: {1, 2, 3}
Out[8]: set([1, 2, 3])
(It also changes the order of the items as shown) | This is a Python 2 vs. 3 issue. In Python 2, sets are printed like `set([...])`, because `{...}` set literals were not added until Python 2.7. The SymPy printer was made before Python 3.
After SymPy version 1.0, SymPy no longer supports Python 2.6, so this has been fixed in SymPy master to always print using `{...}` (even in Python 2) at < for the string printer, but apparently I missed that the pretty printer does this as well. I've put a fix in at <
So, in short, after these changes (i.e., in the development version of SymPy and in all future versions), SymPy printing will print sets using `{...}` notation. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "python, set, sympy, repr"
} |
Cannot change color of glyphicon
I have span of glyphicon
Here is code
<span class="glyphicon glyphicon-calendar blue" style="color: #1d69b4;background:transparent;border:none;"></span>
On my local machine I have it blue color
Screen1
But on server I have this
Screen2
Why so and how I can make it same color like on local server? | Happens with me many times, after deleting caches and cookies it works fine. you can try it. or try it on different browser/system. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, html, css, twitter bootstrap, glyphicons"
} |
Context switches in control paths of a non-preemptive kernel (Linux)
The Linux kernel is non-preemptive, but I just read that there could be context-switches in different control paths. Doesn't that contradict the non-preemptive nature on the Linux kernel? | No, it does not contradict this, because the latest Linux kernels are pre-emptive. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "linux, kernel, preemption"
} |
How to retain special characters in file names when converting from SVN to Mercurial (Windows)?
I'm using `hg convert` to convert a SVN repository to Mercurial. But special characters like æ, ø and å (Danish) comes out as æ ø and Ã¥ in file names.
The exact command I used was:
hg convert repo-hg
I'm using TortoiseHg 2.1.4 with Mercurial 1.9.3 on Windows 7.
How can I retain the original special characters? | Those messed up characters are UTF-8 mistranslated as (likely) Windows-1252. As @LazyBadger said, the global option `--encoding utf8` may be able to help. Can you point me to a public Danish server to try to clone? | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "version control, encoding, mercurial"
} |
python - "SyntaxError: encoding issue: with BOM"
I am trying to run some cronjobs in django.
I have three of them, 2 of them are running flawlessly. but the third one is giving me the error:
../../monthly_abo_live.py", line 1
SyntaxError: encoding problem: with BOM
the first 2 lines of this file are:
1. # -*- coding: utf-8 -*-
2. from django.core.management.base import BaseCommand, CommandError
3. ...
the other 2 cronjobs are the same as this one. i am stuck - why only this one is complaining? It seems python doesnot support `utf-8`? it cannot be, right? | According to this page:
<
you have two options...
To define a source code encoding, a magic comment must
be placed into the source files either as first or second
line in the file, such as:
# coding=<encoding name>
or (using formats recognized by popular editors)
#!/usr/bin/python
# -*- coding: <encoding name> -*-
_(Note: While the above is a direct quote, @tdelaney pointed out - and I agree - that instead of the fixed path`#!/usr/bin/python` one should use `#!/usr/bin/env python`.)_
It looks like you're using part of the second option but did not include the required first line ( `#!/usr/bin/python` ). Try inserting that before your "coding" line and see what happens. | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": -1,
"tags": "python, django, byte order mark"
} |
How SaveChanges method works in EntityFramework?
I'm working on a desktop application using EntityFramework and PostgreSQL, and since ef doesn't handle db permissions, I would like to know if `SaveChanges()` will update the entire row or just modified columns? (problem of foreign keys deleting after row update) | The SaveChanges() method goes to save all changes made to the database context which have not been pushed to the database yet, in other words, saves on the database all changes made to the context since the last call to SaveChanges() happened.
The method goes and saves the data as currently available in the context, which means it will update the entire row, not just the column you changed, if a property of your object model is set to NULL, the framework will try to save NULL in that mapping column in the database. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, entity framework, savechanges"
} |
配列に直前5秒間に入力されたデータだけを残し、前から毎秒削除していく方法を教えて下さい
Ruby
056
| hash_array = [ hash_data1, hash_data2, … ] # Hash data 0
array.push(hash_array)
array.shift if array.count > 5
| stackexchange-ja_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby"
} |
Convert a field in a Google Spreadsheet document from text to number using a formula ignoring text but keeping numbers
I have a Google Spreadsheet document with a column which contains string data which includes both numbers and text. For example:
$39,90 + Tax
$69,90 + Tax
$20 / month
I want to sum all those values, but using SUM() doesn't work because of the text included in each field. I've tried to create a new column and come up with a formula to convert those fields into:
39.90
69.90
20.00
But whatever I try, I always get `#VALUE!` or `#ERROR!`. So, how do I do this? (either directly sum all numbers contained in the original strings, or create a new column with only the numbers from the other column). | Try: `=arrayformula(VALUE(substitute(regexextract(A1:A3,"[\d\,]+"),",",".")))`
This is essentially the answer offered by user135384 in How to SUM a row of numbers after extracting numbers with REGEX?. There are a few modifications:
* that topic was concerned with summing a range, so `sum()` was removed.
* the output is a string, so the opportunity is taken to `substitute` the "decimal comma" with a "decimal point".
* convert the string to a `value`.
* * *

If not password protected..
//servername/sharename /home/Pasta\ personal/DirectoryNameInYourLocalFolderToMountTo cifs guest,uid=1000,iocharset=utf8 0 0
If password protected..
//servername/sharename /home/Pasta\ personal/DirectoryNameInYourLocalFolderToMountTo cifs username=msusername,password=mspassword,iocharset=utf8,sec=ntlm 0 0
When you are finished, hit Control-O (the letter) then Enter to save. Then Control-X to exit
Now you can either reboot, or remount your filesystems from the command prompt with `sudo mount -a`
MountWindowsSharesPermanently | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 1,
"tags": "14.04, smb"
} |
compare dates in mssql
So I have a date field in my database. Its of the type "Date". The value of the field is `2014-05-04` (yyyy-dd-mm).
How do I check, in sql, if the date is before or after today?
So far I have tied with:
SELECT * FROM table WHERE theDate > GetDate()
SELECT * FROM table WHERE CAST(theDate as Date) > CAST(GetDate() as Date)
How do you check if "2014-05-04" is before today? | The pointy bit of less than / greater than points to the lesser side.
So you want
SELECT * FROM table WHERE theDate < convert(date, GetDate()) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "sql, sql server, date"
} |
Can Cesium map run on Apache HTTP server instead of node.js environment?
I have an Apache HTTP server that handles all my requests for a Ruby on Rails project. We are thinking of adding a Cesium map component. I am wondering if I can run Cesium on the Apache HTTP server instead of setting up a node.js environment? | Yes, Cesium is completely client-side and can be served by any HTML server. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 5,
"tags": "node.js, apache, cesiumjs"
} |
Apollo Client and Update Forms
I was wondering if anyone has a good example of an update form using Apollo Client and the new query and mutation components. By update I mean:
* Populate form values with query results
* Update the component state (or apollo-link-state?) when the input is edited.
* On submission update the state (or apollo-link-state?)
I'm struggling with it right now and I'm wondering what the best way to build it would be. Should I be using Apollo-link-state to store the form state? If not, I can't find a way to map the props from the query component into component state object without using the query HOC. Any examples would be great!
Thanks! | If the state doesn't need to be accessed by other parts of your app, `apollo-link-state` is probably overkill -- regular component state will do just fine. Just create a component like you would when using the HOC:
class MyComponent extends React.Component {
constructor (props) {
super(props)
this.state = {
fieldA = props.myQuery.fieldA
fieldB = props.myQuery.fieldB
}
render () {
// your form fields here
}
}
}
You can then just do:
<Query>
{({data, loading})=>(
if (loading || error) return null
<MyComponent myQuery={data.myQuery}>
)}
</Query> | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "reactjs, graphql, react apollo, apollo client"
} |
How to get the Date Of Birth given number of years months and days of a person in java
Given year, month and days of a person, need to get Date of Birth - Example - 19 years 1 moth and 2 days 16-Sept-2010 (have calculated it manually, may not be accurate) | LocalDateTime.now().minusYears(years).minusMonths(months).minusDays(days) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "java"
} |
How to check renamed file in git
Some files name has been changed in the project. Project is maintained using git. How can I get this information ?
I know that we can rename the files in git using git mv command. but Can i check this formation for previously renamed file (in older commits). | Git does not track files, but it tracks content that happens to be stored in files. This is the cause why you cannot track empty directories, as there is no content inside them, just files and also the cause why there is no explicit copy or rename tracking in git. Renames and copies are determined dynamically in git and in the commands that could be interested like `git log` or `git diff`, you can control whether renames and copies are detected and how much change in a file is still considered a rename or copy. The `git mv` operation is just a convenience synonym for the deletion of the old file and addition of the new file. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "git"
} |
Clean/reduce static in electret microphone caused by "dirty" Raspberry Pi pin output voltage
I'm currently trying to wire up an electret microphone to a Raspberry Pi. I just figured out how to wire it up to a button cell battery after a couple of days of struggling. Still learning electronics so bear with me.
!schematic
simulate this circuit - Schematic created using CircuitLab
I want to remove the button cell, and replace it with the +3.3V to GRND pins on the Raspberry Pi 3B+, but the problem I'm encountering is when connecting ground to the ground pin on the Pi, I get a lot of audible static in my voice recordings.
I'm assuming that this is because the ground pin isn't limited to -3.3V like with my button cell.
**Is there a way to limit the negative voltage potential of the ground pin?**
My instincts tell me that using a capacitor can accomplish this somehow, but I'm not sure of the approach. | Expanding on KD9PDP's answer.
If the 3.3V from the RPi is noisy, you can improve the filter by adding a series resistor, electret mics don't draw much current. You may need to experiment with the resistor values.
If you have noise on the ground wires, that is harder to fix. If you can float your RPi, connect the mic circuit ground to one point at the RPi.
!schematic
simulate this circuit - Schematic created using CircuitLab | stackexchange-electronics | {
"answer_score": 1,
"question_score": 1,
"tags": "dc, raspberry pi, ground"
} |
How do I find unique rows in a numpy array with different shaped rows?
My numpy array consists of lists of different orders as rows. Eg:
array = [[item1, item2],
[item1, item2],
[item1, item2, item3],
[item1, item2, item3, item4]]
#required output
unique_rows = [[item1, item2],
[item1, item2, item3],
[item1, item2, item3, item4]]
I want to find unique rows for an array like this where a row length maybe 8 or 80 in length. I tried to use the np.unique() method but I got this error:
ValueError: shape mismatch: objects cannot be broadcast to a single shape | If the items are hashable, you could try:
set(tuple(i) for i in array)
which gives:
{('item1', 'item2'),
('item1', 'item2', 'item3'),
('item1', 'item2', 'item3', 'item4')} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python 3.x, numpy"
} |
Ocaml equivalent for Lisp's let*?
I'd rather use `let ... and ... and ... in` than nested `let`'s when possible, but the normal let syntax doesn't allow this for expressions that depend on each other.
Not allowed:
let encrypt password =
let seed = int 16
and keys = xlat seed (length password)
and plaintext = map code (explode password) in
map2 logxor plaintext keys
Does OCaml have an equivalent to Lisp's `let*`, which does allow this? | Nested `let`'s don't need nested indentation, so that's good enough. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "lisp, ocaml, let"
} |
Steps to display clientSide Time on contentpage asp.net / c#
My master page has text box : txt1 contentplaceholder= holder1
my content page has a textbox : txt2
when I display the content page, it has to display the client side time (not the server time) automatically without any click events. txt2.text ==> dd MMM format (eg : 31 May)
i found the following code :
<input type="hidden" id="clienttime" runat="server" />
(function $ {
$("#clienttime").val(new Date().toUTCString());
});
but, its not working and i am not sure about how to call this function and where to insert the code exactly. Please explain in step by step | All you need is
<input type="hidden" id="clienttime" runat="server" />
<script>
$("#clienttime").val(new Date().toUTCString());
</script>
BUT, this puts the time in a hidden field so it can't be seen.
If it should be seen, change the hidden input to a label or normal textbox.
<label id="lblClientTime"></label>
<script>
$("#lblClientTime").text(new Date().toUTCString());
</script>
Requires jQuery. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, client side scripting"
} |
Squaring sides of an inequality
I want to know what will happen to the inequality in these cases
$a>x>b$ If $a$ and $b$ negative When i square the both sides of it Is it going to be $b^2>x^2>a^2$
Ok but what would happen if $a$ is a positive and $b$ is a negative number when i square ? EXAMPLE $2>x>-1$ another case $2>x>-4$
i forgot mentioning this case ? If it is something like
$2>x>-2$ | I assume that all values in mentioned inequalities are real numbers.
When you square something the sign goes out: $x^2 = (-x)^2 = \vert x \vert^2$. So the form of your inequality after applying the power of two depends on absolute values. Suppose you had $a<x<b$ such that $\vert a \vert < \vert b \vert$, then nothing changes, you still has $a^2 < x^2 < b^2$. This is a safe condition for squaring your inequality. Another possible case is when the condition $\vert a \vert < \vert b \vert$ is not satisfied, for example, consider the following inequality: $-2 < x < 1$. After straightforward squaring it becomes $4 < x^2 < 1$, which is obviously incorrect, but you can now rewrite it as $1 < x^2 < 4$ or $b^2 < x^2 < a^2$.
So the general rule is that for given inequality $a < x < b$ if $\vert a \vert < \vert b \vert$ then $a^2 < x^2 < b^2$, else if $\vert a \vert > \vert b \vert$ then $b^2 < x^2 < a^2$. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "inequality"
} |
Character Model crashes game (Unity VR)
I am creating a VR game. Currently, I'm testing it on an `Android` device.
Now I when I run the application it runs smoothly and without any issue.
However when I add the following model:
 {
field.attr('value', value);
return true;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, date, forms, sheepit"
} |
CSS: How do I select CSS for all the <li> elements that do have not been styled yet?
So I've marked up some of the edge cases in my list (first, second, last, and the last odd child) like so:
/* First and second elements */
li:first-child, li:first-child + li {
...
}
/* Last odd and last elements */
li:last-child {
...
}
/* CSS for second last list element, only when it's odd. */
li:nth-last-child(2):nth-child(odd) {
...
}
How do I select identical CSS for all the remaining elements? And could you walk me through the process so I know how to do it next? | Just define `li` styles. The psuedoclass will override those styles because of specificity rules. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "css"
} |
Passing an array to a named port connection
If I am sending some parameters to any module in verilog like:
SUM( .a(a), .b(b), .out(out));
It will work fine. What if I want to pass an array as input or want to take arrays as output? For example:
integer a=10;
integer b=20;
integer c[2:0]={2,4,6};
integer d=0;
any module(.input1(a), .input2(b), .input3(c),.....)
But it will give error that "cannot access memory c directly".
So, how can I send or receive an array in named port connection? | Inputs can be arrays from SystemVerilog 2009. Verilog 1995, 2001 and 2005 do not support array ports.
module dut(
input [7:0] a [3:0]
);
endmodule | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "verilog"
} |
system.windows.form.key in WPF c#
I'm new to WPF and I want to use 'Keys' object in WPF. That's how my code looks like in WinForm
public List<Keys> keysList= new List<Keys>();
I want to use this in my WPF app but it can't recognize 'Keys'. Is there any alternative? I searched the web and found nothing.
Thanks!!!! | I think you are using the Key Enumeration Namespace: System.Windows.Forms, where you should be using Key Enumeration Namespace: System.Windows.Input | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "c#, wpf"
} |
What programming languages are scopes written in?
I'd like to get started writing a Scope for Ubuntu.
What programming languages are available and what should I choose? | Once upon a time, scopes had Python and Vala bindings. Python was the recommended language. This actually still applies for the desktop and Unity 7. However, while it will still be around for a bit (i.e. it's still shipped in Ubuntu 14.04 LTS), we're phasing out Unity 7 in favour of Unity 8 in the new world where we'll have a single Unity codebase that runs across devices and form factors (e.g. phone and desktop).
So at this point, the **recommendation for new projects is to write scopes for Unity 8**. In Unity 8 **the supported language is C++**. All current tutorials and API docs are based on C++.
The reasons for going for C++ are twofold: performance and compatibility with the Qt APIs available throughout the platform.
We do recognize the value of supporting other bindings. While Go is still not on par with the C++ bindings, **you can also already write scopes in Go** (see the preliminary documentation) and further down the road we're also _considering_ adding JavaScript. | stackexchange-askubuntu | {
"answer_score": 12,
"question_score": 7,
"tags": "application development, scopes"
} |
Can't access jQuery events on object
I'm trying to check the events that are attached to an object in its event handler. Why is the check below yielding undefined?
HTML:
<button>Print out events in console</button>
JS:
$('button').on('click', function(ev) {
console.dir($._data($(ev.target), 'events')); // undefined -- Why?
});
JSFiddle | It must be like the below as the first argument is a `DOM` element:
$('button').on('click.myNamespace', function(ev) {
console.dir($._data(ev.target, 'events')); // undefined -- Why?
});
> More info from jQuery Blog **$(element).data(“events”)** : In version 1.6, jQuery separated its internal data from the user’s data to prevent name collisions. However, some people were using the internal undocumented “events” data structure so we made it possible to still retrieve that via .data(). This is now removed in 1.8, but you can still get to the events data for debugging purposes via $._data(element, "events"). Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, jquery, event handling"
} |
How can I match all elements that start with a number or a relevant symbol in MYSQL?
Here's my "where" part:
$fornecedor->where = "nome_fantasia REGEXP '^[0-9+#-]*$%'";
It does not work. How can I match it? | `REGEXP` doesn't want `%` at the end. Also, your pattern searches the entire string because it starts with `^` and ends with `$`. Try this:
$fornecedor->where = "nome_fantasia REGEXP '^[0-9+#-]'";
This searches only for a single matching character at the beginning of the line, since you don't care about anything after that. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "php, mysql, regex"
} |
How do I query info from 2 tables based on 2 variables?
I'm trying to select all from the table Apparel_Colors where the value Apparel_Color_Palette within the Apparel_Colors table equals the value Apparel_Color_Palette within the Apparel table, in which the Apparel_ID within the Apparel table equals 1.
My bad pseudo logic query:
select *
from Apparel_Colors
where Apparel_Colors.Apparel_Color_Palette = Apparel.Apparel_Color_Palette
AND Apparel.Apparel_ID = 1;
Basically, I only know the Apparel_ID. And, with the Apparel_ID I'm trying to get all the colors within the apparels color palette.
 :
select * from Apparel_Colors, apparel where Apparel_Colors.Apparel_Color_Palette =
Apparel.Apparel_Color_Palette AND Apparel.Apparel_ID = 1; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql"
} |
Ubuntu Core serial port on Raspberry PI 2
I am trying to package an applications which uses a serial port as a Snap. Target platform is Raspberry Pi 2 running Ubuntu Core 16.
From the documentation I gathered that I should add the 'serial-port' plug and then connect it, but that interface is not available on RPi. I am using an USB to serial adapter at /dev/ttyUSB0.
My application works in devmode, but on strict permission is denied.
This is my minimal snapcraft.yaml:
name: myapp
version: 0.0.1
architectures: [armhf]
summary: reads stuff
description: |
writes stuff
grade: devel
confinement: devmode
apps:
writer:
command: bin/serialreader.wrapper
plugs:
- serial-port
parts:
myappfiles:
plugin: dump
source: . | Indeed, the `serial-port` slot is meant to be implemented by a gadget snap, by a device manufacturer. Serial ports cannot currently be accessed from strict confinement on Ubuntu Core without a gadget snap exposing them, and cannot be accessed from strict confinement on classic Ubuntu at all.
See this bug as well as this bug for more information. It's my hope that this situation changes soon. Until then, the only way to do this is to create your own gadget exposing the serial devices you need, create your own Ubuntu Core image containing it, and flash that image to the Raspberry Pi.
* The official Raspberry Pi 2 gadget can be found here. You can fork it and modify it as necessary.
* A tutorial for creating your own image can be found here.
Please do mark those bugs as affecting you if that's the case. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 2,
"tags": "snap, ubuntu core, raspberrypi, serial port"
} |
Selenium Robot Framework Pop Up Access
I am not able to access a pop up window using `selenium` webdriver robot framework.
Steps:
1. site "<
2. click on "Search By Vehicle" Tab.\
3. pop up window opens
I tried to access the pop up using "select window" keyword with some locators like `id` and `name` but was unsuccessful. It shows
ValueError: Window locator with prefix 'id' is not supported.
How can I select this pop up window and access elements over it? | The Problem is that the popup is inside a iFrame.
<iframe id="popup_selector" src="//carlightking.com/selector/selector-home-popup.php" width="100%"></iframe>
hence you have to explicitly select the iframe first
*** Test Case ***
CarLightKing
Open Browser
Wait Until Page contains Element link=Search by Vehicle 5s
Click Element link=Search by Vehicle
Select Frame id=popup_selector | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "selenium, robotframework"
} |
Remove rel=shortlink from HTTP header
HTTP header of posts on my site looks like this:
accept-ranges:bytes
cache-control:public, max-age=0,public,public
content-encoding:gzip
content-length:5369
content-type:text/html; charset=UTF-8
date:Fri, 08 Dec 2017 07:27:40 GMT
expires:Fri, 08 Dec 2017 07:19:33 GMT
link:< rel=shortlink
server:Apache
status:200
vary:Accept-Encoding
How to remove this line from HTTP header responce:
link:< rel=shortlink
_Please, do not confuse this with`<head> </head>` section of HTML, I removed it from there already, I would like to remove it from HTTP header response too._ | <?php
add_filter('after_setup_theme', 'remove_redundant_shortlink');
function remove_redundant_shortlink() {
// remove HTML meta tag
// <link rel='shortlink' href=' />
remove_action('wp_head', 'wp_shortlink_wp_head', 10);
// remove HTTP header
// Link: < rel=shortlink
remove_action( 'template_redirect', 'wp_shortlink_header', 11);
}
Tested in WordPress 4.4 and up to 4.9.1 | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 2,
"tags": "headers, http"
} |
Why do we distinguish between view and pure?
I understand that the difference is that, while neither may change the state, `view` may read the state and `pure` may not. I also understand that it's useful to distinguish possibly state-changing functions from those guaranteed not to change the state.
My question is, why is it useful to indicate that a function won't even access state? Why doesn't `view` suffice? | If a function is `pure`, then no matter how many times you call it, if you pass the same parameters, it will always return the same value(s).
Example:
function pureFunction(uint a) pure returns(uint){
return a + 5;
}
will always return `6` if you pass `1` as parameter `a`.
However, if the function is `view`, it's reading from the state, which may have changed since the last time you called it.
Example:
uint B = 5;
function viewFunction(uint a) view returns(uint){
return a + B;
}
will also return `6` if you pass `1` as parameter `a`. But if another function modifies the value of `B`, then next time you call `viewFunction(1)`, it will return something different. | stackexchange-ethereum | {
"answer_score": 7,
"question_score": 4,
"tags": "solidity, contract development, contract design"
} |
Join two strings in Scala with one to one mapping
I have two strings in Scala
**Input 1** : "a,c,e,g,i,k"
**Input 2** : "b,d,f,h,j,l"
How do I join the two Strings in Scala?
**Required output** = "ab,cd,ef,gh,ij,kl"
I tried something like:
var columnNameSetOne:Array[String] = Array(); //v1 = "a,c,e,g,i,k"
var columnNameSetTwo:Array[String] = Array(); //v2 = "b,d,f,h,j,l"
After I get the input data as mentioned above
columnNameSetOne = v1.split(",")
columnNameSetTwo = v2.split(",");
val newColumnSet = IntStream.range(0, Math.min(columnNameSetOne.length, columnNameSetTwo.length)).mapToObj(j => (columnNameSetOne(j) + columnNameSetTwo(j))).collect(Collectors.joining(","));
println(newColumnSet)
But I am getting error on j
Also, I am not sure if this would work! | object Solution1 extends App {
val input1 = "a,c,e,g,i,k"
val input2 = "b,d,f,h,j,l"
val i1= input1.split(",")
val i2 = input2.split(",")
val x =i1.zipAll(i2, "", "").map{
case (a,b)=> a + b
}
println(x.mkString(","))
}
//output : ab,cd,ef,gh,ij,kl | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "scala"
} |
Is there a way to update processor_group variables in a processor in NiFi?
I want to update my processor_group variable via a processor. Even ExecuteScript works. Can this be achieved? | You can only update the variable registry through the REST API, the same way the UI does.
It is a PUT to /process-groups/{id}/variable-registry:
< | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "apache nifi"
} |
Sum of arithmetic series and geometric sum
Sum of first 7 arithmetic sum is 28. Sum of their squared values are 812. What's the increment/difference (a) of first sequence?
Sn = 1/2 * n * (a + Un)
S7 = 7/2 * (a + U7)
28 * 2/7 = (a + U7)
8 = a + U7
then the second one
Sn = U1 * (1- r^n) / (1-r)
S7 = U1 * (1 - a^7) / (1-a)
812 = U1 * (1 - a^7) / (1-a)
812 = U1 * (1 - (8-U7)^7) / (1-(8-U7))
I don't know how to solve this '__') asking for a friend | You can use the fact that $a_7=a_1+6d$ where $d$ is the difference between consecutive members.
Then $S_7=\frac{a_1+a_1+6d}{2}\cdot 7=28$ or $a_1+3d=4$, $a_1=4-3d$.
Sum of squares of the first seven members: $$(4-3d)^2+(4-2d)^2+(4-d)^2+4^2+(4+d)^2+(4+2d)^2+(4+3d)^2=7 \cdot 4^2+d^2(9+4+1+1+4+9)=112+28d=812 \rightarrow d^2=25 \rightarrow d=\pm5$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "sequences and series"
} |
What are the original settings for Ayatana blacklist in Loki? 2 wifi icons
I wanted to make steam icon visible on system tray, so I edited `/etc/wingpanel.d/ayatana.blacklist` and I accidentally deleted all of the blacklist names instead of only steam. So the outcome is that now I have two wifi icons on the tray and I wanna get rid of the other one. Could you please tell me what were the original names there? Thank you! | This file is in the `elementary-default-settings` package:
$ dpkg -S /etc/wingpanel.d/ayatana.blacklist
elementary-default-settings: /etc/wingpanel.d/ayatana.blacklist
You can download it and extract its contents
$ sudo apt-get --download-only --reinstall elementary-default-settings
$ dpkg --vextract /var/cache/apt/archives/elementary-default-settings*.deb /tmp
And now you check the contents of the file, overwrite the old one, etc. at `/tmp/etc/wingpanel.d/ayatana.blacklist` | stackexchange-elementaryos | {
"answer_score": 0,
"question_score": 1,
"tags": "release loki, wingpanel"
} |
Proper way to queue system notifications?
I wrote the following jQuery plugin that is basically just a simple notification system used to display messages to the user. This works great if you have 1 message to display at a time. However, if you have multiple messages to display to the user they obviously display right on top of one another.
My question is, given this code, how would you recommend that I implement a message queuing system? I'd like to only show 1 message at a time, so when the close button is clicked or the fadeOut has completed, the next message would fire off and start the process.
My initial thought was to check if a message was already being displayed and maybe push this current message onto an array then pop it off when the first message is being remove, but I cannot seem to figure that out.
JsFiddle link | I assume you want to display notifications in the order you receive them. Use an array as a queue (`push(x)` to add a notifications to the end of the list, `shift()` to grab the next message received from the front of the queue).
Add a handle to detect when the message is closed or read, and then `shift()` the notifications queue to grab the next message to display, which will remove it from the queue. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "jquery, jquery plugins, message queue"
} |
solaris + grep syntax in solaris
my target is to match Exactly the string snmpmanager from hosts file on solaris & linux
the following command work on Linux (red-hat 5.1) but not for SunOS , please advice how to fit the syntax to solaris?
example from solaris OS
grep -icE '(^|[[:space:]])snmpmanager($|[[:space:]])' /etc/hosts
grep: illegal option -- E
after I fixed it to
egrep -i '(^|[[:space:]])snmpmanager($|[[:space:]])' /etc/hosts
or egrep -i '(^|[\s])snmpmanager($|\s])' /etc/hosts
or egrep -i '(^|[\t])snmpmanager($|\t])' /etc/hosts
but I don’t get any match output (but snmpmanager already defined in host file) ??
my host file
10.170.10.5 loghost
10.170.10.61 Master SyslogSer vip Tcc NtpServer1 NtpServer2 snmpManager snmpManagerPA1 snmpManagerPA2 | I don't think the standard Solaris (e)grep understands the `[[:space:]]` syntax so you would have to use something like
egrep -i (^| |<-TAB->)snmpmanager($| |<-TAB->)
where `<-TAB->` is `Ctrl-V``Tab`
If you use /usr/xpg4/bin/egrep then it works as expected.
/usr/xpg4/bin/egrep -i '([[:space:]])snmpmanager($|[[:space:]])' /etc/hosts | stackexchange-serverfault | {
"answer_score": 4,
"question_score": 2,
"tags": "solaris, grep"
} |
Setting the fill of a rectangle drawn with canvas to an RGB value
w.create_rectangle(x, y, s, s, fill=(109,170,44))
I want to achieve something like this, but when I try it I get an error. I'm creating several rectangles using an array / list and I want them to be this shade of green, but can't seem to find a way that works. So far the only thing that has worked is
w.create_rectangle(x, y, s, s, fill="green")
But it's not the shade I want. Any help is greatly appreciated, and I feel although I'm missing something big and really easy here, but I've been hung up on this problem for awhile now. | You are getting an "unknown color name" error. You have to either use the name from the list of colors or use hexadecimal format: #RRGGBB
To convert a tuple of integer values to RGB format use this:
colorval = "#%02x%02x%02x" % (109, 170, 44)
This will result in _#6daa2c_ | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "python 3.x, tkinter, tkinter canvas"
} |
Free y axis in ggplot and plotnine
I need help with a plot in python. I used the example dataset mpg.
import pandas as pd
import numpy as np
from plotnine import *
from plotnine.data import *
import matplotlib.pyplot as plt
%matplotlib inline
mpg.head()
mpg = mpg.loc[(mpg.manufacturer=="audi") | (mpg.manufacturer=="jeep") ]
p = ggplot(aes(x='displ', y='manufacturer'), mpg)
I obtain this plot: , for example something like this: ) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, r, ggplot2, plotnine"
} |
Error in int vba function calculation?
I am doing a calculation of values using Microsoft Excel vba.
I have a portion of codes like the below:
`INT(151.2 * 100)`
I notice that the result from this calculation is 15119 but the correct result should be 15220.
It is ok if i remove the `INT()`
`151.2 * 100`
The result returned will be 15220.
Can anyone advise why is there such a difference and whether it is correct to simply remove the `INT()` to achieve the correct result? | Floating-point arithmetic.
a = (151.2 * 100)
Print Int(a)
15119
Print a
15120
Print a = 15120
False
There is no double-precision number to represent the result of `151.2 * 100` exactly as 15120. The closest one is apparently just under 15120. When you `Int` it, it gets truncated, i.e. rounded down to 15119.
Instead of truncating, you could round:
Print CInt(a)
15120
Print Round(a)
15120
Note that if you have a variable `i` of type Integer and you just say `i = 151.2 * 100` as you suggest, then you are _implicitly_ coercing the result to an integer i.e. implicitly saying `i = CInt(151.2 * 100)`. I think it's better practice to be explicit. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "vba"
} |
Is it possible to split multipolygon into smaller polygons?
i have a multipolygon geometry like this: !Gray area is the area where is no rivers, roads, villages and etc.
I need somehow to split this geometry to smaller polygons, to gray ones. So, i would like to ask if it is possible and how i could do that. Thanks. | Depending upon the implementation you are using, a multi-polygon is a collection of polygons. If you can obtain a list of the polygons comprising the multi-polygon via you implementation's API then you are a large way to doing what you need. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "polygons, geotools"
} |
How to differ between a upper or lower case words in a SELECT query
Basically i feel like the problem is simple. but cant find any fix for it.
In a login form, i use php to query my database which on its side check the passed username and password by selecting from the database table any row that has that 2 values.
What seems to be the problem is when i login for ex.
> user: mm
>
> pass: oo
that works. and that is right as they are on the db table.
but now if i use
> user: MM
>
> pass: oo
still works?? which should not. As my db has only user as 'mm' not 'MM'. I need it to distinguish between upper and lower because in other rows i have mix of upper an lower letters | You'll have to change the collation/encoding of the column from a "case-insensitive" encoding to a case-sensitive one, such as `utf8_general_cs` or `latin1_general_cs` | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "php, mysql, select"
} |
how do i count the replaced char in a string?
[so i put the string like "hello world" and want to change "l" to "a" then i need to count the no. of changed letters how do i count the change letters only? help pls[1]: < | a possible solution would be computing the length difference between the input string and the same one with find string substituted with "":
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
newStringTB.Text = inputTB.Text.Replace(findTB.Text, replaceTB.Text)
noOfReplacedTB.Text = Len(inputTB.Text) - Len(Replace(inputTB.Text, findTB.Text, ""))
End Sub
just change:
* "Button1" to your actual command button name
* "newStringTB", "findTB", "replaceTB" and "noOfReplacedTB" to your actual textboxes names | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": -1,
"tags": "vba, vb.net"
} |
Help for substitute of a gym device
In my local gym, the _butterfly_ device of the multi-gym in not working properly. I want to have proper shapes and cuts of my body especially my abdomen part. Can anyone give a suitable substitute device or workout? Well I mean this..
 <
* wide grip push ups <
* furniture glider flys/and two roller or dumbbell push up roll out < and <
* resistence band flys <
* dips with elbows out (not close to the body) <
* one arm bench presses with max ROM <
* TRX bodyweight flys < | stackexchange-fitness | {
"answer_score": 3,
"question_score": 1,
"tags": "abdominals, getting in shape"
} |
how do I change my bash_profile to read and expose all the func() defined in some script files I have already?
I have a few `.sh` here and there with some `func()` defined in them I want to change my `bash_profile` to read all of them and expose to my bash shell | You need to ensure that no harmful code is called within your `.sh`. Ideally, it should only include functions. Then you can `source` the file.
A simple test.sh I made:
$ cat ./test.sh
function test_source() {
echo "** Called with $1"
}
and sourcing/invoking:
$ . test.sh
$ test_source asd
** Called with asd
So once you have tested this, you can add it to your `~/.profile` or `~/.bash_profile` by sourcing it there:
if [ -f "/path/to/your/dotsh.sh" ] ; then
source "/path/to/your/dotsh.sh"
fi
Logout, login (or open a new terminal) and the functions should be available to you | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "bash"
} |
Is $\{s_0 w s_1 : s_0s_1\in L_1, w\in L_2 \}$ context free if $L_1$ and $L_2$ are?
In class, it was alluded to that a language: \begin{equation*} \\{s_0 w s_1 : s_0s_1\in L_1, w\in L_2 \\} \end{equation*} would be context free, if $L_1$ and $L_2$ are context free.
Intuitively, that doesn't make sense to me. I tried doing my own research and attempted a proof using the pumping lemma, but didn't get anywhere. Maybe I misunderstood? If that is correct, how could I prove it (or convince myself). | Class is right.
The pumping Lemma is not very helpful in this setting. It is usually used to show a given language non-context-free.
As for your language, first try to understand the special case, where $L_s = \\{A\\}$ for a special symbol $A$, that is try to prove that the language $\\{ s_1As_2 \mid s_1s_2\in L_1 \\}$ is context-free whenever $L_1$ is context-free.
In the comments below, Yuval gives a hint how to perform the construction with a PDA, for the general case. Start an automaton for $L_1$. At any nondeterministic moment (once during the computation) interrupt the $L_1$ computation and push a new bottom-of-stack symbol. Then use that as a marker to simulate a PDA for $L_2$ which stops when we accept by empty stack. Remove the marker, and happily resume the computation on the second part of $L_1$.
A simple construction using CF grammars is given by Yuval in his answer. | stackexchange-cs | {
"answer_score": 4,
"question_score": 3,
"tags": "formal languages, context free, closure properties"
} |
How to run rake task, not used cron
Ruby 1.8.7 I have a post.rake and how to run rake task every day?
1. solution add a script in cron:
0 0 * * * /path/script.sh
script.sh:
#!/bin/bash
source /home/user/.bashrc
cd /path/to/project
export RAILS_ENV=production
bundle exec rake post:crontask -s
May have other solutions? | That's not a bad approach. There are some popular Ruby gems that make things easier. whenever and rufus-scheduler are both popular. They also work with Ruby 1.8.7, which isn't likely to be true of most alternatives. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, ruby"
} |
How to Change Y axis on a pandas dataframe plot
I have the following list:
[('und', 52),
('die', 36),
('von', 33),
('der', 29),
('in', 20),
('das', 17),
('für', 17),
('eine', 15),
('des', 14),
('Die', 14),
('ODP', 14),
('wurde', 13),
('zu', 13)]
With the following code I convert it to a pandas dataframe:
df = pd.DataFrame(sorted_by_value, columns=['Wort', 'Vorkommen'])
Then I plot it:
fig, ax_lst = plt.subplots(1,1) # a figure with a 2x2 grid of Axes
df10 = df[:20]
df10.Vorkommen.plot(kind='barh')
plt.show()
How can I change the y axis from the index to the words?

(x^2+b^2)}$
> Integrate $$\int_0^\infty \frac{x\mathrm dx}{(x^2+a^2)(x^2+b^2)}$$
Let, $x^2=\dfrac{1}{z}$ and, $2x\mathrm dx=-\dfrac{1}{z^2}\mathrm dz$
$$-\frac{1}{2}\int_\infty^0 \frac{\mathrm dz}{2+z(a^2+b^2)}$$ $$-\frac{1}{2(a^2+b^2)}\int_\infty^0 \frac{\mathrm dz}{\sqrt{\dfrac{4}{(a^2+b^2)^2}}+(\sqrt{z})^2}$$ $$-\frac{1}{2(a^2+b^2)}[\ln|\sqrt{z}+\sqrt{z+\frac{4}{(a^2+b^2)^2}}|]_\infty^0$$
But, I don't get the answer which my book got. I don't think that I have made any mistake. The answer of my book is $\frac{1}{a^2-b^2}\ln\frac{a}{b}$ If whole process of my work needed than, I will add it. | As regards your substitution $x^2=\dfrac{1}{z}$, you should have $$\int_0^\infty \frac{x}{(x^2+a^2)(x^2+b^2)}\,dx=-\frac{1}{2}\int_\infty^0 \frac{dz}{(1+za^2)(1+zb^2)}.$$
Assuming that $a^2\not=b^2$, I propose a simpler substitution $t=x^2$: $$\begin{align}\int_0^\infty \frac{x}{(x^2+a^2)(x^2+b^2)}\,dx&= \frac{1}{2}\int_0^\infty \frac{1}{(t+a^2)(t+b^2)}\,dt\\\ &=\frac{1}{2(a^2-b^2)}\int_0^\infty \left(\frac{1}{t+b^2}-\frac{1}{t+a^2}\right)\,dt\\\ &=\frac{1}{2(a^2-b^2)}\left[\ln\left(\frac{t+b^2}{t+a^2}\right)\right]_0^\infty=\frac{\ln(|a/b|)}{a^2-b^2}. \end{align}$$ | stackexchange-math | {
"answer_score": 4,
"question_score": 1,
"tags": "calculus, integration, definite integrals"
} |
Module not found while compiling in React
While trying to import the `collection-preview.components.jsx` file in the `shop-page.jsx`, there occurs an error saying:
"Module not found: Can't resolve '../../components/collection-preview/collection-preview'"
URL of the code and the error is shared in the link: !1
I would like to know what am I missing here and why the files are not getting compiled. | Your file called `collection-preview.component` but you import `collection-preview`, just change the name to `collection-preview.component`, it should work
You could also drop `js` and `jsx` ending for files when importing :) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, reactjs, module, compiler errors"
} |
Can I repair light scratches on a laminate countertop?
I was foolish and scratched my laminate countertop, which I would like to repair. Everything I have found online shows solutions for filling in chips (or deeper cuts), mainly in laminate that has a uniform colour. My counter top varies in colour, and the scratches appear to only be in the top coating, so I am hoping there is another solution.
 {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
return(xmlhttp.responseText);
}
};
xmlhttp.open("GET", path, true);
xmlhttp.send();
}
The chrome returns: `XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'null' is therefore not allowed access.` I am using pure js and I want to keep it that way. Is there any way to fix it in js? Thx | Simply add below ajax request header at server side to share data over cross domain
Access-Control-Allow-Origin: *
OR
Access-Control-Allow-Origin: <server1 IP or domain name>
For your question
function sendGet(path) {
var xmlhttp;
xmlhttp.setRequestHeader("Origin","your server ip or domain of client server");
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
return(xmlhttp.responseText);
}
};
xmlhttp.open("GET", path, true);
xmlhttp.send();
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, ajax"
} |
yum client not reflecting state of the server
I am trying to setup a local yum repo and have religiously followed the steps as Click here.It seems to be working fine. But the only problem on when i add new rpm to this repo. executed "yum makecache" and it returns "Metadata file does not match checksum" | The problem was due caching and the cache was due to a http caching. have added "http_caching=none" in yum.conf file.Thus the yum doesn't cache any of the information and retrieves the same from the server.If you still want to use htpp caching you have to wait until the cache times out. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "yum, rhel"
} |
solr proximity search with NOT
For proximity search in SOLR, I am forming query like "word1 word2"~10. This is returning the documents which are containing word1 and word2 are with in 10 words distance.
Now i want reverse of this search , i.e I want to get the documents which are not containing word1 and word2 are with in 10 words distance.
To get this I made query like NOT "word1 word2"~10.
But it is not returning any documents. Please advice. | Can you try with the following negative query:
+word1 +word2 -"word1 word2"~10
You are effectively searching all documents that contain both "word1" and "word2", excluding those that are within a span distance of 10. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "apache, solr, proximity"
} |
Where can I find software images for shortcuts
I am creating desktop shortcuts on Ubuntu and I did the whole process of finding the executable in the applications folder then copying them to desktop and finally right clicking and allowing them to be launched. The problem I have is that the shortcut has no image. On windows I would easily go to the installed path of the program and find its image but on Linux I have no idea where I can find those files. | First search the package of your executable
dpkg -S /full/path/to/executable
Then list that package's contents, see if it contains icons.
dpkg -L packagename | stackexchange-superuser | {
"answer_score": 0,
"question_score": 0,
"tags": "linux, ubuntu"
} |
Meteor - How to use Blaze.renderWithData in a bootbox and have the result remain reactive?
I am using the following:
let box = bootbox.dialog({title:'',message:''});
box.find('.bootbox-body').remove();
Blaze.renderWithData(template,doc,box.find(".modal-body")[0]);
It renders correctly, but is not reactive.
I suspect I have a problem passing in the doc directly, and have the _id of the doc available.
What should I be passing to renderWithData in order for the result to be reactive? | I found my solution.
Instead of
let doc = MyCollection.findOne({_id});
Blaze.renderWithData(template,doc,box.find(".modal-body")[0]);
Or
Blaze.renderWithData(template,MyCollection.findOne({_id}),box.find(".modal-body")[0]);
I switched to
Blaze.renderWithData(template,function(){
MyCollection.findOne({_id})
},box.find(".modal-body")[0]);
This now makes the dialog reactive. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "templates, meteor, meteor blaze, bootbox"
} |
Integer in the programming language Lua
I want to get all the numbers by `table.concat`
number = { 100.5, 0.90, 500.10 };
print( table.concat( number, ', ' ) )
-- output 100.5, 0.9, 500.1
number = { 100.5, 0.90, 500.10 };
print( table.concat( math.floor( number ), ', ' ) )
-- output 100
How can fix this bug? | You can't as there are no table transformation functions out of the box in Lua, you have to create a new table with transformed values and concat that:
number = { 100.5, 0.90, 500.10 };
intT ={}
for i, v in ipairs(number) do
table.insert(intT, math.ceil(v))
end
print( table.concat( intT, ', ' ) )
If you have lots of such transforms it is easy to create such transformer:
function map(f, t)
local newT ={}
for i, v in ipairs(t) do
table.insert(newT, f(v))
end
return newT
end
print( table.concat( map(math.ceil, number), ', ' ) ) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "lua, numbers, concatenation, lua table"
} |
Units of Linear Speed in a Circular Motion
During Uniform Circular Motion, the linear speed of the particle is defined as the radius times the angular speed. $$ v = r\omega $$ The units of linear speed is meters/second (m/s). But the units of $ r\omega $ is $ m\frac {rad}{s} $. How is this possible? And why does the unit "radian" cancel out? | Rad is a dimensionless unit. It is defined as such an angle that it intercepts an arc on a circle with the length equal to the radius of a circle. Angle in radians is the length of an arc over radius, therefore meter over meter: $\theta = L_{arc}/R$. They are dimensionless in nature and people write "rad" simply for convenience. | stackexchange-physics | {
"answer_score": 2,
"question_score": 0,
"tags": "kinematics, dimensional analysis, speed, si units"
} |
Was Couladin a Darkfriend or just nuts?
When Rand undertook his journey to become _Car'a'carn_ , his chief rival was Couladin, an Aiel warrior who declared himself to be clan chief of the Shaido Aiel. Couladin hated Rand from the instant he saw him, but later reinforced his own claim by revealing that he
> also had a dragon tattoo on each arm, later revealed to have been placed there by Asmodean in an attempt to distract Rand.
However, given how he received this, it seems unlikely he didn't know the source or what it entailed. Then again, he never seemed like a stable individual to begin with, and may have simply believed he woke up like that one morning.
**Was Couladin a Darkfriend... or just plain nuts?** | **Personal opinion - No, he was not a Darkfriend.**
I believe that if he was indeed a Darkfriend, the author would've revealed that in the book at some point, either from Couladin's POV or Asmodean POV.
He was indeed a power-thirsty and unstable individual among the Shaido Aiel who disproved of Rand's claims and him entering Rhuidean. We can assume that Couladin gained the tattoos either in his sleep or while awake, but he took them as legitimate claim as the Car'a'carn. | stackexchange-scifi | {
"answer_score": 4,
"question_score": 8,
"tags": "the wheel of time, character motivation"
} |
Spring Security Remember Me
I'm developing a Spring MVC web app and have configured the Spring Security to intercept all URLs and authenticate them. If the user ticks the " **remember me** ", to automatically log in the user without redirecting to the login page.
Say, my login URL is
> example.com/signin
and homepage is
> example.com/home
When a user enters any URL to a valid web page (e.g. example.com/home) which needs authentication, if the **remember me is enabled** , he is directed to that specific web page without authenticating again.
But when a user enters example.com/signin, it just displays login form even if he is already authenticated and remembered.
How can I redirect him to the homepage(example.com/home) if he is an **authenticated and remmeber-me enabled** user without displaying the login page? | These links might help you to implement the remember me using spring security.
< < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, spring, spring mvc, authentication, spring security"
} |
java.lang.NoClassDefFoundError: org/apache/kafka/clients/producer/Producer
I'm trying to use Kafka:
import java.util.Properties;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
public class SimpleProducer {
public static void main(String[] args) {
Properties props = new Properties();
Producer<String, String> producer = new KafkaProducer<String, String>(props);
}
}
But getting the following error:
> java.lang.NoClassDefFoundError: org/apache/kafka/clients/producer/Producer
build.gradle:
...
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'org.apache.kafka', name: 'kafka-clients', version: '2.2.0'
}
... | I ran:
java -jar TestProejct-1.0-SNAPSHOT.jar -cp "D:\Software\kafka_2.12-2.2.0\libs\kafka-clients-2.2.0.jar"
There were several problems:
1. java doesn't aceept both -jar and -cp, so I had to include my jar in the classpath itself in addition to Kafka.
2. I had to specify the main class I wanted to run.
3. There was more than one jar to import from Kafka, so I had to specify * insead of kafka-clients-2.2.0.jar.
This solved the problem:
java -cp "D:\Software\kafka_2.12-2.2.0\libs\*;TestProejct-1.0-SNAPSHOT.jar" SimpleProducer | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "java, gradle, apache kafka"
} |
Download a generated file and redirect in Django
I have a form with which users submit data to my application, and the response to submitting the form is a download with data depending on what they submitted. Since the submission affects the data in the database I want to redirect from this page to prevent the submission accidentally being made twice.
The only solution I've come across is to save the file on the server and redirect to a page which causes the file to download. However I don't really want to be keeping these files or having to manage them on the server.
Is there a way to download the file and then cause the page to redirect? | Consider also the case when the user's internet connection happens to break during the download. Should the user have a possibility to request the same download again in this case? Then you need to store either the generated file or all data needed to regenerate it anyway. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "django"
} |
What are the least sets of generators for $S_n$
Nearly all the books I read give $S_n$ $(n \geq 2)$ and the generating set $\\{(i,i+1) | 1 \leq i < n \\}$ as an example when talking about presentation groups. But is $\\{(i,i+1) | 1 \leq i < n \\}$ the least set of generators, i.e., is the order of any generating set for $S_n$ equal to or greater than $n-1$? If it is the least, how to prove? Are there any other least set of generators? In general, what do these least sets look like?
Forgive me for so many questions. Thanks sincerely for any answers or hints. | I think $(1,2), (1,2,\ldots, n)$ is also a set of generators. | stackexchange-math | {
"answer_score": 23,
"question_score": 11,
"tags": "group theory, finite groups, symmetric groups"
} |
Theorem 14.2 from Davidson Stochastic Limit heory
In Theorem 14.2 of his book _Stochastic Limit Theory_ Davidson establishes the bound
$$E[\big|E[X|\mathcal F]-E[X]\big|]\leq 4M\alpha$$
where $\alpha,M\geq0$ are constants, and $|X|\leq M$. He then writes:
"Since $\big|E[X|\mathcal F]-E[X]\big| \leq 2M$ it follows that, for $p\geq1$, $\|E[X|\mathcal F]-E[X]\|_p \leq 2M(2\alpha)^{1/p}$"
Why is this true? | Let $Y:=\left\lvert\mathbb E\left[X\mid\mathcal F\right]-\mathbb E\left[X \right]\right\rvert$. It is already shown that $\mathbb EY\leqslant 4M\alpha$. Moreover, we know that $0\leqslant Y\leqslant 2M$ hence $$ \mathbb E\left[Y^p\right]=\mathbb E\left[Y\cdot Y^{p-1}\right]\leqslant \mathbb E[Y] (2M)^{p-1}\leqslant 4M\alpha(2M)^{p-1} =2^{p+1}M^p\alpha. $$ Then take the power $1/p$ to get the wanted inequality. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "probability, probability theory, lp spaces, conditional expectation"
} |
Difference between 'getfacl' and 'ls -l'
What is the difference between
`getfacl` and `ls -l` in **Linux**?
Both of them produce output with the same content.
Am I wrong? | From the `getfacl(1)` man page:
> For each file, getfacl displays the file name, owner, the group, and the Access Control List (ACL). If a directory has a default ACL, get‐ facl also displays the default ACL. Non-directories cannot have default ACLs.
Basically, `getfacl` is used to get the filename, the owners, and the file mode in a shell script friendly output. Unlike `ls`, which is used mainly to list directory contents. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 0,
"tags": "linux, file permissions, acl"
} |
how to inspect jquery code on chrome developer tools?
I use web developer tools to inspect html and subsequently see the css that is attached to the html element. This is proving to be a great process for learning from other websites (and the debugging my own)
Is there a way to inspect the javascript as well? So when I select the element, to be able to see the javascript related to the element? | In the element panel you can find all information related to an element including events attached to it.
You can use console in the element panel to inspect an element using `dir(elementId)`which dumps the object with the given id, as a JavaScript object with its properties. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "google chrome, google chrome devtools"
} |
There are 6 cards, 3 blue and 3 red. What is the probability of putting them in a row with alternating colors?
I solved this question this way.
First, there are two ways that the cards will not be alternating:
B - R - B - R - B - R
R - B - R - B - R - B
Second, there are 6! (720) possible orders in which the cards can be dealt.
So, the answer is 2/720. Is this correct? | Without loss of generality, the first card is blue. Then choose a red one with probability $\frac{3}{5}$, a blue one with probability $\frac{2}{4}=\frac{1}{2}$, a red one with probability $\frac{2}{3}$, and the last blue one with probability $\frac{1}{2}$, followed by the last red one. The result is $\frac{2}{5}\cdot(\frac{1}{2})^2=\frac{1}{10}$. | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "combinatorics, permutations"
} |
Job offers world map
Maybe it was already asked, but a world map would be nice for careers. Where you can see countries with jobs. Then you can zoom or filter by technology and so.
Like the candidate search for employers but in reverse. | We're in the middle of redesigning a few pages on Careers. While the map is not a focus, we are looking to bring in a geographical element to the front page which should cover your use case. We'll have some early versions to show off in a few weeks. | stackexchange-meta | {
"answer_score": 2,
"question_score": 6,
"tags": "feature request, status declined, jobs, feedback"
} |
plot coordinates {(a_1,3) (a_2,2) (a_i,4) (a_r,1)} in pgfplots
I am using the following code:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\pagestyle{empty}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot+[ycomb] plot coordinates
{(0,3) (1,2) (2,4) (3,1)};
\end{axis}
\end{tikzpicture}
\end{document}
and the output is:
!enter image description here
but If I have the coordinates `{(a_1,3) (a_2,2) ... (a_i,4) ... (a_r,1)}`, with `0 < a_1 < a_2 < ...< a_i < ... < a_r` How can I to plot these coordinates?
Thanks in advance! | You can use `symbolic x coords={...}` and `xtick=data`
Code:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\pagestyle{empty}
\begin{document}
\begin{tikzpicture}
\begin{axis}[symbolic x coords={$a_1$,$a_2$,$a_i$,$a_r$},xtick=data,]
\addplot+[ycomb] plot coordinates
{($a_1$,3) ($a_2$,2) ($a_i$,4) ($a_r$,1)};
\end{axis}
\end{tikzpicture}
\end{document}
!enter image description here | stackexchange-tex | {
"answer_score": 6,
"question_score": 5,
"tags": "pgfplots"
} |
vb.net array from comma separated strings
I'd like to get a String array from a String that is delimited with spaces (" ") and commas. Is there a clever way to do this?
For example, if the string was:
> cat dog giraffe "big elephant" snake
I'd like the resulting array to contain strings
> cat
>
> dog
>
> giraffe
>
> big elephant
>
> snake
I know I could do a Split(str, " ") but the result would differ from what I wanted. I've never used RegEx, but I have a hunch that the solution might have something to do with it. | Treating the input as space-delimited CSV can greatly simplify the task:
Imports Microsoft.VisualBasic.FileIO.TextFieldParser
...
Dim s As String = "cat dog giraffe ""big elephant"" snake"
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(New System.IO.StringReader(s))
Dim CurrentRecord As String()
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {" "}
afile.HasFieldsEnclosedInQuotes = True
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
Console.WriteLine(String.Join("; ", CurrentRecord))
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
It prints `cat; dog; giraffe; big elephant; snake`.
The code is adapted from _Parse Delimited CSV in .NET_. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "arrays, vb.net, string"
} |
Model use in jquery/javascript
Im trying to either set the value of a variable to @Model.IsPublic which is a boolean value. In my javascript/jquery i have this.
var [email protected]
when i put a semicolon to finish the line it gives me an error. Might be a dumb question. but how can i set a variable to the models value | The problem is because when converting `bool` to `string` ASP MVC uses uppercase. Javascript expects lowercase. What you are effectively doing right now is this:
var pub = True; // = error (unless you have an entity called 'True' - which I hope you don't)
What you need to do is this:
var pub = @Model.IsPublic.ToString().ToLower() // = var pub = true|false;
Alternatively, if you want to create the javascript variable as a string, you simply need to wrap the Model value in quotes:
var pub = "@Model.IsPublic"; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, jquery, asp.net mvc, razor"
} |
Wordpress accessing post_meta on save
I am trying to get the value of a post_meta when the post is published. The problem is that all I can get is the post ID, but the post_meta must not yet be in the database when I make the query. I do not know to get this hook to fire after all of the post_meta for the post has been saved:
function get_some_meta($post) {
$feat_img = get_post_meta($post->ID, 'feat_img', true); // This has not yet been saved, so I can not retrieve it...
// Do something with $feat_img...
}
add_action('save_post', 'get_some_meta', 11, 1); | You can only get the post meta before or after the post is saved. However, the post data is not available while word press is saving the post meta, which technically means its updating the post data, anyways. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, wordpress"
} |
Attribute in C# winforms to specify resource selector?
I made a custom control for WinForms in C#. One of it's properties is an audio stream that will be played at some point. Is there a way I can tell VS that this property should be chosen from the resource manifest (specifically audio resources) with a property or similar?
!The property, defined.
The commented property is an audio stream.
!Control properties.
This is how it shows in the WinForms designer.
!Binary data editor.
This is what you get when you click the edit [...] button. I want this to be replaced by an [audio] resource chooser. | What you are looking for is:
[Editor(typeof(MyAudioEditor), typeof(UITypeEditor)]
This attribute let you specify a specific editor to be used when that property is displayed in a property grid.
You can then derive and create your new editor from a base type. The base type must be or must derive from System.Drawing.Design.UITypeEditor.
In most case, when the Editor is invoked, you pop-up a form of your choice, and bind its return value to your property.
UITypeEditor has 4 virtual methods and one virtual property that let you change all the behavior when someone interact with your property or when your property is painted in the grid. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "c#, winforms, properties, attributes, embedded resource"
} |
PHP Websocket Server hybi10
So Chrome 14 has implemented hybi10 version of websockets. I have a in house program that our company uses via chrome that uses websockets which is broken with this change.
Has anyone been successful framing the data using a php server? I am able to get the new handshake to work but I can't seem to figure out the framing. There is a python example here < but I am having a difficult time converting this to php, anyone have a suggestion?
I should mention that the function in question on the python example is decode_hybi(). | i just completed a class wich makes the PHP-Websocket-Server of Nico Kaiser (< capable of handling hybi-10 frames and handshake. You can download the new class here: < (Connection.php) | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 7,
"tags": "php, websocket"
} |
Проверка даты
Есть функция валидации, в ней следующее выражение
var valid = /^\d{2}-\d{2}-\d{4}/;
return valid.test(value);
В описании регулярных выражений нашел логические операторы больше, меньше; пытюсь добавить к существующему коду "но он не работает" © Кеп
valid = /^(0<\d{2}<32)-(0<\d{2}<13)-(1000<\d{4}<3000)/;
Формат даты dd-mm-yyyy. | Правильно будет
valid = /^[0-3][0-9]-[0|1][0-9]-(19|20)[0-9]{2}/ | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "дата, регулярные выражения, javascript"
} |
Update array by using array index in python
How to use an array index to update a value in array.The compiler keep mention Index Error:list assignment index out of range.
Array Value before change:
[10,0,9,1]
Array value after update:
[9,0,9,1]
x = int(input("Input a number"))
drinkstock = [10,0,9,1]
z=int(drinkstock[x]-1)
for y in drinkstock:
if drinkstock.index(y)==x:
drinkstock[y]=z
print(y) | The for y in drinkstock allows you to access each number inside the array drinkstock.
So you would get:
y = 10 #first iteration
y = 0 #second iteration
y = 9 #third iteration
y = 1 #fourth iteration
So then when you do:
drinkstock[y] = z
you are trying to access the 10th index in drinkstock which does not exist.
Instead, you can do:
for i in range(len(drinkstonk)):
drinkstonk[i] = z
Not sure why you are trying to loop through the entire array though since it looks like you only updated one index value. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "python, arrays"
} |
Maximum Entropy for Natural Language Processing
Can anyone explain simply how how maximum entropy models work when used in Natural Language Processing. I need to statistically parse simple words and phrases to try to figure out the likelihood of specific words and what objects they refer to or what phrases they are contained within. | I recommend the NLTK python package. You can also use MALLET or WEKA. For a theoretical background, you should ask at < or < . | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "statistics, nlp, named entity recognition"
} |
Parsing browser request header in C++
I mading a simple webserver in C++ and i need parse the request headers. How i made that?
Here is my headers...
GET /test?username=2 HTTP/1.1
Host: stream.mysite.com:7777
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: auth=asdfasdfaasdfasd
I need get the page (/test?username=2) and the content of the cookie variable auth (asdfasdfaasdfasd).
Thanks! | A simple example to get you started:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string tk1, tk2, line = "GET /test?username=2 HTTP/1.1";
std::stringstream ss(line);
ss >> tk1;
ss >> tk2;
if (tk1 == "GET") {
std::cout << "requested path: " << tk2 << std::endl;
}
return 0;
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": -1,
"tags": "c++, string, parsing, webserver"
} |
Разложение проекта по директориям
Как правильней разложить проектные файлы по директориям?
Некоторые ide генерируют папки source, headers, objects c абсолютно идентичной иерархией директорий, но находятся там файлы с разным расширением. Встречал когда одна иерархия директорий проекта, но h и cpp файлы вместе сложенны.
Какой способ правильней и чем? | Для мелких проектов группировка по типам может быть удобна.
Но чем больше проект, тем менее удобной будет группировка по типу файлов. Всё время придётся держать несколько папок развёрнутыми. Например, ты меняешь что-то в cpp-файле, что требует внести изменения и в h-файл. И вот у тебя уже одновременно в solution explorer'е до одной и той же сущности развёрнуто два весьма жирных каталога. Поэтому лучше сгруппировать логически на основе сущностей, сложив всё, относящееся к одной сущности, в одну папку. | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "c++"
} |
Multiple conditions in a like function
I have a set of data, each point either starts with a `AB`, `PO`, or `LV`. there are also a number of entries with things I don't want like `MC` or `BV`. I also have some dates, it looks like this.
Select distinct clm.Theletter, clm.thenotedate, clm.theorigdate
from table.table
where clm.thenotedate>= ''2018-01-21'' and clm.theorigdate>''2018-01-01''
and clm.Theletter_NUM LIKE ''HP%''
order by clm.thenotedate asc
);
and I get a list of everything I want that starts with `AB`, but I also want the stuff that starts with `PO` and `LV`? I tried using OR after my first LIKE but it seems to ignore the date functions and retrieve everything before 2018-01-01 that starts with `PO` and `LV`, which is a lot. | It is probably simplest if you do:
. . . and
left(clm.Theletter_NUM, 2) in ('AB', 'PO', 'LV')
Most databases support a `left()` function on strings. If not, just use the appropriate substring function. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "sql, sql like"
} |
Append $index to the end of the string in Smarty3
I have the following HTML code:
<input type="text"
name="line_item[hotel_info][{{$index}}][second_last_name_{{$index}}]"
value="{{$PREVIOUS_REQUEST.hotel_info.$index.second_last_name_$index}}"
>
What's the right way to append `$index` to the string being passed to the value? This `$PREVIOUS_REQUEST.hotel_info.$index.second_last_name_$index` is failing since Smarty doesn't like the `_$index` at the end of the string. Any help?
**UPDATE:** using `cat`:
I have tried using `cat` modifiers but still not working:
{{$PREVIOUS_REQUEST.hotel_info.$index.hotel_name_|cat:$index}}
Return `0` which is the value of `$index` but I need the value stored in the var. | Looks like you will need to use an intermediate variable:
{assign "sln" "second_last_name_$index"}
value="{{$PREVIOUS_REQUEST.hotel_info.$index.$sln}}"
Example:
$PREVIOUS_REQUEST = [ 'hotel_info' => [
0 => [ 'second_last_name_0' => 'foo' ],
1 => [ 'second_last_name_1' => 'bar' ],
]];
$smarty = new \Smarty;
$smarty->assign('PREVIOUS_REQUEST', $PREVIOUS_REQUEST);
$smarty->assign('index', 0);
$smarty->display(<<<'EOTPL'
string:
{assign "sln" "second_last_name_$index"}
index="{{$index}}"
index="{{$sln}}"
value="{{$PREVIOUS_REQUEST.hotel_info.$index.$sln}}"
EOTPL
);
Outputs:
index="0"
index="second_last_name_0"
value="foo" | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, smarty, smarty3"
} |
How to pass a Data Flow from one package to another
I'd like to pass a Data Flow from one package to another for the following reasons:
1. It would help in refactoring common logic in SSIS packages.
2. It would enable concurrent development of larger SSIS packages.
At first glance, the Execute Package Task sounded promising, but it looks like I can only pass fairly simple variables in and out of the package.
Is there a way to do this using SSIS? | cozyroc.com is a third party tool that can do this I believe. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "ssis"
} |
Expire option doesn't work in Rails.cache
I use the Rails.cache.fetch method with the :expires_in option in Rails 2.3.10.
> Rails.cache.fetch "key", :expires_in => 2.seconds
In development, my cache never get expired and Rails always hits the cache.
> Log: "Cache hit" | The default cache in Rails 2 is `ActiveSupport::Cache::MemoryStore`. It does not support expiration with the `:expires_in` option. In fact, **only** `ActiveSupport::Cache::MemCacheStore` has support for cache expiration.
In Rails 3, `:expires_in` is supported for all cache stores. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 10,
"tags": "ruby on rails, memcached"
} |
REGEX for complete word matching
OK So i am confused (obviously)
I'm trying to return rows (from Oracle) where a text field contains a complete word, not just the substring.
a simple example is the word 'I'.
Show me all rows where the string contains the word 'I', but not simply where 'I' is a substring somewhere as in `'%I%'`
so I wrote what i thought would be a simple regex:
select REGEXP_INSTR(upper(description), '\bI\b') from mytab;
expecting that I should be detected with word boundaries. I get no results (or rather the result 0 for each row.
what i expect:
* 'I am the Administrator' -> 1
* 'I'm the administrator' -> 0
* 'Am I the administrator' -> 1
* 'It is the infamous administrator' -> 0
* 'The adminisrtrator, tis I' -> 1
isn't the /b supposed to find the contained string by word boundary?
tia | I believe that \b is not supported by your flavor of regex :
<
Therefore you could do something like :
(^|\s)word(\s|$)
To at least ensure that your "word" is separated by some whitespace or it's the whole string. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 3,
"tags": "sql, regex, oracle, oracle10g, oracle11g"
} |
Migrating asp.net website to linux?
I have a asp.net website developed in VS 2010 and hosted on godaddy asp.net hosting enviroment. Now, i am setting my own server and need to migrate the same to linux. Do i need to do something extra in coding or installing any third party web server for dot net applications on Linux distro will do. | You'll need to use Mono to run .NET on Linux. Last time I looked it only supported .NET 2.0 although it is probably more advanced by now.
EDIT: It looks like Mono now supports .NET 4 features - see < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "asp.net, linux"
} |
iOS one month from current Date.
I'm trying to get one month from the current date.
Below is what I have and it is returning: `4027-09-24 16:59:00 +0000`. currentDate is right. What's going on?
// Get todays date to set the monthly subscription expiration date
NSDate *currentDate = [NSDate date];
NSLog(@"Current Date = %@", currentDate);
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit fromDate:currentDate];
dateComponents.month = dateComponents.month + 1;
NSDate *currentDatePlus1Month = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(@"Date = %@", currentDatePlus1Month); | Try this instead:
// Get todays date to set the monthly subscription expiration date
NSDate *currentDate = [NSDate date];
NSLog(@"Current Date = %@", currentDate);
NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.month = 1;
NSDate *currentDatePlus1Month = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(@"Date = %@", currentDatePlus1Month); | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 4,
"tags": "ios, date, calendar, nsdate, nscalendar"
} |
Transfer values between tabs in Numbers for iPad
I have two tabs in one spreadsheet in my Numbers for iPad. Is there a way I can transfer a value between those tabs? | There are two ways, depending on what you want to do.
If you just want to **copy the current value or formula,** make sure you are not in edit mode (i.e. there should be no keyboard or number pad visible). Click once on the cell you want to copy, pause so it doesn't think you are double tapping, and then tap again. A popover menu should appear. Click copy and then go to the other tab. Select the cell where you want to paste and repeat the "slow motion double tap." Then click paste.
If you want a cell to **reference a cell from another tab** you can do this to. Start by (quickly) double tapping the empty cell where you want the value from the other tab to appear. This should put you into edit mode. Push the equal sign button. Now navigate to the other tab and select the cell with the value you want to reference. Tap the cell once, and push the green check mark. | stackexchange-apple | {
"answer_score": 4,
"question_score": 2,
"tags": "ipad, ios, numbers"
} |
Order preserving map from interval $(0,1)$ to the ultrafilter
Let $\mathcal{A}= \prod_{n \in \mathbb{N}} \mathcal{A}_n /\mathcal{U}$, where $\mathcal{A}_n=(\\{0, 1, \dots, n\\},<)$ and $\mathcal{U}$ is a non-principal ultrafilter of $\mathbb{N}$.
Does there exist a function $f:(0,1) \to A$ such that $f(x)<^{\mathcal{A}}f(y)$ whenever $x<y$?
I see that $f$ won't be surjective, since $\mathcal{A}$ contains a least element $[0,0, \dots]$ but $(0,1)$ has no least element. | For a given $r\in(0,1)$ choose $(i_n)_{n\in\omega}$ be such that $\lim_{n\to\infty}i_n/n=r$.
Then $f(r)=[(i_n)]_{\mathcal U}$, | stackexchange-math | {
"answer_score": 4,
"question_score": 3,
"tags": "logic, model theory, natural numbers, filters"
} |
Array resets after push
I want that when I press the submit button it adds a value to the array but instead it keeps returning the same value.
$(document).ready(function(){
if(typeof arr == "undefined"){
var arr = new Array();
}
arr.push(2);
$("#submit").click(function(){
console.log(arr);
});
});
I want it to add a 2 each time I press submit like this: First press
[2]
Second press
[2, 2]
But now the array just stays 2 as if it just refreshes. | Your `push` is inside DOMReady. It is only ever called once. Did you mean to call it inside the `#submit` click listener?
Or does the `#submit` click actually submit a form so that you end up reloading the page, and you expect DOMReady to append to the existing array? In that case, no, it doesn't work that way, javascript variables aren't persistent across page refreshes (unless you store them in something like a cookie or localStorage) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript, jquery"
} |
Why doesn't Opera play Last.fm? How can I get it to work?
How can I get Opera to play Last.fm? <
I'm using version 12.02, Windows XP.
Opera/9.80 (Windows NT 5.1; U; en) Presto/2.10.289 Version/12.02
Description: Shockwave Flash 11.4 r402 C:\WINDOWS\system32\Macromed\Flash\NPSWF32_11_4_402_287.dll
application/futuresplash FutureSplash movie spl
application/x-shockwave-flash Adobe Flash movie swf | I'm pretty sure we can solve your problem since your last.fm link plays correctly here with Opera 12.12
1. download newest Opera from here
2. install Opera in **portable mode** (That way it won't mess up your current Opera)
3. download the Adobe Flash Removal tool
uninstall all Flash versions using the removal tool
4. download newest Adobe Flash Player. Be careful and choose _Flash Player 11 for Other Browsers_
5. Install Adobe Flash Player
6. Open your newly created Opera Browser and check if your last.fm link is playing
If everything works fine, leave a comment here and we examine your old opera profile. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 0,
"tags": "opera, audio streaming, internet radio, last.fm"
} |
Simple way to merge multiple source files into one fatbinary
To simplify the build process in a project, I'd like to compile multiple source files into device PTX code, and have all those modules in a single `.fatbin` file to be linked later.
I can achieve this currently through either compiling each file individually to `.ptx`, or compiling all simultaneously while using `--keep` to keep intermediate files, then adding each to a fatbinary explicitly:
nvcc -c --keep mysource1.cu mysource2.cu ...
fatbinary --create="mysources.fatbin" --image3=kind=ptx,file=mysource1.ptx --image3=kind=ptx,file=mysource2.ptx ...
This is quite cumbersome though, so I was wondering if there is a simpler/more terse way of doing so, perhaps in a single nvcc invocation. I've tried calling `nvcc --fatbin --device-link` on multiple source files, but that does not seem to keep the ptx code in the output fatbinary (at least not when inspecting with `cuobjdump`). | One possible approach here would be to use a library. The command could look something like this:
nvcc -gencode arch=compute_XX,code=sm_XX -gencode ... --lib -rdc=true -o libmy.a mysource1.cu ...
The above command could be used in the case where you know device linking will eventually be necessary. In that case, you would specify the device-link step later, when you link objects or your final executable against the static library.
For the case where you know that device linking will not be necessary, just omit the `-rdc=true` switch. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "cuda, nvcc, ptx"
} |
R-LaTeX Wide table
I'm writing a report with sweave. I have to put-in a very wide table:
from R
dim(myData)
> 50 60
The R code I wrote to generate the LaTex table is:
print(xtable(myData, caption="my wide table", label="tab:myTab", digits=3),
tabular.environment="longtable", caption.placement="top",
## floating.environment="sidewaystable", ## a trial
size="\\tiny", table.placement="", floating=FALSE)
The problem is that the table is too wide for the dimension of the page, so, is there a way to divide the table in different pages, such as LaTeX longtable environment but, by the width??
I hope I have been able to explain my problem.
Regards
Riccardo | You could create multiple tables manually by subsetting your data
Table 1 (assuming first three columns should be in both
print(xtable(myData[,c(1:3,4:25)], caption="my wide table", label="tab:myTab", digits=3),
tabular.environment="longtable", caption.placement="top",
size="\\tiny", table.placement="", floating=FALSE)
Table 2
print(xtable(myData[,c(1:3,25:50)], caption="my wide table", label="tab:myTab", digits=3),
tabular.environment="longtable", caption.placement="top",
size="\\tiny", table.placement="", floating=FALSE) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "r, latex"
} |
Multi select files in media browser
I would like to multi-select files in media browser. I came across this sandbox module: Media Multiselect but it has bugs that render it not usable. Does anyone know of a solution to multi-selecting files in media browser? | People are using this patch on latest media to multi-select media files on fields: <
Personally I had some problems to make it work at first, but finally I got it working (Had to disable admin_language module). | stackexchange-drupal | {
"answer_score": 0,
"question_score": 0,
"tags": "media"
} |
Detecting mouse wheel movement in Flash (AS3)
I have a Flash application that have to detect the mouse wheel event (MouseEvent.MOUSE_WHEEL), I've tested on a stand alone flash player and works perfect, but when i put the swf in a web browser, the mouse wheel stop working.
I've tested this in: Internet Explorer 7.0, Mozilla Firefox 3, Safari 3 and Google Chrome; and this behavior happens in all of the browsers
PS: The swf file is embed in the body of the page, a simple page with only the swf.
EDIT: The swf has wmode set to opaque and it has focus on it when this bug happens. | Does your SWF file have focus when you try to scroll? If it does not, the browser window will scroll instead.
Probably related: I found this bug in the Adobe JIRA btw: < This is when the wmode is transparent or opaque. Can you check your html code for this property? Here is a workaround: | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "flash, actionscript 3, mousewheel"
} |
Testing that something fails to parse in Xtext
I have the following grammar:
grammar ru.focusmedia.fire.idl.IDL with org.eclipse.xtext.xbase.Xbase
generate idl "
Model:
'package' package=QualifiedName
imports+=Import*
typeDefs+=TypeDef+;
...
So the string `asd` should fail to parse, as should anything not starting with `package`. I expected `ParseHelper.parse("asd")` to throw an exception or to return `null`, but it does neither. How do I recognize that parsing failed? | You can query the resource that contains the parse result for errors by means of Resource#getErrors. Something like `resultFromParseHelper.eResource().getErrors()` should do the trick.
Using junit:
Assert.assertEquals(result.eResource().getErrors().toString,0,result.eResource().getErrors().size) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "xtext"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.