INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Can't Center Ordered List Title
I have an ordered list with an H3 and then a paragraph.
I can't figure out how to center the heading.
.list {
list-style: decimal;
list-style-position: inside;
margin-left: 0px;
display: inline-block;
}
.list li h3 {
display: inline-block;
margin: 0 auto;
text-align: center;
}
<ol class="list" reversed="reversed">
<li>
<h3>Fourth Prime</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus feugiat at metus ut ultricies. Aliquam lacinia libero sit amet ex accumsan, sit amet imperdiet sapien vehicula. In hac habitasse platea.</p>
</li>
</ol>
|
If you want the H3 centered look at the display css option, currently `display: inline-block` is not allowing the H3 tag to be centered.
.list li h3 {
display: inline-block; // block or list-item
margin: 0 auto;
text-align: center;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "html, css, html lists, centering"
}
|
When provisioning a Cosmos DB - Gremlin API from PowerShell, is there a way to set the capacity mode to Serverless?
When I create a Cosmos DB - Gremlin API from the Azure Portal there is an option to set the capacity mode to serverless:

$capabilities= @(@{"name"="EnableServerless"},@{"name"="EnableGremlin"})
$CosmosDBProperties = @{
"databaseAccountOfferType"="Standard";
"locations"=$failoverLocations;
"capabilities"=$capabilities;
}
New-AzResource -ResourceType "Microsoft.DocumentDb/databaseAccounts" `
-ApiVersion "2019-12-12" -ResourceGroupName $resourceGroupName `
-Location $accountLocation -Name $accountName -PropertyObject $CosmosDBProperties
Note that the cmdlet is New-AzResource not New-AzCosmosDBAccount.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "powershell, azure cosmosdb, azure cosmosdb gremlinapi"
}
|
global variable from django to javascript
I would like some **variables from my settings.py** to be **available in every javascript** running across my project.
What is the most elegant way of achieving this?
Right now I can think of two:
* write a context processor and declare those globals in a base template. All templates must extend the base template.
* declare those globals in a dynamically generated .js file (by some view) and load this file using `<script>` tag in a base template. All templates must extend the base template.
Can I do it without a base template?
|
I would use option 1. You should use a base template in any case, and a context processor is probably the best way of getting the variables into it.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 5,
"tags": "javascript, python, django"
}
|
Google App Engine: Unable to find 'increasing daily budget'
I can't find it.
< talks about it but doesn't say where.
This one says it's in the billing section, but the billing section lists my billing accounts and inside an account I can't find it either.
|
Using the new console, you can change your billing from your App Engine settings: < /appengine/settings
Make sure you've linked your project to a billing account. To do this, head over to your project-level settings: < /settings
If that still doesn't work, try the old console: **s~your-app-id**.
You must prepend the "s~" to your App ID in the old console URL if your app uses High Replication Datastore (very likely).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "google app engine, payment"
}
|
How can I chage the color of the link in Html.Action link, when the mouse is over the div?
I am using MVC3. I have a table and an Html.ActionLink inside of it. I have already set the text decoration for none, but the link is still blue. I change the table:hover background-color and the color(of the text), and when I put the mouse over the row, the text that are not a link gets white, but the link still blue. If I change the a:hover, the link gets white just when I put the mouse over it, and not just over the row.
Is there a way to do that with css?
|
Typically, to cover all the anchors when you are hovering over the row.
#tableid tr:hover a {
/* Your Styles */
}
But this does not work on all IE browser so, use JS to catch the event and apply styles to anchors in it.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "css, asp.net mvc 3, actionlink"
}
|
Anyway to watch my own monero address without installing the full monero wallet?
Is there a way to monitor my monero address without the need to download the entire blockchain? And I don't want to constantly paste my private view key into a block explorer to see it neither. I want it to be able to just click a button or visit a link and be able to see my balance from time to time. What solutions are there?
|
You can download the official GUI and set up a view-only wallet, without downloading the entire blockchain. You would still have to sync your wallet with the network. This doesn't take a long time.
Connecting to remote node \- so you don't have to download the blockchain.
Set-up a view-only wallet
|
stackexchange-monero
|
{
"answer_score": 1,
"question_score": 1,
"tags": "viewkey, block explorer, balance, view only"
}
|
Adler-32 in Multilevel Security Environment Safe Practices
I'm implementing a multilevel security environment on several several web servers running Debian. I've done quite a bit of reading on fast hash checking algorithms to compliment the other security components.
It seems Adler-32 is quite fast and compact (which I'm quite fond of), although I understand it can be 'easily' forged. This aspect of it makes me a bit nervous, so is there some way to safeguard against it being forged somehow?
|
No. CRCs can also be easily forged. If you are worried about forging (and make sure that you understand _why_ you are worried about forging), then you need to use a cryptographically secure hash. E.g. SHA-2.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "security, hash, adler32"
}
|
.Net StopWatch and Powershell
I have a powershell script that is currently running every 4 hours via task scheduler. It cleans a drive and when it's done it fires off an email to me telling me what it moved and where and the amount of time it took to perform this task.
However, I seem to be having issues with the time it displays at the end. I recently got an email that it took 4 minutes, when I know that it took closer to 30 minutes.
The basic structure looks like this:
$StopWatch = new-object system.diagnostics.stopwatch
$StopWatch.Start()
Do { All this stuff }
While(This condition is false)
$StopWatch.Stop()
$Minutes = $StopWatch.elapsed.minutes
What am I missing here? This thing is just reading the system time and then comparing it to the current time whenever `.elapsed` is accessed right?
|
Try using $StopWatch.Elapsed.TotalMinutes instead of $StopWatch.Elapsed.Minutes
The latter will not count beyond 59 so for a task that took 64 minutes to run, the Minutes property will only show 4. The Hours property in this particular example however would have increased to 1, up from 0.
You could easily verify/try this out using the same object you already have but by looking at the Seconds/TotalSeconds properties instead since it follows the same logic.
$StopWatch = new-object system.diagnostics.stopwatch
$StopWatch.Start()
Do { All this stuff }
While(This condition is false)
$StopWatch.Stop()
$Minutes = $StopWatch.Elapsed.TotalMinutes
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 5,
"tags": ".net, powershell, stopwatch"
}
|
Is there a way to sign my WinForms program for free?
I've just finished creating a WinForms application for my company. Everything works fine, but when my co-workers run the program, they need to provide the domain administrator password, which one of those co-workers doesn't have access to. How could I sign the program, or make an exception somewhere on their computers so that they don't have to use the admin login to use it? I'm not going to pay for a certificate.
I'm developing in Visual Studio 2015. The computers are running windows 8.1.
Thanks
|
**Short answer:**
Yes. You can have your AD Administrator issue and load a certificate as part of the Global User Policy on your network.
**Long answer:**
You need to use the right type of certificate for signing of the application manifest, if, for example, you are planning to use ClickOnce to deploy the application. (This is much easier to do than using SignTool.exe to sign a binary).
Your AD Admin will need to setup your PDC as a Root CA for your network. This Root CA will issue the certificate and the certificate will need to be included in the default network profile of your target users on the locked down network environment.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": -3,
"tags": "c#, winforms, signature"
}
|
Casting LONG to function pointer?
How does this work?
I looked at this tutorial from here:
> WNDPROC fWndProc = (WNDPROC)GetWindowLong(Msg.hwnd, GWL_WNDPROC);
From msdn it explains that GetWindowLong returns a LONG that is defined as just a long. This confuses me because it is converted into a function pointer (WNDPROC).
What happens when you convert a long into a function pointer? They are completely different things. How can the function pointer even work when a long isn't even a function?
|
A pointer is just address of variable; So it is presented by integer.
Standard says `uintptr_t` and `intptr_t` is compatible with pointers
#include <stdint.h>
int a;
int *pa = &a;
uintptr_t addr_of_a = (uintpt_t)pa;
In 32-bit system, `sizeof(uintptr_t)` = `sizeof(int *)` = `4`. In 64-bit system, they're `8`.
`GetWindowLong` function is used for 32-bit system, so its return value's type is `LONG`, which is 4 byte.
In 64-bit system, however, size of pointer is 8 byte. So microsoft deprecate `GetWindowLong`, and you should use `GetWindowLongPtr` and `LONG_PTR`.
// the type of the return value of GetWindowLongPtr is LONG_PTR. So this code is safe and portable.
WNDPROC fWndProc = (WNDPROC)GetWindowLongPtr(Msg.hwnd, GWLP_WNDPROC);
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c++, windows, function, winapi, pointers"
}
|
Reset colors and theming to defaults after Windows Server upgrade
For reasons too long to discuss here, we have upgraded a Windows Server 2012 VM to Windows Server 2019. We hardly ever do this, but the upgrade actually went well.
However, one thing a few folks noticed is that, when a new user logs in, the color scheme and other window theming looks like Server 2012 rather than Server 2019. Not a major issue, but people have noticed nonetheless. I'm not talking about the default wallpaper but more the way windows and borders look.
I would expect this for _existing_ accounts but not brand-new ones created post-upgrade.
Is anyone aware of a way to set new-user themes to the Server 2019 defaults instead of the Server 2012 defaults?
|
I think I found the closest thing to an answer: replace _C:\Users\Default_ with another _C:\Users\Default_ from a vanilla (not upgraded) installation of Windows Server 2019 (or whatever version of Windows Server you are upgrading to).
During the in-place upgrade process, Windows Server preserves some settings in _C:\Users\Default_ , including theme/color settings.
After copying the _C:\Users\Default_ directory structure to your upgraded Windows Server installation, make sure that permissions on the files and folders are preserved from the source _C:\Users\Default_.
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 2,
"tags": "windows server 2012, upgrade, windows server 2019"
}
|
How do you change your apparent country of origin to test a site?
I want to be able to set my country of origin - does this involve testing through a proxy, or is there something that can be set else where?
|
I would use TOR for this purpose. That way you are sure you are hitting the site from a different country.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 7,
"tags": "browser, regional, web testing"
}
|
Wordpress: If the_category != "category2"
Quick Wordpress question. Is it possible to check against a specific category, so not to display it? I tried this, but my category was still being echoed (no errors).
<?php if (the_category() != "NAMEOFMYCATEGORY") { the_category(' | '); } ?>
Or would I need to work with a new function?
To clarify: I want to HIDE 1 specific category so it doesn't show up.
|
This should work:
<?php
foreach (get_the_category() as $category) {
if ( $category->name !== 'FORBIDDEN CATEGORY NAME' ) {
echo '<a href="' . get_category_link($category->term_id) . '">' .$category->name . '</a><br />'; //Markup as you see fit
}
The name is Caps sensitive.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 1,
"tags": "php, wordpress, categories"
}
|
Mixing HQL with criteria
As far as I can tell there are a number of ways to access data in nhibernate; HQL, Criteria, linq to nhibernate and raw sql.
Is it possible in nhibernate to mix the query technoligies when accessing a data source. For example having a where clause as a (detached) criteria and the select or join as a HQL? Or any other combination of the above.
|
The current preferred technologies are `Linq` and `QueryOver`, internally they map respectively on `HQL` and `Criteria`. You can use the one you feel more indicated in a project without any particular drawback, but of course you can't mix them in a single statement, ie you can't append a QueryOver to a Linq statement and vice-versa.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "c#, nhibernate"
}
|
Calculate sum of time in JavaScript
I have records in mongodb, time are string.
**Time**
00:10:40
00:40:10
01:10:20
00:43:40
00:42:40
00:30:40
00:54:10
00:47:40
00:50:40
01:05:40
00:45:40
00:51:40
00:36:40
how to calculate sum of whole times?
|
Is your time strings in an array?
You can use something like this:
var hours = 0;
var minutes = 0;
var seconds = 0;
var sum = '';
var myArray = ["01:40:40","03:50:50"];
var myFunction = function(){
for(var i in myArray){
hours += parseInt(myArray[i].substring(0, 2))
minutes += parseInt(myArray[i].substring(3, 5))
seconds += parseInt(myArray[i].substring(6))
}
if(seconds > 59){
minutes += parseInt(seconds / 60);
seconds = parseInt(seconds % 60);
}
if(minutes > 59){
hours += parseInt(minutes / 60);
minutes = parseInt(minutes % 60);
}
sum = hours + ":" + minutes + ":" + seconds;
console.log(sum);
}
myFunction();
Feel free to ask if you have any other questions.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "javascript, node.js, mongodb, datetime, time"
}
|
MS SQL Server: Check to see if a user can execute a stored procedure
How can you check to see if a user can execute a stored procedure in MS SQL server?
I can see if the user has explicit execute permissions by connecting to the master database and executing:
databasename..sp_helpprotect 'storedProcedureName', 'username'
however if the user is a member of a role that has execute permissions sp_helprotect won't help me.
Ideally I'd like to be able to call something like
databasename..sp_canexecute 'storedProcedureName', 'username'
which would return a bool.
|
`fn_my_permissions` and `HAS_PERMS_BY_NAME`
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 9,
"tags": "sql, sql server, sql server 2005, tsql, stored procedures"
}
|
To open a new page and run a javascript function in that new page
Hi i am trying to open a new page using button click from page 1 and in the page 2 i want to have a popup message using alert . But the alert is executed in my page 1 itself. Please let me know if i am doing anything wrong .
function sendemail(){
alert('success');
var popup = window.open();
window.onload = test();
function test(){
alert('new');
}
}
sndWelcomEmail.addEventListener('click',sendemail);
|
Simply alert the new window not the old one:
function sendemail() {
var popup = window.open();
window.onload = test();
function test() {
popup.alert('new');
}
}
sndWelcomEmail.addEventListener('click', sendemail);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, html, css"
}
|
How to make an html form start a function
I'm wondering if there is an easy way to make a form button with text input start a form that will check if the answer's correct and then proceed to tell you. Here's what I have, can you tell me what I need?
<!doctype html>
<body>
<center>
<form name="Input" action="Answer" method="get">
<input type="text" name="Input">
<input type="submit" value="submit">
</form>
<script type="text/javascript">
var A = Math.floor(Math.random()*11);
var B = Math.floor(Math.random()*11);
var C = A+B;
var Input = document.getElementById('Input');
document.write(A + "+" + B)
function Answer()
{
alert("correct!!");
}
</script>
</body>
</html>
|
function calculateAnswer()
{
var A = Math.floor(Math.random()*11);
var B = Math.floor(Math.random()*11);
var C = A+B;
var Input = document.getElementById('Input');
if(Input.value == C)
{
document.body.innerHTML += (A + "+" + B);
// Or another thing to do if the answer's correct
}
}
Also, attach an event listener to the submit button to make it run the function:
referenceToTheSubmitButton.addEventListener("click", calculateAnswer);
Indent as needed. Enjoy! :D
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, forms, textinput"
}
|
ValueError: Works with IDLE timeformat error in CMD
This works in IDLE but in Command Prompt Ill get this error _" ValueError: time data 'Fri Feb 19 10:00:00 2021' does not match format '%a %b %d %H:%M:%S %Y'"_
file_mtime = time.ctime(os.path.getmtime(matfil))
now = datetime.now()
current_time = now.strftime('%Y-%m-%d %H:%M')
file_time_format = '%a %b %d %H:%M:%S %Y'
current_time_format = '%Y-%m-%d %H:%M'
file_tdelta = datetime.strptime(current_time, current_time_format) - datetime.strptime(file_mtime, file_time_format)
print file_tdelta.seconds
if file_tdelta.seconds < 2700:
|
Ill changed from time.ctime to .strftime and now it works in CMD.
file_mtime = datetime.fromtimestamp(os.path.getmtime(matfil)).strftime("%Y-%m-%d %H:%M")
now = datetime.now()
current_time = now.strftime('%Y-%m-%d %H:%M')
timeformat = '%Y-%m-%d %H:%M'
file_tdelta = datetime.strptime(current_time, timeformat) - datetime.strptime(file_mtime, timeformat)
print file_mtime
print current_time
print file_tdelta.seconds
#Körs bara om filens datum är nyare än 45 minuter sedan.
if file_tdelta.seconds < 2700:
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, python 2.7, datetime format, python datetime"
}
|
LXC: Can I guarantee a certain level of CPU resources to a given container
We're going to use LXC to multi-purpose our hardware while keeping the various applications easy to manage, develop, upgrade, and logically segregated.
What I want to know is if I can **guarantee certain resources** , such as CPU, **to a certain container**.
We have one process which will run in its own container that is a critical component of our application infrastructure. I'd like to dual purpose that box and let a non-critical, but resource-intensive, component (the worker node) reside in a separate container on the same hardware, but to be safe I want to guarantee that, when the critical component needs CPU, it gets it, at the expense of the non critical component.
I'd rather do this at the container level rather than jury-rigging the application with `nice` or something like that because this configuration is only valid on one piece of hardware, on other boxes the worker node stands alone.
|
After a few days further research... cgroups!
This video from Red Hat sums it all up brilliantly. Now get it implemented!
<
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 1,
"tags": "architecture, lxc, container"
}
|
Why tausend (not dausend)?
Why are
**th** ree **d** rei
**th** ou **d** u
**th** orn **D** orn
**th** in **d** ünn
**th** en **d** ann
but
**th** ousand **t** ausend?
|
Indo-European *t normally becomes *Þ in proto-Germanic and then /d/ in High German. You have cited some examples for this. But thousand/tausend is an exception. In Old High German we have both the expected dūsunt and the unexpected tūsent. This variation is an example of “Notker’s Anlautgesetz”, which (simply put) stipulates that initial voiced stops b, d, g become voiceless if they are preceded in close junction by a word ending in a voiceless consonant. In this case, compounds like (the ancestor of) “fünf tausend”, “sechs tausend” have their /t/ by assimilation to the preceding voiceless consonant. The form with t- then gets generalised in all contexts.
|
stackexchange-german
|
{
"answer_score": 6,
"question_score": 0,
"tags": "english to german, german to english"
}
|
How to select a selected element in jquery?
$('#something').click(function() {
//select the same element that was clicked and slide it down
});
Is it possible in jquery to select the same element that the function is working with without actually slecting it again?
|
That should work. The rest is plain css. If you talk about scrolling, you can achieve this with some Javascript.
$('#something').click(function() {
//select the same element that was clicked and slide it down
$(this).toggleClass('slideMeDown');
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "jquery"
}
|
Windows Forms: How to display multiple values in a column
I have a situation where in I have to display data in tabular form with each cell having multiple pair of values,list of values as show below
Column1 Column2 Column3
1 v1 v2 vl1
vl2
vl3
2 v3 v4 vl4
vl5
vl6
How can I do this using windows forms.
Any help is greatly appreciated.
Thanks JeeZ
|
Have you tried setting the wrapmode for the column to allow for '\n'? Here's a quick example that seems to yield the format you posted above.
dataGridView1.Columns.Add("Column1", "Column1");
dataGridView1.Columns.Add("Column2", "Column2");
dataGridView1.Columns.Add("Column3", "Column3");
//this is the key line...to allow \n in column
dataGridView1.Columns[2].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView1.Rows.Add(new object[] { 1, "v1 v2", "vl1\nvl2\nvl3" });
dataGridView1.Rows.Add(new object[] { 2, "v3 v4", "vl4\nvl5\nvl6" });
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, winforms"
}
|
Why is the code showing NameError for the following code
from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x,y: x*(1/2**li.index(x))) + y*(1/2**li.index(y)) , li)
print(sum)
Error that is being shown is NameError: name 'y' is not defined
|
First, you should not override sum as it is a builtin, but the problem is not there. The problem is with the parentheses. You close the lambda parenthesis before the plus sign. You can try something like that:
reduce(lambda x,y: x*(1/2**a.index(x)) + y*(1/2**a.index(y)), li)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python 3.x, reduce"
}
|
Possible to selected item in listView1 is selected in listView2? c#
Just wondering if it is possible to select the same item in `listView2` like the item in `listView1` is selected? So that the user don't have to select the same item twice. Just for usability :) I'm programming in c#
|
Handle `ItemSelectedChanged` of ListView1`
private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
foreach (int item in listView1.SelectedIndices)
{
if (listView1.Items[item].Selected)
{
listView2.Items[item].Selected = true;
tabControl1.SelectedIndex = 1;
listView2.Select();
}
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, listview"
}
|
Does z3's SAT solver obtain a complete assignment before doing a theory consistency check?
Does z3's SAT solver(s) obtain a complete assignment to the propositional(ized) part of an SMT problem before doing a theory consistency check? In particular, I am curious to know what is done by default for each of the following background theories/combination (if this is theory-dependent): Linear Real Arithmetic (LRA), Linear Integer Real Arithmetic (LIRA), Non-Linear Integer Real Arithmetic (NIRA)? Also, where in the actual code (codeplex stable z3 v4.3.1) is a propositional literal (heuristically) decided by the SAT solver?
|
No, Z3 does not obtain a complete assignment before doing theory consistency checks. However, it delays "expensive" checks. "Expensive" checks are performed in a step called `final_check` that is performed only when a (complete) proprositional assignment is produced. Here the word "expensive" is relative. Linear real arithmetic consistency checks can be quite expensive due to big number arithmetic computations, but they are considered "cheap" in Z3.
Linear real arithmetic checks are done eagerly. Nonlinear and linear integer arithmetic checks are done at the `final_check` step.
Note that Z3 contains more than one solver. The behavior above is for the one implemented in the directory `smt`. The nonlinear real arithmetic solver (`nlsat` directory) works in a completely different way, and it does not use the `final_check` approach described above.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "z3, smt"
}
|
Using brackets with Harvard Referencing Style in biblatex
I'm new to using LaTex. I'm trying to put references in the Harvard style. So far I have managed to get the reference right. Below is my code:
\documentclass{article}
\usepackage[backend=bibtex,style=authoryear]{biblatex}
\bibliography{export}
\begin{document}
My Name is Mary \textcite{6824747}
\printbibliography
\end{document}
My export.bib file looks like this:
@online{6824747,
title = "Computational Modeling",
url = "
urldate = "2015-08-31",
year = "2013",
month = "07"
}
Below is how my reference looks like **. Any help is appreciated.
|
You can use `\parencite` instead of `\textcite`. In this particular case `\autocite` also works. See the `biblatex` documentation for the list of available citation commands. The example below also demonstrates `\footcite`.
 : name(name) {}
std::string const& getName() const {
return name;
}
private:
std::string name;
};
int main(){
// std::vector<int> ar = {1,2,3};
std::vector<Person> persons = {"John", "David", "Peter"};
}
I am getting error:
could not convert ‘{"John", "David", "Peter"}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<Person>’
So why vector of `int`s is enabled to brace-initialize, but custom class with implicit constructor (with `std::string`) cannot? And how to enable it?
|
You just need more braces:
std::vector<Person> persons = {
{"John"}, {"David"}, {"Peter"}
};
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "c++, constructor, stdvector, list initialization"
}
|
In Tensorflow, what is the difference between a Variable and a Tensor?
The Tensorflow documentation states that a `Variable` can be used any place a `Tensor` can be used, and they seem to be fairly interchangeable. For example, if `v` is a `Variable`, then `x = 1.0 + v` becomes a `Tensor`.
What is the difference between the two, and when would I use one over the other?
|
It's true that a Variable can be used any place a Tensor can, but the key differences between the two are that a Variable maintains its state across multiple calls to run() and a variable's value can be updated by backpropagation (it can also be saved, restored etc as per the documentation).
These differences mean that you should think of a variable as representing your model's **trainable parameters** (for example, the weights and biases of a neural network), while you can think of a Tensor as representing the data being fed into your model and the intermediate representations of that data as it passes through your model.
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 11,
"tags": "python, tensorflow"
}
|
scraping the text from source code using python
I'm trying to scrape google search results using python and selenium. I'm able to get only the first search result. Here is the code I'm using.
driver.get(url)
res = driver.find_elements_by_css_selector('div.g')
link = res[0].find_element_by_tag_name("a")
href = link.get_attribute("href")
How can I get all the search results?
|
Try to get list of links (from first page only. If you need to scrape more pages, you need to click "Next" button in a loop and append results from following pages) as below:
href = [link.get_attribute("href") for link in driver.find_elements_by_css_selector('div.g a')]
P.S. You also might use solutions from this question to get results as GET request response with `requests` lib
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python 2.7, selenium, web scraping"
}
|
can i apply quota on non partitioned /home drive RHEL7
I am having one RHEL 7 installed machine with following xfs partitions.
1. /
2. /swap
3. /boot
i did not create /home drive while creating partitions.
now i want to apply quota and not able to fine entries for '/home' drive in fstab file.
/home is resides in / (root) directory
please guide me how can i apply quota.
Aneesh
|
As it states in RHEL 7 documentation (< Disk Quotas are enabled on a filesystem, not on a folder inside a filesystem.
So, if you want quotas on only /home, then it needs to be its own partition/filesystem. If you want to avoid showing /home is fstab, but still have quotas, then you need to enable quota on the partition that contains it (/ in this case).
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linux, hard drive, centos7, rhel7, quota"
}
|
CNAME point subdomain to another domain
I know this has been asked before in various forms, but I've tried all the suggestions and had no luck (or maybe skills).
I am trying to point a subdomain (mail.abcd.com) to Rackspace's hosted Webmail service for a client.
My understanding is I should be able to set up cname for the subdomain and point it to rackspace's hostname: apps.rackspace.com
I have set up the following cnames:
www.mail IN CNAME apps.rackspace.com
autodiscover IN CNAME autodiscover.emailsrvr.com
mail IN CNAME apps.rackspace.com
I have tried doing dig mail.abcd.com and nslookup but both report that mail.abcd.com is a nonexistent domain.
I have restarted the name server numerous times.
I'm sure I must be missing something silly.
Thanks for any help!
Cheers
|
A few observations:
The name servers are reported as `ns1.onkea.com` and `ns2.onkea.com`. This is where you need to make the changes. You should need to restart the name server, only reload the zone.
Your `CNAME` entries should end in a period (apps.rackspace.com.). Otherwise, they should be interpreted as ending in (.abcd.com.) giving the address apps.rackspace.com.abcd.com instead of what you intend.
Redirecting `mail` when you have existing `MX` records pointing elsewhere doesn't seem to be very useful. If you are sending email to the Internet using these names, it will appear spamish. Mail will be delivered to the servers specified by the `MX` records.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 1,
"tags": "domain name system, subdomain, cname record"
}
|
jquery getScript data
<script>
$.getScript("javascriptfile.js", function(data ){
alert("Script loaded and executed."+data);
});
</script>
data return undefined. I want to get the response data or content of javascriptfile.js
tested below not working
$.getScript(" function(data){
alert("Script loaded and executed."+data);
});
|
There's a problem
//This one will NOT work
$.getScript("
function (data) {
alert("Script loaded and executed." + data);
});
//This one will work
$.getScript("js/jquery.min.js",
function (data) {
alert("Script loaded and executed." + data);
});
`$.getScript()` doesn't provide content of the script file if you are making a cross origin request outside of your domain.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "javascript, jquery"
}
|
How to find limit of $\sum\limits_{k = 1}^{n - 1}(1 + \frac{k}{n})sin\frac{k\pi}{n^2}$
How to find limit of $\sum\limits_{k = 1}^{n - 1}(1 + \frac{k}{n})sin\frac{k\pi}{n^2}$
What i should to do then see sums like this?
|
Using Taylor Lagrange inequality we have
$$\left\vert\sin\left(\frac{k\pi}{n^2}\right)-\frac{k\pi}{n^2}\right\vert\le \frac{M}{n^3}$$ so with this inequality we prove that the desired limit is equal to
$$\lim_{n\to\infty}\frac1n\sum_{k=1}^{n-1}\left(1+\frac kn\right)\frac{k\pi}n=\int_0^1(1+x)\pi xdx$$ using the Riemann sum.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "summation"
}
|
What is that "New contributor" icon supposed to be?
I read through most of this thread but found no answers.
What is this?
 {echo 'selected="selected"';}?>>10</option>
<option value="20" <?php if($value == '20') {echo 'selected="selected"';}?>>20</option>
<option value="50" <?php if($value == '50') {echo 'selected="selected"';}?>>50</option>
`$value` is a variable which comes from PHP codes. This methods seems to be very simple and naive. Is it the best way to do so?
|
Not a bad way to do it. But why not create the entire thing using programmatic approach (i.e., generate the code using a PHP loop through an array):
$items = array(10, 20, 50);
for ($i = 0; $i < count($items); $i ++) {
echo("<option value='" . $items[$i] . "'");
if ($items[$i] === $value) {
echo(" selected='selected'");
}
echo(">" . $items[$i] . "</option>");
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, html, forms"
}
|
Copy cms page and create many for different stores
Requirements: I have to display same CMS page for different site so I have to create copies of 1 cms pages to display for other store-views. Is there any method to copy 1 cms page like we can do copy product to create duplicate products?
|
As far as I know you can't use one CMS page for different store views in Magento. Instead you should have different CMS pages for each store view.
And unfortunately it's not possible to duplicate CMS pages in Magento. But there are bunch of extensions which can do the job for you. Below are some of those extensions.
< <
Hope this helps.
|
stackexchange-magento
|
{
"answer_score": 2,
"question_score": 0,
"tags": "magento 1.9, cms"
}
|
Query classnames of checked items as array?
I have many checkboxes on a page, like this:
<input type="checkbox" id="cb_31" class="observedType1">
<input type="checkbox" id="cb_32" class="observedType1" checked="checked">
<input type="checkbox" id="cb_33" class="observedType1">
<input type="checkbox" id="cb_40" class="observedType2" checked="checked">
I then wanted to retrieve the classes of all checked boxes in an array (ideally as a list of unique items), so I'm looking to for `['observedType1'l'observedType2'].`
My best idea was: `var clss=$("[class*='observedType']:checked").attr("class");` but that only gives me a string "`observedType1`".
How can I get the array I am looking for? (or a "list" to walk through in a loop)...
There's also a fiddle
|
You need to iterate all the `:checked` checkboxes, here you can use `.map()`
var clss=$("[class*='observedType']:checked").map(function(){
return $(this).attr('class')
}).get();
Updated Fiddle
* * *
I would recommend you to use custom `data-*` prefix custom attribute to store the arbitrary data.
<input type="checkbox" id="cb_31" class="observedType" data-type="observedType1">
Which can be retrieved using `.data()` method
var clss = $(".observedType:checked").map(function() {
return $(this).data('type')
}).get();
With Custom attribute Fiddle
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, jquery, arrays"
}
|
Cannot see sources will debugging on local JBoss server
I have a project producing a `.war` file, I created a local `JBoss 7.1` server in `eclipse` referencing my local `JBoss` installation. Then I start the local server in debug mode, copy my war file to `{JBOSS_HOME}\standalone\deployments`, and it deploys it correctly.
But when I add a breakpoint in `eclipse`, the code stops like it should, but showing me a "`Source not found`" white page.
How can I link or synchronize the source code to my local server? Thank you.
|
Okay so I solved my problem and it seems pretty obvious now that I found it :
My project is generating a `projectname.war`, and a `projectname-sources.jar`, I just had to deploy also the `projectname-sources.jar`...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, eclipse, debugging, jboss"
}
|
Iframe api state change does not trigger with mdl js
The iframe api onStateChange does not get triggered when mdl js is present.
See codepen . This will not console log state changes , deleting
<script src="
will console log the changes.
|
Based from this link, there was a temporary issue with the iFrame Player API and as a temporary fix, you just need to add the event listener within the `onReady` event:
function onReady() {
player.addEventListener('onStateChange', function(e) {
console.log('State is:', e.data);
});
}
Make sure to remove the `onStateChange` event from the YT.PLAYER constructor (see the jsfiddle).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, youtube api, youtube iframe api"
}
|
iOS Table View Refresh Cell
I followed the advice in the link below to add images to cells in a table view.
Adding Image to Table Cell (iOS)
Is there a way to force refresh a cell i.e. add/remove images or indicators?
|
You can call `[self.tableview reloadData];` on the tableview and refresh the entire table.
Otherwise you can do this to refresh a single cell.
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPathOfYourCell] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
|
stackexchange-stackoverflow
|
{
"answer_score": 63,
"question_score": 21,
"tags": "ios, iphone, objective c, uitableview"
}
|
Matplotlib 3D plot doesn't plot correctly
I'm having a problem trying to plot a series of lines in a 3D plot in MatPlotLib. When I run the code below all the lines are plotted at the last value of y??? Even though y is correctly incremented in the loop. Any Help understanding this would be appreciated. Thanks David
#========== Code Start=================
import numpy as np
import matplotlib
from matplotlib.figure import Figure
import pylab as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
x=np.arange(5)
y=np.zeros(len(x))
for i in range(1,10):
y.fill(i)
z=plt.randn(len(y))
ax.plot(xs=x, ys=y, zs=z)#, zdir='z', label='ys=0, zdir=z')
plt.draw()
print i,len(y),y,x,z
plt.xlabel('X')
plt.ylabel('Y')
plt.zlabel('Z')
plt.show()
#========== Code End=================
|
It looks like y might be pointed to by all plots. So you are passing the reference to y when you execute ax.plot. It is the same reference each time, but the values are changed on each pass. When the plt.show() is executed the reference to y is used and it is now set at 9. So, create a different object for y on each pass with the values you want for that pass:
y = np.zeros(len(x))
y.file(i)
There might be a numpy command that fills with the value you want in one go, but you get the picture.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python, matplotlib"
}
|
Specify port number and content database for a query in marklogic
I am writing few test cases in test server 8062, but my data resides on port number 8060 with a specific content database.Without changing the content db of test server using the admin console, is it possible to specify which port and content db to hit for a specific query? Also I do not want to load the contents of content db to test server db. For e.g. something like:
let $current := (fn:count(cts:uri-match("*.xml*")),(),
<options xmlns="xdmp:eval">
<database>{xdmp:database("prj-content")}</database>
</options>)
|
In MarkLogic the data doesn't "reside" on a port. Rather an app server that's connected to a database listens on a port for HTTP or XDBC requests. You can have many app servers fronting the same database. Testing and administration are two good use cases for more than one app server configured for a database.
Your test server (port 8062) should specify your `prj-content` database. What is its current database configuration? Why is that different than `prj-content`. If you do that, you won't have to specify the database at runtime.
If you really do need to specify the database at runtime you can use xdmp:eval, xdmp:invoke, or xdmp:invoke-function.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "xquery, marklogic"
}
|
How to insert generated list at the beginning of the result list?
I have one list like `list<T> result;` and in for loop I generate another list in every pass like
list<T> result;
for(int i=0;i<10;i++){
list<T> temp=generated_list();
// here I want to add at the beginning of the result list values from temp list
}
How to insert generated list at the beginning of the result list ? Is there better way than a loop or creating new by concatenation and then set result to result list ?
|
`std::list<T>::splice` member function is most effcient way to do what you want to
list<T> result;
for(int i=0;i<10;i++){
list<T> temp=generated_list();
result.splice(result.begin(), temp);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "c++, stl"
}
|
Can't make app: ... attributes to work in xml file
I'm looking for an optimal way to resize wrapping text in a TextView so that it will fit within Width.
I am referring to this Thread: Here is official Android Dev page
The problem I have app:attributes does not work even though i added implementation in gradle file. Error: "Namespace 'app' is not bound"
Here are is XML code fragment
app:autoSizeMaxTextSize="50sp"
app:autoSizeMinTextSize="12sp"
app:autoSizeStepGranularity="2sp"
app:autoSizeTextType="uniform"
And here is my gradle file
implementation 'com.android.support:support-compat:28.0.0'
|
You have to provide `xmlns:app=" in the Parent Layout. Then you can use the `app:attributes`. Refer this answer and first comment on the answer and Gradle file error shows clearly your using androidx and trying to import android version 28 library
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "android, xml, kotlin, android gradle plugin, build.gradle"
}
|
is it possible to detect viewport width and write to mysql in jquery and then retrieve width in php without page reload
thanks for reading...
It is my understanding (which my be wrong) content hidden with css loads but is kept hidden. Rather than using media queries to toggle hidden/visible content depending on the device, I was wondering if it is possible to use jquery on the page load to get the viewport width... and then write the width to mysql... and then retrieve the width with php on the same page without a page re-load.
If so, how would the jquery be written?
Thanks in advance for taking the time to read, Pete
|
**My Found Solution:**
After spending the day yesterday testing and trying different approaches I found this plugin this morning which solved my problem.
The goal was to prevent the loading of hidden code depending on viewpoint size. My original programming used toggles shown/hidden by media queries. Use of the Mobile Detect plugin allows the use of php if statements depending on device. A recommended plugin for sure.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, jquery, mysql, css"
}
|
Rails How to find record when searching on association of association
I have three tables: `users`, `cars`, and `mechanics`.
associations:
* user has_many cars, car belongs to user
* car belongs_to mechanic, machanic has_many cars
I want to find users with cars repaired by a specific mechanic, so I'm doing something like this:
`User.joins(:cars).where('cars.color = ? AND cars.type = ? AND cars.mechanic.name = ?', 'green', 'estate', 'paul')`
The trick is that I don't know how to write this `cars.mechanic.name` part.
|
User
.joins( :cars => :mechanic )
.where( :cars => {:color => "green", :type => "estate"},
:mechanic => {:name => "paul"} )
Try this may be this will work.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ruby on rails, activerecord"
}
|
Stop caching for a specific node (by nid) Drupal 7
Ideally i want to set custom params for caching in some particular nodes using conditions in my **template.php**
**_E.g. algorithm:** for node with known **nid** set custom caching params_
But that's enough for my purpose simply exclude from caching particular node. I fond this solution: Stop caching for a specific node type Drupal 7 this is exacly what im looking for but how i can change condition of checking from node type to nid.
I know about CacheExclude module, but for me unwanted to install module for just exclude one node for caching.
I'll be very grateful for helping me.
|
A module with the below in it should stop caching on node 2. Change the number to do it on a different node id.
function MYMODULE_init(){
if (arg(0) == 'node' && arg(1) == 2) {
drupal_page_is_cacheable(FALSE);
}
}
|
stackexchange-drupal
|
{
"answer_score": 0,
"question_score": 1,
"tags": "theming, caching"
}
|
Excel Persistent Window
I would like to display a form invoked from a button within Excel like a messagebox i.e. always on top and persistent until it is dismissed.
So, far I am using
Form frm = new Form();
frm.TopMost=true;
This only keeps the window on top but user could still click around the worksheet.
|
This should do it: `frm.ShowDialog();`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, excel"
}
|
Why can we not post asking for resources for learning on Stack Overflow?
So I asked this question on Stack Overflow asking for some resources to start learning Retrofit. I had a feeling I was going to get some negative responses saying that this is not a specific question, this site is not for these questions, etc. It seems like people on Stack Overflow do not like these "where should I start?" style posts.
Stack Overflow represents the congregation of programming knowledge. Knowing where to start as a budding developer is an important first step in learning something new. I guess I just want to open up discussion about these kind of posts:
1. Why are they frowned upon?
2. What's wrong with letting people post these types of questions?
3. How is it a detriment to Stack Overflow?
|
The reason they are frowned upon is because, by virtue of being third-party resources, Stack Overflow has no control over them and therefore cannot guarantee their availability, reliability or currency. An answer becomes useless the moment a link breaks and the information is no longer retrievable (archive notwithstanding). Furthermore, such questions can and do attract spam answers.
The mission of SO is to build a central programming knowledgebase. The best way to ensure that this knowledge remains available for as long as SO continues to exist, is to host it on the site itself (and even in the unlikely event of SO itself going under for some reason, we have data dumps of all our content so not all will be lost). Questions whose answers simply consist of links to other resources over which we have no control run foul of this mission.
|
stackexchange-meta_stackoverflow
|
{
"answer_score": 17,
"question_score": -6,
"tags": "discussion"
}
|
Chrome Developer Tools, using inspection functions inside script tags
I've looked around on google and I cannot figure out to use for instance the dir() function within the web page I'm working on, I would like to have it spit out debug statements, as I'm used to doing with Firebug.
A clearer example
What I want is to do the following.
<script>
a=document.getElementById('gabber');
dir(a);
</script>
However doing this gets an undefined error.
|
console.dir works for me:
console.dir(document.getElementById('foo'));
You can see all the functions available on the console like this:
for (var n in console) {
if (typeof console[n] == "function") {
console.log(n);
}
}
(I get the following on Chrome 5.0.322.2:)
debug
error
info
log
warn
dir
dirxml
trace
assert
count
markTimeline
time
timeEnd
group
groupEnd
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 3,
"tags": "javascript, debugging, google chrome"
}
|
How to make class or module just for import/export job ( classes )
Explanation (in some class i want to import more classes) Look like this :
import myClass1 'pathto1';
import myClass2 'pathto2';
import myClassn 'pathton';
I want simple to make bypass with one file ( class export ) : To be like this (in one line):
import AllMyClasses 'pathToLib';
What is the best look for that file ?
|
If you write your "bypass" file like this:
import { MyClass1 } from './path/to/one';
import { MyClass2 } from './path/to/otwo';
import { MyClass3 } from './path/to/three';
export { MyClass1, MyClass2, MyClass2 };
You can then import all of these classes in another file like this:
import * as AllMyClasses from '/path/to/bypass/file';
const m = new AllMyClasses.MyClass1();
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "typescript"
}
|
Comparison without deriving Ord
My prof asked us to implement bubble sort in Haskell. The problem should be easy, however, he specified the function signature like this
bsort :: (a -> a -> Bool) -> [a] -> [a]
bsort = undefined
The problem is that a is not deriving `Ord`, so I have no idea how to compare `a`s. So I wonder if this is doable or he forgot to add `(Ord a) =>`?
|
Yes, it is doable, no he did not forget. Here's a hint:
bsort (<=) = undefined
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 1,
"tags": "haskell, functional programming, higher order functions"
}
|
missing parameter type for `_`
I'm trying to sort a list by how close the entries of a list are to num.
I decided to try use `sortWith`, but the following snippet:
list.sortWith(math.abs(_ - num) < math.abs(_ - num))
failed with missing parameter type for `_` in scala. list is of type `List[Int]`.
Following the other threads, I know that `_` is somehow type ambiguous, but I'm not sure why, (and why the following snippet is not type ambiguous):
scala> val sortedDudes = dudes.sortWith(_.name < _.name)
sortedDudes: Array[Person] = Array(Al, Paul, Tyler)
(Source)
|
def foo = {
val num = 2
val list: List[Int] = List(1, 2)
list.sortWith((a, b) => math.abs(a - num) < math.abs(b - num))
}
work perfectly. It's because scala trying get `_` from `math.abs`, not `sortWith`
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "scala"
}
|
Inputting variable name into functions
I'm pretty new to Go, and I'd like to make this snippet into a function.
Basically, I would like to know if there is a possible way to pass a variable name into a function call so if I called:
`changeColor(varName) `
It would run, and then assign a new value to the original variable, which was inputted into the function call.
Hopefully this makes sense, and thanks in advance
if varName == yellow {
varName = black
} else {
varName = yellow
}
|
You can learn about the concept in general by reading up on different Evaluation Strategies that programming languages employ. In Go you can achieve the behavior you are looking for with pointers.
Without pointers you are usually passing around copies of your variable. With pointers, you are passing a copy of the _location_ of the value in memory. This means the function can then modify the actual value at the location is has learned about.
Here is an example that does what you explained:
<
Keep in mind this is probably not the best way to do this in a real program. If the point is to just learn though, then go for it. Try playing around with passing pointers to pointers and so on :p
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -3,
"tags": "go"
}
|
What is a simple book summarizing Cartesian philosophy?
I know a bit of French, so I can read Descartes' work directly, but I would prefer to start with a simple book which summarizes descartes' philosophy.
|
Descartes is one of few European philosophers whom one can read without any introduction from the secondary literature. Hence I recommend to start studying Descartes by the primary sources. You get a fresh impression of his thinking and you can form your own opinion:
* Discours de La Méthode
* Meditationes de prima philosophia
At most, a short survey of his life would be helpful: When and where did he live? His education at La Flèche, his move from France to the Netherlands and finally to Stockholm.
Concerning the discussion of Descartes' thoughts: The full edition of the meditations contains six objections from his fellow philosophers together with Descartes' reply.
And to answer your original question, e.g., _Cottingham, John (Ed.): The Cambridge Companion to Descartes._ (1992)
|
stackexchange-philosophy
|
{
"answer_score": 4,
"question_score": 3,
"tags": "reference request, descartes"
}
|
adding infinites fragments?
I'm using working to build my app and I have come to a situation here.
I have a `fragment` "product" with the name and price of the product so, when the user clicks on "buys" or sells" he will see a list of `fragments`.
I would like to add as `fragments` as products has the DB but all I have seen is that I need a `<FrameLayout>` per `fragment`. Is there a way I can do this dynamically from the code?
Thank you, Alvaro.
|
1. Yes you can add fragment dynamically with code.
2. Are you sure that Fragments are what you want ? The way I uderstand what you are saying, I think that you need to show a list of Views.
A View is something which will show informations and can listen for user inputs (like touch input). It's pretty simple to manage.
A Fragment is something way more complex which can contain a view but is much more powerful and heavy (both in term of performance and in term of code complexity). Quite usually a Fragment will represent the whole screen of an application.
So take a look at Views and at what they can do, then take a look at ListViews to see how you can dynamically take data from your database and print it with it.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "android, android fragments"
}
|
Use Obfuscar for publishing applications
I am able to obfuscate a .dll in my visual studio solution upon running it. . -->
<Exec Command="COPY $(ProjectDir)$(IntermediateOutputPath)Protected\$(TargetFileName) $(ProjectDir)$(IntermediateOutputPath)$(TargetFileName)" />
</Target>
This allowed me to change the dll file on publish.
Thanks everyone for helping me solve this. I really appreciate it!
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, visual studio, .net core, obfuscation, obfuscar"
}
|
View Excel file using Activex Control
I want to view excel file in my windows application which I am trying to build using visual studio 2010.
How can I do this ?
Is there any excel activeX control for this.
Suggestion are warmly welcome....
Please Help
|
Use WebBrowser control to preview Excel file in Windows Forms application.
Samples:
* How to Integrate Excel in a Windows Form Application using the WebBrowser
* How to use the WebBrowser control to open Office documents in Visual C#
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, visual studio 2010, excel, activex, activexobject"
}
|
Get high resolution for bitmap fonts under pdflatex?
I’m using the Boisik font/package, which is not available as Type 1 and so (unless I’ve missed something) is only able to produce bitmapped fonts in the pdf output. By default, the resolution of these is fairly low.
Using a `latex` → `dvips` → `ps2pdf` workflow, I can at least make sure the generated bitmaps are high resolution, by invoking `dvips` with an option like `dvips -D 2400` (as suggested in the Boisik documentation).
Is there any way to do this while using `pdflatex`?
|
The parameter to set is `\pdfpkresolution` that TeX Live (and MiKTeX, I believe) sets to 600 (dpi).
It can be set in the document by
\pdfpkresolution=2400
There is also a token register `\pdfpkmode` that chooses the Metafont mode for creating the bitmaps, if non empty:
\pdfpkmode={supre}
The `supre` mode is found in `modes.mf` and is for a 2400 dpi printer (but it may be not the right one for yours.
|
stackexchange-tex
|
{
"answer_score": 8,
"question_score": 8,
"tags": "fonts, pdftex, resolution"
}
|
Make $f(x)=\sin x-\frac{x+ax^3}{1+bx^2}$ be the infinitesimal of the highest order
Here is the question:
> Find $a$ and $b$, letting $$f(x)=\sin x-\frac{x+ax^3}{1+bx^2}$$ be the infinitesimal of the highest order when $x \to 0$, and find that order.
According to the key, $a=-\frac{7}{60}$, $b=\frac{1}{20}$, and the highest order can be reached is $7$.
I have used the Maclaurin expansion of $\sin x$, but I cannot understand how can things like $-\frac{x^3}{3!}$ and $\frac{x^5}{5!}$ be cancelled. It seems what we have is just $\frac{x+ax^3}{1+bx^2}$ and its highest order is only 1.
|
The Maclaurin expansion of $\sin x$ is, as you know, $x - x^3/6 + x^5/120 - x^7/5040 + \cdots$.
You want to choose $a$ and $b$ so that the Maclaurin expansion of $(x+ax^3)/(1+bx^2)$ matches this for as many terms as possible.
You wouldn't want to find that expansion by differentiating repeatedly, but you don't have to - rather you can just write out the denominator as
$$ {1 \over 1+bx^2} = 1 - bx^2 + b^2 x^4 - b^3 x^6 + \cdots $$
and multiply out:
$$ \left( x + ax^3 \right) \left( 1 - bx^2 + b^2 x^4 + \cdots \right) = x + (a-b) x^3 + (b^2 - ab) x^5 + \cdots $$
so now you want to find $a, b$ such that $a-b = -1/6, b^2-ab = 1/120$. These turn out to be the values of $a$ and $b$ that are given in the key.
But if you try to do this matching the $x^7$ terms as well, you'll find that the resulting system of three equations in two unknowns has no solution. So this is the best you can do.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "calculus, taylor expansion, infinitesimals"
}
|
Why are SQL servers not attacked as frequently as ssh servers?
I have a server running with both SSH and MySQL accessible to the public internet. Both run on default ports (22 and 3306).
The ssh server is attacked by bots all the time. This is the output of `fail2ban-client status sshd` after about two weeks:
Status for the jail: sshd
|- Filter
| |- Currently failed: 1
| |- Total failed: 1491
| `- File list: /var/log/auth.log
`- Actions
|- Currently banned: 697
|- Total banned: 697
The log for the MySQL server after the same time:
Status for the jail: mysqld-auth
|- Filter
| |- Currently failed: 0
| |- Total failed: 3
| `- File list: /var/log/mysql/error.log
`- Actions
|- Currently banned: 1
|- Total banned: 1
Why is the MySQL server not also attacked? Are attackers simply not interested in database access?
|
Because:
1) Most RDBMS (including MySQL) don't instrinsically support client connections or access to a shell to start a new client (limiting malware's ability to spread)
2) Most people don't expose their DBMS on the internet
|
stackexchange-security
|
{
"answer_score": 3,
"question_score": 1,
"tags": "attacks, ssh, brute force, mysql"
}
|
JavaScript Calculation Help (Multiplying Time)
I have some code that I was using to generate a calculation from two inputs but am having trouble generating the result I need.
I have two inputs (let's call them input1 and input 2). When you enter in a value, it calculates it based on the following:
**(input1 x 0.156$) x ( (input2 x 15 seconds) x 4.2) x 12 months**
My original code is as follows:
var calculation = function() {
var input1 = document.getElementById('people').value;
var input2 = document.getElementById('stories').value;
var result = Math.floor(input1 * 0.2 * input2 * 30);
document.getElementById('result').innerHTML = result;
return false;
}
It's the var result that I'm having difficulty changing (the code above was for a different calculation). Any help would be greatly appreciated!
|
It looks to me that you are not implementing your formula correctly, try changing it to:
var result = Math.floor((input1 * 0.156) * ((input2 * 15)*4.2)*12);
It also will be good to tell us what 4.2 stands for.
Here's a working JSFiddle
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
}
|
How to install TPC-E EGen using gcc 4.8 (or above)?
I am stuck with the installation of TPC-E EGen on Mac OS X (or Linux). I have downloaded the workload generator from TPC website : www.tpc.org/tpce/egen-download-request.asp but I failed to build it.
When using the following command for building the utilities:
cd Utilities/prj/GNUMake/
make
I receive the following error:
../../prj/GNUMake/Makefile.EGenUtilities:136: ../../obj/DateTime.d: No such file or directory
../../prj/GNUMake/Makefile.EGenUtilities:136: ../../obj/EGenVersion.d: No such file or directory
../../prj/GNUMake/Makefile.EGenUtilities:136: ../../obj/error.d: No such file or directory
../../obj/locking.d:3: *** missing separator. Stop.
which is not a meaningful error and does not help in how to resolve the issue.
Any help or hint would be appreciated.
|
I found the problems:
1- in EGenStandardTypes.h, I had to replace
\#if defined (__unix) || (_AIX)
by
\#if defined(unix) || defined(\__unix__) || defined(\__unix) || defined(\__APPLE__) && defined(\__MACH__) || (_AIX)
in order to make this part of code work for Mac OS X as well.
2- in DateTime.cpp and error.cpp
I had to comment out `#error` directive usages, as my current version of GCC did not support it.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "database, transactions, benchmarking"
}
|
Excel Formula - FORECAST, OFFSET, MATCH
I'm working with a workbook that was provided to me. The issue I'm having is that the below formula references a separate table (Cov. & Ded. Factors) and is adding a 4th decimal place to the factor listed in that table.
The table is structured as the following:
Limit Factor
100000 0.867
105000 0.880
110000 0.893
115000 0.907
120000 0.920
125000 0.933
The problem is that if my limit value is 100999, the factor being returned is 0.8696 instead of 0.867. I'm not familiar enough with the functions that were provided to know how to fix it. Any ideas?
=IFERROR(FORECAST($D20,OFFSET('Cov. & Ded. Factors'!$B$4:$B$384,MATCH('Rater v2.1'!$D20,'Cov. & Ded. Factors'!$A$4:$A$384,1)-1,0,2),OFFSET('Cov. & Ded. Factors'!$A$4:$A$384,MATCH('Rater v2.1'!$D20,'Cov. & Ded. Factors'!$A$4:$A$384,1)-1,0,2)),"")
|
There is a round function that you can nest the code in:
=round(IFERROR(FORECAST($D20,OFFSET('Cov. & Ded. Factors'!$B$4:$B$384,MATCH('Rater v2.1'!$D20,'Cov. & Ded. Factors'!$A$4:$A$384,1)-1,0,2),OFFSET('Cov. & Ded. Factors'!$A$4:$A$384,MATCH('Rater v2.1'!$D20,'Cov. & Ded. Factors'!$A$4:$A$384,1)-1,0,2)),""), 3)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "excel, excel formula"
}
|
Conditional probability of two lightbulbs
A box contains four $40$W light bulbs, five $60$W bulbs and six $75$W bulbs.
(a) If two bulbs are randomly selected from the box of light bulbs, and at least one of them is found to be rated 75W, what is the probability that both of them are 75-W bulbs?
(b) Given that at least one of the two selected is not rated 75-W , what is the probability that both selected bulbs have the same rating?
For(a), my solution is below but that was wrong, can you explain why?
P(both $75$W)= $\frac{(6/15)(5/14)}{1-(9/15)(8/14)}$
For(b), the answer of my solution is:
$\frac{(5/15)(4/14)+(4/15)(3/14)}{1-(6/15)(5/14)}=0.178$, is it true?
|
I cannot find a flaw in your solution of (a).
Let $X$ denote the number of $75$-W bulbs that are selected.
Then:$$P(X=2\mid X\geq1)=\frac{P(X=2)}{P(X\geq1)}=\frac{P(X=2)}{1-P(X=0)}$$
Here $P(X=2)=\frac6{15}\frac5{14}$ and $P(X=0)=\frac9{15}\frac8{14}$ which agrees with what you wrote as solution.
Also your answer on (b) is correct.
If $Y$ denotes the number of $40$-W bulbs and $Z$ the number of $60$-W bulbs that are selected and $E$ denotes the event that both selected bulbs have the same rating then:$$P(E\mid X\leq1)=\frac{P(E\cap\\{X\leq1)\\}}{P(X\leq1)}=\frac{P(E\cap\\{X=0\\})+P(E\cap\\{X=1\\})}{1-P(X=2)}=$$$$\frac{P(E\cap\\{X=0\\})+0}{1-P(X=2)}=\frac{P(Y=2)+P(Z=2)}{1-P(X=2)}$$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "probability"
}
|
Does twitter support webhooks for chatbots or should i use Stream API?
I am trying to build a twitter chat bot which is interactive and replies according to incoming messages from users. Webhook documentation is unclear on how do I receive incoming message notifications. I'm using python.
|
Answering my own question. Webhook isn't needed, after searching for long hours on Twitter Documentation, I made a well working DM bot, it uses Twitter Stream API, and StreamListener class from tweepy, whenever a DM is received, I send requests to REST API which sends DM to the mentioned recipient.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, api, twitter, twitter oauth, chatbot"
}
|
batch file breaks when checking if a variable is defined
I am trying to write a batch file to locate a program's install directory.
CALL:get_vsinstalldir InstallDir
echo InstallDir="%InstallDir%"
EXIT /B 0
@REM get the location of the visual studio 2012 installation
:get_vsinstalldir
FOR /F "tokens=2*" %%A IN ('REG.EXE QUERY "HKCU\Software\Microsoft\VisualStudio\11.0_Config" /V "ShellFolder" 2^>NUL ^| FIND "REG_SZ"') DO SET %~1=%%B
EXIT /B 0
This works fine and outputs something like `InstallDir="C:\path to VS\blah"`
But, if I check to see if the `InstallDir` is already defined like this:
if not defined InstallDir (
CALL:get_vsinstalldir InstallDir
echo InstallDir="%InstallDir%"
)
Then, it prints `InstallDir=""`
Why is the `if not defined` statement breaking my batch file?
|
Try enabling delayed expansion, put `setlocal enabledelayedexpansion` at first line, then use exclamation points to verify it's defined or no:
if not defined InstallDir (
CALL:get_vsinstalldir InstallDir
echo InstallDir="!InstallDir!"
)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "windows, batch file"
}
|
Don't understand the difference between $P(a \le X \le b)$ and $P(X\in B)$
By def, $P(a \le X \le b)=\int_a^b f_X(x) dx$ and $P(X\in B)=\int_B f_X(x) dx$.
I think I understand $P(a \le X \le b)$ well enough: it tells you that if $X$ is the random variable that maps the height of someone to $x$, then $P(a \le X \le b)$ asks what's the probability of someone's height, or $x$, being between $a$ and $b$.
$P(X\in B)$ is a lot more confusing. My textbook, Tsitsiklis' _Intro to Probability and Statistics_ , said this is 'the PDF of $X$ for every subset $B$ of the real line'.
I have no idea what that is supposed to mean. Is it just the probability of $x$ being a real number?
The integral also doesn't make much sense to me. I can understand what $\int_a^b$ means - the area under the function between $x=a$ and $x=b$. But $\int_B$ only gives the lower bound...I am sure it doesn't mean the area from $B$ to infinite...so what does it mean?
|
$B$ in the statement $P(X\in B)$ is a **subset** of $\mathbb R$.
In fact, you can rewrite $P(a\leq X\leq B)$ as $$P(X\in [a, b])$$ in which case you can use the second definition to get, $$P(X\in [a, b]) = \int_{[a,b]}f_X(x)dx$$
and, "luckily", measure theory also tells you that
$$\int_{[a,b]}f_X(x)dx = \int_a^bf_X(x)dx$$
so the two definitions are compatible.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "probability"
}
|
Swift ios viewDidLoad, viewDidAppear image control size different
i have noticed that an UiImageView that's set to take full width is not given its correct width before viewDidAppear.
This is a bit problmatic for me because:
* I load in a custom logo graphic that can have any high/width
* This means that to keep scale (and full width) I set a height constraint to match width/height proportions in the .png file
However, I can not get true image width before _viewDidAppear_ \- nor viewWillAppear
Am I missing a stage / tehcnique here (new to xcode/ios/swift) or will I have o maybe make my own calcluations and no rely on retrieving the width of an uiimageview?
|
keep in mind that `viewDidLoad` is called only when your view is loaded and not yet put on a superview, so you still don't know how is it's final frame, it has just the frame you defined in its xib file (if any)
but then you add it in a superview (in many way) and so (following its autoresizingMask) its frame size changes, and you can get them only in `viewDidAppear` method
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "ios, swift, uiimageview"
}
|
Function-like macro definition
The problem is, that I don't quite understand what the following definition does. Can somebody explain it to me?
#define Vpc3MemSet_( _pToVpc3Memory, _bValue, _wLength )\
Vpc3MemSet( _pToVpc3Memory, _bValue, _wLength )
|
Your macro does nearly nothing. It replaces `Vpc3MemSet_` (with underscore) by `Vpc3MemSet` (without underscore). Such macros usually make sense if there are different, platform-dependent variants (say for Linux, macOS, and Windows). For (fictional) example:
#ifdef __WINDOWS__
#define Vpc3MemSet_( _pToVpc3Memory, _bValue, _wLength )\
Vpc3MemSet( _pToVpc3Memory, _bValue, _wLength )
#else
#define Vpc3MemSet_( _pToVpc3Memory, _bValue, _wLength )\
memset(_pToVpc3Memory, _bValue, _wLength * sizeof(Vpc3))
#endif
You can call the platform-dependent function with the same macro call:
Vpc3MemSet_(memory, value, length);
This will expand to different function calls on Windows and Linux.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "function, c preprocessor"
}
|
Why does $\binom{n}{2} = \frac{n^2 - n }{2}$?
In a proof in _Introduction to Algorithms,_ the book says $\binom{n}{2} \cdot \frac{1}{n^{2}} = \frac{n^2 - n }{2}\cdot \frac{1}{n^{2}}$, which implies $\binom{n}{2} = \frac{n^2 - n }{2}$.
Why are these equivalent? Is it a special case of a more general rule?
|
> Is it a special case of a more general rule?
**Yes.** In general, we have that $$ \binom{n}{k}=\frac{n!}{k!(n-k)!} $$ whenever $k\leq n$ and $0$ if $k>n$. You can see here for a more intuitive description of this using a combinatorial argument. In your case, you have $k=2$ (so you truly do have a "special case" of a more general rule). Thus, we have the following; $$\require{cancel} \binom{n}{2}=\frac{n!}{2!(n-2)!}=\frac{n(n-1)\cancel{(n-2)!}}{2!\cancel{(n-2)!}}=\frac{n(n-1)}{2}=\frac{n^2-n}{2}, $$ which is what you wanted to show. Does that clear things up?
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 2,
"tags": "combinatorics, algebra precalculus, binomial coefficients"
}
|
webview onNavigationStateChange returns url of previous page
In react native webview, when I navigate to a page the `onNavigationStateChange` returns `url` of the previous page? I think its an issue and posted it to github react native issues.
<WebView
ref={r => this.webview = r}
style = {{marginTop : 0}}
onNavigationStateChange=
{this._onNavigationStateChange.bind(this)}
startInLoadingState = {true}
source = {{uri: ' }}
/>
_onNavigationStateChange(webViewState)
{
this.setState(
{
youtube_video_url: webViewState.url
})
}
When I print this `youtube_video_url`, it is of the previous page or previous browsed video.
|
Sadly, all the webview methods like onNavigationStateChange, onLoad, onLoadStart etc are not working as expected in cases of single page application websites or websites that don't trigger a window.load event.
Normaly onNavigationStateChange gets triggered in the beginning of a request with {loading: true, url: "someUrl", ...} and once after the loading of the url with {loading: false, url: "someUrl", ...}.
There is no global workaround (to my knowledge) that will work correctly for all websites and for both iOs/Android but maybe this can help in your case:
<
Basically you inject a custom javascript in the webview that notifies the WebView which is the loaded page. You can enhance it if you want to catch custom window.history manipulation events.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "react native"
}
|
Private Windows 10 Enterprise Store
Has anyone out there figured out how to set up private windows stores for easier deployment so that we don't have to do power shell scripts or remote debugging?
|
There will be a business store for Windows 10 integrated in the public store. You will be able to use it as a business customer in the future.
Right now it's not available yet. See screenshot.
 you need to do 3 things. First, find the maximum gain you need. Second, multiply this times the greatest frequency you need, and then multiply this by at least 10. This is called the gain-bandwidth product. Finally, multiply peak voltage times the highest frequency times 2 pi. This is the required slew rate.
Now check that your gain-bandwidth product is less than the op amp gain bandwidth. The reason for the added factor of 10 (or more) is because the op amp needs what's called excess gain in order to provide accurate signal amplification. If the op amp's GBW is OK, check the slew rate requirement against the op amp slew rate.
Finally, you have not specified the load which the op amp must drive. If this is something benign, like an amplifier you should have no trouble. On the other hand, if you're trying to drive a load such as a speaker, you may need to learn about amplifier loading.
|
stackexchange-electronics
|
{
"answer_score": 3,
"question_score": 2,
"tags": "circuit design"
}
|
is there any way to attach an ngClass to a pseudo-class?
I am trying to put a dynamic style on this element:
input[type=range].MPslide.pvd-slider::-webkit-slider-runnable-track{}
Unfortunately it doesn't exist in my template so I can not place an [ngClass] on it. At the moment I am doing this by setting a global CSS variable onInit() but this seems like a workaround. What am I missing? Is there a cleaner way to do this? Thanks for any insights or suggestions!
|
Add a dynamic class on the container of your intended element (the component it's in) and do something like this
// my-component.html
<the-component [class.myClass]="myCondition"></the-component>
and
// my-component.css
:host ::ng-deep .myClass input[type=range].MPslide.pvd-slider::-webkit-slider-runnable-track{
// your dynamic style
}
you can read more about `:host` and `::ng-deep` from Angular style special selctor
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, css, angular, css selectors, pseudo class"
}
|
How to reference cells in a conditional formatting formula rule?
I wold like to use the value of the current cell into to "Custom formula is.." when using conditional formatting.
I would like to enter a "Custom formula", which will check if value of cell is ether'a' or 'b'.
What will be correct syntax?
|
Please try:
Select the range the conditional formatting is to apply to, say C5:C10. Format, Conditional formatting…, Add new rule, Format cells if…, **Custom formula is** :
=or(c5="a",c5="b")
Select your Formatting style (Default may suit) and `Done`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "google sheets, formula, gs conditional formatting"
}
|
How do i color a specific size that i mentioned?
How do i specify a particular size ,example width and height at a particular place and fill it with a specific color?without using any tags like < h1 > or < p >.I mean
width="500" height="200"
and make that area colored? How do i do that ? I have been trying but unable to make it.I made it using < h1 > tags but does it work without using any < h1 > or some other tags? Its necessary for me to make a particular area in my window to be colored without syntax.so Please help me
|
you can use then play with the class you add to it :
<span class="myspan">your text</span>
then in css
<style>
.myspan{
color:blue;
background-color:grey;
width:200px;
height:50px:
font-size:15pt;
}
</style>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, css"
}
|
Replace redundant Code with SP / UDF
I have code:
SELECT Date
,trafficsource
INTO #temp
FROM SomeTable;
That is the first step. The second step is the following code:
INSERT INTO dbo.DimTrafficSource ( TrafficSource, LogInsert )
SELECT DISTINCT fact.trafficSource
,GETDATE()
FROM #temp fact
LEFT JOIN dbo.DimTrafficSource dim ON fact.trafficSource = dim.TrafficSource
WHERE dim.TrafficSource IS NULL
Now, the second step is used in many other stored procedures. To avoid using the same "`hardcoded`" code in them, I'd prefer to replace this functionality with other function / stored procedure so when I want to modify the logic, I want to modify it at one place, not in every stored procedure using this code. Is it possible when there is a temp table used? How?
|
Yes you can. If you switch from a local to a global temp table (## instead of #) it will be available to all SPs you create. The example below demonstrates this.
However I would recommend you switch to regular table. Temp tables can be hard to debug and track. It is not always obvious when they do/don't exist.
Example
/* Temp procedure 1 creates a
* global temp table.
*/
CREATE PROCEDURE #Temp1 AS
BEGIN
SELECT
1 AS x
INTO
##tempT
;
END
GO
/* Temp procedure 2
* can access the temp table..
*/
CREATE PROCEDURE #Temp2 AS
BEGIN
SELECT
x
FROM
##tempT
;
END
GO
/* Excecuting the SPs
* show the temp table is shared.
*/
EXECUTE #Temp1;
EXECUTE #Temp2;
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql server, tsql, stored procedures, sql server 2012"
}
|
order a row by column name of other data frame and match in length
For example you have this data frame :
dd <- data.frame(b = c("cpg1", "cpg2", "cpg3", "cpg4"),
x = c("A", "D", "A", "C"), y = c(8, 3, 9, 9),
z = c(1, 1, 1, 2))
dd
b x y z
1 cpg1 A 8 1
2 cpg2 D 3 1
3 cpg3 A 9 1
4 cpg4 C 9 2
I want to order the column names (b,x,y,z) by a row in another data frame which is:
d <- data.frame(pos = c("x", "z", "b"),
g = c("A", "D", "A"), h = c(8, 3, 9))
d
pos g h
1 x A 8
2 z D 3
3 b A 9
So I want to order the column name of dd with the row d$pos and dd also needs to have the same number in the row d$pos.
I tried with order and match but it did not give me the need result. My dataset is quite large, so something automtic would be ideal.
Thanks a lot for your help!
|
We can do a `match` and then order the columns
i1 <- match(d$pos, names(dd), nomatch = 0)
dd[i1]
# x z b
#1 A 1 cpg1
#2 D 1 cpg2
#3 A 1 cpg3
#4 C 2 cpg4
Or if we want only the columns based on the 'd$pos'
dd[as.character(d$pos)]
# x z b
#1 A 1 cpg1
#2 D 1 cpg2
#3 A 1 cpg3
#4 C 2 cpg4
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "r, row, identity column"
}
|
Model a Rubix Cube in an Array Java
Does anybody have any idea on how to model a rubix cube in an array? I can't seem to think of a way?
|
The source code for this one is available:
Your in luck, it's Java. :)
This paper shows different ways to model the cube -
and another exploratory paper...
<
but a simple answer would be a 3x3x3 array with 3 digits.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java, multidimensional array, rubiks cube"
}
|
How to grant access to AWS Lambda in Python to read external web pages?
I am trying to read an external API using AWS Lambda (written in Python) but it fails. It seems the problem is related to access and permissions.
(module initialization error: HTTP Error 403: Forbidden)
Thanks for your guidance in advance.
from urllib.request import urlopen
url = "
response = urlopen(url)
data = json.loads(response.read())
|
If you are using an https connection, then you should not face any problem. To check if your external API is working, create a new lambda function and try to call API from there. Run tests and post results here. For more reference, please refer to this link Invoking REST API from within lambda function
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "python 3.x, amazon web services, aws lambda"
}
|
Conditional sentences not starting with "if"
> Were I rich, I would live on Long Island.
> If I were rich, I would live on Long Island.
Is the first sentence still used, or is used in particular contexts (in example, to give emphasis to the sentence)?
|
It's rarely used nowadays (in the US at least). It will usually come off as sounding stilted in everyday speech, but possibly more educated/sophisticated in formal speaking and writing (but even then, should probably be used sparingly).
|
stackexchange-english
|
{
"answer_score": 6,
"question_score": 6,
"tags": "word choice, word order, conditionals, subjunctive mood, bare conditional"
}
|
Change multiple div contents based on same classname?
I have unique id's for these but I want to change all div's with class="on" to contents "Goodbye". Is there a way to do this without having to call to each id individually?
**This...**
<div class="on" id="1">Hi</div>
<div class="random" id="2">Hi</div>
<div class="on" id="3">Hi</div>
**...would look like this.**
<div class="on" id="1">Goodbye</div>
<div class="random" id="2">Hi</div>
<div class="on" id="3">Goodbye</div>
|
Try `.html()`:
$('.on').html('Goodbye');
Or `.text()`:
$('.on').text('Goodbye');
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "jquery"
}
|
Can Gauntlets of Energy Transformation affect a Duskblade's channeled spells?
Could a Duskblade use Gauntlets of Energy Transformation ( _Magic Item Compendium_ , p. 102) to alter a channeled shocking grasp spell to another form of energy?
Their description states that the gauntlets
> allow you to change the type of energy produced by any weapon you hold.
Once you have channeled shocking grasp could you use a swift action to transform the damage with the gauntlets to another type of energy damage?
|
Specific to your question:
No, the gauntlets wouldn't do that. The energy of Shocking Grasp is coming from the spell itself. Therefore, only a metamagic feat, or metamagic-like effect, could change the type of energy from Shocking Grasp; such as Energy Admixture (Complete Arcane).
The type of energy of the weapon that the gauntlets would change, would be from, for example, Flaming Burst to Icy Burst. That type of energy does come from the weapon, and not a spell.
If you are attacking while channeling a spell, you could still use the gauntlets to change the energy of the weapon if it is enchanted as such - but would not have an effect on the spell the weapon is channeling. So the gauntlets would have a benefit, especially if you are attacking something that is prone to a specific energy type.
|
stackexchange-rpg
|
{
"answer_score": 3,
"question_score": 2,
"tags": "dnd 3.5e, magic items"
}
|
Vectorise sequential numpy calculations
I have a number of operations in numpy which I can perfectly perform in a loop, but I haven't been able to vectorise them in one numpy call.
# data matrix
d = np.random.rand(1496, 1, 2)
# boolean matrix
r = np.random.rand(5, 1496, 1, 2) > 0.5
# result matrix
x = np.empty((5,))
# How can I avoid this loop?
for i in xrange(r.shape[0]):
x[i] = d[r[i]].sum()
Is it possible to speed things up by somehow vectorising the loop?
|
You can vectorize it as this; since `d` is one dimension less than `r`, when they are multiplied, `d` will be broadcasted along `axis=0` of `r` and so avoid the loop; And also since `r` is a boolean array, `d[r].sum()` will be the same as `(d*r).sum`:
(d * r).sum(axis=(1,2,3))
# array([ 775.17049697, 728.61537246, 735.05686655, 765.19469927,
# 759.44834287])
The result is the same as `x`:
((d*r).sum(axis=(1,2,3)) == x).all()
# True
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, performance, numpy"
}
|
Problema com datas em PostgreSQL
Tenho esta query abaixo e quero que o `faturamento`, `ticket_medio` e `qtd_pecas`, `qtd_atendimentos`, sejam divididos pelos números de terças-feiras. Exemplo teve 5 terça feiras com valores registrados nessa view, quero que seja dividido por 5.
Qual função do postgres posso utilizar?
SELECT
id_empresa,
id_loja,
sum(faturamento),
sum(ticket_medio),
sum(qtd_pecas),
sum(qtd_atendimentos)
FROM
sumario_diario
WHERE
to_char(data_sumario, 'dy') = 'tue'
AND id_loja = 19
GROUP BY
id_empresa,
id_loja;
|
Conseguir encontrar a resposta, ficou desta maneira:
SELECT id_empresa, id_loja, avg(faturamento), avg(ticket_medio), avg(qtd_pecas),avg(qtd_atendimentos) FROM sumario_diario
where TO_CHAR(data_sumario, 'dy') = 'tue' and id_loja = 19 group by id_empresa, id_loja
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql, postgresql"
}
|
Are both paths evaluated in an ternary operator?
Using vb.net the following code throws a null pointer exception but the expression should guarantee that `match` is not null.
repeater.DataSource = IIf(collection IsNot Nothing AndAlso match IsNot Nothing, collection.FindAll(match), collection)
Replacing this with regular if-else construct no error is thrown:
If collection IsNot Nothing AndAlso match IsNot Nothing Then
repeater.DataSource = collection.FindAll(match)
Else
repeater.DataSource = collection
End If
Are both path's evaluated in an ternary operator?
|
Yes, both sides are evaluated, you should avoid the `IIf()` syntax and use the `If()` instead, because `If()` will short-circuit with `AndAlso`.
For more information read the accepted answer to VB.NET - IIF(,,) - Both “sides” are evaluated. What situations should I watch out for?.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "vb.net"
}
|
Commenting printf() statements in code
Recently, working with a significant amount of code, I observed that sometimes adding some extra printf() statements and commenting them is very useful for debugging in later stages (makes it easier) when the code has to be modified. But there are debates about over-commenting the code and absence of proper comments. I am not sure where this practice stands? Also, a drawback I find in such a way of commenting is that it makes the code look uglier. Here's an example :
...... //code
......
pkt_bytes_decd = avcodec_decode_audio4( aCodecContext, pFrame,
&frame_fin, &packet );
**//printf("%d bytes from packet decoded\n",pkt_bytes_decd);**
......
...... //code
Is it a bad practice ? Can someone discuss the pros and cons from their experience ?
|
It is much cleaner to use some macro that depends on debugging flag being enabled or disabled.
This way, you do not need to uncomment anything to debug. Simply enable debug flag, and it immediately enables logging in all such places.
Sometimes another approach is used - function like `log(level, message)` is called, and it will emit message only if level is above set threshold (typically called error, warning, info, etc). It is not as efficient, but makes debugging much easier.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "c, coding style, comments"
}
|
Purchasing a Steam Game in Europe (though I am a US citizen)
Ok, I'm hoping this question doesn't get closed with regards to small locale as I'm trying to cover all of Europe with this one :)
I am a US citizen currently working on an international assignment in Europe, and I am an avid gamer.
Does anybody here know if it is possible to purchase the North American versions of games while in Europe? I notice that the Steam store recognizes that I am over here and everything shows up priced in Euros. Does this also mean I'm getting a localized version of the game as well?
If so, any way to circumvent this so that I don't run into any problems when my assignment is complete?
|
You can often get around the blocks that they have in place by simply contacting Steam Support (you need to register a separate account at their site) and requesting the American store, but you will then have to pay with an American credit card. I did this several times when I was in Australia and it takes 1-3 days for them to unlock your account to do so, so it may not be the best option for grabbing that game on sale.
I played the uncensored version of L4D2 while I was in Australia via this method, though I couldn't play multiplayer (I'm not sure if there were any local multiplayer servers in any case)
|
stackexchange-gaming
|
{
"answer_score": 11,
"question_score": 7,
"tags": "steam, region lock"
}
|
Eclipse autocomplete to replace the function name
IntelliJ has this with TAB is there something like this for Eclipse? Any plugin that does this?
|
Hold `Ctrl` when the content assist popup is active to toggle the "overwrite" mode:
 as an int when printing?
I'm trying to append the integral return value of localtime (in Perl) but I can't seem to avoid it converting the return val to something that looks like this: Sun Jul 26 16:34:49 2009 When I say print localtime I see what I want, but when I say $foo = localtime,""; print $foo; I get the string. I want those digits. I tried $foo = localtime() * 1 but that reverts to 1969 AND gets the string.
Very confusing.
|
That string is what `localtime` returns in a scalar context. It returns
( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime();
in a list context. If you want just the timestamp, use `time`.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "perl, localtime"
}
|
Complex number forming equilateral triangle
Suppose we have 3 complex numbers , such that $$|z_1|=|z_2|=|z_3|=1$$ and they form equilateral triangle then will condition $$z_1.z_2.z_3=1$$ always be true? I know cube roots of unity , that is $w,w^2,1$ satisfy here but is this always true?
|
No. Rotate the three point by multiplying with $e^{i\theta}$. Then the product is multiplied by $e^{3i\theta}$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "complex analysis, complex numbers"
}
|
Scala / Lift: Set up hotdeploy through Eclipse?
How do I set up hotdeploy for Scala/Lift projects in Eclipse?
Basically, I would like to be able to
1. Set up a new project, from say lift-archetype-basic
2. Launch jetty:run, either from some run-configuration or through terminal
3. Be able to edit Scala files in Eclipse, Save/Auto compile
4. Refresh the web-page in the browser and see the updates.
The tutorial at < is out-dated and I really can't figure out how to set this up.
I currently have
* Eclipse 3.5
* Maven IAM plugin version 0.11
* Scala plugin 2.8.0.RC6
Should I use any other versions or plugins?
|
With SBT it's possible to continuously recompile and reload the web application when using Jetty:
jetty-run
~ prepare-webapp
`jetty-run` starts Jetty and the `~ prepare-webapp` recompiles and recreates the web application whenever sources files change.
SBT is compatIble with Maven and Ivy, so you may generate the project file layout with Maven archetypes, and switch to SBT later - it will recognize repositories and dependencies specified in the POM.
This tutorial video shows, how to get stated with SBT and Eclipse.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "eclipse, scala, scala 2.8, lift, hotdeploy"
}
|
How can I make a multi-language app with the Java code?
I am already well aware of how easy it is to make a multilanguage app with Android by using the string.xml code. That part was nice and easy.
The issue is I have a lot of dynamic texts in my app that are made with my Java code. This is the part where I am can't find how to also make multilingual. The way I am picturing a solution is having some kind of condition in which I verify what language it is in, and change the string. For example:
if(language.equals(English))
textView1.setText("Hi! This is in English!");
if(language.equals(Portuguese))
textView1.setText("Oi! Isso é em Português!");
Is it possible for me to do something like this? If so, how can I do it?
Thanks!
|
Extract those strings into the `strings.xml` file too and it will choose the value from the correct file depending on the language. There is **no** reason to have those strings _hardcoded_ in your java.
String hello = getResources().getString(R.string.hello);
Will have the right language if its available, since at runtime, the Android system uses the appropriate set of string resources based on the locale currently set for the user's device. For instance if you have `res/values-ru/strings.xml` that contains `res/values/strings.xml` and the device is in russian, it will take the value (if it's available) from the first one.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "java, android, multilingual, dynamic text"
}
|
$T:V\rightarrow V $ is over $\mathbb{R}$ , it's matrix is $A$, $A=PDP^*$. Is it true that $A$, $D$, and $P$ are in $M_{n \times n}(\mathbb{R})$
$T:V\rightarrow V$ is over $\mathbb{R}$ and $V$ of finite dimension $n$, and I know that it is orthogonally diagonalizable.
The Matrix that represents it - call it $A$ ,in orthonormal basis is orthogonally diagonalizable as well. So $A=PDP^*$ where $P^*$ is a unitary matrix, and $D$ a diagonal matrix.
Is it true that $A$, $D$, and $P$ are in $M_{n \times n}(\mathbb{R})$ (real matrices) because the transformation is over $\mathbb{R}$? I want to conclude that $P^*$ = $P^t$.
Thanks a lot!!
|
No it is not in general true.
Let $A=\left(\begin{matrix}0&1\\\ -1&0\end{matrix}\right)$.
The $A$ is anti-symmetric, and therefore it is orthogonally diagonalizable, and its eigenvalues are $\pm i$. Therefore, $D$ contains purely imaginary elements in the diagonal. Clearly, $P$ is not a real matrix either. In fact $$ P=\left(\begin{matrix} 1& i\\\ i&1\end{matrix}\right) $$
Nevertheless it is true is $A$ is symmetric (real symmetric). In such case, the eigenvalues are real (and so is $D$) and a diagonalization is achieved via a real unitary matrix $P$.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linear algebra, matrices, operator theory"
}
|
NFS status: execstartpre=/usr/sbin/exportfs -r error
when I run `systemctl status nfs` I see that there is an error which you can see in the image below:

If you want to export to a subnet use a valid subnet.
/mnt 192.168.0.0/24(<your-nfs-export-options>)
or
/mnt 192.168.0.0/255.255.255.0(<your-nfs-export-options>)
For a more detailed and full description consult `man exports`.
|
stackexchange-unix
|
{
"answer_score": 0,
"question_score": 0,
"tags": "rhel, nfs"
}
|
How to add CSS Transition for button sliding
I am new to css transitions and i want to add sliding effect for my buttons "option1" and "option2" when i click on "view more". These buttons should appear from behind view more.
I am currently using `ng-if` to hide and show two of my buttons
<div class="bottom-right">
<button class="btn button1" ng-click="showAll()">view more</button>
<button ng-if="viewmore" class="btn button1">option1</button>
<button ng-if="viewmore" class="btn button1">option2</button>
</div>
how can i do that?
here is my plunker <
|
i'd recommend using ngAnimate to achieve that effect.
Since angular 1.2.* came out approximately 2 years ago, here's a great article that explains how to achieve exactly what you need with this version:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "angularjs, css"
}
|
How can I access detox element matchers in custom helpers?
I am looking to access the `element` and `by` variables which are globally available in my test, but when I try to call them from a helper module required/imported by the test I get an undefined error. How can I import these variables directly?
|
Make sure `detox.init()` call happens earlier than you access those variables (`element`, `by`) because init method is the actual place where Detox globally exposes them.
After you call `await detox.init(<your options>`), you'll be able to initialize your helpers.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "react native, detox"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.