INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
grep + changing values in vector in R
I have a two-variable data frame `data` containing `VariableA` & `VariableB`. Both columns are of the character class. What I would like to do is grep Variable A for elements with capital letters. Then, with the rows containing those elements I would like to change the Foos in Column B with "Yes". The `grep` part works fine:
data <- data.frame(VariableA = c("A","a","B","b","C","c","D","d"),VariableB= c("Foo", "Foo","Foo", "Foo","Foo","Foo","Foo","Foo"))
grep("[A-Z]", data$VariableA)
This returns an integer string containing all of the row numbers where there are capital letters. Is there a way to then change the values of `VariableB` only for those with capital letters in a single call? Without subsetting and merging a bunch of times? | [Edited to use code provided in the question]
Here's how I would do it. This changes the values in column B and rows where A contains a capital letter.
# Create data frame, keep strings as strings
data <- data.frame(VariableA = c("A","a","B","b","C","c","D","d"),VariableB= c("Foo", "Foo","Foo", "Foo","Foo","Foo","Foo","Foo"), stringsAsFactors=FALSE)
# A single call to change column B when column A contains a capital letter
data[grep("[A-Z]", data$VariableA), "VariableB"] <- "newFoo" | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "r, regex"
} |
Why do I get "incompatible error" while opening .sh files using vi in cygwin?
I am very much annoyed by this error:
$ vi abc.sh
Error detected while processing /home/DELL/.virc:
line 1:
E518: Unknown option: incompatible
Press ENTER or type command to continue
/bin/bash: line 2: \: command not found
I don't know, how it is affecting my programs and how this error occurred in my laptop?
I tried reinstalling the package, too. | The option name is `nocompatible`. Replace `incompatible` with `nocompatible` to solve your problem. | stackexchange-vi | {
"answer_score": 4,
"question_score": 1,
"tags": "bash, error"
} |
how to display images in for loop php?
i had 5 images **path** and **name** in mysql database.
now i want to display that in a slider in for loop
include ('conn.php');
$select_path="select * from image_table";
$var=mysqli_query($conn,$select_path);
while($row=mysqli_fetch_array($var))
{
$image_name=$row["name"];
$image_path=$row["path"];
$url=$image_path.$image_name;
}
echo' <div id="ninja-slider">
<div class="slider-inner">
<ul>';
for($i=0;$i < $url;$i++){
echo'<li>';
echo' <a class="ns-img" href="'.$url[$i].'"></a>
<div class="caption">image 1</div>
</li>';}
</ul>
<div class="fs-icon" title="Expand/Close"></div>
</div>
</div>
for loop can display a list from database? | This is not a good habit to loop multiple times unnecessary. We should avoid unnecessary loops in our programs.
include ('conn.php');
$select_path="select * from image_table";
$var=mysqli_query($conn,$select_path);
if(mysql_num_rows($var) > 0){
echo' <div id="ninja-slider"><div class="slider-inner"><ul>';
while($row=mysqli_fetch_array($var))
{
$image_name=$row["name"];
$image_path=$row["path"];
$url=$image_path.$image_name;
echo '<li>';
echo '<a class="ns-img" href="'.$url.'"><img src="'.$url.'" /></a>';
echo '<div class="caption">image 1</div></li>';
}
echo '</ul><div class="fs-icon" title="Expand/Close"></div></div></div>';
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, html, mysql"
} |
iframe downloads the html source instead of displaying it
I am trying to embed an html file in a page.
I use the following code:
<iframe src="{{resource.previewUrl}}" allowfullscreen webkitallowfullscreen mozallowfullscreen height="700" width="100%" frameborder="0" marginheight="0" marginwidth="0" ></iframe>
The source I get through angular is the address to the index.html file which is in Azure blob storage:
_sc.resource.previewUrl = $sce.trustAsResourceUrl("
When I open the page, it downloads the index.html file to my computer instead of displaying it. How can I force it to display? | The problem is because of the content-type property of the blob. If content-type property of a blob is not set explicitly, Azure Blob storage assigns `application/octet-stream`.
In your case because you're not setting this property, even for your HTML files, the content type is set as default value i.e. `application/octet-stream`. Because the browser (especially Chrome) does not understand how to deal with this content type, it downloads it instead of rendering it.
Changing the content type of the blob to `text/html` should fix the problem. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 9,
"tags": "html, angularjs, azure, iframe, azure blob storage"
} |
Vertica include column names in output, but not row count footer
I am running some Vertica SQL queries from the command line and saving them to CSVs.
I want to keep column names, so I do not use the -t option. The problem is that I now am also left with the footer which gives the row count (e.g. (20 rows). I know that I could remove this footer in a separate command (as it will always be in the last row), but I was wondering if there is a more elegant solution.
I have been looking at the documentation here:
< | Use `\pset footer off`.
More info on the metacommand is available at the documentation.
Example:
dbadmin=> select count(*) from sessions;
count
-------
5
(1 row)
dbadmin=> \pset footer off
Default footer is off.
dbadmin=> select count(*) from sessions;
count
-------
5 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "vertica, vsql"
} |
Move BC before/after reformatting
I plan on reformatting my main drive. I did this once before and of course lost access to my Bitcoin Core wallet and the Bitcoins therein.
Does anybody know how I can go about transferring my Bitcoins before or after I reformat my drive?
Can I just copy and paste the Bitcoin Core folder to my second drive before formatting, and then transfer it back afterwards? | You can just copy your `wallet.dat` from your local wallet directory. If using windows it will be in `%appdata%/Bitcoin`. After reformatting download a fresh copy of Bitcoin Core and replace the wallet.dat with the one you saved prior to reformatting.
There's also the method of using the `backupwallet` and `importwallet` commands. < | stackexchange-bitcoin | {
"answer_score": 1,
"question_score": 1,
"tags": "backup, installation"
} |
Как выводить числа, которые выводятся в экспоненциальной записи, в нормальном (десятичном) виде?
Почему так числа отображаются: `7e-06 3e-06 4e-06`?
Как сделать вывод привычным, чтобы было удобней читать?
Если с большими значениями: `0.7 0.3 0.4,0.07 0.03 0.04, 0.0007 0.0003 0.0004`, то всё нормально, но со стотысячными долями: `7e-06 3e-06 4e-06`.
a = 0.000003
b = 0.000004
c = a + b
if a < b:
print(c, a, b)
else:
print(a) | Воспользуйтесь форматированием строк. Еще удобнее воспользоваться `f-string`, который стал доступен начиная с Python 3.6.
исходный вариант - форматирование по умолчанию:
In [52]: print(a, b, c)
3e-06 4e-06 7e-06
используем форматирование строк:
In [54]: print("{:.8f}, {:.8f}, {:.8f}".format(a,b,c))
0.00000300, 0.00000400, 0.00000700
используем `f-string` форматирование (обратите внимание на букву `f` перед началом строкового литерала: `f"<string_literal>"`):
In [53]: print(f"{a:.8f}, {b:.8f}, {c:.8f}")
0.00000300, 0.00000400, 0.00000700 | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "python, python 3.x, форматирование"
} |
Performance of Output redirection vs fprintf from within program
I was wondering if there was any benefit/detriment to using output redirection on unix, compared to calling fprintf(file, ...);
edit: to further clarify. I'm writing a program that will need to do a data dump to disk: 50000+ lines by 40 characters of data.
The program itself takes up a significant amount of memory as it is, and I need to know whether or not allocating a buffer inside the program will incur a bigger memory penalty than using a unix output redirect.
I have noticed that the difference in output time is within margin of error. Both are very efficient and the only difference is that I need to write extra code for writing to a file without unix redirects.
However, most of my attempts at benchmarking have run up against the same issue: they don't show how much memory is allocated for the buffered output if I use output redirection. | If there is any difference, it would stem from whether a chosen file descriptor is buffered or not. `stderr` is often unbuffered, `stdout` is buffered, so if you use output redirection for the latter, you might be able to notice a tiny, possibly but unlikely statistically significant speedup compared to writing to `stderr`.
The underlying mechanism for writes is the same in both cases, it is the initialization phase (opening and assigning file descriptors) that will be different, but it is only performed once. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "c, unix"
} |
How to revert the Draggable compoent's position when drag stops using React
I have a `Draggable` component with a container in it. I want the position of the `Draggable` to reset when the dragging is stopped (`onStop`). This is my `Draggable`'s properties:
<Draggable
axis="x"
bounds={{top: 0, bottom: 0, left: -75, right: 0}}
onStop={//what to do here}
>
How can I do that? | So, I researched and you can just use `position={{x: 0, y: 0}}` to make it work. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, reactjs, draggable"
} |
Cannot get Clarity Cards to appear in single row
I am able to add a card however when I try and add multiple cards in a row they stack below each other. The documentation is not clear what other steps are required to make these appear on the same row. I am happy to manually do this with blocking, set width and height etc however my understanding was this would be dynamic, am I misunderstanding the template or doing something stupid?
<div class="row">
<ng-template ngFor let-tile [ngForOf]="tiles" let-i="index"
[ngForTrackBy]="trackByFn">
<div class="col-lg-4 col-md-12 col-sm-12 col-xs-12">
<a href={{tile.url}} class="card clickable">
<div class="card-img">
<img src={{tile.icon}} alt="..." height="42" width="42"/>
</div>
<div class="card-block">
<p class="card-text">
{{tile.text}}
</p>
</div>
</a>
</div>
</ng-template>
</div> | The old grid was deprecated as part of Clarity's 1.0 release:
> Deprecation of old grid (#2757)
>
> Clarity has had deprecated the old grid already, but has actually removed it from the main @clr/ui bundles. If you are still using the old grid (which includes the old unprefixed .row and .col classes), we have provided a temporary file you can include until you fully migrate to the new grid classes. To do this, add @clr/ui/clr-grid-deprecated.css to your project.
So you can either import this CSS file to still use the deprecated classes, or move the the new grid: < The difference with the new gird is pretty much just prefixing the various classes with `clr-`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "vmware clarity"
} |
How can I diff a tree and a remote branch in git?
I need to diff two objects in git. One is a tree (directory) in my working directory, and the other one is a remote branch. I can do so if I find the SHA of the tree and use that in the argument of my git diff command along with the remote branch. However, I am trying to find a way not to have to dig in the SHA first.
So, for example, if:
My_Working_Dir
file1
file2
Dir1
file3
file4
remote_branch/master
file3
file4
Then I like to be able to issue something like this:
git diff Dir1 remote_branch/master
This works if I replace Dir1 with its SHA, but not if I just try to use the directory name. I have tried to use diff-tree as well. But that is not helping either. Please note that the remote_branch/master does not have the Dir1 directory.
Any help is appreciated.
Thanks in advance. | You can use `<branch>:<file_path>` notation with `git diff`
`git diff remote_branch/master:file3 HEAD:Dir1/file3`
`git diff remote_branch/master:file4 HEAD:Dir1/file4` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "git, git diff, git diff tree"
} |
How to combine winner and workgroups?
I use many workgroups in my workflow (package `workgroups` or `workgroups2`). If I switch to some workgroup and try to `winner-undo` I get window configuration from previous workgroup. Can I use separate `winner-undo` history for each workgroup?
!My workgroups | I've just pushed a commit in workgroups2.
Now `winner-undo`, `winner-redo` commands are remapped to workgroups' commands which do the same thing as `winner` but for each workgroup. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "emacs, window, workflow"
} |
How to convert Capture to Image<Bgr,Byte> using Emgu library
I am struggling to covert Capture into Image using Emgu libraries in C#. I know that there are examples of code on Emgu website, but these don't involve camera capture. I want to get some processing done to the frames from camera.
This is what I have so far:
Capture capture = null;
capture = new Capture(); //create a camera capture
capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.Fps, 30);
capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight, 240);
capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth, 320);
viewer.Image = capture.QueryFrame()
viewer.ShowDialog();
I would like to be able to use capture in the following line:
Image<Gray, Byte> gray = capture.Convert<Gray, Byte>().PyrDown().PyrUp();
Thank you | I think if you have a Mat and you want an Image you could do the following:
Image<Bgr, Byte> img = new Image<Bgr, Byte>(theMat.Bitmap);
Doug | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, image processing, emgucv"
} |
Посоветуйте азиатские маркеты для андройд приложения?
Я насколько знаю у китайцев нет дуступа к Google Play. | Основных маркета три(в порядке популярности):
1. (Myapp) от Tencent
2. 360(360 Mobile Assistant) от "Qihu 360"
3. (Baidu Mobile Assistant) от Baidu
Ориентироватся нужно прежде всего на них. Остальные маркеты используются на довольно малом количестве устройств и/или завязаны на производителя(как например Huawei App Store). | stackexchange-ru_stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "android"
} |
React test state change after timeout
say I have a Card element that flips when clicked upon. After 2 seconds, it must automatically flip back. In CSS terms, after clicking, the transform style is set to **rotateY(180deg)** , after 2 seconds it should becom **Initial**
I want to write unit tests for this back-flip (currently the test passes even though I expect the transform prop to equal initial):
it( 'flips', () => {
const testedCard = shallow( <Card /> )
testedCard.setState( { faceUp: true } )
setTimeout(
() => {
const cardFlipper = testedCard.node.props.children
expect( cardFlipper.props.transform ).to.equal( 'initdasddaial' )
},
2500
);
} ) | If you are using `mocha` or `jasmine`, you can pass a `done` callback in the `it`:
it( 'flips', (done) => {
const testedCard = shallow( <Card /> )
testedCard.setState( { faceUp: true } )
setTimeout(
() => {
const cardFlipper = testedCard.node.props.children
expect( cardFlipper.props.transform ).to.equal( 'initdasddaial' )
done();
},
2500
);
} )
However, depending on your test runner (settings), the `done` timeout might occur _before_ 2500 mills. You might have to configure a different timeout value.
As a side note, unit tests based on timing are not usually a good idea. Consider designing the component so that you can test more deterministically. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "reactjs, settimeout"
} |
Fastener on 2017 VW Jetta won’t screw back in after replacing light bulbs
I have a fastener that is screwed into the taillight for my 2017 Jetta. I successfully replaced a bulb but the screw won’t screw back in.
I confirmed it’s an issue with the screw as another screw from the other tail light was able to be screwed in. Anyone have any ideas of how to fix it short of replacing the part?
pic of fastener
` and have all my meta values stored in a `$variable`, or is it better to get each individually?
I would assume it is the former, but wanted to get some feedback. | Assuming you're retrieving the posts using a standard WP_Query in some manner, then the postmeta data is automatically retrieved for all the relevant posts and cached in memory. When you later call `get_post_meta`, the data is simply returned from here.
So honestly, it doesn't make any significant difference which approach you take. The `get_post_meta` function isn't making database calls unless the data isn't in memory already.
If you're making a WP_Query and have no need to cache the postmeta info, you can set the `update_post_meta_cache` argument in the query to false. Similarly, you can set the `update_post_term_cache` to false to prevent it from caching relevant terms from the taxonomy system as well. These can speed up a query for specific cases where you know that you don't need the meta/terms in advance. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post meta"
} |
Triple Integral in Spherical Coordinates.
$\newcommand{\de}{\operatorname{d}}$A little stuck on this one.
$$\iiint_V ye^{-(x^2+y^2+z^2)^2}\,{\rm d} V$$ Use Spherical Coordinates to evaluate where V is the solid that lies between y=0 and the hemisphere $x^2+y^2+z^2=1$ in the right half space $(y>0)$.
So my bounds will be $0\le r\le1$, $0\le \theta\le\pi$, $0\le \phi\le\pi$.
The integral will become $$\int_0^1\int_0^\pi\int_0^\pi y\,e^{-(r^2)^2}r^2\sin(\phi)\,{\rm d} \phi \,{\rm d} \theta \,{\rm d} r$$
I'm not too sure how to solve it out from this point :(
In advance, thanks for your help! | As has been commented, you need to substitute $y=r\sin(\theta)\sin(\phi)$ into your final equation. You will then have
$$\int_0^1\int_0^\pi\int_0^\pi r^3\sin(\theta)\sin^2(\phi)e^{-r^4}d\phi\;d\theta\;dr=\int_0^1r^3e^{-r^4}dr\int_0^\pi\sin(\theta)d\theta\int_0^\pi\sin^2(\phi)d\phi$$ which can be easily integrated, realising that $\sin^2(\phi)=\frac12(1-\cos(2x))$. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "integration, multivariable calculus, spherical coordinates"
} |
Как отсылать "multipart/form-data" через python с помощью requests?
Запрос формируется подобным образом:
-----------------------------40338331074230303145107977467
Content-Disposition: form-data; name="name"
что-то
-----------------------------40338331074230303145107977467
Content-Disposition: form-data; name="token"
-----------------------------40338331074230303145107977467--
Как можно отослать такой запрос? | Формы “multipart/form-data” отправляются в параметре `files`. В вашем случае:
requests.post(
'
files=(
('name', (None, 'что-то')),
('token', (None, '')),
)
) | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, requests"
} |
Find a String but return the previous String
I'm trying to find a String in a Textfile. I'm using the RegEx Method for that. But I need to get the Previous String, which is existing before the found String, as Method Output. How can i do it with c#? Can anyone give me some Idea?
For Example:
In that Textfile is a Line with `'routerbl router0000;'`
I'm searching `'router0000;'` and if i find `'router0000;'` then i want to get `'routerbl'`. | You have two possibilities
1. Match what you want using a capturing group, something like this
(\S+)\s+router0000
and you will find your result in the capturing group 1
2. Match your pattern and ensure the following string with a lookahead
\S+(?=\s+router0000)
this will match only the part you want. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "c#, regex"
} |
Functions pointers
Hey guys I have a question: How can i call a function from an enum structure with pointers?
For example I have this structure:
typedef enum struct_e
{
FUNCTION_ONE,
FUNCTION_TWO,
FUNCTION_THREE,
FUNCTION_FOUR,
} sctruct_t;
And I have a function that receives one of these variables and the parameters of the function (for example an int)
void call_functions(struct_t action, int exemple) {...}
// -> call like this call_functions(FUNCTION_ONE, 45);
And in that function I have to call one of the functions like this one:
void function_one(int a)
{
printf("You have %d years old", a);
} | Assuming each of the functions to call has type `void (*)(int)`, you can create an array of function pointers, using the enum values as the array index:
typedef void (*call_func_type)(int);
call_func_type func_list[] = {
[FUNCTION_ONE] = function_one,
[FUNCTION_TWO] = function_two,
[FUNCTION_THREE] = function_three,
[FUNCTION_FOUR] = function_four
}
Then `call_functions` would just index into that array:
void call_functions(struct_t action, int example)
{
func_listaction;
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "c, pointers, structure"
} |
How to create a loop and stop it if condition is met?
I have a function that posts a message to the parent component after 1 second.
setTimeout(function(){
var widgetHeight = getDocHeight();
parent.postMessage(widgetHeight, hostURL);
}, 1000)
I want to refactor this so that I create a loop that checks the `widgetHeight` every 1/10th second and if it changed than post the message to the parent and stop the loop.
How can I do this? | Use an interval to create a repeatable timer.
let timer
let prevWidgetHeight = getDocHeight(); //Get initial height
timer = setInterval(function(){
let widgetHeight = getDocHeight(); //Get the current height
//Compare new height to previous height:
if(widgetHeight !== prevWidgetHeight) { //If the current height is not the same as the initial height,
prevWidgetHeight = widgetHeight
parent.postMessage(widgetHeight, hostURL); //Make the update
clearInterval(timer) //Stop the timer
}
}, 100) //100ms is 1/10th of second
This stops the loop once the height differs from the height set before starting the loop. Stopping it means new changes won't be passed on though. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, loops"
} |
What is this query language called
As I understand Apache Lucene and Google (GSA or GCS) are completely different search engines / frameworks and their parsers have varying logic but their query languages seem extremely similar, or the same. If they are the same what is this query language called? If not the same what is each called/what are the differences?
example:
field1:foo "some text"
and the item existed in the dataset
{
"field1": "foo",
"somefield": "bla bal some text"
}
would be in the result | You might call it "search syntax", it's kindof a mashup of the old days of information retrieval research (80s and 90s) and what the suddenly dominant web search engines settled on in the late 90s.
Modern customer-oriented search engines match all the words in the query in all fields, although some allow partial matches. Most allow ways to override the default behavior using query syntax such as Boolean operators like AND (sometimes "+"), OR (sometimes "||") and NOT (sometimes "_"), quote marks to indicate phrase search matches, and field filters like "department:".
After all that, it occurs to me that you may come from a database background, and be asking about why the result doesn't exactly match the query. If that's the case, it's because the search engine has an inverted index that can match parts of fields, and then sort results by a relevance algorithm, usually TF IDF. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "lucene, google search, google query language"
} |
Buffer Solution - Sodium Benzoate
> A buffer with a pH of $\mathrm{4.79}$ contains $\mathrm{ 0.39\ M}$ of sodium benzoate and $\mathrm{0.10\ M}$ of benzoic acid. What is the concentration of $\mathrm{[\ce{H} ]}$ in the solution after the addition of $\mathrm{0.058\ mol}$ of $\ce{HCl}$ to a final volume of $\mathrm{1.6\ L}$?
My thought is that $$\mathrm{pH=pK_a+Log_{10}(\frac{[base]}{[acid]})}$$
When we added $\mathrm{0.058\ mol}$ of $\ce{HCl}$, the concentration of both acid and base decreased by $\frac{.058}{1.6}$, so I take that ratio and apply it. I found $\mathrm{pK_a}$ by just applying what's given. Not sure where I am going wrong. | In that equation, the acid and base are a conjugate acid/base pair. We assume HCl quantitatively dissociates and protonates benzoates. The concentration of the acid increases, and the base decreases.
Empirically, the pH should go down in this case. Without seeing your specific calculation, we can't comment where you are going wrong, but the proper flow should look something like:
$$\mathrm{pH=pK_a+Log_{10}(\frac{[base]-[Added H]}{[acid]+[AddedH]})}$$
$$\mathrm{pH=pK_a+Log_{10}(\frac{0.39M - 0.036M}{0.10M + 0.036M})}$$
$$\mathrm{pH=pK_a+Log_{10}(\frac{0.354M}{0.136M})}$$ From your calculated $\mathrm{pKa = 4.20}$, you should get there pretty quickly.
Just applying the difference in the log values of the changed ratios, I get $\mathrm{pH = 4.61}$ | stackexchange-chemistry | {
"answer_score": 4,
"question_score": 2,
"tags": "acid base, analytical chemistry"
} |
CSS image background position
This is my problem:
<
I need the background image (with url) to be placed at the top left position of the image, and want the text to be moved next to the background image.
As you've probably noticed I'm using two backgrounds, so its probably not possible to use just one div, right?
Have you guys any solutions for that? | I don't know if this is exactly what you are looking for, but you can have 2 background elements at the same time, as long as they don't conflict each other. < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "css, background"
} |
Check if liferay community is active or not
I need check if the community is active or not through code. I am using Liferay 6.0.6 CE.
When I fetch myPlaces using `List<Group> myPlaces = user.getMyPlaces(max);` I get all the not active communities in the list as well which I don't want. I want only the active communities to be returned in the List. | Sometimes it is necessary to program a little bit self :)
List<Group> myActivePlaces = new ArrayList<Group>();
List<Group> myPlaces = user.getMySites();
for (Group group : myPlaces) {
if(group.isActive()){
myActivePlaces.add(group);
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, liferay, liferay 6"
} |
Декодирование кириллицы из json
Вместо кириллических символов получаю `\u4430\u0446`. Библиотеки типа Json.NET не подключаются к моей CRM системе. Так что нужно как-то стандартными декодерами это сделать. Как декодировать стандартными средствами C#?
Вот пример кода:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
request.Method = "GET";
request.Accept = "application/json";
WebResponse resp = request.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader rdr = new StreamReader(stream);
string str = rdr.ReadToEnd();
Console.WriteLine(str);
Спасибо за ответы! | System.Text.RegularExpressions.Regex.Unescape("\u4430\u0446"); | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "c#, json, перекодировка"
} |
-[_NSZeroData JMbase64EncodedString]: unrecognized selector sent to instance
When using `JumioCore.framework` I get this error when try to call a method which is in a extension:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_NSZeroData JMbase64EncodedString]: unrecognized selector sent to instance 0x7fd709fa3aa0'
Example call that cause the exception:
NSData *data = [NSData data];
NSString *answer = [data JMbase64EncodedString];
why is this happening? What am I missing? This is the Jumio webpage: < | So, this answer is very simple but it was hard to find because `JumioSDK` doesn't explain that in its guide to install the SDK.
What you need to avoid those errors is include certain frameworks after start working. This is the list of the frameworks to be added:
* libz
* libiconv
* libc++
* MobileCoreServices
* Accelerate
* System configuration
also remember to add `-ObjC` in `another linker flags`
Let me know if someone have some problem. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, objective c, cocoapods"
} |
Can I temporarily cap off a PVC drain line without solvent (during a reno)?
I'm doing a bathroom reno and will be removing the bathtub and shower, and they will be out for quite some time. Because of this, I want to cap off the 1.5" and 2" PVC drain pipes (rather than stuff a towel in them or something similar). Can I simply put a PVC cap on without any solvent, or will that leak sewer gasses? | Yes. DWV pipe caps fit quite snugly, without glue, and will not pass any detectable amount of vent gases. You had better be sure that those drain lines will never be subject to filling with waste water, condensation, etc. If you're planning to glue-up some new drain/vent piping as part of your project, you'll be needing something like expansion plugs to properly water-test your work, and those will work excellent as temporary pipe plugs. | stackexchange-diy | {
"answer_score": 21,
"question_score": 9,
"tags": "plumbing, drain, pvc"
} |
Reading StdOut Asynch from a c console app
I have a console based c app . I am executing it from c# silently using Redirecting Standard Output and doing it synchronously which works fine. Now i want to do it in asynch manner which is giving output like synch manner. i.e OutPutDataRecieved event is fired but only after the console app(exe) finishes.OutputDataRecieved event is fired for each line after finish, not instantly as soon as it gets a line in output.
The code for asynch works for CMD.exe etc ,So,I am sure its c based app having problem in output. FYI:The output in c console is done using printf. Based on my findings: I think c console app is not giving output/writing to stdout until it finishes its execution. I tried setting buffer to null or flushing after every printf but none works.
Any tricks?? | You can disable the buffering using setvbuf.
Here is a quick example, if you remove the call to `setvbuf` then the redirected content is only written once you press enter (waiting on the getchar()). With the `setvbuf`, the string is written to the redirected stream directly.
int _tmain(int argc, _TCHAR* argv[])
{
setvbuf(stdout, NULL,_IONBF, 0);
printf("Hello");
getchar();
return 0;
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, c, process, console, asynchronous"
} |
In Perl, how can I use the regex substitution operator to replace non-ASCII characters in a substring?
How to use this command:
perl -pi -e 's/[^[:ascii:]]/#/g' file
to change only characters at offset A to offset B of each line? | Alternatively to rubber boots' answer, you can operate on a substring instead of the whole string to begin with:
perl -pi -e 'substr($_, 5, 5) =~ s/[^[:ascii:]]/#/g' file
To illustrate:
perl -e 'print "\xff" x 16' | \
perl -p -e 'substr($_, 5, 5) =~ s/[^[:ascii:]]/#/g' | \
hd
will print
ff ff ff ff ff 23 23 23 23 23 ff ff ff ff ff ff
In this code, the first offset is 0-based, and you have to use the length instead of the second offset, so it will be `substr($_, A-1, B-A)`. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 2,
"tags": "regex, perl"
} |
autoref: Short and long label
I understand that it's possible to have \autoref generate references like Theorem 12, or Thm. 12, etc. where the label is always the same. Is there any way to have a short and long version of autoref? Sometimes I'll be referencing a theorem in equations, and I don't want Proposition 12 or something, but an abbreviation. In the main text, I will always want the long form. Is there a pain-free way of doing this? | Instead of using `\autoref`, I suggest you also load the `cleveref` package and then assign the abbreviated labels to `\cref` (via a `\crefname` directive) and the non-abbreviated labels to `\Cref` (via a `\Crefname` directive).
 menu for his restaurant in internet; he also manages his dayly and weekly specials with a small application via internet, entering only name of food (description) and price. Now he wants to print his pages to a (paper) menu card. but how he (I) tried, the printout is always poor, because the html page was not designed for printing. Graphics (eg. backgrounds) are not printed, shifted, on one extra page and so on.
So my idea was to get the page as graphic and print it - after small corrections - via a graphics programm.
Is that possible, or are there ways to control printout better, than the stadard printig engines of browsers?
He wants a WYSIWYG and not "what you get is what the browser thinks you want to see"
other ideas are welcome | Have you tried wkhtmltoimage ? < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html, printing, converters"
} |
verilog representing binary value problem in verilog
My task is to create a text file and put my first name as binary data in the text file, and then to read this file and convert this binary to characters and put it in another file as characters.
So my question is how do I represent my name in binary.
I tried:
reg [255:0] myname = 01001110011010010110101101101111011011000110111101111010;
But it did not work. The error says the number is too big.
Then I tried:
reg [1:0] myname1 = 2'b0100_1110_0110_1001_0110_1011_0110_1111_0110_1100_0110_1111_0111_1010;
This also did not work. It always gave "_" as an output. | reg [255:0] myname = 01001110011010010110101101101111011011000110111101111010;
In this case you have a huge decimal number `1,001,110,011,010,010,110,101,101,101,111,011,011,000,110,111,101,111,010` which you try to assign to a relatively small reg (256 bit wide). It does fit in 256 bits but you will have big problems decoding it.
reg [1:0] myname1 = 2'b0100_1110_0110_1001_0110_1011_0110_1111_0110_1100_0110_1111_0111_1010;
Here you are trying to squeeze a 56 bit **binary** number into a 2 bit variable. This is physically impossible and the number gets truncated to 2 bits. Underscores are only used for readabilityt purposes and do not have any other effect.
I guess, you need something like the following:
reg [255:0] myname = 256'b01001110011010010110101101101111011011000110111101111010;
You can add underscores for readability if you wish. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "verilog, quartus"
} |
Open binary file from HTML5 offline web application
I'm able to use HTML5 standard File API and IndexedDB to store large binary files in the browser.
However, when offline, I need to be able to open these files. Using data URLs works great for small files, but none of the browsers support 10Mb file opening through data URL. Is there any other solution, except for non-standard window.webkitRequestFileSystem? | I've actually found an answer here: <
It is possible to save result of FileReader.readAsArrayBuffer in IndexedDB. When offline, it is possible to create a blob from this typed array and then create data URL to be passed to window.open function. Works with large files! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, fileapi"
} |
How to test if Scala combinator parser matches a string
I have a Scala combinator parser that handles comma-delimited lists of decimal numbers.
object NumberListParser extends RegexParsers {
def number: Parser[Double] = """\d+(\.\d*)?""".r ^^ (_.toDouble)
def numbers: Parser[List[Double]] = rep1sep(number, ",")
def itMatches(s: String): Boolean = parseAll(numbers, s) match {
case _: Success[_] => true
case _ => false
}
}
The `itMatches` function returns `true` when given a string that matches the pattern. For example:
NumberListParser.itMatches("12.4,3.141") // returns true
NumberListParser.itMatches("bogus") // returns false
Is there a more terse way to do this? I couldn't find one in the documentation, but my function sees a bit verbose, so I wonder if I'm overlooking something. | I guess I should add my comment as an answer, since it is the answer. You can use the `successful` method on `ParseResult`, which is designed for precisely this purpose:
import scala.util.parsing.combinator._
object NumberListParser extends RegexParsers {
def number = """\d+(\.\d*)?""".r ^^ (_.toDouble)
def numbers = rep1sep(number, ",")
def itMatches(s: String): Boolean = parseAll(numbers, s).successful
}
This gives exactly the same behavior as your implementation. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "scala, parser combinators"
} |
HTML Table Question
When you create a basic HTML table everything seems to stay in center of the table. I don't want this how can i stop this from happening?
I wish to use a 2 column html table one for column for a sidebar one for content. Because i have so much content the sidebar text (which is little) gos to the middle of column.
How do i align the text to stay to the top left of the columns? | In the `<td>` element that contains the lefthand sidebar, try specifying a style that aligns text to the top:
`<td style="vertical-align: top">(Sidebar HTML code here)</td>` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "html, html table"
} |
Evaluate $\lfloor n / \lfloor n / \lfloor \sqrt n \rfloor \rfloor \rfloor$ for positive integers $n$.
I'm considering:
$$ \left\lfloor {n \over \lfloor n / \lfloor \sqrt n \rfloor\rfloor} \right\rfloor \:\:\:\: \forall n \in \mathbf N^+ $$
which seems to be $\lfloor \sqrt n \rfloor$.
Is there any way to prove or disprove? | Let $n$ be a real number such that $n\geq 1$, and $m:=\left\lfloor\sqrt{n}\right\rfloor$. Then, we have $$m^2\leq n< (m+1)^2=m^2+2m+1\leq m^2+3m\,.$$ Thus, $$m\leq \frac{n}{m}< m+3\,.$$ Set $k:=\left\lfloor\dfrac{n}{m}\right\rfloor$, so that $k\in\\{m,m+1,m+2\\}$. If $k=m$, then $m^2\leq n<m(m+1)$. That is, $$m\le\frac{n}{k}<m+1\,,\text{ whence }\left\lfloor\frac{n}{k}\right\rfloor=m\,.$$ If $k=m+1$, then $m(m+1)\leq n<m(m+2)$. Thus, $$m\leq \frac{n}{k}<\frac{m(m+2)}{m+1}=\frac{(m+1)^2-1}{m+1}<m+1\,,$$ so $\left\lfloor\dfrac{n}{k}\right\rfloor=m$. If $k=m+2$, then $m(m+2)\leq n<(m+1)^2$. Hence, $$m\leq \frac{n}{k}<m+\frac{1}{m+2}<m+1\,,\text{ making }\left\lfloor\frac{n}{k}\right\rfloor=m\,.$$ In other words, $$\left\lfloor\frac{n}{\left\lfloor\frac{n}{\left\lfloor\sqrt{n}\right\rfloor}\right\rfloor}\right\rfloor=\left\lfloor\sqrt{n}\right\rfloor$$ for all real numbers $n\geq 1$. | stackexchange-math | {
"answer_score": 7,
"question_score": 5,
"tags": "elementary number theory, ceiling and floor functions"
} |
Why is this simple 3 line program not working?
class Pract:
p1 = Pract() #creating an instance of Pract
p1.age=45 #creating a field-variable
print(p1.age)
I checked this Youtube, in the video its shows as working, but I couldn't run it. | # First declare a class (empty, in this case)
class Pract:
pass
# Then instantiate it
p1 = Pract()
# Then set the attribute
p1.age = 45
# Then print the attribute
print(p1.age)
You cannot instantiate a class _before_ you finish declaring it. Everything you put inside `class` is part of the class definition. You have to de-indent your code in order to mark the end of the class definition. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -4,
"tags": "python, python 3.x"
} |
JMeter - Send error message when exceeding a max execution time but do not stop request
I have some HTTP requests in my Test Plan and I would like to analyze which are executed in a certain limit of time and which or not. The PreProcessor _Sample Timeout_ could be useful here, but I also would like to check if the HTTP request itself is working, so I need the request not to be stopped when exceeding the time limit.
The perfect behavior would be that the request is marked in red if it exceeds the timeout, and that we can still see the real time of execution and the request result.
Is there a way to do so? | You need to add Duration Assertion to your request, It'll mark as failure (red) the request, but let the request finish and save its response/ load time
> A Duration Assertion can be used to detect responses that take too long to complete.
For example assertion message:
Assertion failure message: The operation lasted too long: It took 15,111 milliseconds, but should not have lasted longer than 1,000 milliseconds. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "http, jmeter, timeout, jmeter 4.0"
} |
Book recommendations for relearning math from elementary school arithmetic?
I was always branded weak at mathematics back at school though i loved it. The reason was that I lacked basics in maths. Due to this problem I stopped learning maths after my 10th grade. But I always feel that I can do better.
I want to learn maths again, from Addition to Everything. I want to start afresh from techniques of division to multiplication. Is there any comprehensive book that can teach me the basics? | The first thing you need to do is to figure out how much you know. You need to know which level you are at.
I recommend going to someplace like khanacademy and try some of the exercises.
Another thing I like to do is to find something that I want to learn, that at the moment is over my head. Then I figure out, what do I need to know to understand this? Then I can make a list for myself of concepts/techniques I need to learn. | stackexchange-math | {
"answer_score": 4,
"question_score": 7,
"tags": "education, self learning, learning"
} |
How to localize HeaderText in GridView or validation controls?
I cannot figure out why HeaderText or validation controls always fallback to default culture - even though rest of the controls are in correct culture.
I have a GridView with HeaderText specified in this way>
<asp:BoundField DataField="totalSales" HeaderText="<%$ Resources:Strings,TotalSales %>" />
In the same way I have validation controls and they can't be localized.
Only this syntax does work: `<%= Resources.Strings.Payments %>`
I set different culture in Master page using this statement in Page_Init
Me.Page.Culture = "pl-PL"
Me.Page.UICulture = "pl-PL"
Can anyone spot what's wrong? I have been Googling it for last few days without success.
Thanks! | Have you tried to use ExpressionBuilder? That works very well and allows you to localize everything using the same approach. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "asp.net, vb.net, localization"
} |
Fastest way to create this number?
I'm writing a function to extend a number with sign to a wider bit length. This is a very frequently used action in the PowerPC instruction set. This is what I have so far:
function exts(value, from, to) {
return (value | something_goes_here);
}
`value` is the integer input, `from` is the number of bits that the `value` is using, and `to` is the target bit length.
What is the most efficient way to create a number that has `to - from` bits set to `1`, followed by `from` bits set to `0`?
Ignoring the fact that JavaScript has no `0b` number syntax, for example, if I called
exts(0b1010101010, 10, 14)
I would want the function to OR the value with `0b11110000000000`, returning a sign-extended result of `0b11111010101010`. | A number containing `p` one bits followed by `q` zero bits can be generated via
((1<<p)-1)<<q
thus in your case
((1<<(to-from))-1)<<from
or much shorter
(1<<to)-(1<<from) | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 6,
"tags": "javascript, bit manipulation"
} |
Functional Analysis problem: $\operatorname{Im} A$ is $a$ closed subspace in $E_{2}$.
> Let $A \in \mathscr{L}\left(E_{1}, E_{2}\right)$ and let $\operatorname{dim}$ Coker $A<+\infty$. Then $\operatorname{Im} A$ is $a$ closed subspace in $E_{2}$.
Be $E_{1}, E_{2}$ two Banach spaces and $\mathscr{L}\left(E_{1}, E_{2}\right)$ the set of all lineal continuous functions.
Proof.
Ker $A$ is a closed subspace of $E_{1}$ because of the continous of $A$ and therefore the quotient space $E_{1} /$ Ker $A$ has a Banach space .
the function $A$ induces a continuous $ A_{1}: E_{1} /$ Ker $A \rightarrow E_{2}$ with $\operatorname{Im} A_{1}=\operatorname{Im} A$ and $\operatorname{Ker} A_{1}=0 .$
But, what can i do after that?
I don't know what to do.
How the function $A$ induces $A_1$ ? | Pick $K$ to be a finite dimensional completement of $\text{Im}(A)$, then $K$ is closed. Consider the map $B: E_1/\ker A\oplus K\rightarrow E_2$ defined by $B(x+\ker A, y) = A(x) + y$. It's easy to see that $B$ is a bounded linear bijection. Therefore by open mapping theorem, $B$ is a homeomorphism, and it sends the closed subspace $E_1\oplus\\{0\\}$ to a closed space of $E_2$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "functional analysis"
} |
TCP messages - Durable and fast solution tips?
We use Spring integration for TCP socket communication with the hardware. The client would be sending a sequence number to uniquely identify a message. My requirement is to store these sequence numbers part of the socket message and validate them for non repetitive sequence numbers. I went thru IdempotentReceiver, sounds like what i wanted. But I need a durable and faster mechanism to store it, before unexpected shutdown of service and use the in memory cache for retrieving the latest sequence number.
Thank you in advance.! | You can use `PropertiesPersistingMetadataStore` for idempotent receiver:
> The `PropertiesPersistingMetadataStore` is backed by a properties file and a `PropertiesPersister`.
>
> By default, it only persists the state when the application context is closed normally. It implements `Flushable` so you can persist the state at will, be invoking `flush()`.
See more in its JavaDocs. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sockets, spring integration"
} |
Building an app on Linux for Windows
I am new in the programming world and I am really glad that I have finished building my first program. Its a simple C++ game that I programmed in QT on Ubuntu. Now I want to create executable files which contain all the neccessary dependencies, so the program can be ran without having QT and the used libraries.
I've been reading through questions and forum posts for the last two days, but I cant get my head around the process. I know that in order to make the program executable it has to contain all the links to the .so files or the .dll on windows, but I have no idea how to convert from .so to .dll and how to include those into my program.
I really did look at a lot of posts and all of them seemed a bit too advance. Also the whole building, releasing, packaging, deploying processes are not clear to me, but I haven't found any decent information starting from scratch.Can you point me into the right direction ?
Thanks | I can't recommend enough _not_ cross-compiling, get a virtual machine with your target OS and install the native toolchain plus any required libraries. This is simpler, less error-prone, and issues are easier to diagnose.
There's also the massive advantage that you can test the software on the platform you're building on. Remember you'll still need access to your target OS in order to test what you have built, so in reality cross-compiling offers you no advantage.
Of course everything I've said is irrelevant if you're building for an embedded OS whose toolchain is designed for cross-compilation anyway. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "c++, linux, windows, qt, ubuntu"
} |
Karate-Gatling: Add List of uriPatterns into karateProtocol()
I have a Collection[String] of uriPatterns to include in `karateProtocol()`. Is there a way to iterate through the collection and add the `MethodPause` (in this case is Nil) without hard coding it? | If you see the internal code `PreDef.scala` \- `karateProtocol()` is just a helper that in Scala terms - wraps `new KarateProtocol(Map[String, Seq])`.
So just build a Scala `Map` that has entries of the form `String -> Nil` and construct a `KarateProtocol`. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "karate"
} |
How to get wordpress custom fields rss feed into zend?
My web site is based on zend framework that have wordpress blog. I want to get new post details in the site. Using zend **Zend_Feed_Reader** function I can get title, link, description ... But there is no method to get wordpress custom fields feed. Is there any existing method or any other way to do that?
Thanks | Try to include `wp-load.php` in your zend site. This will give you access to everything in wordpress (functions, posts, meta) and you won't have to go out and retrieve an RSS feed to get it. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "wordpress, zend framework, rss"
} |
Better way to extract elements from a line using perl?
I want to extract some elements from each line of a file. Below is the line:
# 1150 Reading location 09ef38 data = 00b5eda4
I would like to extract the address **09ef38** and the data **00b5eda4** from this line.
The way I use is the simple one like below:
while($line = < INFILE >) {
if ($line =~ /\#\s*(\S+)\s*(\S+)\s*(\S+)\s*(\S+)\s*(\S+)\s*=\s*(\S+)/) {
$time = $1;
$address = $4;
$data = $6;
printf(OUTFILE "%s,%s,%s \n",$time,$address,$data);
}
}
I am wondering is there any better idea to do this ? easier and cleaner?
Thanks a lot!
TCGG | Another option is to split the string on whitespace:
my ($time, $addr, $data) = (split / +/, $line)[1, 4, 7]; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "perl"
} |
How do I email Active Directory distribution groups from a c# web application?
I'm trying to send email to Active Directory distribution groups.
I know you can send mail using something like:
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
//set the content
mail.Subject = "This is an email";
mail.Body = "this is a sample body with html in it.";
mail.IsBodyHtml = true;
//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
// i seem to need this too....
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.Send(mail);
But when I try to stick in a (valid) AD group (eg "My Test Group") in the `To` field, it kicks it out because it is not a valid email address.
I'm sure this is really straightforward, but I seem to be stuck...
Thanks | You distribution group has a mail address, that's what you need to add in the 'to' parameter. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, active directory, smtp, email, active directory group"
} |
Python percentile rank of a column, grouped by multiple other columns
I would like to group a pandas dataframe by multiple fields ('date' and 'category'), and for each group, rank values of another field ('value') by percentile, while retaining the original ('value') field.
I have attempted:
df2 = df.groupby(['date', 'category'])['value'].rank(pct=True)
But this returns only percentiles for the 'value' field. | I believe you need assign `Series` to new column:
df = pd.DataFrame({
'value':[1,3,5,7,1,0],
'category':[5] * 6,
'date':list('aaabbb')
})
df['new'] = df.groupby(['date', 'category'])['value'].rank(pct=True)
print (df)
value category date new
0 1 5 a 0.333333
1 3 5 a 0.666667
2 5 5 a 1.000000
3 7 5 b 1.000000
4 1 5 b 0.666667
5 0 5 b 0.333333
Alternative with `DataFrame.assign`:
df = df.assign(new= df.groupby(['date', 'category'])['value'].rank(pct=True)) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, pandas, percentile"
} |
Python Create fixed banner within console / with console
I am working on a text-based RPG game, and I need a way of displaying the important figures such as remaining life and level so that it is always available to be checked.
Is there a way of creating a stationary banner within the console to display such figures? If not, do I have to create a GUI with the banner and embed the console?
Any alternative solutions that also work would be appreciated, given that it shows the figures at all times.
Thank you. | I believe you're looking for a TUI layer. You might checkout the `curses` library,urwid, or even possibly picotui. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, python 3.x, python 3.5, adventure"
} |
Efficient NumPy rows rotation over variable distances
Given a 2D `M x N` NumPy array and a list of rotation distances, I want to rotate all `M` rows over the distances in the list. This is what I currently have:
import numpy as np
M = 6
N = 8
dists = [2,0,2,1,4,2] # for example
matrix = np.random.randint(0,2,(M,N))
for i in range(M):
matrix[i] = np.roll(matrix[i], -dists[i])
The last two lines are actually part of an inner loop that gets executed hundreds of thousands of times and it is bottlenecking my performance as measured by cProfile. Is it possible to, for instance, avoid the for-loop and to do this more efficiently? | We can simulate the rolling behaviour with modulus operation after adding `dists` with a `range(0...N)` array to give us column indices for each row from where elements are to be picked and shuffled in the same row. We can vectorize this process across all rows with the help of `broadcasting`. Thus, we would have an implementation like so -
M,N = matrix.shape # Store matrix shape
# Get column indices for all elems for a rolled version with modulus operation
col_idx = np.mod(np.arange(N) + dists[:,None],N)
# Index into matrix with ranged row indices and col indices to get final o/p
out = matrix[np.arange(M)[:,None],col_idx] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "python, python 3.x, numpy, optimization"
} |
How to check if a key exists in a Ruby hash?
I am using search of Net::LDAP, the returned entry is something like this.
#<Net::LDAP::Entry:0x7f47a6491c00
@myhash=
{:loginshell=>["/bin/bash"],
:cn=>["M... R..."],
:homedirectory=>["/mnt/home/m..."],
:uid=>["m..."],
:userpassword=>["{CRYPT}$1$3zR/C...$R1"],
...
}>
I tried to do the following, but failed.
(1)
e = entry.to_hash
e.has_key? "uid"
(2)
entry.has_key? "uid"
The first error says "to_hash" undefined, the second "has_key" undefined. Then I really don't know how to do it, basically I want to find if "uid" is present and if so get its correspondent value.
Thank you very much for the tip.
BTW, it only responds to "entry.uid", but if the search key is provided as a string, how to do that? for example,
def get_value(key)
if entry has key
return key's value
end
end | `:uid` is a `Symbol`. That's not a `String`.
try this:
e.has_key? :uid | stackexchange-stackoverflow | {
"answer_score": 35,
"question_score": 17,
"tags": "ruby"
} |
Mechanics of 'x % y != 0' in C++
Can someone please explain the under-the-hood mechanics of `x % y !=0` in C++? It evaluates to 0 if there is no remainder in integer division and it evaluates to 1 if there is any remainder of any amount. I find this to be quite useful, but I'd like to understand what is taking place, as the syntax is not intuitive to me.
I discovered this in a separate thread, which I do not have permissions to comment in:
Fast ceiling of an integer division in C / C++
Thank you.
(Please forgive any formatting faux pas; this is my first go here) | `%` is the integer remainder operator. For example:
* `21 % 7 == 0`
* `22 % 7 == 1`
* `25 % 7 == 4`
* `27 % 7 == 6`
* `28 % 7 == 0`
`x % y != 0` is true if the integer division yields a non-zero remainder, false if it doesn't. `x % y` is simply that remainder; `x % y != 0` tests whether that remainder is non-zero.
(Note that `x % y != 0` can also be written as `(x % y) != 0`.)
It's slightly complicated when you consider negative operands. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++, modulus, integer division"
} |
Saving Joomla front end test scores to the server
In a Joomla website I'm working on, the user does an English word knowledge test. The score on this test is calculated by some jQuery code and displayed on the test page. I want to save this score on the front end to the server as part of the user data stored there. I would like the score to be saved automatically on completion of the test. I understand that a php script will be necessary but I was wondering how a script might be triggered by jQuery. I have also looked at the SO articles "saving data from joomla frontend" and "Run php file through jquery link click". These are helpful but are there any tutorials on php scripting within the Joomla environment? I've checked the Joomla documentation but this seems to be largely oriented towards plugin development. Any help would be much appreciated Thanks in anticipation. | 1) Create PHP script to store score to DB
<?php
define( '_JEXEC', 1 );
define('JPATH_BASE', '/home/snehapur/snehyog');
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
/* Create the Application */
$mainframe =& JFactory::getApplication('site');
$task = JRequest::getVar('task');
if($task == 'savescore') {
$userId = JRequest::getVar('userId');
$score = JRequest::getVar('score');
// php code to save score in DB
}
?>
2) Call PHP Script from jQuery
jQuery.get( "myPhpScript.php?task=savescore&userId=123", function( data ) {
alert(data);
}); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, jquery, joomla"
} |
How to set the option selected in a select field with vue?
<span class="input-group-btn" style="min-width: 100px">
<select class="form-control" v-model="field.related_field">
<option value="null"></option>
<option v-for="f in fields" v-bind:value="f.id" v-if="f.id != ''" v-bind:selected="f.id == field.related_field ? true : false">{{ f.label }}</option>
</select>
</span>
This is my code in vue js. I am trying to set the option selected if the user submitted anything before when I am fetching from database. I tried to bind with the selected attribute. Can anyone help with this, please? | `v-model` takes care of this for you. Just set the expression you are binding with `v-model` to the value you want.
this.field.related_field = <value you want to default to> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "javascript, vue.js, vuejs2, vue component"
} |
Right indicator sometimes ticks really fast and lights don't illuminate
This is slightly different to what I'd expect when a bulb has blown as the indicator only sporadically stops illuminating bulbs and ticks really fast. This is different from when a bulb is completely blown and constantly ticks really fast and all bulbs except the blown one still illuminate briefly. This issue only appears on the right indicator, the left one is fine.
As far as written text can describe, it would go tick-tock, tick-tock, tick, tick, tick, tick-tock...
A video may explain much better; <
Due to the inconsistent nature, I've only been able to observe it whilst in the car. From the reflection off another car in front of me, the front bulb definitely did not illuminate during the high-frequency ticking.
How do I diagnose what is causing this? I'd assume it is bulb and/or fuse related?
If the car make/model makes a difference, it is a 2004 Holden Astra. | If the bulbs are are working, replace the unit. Last Time I did it the flasher unit was so cheap that I do not remember the price. | stackexchange-mechanics | {
"answer_score": 1,
"question_score": 0,
"tags": "electrical, indicators, bulbs"
} |
Checkbox in datagrid view in Window form in C#
I create the checkbox column in datagrid. and it works fine. But i need to select or fire the click event to whole the checkbox column with another checkbox outside the datagrid.I tried it but it just checked the checkbox but it doesn't fire the click event within the cells containing the checkbox. SO is there any solution?please help | Loop through the grid and set the value as shown for the column concerned in the checked event of the other checkbox
foreach (DataGridViewRow var in dataGridView1.Rows)
{
var.Cells[3].Value = true;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "c#"
} |
Constant for polynomials of limited degree
I'm trying to prove the following:
There exists a constant $C \in \mathbb{R}$ such that for all polynomials $f(t) \in \mathbb{R}[t]$ of degree not greater than $ 2014 $ we have
$$ |f(10)| \leq C\sup\limits_{t \in [0,1]} |f(t)| $$
What surprises me, this task was mentioned at functional analysis class and I can't find a way to connect it to the subject | Consider the space of polynomials of degree not greater than $2014$, for $f(t) = \sum_{n=0}^{2014} a_n t^n$, we define its norm $$\|f(t)\|_1 = \sum_{n=0}^{2014}|a_n|$$
Since we are dealing with a finite dimensional space(in which all the norms are equivalent), this norm is equivalent to the norm
$$\|f(x)\|_2 = \sup_{t\in [0,1]}|f(t)|$$
in particular, there exists $C>0$ such that $\|f(t)\|_1 \leq C\|f(t)\|_2$
Then remark that $|f(10)| \leq 10^{2014}\sum_{n=0}^{2014}|a_n|$, so
$$|f(10)| \leq 10^{2014} C\|f(t)\|_2= 10^{2014} C\sup_{t\in [0,1]}|f(t)|$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "functional analysis, polynomials"
} |
Regular expression, replace "22,09" with "22.09"
I am importing a dataset in csv format to a database.
The structure of the csv files are like this
> Part number, Description, Netto price, Brutto price, comment
> 11009, Ball Bearing, "22,09", "38,05", "Note, this article is the same as koyo xxxxxx"
As I am not yet familiar with regular expressions, can someone please put help me?
Or maybe a write perl script for me.
Thank you | There's no need for that; it can be done in MySQL alone.
LOAD DATA INFILE 'data.csv'
INTO TABLE prices
FIELDS
TERMINATED BY ','
ENCLOSED BY '"'
(partno, desc, @net, @gross, comment)
SET
net=REPLACE(@net, ',', '.'),
gross=REPLACE(@gross, ',', '.'), | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "mysql, database, regex"
} |
Searching For Text Including Double Quotes In SQL Server
Can anybody tell me how I can query for an item having a double-quote (") in them? The query I am trying to run is
SELECT * FROM Table WHERE Code = 'CAT"A"'
This query doesn't return anything although I do have an entry for CAT"A" I can find it using
SELECT * FROM Table WHERE Code LIKE 'CAT%'
But the "Code" being used will be variable, so I cannot use LIKE in this case. Any help is greatly appreciated :)
G | My bad, I realised the reason why it wasn't working was because I was using an Alias (Code was an alias). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "sql"
} |
Do Telepathic Talent and an elan's resistance stack?
Do racial traits bonus stack?
> ### Telepathic Talent:
>
> **Benefit:** You can expend your psionic focus to gain a +2 trait bonus to your saves against mind-affecting powers and psi-like abilities. This talent grants no benefit if you do not have the ability to gain psionic focus.
and
> ### Elan
>
> **Resistance (Su):** Elans can use psionic energy to increase their resistance to various forms of attack. As an immediate action, an elan can spend 1 power point to gain a +4 racial bonus on saving throws until the beginning of her next action.
if I'm a elan (with focus), if is a mind-affecting power to resist, Can I use both? | Telepathic Talent gives you a “trait” bonus, and the elan’s resistance gives you a “racial” bonus. These are not the same thing: “trait” ≠ “racial.” Since they are bonuses of different types, they stack. In situations where both apply, you add both bonuses together. | stackexchange-rpg | {
"answer_score": 4,
"question_score": 2,
"tags": "pathfinder 1e, psionics"
} |
How to pass values('how many' are known at runtime) to SQL query
I have following java code in which String array i.e. list which is dynamic value known at runtime. I need to pass this value to query mentioned in string variable i.e. SQL.
List[] list = new Arraylist();
String SQL = "select * from Table_name where col_1 IN ("+list[1]+")" OR
"col_1 IN("+list[2]+")" ....... OR "col_1 IN("+list[n]+")";
List <Class_Name> systemtails = jdbcTemplateObject.query(SQL, new
Class_Name_Mapper());
One way to do is enclosing following query in a loop, that makes query to execute more than once which in-turn affect performance.
String SQL = "select * from Table_name where col_1 IN ("+list[i]+")";
where i=1,2,3,4...n. All answers are welcomed and thank you in advance :).
PS : Query is just framed for question perspective in reality believe me it is very complex and big. | So I understand your query is in a for loop like so:
For int I = 0; I < list.size; I++ {
String SQL = "select * from Table_name where col_1 IN ("+list[i]+")";
List <Class_Name> systemtails = jdbcTemplateObject.query(SQL, new
Class_Name_Mapper());
}
why not do this instead:
String SQL = "select * from Table_name where col_1 IN (";
For int I = 0; I < list.size; I++ {
SQL+=list[I];
If(I != list.size -1){
SQL+=",";
}else{
SQL +=")";
}
}
List <Class_Name> systemtails = jdbcTemplateObject.query(SQL, new
Class_Name_Mapper()); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, mysql, arrays, list, arraylist"
} |
"no tests have been done" or "no test has been done"?
Should I say "no tests have been done" or "no test has been done" in case when only one test could possibly be done?
For example, in the case of a director who entered an empty classroom where a reportedly lazy teacher works, he may report to the principle as:
> I've checked all her papers. The tests on papers 1 through 5 have been done, however, **no tests have been done on paper 6 yet**
So, here the plural "no tests have been done" is used because there are more than one students in the class.
However, if it's one of those student's parent writing a complaint about that lazy teacher to the principal, then could he/she write something like:
> It's been already quite a long time since my daughter's progress has been tested. The tests on papers 1 through 5 were done long time ago. And **no test has been done on paper 6 yet**
? | It should be “no test has been done” in both cases, because there is only one test per paper. The number of test recipients is irrelevant. | stackexchange-ell | {
"answer_score": 1,
"question_score": 0,
"tags": "phrase choice"
} |
What is this black patch on the ocean floor featured on Google Maps?
I would like to visit this location around latitude 14.346756 & longitude -80.223648. However, there is a black patch on the ocean floor in Google Maps (only visible in satellite view).
!black patch on the ocean floor
What is this? | If you zoom in, an atoll appears in that area:

**EDIT:**
While Google Maps does not show anything in its map layer there, OpenStreetMap contains much more detailed information, including the name of that place: Serrana bank | stackexchange-travel | {
"answer_score": 33,
"question_score": 18,
"tags": "islands, caribbean"
} |
Implicit Conversion from Objective-C Pointer to int * is Disallowed With ARC
I have an class DMGStatController which has a delegate of type DMGSecondaryStatViewController. I write
DMGStatController *controller = [[DMGStatController alloc] init];
controller.delegate = self;
It is this second line of code that is giving me the error "Implicit Conversion from Objective-C Pointer to int * is Disallowed With ARC". I don't know what the compiler is talking about... DMGStatController's property delegate is of type DMGSecondaryStatViewController, not int *. Any help would be much appreciated.
Also, here is where I declare the delegate.
#import <UIKit/UIKit.h>
#import "DMGSecondaryStatViewController.h"
@interface DMGStatDescriptionViewController : UIViewController{
}
@property(nonatomic , retain) DMGSecondaryStatViewController *delegate;
@property(nonatomic , retain) NSString *finalStatChosen;
@end | Make sure to `#import "DMGStatController.h"`, and that the header includes a `@class DMGSecondaryStatController`. You likely have a warning about the fact that it doesn't know what `DMGSecondaryStatController` is and that it's defaulting to `int`. Make sure that there are no warnings in your ObjC code. Most ObjC "warnings" are in fact errors. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "objective c, ios, xcode"
} |
No call stack on Exception in xCode 4
I got an exception I can't back trace. I would like to know where the exception is thrown. Is there an option for that in xCode 4.2? As you can see the call stack is not much of a help. The only thing I know is that Iam trying to access an item in a NSArray at a faulty index.
All ideas are welcomed. Thanks!
!enter image description here | Set a breakpoint on `objc_exception_throw` and that will stop the program on that message.
**EDIT** ... Or just set the Exception Breakpoint in Xcode. Too used to doing this stuff directly in gdb. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 5,
"tags": "objective c, xcode, debugging, xcode4, xcode4.2"
} |
Update table if conditions met. (update the value from table b to a) corresponding value required
I have a table a in which i have fields 'date', 'time', cost and order_id
table b which has fields 'year' 'month' 'hour' 'cost' and order_id fields.
both tables are linked with "order_id" field. i want to update table a if year, month, hour and order_id is same in both tables and update the corresponding value from table b to table a field "cost"
I have used this statement, but query is not working? what is wrong in it? i need help
UPDATE item a, cost b
SET a.cost = b.cost
WHERE a.order_id = b.order_id
AND YEAR(a.date) = b.YEAR
AND month(a.date) = b.month
AND hour(a.time) = b.hour | UPDATE item a
JOIN cost b ON a.order_id = b.order_id
AND YEAR(a.date) = b.YEAR
AND month(a.date) = b.month
AND hour(a.time) = b.hour
SET a.cost = b.cost | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "mysql, sql update"
} |
Is it possible to recreate VirtualDub Deshaker functionality in Adobe Premiere/After Effects?
I'd like to automatically stabilize some poorly-shot shaky footage in Adobe Premiere or After Effects.
VirtualDub Deshaker analyzes frame motion, computes smoothing, adjusts frame position, scale and rotation, and does smart filling of the area outside a frame.
Is anything similarly powerful achievable using Adobe software, possibly via third-party plugins? | After Effects CS5.5 has the Warp Stabilizer (also check the video on the main Adobe After Effects site). | stackexchange-avp | {
"answer_score": 4,
"question_score": 3,
"tags": "software, virtualdub, premiere, after effects"
} |
How to send api request with authentication in ruby
I have this curl command to send api request with authentication. I am writing a test using airborne where I need to send an api request inside the test. curl command
curl \
-v -u [email protected]:Abcd1234
I have the test like below but I need to add the authentication. How do i do it?
describe 'Test to GET' do
it 'should get the existing data'do
get "
expect_status(200)
end
end | `-u` option sends a basic auth header to the client.
The very top of `README` of _Airborne_ shows how to send an auth header:
describe 'Test to GET' do
it 'should get the existing data' do
get "
{ 'x-auth-token' => 'my_token' }
expect_status(200)
end
end
How to get the token out of `user`:`password` pair I’d leave for you as a homework (e. g. you might simply log `curl` request.)
You also might set the auth header globally via _Airborne_ config. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "ruby on rails, ruby, api, rest client, airborne"
} |
How to use ADC interrupt on STM32 blue pill
I'm currently using the STM32F1xx boards from < To program my blue pill but I can’t find how to write the interrupt for the ADC. I’ve set the registers to output an interrupt when it finishes but I can’t find how to write the code for the interrupt.
I’ve tried the ”ISR(ADC_vect)” function which works for arduino, but the compiler is complaining that ”ISR” is not recognized. I’ve tried to look for the documentation for the STM32duino, but the little I could find didn’t even mention the ADC or any interrupt routines. I’ve searched though the STM32duino forum without any luck. If anyone knows how to solve this or where to find information about interrupt code for the STM32 boards I would be very happy :) | As you already found, the function to override is `__irq_adc()` defined weakly here and bound to the interrupt vector table here.
If you've defined it and it's not working, it's probably because you got rid of the `attachInterrupt()` call entirely, which does more than just assign an interrupt handler; it also enables the interrupt for that ADC. So:
myADC.calibrate();
myADC.setSampleRate(ADC_SMPR_1_5);
adc_enable_irq(ADC1, ADC_EOC);
myADC.setPins(&pin, 1);
extern "C" void __irq_adc() {
// handle the interrupt
// make sure to check statuses and clear flags as shown in the default handler
}
Not sure if the `extern "C"` will be needed, probably will be, you'll have to check and find out. | stackexchange-arduino | {
"answer_score": 1,
"question_score": 2,
"tags": "interrupt, adc, stm32"
} |
Does WSO2 Identity Server 5.1.0 supports Manager/Worker cluster deployment pattern
WSO2 Documentation found here describes that WSO2 Identity Server based on Carbon 4.2.X does not support Manager/Worker deployment pattern. However, WSO2 Identity Server 5.1.0 was just released and it is based on Carbon 4.4.X. Can I assume that this version supports this deployment pattern? If so is the configuration the same as other products based on Carbon 4.4.x? The documentation does not seems to be updated against this new version. | Yes, There was a shortcoming in the docs and it is fixed now. You can follow guide at [1]. WSO2 IS doesn't need the worker/manager separation as it is not hosting any artifacts like other servers. For further details read [2]
[1] <
[2] < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "wso2, wso2 identity server"
} |
Добавить товар в корзину js
Нужно добавить товар в корзину,если такой есть то увеличить count++. Не используя методы которые напрямую меняют массив.
basket: state.basket.find(
item => (item.id === action.payload.id)
?
state.basket.concat({
id: action.payload.id,
count: item.count++,
})
: state.basket.concat({
id: action.payload.id,
count: 1,
})
) ? state.basket : state.basket.concat({
id: action.payload.id,
count: 1,
})
basket: [
{
id: 12,
count:1
},
{
id: 13,
count:1
}
] | basket: state.basket.find((item) => item.id === action.payload.id ? item.count++ : null)
?
[...state.basket]
:
[...state.basket].concat(
{
id: action.payload.id,
count: 1,
}
) | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, reactjs"
} |
What is the difference between Object b(); and Object b;?
To be more explicit, I get a compile time error when I try accessing an instance variable when I create an object using (), but when I don't, the code compiles and runs as expected. Also, this problem only applies to the default constructor. I would like to understand why.
using namespace std;
#include <iostream>
class Student {
public:
int gpa;
Student() {
gpa = 4;
}
Student( int x ) {
gpa = x;
}
};
int main() {
Student zero;
Student sally( 2 );
Student jack();
cout << zero.gpa << endl; //prints 4
cout << sally.gpa << endl; // prints 2
cout << jack.gpa << endl; //error: request for member 'gpa' in 'jack', which is of non-class type 'Student()'
} | The problem is that `Student jack();` declares a function with `Student` as a return type. It doesn't declare an object of that class as you expect. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "c++, class, instance variables, default constructor"
} |
Calculating a spiral in MATLAB
We have these logarithmic spirals which are circling around the centre of the coordinate system:
x = ebθ cos(θ)
y = ebθ sin(θ)
where the _e bθ_ is the distance between the point (which is on the spiral) and the centre; and the _θ_ is the angle between the line connecting the point and the origin and the axis _x_.
Consider a spiral where the angle is _θ ϵ <0,10π>_ and the parameter is _b=0.1_. By thickening points on the spirals (and the angle _θ_ ) calculate the circumference with the relative precision better than _1%_. Draw the spiral!
I'm preparing for a (MATLAB) test and I'm stuck with this exercise. Please help, any hint is appreciated. | Start by computing a list of x,y for your range of theta and value of b. For more accurate results, have your theta increment in smaller steps (I chose 5000 arbitrarily). Then, its simply computing the distance for each pair of consecutive points and summing them up.
t = linspace(0,10*pi,5000);
b = 0.1;
x = exp(b*t).*cos(t);
y = exp(b*t).*sin(t);
result = sum(sqrt((x(2:end) - x(1:end-1)).^2 + (y(2:end)-y(1:end-1)).^2)) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "matlab, geometry"
} |
Can I use the content of div:before as an anchor to toggle visibility of the rest of the div?
I have the following css (idea from blog post of Zachary Harmany):
.proof{
display: block;
content: "Proof:";
}
.proof:before {
content: inherit;
font-style: italic;
}
Then html
<div class="proof"> This is trivial. </div>
produces something like:
> _Proof:_
>
> This is trivial.
I would like to use the "Proof:" keyword to toggle the visibility of the proof (here the sentence "This is trivial.") _onclick_.
Is it possible to use the content of .proof:before as an anchor to toggle the visibility of the rest of the content of .proof? | Answer is yes :
maybe `height` and `pointer-events` can help to show you that it is possible:
.proof{
height:1.2em;
overflow:hidden;
pointer-events:auto;
}
.proof:before {
content: "Proof: onclick toggles show/hide real content";
display:block;
font-style: italic;
cursor:pointer;
}
.proof:active , .proof:focus {
height:auto;
pointer-events:none;
outline:none;
}
<div class="proof" tabindex="0"> This is trivial. you see me or not onclick :) </div>
So you need to catch the onclick from the element itself. If you hover or click the pseudo-elements, you do meanwhile click or hover the element itself. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, html, css"
} |
How do you represent an application in UML?
Is it as simple as just a square or rectangle with the application name in the center? | If by application, you mean an other (external) system which interact with your system (application) then it is an actor. You can stereotype that actor as application and in some software gives it a specialized icon (square or whatever). Unfortunately all UML softwares are very poor in representation so sometimes it's better to use a graphics software to draw nice UML diagrams. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "uml"
} |
Having trouble linking Cassandra and Thrift sources in Eclipse
I am using Cassandra (0.7.2) and Thrift (0.7) with eclipse 3.4 and having trouble getting the source files linked in. I have built both Thrift and Cassandra using ant, after building Cassandra there is a sources directory under build/lib which contains source .jars. Unfortunately even after linking these into eclipse, I still can not see the source for anything. To add sources I am going to build path->sources tab->link source (here I select the source folder containing the source jars). I have also tried ctrl-clicking on classes, which complain that no attached source could be found, and I try to specify the source path via the browse button provided. Still no luck
I am a bit new to eclipse, so it certainly could be user error on my part. Any pointers or tips?
Thanks so much | I always set up the source like this: `Properties > Java Build Path > Libraries tab`, expand the Jar, select 'Source attachment', click 'Edit', and select the source Jar or Zip file for the Jar. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "eclipse, cassandra, thrift"
} |
Explanation of output of a java program
I came across the following program
class Boolean {
public static void main(String argv[]) {
boolean x;
x = 4.4f == 4.4;
System.out.println(x);
}
}
The output of the following program is `false`
But if we write the program in the following fashion, then
class Boolean {
public static void main(String argv[]) {
boolean x;
x = 4.5f == 4.5;
System.out.println(x);
}
}
In this case the output is `true`
Can somebody explain me why ?? | You generally shouldn't compare floating point values with == operator. You should use 'close enough' comparison like checking if values differ by some small value:
` double epsilon = 0.000001
boolean equal = Math.abs(value1-value2) < epsilon `
In your example, 4.4f is not equal to 4.4, because java defaults floating point values to **double** type, which is 64bit, and to compare them java casts 4.4f to double, which causes it to be slightly different from original double value 4.4(because of problems representing decimal fractions with binary).
Here's a good link on floating point numbers. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 5,
"tags": "java, boolean"
} |
Removing some characters in a DataFrame
I have a problem on replacing this value "..." by NaN. Here is my code
import pandas as pd
import numpy as np
energy = pd.read_excel('Energy Indicators.xls')
del energy['Unnamed: 0']
del energy['Unnamed: 1']
energy.columns = ['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']
energy.replace("...", np.NaN)
energy['Energy Supply']
They always appear :
Out[46]:
17 321
18 102
19 1959
20 ...
21 9
...
241 344
242 400
243 480
244 NaN
245 NaN
Name: Energy Supply, Length: 229, dtype: objec
Anyone can help me solve this ?
Thank you | Your problem is that replace returns a DataFrame by defaulft (see doc). To solve this you can either
energy = energy.replace("...", np.NaN)
or
energy.replace("...", np.NaN, inplace=True)
You can even avoid this problem altogether by specifying that "..." should be interpreted as NaN at read time:
energy = pd.read_excel("Energy Indicators.xls", na_values="...")
See doc. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, pandas"
} |
how to addClass('overflow');
I want click a button then it add the class
.overflow{overflow-y:scroll};
I used `addClass('overflow'}`, but it reload the whole page on clicked.
After an action it will `removeClass('overflow')` I will not choose to use `.css('overflow','hidden')` because `'auto','scroll','hidden'` is not suitable for me, I want it being completely remove after used. | Why dont you just use an `<a>` with `href="#"` ?
That wouldn't reload the page and still trigger your script.
In yor posted code u have a minor typo: You ended the `addClass()` with `}` ... This would be the correct code:
`$("#targetElement").addClass('overflow');` | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery, html, css"
} |
How to revoke a GPG key without confirmation?
After running the following command to revoke a key
gpg --gen-revoke <key ID>
I have to then press `y`, 2 times `Enter` followed by `y`
**How would you suggest to answer automatically, that is revoking a key without any other user interaction than the passphrase prompt?** | It appears to me that gpg opens the controlling terminal directly, so you're unable to redirect input. | stackexchange-unix | {
"answer_score": 0,
"question_score": 1,
"tags": "command line, scripting, gpg"
} |
finding all the mobius transformation.?
find all the mobius transformation that map the units disc$ D$ onto the left half plane
$H^-$ = {$w \in C : Re w <0 $}
My attempts : I know that all the Möbius transformations can be written on the form
$$w=f(z)=\frac{az+b}{cz+d}$$
here i don't know how can i find all the mobius transformation .
as im not getting in my heads pliz help me | **Hint:** It's a standard result that the Möbius transformations which map the unit disk onto itself are those of the form$$z\mapsto\omega\frac{z-a}{1-\overline az},$$with $|\omega|=1$ (there's a proof here). Now, find _one_ Möbius which maps the left half plane onto the unit disk and you're don (well, almost). | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "complex analysis, mobius transformation"
} |
Progress Dialog in Android doesn't Show?
Okay.. I am doing something similar to the below:
private void onCreate() {
final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true);
Thread t = new Thread() {
public void run() {
//do some serious stuff...
dialog.dismiss();
}
};
t.start();
t.join();
stepTwo();
}
However, what I am finding is that my progress dialog never even shows up. My App stalls for a moment so I know it is chugging along inside of thread t, but why doesnt my dialog appear?
IF I remove the line:
t.join();
Then what I find happens is that the progress dialog does show up, but my app starts stepTwo(); before what happens in the thread is complete..
Any ideas? | Try to use an handler
public class MyActivity {
private Handler handler;
private void onCreate() {
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
pd.dismiss();
stepTwo();
}
};
final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true);
Thread t = new MyThread() {
t.start():
}
private class MyThread extends Thread() {
public void run() {
//do some serious stuff...
handler.sendEmptyMessage(0);
}
}
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java, android, multithreading"
} |
How can I combine(concatenate) two data frames with the same column name in java
Can I append a dataframe to the right of other dataframe having same column names | You can join two dataframes like this.
df1.join(df2, df1.col("column").equalTo(df2("column")));
If you are looking for Union, then you can do something like this.
df1.unionAll(df2); // spark 1.6
Spark 2.0, `unionAll` was renamed to `union`) | stackexchange-stackoverflow | {
"answer_score": 29,
"question_score": 12,
"tags": "java, apache spark"
} |
Can't change base color of icing
:
baz: int
I want to do this:
base = Base(1, 2)
derived = Derived(base, 3)
But this would try to assign `base` to `derived.foo`. Is there a way to accomplish this in such a way that I don't have to iterate over each field? I could for example serialize `base` to json, add the additional field, then deserialize to `derived` but that seems a bit hacky. | You can unpack the fields of one instance when creating another:
>>> from dataclasses import asdict
>>> Derived(**asdict(base), baz=3) # by keyword
Derived(foo=1, bar=2, baz=3)
>>> Derived(*asdict(base).values(), 3) # positional
Derived(foo=1, bar=2, baz=3)
Note that using `asdict` makes a deep-copy, so that there won't be any references accidentally shared. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "python, python 3.x"
} |
Regresión por quantiles por categoria en R usando quantreg
Teniendo la siguiente base de datos.
df <- data.frame(C1=c('A','A','A','B','B','B','B','C','C'),
C2=c('1','2','3','1','3','5','6','0','2'),
C3=c(10,20,40,60,70,10,20,60,90),
stringsAsFactors = FALSE)
Quisiera calcular una regresión lineal para el quantil 95 entre C2 y C3 usando `quantreg` separadamente para cada factor de la columna C1 (A, B C). El código que tengo hasta ahora es:
library(quantreg)
fit1 <- rq(C3 ~ C2, tau = .05, data = df)
summary(df) | Si no te entendí mal, puedes hacer lo siguiente:
# aplicamos rq a cada set de datos dado C1
lapply(unique(df$C1),
FUN = function(x) {tmp <- df[df$C1==x,];rq(C3 ~ C2, tau = .05, data = tmp)}
) -> model_lst
# Renombramos los elementos de la lista al nombre de C1
model_lst <- setNames(model_lst, unique(df$C1))
# ahora sí podemos acceder a cada modelo
model_lst[["A"]]
model_lst[["B"]]
model_lst[["C"]]
Básicamente, por cada set de datos correspondiente al valor de `C1`, aplicamos la regresión `rq()`, al finalizar, tendremos una lista con cada uno de los modelos. | stackexchange-es_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "r, regresión lineal"
} |
Ampersand converted into %26 in url
I'm trying to put/concatenate in the url, once a form is submitted, the q and/or the fq from a search query. This is the code I have tried so far:
<input type="hidden" name="q" value="{{ content.params.q }}'{% verbatim %}&type={% endverbatim %}'{{request.GET.type}}" />
or
<input type="hidden" name="q" value="{{ content.params.q }}&type{{request.GET.type}}" />
I also tried with
{% autoescape on %}
to no avail. Basically I want the final url (i.e. what is in the address bar after the form is submitted) to be something like
q=something&somethingelse
Instead, I get
q=something%26type%3Dsomethingelse
How can I get the template to output ampersand and equals as they are without being encoded into %? | Actually I used javascript for this.
<form role = "form" id="filter" action="/search/" method="get">
<input type="text" name="something" id="something" ...>
[...]
$(document).ready(function() {
$("#filter").submit(function(event) {
event.preventDefault();
$this = $(this);
var something = $('#something').val();
var qstr = window.location.search;
var url = qstr + '&something=' + something;
};
window.location.search = url;
});
}); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "django, solr"
} |
Take 2 fields in a content type with php
I have a content type with the following fields: Name, Language, Date, Photo, Text associated with the following names for internal use: title, language, field_date, field_photo, body
I created instances. One of these is called "Mondovi." I would like to see only the fields field_data and body of this instance. I want to use php to put them within the content or within a block. What to do? | Let assume that you are using Drupal 7
You need to know nid of node "Mondovi".
Then you can use following code:
$node = node_view(node_load(NID_OF_NODE));
// print value of body field without field label
print render($node['body'][0]);
// or print body value with field label and all div wrappers
print render($node['body']);
// print value of field_data without field label
// if field can have multiple values - use cycle to dipslay all of them
print render($node['field_data'][0]); | stackexchange-drupal | {
"answer_score": 2,
"question_score": 1,
"tags": "views, 7"
} |
Running a C# executable outside of folder containing external library
I have a C# program that uses an external opensource library that I downloaded from the internet, specifically openxml to create excel files. Now I want to run my executable files on computers that do not have this library installed.
I already know that I can have visual studios to make a copy of the library in either the debug or release folder by setting the copy local property to true, and I am doing this.
The problem is that now the executable file can be run on other computers and generate excel files, but the executable file has to be run in the debug or release folder where the library is saved.
When I try to copy the executable file and run it outside of the folder an exception is thrown telling me that the library cannot be found, how do I make it find the library when running the executable outside of the folder?
Thanks,
-Jake | There should be several options that should work.
The problem is that the library is not in the path.
This might help. "< You would just need to always have the library in the same location.
You could add the it to the path variable (though this could cause conflicts elsewhere). You could add the folder to the temporary path, i.e. the console whenever it starts up. You could add it to the relative path "Visual Studio: how to set path to dll?"
Hopefully that helps | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, visual studio 2010, dll, executable, dllnotfoundexception"
} |
PHP : Is calculating with strings reliable
In PHP I make a simple calculation, but with strings
$num_1 = '200.50'; (string)
$num_2 = '100.50'; (string)
echo $num_1 - $num_2
The result is as expected `100.00`
What I wonder about is the fact that I did not cast the values to float and still got the correct result.
And my question is if this kind of (string) calculation is reliable ? | It's reliable if you use numbers in your string. If you use alphabet characters, special characters, or other things you wouldn't expect in basic maths, you may get unexpected results.
To learn more about what behavior you can expect and how to prevent issues, see the PHP docs for type juggling.
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
Can you guess the two famous titles?
I took two famous titles.
From each and every word in those titles I replaced a single letter with another letter to form new words.
Then I scrambled all the new words from both the titles to get:
> Go get any lime pie like Bo did
What are the two titles? What is the common theme? | The two titles are:
> **No Time to Die**
> (Go lime Bo did)
>
> and
>
> **Live and Let Die**
> (like any get pie)
These are both:
> Films featuring the character **James Bond** where the title ends with the word 'Die'. | stackexchange-puzzling | {
"answer_score": 10,
"question_score": 6,
"tags": "knowledge, wordplay"
} |
Where I can download MySQLSchemaProvider for Codesmith Generator?
I currently need to work with MYSQL so I wonder where I can download the latest version of MySQLSchemaProvider. I am using CodeSmith Generator version version: 5.3.4.
Thanks | The latest MySQLSchemaProvider ships with CodeSmith Generator. You can see a list of the providers we ship with in the screenshot located here | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "mysql, code generation, codesmith"
} |
How do I name a chart object?
How do I change the name of a chartobject instead of referring it as ChartObject(1)? The Chartobject is on a sheet named "Unit2SelectedData"
Sheets("Unit2SelectedData").ChartObjects.Add Left:=1700, Top:=50, Width:=800, Height:=400
Sheets("Unit2SelectedData").ChartObjects(1).Activate | Try setting the `ChartObject` first, and then name it:
Dim ChtObj As ChartObject
Set ChtObj = Sheets("Unit2SelectedData").ChartObjects.Add(Left:=1700, Top:=50, Width:=800, Height:=400)
ChtObj.Name = "My Chart" | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "excel, vba"
} |
Displaying a large number of columns in a table
I have a _Twitter Bootstrap_ based table with responsive CSS.
Everything looks good but, when I try to put more columns than the _size of the table_ supports, I have a line breaking.
I tried to **change font size**. But I think it would be strange or confusing for the user if I have different font sizes in each table. So I am in a dead end.
### Some restrictions
* Maximum width: The table must **not exceed 940 pixels**.
* **Single Table** : I can't divide the information in multiple tables.
This is what I have:
!enter image description here
Is there a better way to display tabular data considering the restrictions? | First option, if you do not wish to change any other parameters, you can implement a **horizontal scroll bar**. It's not the best option, but, it does get you to show(?) the entire table with consistent size without exceeding the 940 pixel width.
Second option, make the **columns movable**. You wrap/crumple up the out of bound columns so as they only expand when the wrap/crumple is clicked on. This way, the user can customize the table to see only things he's interested in and the rest information is still available but, hidden away.
Third option, go down the path of information visualziation. If you are not hell bent on using a table, you can look into **small multiples or multivariate charts** like parallel plots, etc. depending on the type of data you have and the output you desire. | stackexchange-ux | {
"answer_score": 0,
"question_score": 0,
"tags": "design patterns, info visualisation, responsive design, data tables"
} |
How do I get to Zora's Domain?
I am stuck on The Legend of Zelda: Ocarina of Time on 3DS. I am at Lake Hylia and there appears to be a temple under the lake. From what the owl said and online guides I'm supposed to play Zelda's Lullaby somewhere but I've tried loads of places all around the lake and got nothing so far.
There is an island with a stone that says "When water fills the lake, shoot for the morning sun." I have tried shooting the slingshot between the two pillars, at the sun, and playing Zelda's Lullaby there.
I'm just baffled because there is zero clues as to what to do next... | The hint from the owl is to enter Zora's Domain. The entrance to the path to Zora's Domain is in Hyrule field near the entrance to Kakariko Village. Make your way to the end of the path where you will find the Triforce symbol he's referring to.
Just so you know, you can also go fishing in Lake Hylia. Also, when looking at your map subscreen the flashing dot is where to go next. | stackexchange-gaming | {
"answer_score": 6,
"question_score": 5,
"tags": "zelda ocarina of time"
} |
Remove text caret/pointer from focused readonly input
I am using an `<input readonly="readonly">`, styled as normal text to remove the appearance of an interactive field, but still display the value.
This is very useful to prevent a user from editing a field, while still being able to post the value. I realize this is a convenience method and that there are several workarounds, but I want to use this method.
**Problem:** The blinking caret still appears when the field is clicked/focused. (At least in FF and IE8 on Win7)
Ideally, I would like it to behave as it normally does, focusable, but without the blinking caret.
Javascript solutions welcome. | On mine there is no caret or so:
<input type="text" value="test" readonly="readonly" >
Take a look at this: <
Sorry, now I understand your problem.
Try this:
<input type="text" value="test" onfocus="this.blur()" readonly="readonly" > | stackexchange-stackoverflow | {
"answer_score": 56,
"question_score": 45,
"tags": "html, css, forms, caret"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.