INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Assertion failed (blockSize % 2 == 1 && blockSize > 1) in cv::adaptiveThreshold
I'm trying to do an adaptive threshold:
cv::Mat mat = cv::imread(inputFile);
cv::cvtColor(mat, mat, CV_BGR2GRAY);
cv::adaptiveThreshold(mat, mat, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 20, 0);
cv::imwrite(outputFile, mat);
But it fails with this message:
OpenCV Error: Assertion failed (blockSize % 2 == 1 && blockSize > 1) in cv::adaptiveThreshold, file ..\..\..\..\opencv\modules\imgproc\src\thresh.cpp, line 797
What is the problem? | The problem was that I was putting an even value for blockSize, while it required only odd values, so changing it from 20 to 21 fixed the assert failure:
cv::adaptiveThreshold(mat, mat, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 21, 0);
The docs kind of mention it, but they are not explicit it will fail if blockSize is not odd:
> blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.
As you can see, nowhere does it say "it will fail if blockSize is not odd". | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 5,
"tags": "c++, opencv"
} |
"Go To Shopping Cart" opens in a new window
After selecting an item in the store, it gives two options: "continue shopping" or "Go To Shopping Cart". If I select the "Go To Shopping Cart", it opens in a new window. How can I fix it? I need it to stay in the same window and just open new page. Thanks | "Go To Shopping Cart" link might have onclick="window.open()" property set. In some cases it may be target = "_blank" . That is why it is getting opened in new window. You may turn on template hints from admin to find out the phtml from which it is being rendered and then just remove this property and flush your cache and check again. It must open in same window now.
To turn on template path hints in Magento:
Log into the magento back-end admin
Go to System -> Configuration in the main menu
Go to Developer on the bottom left under ADVANCED
Switch to the store view on the top left to your current website or store view.
Under the Debug tab of the same Developer config page you will see a new option appear that will allow you to turn on/off template path hints.
Enter your IP in IP restriction text box
Save and refresh page | stackexchange-magento | {
"answer_score": 0,
"question_score": 0,
"tags": "shopping cart"
} |
How to group CTests together?
I would like to make groups of CTests to improve readability with a structure like this: 
project(Test)
set(CMAKE_CXX_STANDARD 14)
enable_testing()
add_executable(env environment.cpp)
add_test(Environment env)
add_subdirectory(unit) # Includes tests 'UserInterface' and 'Test2'
The tests in the subdirectory are not grouped together when I run it:
 to be built with `CMake`.
What you can do is:
* Impose a naming scheme, e.g. prefix tests by a common identifier. For all tests that are registered with `add_test(foo_...)`, you can run this group with `ctest -R foo_` for example.
* Associate setup- and teardown-like test with a set of tests (have a look at test properties like `FIXTURES_CLEANUP`). However, this doesn't give you structure per se, it only ensures a certain existing test is run as a setup/teardown before/after the test in question. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c++, unit testing, testing, clion, ctest"
} |
Batch Variable Value Check Range?
looking to do a range comparison of the value of a variable, what would be the correct syntax to say
if %VAR1% GEQ 7 AND LSS 22
Thank you | You can nest/compose the if conditions like this:
if %VAR1% GEQ 7 if %VAR1% LSS 22 echo yep | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "variables, batch file, comparison, range"
} |
Egit, Eclipse folder structure
Let's say I have several projects in c:\dev\ and want to keep them there (this is my eclipse workspace)
What is the least inconvenient way to setup egit? | Turns out there is a bug in egit where you cannot create a git repo on an existing folder
You need to use msysgit to create the git repo on the command line, using git init
Then you can use egit as per the user guide | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "egit"
} |
Confusion about inline function
I have a question regarding **inline function**.
#include <iostream>
using namespace std;
class A
{
public:
inline void fun()
{
int i=5;
cout<<i<<endl;
}
};
int main()
{
A a1;
int i = 2;
a1.fun();
cout<<i<<endl;
return 0;
}
In above program, when function `fun()` was called, the compiler should have made copy of this function and insert into **main** function body because it is `inline`.
So, I have a question, Why doesn't compiler give an error of variable `int i;` being re-declared? | You seem confused about scopes. They're not "within the same" scope
You can declare multiple variables with the same name at different scopes. A very simple example would be the following:
int main()
{
int a; // 'a' refers to the int until it is shadowed or its block ends
{
float a; // 'a' refers to the float until the end of this block
} // 'a' now refers to the int again
}
Inline expansion is not pure text replacement (as opposed to macros).
Whether a function is inlined or not has no effect on semantics Otherwise the program would behave differently depending on whether the function was inlined or not, and return statements would not behave properly at all. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "c++, function, inline"
} |
Get all form elements value to be attached for ajax call
I have an object that is inside of a form.
His value is assigned to an ajax call like this
var $$ = $(this);
if (typeof settings.data == 'string') {
data = settings.data + '&' + this.name + '=' + $$.val();
} else if (typeof settings.data == 'object') {
data = settings.data;
data[this.name] = $$.val();
}
I want to get the parent form of this element, and to loop through all inputs and add that too to the data to be used on an Ajax call.
I want the input name to be the key for the data array.
Probably something like:
var form = $$.parents('form:first');
and next thing to loop through the inputs and attach to data.
How to do that using jQuery? | I think you're reinventing the wheel here, there's already a `.serialize()` method specifically for this, like this:
var data = $(this).closest("form").serialize();
Or if you want an object representation you can loop through/add to, you can use `.serializeArray()` then manipulate it before passing it as the data option. It's unclear _exactly_ what you're after, but it _sounds_ like you just want to pass the entire form as the data argument to `$.ajax()` or a short-hand version, in which case `.serialize()` would be perfect. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "javascript, jquery, forms"
} |
Changing Kafka Configuration on spotify/kafka Dockerfile
I'm trying to change the configuration of Kafka that is inside this public docker image: <
I'm trying to connect to the container with:
docker exec -ti <CONTAINER_ID> bash
But I cannot find where the server.properties is. | The `server.properties` file is inside the `$KAFKA_HOME/config/` directory.
This variable is in Dockerfile, and is used in `start-kafka.sh` script. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "docker, apache kafka"
} |
#1044 - Access denied for user 'root'@'localhost' to database 'information_schema'
Someone sold us a script and not sure if it's working so I need to test it before it's too late however I'am getting the error **"#1044 - Access denied for user 'root'@'localhost' to database 'information_schema'"**
I wasn't able to put the code entirely so here is the pastebin link : <
I searched but couldn't really find a lot of help since i don't have experience on those stuff .note that I'am using Wamp server & getting this error when I try to import the .SQL file on PHPmyAdmin I guess that information_schema already exists on the database however not sure what part should I delete etc... | It's saving you from yourself.
You should not be running statements on the info schema db (unless you REALLY know what you're doing). The database serves as a "meta" repository that dictates how the server operates. Chances are that you have no need to touch it and you'll likely brick your server if you do. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, mysql"
} |
BeautifulSoup Find tag with text containing
I have the `html` code and I want to find a tag by its text but because it has ` ` the result is `None`:
soup = BeautifulSoup('<li><strong>Hello </li>', 'html.parser')
text1 = soup.find('strong', text = 'Hello')
text2 = soup.find('strong', text = 'Hello ')
text3 = soup.find('strong', text = 'Hello ')
print(text1, text2, text3)
Output:
None None None
How can I handle ` `? | The non-breaking space is parsed as `\xa0`, so you can either run:
text = soup.find('strong', text='Hello\xa0')
Or you could use regex:
import re
text = soup.find('strong', text=re.compile("Hello"))
Alternatively you could use a lambda function that looks for `Hello` at the start of the string:
text = soup.find("strong", text=lambda value: value.startswith("Hello")) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, beautifulsoup"
} |
Roots of unity over $\mathbb{Q}$
I want to show the following proposition from Algebra, Hungerford V.8.9.
If $n > 2$ and $\xi$ is a primitive $n$th root of unity over $\mathbb{Q}$, then $[\mathbb{Q}(\xi + \xi^{-1}) : \mathbb{Q}]= \frac{\varphi(n)}{2}$, where $\varphi(n)$ denotes the Euler's totient or phi function.
Thanks in advance. | **Hint** : Under the Galois correspondence prove that $\mathbb{Q}(\zeta+\zeta^{-1})$ corresponds to the subgroup $\langle -1 \rangle$ of order $2$ of $\mathrm{Gal}(\mathbb{Q}(\zeta)/\mathbb{Q}) \cong (\mathbb{Z}/n)^*$. Since $-1$ corresponds to the complex conjugation, you have to prove $\mathbb{Q}(\zeta+\zeta^{-1}) = \mathbb{Q}(\zeta) \cap \mathbb{R}$. | stackexchange-math | {
"answer_score": 5,
"question_score": 3,
"tags": "abstract algebra, roots, extension field, totient function, cyclotomic polynomials"
} |
Rspec -- need to stub File.open that gets called in another file
In my test I'm initializing a new class called `Package` with some parameters.
In the initialization of this class, I open a file that is available on my remote boxes but not something that is commonly there locally. I was wondering how I would go about stubbing that method in my test.
I'm using rspec and mocha. I tried something like:
File.stubs(:open).with(:file).returns(File.open("#{package_root}/test_files/test.yml"))
I had this line before I initialized `Package` in my test.
I got this error:
unexpected invocation: File.open('package/test_files/test.yml')
satisfied expectations:
- allowed any number of times, not yet invoked: File.open(:file)
I'm not that familiar with rspec or mocha, so help is appreciated. Thanks! | I'm not sure you need that `.with(:file)` part, try dropping it altogether. Also, I believe by specifying it that way you are literally telling it to expect someone to call that method and pass it a `:file` symbol rather than e.g. a string filename. Also consider preloading the test YAML file and just returning that:
let(:file_like_object) { double("file like object") }
File.stub(:open).and_return(file_like_object) | stackexchange-stackoverflow | {
"answer_score": 11,
"question_score": 15,
"tags": "ruby, testing, rspec, mocking, stubbing"
} |
Communication between two browser windows: popup and parent
Hi I have a parent window, lets saz M, on clicking a button in M, a popup window is opened. When some option is selected in the popup and the OK button is clicked, the popup should close and in the main window a message should be displayed. Is this possible through javascript? | yes, it's possible.
close a popup with `window.close()`
communicate with parent window with `window.opener.postMessage()` (`window.opener` is the parent window object, you can even call a direct named function within it for example `window.opener.funcName()`)
next time please look for existing solution before you ask for one, there are plenty of those.
good luck | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 5,
"tags": "javascript, jquery, html"
} |
definition of product of modules
I have been given this definition of a product between modules:
If $I$ is an indexing set with $M_i$ as an $R$-Module then the product $\prod \limits_{i \in I} M_i$ is defined as the set consisting of I indexed tuples $(x_i)_{i\in I}$ for each $i \in I$ which is made into an R module by component wise addition and multiplication.
my problem is understanding this definition, could anyone give me a basic example of what the product of two Modules $M_1$ and $M_2$ would be, just so i could see how it works practically.
thanks in advance for the help! | Consider $\prod \limits_{i \in I} M_i$.
The sum is $$( a_i)_{i \in I } + ( b_i)_{i \in I } = ( a_i + b_i)_{i \in I }$$ The action of R : $$ r \cdot ( a_i)_{i \in I } = ( r \cdot a_i)_{i \in I }$$ | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "abstract algebra, modules, definition"
} |
Regex to find last token on a string
I was wondering if there is a way having this
var string = "foo::bar"
To get the last part of the string: `"bar"` using just regex.
I was trying to do look-aheads but couldn't master them enough to do this.
\--
UPDATE
Perhaps some examples will make the question clearer.
var st1 = "foo::bar::0"
match should be 0
var st2 = "foo::bar::0-3aab"
match should be 0-3aab
var st3 = "foo"
no match should be found | You can use a negative lookahead:
/::(?!.*::)(.*)$/
The result will then be in the capture.
Another approach:
/^.*::(.*)$/
This should work because the `.*` matches greedily, so the `::` will match the _last_ occurence of that string. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "javascript, regex, lookahead"
} |
Subtrair variáveis Datetime
Tenho dois campos datetime e gostaria de saber a diferença entre eles. Estou desenvolvendo em Php Gtk, então as funções tem que ser de mais baixo nível possível. | Uma das formas de fazer isto orientado a objetos, é usando a classe DateTime, a mesma possui o método diff que retorna um objeto DateInterval, que representa o intervalo entre duas datas distintas:
Seguindo o exemplo de datas:
$data1 = new DateTime( '2013-12-11' );
$data2 = new DateTime( '1994-04-17' );
$intervalo = $data1->diff( $data2 );
echo "Intervalo é de {$intervalo->y} anos, {$intervalo->m} meses e {$intervalo->d} dias";
Fonte: Como calcular a diferença entre duas datas? | stackexchange-pt_stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "php"
} |
Dimension problem
Let $f \colon \mathbb{C}^5 \rightarrow \mathbb{C}^7$ a linear function, $f(2 i e_1 + e_3) = f(e_2)$ and $\mathbb{C}^7=X \oplus Im(f)$. What dimension has $X$? | Hint: Apply the rank-nullity theorem. Given that $f$ satisfies at least the relation that you listed, what are the possible dimensions of the kernel?
Second hint: Take a basis $v_1, \ldots v_5$ of $\mathbb{C}^5$ such that $v_1=2ie_1-e_2+3_3$ | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "linear algebra, complex numbers"
} |
PUBMED author/article database
I am looking for a way to download the author and associated articles database from pubmed or any other source. I can't seem to locate this anywhere on ncbi FTP site.
Does anyone know if there's such database available? | Did you try this :
<ftp://ftp.ncbi.nih.gov/pubmed/>
Also, I would try the E-utilities
<
Good luck! | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "bioinformatics, pubmed"
} |
ASP.Net Core 2 how to trigger/call code after authentication
How can I trigger some code right after authentication? Let's say I want to give my application a single session constraint per user, for example. How can I implement it in ASP.Net Core 2.0?
# Update:
Clarification, I want to trigger code right after a user is considered authenticated (after .net authentication middleware have validated the user is who claims to be). I have not mentioned Middleware before because there might be an easier way, like an event, to trigger some code. Maybe the proper question would be if is there such event/way, or if I should manage it through a custom Middleware attached right after Authentication? | The simplest scenario, is calling the method you want in any action in MVC controller. Actions are always called after authentication (I think this is not what you need, but the information your provided are very poor, as you did not mentioned exactly what do you mean by _right after authentication_ ).
The other possiblity ( **which is probably what you want** ), is to create a **middleware** , and add it to the pipeline exactly after authentication middleware. When you have your middleware in the pipeline, you can write to do what ever you want.
Middleware writing is well documented here:
< | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "c#, asp.net core 2.0"
} |
Using IPython from the Python shell like `code.interact()`
Is it possible to use the IPython shell from an existing Python shell, as a shell-inside-a-shell, similarly to the built-in `code.interact()`? | The recommended way of embedding IPython works fine:
~ $ python
Python 2.7 [...]
>>> from IPython.Shell import IPShellEmbed
>>> ipshell = IPShellEmbed()
>>> ipshell()
In [1]: | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 20,
"tags": "python, shell, ipython"
} |
Unable to cancel adding an Assessment on Developer Story
I was exploring the options one has available to include on one's Developer Story, and happened to notice that I _can't cancel an attempt toadd an Assessment item_:
. I want to calculate the number of 1s in each row. This can be done using SUM of each row or COUNTIFS on each row.
My goal is to have a single dynamic array formula which would sum/countifs each row and hence spill automatically according to the number of rows in the 2D dynamic array.
How do I do this?
What I tried:
* I added a support column in A1# as Sequence(Rows(B1#))
* I tried SUM(INDEX(B1#,A1#,0)) but obviously this doesn't work because SUM is bound to return a single value while I am expecting a spill of totals across ROWS(B1#)
* I tried COUNTIFS(INDEX(B1#,A1#,0),1) but this also results in a single value that too #VALUE! | `MMULT()` with `SEQUENCE()` may work for you. Give a try on below formula.
=MMULT(B1:E14,SEQUENCE(COLUMNS(B1:E14),,,0))
, make reading very slow. This in turns slows down processing and yields low CPU usage. You can try defragmenting, compressing the input files (as they become smaller in disk size, processing speed will increase) or other means of improving IO. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python 2.7, multiprocessing, cpu usage"
} |
Getting a color with same tint, but of another color?
In my CSS, I defined the `#error` div as:
#error {
border-width:1px;
border-style:solid;
border-color: #DD3C10;
background:#FFEBE8;
/* Other settings */
}
The code above isn't mine, actually - I used the same colors as Facebook. Now, I want to do the same with the `#success` div, but I don't know which colors to use. I want to keep the same tint (which is, the position on the line between "full color" and "white"), but of green instead of red. How do I do it? Is there a "formula"? | You care about the L (lightness) component in the HSL representation of your color. You can find an online converter (RGB/HEX to HSL) here: little link.
HSL for `#DD3C10` is `13° 86% 46%`, while `#FFEBE8` is `8° 100% 95%`. Difference in lightness is, as you see, `49%`.
Suppose your green for `border` is `#00FF00`, which is `120° 100% 50%` in HSL. To calculate the new lightness component, just add `49%`. Thus the green for `background` is `120° 100% 99%` which is `#FAFFFA`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "css, colors"
} |
Can I merge points from different flight companies to use in Star Alliance?
If I have points in multiple Star Alliance member companies, can I sum up all these points to get a Star Alliance flight ticket? | No, you can not transfer points between Star Alliance carriers.
There are some mechanisms that can be used to transfer between specific carriers, such as points.com, or transferring via a hotel program (eg, carrierA -> hotel program -> carrierB), however these are generally poor value as you end up losing a significant number of points during the transfer(s). | stackexchange-travel | {
"answer_score": 8,
"question_score": 4,
"tags": "loyalty programs, star alliance"
} |
Error response from daemon when starting a docker container
When I type `docker start projects` I get this error:
> Error response from daemon: invalid header field value "oci runtime error: container_linux.go:247: starting container process caused \"exec: \\\"/bin/bash”\\\": stat /bin/bash”: no such file or directory\"\n" Error: failed to start containers: projects
What should I do so I can start my docker containers? | There are two possible errors
1. The file or directory you are mapping is invalid
2. The base image you are using do not have /bin/bash
and try to start a new container instead of old one from docker run projects | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 6,
"tags": "docker"
} |
Timer running while on home screen iPhone - Objective C
I am interested in building a Timer Based game such as mafia wars or soemthing like that. I'm stuck on one question.
What would be the best way to retain a timer, even if the app is closed?
Should I do this based on the Device Clock? or should I set a time to a server, and get the time when the device starts up?
If any one knows a better way for this,
let me know. Thanks.
@lessfame | If you only need to retain the time and show how much time elapsed since the game was closed (i.e. you don't need to notify the user when the time is up), you can use the [`[NSDate timeIntervalSinceNow]`]( method to determine the amount of milliseconds that passed between two times. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "iphone, objective c"
} |
C++ : const reference to local object
const std::string s1 = "abc";
const std::string & s2 = "abc";
Is the definition of `s2` legal? If so, what is the difference between between `s1` and `s2`?
Thanks. | Yes, s2 is legal. s2 is bound to a temporary std::string - extending the temporaries lifetime. s1 isn't a temporary, it's a named variable.
See 12.2/5:
> The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 4,
"tags": "c++"
} |
Why setState from parent component calling child componentDidUpdate?
In this example `componentDidUpdate` fired when I set state trail. HelloMessage props and state not changed so why this method is calling? How to prevent this?
class HelloMessage extends React.Component {
componentDidUpdate(prevProps, prevState) {
console.log('HelloMessage did update');
}
render() {
return <div>Hellooo</div>;
}
}
class App extends React.Component {
state = { trail: null }
componentDidMount() {
this.setState({ trail: 'First' });
}
render() {
return (
<div>
<HelloMessage />
<div>
{this.state.trail}
</div>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
); | It's expected behavior. Whenever the parent component's states changes the component will be re-rendered. And all of your components logic ie. child component also exists inside render method. So, the child component is rendered again.
If you do not want the updates, then you need to return react's shouldComponentUpdate hook explicitly.
shouldComponentUpdate(nextProps, nextState) {
return nextState
}
Since nextState of the child component is still `null` shouldComponentUpdate will return null. This inform not to update the component. This will allow the child component to be re-rendered only when child's state gets changes. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "reactjs"
} |
Cypher: Avoid duplicate nodes
Have the below relationship
Bob-[:TWINS]-Alice
I need to return all twins. Below is the cypher being used but returns duplicates
MATCH a-[:TWINS]-b
RETURN a.name, b.name
I've set this up in Neo4j console here.
How not to return duplicates? I know this can be easily fixed by including the direction of the relationship but here the direction is not relevant. So wondering how to avoid duplicates. | This is the classic way:
MATCH a-[:TWINS]-b
WHERE id(a) < id(b)
RETURN a, b | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "neo4j, cypher, spring data neo4j"
} |
convert percent to decimal out of 10
I have a ratings system where users can vote on posts and rate them in 10's. For example 10, 20, 30, 40 and so on up to 100.
When I get the AVG vote for example I get 95 how can I change the output to say 9.5
I know its probably really simple but I am struggling to find the answer. Any help would be much appreciated | $avgVote = round($avgVote/10, 1); // 95 -> 9.5 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "php, decimal"
} |
C++11 regex to match $VARNAME or ${VARNAME}
need a C++11 regex to match:
"$VARNAME" or "${VARNAME}"
Where VARNAME can be any alphanumeric literal.
Here's what I tried:
#include <iostream>
#include <regex>
#include <string>
using namespace std;
void main() {
string line = "${USERPROFILE}/blah/blah/blah";
smatch M;
regex r1{ R"(\$\{?(\w+)\}?)" };
bool success = regex_match(line, M, r1);
if (!success) {
cout << "Why doesn't this match?" << endl;
}
return;
}
Why doesn't this match? | because your pattern doesn't `match` your test string. instead of `std::regex_match` you need `std::regex_search` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "regex, c++11"
} |
bootstrap navbar-brand responsive ness issue
I have the following js fiddle. It works perfectly fine, however the issue is that on mobile version/width the navbar becomes two lines (just try resizing the window smaller). How can I make the navbar height the same size on mobile and desktop version?
Here's the navbar code:
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand nav-title-logo" href="{{ url_host }}{{ path('ShopiousMainBundle_homepage') }}"> </a>
</div> | Try with this CSS
.navbar {
max-height: 50px;
}
DEMO | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, css, twitter bootstrap, twitter bootstrap 3"
} |
In hashmap , set custom object value with in place object instantiation
I am creating a HashMap with custom object (say Employee) as key. **I have no modification access to Employee class.** Employee object has no args constructor Say `Map<String, Employee> empMap` is my map object. How can I instantiate object in place and set values and put it in map.
Map<String, Employee> mymap = new HashMap<>();
myMap.put("employee_key", () -> {
Employee e = new Employee();
e.setSalary(10000);
return e;
});
This shows error : Target type of lambda conversion must be an interface.
What i **dont** want to do:
myMap.put("employee_key", getEmployee(1000));
private Employee getEmployee(int salary){
Employee e = new Employee();
e.setSalary(salary);
return e;
}
In short, I am expecting in place instantiation and assignment while putting it as value in a map **without using extra method** . | I agree with deHaar that simply using `put`, with or without a convenience method, is likely your best option. However what you've asked for can be fairly nicely achieved using the `compute` method:
myMap.compute("employee_key", (k, v) -> {
Employee e = new Employee();
e.setSalary(10000);
return e;
}); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "java, java 8, hashmap"
} |
zenmap "intense scan plus udp" lan port has unknown port ,but lsof netstat doesn't shown those ports
I am new to nmap and I use zenmap "intense scan plus udp" to scan my router lan port , there has difference unknown "UDP" port each scan ,but each time I use lsof or netstat doesn't shown those udp port. How is possible happened?
The following is my command "nmap -sS -sU -T4 -A -v 192.168.0.1" | > ...like 21524 ,41702,42639,51554,60331 those highest udp port
There is probably a socket waiting for data on this port for a short time only. Typical examples are DNS lookups where each request should use a different origin port to deter DNS spoofing attacks. And this socket (and thus the port) is immediately closed after the DNS response is received. Thus you will not find it with netstat or similar if you look a few seconds later. | stackexchange-security | {
"answer_score": 1,
"question_score": 0,
"tags": "nmap"
} |
Prove that for integers $a,b$, if $3|ab$ with $15x+by = 1$ for some integers $x,y$ then $3|a.$
Prove that for integers $a,b$, if $3 \mid ab$ with $15x+by = 1$ for some $x,y \in \mathbb{Z}$ then $3 \mid a$.
I know that I have to show that $a=3k$, where $k \in \mathbb{Z}$.
Also I see that $15x+by=1$ can be written as $3(5)x+by=1$.
I do not know what else to do to show that $a=3k$. | I have actully done it this way: ab=3p, where p is an integer I know that 15x + by=1
a(15x+by)=a
15ax+aby=a
a=3(5)xa+3py
a=3(5xa+py), where 5xa+py is an integer b/c x,a,y,p are integers
so a is divisible by 3 | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "proof writing, divisibility"
} |
Duplicate DataGridView by Button Click Event
does someone can help me out. I'm facing a Problem. I have a DataGridView on a C# Windows Form with a Button below. I want to copy exactly the same Column definitions on a new Table below when clicking the Button so a new DataGridView gets added with the same Column definition as the table above, so to say a exact copy of the DataGridView without Data inside.
Is there a way to achieve this. I didn't found anything on the internet that helped me.
Probably someone has an Idea? | >
> private void Duplicate()
> { DataGridView dataGridView2=new DataGridView();
> foreach(DataGridViewColumn col in datagridview1.Columns) {
> int index=datagridview1.Columns.indexOf(col);
> dataGridView2.Columns[index].Name = col.Name; }
> dataGridView2.Location=new
> Point(dataGridView1.Location.X,button.Location.Y+20);
> this.Controls.Add(dataGridView2);
> }
> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, .net, winforms"
} |
How do I distribute apps created using ARCore in the store?
I am trying to create an app using arcore-unity-sdk-preview, which is supported by Google.
However, in order to use this ARCore, arcore-preview.apk must be installed. Otherwise, ARCore will stop working.
If I distribute the app I created in the store, the user will not be able to use the app unless I receive the arcore-preview.apk. Is there a solution to this problem?
Or are still experiencing this issue because it's not fully released yet?
If know about this, please help me. | As you said, distribution is still an issue because it's not fully released.
To work around this issue, you could upload the apk somewhere / ship it in your app's files and install it programmatically but the user has to allow installation of apps from unknown sources (`Settings > Security > Unknown Sources`) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "unity3d, arcore"
} |
Where can I get some information on starting C# programming with MVC / ASP.NET?
I'm a Java developer looking to learn some C#/ASP.NET. One thing I've never liked about .NET from the get-go was that it didn't have support for MVC. But now it does! So I was wondering if anybody knew where to get started learning C# MVC.
Also, do you need the non-free version of developer-studio to do this? | Just to add to Will's answer, Scott has a series on ASP.NET MVC development:
ASP.NET MVC Framework Part 1
ASP.NET MVC Framework (Part 2): URL Routing
ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views
ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 7,
"tags": "c#, asp.net mvc"
} |
How to change user with authentication inside shell script
It is possible to change the user within a shell script by `su - newuser`; but what if the newuser needs authentication. How can I provide the password within the shell script?
None of the users is root. | Using passwords in plain text files is not recommended. However, if no security risk is involved, create an `expect` script. Expect is a scripting language designed to interact with interactive shells and it is perfect for things like authentication or automation of processes that require a user to type in different things or select different options in a shell environment. | stackexchange-unix | {
"answer_score": 2,
"question_score": 1,
"tags": "linux, shell, ssh, shell script"
} |
TypeError after float to string conversion
i'm writing my first program in python. I have a function that should save a number in a txt file. This number is obtained with some math, converted in int, (just because i need only the integer part) then in string. Then saved into txt.
Here i just deleted the saving part and replaced with print.
str=140
str0 = float(str0)
str = float(str)
perc0 = 100-(str*100/str0)
perc0 = int(perc0)
perc0 = str(perc0)
print(perc0)
But the result is
File ".\temp.py", line 10, in <module>
perc0 = str(perc0)
TypeError: 'float' object is not callable
What am i doing wrong? Sorry for dumb question, but after some research i don't really know what's wrong, meybe i'm missing some basics | `str` is a keyword in python. You should avoid using that as a variable name. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "python"
} |
Error when opening eclipse with Spring Tools Suite
I am using the Spring Tool Suite for eclipse. When I launch the program. I get the following message:
> An internal error occurred during: "Initializing Spring Tooling".
>
> Attempted to beginRule: P/some.package.name, does not match outer scope rule: Beans Model Initialization
But I don't understand what it means
Thanks for your help | It was a problem with the eclipse project. As this was a maven project, I was able to do the following:
I deleted the project in eclipse _(right click - delete)_. I then deleted the `.project` file from the directory and imported the project as _existing maven project_.
**(I think you can only do this if you are using maven)** | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 3,
"tags": "java, eclipse, spring, spring tool suite"
} |
Are there spreadsheet functions to query route planner for travel time and distance?
I would like to realise a spreadsheet where the columns are as follows.
Place A | Place B | Distance by road between A and B | Travel time by road between A and B
---|---|---|---
I thought this might be possible using the 'Google' functions of Google Docs' spreadsheet, but I've found none that does the trick.
In the end, I could knock up an app to do this using the Google Maps API, but I would rather avoid it if I can. | _MapQuest_ seems to be the best bet, as they have a URL-based API for directions, whereas _Google Maps_ seems to be a _JavaScript_ library.
This worked for me in a _Google Docs Spreadsheet_. This one gets the distance (miles):
=importXML(" & A2 & "&to=" & B2,"//response/route/distance")
And this one gets the time (formatted in _hh:mm:ss_ ):
=importXML(" & A2 & "&to=" & B2,"//response/route/formattedTime")
where _A2_ is the origin and _B2_ is the destination.
You have to get an API key from _MapQuest_ and replace the value _YOUR_KEY_HERE_ with it. | stackexchange-gis | {
"answer_score": 9,
"question_score": 14,
"tags": "google docs"
} |
is it safe to unplug a USB drive while Windows is in sleep/hibernate/off mode?
I have a portable USB flash drive that I use with my netbook. When I'm on the go, it is convenient to be able to simply close the lid and remove my flash drive without first having to use Windows's Safely Remove Hardware routine. The netbook changes to sleep mode (ACPI S3 mode) when I close the lid. Is it possible to do this safely with Windows 7 Home Premium? What about for hibernate (S4) and off modes? | The "Safely Remove Hardware" routine finishes cached/delayed writes to the drive, so data isn't left in an inconsistent state when the drive is removed. As far as I know, when your netbook changes to sleep mode it also finishes any writing to the flash drive. You can unplug the drive as soon as the netbook is actually in sleep mode (which can take several seconds after you close the lid).
If the netbook is hibernated, it _should_ be safe to unplug the drive. A poorly-written program may throw errors when you resume if it expects the drive to be available.
If the netbook is off, it's always safe to just unplug the drive. | stackexchange-superuser | {
"answer_score": 8,
"question_score": 9,
"tags": "windows 7, usb storage, hotswapping"
} |
Чат с помощью websocket + ajax в тандеме
Я вот тут кушал-кушал, и вдруг меня осенило: а что, если сделать чат с помощью `websocket + ajax` в тандеме? Пусть через сокет нельзя передать сам текст сообщения, потому что его может перехватить злоумышленник, но можно ведь передать команду на выполнение `ajax` запроса, который и загрузит сообщение. А, ребята, так ведь можно?
То есть процесс будет выглядеть так: на сервере появилось новое сообщение, через сокет браузер узнал об этом и через `ajax` загрузил? | > Пусть через сокет нельзя передать сам текст сообщения, потому что его может перехватить злоумышленник
Воспользуйтесь wss, хотя что у вас там за чат - шаринг банковских карточек или поддержка командного центра запуска МБР? :)
Лишнего удумали, ws отличный транспорт, а для поддержки старья выбирайте правильные либы, типа sockjs или socket.io. | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ajax, websocket"
} |
how we will find camera is running or not in any application?
_**How we will find Camera is open or not in any application?_** =>i have one service in our application where camera is going on continue on in background,but now i am open again default camera application at that time camera not found exception occur.
=>At that time i want to any notification if camera is open in other application. if any body have idea than please give me suggestion. Thanks | > i have one service in our application where camera is going on continue on in background
This is not supported by Android AFAIK.
> At that time i want to any notification if camera is open in other application
This is not supported by Android AFAIK. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android"
} |
Uart TxD & RxD voltage
What's voltage of RPi pins 14 & 15 (RxD & TxD)?
I want to use an octocouplers, so I'm very interested in voltage parameter. | All the Pi's gpios (which include the UART RXD, TXD gpios) are 0-3.3V. A voltage outside that range will likely damage the gpio, how quickly will depend on how much current is allowed to flow. | stackexchange-raspberrypi | {
"answer_score": 2,
"question_score": 0,
"tags": "gpio, uart"
} |
Take a picture of me/for me (which preposition better translates)?
As an experienced tourist in China, I know the sentence:
Although it gives the desired result-- someone taking a picture of me, for me, with my own camera-- I am not sure of the exact corresponding English translation.
Does it mean:
A) Can you take a picture _for_ me?
Or,
B) Can you take a picture _of_ me?
And how can I distinguish between the two, or add a second object like "Can you take of picture of her for me?" | '..' means 'take a picture of ..', so your sentence means 'can you take a picture of me'.
The verbatim translation for 'do [something] for [someone]' is '....', but in your scenario (asking stranger for help), it is more common to say '....' (help [someone] do [something]), so 'can you take a picture of her for me' would be '' | stackexchange-chinese | {
"answer_score": 2,
"question_score": 1,
"tags": "grammar, mandarin, preposition"
} |
Checkbox itemtemplate templatefield text after databound
I have the following checkboxes in my gridview:
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Active")%>
<asp:CheckBox ID="Active" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
And it working very fine. I'm populating it with a bool value. The problem is that its showing the string text in the gridview, like:
True [x] False [ ] True [x]
and so long... I would like to show just the checkboxes. I tried this in the rowDataBound event:
if (result.Active)
{
((CheckBox)e.Row.FindControl("Active")).Checked = true;
((CheckBox)e.Row.FindControl("Active")).Text = string.Empty;
}
But its not working. There is a way?
Thanks,
Pedro Dusso | Instead of TemplateField, why don't you just use the CheckBoxField?
<asp:CheckBoxField DataField="Active" HeaderText="Active" />
If you have to use TemplateField because of Insert/Edit then you should be able to do
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox id="CheckBoxActive" runat="server" Checked='<%#Eval("Active") %>' />
</ItemTemplate>
</asp:TemplateField> | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "asp.net, gridview, itemtemplate"
} |
adding multiple existing folders and multiple existing files to Visual Studio project in single step
Does anyone have a way to add multiple folders and (existing) files within those folders to a Visual Studio project in a single step (or via macro)? Let's assume all of the folders and files were copied/pasted into the project folder where they need to reside relative to the project folder, but are not actually stored in the .csproj or .vbproj file, which I believe is a requirement to compile those files into the solution/project.
This works great if you have a web application project in your solution, but not so well if you have a .csproj or .vbproj. In that case, you must manually add folders (and nested folders), and add existing files and browse to each one individually, which can take a long time. | In the solution explorer, select the project, click the "Show All Files" button - !enter image description here.
This will show all the files, even those not part of the project. You can now select all of these in the solution explorer (using `Ctrl` \+ Click) then right click and go to "Include In Project". | stackexchange-stackoverflow | {
"answer_score": 47,
"question_score": 30,
"tags": "visual studio, file, add, directory"
} |
Service to allow users to upload large files
I need an app/service I can put on our web server (LAMP) that will allow external (and unauthenticated) users to upload large files (10 MB - 100 MB for now) to our website, instead of trying to email them.
If possible, it should be very user-friendly, as it will be used by non-technical users.
I don't really want to roll my own, as I'm sure this must've been done before, but I'm not sure exactly what to search for. I seem to get a lot of results for torrent servers etc. | I agree with Jens. To help you along, this might help: < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "php, upload"
} |
Merge PDF files
I already read the thread how to merge epub files but Is there any way by which I can merge different pdf files into one. Earlier I have tried an app for this purpose but I lost all my pdf files after merging. | For serious work with PDF, you can't stay away from Adobe Acrobat… still…
You might also look at Nitro. | stackexchange-ebooks | {
"answer_score": 2,
"question_score": 5,
"tags": "pdf"
} |
windows command for grand total
Is there a easy way to calculate the grand total of all the numberic values specified line by line using a windows command (or batch file - least prefer)
suppose
7612
7724
19844
20092
20184
20468
27100
36456
39428
54264
69008
97208
assume this is in a file
I want the total of all the values. thanks in advance | I'm not aware of any command line utility to compute such a sum. But you can use a for loop iterating through the file. Something like this will work but you will need a helper batch file. In Sum.bat dump:
REM. Turn off echo-ing of individual commands
@echo off
REM. Set variable a to 0. /a mean arithmetic expression
set /a sum = 0
REM. For loop updating the sum as we go
FOR /F %%i IN (file.txt) DO set /a sum += %%i
REM. Output
echo %sum% | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "windows, command line"
} |
What is entropy?
We discuss a lot of topics and use measures of entropy to determine how difficult it is for an attacker to be successful. What does entropy mean in the context of cryptography? How is entropy calculated in the general case? | In information theory, entropy is the measure of uncertainty associated with a random variable. In terms of Cryptography, entropy must be supplied by the cipher for injection into the plaintext of a message so as to neutralise the amount of structure that is present in the unsecure plaintext message. How it is measured depends on the cipher.
Have a look at the following article. It provides a survey of entropy measures and their applications in cryptography: "Entropy Measures and Unconditional Security in Cryptography (1997) " | stackexchange-crypto | {
"answer_score": 30,
"question_score": 43,
"tags": "randomness, entropy"
} |
Select2 Initialize select after appending data to existing select
In my select2 select, i need to append li after document is ready, and after appending, how can i reinitialize select2. If I once close and again open the select, the appended data are selectable but not as soon as i append. How can i reinitialize it. | You have to destroy the select2 on these elements and then reinitialize it.
$("select").select2("destroy").select2(); | stackexchange-stackoverflow | {
"answer_score": 37,
"question_score": 16,
"tags": "jquery, jquery select2"
} |
How can I create a select list with all languages?
I need to have a field on a form, where the user can choose from the set of world languages for an event.
It's going to be an Autocomplete term widget (tagging) field.
How can I reuse the inbuilt language list in Drupal for this purpose? | there is the _locale_get_predefined_list which return you an array. so you need to do the field yourself.
you also could try language_field, you should be able to use that directly in your form. | stackexchange-drupal | {
"answer_score": 3,
"question_score": 1,
"tags": "taxonomy terms, i18n l10n"
} |
pyodbc "commit" command not recognised in Python 3.2
Has anybody got pyodbc installed with Python 3.2? I have, and all is well except that the interpreter doesn't recognise "commit()". Anyone else got the same problem? Anyone know if I'm doing something wrong? Thanks, John R | here is an example of my code using commit() :
cnxn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=F:\\computing\\Payroll v2 2\\\employees.accdb')
cursor = cnxn.cursor()
cursor.execute("insert into Medication(ID, Doctor, NameOfMedication, Dosage, DateStart, DateEnd, Notes, LastUpdated) values (?,?,?,?,?,?,?,?)",self.ui.residentComboBox.currentText().split()[0], self.ui.doctorLineEdit.text(), self.ui.nameOfMedicationLineEdit.text(), self.ui.dosageLineEdit.text(), self.ui.dateStartDateEdit.text(), self.ui.dateEndDateEdit.text(), self.ui.notesTextEdit.document().toPlainText(), self.ui.lastUpdatedDateTimeEdit.dateTime().toString("dd/MM/yyyy, hh:mm:ss"))
cursor.execute("update Medication set MedEndMonth=? where ((ID=?)) ",month,resID)
cnxn.commit()
self.close() | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, pyodbc"
} |
Initializing, Configuring & Using Automapper.Collection in an Aspnet core boilerplate project
Can anyone detail how to initialize, configure and use automapper.collection in an aspnet core boilerplate project please. A project sample would be much appreciated.
Cheers | You can configure it in the `PreInitialize` method of `YourApplicationModule`.
Configuration.Modules.AbpAutoMapper().Configurators.Add(
cfg =>
{
cfg.AddCollectionMappers();
cfg.CreateMap<OrderItemDTO, OrderItem>().EqualityComparison((odto, o) => odto.ID == o.ID);
}
);
For EF Core, you have to configure the equivalence for each entity.
For more information, see AutoMapper.Collection's README.md. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "automapper, aspnetboilerplate"
} |
Ansible, retrieve ip address for a given network interface via variables
I am currently facing an issue with my ansible role, actually my ansible role installed NRPE server on Linux.
In some case, those servers have multiple NIC and need to bind the NRPE server to one particular NIC (dedicated for the monitoring network).
My goal is to retrieve the IP address of a named network card (which is a variable, as from time to time, it could be another NIC) and set this IP to the server_address option in my nrpe.cfg.
After some research, try and error, ansible_fact seems the way to gather those information. I think I will have to register a variable to use with my jinja2 template.
My main issue is how to retrieve IP address from named NIC (enp0s8).
Thanks for your advices.
Regards,
Nikos | If your playbook has `gather_facts: yes` or if you run a `setup` task in your playbook there should be a variable like this available.
- debug:
var: ansible_enp0s8.ipv4.address
If you want to see all the possible variables that are normally discovered run a command like this `ansible some-hostname -m setup`.
> I try to build the following variable {{ ansible_{{ nrpe_address_server }}.ipv4.address }} it does not work
You don't use {{}} inside an expression, or to say it differently you can't nest them.
What you probably need is something like this.
- debug:
var: hostvars[inventory_hostname]['ansible_'~nrpe_address_server].ipv4.address
Using the [] syntax allows you access specific variable using dynamic data. The `~` is concatenates strings. | stackexchange-serverfault | {
"answer_score": 6,
"question_score": 1,
"tags": "networking, ansible"
} |
RegEx to match sentence containing fixed number of commas
I'd like to match sentence with a certain number of commas. Assuming sentence starts with '. '.
Although I managed to get what I want, my RegEx somehow matches the whole paragraph.
So in other words, I'd like to delimit beginning of this to just one sentence.
My code is as follows:
/(?:\.+.+\,+.+\,+.+\,+.+\,+.+)/ig
I'm doing it in js, btw.
And the dummy paragraph I am working with:
This is RegEx. Whether you think so, too. I'm telling you, this, is what, I, think about this. | /\.(?:(?:[^,\.]+,){4}[^,\.]+)/.exec('This is RegEx. Whether you think so, too. I\'m telling you, this, is what, I, think about this.')[0]
returns
> . I'm telling you, this, is what, I, think about this | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript, regex"
} |
how to get json by retrofit if serialize is date
I have a `Json` like this
"data": {
"2020-05-01": {
"tanggal": "Jumat, 01\/05\/2020",
"subuh": "05:05",
"dzuhur": "12:33",
"ashar": "15:51",
"maghrib": "18:40",
"isya": "19:51"
},
"2020-05-02": {
"tanggal": "Sabtu, 02\/05\/2020",
"subuh": "05:04",
"dzuhur": "12:33",
"ashar": "15:51",
"maghrib": "18:40",
"isya": "19:52"
}
}
how can I get the `Json`, If the object is `Date` but I must have to use retrofit
Thanks for your help. | Try to use a Map:
class Data {
Map<String, MyObject> firstData;
Map<String, MyObject> secondData;
}
Where `MyObject` is:
class MyObject {
String tanggal;
String subuh;
String dzuhur;
String ashar;
String maghrib;
String isya;
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "android, json, retrofit, retrofit2"
} |
Problem regarding overlapping song?
I am using a AVAudio player to play a song,
I take a song from ipod library,
i play a first song but when select other song from ipod library that both song play simultaneously,
How to stop a first song?
I tried to stop a song
- (IBAction)player_stop {
[theAudio stop];
theAudio = Nil;
}
on button play method i write this code
- (IBAction)btn_play {
[self player_stop];
[theAudio play];
}
How i Do that? | You should tell the player, not the audio, to stop.
`[self.player stop];`
To start a new audio you can do as follows:
[self.player stop];
self.player = nil;
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[self.player play]; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "iphone, objective c, cocoa touch, ios4, avaudioplayer"
} |
how soon can return to austria to be with my family after being here 90 days
Can I return to Austria in a few days to be with my daughter. I am a US citizen and have 2 yr leave to remain visa visa. My daughter needs me here in Austria.
* * *
May I just say that my 2 year leave to remain visa is for the UK. | You can stay in the Schengen area for a maximum of 90 days in any 180 (the 90/180 rule1). If you've already been in the area for 90 days you must stay away for 90 days before you return.
Be aware that if you return after 90 days, planning to stay for another 90 days, sooner or later you will be denied entry as it will appear that you are trying to live in the Schengen area through repeated visits.
There is no way to extend your stay under the 90/180 rule. If you wish to stay longer you must apply for a national visa D that will permit a stay of up to six months. More than that will require a residence permit.
1Codified in Regulation (EU) 610/2013 | stackexchange-travel | {
"answer_score": 3,
"question_score": -1,
"tags": "schengen, us citizens, austria, 90 180 visa rules"
} |
How to convert Flutter Date to TimeStamp?
I need to send a `post` request to the REST API where it includes a `Date` value. However the REST API and MySQL accepts a `Timestamp`. Below is how I prepare my current date
User user = User(
name: nameTxtController.text,
email: emailTxtController.text,
phone: mobileTxtController.text,
userLanguage: userLanguage,
userRights: userRight,
lastUpdated: DateTime.now(),
dateCreated: DateTime.now()
);
How to convert this to `Timestamp` ? | Just do the following
User user = User(
name: nameTxtController.text,
email: emailTxtController.text,
phone: mobileTxtController.text,
userLanguage: userLanguage,
userRights: userRight,
lastUpdated: DateTime.now().millisecondsSinceEpoch,
dateCreated: DateTime.now().millisecondsSinceEpoch
);
for this to work, your `user.lastUpdated` and `user.dateCreated` should be of type `int` in your model (`bean` if you are from Java background) class | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 10,
"tags": "android, ios, datetime, dart, flutter"
} |
what is the else statement means in codeigniter index.php line 196
when the following else statement will be executed? if the $system_path is invalid, of cause ,it will go to the else statement. however, in this case, the else statement seems to be meaningless.
< line 196
if (($_temp = realpath($system_path)) !== FALSE)
{
$system_path = $_temp.DIRECTORY_SEPARATOR;
}
else
{
// Ensure there's a trailing slash
$system_path = strtr(
rtrim($system_path, '/\\'),
'/\\',
DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR
).DIRECTORY_SEPARATOR;
} | The point of that `if/else` block is to construct a string that makes any kind of sense for use in the `if` block that follows. That block starts with
if( ! is_dir($system_path))
If `realpath()` returns FALSE then `$system_path` as written cannot be resolved. But that _might_ not mean the path does not exist. Perhaps the developer knows something that 'realpath()' cannot figure out. The `else` part gives the developer the benefit of the doubt. It takes the supplied value of `$system_path` and formats it for use in `is_dir($system_path)`.
Off the top of my head I cannot think of an example where `realpath()` would fail but where `$system_path` does exist. But developers are a creative bunch. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "codeigniter"
} |
Spring: How to use @RequestBody after reading inputStream
I'm having the issue described here but it's not clear to me how to address it.
The issue is that I have an AuthenticationProvider which has to read the body of the request. When my controller method wants to use that data via @RequestMapping, however, it's empty because the Provider has already read the inputStream.
Is there a way to obtain an inputReader from Request which supports mark/reset so my provider can simply roll the stream back to it's initial state after it does the authentication? It seems crazy that the default behavior of the filter is destructive modification of the request object. | The Provider should be triggered only in specific cases, so it shouldn't affect your whole application. But if you need the body in the requests handled by the provider, then you still have a workaround:
1. implement a servlet `Filter`
2. wrap the request
3. in the wrapper cache the request body, and then override the `getInputStream()` method to return a `ByteArrayInputStream` with the cached request body. That way it can be read muiltiple times.
spring's `AbstractRequestLoggingFilter` does something similar and has an example wrapper, you can check it. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "java, spring, http, rest, inputstream"
} |
complex irrational definite integration
> Finding value of $$\frac{8}{\pi}\int^{2}_{0}\frac{1}{x^2-x+1+\sqrt{x^4-4x^3+9x^2-10x+5}}$$
Let $$I=\int^{2}_{0}\frac{1}{x^2-x+1+\sqrt{x^4-4x^3+9x^2-10x+5}}dx$$
$$I=\int^{2}_{0}\frac{1}{x(x-1)+\sqrt{(x^2-2x)^2+5x(x-2)+5)}}dx$$
From $\displaystyle \int^{a}_{0}f(x)dx=\int^{a}_{0}f(a-x)dx$
$$I=\int^{2}_{0}\frac{1}{(2-x)(1-x)+\sqrt{(2-x)^2x^2+5(2-x)(-x)+5}}dx$$
How do i solve it help me please | Let's start multiplying the original fraction (up and down) by $$x^2-x+1-\sqrt{x^4-4x^3+9x^2-10x+5}$$
to obtain
$$\frac{1}{2}\int^{2}_{0}\frac{x^2-x+1-\sqrt{x^4-4x^3+9x^2-10x+5}}{x^3- 3 x^2+4 x -2}dx$$
Now, taking acount:
* $x^2-x+1=(x-1)^2+(x-1)+1$
* $x^4-4x^3+9x^2-10x+5=(x-1)^4+3(x-1)^2+1$
* $ x^3- 3 x^2+4 x -2 =(x-1)((x-1)^2+1)$
we perfom the change $x-1=t$ to transform our integral as follow
$$\frac{1}{2}\int^{1}_{-1}\frac{t^2+t+1-\sqrt{t^4+3t^2+1}}{t(t^2+1)}dt=\frac{1}{2}\int_{-1}^1\frac{t}{t^2+1}+\frac{1}{t^2+1}+\frac{1}{t(t^2+1)}-\frac{\sqrt{t^4+3t^2+1}}{t(t^2+1)}dt$$
As first, third and fourth fraction are odd function over symmetric interval, they vanishes. Only rest the second fraction and then our integral reads
$$\int^{2}_{0}\frac{1}{x^2-x+1+\sqrt{x^4-4x^3+9x^2-10x+5}}dx=\frac{1}{2}\int_{-1}^1\frac{1}{t^2+1}dt=\frac{\pi}{4}$$
Thus
> Finding value of $$\frac{8}{\pi}\int^{2}_{0}\frac{1}{x^2-x+1+\sqrt{x^4-4x^3+9x^2-10x+5}}=2$$ | stackexchange-math | {
"answer_score": 5,
"question_score": 0,
"tags": "definite integrals"
} |
Finding the length of each set of successive values using python or excel
I have a python list/excel range that looks like
[0,0,0,0,1,1,0,0,1,1,1,1,1,0,1,0,0,0,0,0,0,0,1,1,0,0,0] .
I want the following output:
length of 1st set of zeros - 4
length of 2nd set of zeros - 2
length of 3rd set of zeros - 1
length of 4th set of zeros - 7
length of 5th set of zeros - 3
I've tried the formula `" COUNTIF($D2:D$2,D2)"` in Excel which helps me find the nth value, but I'm not sure how to find the length of each set of successive values.
How can the above be achieved in Excel as well as Python? | You should probably use `itertools.groupby`:
counter = 1
suffixes = {1: 'st', 2:'nd', 3:'rd'}
for key, group in itertools.groupby(the_sequence):
if key == 0:
print 'The length of {}{} sequence of zeros is: {}'.format(counter,
suffixes.get(counter, 'th'),
len(tuple(group)))
counter += 1
That outputs:
The length of 1st sequence of zeros is: 4
The length of 2nd sequence of zeros is: 2
The length of 3rd sequence of zeros is: 1
The length of 4th sequence of zeros is: 7
The length of 5th sequence of zeros is: 3
Unfortunately I'm not an excel user and I can't help you with the Excel solution. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "python, excel"
} |
Stop links from executing with JavaScript
I can stop normal inks from working with this:
$('#container a').click(function(event) {
return false;
});
However my site has existing javascript that fires when a link is clicked. The code above doenst stop these from firing. | You may unbind click and stopPropagation
$('#container a').unbind('click').click(function(event) {
event.stopPropagation();
//event.preventDefault();
return false;
}); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
} |
Laravel classloader.php error failed to open stream: No such file or directory
I am able to run "php artisan migrate" fine. I'm able to get all the form input if I use Request::all() but when I try to add the data to my mysql database table I get the below error:
ErrorException in ClassLoader.php line 412:
include(Correct_Path/full-personal/database/migrations/2015_07_06_035501_resume_requesters.php): failed to open stream: No such file or directory
I currently have the form attached to a controller method with the below code:
$input = Request::all();
ResumeRequesters::create($input);
I know that I am properly connected to mysql server because I'm able to migrate my migrations.
Any help would be great. Also why did laravel change so many things in Laravel 5?
Thanks | You have to run `composer dumpautoload` inside your project folder. | stackexchange-stackoverflow | {
"answer_score": 169,
"question_score": 51,
"tags": "php, mysql, laravel, laravel 5"
} |
Create new column if value appears in column of other data frame
I have a dataframe `dfA` with a column `SubscriberID`.
I would like to create a new column (`ReceivedPre`), populated with `1` or `0`, depending on if the `SubscriberID` value appears in the column of another dataframe, `dfB`
I tried the following:
within(dfA, {
ReceivedPre = ifelse(SubID == dfB$SubID, 1, 0)
})
But get a warning message:
Warning message:
In SubID == dfB$SubID :
longer object length is not a multiple of shorter object length
I don't think it is executing entirely correct, as I should get significantly more `1` values in my `ReceivedPre` column. | If we use `within`, the assignment would be `<-` instead of `=` and also use `%in%` instead of `==`
within(dfA, {
ReceivedPre <- ifelse(SubID %in% dfB$SubID, 1, 0)
})
Otherwise, it can `transform`
transform(dfA, ReceivedPre = as.integer(SubID %in% dfB$SubID)) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "r, dataframe, dplyr"
} |
Looking for geodata of Europe's major roads
As stated in the title, I'm currently looking for a shapefile/other geodata source of Europe's major roads (highways). If anybody knows a free datasource (or a possibility to extract that data from Open Street Map without processing the world file), it would be greatly appreciated. | Thought I'd share what I found through lengthy research. It seems, the UNECE (United Nations Economic Commission for Europe) has conducted a transportation network census in 2005. Hidden deep inside their Website, I have found this:
<
You have to download the ArcReader-project, which, when unzipped, contains routable, simplified shapefiles of all major roads along with some useful metadata. Same applies to the train network which can also be found on the page.
!enter image description here | stackexchange-gis | {
"answer_score": 8,
"question_score": 8,
"tags": "openstreetmap, data, europe"
} |
Is there a post-finish operator hook in the python API
I'm writing a generic add-on `bpy.types.Operator` based on this question. It creates and arranges planes along an object, then splits the object along each new plane.
The user has control over the number of planes to arrange, and the direction along which to arrange them. The way I'm going now, everything happens in the `execute` method, so the user never sees how the planes are arranged; they're added, the object is split, and they go away all at once.
In this case, it'd be nice to have the `execute` method be responsible for laying the planes, and then a "final apply" hook splits the object, and removes the planes.
Is it possible to have a block of code run _after_ an operator finishes?
(Is this possible within the python API, or must it be implemented as a modifier in C?) | No, Blender doesn't have this functionality, Check on the documentation for `bpy.app.handlers`, aside from this we don't provide other hooks into Blender. | stackexchange-blender | {
"answer_score": 4,
"question_score": 9,
"tags": "python, operator"
} |
How to stop events from firing in pageload?
I have a problem. Currently, I set the textbox value during PageLoad. However, this triggers the textbox change event.
**Markup**
<asp:TextBox ID="txtToDate" CssClass="text"
runat="server" Width="100px" ReadOnly="false"
AutoPostBack="true" ></asp:TextBox>
**On pageload**
txtToDate.Text = Format(Now.Date, "MM/dd/yyyy")
**Textchange Event**
Protected Sub txtToDate_TextChanged(ByVal sender As Object,
ByVal e As System.EventArgs) Handles txtToDate.TextChanged
Me.Grid.Visible = False
End Sub
How can I prevent the change during PageLoad from triggering the texbox change event? | As mentioned in your question, you don't want to hide the grid during the `PageLoad` event, but you want to hide the Grid on the `TextChange` event of the `Textbox`. You can try something like...
Protected Sub txtToDate_TextChanged(ByVal sender As Object,
ByVal e As System.EventArgs) Handles txtToDate.TextChanged
if(Page.IsPostBack)
Me.Grid.Visible = False
End Sub | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "asp.net, vb.net"
} |
Simple example of using Rails JSON with JQuery?
I'm looking for a very very simple example where a Rails App does the following:
The returned data is a JSON:
[{"is_it_working":true, "very_simple_string":"Yes!"}]
I want to use the following function in JS to return the value of "is_it_working". But how???
function updateImpression(){
$.get('/give_me_json', function(data) {
$('.da_place').html(data);
}
Instead this would return the whole json as a string. | Actually the response is `array` of `json object` so you need to get element from array 1st then property from json. **SEE THE EXAMPLE**
var response = [{"is_it_working":true, "very_simple_string":"Yes!"}];
//1 way
alert(response[0].is_it_working);
//2nd way
$(response).each(function(i,elem){
alert(elem.is_it_working);
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "javascript, jquery, ruby on rails, json"
} |
Tracking keywords on Twitter via Streaming
I am tracking some keywords on Twitter using the command below, I want to print just the "screen_name" property of the tweet author, could get the command above working but want remove "quotes" from author screen_name, how could I do this?
curl -N -d @tracking < -umyuser:mypass | sed -e 's/[{}]/''/g' | awk -v RS=',"' -F: '/^screen_name/ {print $2}'
Thanks | Regular expression parsing of JSON is always a bad idea. Parse the markup into an object with a full JSON parser, then pick out the field you are interested in. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "unix, shell, twitter"
} |
Compiler-error while performing type-casting in Java
Let's see the following expressions in Java.
int temp = -254;
Integer temp2 = (Integer) temp; // compiles because of autoboxing
Integer temp3 = (Integer) -254; // doesn't compile - illegal start of type.
Integer temp4 = (Integer) 10-254; // compiles
Integer temp5 = (Integer) (int) -254; // compiles
Integer temp6 = -254; // compiles
Integer temp7 = (int) -254; // compiles
In the above expressions, why are these expressions `(Integer) 10-254` and `(int) -254` valid whereas the expression `(Integer) -254` doesn't compile even though the constant `-254` can perfectly be evaluated to `Integer`? | This is an interesting edge case, the compiler attempts to perform integer subtraction on the `Integer` class and an `int` literal (254).
Note that the following compiles and is more explicit:
Integer temp3 = (Integer)(-254) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 4,
"tags": "java, casting"
} |
A question related to the minimality of generators of an ideal
I am currently working on the following exercise problem from David Eisenbud's _Commutative Algebra With A View Towards Algebraic Geometry._
> **Exercise 4.9** Consider a local ring $R$ with maximal ideal $m$. Let $I\subset R$ and $x\in m$ a nonzero divisor on $R/I.$ My goal is to show that a minimal set of generators for $I$ maps to a minimal generating set for the image of $I$ in $R/(x)$.
I am trying to prove this claim _via_ _Nakayama's Lemma_ , but I'm not quite sure how to proceed.
Any hint/help will be very much appreciated. Thanks. | Since $I/xI=I/((x)\cap I)$, applying Nakayama's lemma to $I$ and $I/xI$ gives us the desired result. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "abstract algebra, ring theory, commutative algebra, ideals"
} |
CSS: is there a hierarchy with height values?
I want to use the calc function for my height value, but some older browsers don't support it and it makes the site look awful.
.container2 {
height: calc(100% - 87px);
height: -webkit-calc(100% - 87px);
height: -moz-calc(100% - 87px);
height: 500px;
}
I thought if I layed it out like this that browsers that support the calc function would use those first but if it doesn't then it would use the basic value `500px` in this case.
Is there a way to use calc height first, then plain `500px` height if the browser doesn't support it?
Hope that makes sense | You have it backwards: browsers will process all declarations in the same rule and use the last one that is applicable.
So, two things: your fallback `500px` value needs to go on the top, and you need to have the unprefixed `calc()` value at the bottom to ensure that browsers use the standardized implementation over their vendor-specific ones when applicable:
.container2 {
height: 500px;
height: -webkit-calc(100% - 87px);
height: -moz-calc(100% - 87px);
height: calc(100% - 87px);
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "html, css"
} |
Spring Inheritance Autowired Annotations
For inheritance I see examples using XML Definition. I had a doubt using Autowire and Annotations.
I have
@Component
class A{
}
@Component
class B extends A{
}
class TestClass{
@Autowire
A aObj;
}
So I believe this will inject Object of Class A. Correct ? Also If I make my class A as abstract, it will inject Class B object. Correct ?
Also it would be good if someone can give me a link to example for this. | I tried the code and got the results as follows.
For above it throws NoUniqueBeanException.
2. If I make Class A as abstract it injects Class B Bean and works fine.
3. If I don't want to make class A as abstract I need to Use Qualifiers as follows
@Component(value="aBean")
class A{
}
@Component(value="bBean")
class B extends A{
}
class TestClass{
@Autowire
@Qualifier(value="aBean")
A aObj;
}
This injects Class A bean. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "spring"
} |
Color spectrum Image - How to create
I want to create a color spectrum image for a project. How do I create an image like this in photoshop?!color spectrum | I was able to create a near replica in photoshop by using a rainbow gradient left to right.
And then creating 2 layers- one with black to transparent gradient in the bottom and white to transparent gradient on top.
That did the trick I think. | stackexchange-graphicdesign | {
"answer_score": 5,
"question_score": 4,
"tags": "adobe photoshop, color"
} |
Any workaround to getting Copy/Paste working in JDK 7 AWT Applet on Mac?
Since Apple forced the update to JDK 7 on Mac, old AWT applets no longer support copy/paste. For example, if you visit:
Simple AWT Textfield Example
you cannot copy and paste into the applet text field on that page. I've confirmed that you can still copy/paste in AWT on Windows with JDK 7.
Anybody know a workaround? | Oracle released Java 6 Update 24 in February 2011 to remedy 21 vulnerabilities: Announcement
As part of this security release, the ability to copy & paste from a computer's clipboard into a Java applet has been disabled.
To fix this issue there are 2 solutions:
1. Create a digital signature for the applet.
2. Work around: If you do not want to work with the digital signature, add to your java.policy file the following line: permission java.awt.AWTPermission "accessClipboard" | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "java, macos, applet, awt, java 7"
} |
implicitlyWait does not work in webdriver javascript
I want to wait for the error message comes out. However, when I use browser.driver.manage().timeouts().implicitlyWait(), but I have to use browser.driver.sleep()
this.getErrorMessage = function () {
var defer = protractor.promise.defer();
browser.driver.sleep(2000); //This works
browser.driver.manage().timeouts().implicitlyWait(2000); // This does not work
browser.driver.findElement(By.xpath(_error_msg_xpath)).getText().then(function (errorMsg) {
defer.fulfill(errorMsg);
});
return defer.promise;
}; | From what I understand, you need a `browser.wait()` in this case:
this.getErrorMessage = function () {
var EC = protractor.ExpectedConditions;
var elm = element(by.xpath(_error_msg_xpath));
browser.wait(EC.presenceOf(elm), 2000);
return elm.getText();
};
This would wait for the presence of the element _up to_ 2 seconds returning a promise with a text of the element in case the element is found and you would get a Timeout Error in case the element would not become present in 2 seconds. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 3,
"tags": "javascript, selenium webdriver, jasmine, protractor, webdriverjs"
} |
CSV file contains trailing pipe delimiters
I have an excel file and I exported the file into a pipe delimited csv file. However, in each row of the csv file, there are trailing pipes.
Here's a typical row:
dsad|asd|safd|sadaf| |||||||||
ddss|sd|saadfdaf|dadf |||||||||
Does anyone know how not to include those trailing pipes while exporting to csv from excel?
Thanks. | The sheet you are exporting probably contains cell that excel believes has values in them (I call them ghost cells). To prevent this behaviour, I have two suggestions:
* Copy the spreadsheet to a fresh new spreasheet and export again. It should be fine.
* Delete all the columns after the last column containing data (Do not use the `Delete`/`Del` key, select the columns till the end and use `Ctrl`+`-` instead). After this, save the workbook then export again.
If those don't work, there's probably some rows with actual data somewhere, and there, the data will be correctly delimited by the pipes. Might be best to count the number of columns of data that you have and make sure your resulting csv file has the same number of columns.
If this still doesn't work... just shout I guess? ^^; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "excel, csv, delimiter"
} |
heat weighting issue
Here is my blend file: < It's too big for the usual blend file upload sites
And before you send me here heat weighting: failed to find solution for one or more bones I have tried this as much as I can understand from it.
When I parent the bones and mesh, I get the error: "Bone Heat Weighting: failed to find solution for one or more bones"
Anytime I have ever dealt with bones and mesh, I always get this error and I can never figure it out. Can you check my file out and explain what is the issue, pls? | You can first _Merge by Distance_ , it looks like you have overlapping vertices. Then scale up a lot both the object and the armature (like 5 times), apply the scale, parent the object to the armature, it should work. Scale down if needed. It looks like when the topology is too dense it won't work so sometimes you need to scale up. As a side note, do you need so many faces? | stackexchange-blender | {
"answer_score": 2,
"question_score": 1,
"tags": "modeling, bones"
} |
How to store HStore field properly?
Here I have a `HStoreField` which will be taken from user Input.
User gives the input in the format `s:Small,l:Large,` But I think the `HStoreField` needs the data type like this`{'s': 'Small','l':'Large'}`.
How can I covert the user data into this format so that I can store into the `HStoreField`.
Or simply I need to store the data. How can I do it ?
class MyModel(models.Model):
properties = HStoreField()
# view
properties = request.POST.get('properties')
print(properties)
#properties has data in this format s:Small,l:Large,
MyModel.objects.create(properties=properties)
I get the error like this.
django.db.utils.InternalError: Unexpected end of string
LINE 1: ...antity_reserved") VALUES ('ttt', 11, 'ttt', '55', 'Small:rrr... | You can parse the properties string and create dictionary from it:
properties = 's:Small,l:Large,'
properties_dict = {}
for pair in properties[:-1].split(','):
key, value = pair.split(':')
properties_dict[key] = value
>>> print(properties_dict)
{'s': 'Small', 'l':'Large'} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "python, django, django models, django views, django postgresql"
} |
Are toast columns compressed also in shared_buffers?
Reading here I cannot find a clear answer: <
I need to know if setting storage to `EXTERNAL` for a particular column, I can gain a little performance. Most of my data is retrieved from `SHARED_BUFFERS`.
I'm curious to know if decompression is done for every query working on that field. | Yes, they are.
`shared_buffers` is block-oriented, and stored in the same format as on-disk.
This is generally good for performance, since the decompression is very fast, and the compression means that more fits in `shared_buffers`. The only case it might hurt is if you have enough storage to fit the whole dataset in `shared_buffers` uncompressed too. | stackexchange-dba | {
"answer_score": 2,
"question_score": 1,
"tags": "postgresql, compression"
} |
Dynamically add amount to cart in woocommerce
I am very new to this community. kindly help me to get resolve form wordpress related query.
I am working on woocommerce website and need to add a service for ex:"electricity bill payment" . So, user has to dynamically add the amount and it should add to the card and reduced from his main wallet.
Is there any plugin or extension for this dynamically price added by this enduser ?
Plz suggest me and sorry for my bad english.
Many thanks, sai | function woo_add_cart_fee() {
global $woocommerce;
$woocommerce->cart->add_fee( __('Custom', 'woocommerce'), 5 );
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
Would you please add above code in your active theme `functions.php` ? but it will be applied on over all cart. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "wordpress, woocommerce, hook woocommerce"
} |
Patch an install4j uninstaller application possible?
We detected a bug within our uninstall routine of one of our released products. Now we are thinking about providing a patch to fix this bug in the uninstaller application of install4j. In generally is this possible? We don't want to make changes to our main application only to replace the _uninstaller.exe_. I thought about to create an addon installer do nothing but to install a new uninstaller executable. Is this possible?
Thanks in advance. | The executable `uninstaller.exe` does not contain your uninstaller logic. All screens and actions are contained in the file `.install4j/i4jparams.conf`. You can replace that file with an add-on installer. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "install4j"
} |
How to properly terminate or throw from index.php
In index.php of a Zend Framework app. I check for the existence of application.ini and local.ini. If these don't exist then I want to exit and put a message in a place where it can be seen such as syslog. In the context of PHP and ZF1 what is a good approach? If I throw then that will cause an exit but I'm not sure that it would be logged anywhere. | You could try wrapping your application execution in a `try {} catch {}` block:
try {
$application->bootstrap()->run();
} catch (\Exception $e) {
error_log($e->getMessage(), $e->getCode());
throw $e;
}
This way you'll catch all exceptions, log them to your PHP error log and still see the exception being thrown.
As you can see it uses PHP's error_log function.
If you want to write the message to syslog just replace the `error_log` line with
syslog(LOG_ERR, $e->getMessage());
You can also call `$e->getTraceAsString()` if you want to log the whole stack trace. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, exception, zend framework"
} |
Why did my import fail in Java?
I hava a `StdDraw.java` under the same folder of my working file, and `picture()` is a method within `StdDraw.java`.
However, I failed adding this line to import the method, suggesting by
> package StdDraw does not exist
import StdDraw.picture
How could I possibly do that? Using package? Setting path? Or any modifications? I came from python and find it a little bit weird. | You can't import non-static methods (only classes and static members), and you don't have to!
If both your classes live in the default package then you should be able to do the following without any import statements :
myStdDrawObject.picture(); // if picture is non-static
or
StdDraw.picture(); // if picture is static
Note also, that you can't use static imports on classes that live in the default package. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "java"
} |
Array of UIViews
is there a way to create an array of UIViews?
I've tried bot I can't add an values
var views = UIView?
This results in nil
views[0]?.backgroundColor = UIColor.redColor()
I also tried
var views = NSMutableArray()
for (var a = 0; a<100; a++){
views[a] = UIView()
}
views[0].backgroundColor = UIColor.redColor() // fails | In this line:
var views = UIView?
you are creating an array of optionals, filled in with `nil` \- that is what you set with the `repeatedValue` parameter. The correct way would be:
var views = UIView)
Note however that it creates one `UIView` instance only, and assigns it to all 64 elements. Also, unless there's a specific reason, I don't think you need an array of optionals, so should consider using `[UIView]`
That said, if you want an array of unique instances, you can use this code:
var views = [UIView]()
for _ in 1...100 {
views.append(UIView())
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 5,
"tags": "ios, cocoa touch, swift, uikit"
} |
Are deli cut meats bad for a 15-month-old?
We've been feeding our 15-month-old deli ham for dinner pretty regularly. Recently, a family member was alarmed that we were feeding him any kind of deli meat because it is "bad for them". We typically get Prima Della Black Forrest Ham or Oven Roasted Chicken.
As usual, the collective wisdom of Google muddies the water, so I'm wondering if deli meats are a big no-no?
If so, can somebody point us to a realistic meal plan? | Your family member may be confusing the advice to avoid all deli meat for pregnant mothers.
Deli meats and other precooked meats put pregnant women at a high risk for listeriosis and are advised to avoid them unless cooked to steaming hot.
Once a child is transitioned to solid foods, the only main concerns are common allergens (seafood, tree nuts, etc.), and, of course, healthy food habits. There's nothing wrong with deli meats beyond the normal high-sodium/high-fat factors that impact any adult's consumption. | stackexchange-parenting | {
"answer_score": 10,
"question_score": 10,
"tags": "toddler, health, food"
} |
Integration with $\sin(t)$ as the variable.
I am currently working on a question about Calculus on Manifolds and ran into an integral that I'm confused about. How would you evaluate:
$$\int_0^{2\pi}\cos(t) d\sin(t)$$
The answer is $\pi$, by simplifying the above to: $$\frac{1}{2}\cdot \int_0^{2\pi}dt$$ I tried using u-sub but I think I'm missing something here. Am I supposed to use the identity $\sin(2x) = 2\sin x\cos x$? | This is the Riemann-Stieltjes integral, a generalization of the Riemann integral. Since $\sin(t)$ is everywhere continuously differentiable, we have that the integral is equivalent to
$$\int_{0}^{2\pi}\cos(t)\left(\frac{d}{dt}\sin(t)\right)\,dt=\int_{0}^{2\pi}{\big(\cos(t)\big)}^2\,dt$$
Do you think you can take it from here? | stackexchange-math | {
"answer_score": 4,
"question_score": 0,
"tags": "integration, differential geometry"
} |
How to prevent VSC from adding "require"?
While editing some JS files, VSC systematically adds "`require()`" calls, which I have to remove as quickly
How to prevent VSC from adding theses lines with "`require`"?
Thanks Didier | You can create a `jsconfig.json` file inside your project and set `"javascript.suggest.autoImports"` to `false` as documented here to disable auto-import IntelliSense in your code-base.
You can alternatively disable it globally by going to VSC settings (`Ctrl + ,`), search for "javascript auto import" and disable there. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, visual studio code"
} |
how to insert <?php echo $image;?> in <img src=""> tag
i'm trying to modify my PHP code so that i can insert html tag just inside it.the original code was:
<?php
if( $image ){
?>
<a class="product_image image-woo" href="<?php echo $product_url;?>">
<?php echo $image;?>
</a>
<?php } ?>
now,i,ve edited in this way:
<?php
if( $image ){
?>
<img data-src="<?php echo $image;?>" class="something">
<?php } ?>
What,s wrong about? | try this
if($image) {
$doc = new DOMDocument();
$doc->loadHTML($image);
$imgs = $doc->getElementsByTagName('img');
foreach ($imgs as $img) { ?>
<img data-src="<?php echo $img->getAttribute("src");?>" class="something"/>
<?php }
} ?> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, image, echo"
} |
How to avoid unrelated data from postgresql search
I want to get the data to contain keyword of both "LED" and "car"
select count ( * ) from test_eu where eng_discription ~ '.* led .* AND .* car .*';
When I search PostgreSQL with the above code, results include those unrelated data like
so-cal **led** **car** dboard
**car** efully instal **led**
In order to avoid this, I thought both sides of the searching keyword contain space " " solve this problem.
regex of space is
\s
so I made this code
select count ( * ) from test_eu where eng_discription ~ '\sled\s and \scar\s';
but still does not work. How should I modify my code? | Assuming you want to check for the presence of both `LED` and `car`, anywhere in the description column, you could try:
SELECT COUNT(*) AS cnt
FROM test_eu
WHERE eng_discription ~* '\yled\y' AND eng_discription ~* '\ycar\y'; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "regex, postgresql"
} |
apt update gives errors
When I run the command `sudo apt update`, I get the following errors:
W: GPG error: Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8873E7BF70F1BBEA
W: Failed to fetch 404 Not Found [IP: 154.53.224.162 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.
I am running Ubuntu 14.04 and use `lubuntu-desktop`.
How can I fix this? | ### Taking a look around
It doesn't look like your sources.list contains `
You will need to check the files within `/etc/apt/sources.list.d/` and find the problematic file containing this repo. After you delete the file, or comment out the line, try `sudo apt-get update` to see if you've fixed the problem.
### Note
If you wish to use mega.nz as a repository for `MEGAsync`, you will need to find the updated/correct URL, as well as determine and import the signer's public key (`apt-key`). Please read up on `apt` and how it uses public/private keys before importing keys without understanding the consequences. | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "14.04, apt, updates, lubuntu"
} |
Set TabItem header as TextBlock in XAML
Right now I have something like this:
<TabItem Name="tbActive" Width="100" Height="100" Header="Current" >
and in the code behind I set the Header -- so setting it above is a bit pointless
TextBlock tb = new TextBlock();
tb.Text = "Current";
tb.MouseDown += new MouseButtonEventHandler(tb_MouseDown);
tbActive.Header = tb;
I don't want to use this code behind... I'd rather it all be XAML. So how can I set the 4 textblock lines in my TabItem XAML ? | <TabItem Name="tbActive" Width="100" Height="100">
<TabItem.Header>
<TextBlock Text="Current"
MouseDown="tb_MouseDown"/>
</TabItem.Header>
</TabItem> | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "c#, wpf, xaml"
} |
RFC 5246 TLS 1.2: padding example mistake?
From RFC 5246, page 22:
Example: If the block length is 8 bytes, the content length
(TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes,
then the length before padding is 82 bytes (this does not include the
IV. Thus, the padding length modulo 8 must be equal to 6 in order to
make the total length an even multiple of 8 bytes (the block length).
The padding length can be 6, 14, 22, and so on, through 254. If the
padding length were the minimum necessary, 6, the padding would be 6
bytes, each containing the value 6. Thus, the last 8 octets of the
GenericBlockCipher before block encryption would be xx 06 06 06 06 06
06 06, where xx is the last octet of the MAC.
So, `61+20=82`, last 8 octets contains seven `06`? Did I misunderstand something? Or such important document contains mistake? | The document is correct, `xx` is the last octet of the MAC, followed by six times the `06` octet as padding, followed by the length octet (`06`). The last length octet is not part of the padding.
See the definition of GenericBlockCipher in section 6.2.3.2 of RFC 5246:
struct {
opaque IV[SecurityParameters.record_iv_length];
block-ciphered struct {
opaque content[TLSCompressed.length];
opaque MAC[SecurityParameters.mac_length];
uint8 padding[GenericBlockCipher.padding_length];
uint8 padding_length;
};
} GenericBlockCipher; | stackexchange-security | {
"answer_score": 3,
"question_score": 1,
"tags": "tls"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.