INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Finding work via Line Integrals
The position of an object with mass $m$ at time is $r(t) = at^2 \vec{i} + bt^3 \vec{j}$, where $0 \leq t \leq 1$.
Part a asks for the force, which I found to be $2ma \vec{i} + 6mbt \vec{j}$, which is correct.
Part b asks for the work done by the force in the given time interval.
I am not sure how to approach this. I tried integrating the equation from part a from 0 to 1 , but I don't think that is the correct way. Any hints in the right direction are appreciated, thank you! (The correct answer for b is $2ma^2 + 4.5mb^2$) | To compute work what you have to do is
$$\int\limits_{C} \vec{F} \cdot \text{d} \vec{r},$$
which is to say you compute the integral in the given interval of the dot product of the force and the time derivative of the curve. Writing it explicitly
$$W = \int_0^1 (2ma)(2at) + (6mbt)(3bt^2) \, dt.$$
When you do it you will find the desired result. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "calculus, integration, multivariable calculus, definite integrals"
} |
How do I get the tadtone located under the lilypad?
> **Beware of spoilers.**
I'm currently in Flooded Faron Woods, collecting the tadtone pieces in order to get the Water Dragon's piece of the Song of the Hero. I've collected all of the pieces save one. Near the entrance to the first dungeon in Faron Woods, there is a lilypad containing a tadtone. I'm unable to get it. I've tried flipping it over with my whip, jumping on it from another lilypad, smashing into it, and just about anything else I can think of, however nothing has proved successful.
On the map below, the tadtone and lilypad is located at the "1", on the map below:
!enter image description here
(image source: <
How do I get my hands on this last tadtone? | To be able to get that tadtone, you need to flip that lilypad over. The spiky side is down in the water so you won't be able to use your whip on it. So if you remember what happened in the **Ancient Cistern** with the lilypads, to flip it, you need to jump on it from high above. The only way you'll be able to jump on it with a significant enough height would be from the great tree.
It should be pretty obvious where to jump from. When you climb the tree, there will be a part of the platform jutting out in the direction of that lilypad. Go to the end (and make sure you're facing in the direction of the pad) and jump down. You should be able to land on the lilypad, flipping it over and releasing the tadtone. | stackexchange-gaming | {
"answer_score": 10,
"question_score": 8,
"tags": "zelda skyward sword"
} |
Facebook targeted ad to target younger than 18
We have a free course which educates children between 14 and 16 how to learn and behave with disabled children and how to best help them.
We plan to advertise it via Facebook targeted ads. But... We cannot create an ad to target younger than 18. But in reality all children from our aim group have Facebook accounts.
How shall we then advertise this course for our aim audience? | When choosing your ad set, the default range is 18-65. You should be able to change it.
 is a string of characters used to identify a name or a web resource
VS
> A uniform resource locator, abbreviated URL, also known as web address, is a specific character string that constitutes a reference to a resource.
Never heard about `UNIVERSAL` but here are the common, URL and URI, I guess Universal must be probably a synonym
This guy here uses Universal in his article | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 5,
"tags": "url, resources, uniform"
} |
bootstrap footer spacing issue
I have a website that i'm working on that is Wordpress built with bootstrap. everything is working perfectly except for the footer which seems to have a space below it that will not go away. I have looked in all of the CSS and even checked to make sure it wasn't wrapped by any containers. Can someone help me out?
` | Your `body` has a `padding-bottom: 51px` set. DOM/CSS inspectors like Firebug or Chrome dev tools are very useful and can help you find the cause of these issues. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "css, wordpress, twitter bootstrap"
} |
Winston js. My log files aren't rotating after exceeding maxsize
I have the following winston configuration:
'use strict'
import winston from 'winston'
import config from '../../config/environment'
export default winston.createLogger({
level: 'info',
format: winston.format.printf(info => info.message),
transports: [
new winston.transports.Console(),
new winston.transports.File({
filename: `${config.logsPath}/express.error.log`,
maxsize: 300,
level: 'error'
}),
new winston.transports.File({
filename: `${config.logsPath}/express.log`,
maxsize: 300
})]
})
None of this files are rotating after they reach the 300 bytes threshold. | You are using the version `3.0.0` release candidate which has a bug in its `File` transport. Basically, once over the `maxsize` threshold, internal `self.filename` variable was not being updated so `_createStream` would re-open the append stream to the existing file and continue writing to it. It works the first time around because `self.filename` is set when initializing from options.
I've submitted a PR which fixes the issue. Alternatively, you can revert to `2.4.0` where this isn't an issue. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 6,
"tags": "javascript, node.js, logging, winston"
} |
Unexpected return of sorting a string()
Private Sub bttSort_Click(sender As Object, e As EventArgs) Handles bttSort.Click
DataView1.Rows.Clear()
Dim i As Integer
Dim j As Integer
Dim temp As Integer
For i = 0 To list1.Length - 1
For j = (i + 1) To list1.Length - 1
If list1(i) > list1(j) Then
temp = list1(i)
list1(i) = list1(j)
list1(j) = temp
End If
Next
Next
DataView1.Rows.Clear()
For m As Integer = 0 To list1.Length - 1
DataView1.Rows.Add(list1(m))
Next
End Sub
I entered a string(1,3,5,6,7,113,23,62) After running the code above, the output should be sorted as (1, 3, 5, 6, 7, 23, 62, 113). But my out put was (1, 113, 23, 3, 5, 6, 62, 7). I have no idea, hope someone can help me. Thank you. | The will onyl get the output you want working with int, long, double.. but with string, they sort lexycographically, which means..
1, 113, 23, 3, 5, etc....
all the 1's first.. then 2's... etc... ;)
Convert all the elements to integers, and try again! ;)
You will get the expected output! ;) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "arrays, vb.net, string, loops, visual studio 2012"
} |
proof of lemma 10-8, In functional analysis book of Rudin page 232
In functional analysis book of Rudin page 232, proof of lemma 10-8 We have a function $ h_r(\lambda)= \frac{r^2 g(\lambda)}{z^2(2r-g(\lambda))} , \lambda \in \mathbb{C} $ and $ g(\lambda)$ is an entire function on $\mathbb{C}$. Then $ h_r(\lambda)$ is analytic in $ \lbrace \lambda :|\lambda|< 2r \rbrace $. My question is that why $ h_r(\lambda)$ is analytic in $ \lambda=0$ ? Please help me. thanks | The proof starts with
> Since $f$ has no zero, there is an entire function $g$ such that $f = \exp\\{g\\},\; g(0) = g'(0) = 0$, and $\operatorname{Re} [g(\lambda)] \leq \lvert\lambda\rvert$.
The condition $g(0) = g'(0) = 0$ - where $g'(0) = 0$ follows from $f'(0) = 0$, and $g(0) = 0$ is by choice ($f(0) = 1$) - ensures that
$$h_r(\lambda) = \frac{r^2g(\lambda)}{\lambda^2 [2r - g(\lambda)]}$$
is analytic in $\lambda = 0$, since the power series expansion of $g$ starts $a_2\lambda^2 + a_3\lambda^3 + \dotsb$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "complex analysis, functional analysis"
} |
Two prepositions side by side
From this sentence, I am not quite sure why are these two prepositions "on" and "in" used. **And,** can we **swap** the word further with on to be the second sentence?
> If we look further **on in** time, to the year 2737 BC, we arrive at the discovery of tea by a Chinese emperor.
>
> If we look **on further in** time, to the year 2737 BC, we arrive at the discovery of tea by a Chinese emperor. | No. Swapping changes the meaning.
**Further on in time** , means looking at a time that is further from the present (than a previously referenced time).
**Looked on further in time** \- one wouldn't use that because "look on" has a different idiomatic meaning.
You could, however, say something like "Kept looking further back in time.." to mean that one continued looking (if it had already been stated that one had been looking at another period already). | stackexchange-english | {
"answer_score": 0,
"question_score": -1,
"tags": "prepositions, word order, phrasal verbs"
} |
Simple Injector, want to inject conditionally based on runtime value
Say I've the following class definition:
public class CreateThingyController : ICreateThingyController
{
private readonly ICreateThingyHandler handler;
private ISomeBusinessRuleBehaviourDependingOnFlag rule;
public CreateThingyController(ICreateThingyHandler handler)
{
handler = handler;
}
public void CreateThingy(string something, bool flag)
{
if(flag) rule = new BlaImplementation()
else rule = new BoehImplementation
}
}
I really dislike setting the behaviour at runtime like this, so I'd like to leverage SimpleInjector for this. But since I only know what to pick at runtime, depending on some variable I have no idea how to approach this..
Any help would be greatly appreciated!
Edit: Oh, wow, I'm just now beginning the benefit of using a DI container. Awesome stuff. | You might want to look into the Factory pattern here.
public class BusinessRuleBehaviourFactory : ISomefactory
{
public ISomeBusinessRuleBehaviourDependingOnFlag Create(string flag)
{
if (flag == "something")
return new BlaImplementation();
else if (flag == "something else")
return new BoehImplementation();
return new DefaultImplementation();
}
}
Then you just inject your factory into your class
public CreateThingyController(ICreateThingyHandler handler, ISomeFactory someFactory)
{
handler = handler;
factory = someFactory;
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, .net, dependency injection, simple injector, strategy pattern"
} |
Android bluetooth connect check mac addresses
I am trying to compare the MAC address from a paired device to make sure its one of two known addresses in the app. I am using the following to get the device
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdapter.getRemoteDevice(address1);
mmDevice = device;
}
So what I want to do is something like
if(foundMacAddress == address1){
BluetoothDevice device = btAdapter.getRemoteDevice(address1);
}else{
BluetoothDevice device = btAdapter.getRemoteDevice(address2);
}
However I am uncertain as to how I can retrieve and compare the MAC address. | I found that I could loop through the paired devices, and check the address that way:
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
String conn = null;
for(BluetoothDevice device : pairedDevices)
{
String theAddress = device.getAddress();
if(theAddress == address1) {
conn = address1;
}else{
conn = address2;
}
Log.d("CONNECTION: ",conn);
}
BluetoothDevice device = btAdapter.getRemoteDevice(conn);
mmDevice = device; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "android, bluetooth"
} |
Convert a json format into a structured dataframe
I have this pandas:
results = requests.request("POST", url, headers=headers, data=payload).json()
results
{‘ABC: {’26/03/2021': {‘A’: ‘1234’,
‘B’: ‘5678’},
'29/03/2021': {‘A’: ‘5555’,
‘B’: ‘6666’},
'30/03/2021': {‘A’: '44779',
‘B’: '10364'} }
And would you like to convert this dataframe?
COLUMN1 | COLUMN2 | A | B
---|---|---|---
ABC | 26/03/2021 | 1234 | 5678
ABC | 29/03/2021 | 5555 | 6666
ABC | 30/03/2021 | 44779 | 10364
Could you help me find a way out of this? | Try (`results` is your dictionary from the question):
all_data = []
for k, v in results.items():
for kk, vv in v.items():
all_data.append({"COLUMN1": k, "COLUMN2": kk, **vv})
df = pd.DataFrame(all_data)
print(df)
Prints:
COLUMN1 COLUMN2 A B
0 ABC 26/03/2021 1234 5678
1 ABC 29/03/2021 5555 6666
2 ABC 30/03/2021 44779 10364
Prints: | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "python, json, pandas, dataframe"
} |
How to find the line that splits the area into two equal parts?
> Let $R$ be the region bounded by the graphs of $y = \cos \left(\frac{\pi x}{2}\right)$ and $y=x^2 -1$. The line $y=k$ splits the region $R$ into two equal parts. Find the value of $k$.
First find the area.
$$A = \int\limits_{-1}^1 \left[\cos \left(\frac{\pi x}{2}\right) - x^2 +1\right]\, \mathrm{d}x = \frac{4}{\pi} + \frac{4}{3}$$
Not exactly sure about how to find the value of $k$, whats the next step?
* * *
From the wonderful answers of both Ross Millikan and DonAntonio I have figured it out.
$$\int\limits_{-\sqrt{k+1}}^{\sqrt{k+1}} \left[k-x^2+1\right]\, \mathrm{d}x = \frac{A}{2}$$
$$\frac{4}{3}\left(k+1\right)^{3/2} = \frac{A}{2} $$
solve for $k$
$k\approx -0.015$ | For $\,y=k\le 0\,$ evaluate the area between the line (above) and the parabola (below), and this must be half what you got in your original integral. If you get a valid value you're done, otherwise you'll have to assume $\,k>0\,$ and then you'll have to evaluate the area between the trigonometric function (above) and the line (below) as before... | stackexchange-math | {
"answer_score": 4,
"question_score": 2,
"tags": "calculus"
} |
Perform mirror symmetry transformation of 3D model (in OBJ)
I have a full three-dimensional model in OBJ format:

Here is a two-dimensional image of what I seek. (Note, it is not a rotation of the figure.) But I seek a full 3D model in this configuration.
 will see his hand in his pocket facing us.
How do I perform that mirror operation on the figure to produce his (virtual) mirror-symmetric image?
* * *
The model was downloaded here. | You can use `TransformedRegion`. For example:
obj = Import @ FileNameJoin[{
$HomeDirectory,
"Downloads",
"86-rp_dennis_posed_004_bld_free3d",
"rp_dennis_posed_004_100k.OBJ"
}];
Using `TransformedRegion`:
Show[
obj,
TransformedRegion[
obj,
TranslationTransform[{100, 0, 0}] @* ScalingTransform[{-1, 1, 1}]
]
]
;
String query = "insert ignore into time(time_now) values (?)";
pstmt.setString(1, timestamp);
pstmt.executeUpdate();
My database connection is fine as I have a lot of other information that's being uploaded to it with no problem, I'm just having trouble with the timestamp | Something like this should work:
java.util.Date date = new java.util.Date();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("insert ignore into time(time_now) values (?)");
preparedStatement.setTimestamp(1, timestamp); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, mysql"
} |
How can I create multiple new instances of a model and save them to the database?
I'm using the following code to attempt to import a CSV file. However it is just saving the last object of `Fact` rather than saving each of the objects that were built.
Do While Not sr.EndOfStream
Dim aFact as Fact
Dim mArray = sr.ReadLine().Split(",")
aFact.Name = mArray(0)
aFact.Value = mArray(1)
db.Facts.Add(aFact)
End
db.SaveChanges() | Just use a list where you save the object
Dim factList As New List(Of Fact) ' add the list
Do While Not sr.EndOfStream
Dim aFact as Fact
Dim mArray = sr.ReadLine().Split(",")
aFact.Name = mArray(0)
aFact.Value = mArray(1)
factList.Add(aFact) ' put fact object in list
End | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "asp.net mvc, vb.net, entity framework"
} |
Generic Type `toDouble` in Scala
Hi have the following as bellow. It is supposed to be a function that calculate the average of a sequence.
def fun1[T <: { def toDouble:Double }] (seq:Seq[T]) = {
val q2 = seq map { _.toDouble }
val n = q2.size.toDouble
q2.sum / n
}
However I cannot pass `Seq(1,2,3)` to `fun1`. Why? | def fun1[T <: AnyVal{ def toDouble:Double }] (seq:Seq[T]) = {
val q2 = seq map { _.toDouble }
val n = q2.size.toDouble
q2.sum / n
}
fun1(Seq(1, 2, 3))
It seems like the compiler infers the type as AnyRef. Defining it as AnyVal works. AnyRef is the supertype of all objects, while AnyVal is the supertype of all primitives. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "scala, generics"
} |
Upgrade a Laravel 4.2 project to Laravel 5.1
I have project written in Laravel 4.2 that works fine, but I have to improve it by adding some functionality. I want to use Laravel 5.1 for this. Is there any way to automatically convert a Laravel 4.2 project into Laravel 5.1? | Sadly not, it's quite a big change so you'll have to follow their upgrade guide: < Look for **Upgrading To 5.0 From 4.2** | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "laravel 4, laravel 5, laravel 5.1"
} |
up; into the following state?
> to end **up** in the army (dictionary.com _verb_ , end #30)
‘ _End_ ’ denotes ‘ _reach or arrive at a final condition, circumstance, or goal (often followed by up)_ '. Then if it, _end up_ , is followed by prepositional phrases, participles, adjectives, does ‘ ** _up_** ’ denote ‘ ** _into the following state_** ’? | I don't think it helps to view the _up_ as having its own denotation here. The meaning of _end up_ is certainly related to the meanings of various other verb-particle idioms with _up_ (such as _wind up_ : "we wound up talking for hours"; and _turn up_ : "he turned up missing"), but ultimately, they are idioms, and best viewed as complete wholes.
Syntactically, too, it is _end up_ \+ <adverbial>, not _end_ \+ _up_ <adverbial>; for example, one can say "Where did he end up?", but never *"Up where did he end?"
The opposite of _end up_ , incidentally, is _start out_ : "he started out in the Army". It works much the same way. | stackexchange-ell | {
"answer_score": 2,
"question_score": 2,
"tags": "vocabulary"
} |
Какой словообразующий суффикс в слове ЧИТАЙ?
В слове ЧИТАЙ какой словообразующий суффикс - АЙ или А? И что тогда такое Й? | Чит/ай-словообр. суфф./+ нул. формообр. суфф.+ нулевое оконч.
а//ай - чередование в суффиксе. | stackexchange-rus | {
"answer_score": 1,
"question_score": 1,
"tags": "словообразование, суффиксы"
} |
How to add a style definition to a tooltip html string definition?
I'm appending a Bootstrap tooltip to a label in a HTML form. So far the tooltip shows up fine in the render.
But now have the case where a style needs to be added to the `<tr>` tag within the HTML string supplied for that tooltip.
I did try adding the style definition as normal to the tag below, but syntax errors are thrown stating a bracket and `;` are needed:
$('#Event').tooltip({title: "<tr style="padding-bottom: 4px;" ><td><code>Current</code></td><td>Event is still active</td></tr>", html: true, placement: "right"});
**Question:**
What is the correct syntax to style a html string in a tooltip? | Strings in JS is delimited by pairs of matching quotes. For example:
var validStr1 = "hello";
var validStr2 = 'hello';
var validStr3 = "he'l'lo";
var validStr4 = 'he"""llo';
var invalidStr1 = "hello';
var invalidStr2 = "hel"lo";
var invalidStr1 = "hel"'lo';
You are using string as an argument for tooltip function, hence you have to use single and double quotes in code here properly.
$('#Event').tooltip({title: '<tr style="padding-bottom: 4px;" ><td><code>Current</code></td><td>Event is still active</td></tr>', html: true, placement: "right"}); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, html, twitter bootstrap, tooltip"
} |
How to send a Get request in iOS?
I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in `[NSURLRequest setHTTPMethod:]` I am setting it as
[requestObject setHTTPMethod:@"GET"];
Tell me what could be the problem. Also provide me the code if you have. | NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: @"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response1 =
[NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError]; | stackexchange-stackoverflow | {
"answer_score": 82,
"question_score": 26,
"tags": "iphone, objective c, url, get, nsurl"
} |
Filter compare array same index swift 4
My case is create multiple choice questions, and i want to compare array in the same index
Correct answer:
[3, 2, 0, 2, 2]
User answer:
[3, 2, 3, 1, 1]
The expected output:
[3,2]
And this is the code
let filteredArray = correctAnswer.filter{ userAnswer.contains($0) }
print(filteredArray)
But the output:
[3, 2, 2, 2]
Thank you. | If you want to compare two array index by index then you can use `compactMap` with `zip`.
let correctAns = [3, 2, 0, 2, 2]
let userAns = [3, 2, 3, 1, 1]
let finalAns = zip(correctAns, userAns).compactMap({ $0 == $1 ? $0 : nil })
print(finalAns) // [3, 2]
**Edit:** You can even simplified this by using **`@MartinR`** suggestion.
let finalAns = zip(correctAns, userAns).filter(==).map { $1 }
If you want index of correct answer than you can get like this.
let finalAnsIndex = zip(correctAns, userAns).enumerated().compactMap({ $0.element.0 == $0.element.1 ? $0.offset : nil })
print(finalAnsIndex) // [0, 1] | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "arrays, swift, filter, compare"
} |
Cassandra or MySQL/PostgreSQL?
I have huge database (kinda wordnet) and want to know if it's easier to use Cassandra instead of `MySQL`|`PostrgreSQL`
All my life I was using `MySQL` and `PostrgreSQL` and I could easily think in terms of relational algebra, but several weeks ago I learned about Cassandra and that it's used in Facebook and Twitter.
Is it more convenient?
What DBMS are usually used nowadays to store social net's data, relationships between objects, wordnet? | There are many different flavours of "NoSQL" databases. If your application is really like Wordnet perhaps you should look at a graph database such as Neo4j. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 23,
"tags": "mysql, database, postgresql, cassandra, nosql"
} |
Selecting the first nth rows by group with number of rows varied
I like to select the first (2,3,0,4) rows of each group in a data frame.
> f<-data.frame(group=c(1,1,1,2,2,3,4),y=c(1:7))
>
> group y
> 1 1
> 1 2
> 1 3
> 2 4
> 2 5
> 3 6
> 4 7
and obtain a data frame as follows
group y
1 1
1 2
2 4
2 5
4 7
I tried to use `by` and `head` but head does not take a vector.
Thank you for your help. | Version of function with indexes.
fun1 <- function(){
idx <- c(0,which(diff(f$group)!=0))+1
idx2 <- unlist(lapply(1:length(nf),function(x) seq.int(from=idx[x],length.out=nf[x])),use.names=F)
f1 <- f[idx2,]
return(f1)
}
fun2 <- function(){
ddply(f,.(group),function(x) head(x,nf[x[1,1]]))
}
Test data (size suggested by author of question)
f<-data.frame(group=sample(1:1000,50000,T),y=c(1:50000))
f <- f[order(f$group),]
nf <- rpois(length(unique(f$group)),3)
system.time(fun1()) system.time(fun2())
On my system ~60 times faster is fun1. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 4,
"tags": "r, dataframe"
} |
How do I build and install a package from an APKBUILD in Alpine Linux?
I have an APKBUILD and associated files (patches, et cetera), and I would like to build and install it locally. I'm aware that I can build it with `abuild`, but this doesn't seem to keep the package afterwards. How do I build and install a package from an APKBUILD in Alpine Linux? | Actually, `abuild` does keep the built .apk package. It will be placed in a local repository created by abuild that's located in `~/packages`. If you want, you can add this to your repository list by adding the path in `/etc/apk/repositories`. You will have to add a separate entry for each channel you want to install packages built for, so if you want to include the three of testing, community, and main you'd have to add something like this to the file:
/home/<username>/packages/main
/home/<username>/packages/community
/home/<username>/packages/testing
You will then be able to install the package the usual way:
# apk add <package name>
There is also the option of just installing the apk directly by doing something like this:
# apk add ~/packages/<channel>/<architecture/<package name>-<package version>.apk
For example:
# apk add ~/packages/testing/x86_64/giara-0.2-r0.apk | stackexchange-unix | {
"answer_score": 0,
"question_score": 1,
"tags": "software installation, package management, alpine linux, apk tools"
} |
How to properly unit test inequality
So one of the goals of unit testing is to make sure that future changes/refactors won't break existing functionality. Suppose we have the following method:
public bool LessThanFive(double a) {
return a < 5;
}
One way to uni test this is as follow:
public bool LessThanFiveTests_True() {
const double a = 4;
Assert.IsTrue(LessThanFive(a))
}
The problem with this unit test is that if, later on, someone changes the `<` into `<=` in `LessThanFive` method, the test will pass.
What about if we have `DateTime` instead of `double`? | Your assumption seems to be that you write one test, and that test catches all possible bugs. The opposite is closer to the truth: For each potential bug, you need one test to catch it. In practice, certainly, many tests will catch a number of potential bugs, but I exaggerated a bit to convey the idea.
So, to catch the potential bug that the `<` is turned into a `<=`, you need a second test case that tries the function with `5`. This is, btw. a so-called boundary test, and boundary testing is one well-known method to derive a set of useful test cases.
There are many more test design techniques, like, equivalence class partitioning, classification trees, coverage based testing etc. The underlying goal of these methods is, to guide you in developing a test suite where ideally for every potential bug a corresponding test case exists that will detect that bug. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, unit testing"
} |
Only 3 FPS on Mac mini, boot camp, windows 7
Using the GPU test tool from FurMark I get only 3 FPS.
In normal use I notice it when playing fullscreen videos: When the video pans horizontal I get these stripes across the picture.
My setup is like this:
Mac mini 2011 2.3GHz dual-core Intel Core i5
2 GB DDR3 SDRAM (PC3-10600)
500 GB HD
Intel HD 3000 OS: windows 7 Tv: Panasonic G10 50" plasma Tv and computer are connected with an 2 meter HDMI cable
I've tried to change the HDMI cable - did not change anything.
What can I try? | To resolve this issue:
Head to the:
1. Control Panel's
2. Performance Information
3. Tools
4. Adjust Visual Effects
Choose: "Adjust for best appearance"
... problem solved | stackexchange-superuser | {
"answer_score": 2,
"question_score": 0,
"tags": "windows 7, macos, mac, hdmi, boot camp"
} |
Wordpress Limit posts on home page
I am developing a wordpress blog but for some reason the posts won't limit on the home page. I am trying to limit to 3 but it falls back to what is set in the administration area instead of 2. How come?
What am I doing wrong?
<?php
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query('posts_per_page=-1&paged=' . $paged);
query_posts('showposts = 2');
$flag = 1;
while ($wp_query->have_posts()) : $wp_query->the_post();
?> | Try using this code in the functions.php to limit the posts on the homepage, it should limit the posts to 2:
function posts_on_homepage( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'posts_per_page', 2 );
}
}
add_action( 'pre_get_posts', 'posts_on_homepage' ); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php, wordpress"
} |
Is Gmail a Single page application
Today I was going through the my mail box. I just seen that when I am navigating through different folders after # that folder name is changing and data being refreshed. I just want to confirm is Gmail a single page application. I also want to develop a mail box kind of application using Single page application concept. Below is sample URL for inbox folder.
<
Can I develop sample mail box application using angular js as angular js supports concept of SPA? | Yes, Gmail is a single-page application.
That is the reason before loading Gmail you see a progress bar, as it fetches everything from server once and then all the rendering is done on the client side with calls to server only for fetching data and not the DOM.
 via db2Move
I use the following to export the information: `db2move server1 export -sn theschema -tn table, table2, table3`
and it exports fine.
I'm trying to import all the exported information into a derby (local) database.
I've tried using:
db2move C:/IBM/WCToolkitEE60/db/mall import
The problem is, it says:
Application code page not deteermined, using ANSI codepage 1252
Error: String 'C:/IBM/WCToolkitEE60/db/mall
**Error - Line Buffer overrun.
Anyone know what I'm doing wrong here? The DB is DB2 | `db2move` is a utility for reading and writing to DB2 databases. You can't use db2move to write to a Derby database. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "import, db2, export"
} |
Does the price trick you? (Windscreen)
> Foam screen:
>
> Dead cat: <
I thought dead cat windscreens were generally considered better than foam screens, but here you can see that the foam screen is the more expensive of the two. Why? Is the foam screen actually better than the dead cat? (The prices here can be divided by 5,7 to get USD.) | My guess is that foam wind screen is a Senny and not an aftermarket. The dead cat pictured looks like a pretty cheapo model. | stackexchange-sound | {
"answer_score": 1,
"question_score": 0,
"tags": "microphone"
} |
Unable to complete installation using Bitnami
When trying to install Joomla on a local host (OS X 10.10) using Bitnami, I get this error:
> Problem running post-install step. Installation may not complete correctly Error running /Applications/XAMPP/xamppfiles/bin/mysql \--user=root --host=localhost --socket="/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock" --database=bitnami_joomla --password=**** -e "SOURCE /Applications/XAMPP/xamppfiles/apps/joomla/htdocs/installation/sql/mysql/joomla.sql;": Warning: Using a password on the command line interface can be insecure. ERROR 1146 (42S02) at line 14 in file: '/Applications/XAMPP/xamppfiles/apps/joomla/htdocs/installation/sql/mysql/joomla.sql': Table 'bitnami_joomla.jos_assets' doesn't exist
How do I fix this? (I'm obviously dead in the water!) | Simple word of advice:
**Don't use 3rd party software that supposedly make installation easier**
I have never really seen the point in them. In addition to this, we can't really give supports for 3rd party software as it is nothing to do with us.
Joomla is extremely easy to install, even easier in the 3.x series, so I would suggest you download the installation package from the official site, extract it and go through the simple steps. | stackexchange-joomla | {
"answer_score": 1,
"question_score": 0,
"tags": "joomla 3.x, installation"
} |
PHP - Use pdo fetch multiple times
I have below query:
//Get the data
$stmt = $dbh->prepare("
SELECT t1.*, t2.*
FROM softbox_bookings_data t1
LEFT JOIN softbox_bookings t2 ON t1.booking_id = t2.id
WHERE t2.id=:id
GROUP BY t1.model
ORDER BY t2.time ASC");
$stmt->bindParam(":id", $_GET["id"]);
$stmt->execute();
$data = $stmt->fetchAll();
Now I want to be able to use above query multiple times.
First I want to just echo out a variable:
echo $data["name"]; //Returns nothing
Then further down the page, I want to loop the data:
foreach($data as $row){
echo $row["name"]; //Successfully echoes out the name from the database.
}
How come I can't use the `echo $data["name"]` variable and the `foreach()` statement to run through the data? | Turn on error reporting and **always** use `var_dump` instead of `echo` when checking variable values. The latter will only print strings, but `data` is a two-dimensional array. Just check the `var_dump` output.
BTW: Of course `echo` "returns" nothing, its return type is void. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "php, mysql, pdo"
} |
ide sublime2 how to find method definition
I'm using **Sublime 2** for Ruby On Rails programming. I need a ability to click a method name and jump to class where the method is defined. There are many IDE with similar capability... | `Goto symbol` is `Ctrl`-`R` (linux), this gives a pop-up-list of all symbol and class definitions in the file, in definition order, and you can jump to what you're after. You could do the same thing with `Goto Anything`, `Ctrl`-`P` and then typing `@` and the method name.
Also, there is a Goto Symbol plugin, which lets you jump straight to the definition of the method name your cursor is at, with a key binding or click.
However, both those methods are limited to the current file. If you need to jump to definitions in other files, probably the best solution is the SublimeCodeIntel plugin. It seems to be working pretty well and just by hitting `Ctrl`-`f3` (linux) will open up the file at the definition you want. | stackexchange-stackoverflow | {
"answer_score": 51,
"question_score": 51,
"tags": "ruby on rails, ruby, sublimetext"
} |
Is JavaFX a better way to create a html report
I have a Swing application, one thing it does is create an html report that then opens in a browser. Creating this html report within Java and having to write Javascript ectera is hard work. I notice that javafx is now included in Java and I wonder if I could use javafx to create the html report instead and would that be a good idea. | No, it seems I have misunderstopod JavaFX. I thought it was a way to create fancy html applications, but it seems it is more a way to create desktop applications but using technologies familiar to html like CSS to create UI's currently difficult with Swing technology.
For dynamic creating html I am finding the j2html library useful. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, javafx"
} |
Emit to every room a socket is in using _rooms
Is it possible to emit to an array of rooms (specifically all the rooms a socket is in) without a for loop? Similar to how you can join with `socket.join([roomArray])`? | Answering myself (with help from the Socket.IO Slack). Yes, it is!
**With a for loop**
// You can rename the room variable whatever you want
for (const room of Object.keys(socket.rooms)) {
socket.to(room).emit('news', { hello: 'world' });
}
**Without a for loop**
You can use the native `_rooms` property of a socket
// _rooms will be cleared once it has been emitted to
socket._rooms = Object.keys(socket.rooms);
// console.log(socket._rooms) = ['abc', 'efg', ...]
socket.emit('news', { hello: 'world' });
// console.log(socket._rooms) = [] | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "node.js, socket.io"
} |
data-cfasync to validate (W3C)
I am trying to validate my document as XHTML 1.0 Transitional (W3C).
I have the following error:
> there is no attribute "data-cfasync"
which corresponds to this line:
<script data-cfasync="false" type='text/javascript'>/*<![CDATA[*/window.olark||(function(c){var f=window,d=document,l=f.location.protocol=="https:"?"https:":"http:",z=c.name,r="load";var nt=function(){
Please see the source code:
<!-- begin olark code -->
<script data-cfasync="false" type='text/javascript'>/*<![CDATA[*/window.olark||(function(c){var f=window,d=document,l=f.location.protocol=="https:"?"https:":"http:",z=c.name,r="load";var nt=function(){..................
]]>*/</script><noscript><a href="
<!-- end olark code -->
Please help me to pass validation. | You can’t have a `data-cfasync` attribute in XHTML 1.0.
The custom `data-*` attributes are defined for HTML5 (for both syntaxes, HTML and XHTML).
So either switch to XHTML5, or use a different attribute (e.g., `class`). | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "javascript, xhtml, w3c validation"
} |
What triggers notifications of the form "Bell in session Shell" in KDE?
I'm running KDE on Debian Testing.
From time to time, programs running in a terminal (Konsole) trigger system notifications of the form "Bell in session Shell".
**What triggers these notifications?**
Note: I'm not asking how to disable them - I know there's an option to do so in Konsole -> Settings -> Configure Notifications. I'm asking what behaviour triggers them in the first place, with a view of possibly modifying some of the programs that trigger them to not trigger them, or to trigger them under different conditions. | I believe this is how konsole terminal emulator interprets bells.
Try to run in bash
sleep 3 && echo -e "\a"
Then switch to another app and wait 3 seconds.
Many many years ago when real terminals were connected to big computers, there was a special protocol called "escape sequences" to send commands to such terminals. There are sequences to change color, move to new line, or ring bell. First terminals were equipped with real bells to notify operator about some long-running task is ended.
Any modern terminal emulator (konsole, xterm, or real console when your are in text mode) simply emulates such terminal hence understands such sequences.
The `TERM` env. variable tells the name of emulated terminal. Some libs like `ncurses` then use `termcap` (or `terminfo`) file to find which sequence is used for what on this terminal. | stackexchange-superuser | {
"answer_score": 11,
"question_score": 11,
"tags": "shell, kde, konsole, bell"
} |
Lambert W-Function
Is there a standard name for the inverse of the Lambert W-Function, in the manner that the name "exponential function" is the name for the inverse function of the logarithmic function. | To my knowledge, there is no specific name given to the inverses of any of the special functions, like the error function, the beta and $\Gamma$ functions, hypergeometric functions, etc., and Lambert's W function is no exception to the general rule. | stackexchange-math | {
"answer_score": 1,
"question_score": 3,
"tags": "terminology, lambert w"
} |
Get records 10 min before system datetime in SQL
i need to find the records 10 min before system current datetime.
select Id,TimeStamp from ISAlive where RecordUpdatedDate < GETDATE() --SYSDATETIME() | select Id, TimeStamp
from ISAlive
WHERE RecordUpdatedDate = dateadd(minute,-10,getdate())
might be a starting point. Of course, it probably won't match exactly...
...if you want to get the most recent record that fits that criteria, however, try
SELECT TOP 1 ID, TimeStamp
FROM ISAlive
WHERE RecordUpdatedDate <= dateadd(minute, -10, getdate())
ORDER BY RecordUpdatedDate DESC | stackexchange-stackoverflow | {
"answer_score": 46,
"question_score": 25,
"tags": "sql, sql server, sql server 2005, sql server 2008"
} |
node jitsu cannot find local modules
I have an application successfully working locally so I know the code works. However when I go to deploy to node jitsu I get an error that it cannot find a local module. Here is what I have:
**File Setup:**
/index.js
/config/config.js
**index.js**
var cfg = require('./config/config.js');
When trying to deploy node jitsu is giving me an error:
Error: Cannot find module './config/config.js'
Since all this code works locally I do not believe this is a coding issue. I am under the impression that local modules do not need to be included in package.json but perhaps they do for node jitsu? I read their documentation but cannot find anything special for local modules.
Thanks! | Local modules like this should work properly.. so long as you don't have it in `.gitignore` or `.npmignore`.
Modules in the `node_modules` directory require that you add it to the `bundledDependencies` array in your `package.json` file.
An easy way to check for whether the file is included in your deploy is to run `tar -tf $(npm pack)`. | stackexchange-stackoverflow | {
"answer_score": 11,
"question_score": 5,
"tags": "node.js, nodejitsu"
} |
How to get a particular path from sdcard in android?
I have stored my video file here :-
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraVideo");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
return null;
}
}
Retrieve :-
videocursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
but, I am getting all the video files from sdcard, which I don't want. I want only the files stored in "MyCameraVideo" folder.
Thanks in advance.. | Try this :
String selection = MediaStore.Video.Media.DATA +" like?";
String[] selectionArgs = new String[]{"%MyCameraVideo%"};
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
parameters, selection, selectionArgs, null); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "android"
} |
"I won't stay longer than I can help" or "longer than I can't help"?
I've come across the following sentence recently:
> "I won't stay longer than I can help."
I've heard similar uses of "can help" in other contexts and they all sounded strange to me. Shouldn't we say :
> "I won't stay longer than I can't help."
In the same manner, doesn't it sound strange to say:
> "I'm not driving at night, unless I can help it"
Shouldn't one say "unless I can't help it"? | No, one shouldn't.
If you can help it, you won't do it.
> "I won't stay longer than I can help."
Maybe better is
> "I won't stay longer than I can manage."
meaning
> "I will not stay longer if I don't need to"
or alternatively
> "I will stay longer if I do need to." | stackexchange-english | {
"answer_score": 2,
"question_score": 3,
"tags": "meaning, grammaticality"
} |
How to access ALL of my favorites?
OK, I know where I can find the list of favorites. I know how to sort them using the "added", "recent", ... buttons.
But in the list I have, there are only 9 favorites, but I have about 30 bookmarked. So I am missing some button to access the next page, or am I just to ... to see it? What am i missing?
I am using the latest Opera, but I tried also Firefox.
When I think about it, I am not sure if I did realy 30 clicks on bookmarks, I know that I bookmarked some and the 31 I get from the information when I am moving the mouse on my user name.
!enter image description here | Those numbers represent _changed_ favorites in the specified time period.
(edit: by changes I mean, new answers were added, or new comments on the question. As if you owned the question you favorited.)
They do not represent total favorites. | stackexchange-meta | {
"answer_score": 4,
"question_score": 3,
"tags": "support, user interface, bookmarks"
} |
Preferred way to build gui components tree
What is the preferred way to build application gui components tree?
1. Instantiate all components and build an entire tree, controlling it with show/hide/disable/enable operations on user events.
2. Dynamically creating gui with create/add/remove components based on user events.
I'm especially interested with this design problem in JavaFX. | Sorry, I don't know much about JavaFX.
But, I would suggest option 2. If you instantiate everything at the start, you're going to use up a whole load of memory when you only actually need to use memory for the gui components that are currently visible.
Create all of the components for the current screen, and show/hide/disable/enable them. But don't create components that don't live on the current screen/window/form/dialog. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "user interface, javafx, gui designer"
} |
json key:...,value:.... to value_key:value_value in postgresql
how can I change a list of jsonb structure (key/value) to object, dynamically??
for example:
from
`[{'key':'size','value':'200'},{'key':'pound','value':'200'},{'key':'square','value':'true'},...]`
to
`{'size':'200','pound':'200','square':'true',....}`
select jsonb_array_elements( topi.other_information)->'key' as key_field,
jsonb_array_elements( topi.other_information)->'value' as value_field
from items_data.tbl_items topi
but when I use `jsonb_build_object` i need to know the keys. Is there a way to do it? | You need to unnest the array then aggregate it back using `jsonb_object_agg()`
select t.id, jsonb_object_agg(x ->> 'key', x -> 'value')
from items_data.tbl_items t
cross join jsonb_array_elements(t.other_information) as x(element)
group by t.id
`t.id` is the assumed primary key of the table which is needed to keep the values for the same row together during unnesting and grouping.
* * *
If you need that frequently, maybe it makes sense to write a function:
create function flatten(p_input jsonb)
returns jsonb
as
$$
select jsonb_object_agg(x ->> 'key', x -> 'value')
from jsonb_array_elements(p_input) as x(element);
$$
language sql
immutable;
Then you can use it without a group by:
select t.id, flatten(t.other_information)
from items_data.tbl_items t | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "sql, postgresql, select, jsonb"
} |
How to gracefully terminate a remote service process?
Currently I believe I'm doing a ok job managing my applications remote service. When I'm done using it I can see the onDestroy() called, perfect...
Now the issue is I can see the remote process still hanging, via DDMS or via phone's running processes. Users see this and think I'm doing stuff on the background etc... blaming my app and than asking for an exit button... Truth is they don't need an exit button!
So my question:
> How to gracefully terminate a remote service process?
I could get the PID and kill it but something tells me this might not be the nice way to do this since the service might be restarted again...
Any help would be greatly apreciated!
-Jona | > Currently I believe I'm doing a ok job managing my applications remote service.
Simple solution: get rid of the remote service. If you wrote the app and the service, then you do not need it to be remote. The only time you need it to be remote is if the app and the service are part of two separate apps.
> Now the issue is I can see the remote process still hanging, via DDMS or via phone's running processes.
Of course.
> How to gracefully terminate a remote service process?
You don't. Android will terminate it if and when it chooses to. Hence, the simple solution is to get rid of the remote service process by not having a remote service in the first place. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "android, service"
} |
Using an StringIO object for holding uu.encode/uu.decode data
I would like to do the following:
import StringIO, uu
my_data = StringIO.StringIO() # this is a file-like object
uu.encode(in_file, my_data)
# do stuff with my data (send over network)
uu.decode(my_data, out_file) # here I finally write to disk
The above code works. However, if I implement the previous step as a property in an object:
@property
def content(self):
out = StringIO.StringIO()
uu.decode(self._content, out)
return out.getvalue()
@content.setter
def content(self, value):
self._content = StringIO.StringIO()
with open('value', 'rb') as stream:
uu.encode(stream, self._content)
but when I do it like that, `self._content` is empty (`None`, to be precise). Any ideas? | `self._content` is left with the "current point" at its **end** after the `content.setter` method has written to it. You probably want to add `self._content.seek(0)` at the end of that method so you can next _read_ that pseudo-file from the **beginning** (reading while starting from the end will return "nothing more", quite correctly since it does start at the end, and that's probably what's leaving you with the impression that it's "empty";-). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "python, encoding"
} |
What is the actual purpose of pad via library in Altium Designer?
The Altium Designer has schematic symbol library and PCB footprint library. I understand both of these. However, there is a third one called pad via library.
Pad is the exposed copper on PCB where a component is soldered. It could be a SMT pad or a through hole pad. Via on the other hand is a hole in the PCB whereby a PCB track can go from one layer to another.
That is all there is to know about pad and via isn't it? Then why would anyone need to create a library of these? This is new to me. | Here (from here) is an illustration of several types of vias used in HDI (high density interconnect) boards, including the simple through hole via you mention:
 < but not sure if they have been using Facebook API or some other technique.
Instead of going 3rd party I would prefer using Facebook API for this type of purposes if possible. | No, that´s not possible. You can only search for Pages by name: <
There is no "top list", and you can´t get Pages by category. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "facebook, facebook graph api"
} |
Dar um loop infinito
eu presiso de um comando que faz um loop em taskkill, exemplo:
> Se o processo estiver aberto, será detectado o processo e ativara o taskkill, mas também quero que outros comandos diferentes executem, se você não entendeu, é assim:
> o batch identifica o processo em um loop, e executem outros comandos além do taskkill
só que não achei nada sobre isso. | Seria algo assim, no caso esse batch verifica a cada 5 segundos se o processo existe e se existir finaliza ele com taskkill e executa mais alguns comandos (comando2, comando3...) que você pode substituir com os comandos que você quiser.
@echo off
:Loop
Tasklist |find /i "NomeDoProcesso.exe"
if %errorlevel% equ 0 (
taskkill /im "NomeDoProcesso.exe" /f
comando2
comando3
comando4
)
timeout /t 5
goto :Loop | stackexchange-pt_stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "cmd, batch"
} |
Check if JNA is enabled in Cassandra
I know from other posts that Cassandra writes some warning in log files if JNA is not configured properly. My log files (cassandra.log and system.log) do not contain the word "jna" (all case checked). Can I assume that JNA is configured correctly for my instance of Cassandra ?
Is there any way to check if the JNA configuration is correct ? | If JNA is configured properly, you should see a message in your log like this:
INFO [main] 2014-06-06 15:55:11,664 CLibrary.java (line 121) JNA mlockall successful
Also in your log, the JNA library should appear in your classpath output:
INFO [main] 2014-06-06 16:47:13,318 CassandraDaemon.java (line 191) Classpath:...
....:/usr/share/java/jna.jar: | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 9,
"tags": "cassandra"
} |
C# List Contents of Given Directory
How do I list the contents of a given directory?
We can say `private string directory = @"C:\";` and what I then want is to use `Console.WriteLine()` to display the contents of `directory`.
However, after hours of research on this site, I still could not find an answer that worked. I have tried solutions like `Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories))` but the code failed to build. **How do I fix this?**
I have this at the beginning of my code:
using System;
using System.Collections.Generic;
using System.Text;
Am I missing something? What am I doing wrong? How do I fix this? | Directory.EnumerateDirectories().aspx) returns an enumeration of all subdirectories of the specified directory.
foreach (var dir in Directory.EnumerateDirectories(@"C:\"))
{
Console.WriteLine(dir);
}
If however or in addition you wish to specify all files, use File.GetFiles().aspx)
foreach (var file in Directory.GetFiles(@"C:\"))
{
Console.WriteLine(file);
}
Both of these are in the System.IO namespace, so include this in your using section
using System.IO; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, console, directory"
} |
How can i calculate all the selected files overall size?
I have this code where I select files using `openFileDialog`:
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Multiselect = true;
openFileDialog1.FileName = "";
if (this.openFileDialog1.ShowDialog() != DialogResult.Cancel)
this.txtUploadFile.Text = this.openFileDialog1.FileName;
FtpProgress.files = this.openFileDialog1.FileNames;
if (filesn != null)
{
label9.Text = (FtpProgress.files.Length + filesn.Length).ToString();
}
else
{
label9.Text = FtpProgress.files.Length.ToString();
}
}
In label9, I show how many files selected now I want to show in label10 the overall size of all the selected files.
How can I do it? | You can get the size of the file using `FileInfo` class, and get the total size using Linq:
var totalSize = FtpProgress.files.Sum(f => new FileInfo(f).Length);
This will return the total size in `bytes`. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "c#, .net, winforms"
} |
$|G:H|=2$ and $H$ abelian then $H \subset Z(G)$
I have to show whether this is true or false:
> $|G:H|=2$ and $H$ abelian then $H \subset Z(G)$
I have proved that $H \triangleleft G$, but with this I can show that if $h \in H, g\in G$ then exists a $h_1 \in H$ such that $ghg^{-1}=h_1$. I would need to show that $h = h_1$ or find a counter example. I've been thinking of one, since I can't find why should be that $h = h_1$ with no luck
Thanks | _Hint:_ Consider $G=S_3$ and $H=\langle (123) \rangle$. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "abstract algebra, group theory, abelian groups"
} |
What does this ruby operator mean $?
What does the `$?` Ruby operator mean?
I know that it is used for system calls and can be used to tell if a system call was successful.
I tried searching for documentation but couldn't find it. | There is no `$` operator. `$` is used to prefix global variables. What you're thinking of as an operator is actually just a bunch of predefined global variables that Ruby provides for you, which happen to have odd names like `$!` and `$:`.
See < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -2,
"tags": "ruby, system"
} |
Accessing data in variables in class Python 3
I am using Python 3.5 and wish to do something like this I have created a class which has variables `Bitcoin`, `Monero` , 'Etherum' ,etc with various integer values ,I wish to extract them
var1="Bitcoin"
value=classobj.var1 // there is a class which has a variable called Bitcoin and its value is 10 I wish to get its value using classobject.Bitcoin but the variable called var is Dynamic
print (value)
How do I achieve the same ?
**EDIT**
I know it is possible using switch statement but I am looking for other ways | This is almost always a bad idea—and you really should explain why your design looks like this, because it's probably a bad design.
But "almost always" isn't "always", so Python has a way to do this:
getattr(classobj, var) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, class, object"
} |
Segmentation fault(core dumped) when printing pointer's information
I'm reading in my input and putting it in a pointer. I have used malloc so I'm not sure what wrong
CODE:
#define BUFFER 30 //in my .h file
char *inStr;
inStr = malloc(sizeof(char*)*BUFFER);
scanw("%s", &inStr);
inStr[strlen(inStr)] = '\0';
mvwprintw(stdscr, 0, 0, "%s",inStr);
I'm trying to output it onto a ncurses board and am not sure why this is happening. It crashes when I press enter for the input | First item, for a "%s" format, you need to pass a pointer to a buffer. You are actually passing a pointer to a pointer to a buffer. Drop the &. Second, strlen is defined by the presence of a null at the end, so using it to determine where to put a null is a bit nonsensical. Instead, you have to trust scanw to terminate it properly. Note that is a HUGE assumption and is a big part of why the whole scanf family is troubled by buffer overruns - the function has no idea how big the buffer is. Also, as others point out, your malloc size is off - you probably just want something like `malloc(BUFFER)` \- note sizeof(char) is 1 by definition.
char *inStr;
inStr = malloc(BUFFER);
scanw("%s", inStr);
mvwprintw(stdscr, 0, 0, "%s",inStr); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -1,
"tags": "c, string, input, ncurses"
} |
CSS Central Column for Content
I am almost certain that this question has been asked and answered before, however I have failed to find it, maybe because I just cannot explain myself properly in words. What I currently have is a design for my new website, but what I cannot seem to figure out is how to make a central column for content. Let me illustrate for you.
This is what it currently looks like:
<
And this is what I would like it to look like:
<
Apologies if I am not making myself clear enough. Any help is greatly appreciated! | Try this:
.centerDiv {
text-align: center;
width:80%;
margin:0 auto;
background:cyan;
}
<div class="headerContainer">
<div class="centerDiv">center</div>
</div> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, css"
} |
Can i use this syntax in ORACLE ?(SUM(CA.DEPT)=SUM(CA.RECEIVABLE)
Can I use this syntax in ORACLE? `SUM(CA.DEPT)=SUM(CA.RECEIVABLE)` I need to take where total dept and total receivable are equal. If it is wrong what I can use instead of this?
SELECT CA.DEPT,CA.RECEIVABLA
FROM CUSTOMER_ACCOUNT CA
INNER JOIN CUSTOMER_BACKUP CB
ON CA.C_CODE=CB.C_CODE
WHERE SUM(CA.DEPT)=SUM(CA.RECEIVABLE) | > If it is wrong what I can use instead of this?
This is one method
SELECT
ca.dept,
ca.receivabla
FROM
customer_account ca
INNER JOIN customer_backup cb ON ca.c_code = cb.c_code
GROUP BY
ca.dept,
ca.receivabla
HAVING SUM(ca.dept) = SUM(ca.receivable) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "oracle, function, sum"
} |
Nunit - global method executed before each test
Is there any possibility to define a method with Nunit, that would execute before _each_ test in the assembly?
To be perfectly clear: I do NOT want to execute some code _once_ before _all_ tests, but I need to do some general setup before each test. So if i have 10 tests, I want my method to be executed 10 times.
Inheritance is sadly not an option to me (I already use it for a different purpose and cannot mix) | You can define an Action Attribute that contains the desired code in its Before method. Apply it to the assembly with an argument indicating it should be used for every test.
Note that Action Attribute works a bit differently between NUnit 2 and 3, so be sure to check the appropriate level of the docs. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 16,
"tags": "c#, nunit"
} |
pfSense firewall and multiple https servers
I'm using pfSense as our office firewall and am attempting to setup a second HTTPS server that needs to be visible to the outside. Because they are HTTPS servers, they need separate IP addresses. How do I configure pfSense to accept the other static IP addresses I've gotten from our ISP?
Assigned IPs: x.x.x.24-27 Gateway is x.x.x.28 pfSense version: 2.2.6
I've tried adding more NIC ports to the firewall, but pfSense doesn't like multiple interfaces using the same gateway.
pfSense documentation implies that an interface can't have multiple IP addresses and that wouldn't in this case anyhow, since the port 443 traffic needs to be separated out and redirected to different servers.
Virtual IPs sound promising, but I haven't managed to get one to ping yet.
Any suggestions on where I should be looking? | You don't want additional NICs. Just add virtual IPs on WAN for each additional IP. If it's cable service, you often have to power cycle the cable modem after doing so before the IPs will work.
> "pfSense documentation implies that an interface can't have multiple IP addresses"
What'd you see that seemed to imply that? There certainly isn't anything intending to imply that. | stackexchange-serverfault | {
"answer_score": 0,
"question_score": 0,
"tags": "pfsense"
} |
Rails mountable engine: class can't be called using variable
The following in a private controller method:
@commentable = params[:commentable].classify.constantize.find(commentable_id)
Gives me an error:
`uninitialized constant Question`
While doing the following (hard coding the class name):
@commentable = Question.find(commentable_id)
Works just fine.
Any help would be greatly appreciated. | @commentable = "MyEngine::#{params[:commentable].classify}".constantize.find(commentable_id)
Apparently you have to create a string with your engine name in it. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, ruby, ruby on rails 3, ruby on rails 4"
} |
"ffmpeg": java.io.IOException: error=24, Too many open files
I am working with ffmpeg to generate previews, but I get this error in the middle of the execution of my program:
"ffmpeg": java.io.IOException: error=24, Too many open files
Does anybody know how to solve or how to avoid it??
I add the piece of code where I use ffmpeg:
for (int j = 0; j < temp.length; j++) {
if(j==2){
String preview = temp2[i] + temp[j] +".jpg";
Process p = Runtime.getRuntime().exec("ffmpeg -i anotados/" +temp2[i] + " -r 1 -ss 00:00:"+temp[j]+" -t 1 -s 158x116 imagenes/" + preview);
TextOut.write(preview+"\n");
}
} | Check your `ulimit -n` output to see how many open files processes spawned from that shell are allowed to have. Historical Unix systems had a limit of 20 files, but default on my Ubuntu desktop is 1024 open files.
You may need to raise the number of open files you are allowed in the `/etc/security/limits.conf` file. Or, you may need to modify your application to more aggressively close open files.
Another possibility is a system-wide limit on number of files that may be open. I don't know which modern systems would still have such limits in place, but a first place to look would be `sysctl -a` output. (Well, maybe _second_ place, after system documentation.) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 4,
"tags": "java, file"
} |
Where can I find the link icon in Polarion?
I read the tutorials of the demoversion of the _Polarion REQUIREMENTS_ software. On the page _How to link_ , one can read the following: 
out = s.a
end
How can I get it to access the structure s.hello with call('hello') or someting like this?
side question: Is it also possible to access a Variable "hello" with such a function?
Thanks in advance, you guys are awesome! | I would use dynamic structure access like so:
s.(a)
Learn more at the Mathworks website!
Also, if we look at your example function, I notice you're not passing in the structure as an argument, maybe it's global, but here an example of this technique using your function as a framework:
function out = call(s,a)
out = s.(a);
end
Then to use the function, I try:
>> s = struct('hello',42)
s =
hello: 42
>> call(s,'hello')
ans =
42
Works great with no recursion limit! If you're still getting a recursive function, try adding more of your code to the question, we'll get to the bottom of this!
HTH | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "string, matlab, function"
} |
In Javascript a dictionary comprehension, or an Object `map`
I need to generate a couple of objects from lists in Javascript. In Python, I'd write this:
{key_maker(x): val_maker(x) for x in a_list}
Another way to ask is does there exist something like `jQuery.map()` which aggregates objects? Here's my guess (doesn't work):
var result = {}
$.map(a_list, function(x) {
$.extend(result, {key_maker(x): val_maker(x)})
}) | Assuming `a_list` is an Array, the closest would probably be to use `.reduce()`.
var result = a_list.reduce(function(obj, x) {
obj[key_maker(x)] = val_maker(x);
return obj;
}, {});
Array comprehensions are likely coming in a future version of JavaScript.
* * *
You can patch non ES5 compliant implementations with the compatibility patch from MDN.
* * *
If `a_list` is not an Array, but a plain object, you can use `Object.keys()` to perform the same operation.
var result = Object.keys(a_list).reduce(function(obj, x) {
obj[key_maker(a_list[x])] = val_maker(a_list[x]);
return obj;
}, {}); | stackexchange-stackoverflow | {
"answer_score": 61,
"question_score": 86,
"tags": "javascript, jquery, python"
} |
Idiom meaning that something doesn't happen often, but happens more than needed when it does?
I remember that there was an idiom that describes something that doesn't happen often, but happens more than needed when it finally does.
Hypothetical scenario that could be described by such an idiom: Let's say that I spend the whole year asking for a Playstation 4. When Christmas comes around three family members offer me the same console. | An alternative saying to the good one suggested by @Dan Bron is:
**_When it rains, it pours_**
> * When something good or bad occurs, it usually occurs more than once and often within a short period of time:
>
> * “I have a new supervisor at the office, three new assistants to train, and enough work to keep me busy for months — when it rains, it pours.” (AHD)
> | stackexchange-english | {
"answer_score": 34,
"question_score": 8,
"tags": "idiom requests"
} |
activemq deny remote connections
I am trying to run ActiveMQ with Maven using the following command
mvn org.apache.activemq.tooling:maven-activemq-plugin:5.7.0:run
This does work locally, but it blocks remote connections. How can I make ActiveMQ accept remote connections? | Adding to Aksel Willgrets answer.
You need a custom conf (somethings like the deafult activemq xml config that ships with the stand alone dist).
This page documents the maven plugin, read it.
<build>
<plugins>
<plugin>
<groupId>org.apache.activemq.tooling</groupId>
<artifactId>activemq-maven-plugin</artifactId>
<version>5.8.0</version>
<configuration>
<configUri>xbean:file:../conf/activemq.xml</configUri>
.. etc.
That activemq.xml should point out a transport connector (see Aksel Willgerts answer or use the default xml file from ActiveMQ). | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "maven, activemq"
} |
How do I add HTML 5 type attribute to laravel blade?
I have this line in blade format
{{ Form::text('date', null, array('class' => 'form-control', 'type' => 'Date', 'placeholder' => 'Date' )) }}
but when the page loads the type attribute does not get resolved to 'date', it goes to 'text'.
How do I get this in blade?
<input class="form-control" type="date" placeholder="Date" name="date"> | Use Form::input()
Form::input('date', 'date', null, ['class' => 'form-control', 'placeholder' => 'Date']);
Additionally, you can create a Form Macro to "add" methods for HTML5 attributes, such as `date`, `email`, `time`, etc. | stackexchange-stackoverflow | {
"answer_score": 18,
"question_score": 6,
"tags": "php, html, forms, laravel, laravel blade"
} |
.Net MVC pagination library
I am working on my first .Net MVC project, and I need paging support on several pages.
What library do you recommend for this? | PagedList.Mvc
Its used in the paging section of the getting started tutorial on asp.net itself. | stackexchange-softwarerecs | {
"answer_score": 1,
"question_score": 1,
"tags": "web development, .net, mvc"
} |
QGLWidget context destruction
I have a class named `Mesh` which wraps and OpenGL object, with VBO, texture, etc. This class inherits from `QObject` and its parent is set to my `QGLWidget`. So as soon I close the widget it will get deleted by QObject system.
But I have a problem because this mesh class has a destructor that does some OpenGL calls to cleanup. When QObject child destructor kicks in, the OpenGL context is already destroyed and I get a segfault.
How I can make sure that my `~Mesh()` destructor will get called before `QGLWidget` context gets deleted? | You could delete the `Mesh` object explicitly in the destructor of your `QGLWidget` derived class, because everything you put in there would be executed before `~QGLWidget()` itself (and before `~QObject()` which is responsible for the deletion of child objects).
Or you can make the object a non-pointer member, or wrap it in a smart pointer to achieve the same result. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, qt, opengl, qobject, qglwidget"
} |
Adding another link after id does not trigger child state
I'm trying out angular-ui-router's child state and I want to add another link after an id but it doesn't seem to trigger. Example would be:
Parent url: `parent/:id`
Child url: `parent/:id/child`
Here's a plunker of my problem: < | I suggest you to use `ui-sref` as
`ui-sref='parent.child({id:15})'`
here is updated plunker
from your plunker **parent.html**
<p> I am the parent dude! </p>
<a ui-sref='parent.child({id:15})'> A link to my child </a>
<ui-view></ui-view>
Ui-sref api references | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "angularjs, angular ui router"
} |
Gulp sequence for streams
So I have stream1 who writes to dest and I have stream2 who in it's process reads the written file from stream1.
How do I manage to run them in sequence.
There's gulp-sequence but **I need to run streams in sequence in one task and not tasks in sequence.** | OK so i've written a code of my own to do it, you are welcome to create a plugin out of it, and also improve it. enjoy:
var es = require('event-stream');
function sequance(streams){
var ps = es.pause();
ps.pause();
(function runStream(i){
if(i >= streams.length){
ps.resume();
return;
}
var stream = streams[i];
stream = _.isFunction(stream) ? stream() : stream;
stream.on('end', function(){
runStream(i + 1);
});
})(0);
return ps;
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, gulp, sequence"
} |
Safe way to truncate SQL Server Error Log
We are running out of space. What is the safe way to clear the error log?
!What is the safe way to clear this? | You can cycle the error log by calling `sp_cycle_errorlog` and then that will close the current error log and cycle the log extensions. Basically, it'll create a new error log file that SQL Server will be hitting. Then the archived error log(s) can be treated accordingly (delete/move with caution). This will not technically "truncate" the log, it'll just roll it over and you can handle the old logs as you so please, like any other file system file.
When you do this, you should see a new log file with an entry that resembles the following:
> The error log has been reinitialized. See the previous log for older entries.
BOL reference on `sp_cycle_errorlog` | stackexchange-dba | {
"answer_score": 20,
"question_score": 17,
"tags": "sql server, sql server 2008 r2, disk space, errors, truncate"
} |
Div updating with image dynamically..... JSF
How to replace an image in DIV dynamically on click of some other div image as shown in image. Requirement is like that : on click of "DIV1" root should be updated with 1.. on click of "Div2" root should be updated with 2 like that. All div having image loading from some URL and Root is a bigger div. !enter image description here
please reply ... | You can do something like this:
<div>
<h:graphicImage id="root" value="#{managedBean.rootImage}" alt="image"/>
</div>
<div>
<h:commandLink>
<h:graphicImage value="images/image1.png" alt="image1"/>
<f:setPropertyActionListener target="#{managedBean.rootImage}" value="images/image1.png" />
<f:ajax event="action" render="root"/>
</h:commandLink>
</div>
And in your ManagedBean create setter/getters like this:
public class ManagedBean{
public String rootImage;
public void setRootImage(String image) {
this.rootImage= image;
}
public String getRootImage() {
return rootImage;
}
}
Reference: JSF - Two Questions about actions on UIComponent | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "java, jsf, jstl"
} |
Is there a Rails gem for management of a "multi-visit pass" scenario?
I'm a Rails noob. I'm looking to implement an application where users can purchase a multi-visit pass, then spend the credits week-by-week.
For example, register and login, then purchase 10 visits at a gym - the system should list _10 remaining visits_. Sign up to a class and _9 remaining visits_ are listed. When the credits are low, remind the user to top them up with another 10-visit pass, etc.
I know I can use Devise and CanCan to manage the authentication and authorisation aspects.
My question is whether there's already a gem to handle the management of the user's credits, or whether I'd need to write this from scratch.
I've searched < with no luck, but it's entirely possible I'm missing something obvious. | I don't think there is a gem to do that, but it should be pretty simple to code:
* Add `remaining_visits` to your User model and table.
* Do `current_user.update(remaining_visits: current_user.remaining_visits+10)` when a ticket is purchased.
* Copy Devise sessions controller into `app/controllers/devise/sessions_controller.rb`.
* Inside this controller, add this kind of code to `create` (where the user logs in): `current_user.update(remaining_visits: current_user.remaining_visits-1)`.
Note: Instead of copying Devise sessions controller you can just overwrite the `create` action. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ruby on rails, rubygems, user accounts"
} |
UIPickerView next to UIDatePicker not rendering per IB?
Why isn't the actually simulator rendering of my view not matching that in interface builder. I have a UIPickerView next to UIDatePicker looking good in IB, but not in the simulator. In particular the large gap inbetween, and the fact the right hand side fo the time picker goes off the edge of the screen.
Any ideas?
!enter image description here | This happens because `UIDataPicker` always re-renders itself with a static bounds (one landscape mode, one for portrait). So you can change its position but not shape. I've bumped into this fact recently. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "iphone, ios, interface builder, uipickerview, uidatepicker"
} |
JNI style signature of the method
How do you generate the JNI style signature of a method? I need it as a parameter to this particular class's function sendMessage(...):
<
Thanks for any help. | Use `javap -s`. You can do it by hand following the rules in the JNI Specification but at best you will only come up with what `javap -s` would have told you in seconds and at worst you will get it wrong and have a debugging nightmare. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "java, java native interface"
} |
Replace String "Development" with "Staging" or "Production" using SED
I am trying to replace the string
: 'development'
with
: 'production'
using `sed`.
I tried a few options including:
sed -i "s|: \'development\'|: \'staging\'|g" index.php
but without any luck. Output:
sed: 1: "index.php": command i expects \ followed by text
Can someone help? | You don’t need to escape single quotes inside double quotes, see this answer of mine:
> Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of `$`, ```, `\`, and, when history expansion is enabled, `!`.
Thus, these work:
sed -i "s/: 'development'/: 'staging'/g" index.php
sed -i "s|: 'development'|: 'staging'|g" index.php
sed -i 's|: '\''development'\''|: '\''staging'\''|g' index.php | stackexchange-askubuntu | {
"answer_score": 5,
"question_score": 3,
"tags": "command line, sed"
} |
Having trouble getting git to commit after setting origin
I'm trying to get a handle on using git. I've been using it on my PC running Kubuntu. I installed git flow and everything works like a champ.
Now, however, I need to start using a repo on my server. So, I SSH'ed into the box and created a directory for my repos and one inside of it for this particular repo. Then I moved into the directory and ran:
git init --shared --bare
Then I went to the directory of my app and did the following:
git remote add origin 192.168.1.5:/home/will/Repo/testgit
git push origin master
I tried creating another directory elsewhere on my system and then running:
git clone 192.168.1.5:/home/will/Repo/testgit
However, nothing was in the directory. I also tried going back to my original directory, doing:
git commit
git push origin master
It said there were no changes. How do I fix this?
Will | You need to stage your files before committing them.
git add <path to your files>
Also you should set the files that git should ignore by making a .gitignore file in the root folder which contains the patterns of what to ignore. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "git"
} |
Proper grammatical usage of 'had' vs 'having'
> Mr. X was cast as Inspector Y, despite not being able to speak English and _had_ no idea what he was saying in the film.
> Mr. X was cast as Inspector Y, despite not being able to speak English and _having_ no idea what he was saying in the film.
Can someone please explain which of these two versions is grammatically correct, and why? | ## The second version is correct, by the principle of parallelism.
Let's break down what this sentence is actually saying:
> Mr X was cast as Inspector Y despite two facts: (1) he wasn't able to speak English; (2) he had no idea what he was saying in the film.
These two facts are _parallel_ to each other, so they should have the same grammatical structure in the sentence, e.g. both being in the participle form as in your second quoted sentence. | stackexchange-english | {
"answer_score": 1,
"question_score": 1,
"tags": "grammaticality"
} |
Table View selection and pan gesture
I have a table view with a pan gesture on it. When I start panning the tableview up and down the tableView selection gets disable and I can't select tableview cells.
UIPanGesture* tablePanGesture =[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(gestureHandler:)];
tablePanGesture.delegate = self;
[tableView addGestureRecognizer:tablePanGesture];
[tablePanGesture setCancelsTouchesInView:NO];
And I using the following delegate to let my gestures and tableview gestures work together:
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
I have implemented the method for table view didSelectRowAtIndexPath but when I use panning it is not called. Is there any conflict between pan gesture and tableview Delegate? | **You are missing this line:-**
[tablePanGesture setCancelsTouchesInView:NO];
This will let the UIPanGesture recognize the pan gesture and also pass the touch to the next responder means your table view select or tap. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "ios, objective c, iphone, uitableview, uigesturerecognizer"
} |
EF5: How to alter the default Delete function to implement my own
Well, here is my situation:
We have tables that we dont want ever to delete the data. There is a column which is called isDeleted that is supposed to be updated instead instead of deleting it.
I want to develop the accompanying web app with EF5 but i have a problem there. How do i implement that restriction?
I could use stored procedures to delete and select but i was hoping for a way to use the standard functions in EF, just changing how they work. Which way is less arduous and what options i have to achieve what i want, since i´m guessing i´m not the first person to ask for this? | You can override SaveChanges method of your DbContext. E.g. you want to forbid deleting products. You can save entities with IsDeleted flag set to true instead of deleting them:
public override int SaveChanges()
{
var deletedPersonEntries = ChangeTracker.Entries<Person>()
.Where(e => e.State == EntityState.Deleted);
foreach (var e in deletedPersonEntries)
{
e.State = EntityState.Unchanged;
e.Entity.IsDeleted = true;
}
return base.SaveChanges();
}
Another option - raise exception if someone tries to delete product:
if (deltedProductEntries.Any())
throw new Exception("You should not delete products!");
You also can simply set entities state to unchanged, but I don't think its very good solution. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 4,
"tags": ".net, entity framework"
} |
dynamically added option to select is invisible
I am trying to add options to an empty select.
The problem is when I add an option with jQuery or with javascript the added option doesn't appear I tried to debug the function that add the option it is actually adding it to the html but I can't see it on the web site
The select :
<select class="selectpicker" id="partners_id">
</select>
The jquery :
$("#partners_id").append(('<option>', {
value:1,
text:'One'
})) | Try this. You forgot to add $ in append function.
$(document).ready(function(){
$("#partners_id").append($('<option>', {
value:1,
text:'One'
}))
})
Append using button click
$(document).ready(function(){
$( "#btn" ).click(function() {
$("#partners_id").append($('<option>', {
value:1,
text:'One'
}))
});
}) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "jquery, html, bootstrap select"
} |
Can anyone help with paramaterization of conics?
Im struggling to wrap my head around an example. It considers the conic $$ x^{2}+y^{2}-z^{2}=0 $$ then proceeds:
Take $A=[1,0,1]$ and the line $P(U)$ defined by $x=0$. Note that this conic and the point and line are defined over any field since the coefficients are 0 or $1 .$ A point $X \in P(U)$ is of the form $X=[0,1, t]$ or $[0,0,1]$ and the map $\alpha$ is
\begin{align} \alpha([0,1, t]) &=[B((0,1, t),(0,1, t))(1,0,1)-2 B((1,0,1),(0,1, t))(0,1, t)] \\\ &=\left[1-t^{2}, 2 t, 1+t^{2}\right] \\\ \text { or } \alpha([0,0,1])=[-1,0,1] . \end{align}
How do I evaluate $B(v,v)$ or $B(v,v)(a,b,c)$ like they have to go from the first line to the second?
and also why is a point $X \in P(U)$ of the form $X=[0,1, t]$ or $[0,0,1]$
here is the source for reference:<
any help would be fantastic! | For the first question, it is exactly evaluation of a bilinear form, given by the matrix B, on the given vectors: so $B(v,w)=v^tBw$. This gives you a scalar which is understood multipling the following vector.
For the second one, when you have a projective line $l$ and two dinstinct points $P,Q$ on it then every other point can be written as $\lambda P+\mu Q$, for $[\lambda,\mu]\in\mathbb{P}^1$. So you can define $t=\mu/\lambda$, if $\lambda\neq 0$, and consider $l$ as the points in the form $ P+tQ$ union the remaining point corresponding to $\lambda = 0$. | stackexchange-math | {
"answer_score": 0,
"question_score": 1,
"tags": "linear algebra, algebraic geometry, conic sections, algebraic curves, parametrization"
} |
Flask app.route("/authors/add" button Could not build url for endpoint '/authors/add'. Did you mean 'authors' instead?
I added a button to add an author in my authors.html page but the button's url is causing problems with this error
werkzeug.routing.BuildError: Could not build url for endpoint '/authors/add'. Did you mean 'authors' instead?
authors.html
<a href="{{ url_for('/authors/add')}}"> <button type="button" id="addAuthorButton" class="btn-primary" name="button">Add Author</button></a>
routes.py
@app.route("/authors")
def authors():
....
@app.route("/authors/add",methods=['GET','POST'])
def addAuthor():
form =createAuthorForm()
return render_template('addAuthor.html',form=form) | `url_for()` takes a function name as a parameter, not an url. Try this:
<a href="{{ url_for('addAuthor')}}"> … | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "python, flask, routes"
} |
Creating and using an object after being inserted into DB [nodejs]
I have a user class and a database class:
User.js
const Database = require('./database')
const myDB = new Database()
function User (userID) {
this.userID = userID
myDB.insertUser(userID)
}
Database.js
function Database () {
const db = new sqlite3.Database(dbName)
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS ${userTable} (user_id TEXT, balance INT)`)
})
db.close()
}
Database.prototype.insertUser = function (userID, cb) {
// code
}
Database.prototype.getName = function (userID, cb) {
// code
}
I want to do the following, but am unsure as to how to do it synchronously:
const john = new User('john')
console.log(john.getName())
What are the best practices on creating objects that are added to the DB but then used straightaway? | Insertion and reading from DB is an async operation, you have to use either callback or promise. I can see you have defined callbacks but not using it properly.
I'm assuming your insertUser and getName function looks like below.
Database.prototype.insertUser = function (userID, cb) {
// code reading data
cb(null,data)
}
Database.prototype.getName = function (userID, cb) {
// code
cb(null,data)
}
function User (userID,cb) {
this.userID = userID
myDB.insertUser(userID,cb)
}
new User('john', (err, data) => {
this.getName('john', (err, result) => {
console.log(result);
})
}); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "node.js, sqlite"
} |
Gnome's ALT+F2 sometimes freezes while loading icon or completion
I use `Alt`+`F2` a lot in Gnome 2. But when I enter, say, `fir` it sometimes freezes for up to ten seconds in order to complete it to `firefox`. Sometimes, it completes, even got the icon loaded, but does not let me click on run. After a few seconds it just launches the program since I already clicked the button.
Is there any way to un-freeze this? | This seems to be the Bug 133243 tracked at Gnome Bugzilla.
_Ross Girshick_ made a theory trying to explain why this happens and proposed some solutions that needs to be made at the code of the app.
"The problem here, as noted, is that in order to fill g_complete every file in the user's path is access'd and stat'd. This happens once everytime the run dialog is created. On some systems this takes a long time to complete (10-20 seconds on my old PIII 650 latop with gentoo). However, once the kernel has cached the inodes it is much faster to run in the future." | stackexchange-askubuntu | {
"answer_score": 2,
"question_score": 2,
"tags": "gnome"
} |
Angular4: how to access constants in html as href?
I work on angular4. My project has a constant file and that file has an `emailURL`. I have to access `emailURL` on my HTML page but chrome throws an error `Template parse error`. Below is my code
constant.ts
export const CONST_CLASS{
'emailURL':'
}
HTML
<a href=" '{{MY_CONST_CLASS.emailURL}}' + useremail">Username</a>
TS
import { CONST_CLASS } from '../constants';
@Component({
// ...
})
export class MyTestComponent implements OnInit {
public MY_CONST_CLASS = CONST_CLASS;
// ...
}
I also tried below 2 synatx but URL is not getting formed correctly. Please guide me where did I go wrong.
<a href="{{MY_CONST_CLASS.emailURL}}+ useremail">Username</a>
and
<a href="'MY_CONST_CLASS.emailURL' + useremail">Username</a> | It should be
<a [href]="MY_CONST_CLASS.emailURL + useremail">Username</a>
or
<a href="{{MY_CONST_CLASS.emailURL}}{{useremail}}">Username</a>
or
<a href="{{MY_CONST_CLASS.emailURL + usermail}}">Username</a>
that all assumes that your TS component has `usermail` field defined.
export class MyTestComponent implements OnInit {
public MY_CONST_CLASS = CONST_CLASS;
usermail="set it here or somewhere else in component's code";
// ... } | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "angular"
} |
Batch ECHO and echo
I have seen lots of people codes and some times the echo's are in capitals like:
echo hello
and
> "%Temp%\done.vbs" ECHO x=msgbox("message" ,6, "test")
Does it make any difference whether it is a echo or an ECHO. Thanks if any one can help. | It doesn't make any difference, it's pure optic. `Cmd`/batch commands are always case insensitive. It doesn't matter to the parser if you write `ECHO`, `Echo`, `echo` or `eChO`.
Some people like it to write commands in Capitals because the code is a bit more readable.
Others (like me) use both versions, for example, `ECHO` for debugging messages (which will be removed later) and `echo` for permanent messages. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "batch file, echo"
} |
Outputting both stopped and Running processes in linux?
I'm presently using a Linux command in my c program to show a group of processes. When a process is stopped (suspended) though, this command does not list it. I need to list both running AND stopped jobs. **Note:** When I say stopped, I do NOT mean terminated jobs. The issue is with displaying suspended processes.
execvp("/bin/ps", parmList);
I have to use the ps command. Is there anyway to show both running and stopped (suspended) processes in this situation? | There are two ways to go about it:
1) Continuously monitor processes for change in state.
2) Register a handler to get notified asynchronously, when state changes.
> 1st case
execute a script that continously monitors process states. You have to use ps with BSD style options ie
ps axo pid,stat
> 2nd case
you can only monitor the child processes. you can monitor them by using `waitpid()` provided they are child processes.
So, basically you register a handler for signals and in the handler you use waitpid to get the status.
You will find the signals explained here: [< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "c, linux, linux kernel, ps"
} |
What does the notation $p_t = \text{max}_{i<t} p_i$ mean in algorithm 1 of the prioritized experience replay paper?
I am having a hard time converting line 6 of the prioritized experience replay algorithm from the original paper into plain English (see below):  are given maximal priority. On line 6 this would be done for every transition in an initial pass since the history is initialized as empty on line 2.
I’m having trouble with the notation $p_t = \text{max}_{i<t} p_i$. Can someone please state this in plain English? If $t$ = 4 for example, then $p_t$ = 4? How is this equal to max$_{i<t} p_i$.
It seems in my contrived example here, max$_{i<t} p_i$ would be 3. I must be misreading this notation. | From my interpretation what it means is that $p_t$ is the priority value associated with each transition and $p_t = max_{i<t} p_i $ means that the priority of transition number $t$ will be the maximum between the values of the priorities of the previous elements.
Example: since $p_1$ is initialized to $1$, all the new experiences will be too: \begin{equation} p_2 = max\\{p_1\\} = 1, \end{equation}
\begin{equation} p_3 = max\\{p_1,p_2\\} = 1, \end{equation}
\begin{equation} p_4 = max\\{p_1,p_2,p_3\\} = 1. \end{equation} | stackexchange-ai | {
"answer_score": 0,
"question_score": 0,
"tags": "reinforcement learning, dqn, deep rl, experience replay, double dqn"
} |
Where should I read up on sorting posts in rails?
Just an open ended question - I'm using rails 3.0.9. I want to experiment with sorting systems. I'll want to start with a simple upvote/downvote system, and then try out more complex iterations.
However, I would want not to sort simply on upvotes/downvotes but provide a controllable skew for time (so that really interesting posts eventually give way to new ones).
Anyone have any suggestions on where to read about these sorting algorithms either generally or in rails(3)-specific sources?
Thanks everyone! | try meta-where meta-search in this project sorting was talked about using meta-search gem. i hope this helps | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails 3, datetime, sorting, rating"
} |
Has the Rasberry Pi website taken on a new theme?
I was just popping over to the Raspberry Pi blog/official site to check out the news about a ported GPU driver (which can be read here) and I noticed that the site looks ... different.
Take a look at the screenshot:
!screenie of RPi Blog
Is this just me, or did they change the design for something and I missed it? | There is a post by Liz talking about the new design, and
> [...]which we plan on using to repel new customers from now on.
It's supposedly also designed for good reading on an RPi. I think, we can safely assume this madness will be over by tomorrow. (The question that stays is wheter the Quake III bounty is an April's Fools as well, or not...) | stackexchange-raspberrypi | {
"answer_score": 3,
"question_score": 1,
"tags": "official foundation"
} |
Where do these Paths intersect
We have two paths:
$r(t)=\langle cos(t),0,sin(t)\rangle $
$s(t)= \langle 0,cos(t),sin(t)\rangle$
where $t$ in $[0,pi]$
We are given that they are on the surface of $F(x,y,z)= x^2 + y^2 + z^2 -1$
Show that the intersection of these two paths occurs at $\langle0,0,1\rangle$.
My own work showed me:
$cos(t1) = 0$
$0= cos(t2)$
$sin(t1) = sin(t2)$
is true for any $t$. I think I may not be understanding something. Can someone help me see how to solve this kind of problem. | Given the x coordinate of each path, you know that the two paths can intersect only if $\cos(t) = 0$. The y coordinate reveals the same restriction. The z coordinate is the same in both paths, so they will be the same no matter what $t$ is used. Therefore, all you need for the coordinates to intersect is to have $\cos(t) = 0$. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "linear algebra, multivariable calculus"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.