INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Closed in $\mathbb{R}^{2}$ vs closed in $\mathbb{R}$
Define the following subsets of $\mathbb{R}$ and $\mathbb{R}^{2}$ respectively:
$A=\left\\{\frac{1}{n}: n \in \mathbb{N}\right\\}$
$B=\left\\{(x,\frac{1}{x}): x\in\mathbb{R} \smallsetminus \left\\{0\right\\} \right\\}$
I know the first subset, $A$, is neither open nor closed, and the second subset, $B$, is closed.
However, the set $B$ is exactly $A$ but "viewed" in $\mathbb{R}^{2}$, so, why $B$ is neither open nor closed in $\mathbb{R}^{2}$?
**EDIT:**
Redefine $B$ as:
$B=\left\\{(x,\frac{1}{x}): x \in \mathbb{N}\right\\}$.
$B$ is closed in $\mathbb{R}^{2}$, my question is why intuition fails? ie, $A$ is the projection of $B$ on $\mathbb{R}$ and since $A$ is neither open nor closed in $\mathbb{R}$, I thought $B$ was equally neither open nor closed in $\mathbb{R}^{2}$.
|
If you change the definition of $B$ to $B=\left\\{(x,\frac{1}{x}): x \in \mathbb{N}\right\\}$ then you have a discrete set, and any pair of points are at least one unit of distance separated. So there is no limit point for $B$ that is outside of $B$.
This is not the case with $A$, where points in $A$ can get arbitrarily close to each other as they converge to $0$, and the point $0$ is a limit point that is not in $A$ itself.
Roughly, open/closed is based on distance for these spaces under the usual topology. And in $A$, the points are arranged so that their distances can be arbitrarily close. But in the redefined $B$, the points are arranged in a different way that spreads them out too much to avoid getting a closed set.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "general topology"
}
|
Change in angle due to rotation in another plane
I hope someone can help me figure this out.
Step 1: We are looking at the ZX plane (front view). I have two lines, which have been rotated 15 degrees around the Y axis. At this step both lines are identical (except for the colour). !Step 1
Step 2: We are now looking at the XY plane (top view). I take the yellow line and rotate it 60 degrees around the Z Axis. !Step 2
Step 3: We are back at our starting view (ZX plane - front). The angle of the yellow line and the X-Axis is 28.18679 degrees. How can this angle be calculated?
** EDIT ** I used a CAD program to draw this, and I also used the CAD program to measure the angle. I need to calculate the angle programatically though.
!Step 3
Thanks a million!
|
The direction vector of the yellow line is
$$ \pmatrix{\cos\theta\cos\phi\\\\\cos\theta\sin\phi\\\\\sin\theta} $$
with $\theta=15^\circ$ and $\phi=60^\circ$. Thus its angle with the $x$ axis is
$$ \arccos\left(\cos\theta\cos\phi\right)=\arccos\left(\cos15^\circ\cos60^\circ\right)\approx61.1^\circ\;. $$
Since this is far from your measurement of $\approx28.2^\circ$, it seems that what you're interested in may in fact not be the angle of the yellow line with the $x$ axis. The image suggests that the angle you're measuring is the angle between the $x$ axis and the projection of the yellow line onto the $x$-$z$ plane. This is indeed
$$ \arctan\frac{\sin\theta}{\cos\theta\cos\phi}=\arctan\frac{\sin15^\circ}{\cos15^\circ\cos60^\circ}\approx28.18679^\circ\;. $$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "geometry"
}
|
Cross-browser innerText for setting values
Let's say I have the following code:
<html>
<head></head>
<body>
<div id="d">some text</div>
<script type="text/javascript">
var d = document.getElementByid('d');
var innerText = d.innerText || d.textContent;
innerText = 'new text';
</script>
</body>
</html>
And I want to change text value for the div tag with id='d'. Unfortunately the block code above doesn't work and the text content doesn't change.
It works if do the following recipe:
if (d.innerText) d.innerText = 'new text';
else d.textContent = 'new text';
But I dont like the recipe above because it's not compact.
Have you any suggestions why the first approach doesn't work?
|
Instead of multiple assignments, you can grab the property and use that
var text = ('innerText' in d)? 'innerText' : 'textContent';
d[text] = 'New text';
|
stackexchange-stackoverflow
|
{
"answer_score": 21,
"question_score": 11,
"tags": "javascript, html, cross browser, innertext"
}
|
How to export data from model to excel file on rubyonrails
I'm trying to export data from my models to an excel spreadsheet. I have seen 3 ways
1. Using the spreadsheet gem which I didn't understand how to use it, the examples I saw was writing to a local file but I'm looking to generate a file every time user clicks on a link.
2. Creating a method called export, and running the query there, then making a export.xls file in my view, and that file creating the table I want to be exported to the excel file, but this approach don't allow me to create multiple sheets.
3. Followed this tutorial, < but here doesn't show how to put the link in the view, looks to me that I'm missing something in the routes, I can give github so you can take a look at my code if needed.
|
My choice is to just manualy generate CSV file. Like:
File.new("data.csv", "w+") do |f|
@my_data.each do |data|
f << [data.title, data.body, ...].join(", ") + "\n"
end
end
CSV file can be opened with excel or any other spreadsheet soft.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 6,
"tags": "ruby on rails, ruby, ruby on rails 3, excel, spreadsheet"
}
|
SSH connection to Raspberry Pi on Local network failing with iPhone
My iOS app, 'QuickSupport' connects with Local IoT Wi-Fi network and executes some SFTP Commands on the click of a button. I have used Obj C based NMSSH Library for this. It works fine with Simulator but when I test on Real Device using Testflight by clicking that button, it crashes and I get a pop-up message:
{
String file_name = "input.txt";
File input_file = new File(file_name);
Scanner in_file = null;
try{
in_file = new Scanner(input_file);
}
catch(FileNotFoundException ex){
System.out.println("Error: This file doesn't exist");
System.exit(0);
}
while(in_file.hasNextLine()){
String line = in_file.nextLine();
System.out.println(line);
}
in_file.close();
}
That is supposed to read all lines in a .txt file and print them on the screen the FileNotFoundException is thrown. It catches it and prints out the error message with no problem. But the file does exist, I made two files input and input.txt, but the exception is still thrown. This is the file directory where the files and project are.
|
From the looks of it, the program seems to be in the folder "Guided Exercise 4" where the text files are outside that folder. If this is the case then either move the text files into the same folder as the program or `File input_file = new File("..\\" + file_name);` to reference the file in the parent directory. But I would recommend the moving the text files.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, netbeans"
}
|
VB.NET Fill a Large File with bytes
I'm creating a temp file to store a huge matrix that can't fit in memory. I'd like to write the temp file to disk first so I can seek to a position in the file with a stream object. I already know the exact size I need.
What's the easiest way to write, say, 2 gigabytes of zeros?
I tried writing it one byte at a time and that's really slow. I also tried writing byte array chuncks and that's a lot faster but I must suck at the math cause I can't get the final size to be what I expect.
|
The BinaryWriter has a method Seek that allows you to set an arbitrary position on a file also if this position is outside the end of the file.
If you write a simple byte at this position, the OS will resize the file to allow the write at the requested position.
Dim testfile as String = "d:\temp\testfile.bin"
Dim fs As FileStream = File.Create(testfile)
Dim utf8 As UTF8Encoding = new UTF8Encoding()
Dim bw As BinaryWriter = new BinaryWriter(fs, utf8)
bw.Seek(1500, SeekOrigin.Begin) 'only 1500 bytes just for test
bw.Write(255)
fs.Close()
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "vb.net, file io"
}
|
How to use a custom attribute on an assembly in .NET Core 1.1
While I found this post regarding retrieving a custom attribute on an assembly, I am unsure on how to add a custom attribute to an assembly in .NET Core 1.1. In .NET Framework, I would have done something like:
[assembly: AdditionalLocation(@"..\ReadFromHere")]
But my netcore1.1 projects in Visual Studio do not have an AssemblyInfo.cs. Where would I declare a custom attribute for an assembly? Is there something I can put in the .csproj file?
|
You can always create a new `AssemblyInfo.cs` file or any other `.cs` file to do the same.
However you can also use the new auto-generated assembly info mechanism. You can add this to your `csproj` file, replace the value replacing the `Include` attributes value with the type name of your custom attribute:
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>DasMulli.Win32.ServiceUtils.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
|
stackexchange-stackoverflow
|
{
"answer_score": 33,
"question_score": 20,
"tags": ".net core, csproj"
}
|
Client interface web service iphone
my question is: We are developing a IOS app that requires the users to upload content to it (Photos, Videos, Text), through a website, we are testing several options, but we cannot find a user friendly interface (like a nice open source CMS) to do it. Our server is a PHP one.
The main features we need to have on the CMS interface are:
secure login /user and Password upload content to the server (videos, images and text), which will be tagged in different categories
Any ideas or other tested solutions on this?
|
There are companies like Parse and StackMob trying to make the server side of iPhone development easier.
Are you looking for a server that implements an API for your app to use? Are you looking for a full website that lets anyone upload stuff to it?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, javascript, iphone, content management system"
}
|
Extracting values from a string in R using regex
I'm trying to extract the first and second numbers of this string and store them in separate variables.
(User20,10.25)
I can't figure out how to get the user number and then his value.
What I have managed to do so far is this, but I don't know how to remove the rest of the string and get only the number.
gsub("\\(User", "", string)
|
Try
str1 <- '(User20,10.25)'
scan(text=gsub('[^0-9.-]+', ' ', str1),quiet=TRUE)
#[1] 20.00 10.25
In case the string is
str2 <- '(User20-ht,-10.25)'
scan(text=gsub('-(?=[^0-9])|[^0-9.-]+', " ", str2, perl=TRUE), quiet=TRUE)
#[1] 20.00 -10.25
Or
library(stringr)
str_extract_all(str1, '[0-9.-]+')[[1]]
#[1] "20" "10.25"
Or using `stringi`
library(stringi)
stri_extract_all_regex(str1, '[0-9.-]+')[[1]]
#[1] "20" "10.25"
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "regex, r"
}
|
if conditions do not ignore lines in a text file
Why the below awk command does not ignore columns which starts with `ChrC` and `ChrM`:
awk '{if($1 != "ChrC" || $1 != 'ChrM') print $0}' TAIR10_GFF3_genes-fix1.rm_rubbish_rm_protein_rm_id_rm_index.gff | cut -f1 | sort | uniq
Chr1
Chr2
Chr3
Chr4
Chr5
ChrC
ChrM
##gff-version 3
Thank you in advance,
|
Since samples are not provided so couldn't test it, could you please try changing your condition inside `awk`. IMHO why it is printing it because its an OR condition so if 1 of the part fails then also it will print line(based on the logic of OR condition of `1 || 0` \--> `1`), which will NOT happen in case of `AND` condition.
if($1 != "ChrC" && $1 != "ChrM")
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "awk"
}
|
Turn list of strings with mixed inherent types into inherent type
So I have a list of strings, each of which have inherent types.
mixedbag = ['True', '2.7', '3', 'Ninety']
I want to transform this to look like this:
[True, 2.7, 3, 'Ninety']
What I thought of is to create a large try/except chain to evaluate each item in the list, but that doesn't feel like a pythonic way of handling this problem.
|
You could use `ast.literal_eval` in a try-except block.
from ast import literal_eval
def unmix(ele):
try:
ele = literal_eval(ele)
except ValueError:
pass
return ele
* * *
**Demo**
>>> list(map(unmix, mixedbag))
[True, 2.7, 3, 'Ninety']
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "python, list, types"
}
|
Is it possible to exceed Mongodb's document size limit by storing object Id in a single document?
Suppose we have such a mongodb schema (I used the format from mongoose just for illustration purposes):
var userSchema = new Schema({
posts : [Schema.Types.ObjectId] // stores the _id field from post
});
var postSchema = new Schema({
body : String
});
Since the maximum document size in mongodb is 16 MB, which is finite, wouldn't we run the risk of exceeding such a limit such the above schema (even if it is a every small risk ) ?
Thanks.
|
Yes, that's possible for a very large number of posts. The traditional way to overcome the limitation is to invert the schema:
var userSchema = new Schema({
name: String
});
var postSchema = new Schema({
user: { type: Schema.Types.ObjectId }, // _id of the post's user
body : String
});
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "node.js, mongodb"
}
|
touch events on UIimageView which is on UIwindow
I m using UIimageview on top of UIWindow. I want to handle touch event for that Imageview, but m not able to do it.
When i use UIimageView on UIview, we can use touchBegan, touchEnded but how to handle it when it is on UIWindow instead of UIView.
Thanks..
|
If you just want to handle the tap, you have to set,
imageView.userInteractionEnabled = YES;
By default _UIImageView_ has the _userInteractionEnabled_ property set to _NO_. And you can add a tap gesture recognizer to it,
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(anyMethod)];
[imageView addGestureRecognizer:tgr];
[tgr release];
If you want to move the image, you can use _UIPanGestureRecognizer_.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "iphone, objective c, ios, uitouch, uiwindow"
}
|
Change item sortorder in gridview - LINQToSQL
I've got a gridview with a list of categories. In the database (MSSQL2008), the category table has a SortOrder(INT) NULL field.
Currently categories are retrieved using:
Galleries.DataSource = From G In DB.GalleryCategories Order By G.SortOrder, G.Name
Now, what I need to be able to do is add "Move Up" and "Move Down" buttons to each row to allow the user to sort the items in an arbitrary way.
My initial thoughts are along the lines of: Identify ID of selected item. Identify ID of item before/after selected item. Swap of identified items in the DB SortOrders.
I would then have make the sortorder NOT NULL and make sure it's initialised to a unique number
I'd appreciate any alternative suggestions / comments on this approach
Many thanks
|
I have generally seen it done this way, and have done it myself
* SortOrder is an int
* Each item increases by 10 (so, 10,20,30,40) or suitable increment
* To move an item up, subtract 15
* To move an item down, add 15
* To insert an item, take the target and add/subtract 1
* Apply a NormalizeSort() routine which resets the values to even intervals
* 10,20, _25_ ,30,40 => 10,20, _30_ ,40,50
That makes it all pretty simple, since inserting something above something else is just:
list.Add( New Item(..., target.SortOrder +1) )
list.NormalizeSort()
// or
item.SortOrder += 11, etc
If you want to make it a decimal, then you can just make it all sequential and just add .1, etc to the sort order and re-normalize again.
// Andrew
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "asp.net, linq to sql, gridview, datasource"
}
|
can't build taco ios BLD00102 : No such file or directory 'xxx.plist'
I use visual studio 2015 to build mobile cordova useing remotebuild but I got wanrning and error :
Warning PackageApplication is deprecated, use `xcodebuild -exportArchive` instead.
Error BLD102 Error : BLD00102 : No such file or directory 'xxx.plist'
|
Work around is to ignore the problem and locate build folder on mac its hold number that shown when you build set it to release and then go to the xcode open project fix errors and test it
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, cordova, visual studio 2015, taco"
}
|
How to count method calls by instance
I have following Code.
public interface Animal{
void eat();
}
public class Lion implements Animal{
@Override
public void eat() {
System.out.println("Lion can eat");
}
public static void main(String[] args) {
Animal lion = new Lion();
lion.eat();
lion.eat();
lion.eat();
}
}
as you can see I am calling `eat()` thrice. How can I calculate how many times it is called?
Note that, you can not modify `eat()` method from class `Lion`
|
You could use Decorator Pattern with `Animal` interface and your `Lion` instance:
public class EatingDecorator implements Animal {
private Animal target;
private int counter;
public EatingDecorator(Animal target) {
this.target = target;
}
@Override
public void eat() {
target.eat();
counter++;
}
public int getCounter() {
return counter;
}
}
and then apply it
Animal lion = new EatingDecorator(new Lion());
lion.eat();
lion.eat();
lion.eat();
System.out.println(((EatingDecorator) lion).getCounter()); // 3
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 3,
"tags": "java, oop"
}
|
Replace elements of a pandas series with a list containing a single string
I am trying to replace the empty list in a pandas serie with a list containing a single string. Here is what I have:
a = pd.Series([
[],
[],
['a'],
['a'],
["a","b"]
])
The desired output is as following :
b = pd.Series([
['INCOMPLETE'],
['INCOMPLETE'],
['1'],
['1'],
["1","2"]
])
Where I try to replace the empty lists using boolean indexing, I get an automatic coercion of my list of a unique string to just string string:
a[a.map(len) == 0 ] = ['INCOMPLETE']
0 INCOMPLETE
1 INCOMPLETE
2 [a]
3 [a]
4 [a, b]
In contrast the manual replacement works `a[0] = ['INCOMPLETE']`
Does anyone have a workaround?
|
Use lambda function with `if-else` for replace empty string, because if comapre are processing like `False`:
a = a.apply(lambda x: x if x else ['INCOMPLETE'])
print (a)
0 [INCOMPLETE]
1 [INCOMPLETE]
2 [a]
3 [a]
4 [a, b]
dtype: object
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, pandas, series"
}
|
CSS animations on <span>
I am trying to apply a CSS animation to a `<span>` element and I just can't get it to work. I can't find any resource that says whether animations can be applied to `<span>` elements. So, is it me that is making an error, or are spans animation immune?
Edit: Code
Inf<span class="inf_o">o</span>rmation
<br>
do<span class="don_n">n</span>e
<br>
we<span class="dbl_l">ll</span>
and css:
/* animations */
.inf_o
{
-webkit-animation-name: lower_head;
-webkit-animation-duration: 3s;
-webkit-animation-timing-function:ease-in;
-webkit-animation-delay: 1s;
-webkit-animation-play-state: active;
}
@-webkit-keyframes lower_head
{
from {margin-top:0px;}
to {margin-top:10px;}
}
|
looks like you have to set a display property. Obviously block will mess up the word, so you need to use inline. I cooked up a jsfiddle for you: <
As you can see the 'o' animates down.
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 10,
"tags": "html, css"
}
|
Prevent clicking a checkbox in Uniform library
I want to /uncheck a checkbox by JS and prevent user to /uncheck it by click.
in normal checkboxes I can use this code:
$('#checkbox').on('click', function(event){
event.preventDefault();
});
but this code does'nt work for Uniform checkboxes
|
You can disable the click event:
$('#checkbox').unbind('click');
And then handle it like you want with:
$('#checkbox').prop('checked',true);
$.uniform.update();
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "jquery, uniform, jquery uniform"
}
|
Time-dependent action.. is late?
I have a workflow with a time-dependent action. The trigger is correctly scheduled (if I go to "monitoring" I see the fire date being set at the appropriate time). But then action actually fires a couple of minutes later.
Is this an expected behavior of Sfdc? If so, is there an apex way to execute something in an exact point in time, i.e. I know the datetime at which this event will occur but it's not periodical therefore I can't use batch scheduled actions.
Thank you very much for your attention! T.
|
I don't believe there is any guarantee about when a timed workflow will trigger - as stated in the docs : "Time-dependent actions aren't executed independently. They're processed several times every hour, where they're grouped together and executed as a single batch."
I don't know of any way to guarantee a time - all async operations operate based on "available resources" to my knowledge...
|
stackexchange-salesforce
|
{
"answer_score": 7,
"question_score": 5,
"tags": "workflow, time dependent workflow"
}
|
What does 'sus' mean in the sentence "People who joined Facebook after 2017 are sus."?
I saw a tweet:
> People who joined Facebook after 2017 are sus.
What does this word "sus" mean in this sentence?
|
This is a slang term used primarily by members of "Generation Z" (currently aged 10–25) to mean " **sus** picious" but also "dubious", "strange", "creepy", or "socially unacceptable" (in the sense that a "creepy person" is socially unacceptable).
In this sentence, it is saying that anyone who joined Facebook in the year 2017 or afterwards is creepy or socially unacceptable.
|
stackexchange-ell
|
{
"answer_score": 36,
"question_score": 20,
"tags": "word meaning, slang"
}
|
Nice looking xhtml/html when I "View Source"?
I'm just curious if anyone has any tricks on how to keep source code looking good when you "View Source." I'm militant about keeping my code well formatted and spaced while I'm developing and I tend to "View Source" a lot to double check the output (when firebug is overkill). When I start using RenderPartials and RenderActions and anything in the tag it gets pretty messy.
I don't want to send too many extra characters to the browser to keep file size efficient but is there a way to force the xhtml/html to do a newline or tab? I tried a couple of things that didn't work. Thanks!
|
Just send a `\n` and it should come out as a newline in the "view-source" section of the browser.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, asp.net mvc, xhtml"
}
|
Generalize the formula :$1=1, 3+5=8, 7+9+11=27, 13+15+17+19=64$
So the solution of this is $n^3$, as $1=1^3, 3+5=2^3, 7+9+11=3^3$
So I find that the $n+1 = m^2+3m+2 + (n_m)(m+1)$ where $n_m$ is the largest number in the previous equation and $m$ is the number of terms in last equation. How can I prove by induction that the solution is $n^3$, do I have to prove $(n+1)^3$ is equal to that or any other method or I prove that $(n+1)^3-n = 2m^2+2m+2+n_m$ (the differience between $(n+1)$ and $n$
|
Approaching by pattern,
* We know that sum of first $k$ odd numbers is $k^2$.
* We have $1,2,3,4\ldots$ terms which may be expressed as difference of triangular number of terms $$ 1 = \underset{1}{\underbrace{1}} - \underset{0}{\underbrace{0}} $$ $$ 3+5 = \underset{\text{first 3 odd}}{\underbrace{(1+3+5)}} - \underset{\text{first odd}}{\underbrace{1}}$$ $$ 7+9+11 = \underset{\text{first 6 odd}}{\underbrace{(1+3+5+7+9+11)}}-\underset{\text{first 3 odd}}{\underbrace{(1+3+5)}}$$
In particular, $n^{th}$ sum is $$\text{sum of first $T_{n}$ odd numbers - sum of first $T_{n-1}$ odd numbers}$$
* Thus $n^{th}$ sum is $$ 1 = 1^2 - 0^2 $$ $$ 3+5 = 3^2 - 1^2$$ $$ 7+9+11 = 6^2-3^2$$ $$ 13+15+17+19 = 10^2-6^2$$
In particular, $n^{th}$ sum is $$T_{n}^2-T_{n-1}^2$$ $$=\dfrac{n^2(n+1)^2}{4}-\dfrac{n^2(n-1)^2}{4}$$ $$=\dfrac{n^2}{4}(4n)$$ $$=n^3$$
* * *
Note : Once one makes these observations by naked eye, one can simply finish the problem by writing down step $3$ directly.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sequences and series, discrete mathematics, induction"
}
|
How to use MVC viewBag concept in express js?
I am using express js 4.1 along with handlebars template 4.0. When rendering a page I am sending collection of objects from express route.get('/') to handlebar(.hbs) view file. Is there any possibility to the send object like viewbag (similar to MVC) and should access those objects using @viewbag in hbs file? Below code is used to render the hbs file along with collection of 2 objects
var gridData = [
{ Name: 'xxxx', City: 'dddd' },
{ Name: 'yyyy', City: 'rrrr' },
{ Name: 'zzzz', City: 'ssss' }
]
resultSet["gridData"] = gridData;
resultSet["newdata"] = [1,2,3];
res.render('user-list', {viewBag: resultSet});
Here I need to use the viewBag as @viewBag.gridData or @viewBag.newdata in hbs to bind these array values. Also, please suggest how to use @HTML helpers and @section ControlsSection{} in hbs file since the express js follows MVC structure.
|
Instead of `res.render('user-list', {viewBag: gridData});` I have replaced
res.locals.gridData = JSON.stringify(gridData); // To make it global and accessible in hbs view file
res.locals.newdata = newdata;
res.render('user-list');
When rendering 'user-list' page, `dataSource: {{{gridData}}}` will bind the respective datasource in for the grid and this `datasource` is of json type. It works finally!!!
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "node.js, express, handlebars.js, express handlebars"
}
|
Problem: Need to look up a sentence in a database of millions of sentences?
So, I'll be storing millions of sentences in a database each with an author. I need to be able to efficiently search for a sentence and return the author. Now, I'd like to be able to mispell a word or forget a word or two in this sentence, and have the application still be able to match (fuzzy-esque). Can anyone point me in the right direction? How does google do this? Because I can search for lyrics on google for instance and it will return the song with the lyrics? I'm looking to do the same thing?
Thanks all.
If fuzzy makes things too complicated, then I can deal with just an efficient sentence search.
|
For full text search check inverted index data structure.
This is how search engines do it
samples of code
UPDATE: also if you're working on a distributed system check Hadoop \- open source alternative for Goolge's MapReduce
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "algorithm, search, full text search, search engine"
}
|
How can I invert the direction of blocks in a structure?
I have a structure with some blocks facing in the 'normal' direction:
nn nn nn nn
| || || || |
-- -- -- --
I would like to somehow connect a layer above this that has the blocks facing the other way so that I end up with:
-- -- -- --
| || || || |
uu uu uu uu
nn nn nn nn
| || || || |
-- -- -- --
How can I achieve this?
|
It depends on how close they need to be.
The following solution works, if you're happy to have things sticking out around the join:
"Brick 1x2 M. 2 Holes Ø 4,87", [part:32000:7]; There's also a 1x1 brick with a hole, [part:6541:7].
Which could be used as:
!Combined in desired orientation
For tighter coupling, the Minifig Wrench [part:6246d:0] can also fit over a stud, and is deeper than one stud, allowing two bricks to be inserted:
!Erik Amzallag 's method
Respect goes to Erik Amzallag for this one.
I guess it comes down to how you want to hide the join - you could use tiles on the studs that stick out, which wouldn't be possible with the wrench method.
|
stackexchange-bricks
|
{
"answer_score": 32,
"question_score": 45,
"tags": "building, snot"
}
|
Django: How to render non-Boolean database rows as checkboxes?
My model:
class LineItems(models.Model):
descr = models.CharField(max_length=100)
cost = models.DecimalField(max_digits=5, decimal_places=2)
My form:
class LineItemsForm(forms.ModelForm):
class Meta:
model = LineItems
fields = ['descr', 'cost']
Can someone please tell me either 1) how to render all of the product rows as checkboxes or 2) the proper way to do this if I'm coming at it incorrectly?
|
Found what I was looking for. In my form:
LINEITEM_CHOICES = [[x.id, x.descr] for x in LineItems.objects.all()]
class LineItemsForm(forms.Form):
food = forms.MultipleChoiceField(choices=LINEITEM_CHOICES,
widget=forms.CheckboxSelectMultiple(), required=False)
In my view:
{% for radio in lineItems.food %}
<div class="food_radios">
{{ radio }}
</div>
{% endfor %}
My code is based off of this post.
Thank you for your answers.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "django, django forms"
}
|
Sum and drag a formula with VBA
I have a table that looks like this

That way I get
* On B2 -> =B8-SUM(B3:B7)
* On C2 -> =C8-SUM(C3:C7)
and like that for everything on that row.
|
You can write the formula to the entire range in one step. Excel will update the relative references across the columns.
Range("B2:F2").Formula = "=B8-SUM(B3:B7)"
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "excel, vba"
}
|
Laplace transform of : $t^{\gamma-1} F(\alpha,\beta,\delta,t)$, where $F$ is the Gauss' hypergeometric function
What is the Laplace transform of : $t^{\gamma-1} F(\alpha,\beta,\delta,t)$, where $\gamma >0 $ and $F$ is the Gauss' hypergeometric function.
Thanks!
|
There is an explicit formula in the book: A.P. Prudnikov, Yu.A. Brychkov, O.I. Marichev. INTEGRALS AND SERIES, Volume 4. Direct Laplace Transforms. GORDON AND BREACH, 1992.
It is on the page 533 and is in terms of $_{2}F_{2}$ hypergeometric function. For special values of parameters for sure it can be simplified using the same book volume 3.
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 2,
"question_score": 1,
"tags": "pr.probability, probability distributions, integration, integral transforms"
}
|
Eagle tstop layer problem
I'm about to update an old PCB design of mine using Eagle 7.5. The previous design used a DS18B20 and I want to replace that with a 1x3 0.1 pin header. :
).
|
Just fill empty cells with empty items (like a `JLabel`), eg:
class MyFrame extends JFrame
{
MyFrame()
{
setLayout(new GridLayout(3,4));
for (int i = 0; i < 9; ++i)
this.getContentPane().add(new JLabel(""+i));
for (int i = 0; i < 3; ++i)
getContentPane().add(new JLabel());
pack();
setVisible(true);
}
}
This layouts them as
0 1 2 3
4 5 6 7
9
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 5,
"tags": "java, swing, grid layout"
}
|
My Android App Crashes
I have developed a _free_ Android app and placed in on the market. I have fully tested the app on one device (LG Ally) and tested it with the whole range of emulators. I am getting reports of crashes on some 2.2 devices. The people reporting the crashes are not being at all helpful. I am looking for some expert help here.
The application and a description of the problems can be found at:
BASIC! v00.03
If having access to the source would help, send me an email.
Any help that could be provided would be greatly appreciated.
|
Have any of your users submitted an error report? Usually that will include a stack trace of some sort to give you an idea of what is causing the error.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, debugging"
}
|
How do ES6 imports/exports work when creating objects/variables in a module?
Given I have a `Config` class in a file called `Config.js` and I have the following module in a file called `myConfig.js`:
import Config from './Config.js';
const myConfig = new Config();
export myConfig;
If I have multiple files that `import { myConfig } from 'myConfig.js'`, does it instantiate new Configs on each import statement?
|
ES6 modules are singleton. Each time you import the module you will get the same instance. However, you could have tested it quite easily by logging something in the Config constructor.. ;-)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "javascript, ecmascript 6"
}
|
TimeZone convertion in Ruby on Rails
Im my application.rb I've set: config.time_zone = 'Brasilia'. It's ok when I save datetimes in the system. The problem is that I receive datetimes from another system that is already on the correct timezone. So, when this datetime is saved on my RoR system, it's being saved wrongly. Example: The another system sends a datetime 2015-11-10 15:07:00 (that is already on the right timezone, ready to save). But my RoR saves it like 2015-11-10 13:07:00 -0200. Is there a way to tell Rails that this datetime is already on the correct timezone?
|
You need to tell Rails/Ruby which timezone the incoming datetime is in, see a list of timezones using `rake time:zones:all` and then use the right one in the following code, eg.
Time.use_zone("Montevideo") { Time.zone.parse "2015-11-10 15:07:00" }
That will return an `ActiveSupport::TimeWithZone` object with the correct timezone set, and then you'll just store it in your DB and Rails will convert it to the correct UTC time.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ruby on rails, timezone"
}
|
Efficient "Insert" function in linked list
In an interview I was asked to write an insert function for linked list in such a way that after the insertion, the element towards the head side of the inserted element should be greater and the tail side should be smaller when compared to inserted element.
I had implemented the following steps in my code:
1. initially sort the linked list in descending order.
2. get the element.
3. insert the element in such way that the linked list will be in descending order even after insertion.
But I was told that my way was not efficient.
Please let me know if there are efficient way to achieve the same.
|
Sort is an `O(n log n)` operation. If you read the question carefully they never say the list should be sorted, so don't do the sort operation. What you should do instead is start with a new list with only your element, then for each element of the original list append it either to the front (if greater than the new element) or otherwise at the back.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++, c, data structures, linked list"
}
|
How to farm key molds?
I have been killing crimson mobs in the crimson for a while, now, and I still have not had a key mold drop.
Is there an easier way to farm key molds?
I want them so that I can get the vampire knives.
|
Unfortunately, all I can tell you is that Random Numbers are Random.
1 in 2500 is... not a whole lot, I'm afraid. And even after killing 2500 mobs, you're not guaranteed one.
So, if there's no way to get better odds, how can we maximize those odds? Simple -- spawn as many mobs as possible, then kill them. The key here, (ha!) is that it doesn't matter _what_ mobs you kill -- Goblin Armies. Celestial Event Mobs. Pirates. Slimes. All are equally valid.
So, things that will help:
* Fighting off Events in the target Biome (Goblin Army, Pirates, Frost/Pumpkin Moons, etc.)
* Water Candles and Battle Potions (More mobs = more dead mobs)
* Blood Moons / Eclipses (Again, more mobs = more dead mobs)
|
stackexchange-gaming
|
{
"answer_score": 5,
"question_score": 3,
"tags": "terraria, terraria console"
}
|
App to run Chrome web extensions on iPad
I have now moved from Android to iOS. In Android , I used Yandex Browser in which I can use Chrome web extensions. But in the Yandex Browser iOS app f, I can't download chrome web extension.
Does anyone know of a browser on iOS that allows the use of Chrome web extensions?
|
Unfortunately, there is no such browser. The reasons are the App Store review guidelines, which forbid the execution of downloaded code (such as web extensions).
Your best bet is to download browsers with lots of features built-in like iCab or similar and hope it covers your use-case.
Otherwise, maybe you can achieve what you want by having a desktop browser running somewhere and connecting to that using screen sharing from your iPad…
|
stackexchange-apple
|
{
"answer_score": 1,
"question_score": 2,
"tags": "ipad, android, web browser, chrome extensions"
}
|
convert URLDecoder.decode(temp, "UTF-8") to php
I am converting a Java Servlet web application to php.
How should I convert the following Java commands to php?
String temp = request.getParameter("q");
String temp2 = URLDecoder.decode(temp, "UTF-8");
Any help will greatly appreciated...
EDIT:
This is client code:
var myJSONText = playlist.serialize();
$.ajax({
type : 'POST',
url : "playlisthandler.php",
data : {
"q" : encodeURIComponent(myJSONText)
},
success : function(response) { ... },
error : function(response) { ... },
dataType : "json"
});
Are you saying that the encodeURIComponent is redundant?
|
You shouldn't have the need to do so. The `request.getParameter()` in servlet API and the `$_REQUEST` (and inherently also `$_GET` and `$_POST`) in PHP **already** do that based on the request character encoding. The need to do so indicates that the client side is doing it wrong by double-encoding the query string components.
As per your code you're indeed explicitly encoding the query string while jQuery already does that under the covers:
data : { "q" : encodeURIComponent(myJSONText) },
Remove the `encodeURIComponent()` call so that the `data` becomes `{ "q" : myJSONText }`. jQuery will already take care that it will be URL-encoded. The `encodeURIComponent()` is only necessary when you're using plain vanilla `XMLHttpRequest`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, php, servlets, urldecode"
}
|
How long does it exactly take for a view to rotate in iOS?
I want to use NSTimer to call a method once the view is done rotating. How long does the view take to rotate exactly? Thanks for your help!
|
you don't have to use a timer.
in apple's documentation there's an even trigger which is fired after the iphone rotates
see here:
<
I believe you can just implement this method:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ios, orientation, rotation, nstimer"
}
|
Concatenate strings in bash while adding double quotes
I have the following bash script:
set -ex
X="bash -c"
Y="ls -al"
I want to execute (notice the double quotes):
bash -c "ls -al"
The following does not work:
C=$X\ $Y
$C
This gives as output
+ X='bash -c'
+ Y='ls -al'
+ C='bash -c ls -al'
+ bash -c ls -al
There are no double quotes around ls -al
I tried this:
C=$X\ \"$Y\"
But that doesn't work:
+ X='bash -c'
+ Y='ls -al'
+ C='bash -c "ls -al"'
+ bash -c '"ls' '-al"'
How to correctly concatenate Y to X while keeping double quotes around Y?
|
You could use an array variable for `C`:
X="bash -c"
Y="ls -al"
C=($X "$Y")
"${C[@]}"
Note that `$X` is not quoted since we have one command and one parameter.
Or the short version:
C=(bash -c "ls -al")
"${C[@]}"
|
stackexchange-unix
|
{
"answer_score": 4,
"question_score": 2,
"tags": "bash, shell script"
}
|
Best farm route in Act 2
I want to farm Act 2 Inferno but I think my farm route is not that fast enough. I can finish my run in about 40 mins.
My route:
1. Choose the Kill Zoltun Kulle quest
2. TP to Black Canyon Mines - at least 2 elites and/goblin
3. TP to Road to Alacarnus - at least 1 elite near the caged prisoners
4. TP to Zoltun Kulle base - there are 3 maps there but I skip the middle one because there are few elites there.
5. Kill Zoltun Kulle
6. End
The maps Storm Halls and Undead Halls (not sure about the name) are very big but I only encounter 3 - 4 elites there. I want to look for maps that have a high density of elites (with respect to the size of the map)
I tried the 2 caves in Desolate Sands but Desolate Sands is very big and I think I'm just wasting time exploring the map and looking for the caves.
Any ideas?
|
Definitely add the Ancient Path waypoint to that list, as there's often a goblin nearby.
I'd also recommend adding Vault of the Assassin to that list. Although it can take a while to find, you'll bump into a few elites while trying to find it, and once you do, the vault guarantees you a good number of elites once you get there.
I agree that Kulle's lair just doesn't seem to have enough elites to make it worthwhile.
I spent some time doing an "ActII lite" run, where I'd get checkpointed in the VoA, clear it, then hit the Black Canyon Mines, Ancient Path and Road to Alacarnus waypoints and end it there, without bothering with Kulle at all. The time saved by starting inside the Voa each time make the run feel a lot more efficient. It might have been entirely subjective, of course :)
|
stackexchange-gaming
|
{
"answer_score": 1,
"question_score": 1,
"tags": "diablo 3"
}
|
When reselecting “From my computer” in the image uploader, the “browse files” input is missing
I noticed a bug in the “Add Image” popup that can be reproduced as follows:
1. Click on the `Add Image` button
2. Click on the “From the web” radio button
3. Click on “Add Picture” without adding any URL. I see the error message _“You didn't enter a valid URL”_.
4. Click on the “From my computer” radio button
5. You should see the “Add Image” dialog as shown below
!The “browse files” input textbox is missing after reselecting “From my computer”.
As seen in the above image it is now not possible to add files from my computer anymore. We have to close and open the dialog to do so.
My PC Configuration is as follows:
* **OS Verson** : Windows 7 Professional 64-bit.
* **Firefox** : 20.0.1
* **IE** : 10.0.9200.16540
* **Google Chrome** : 26.0.1410.64 m
I do not think it is browser dependent as I was able to reproduce it in Firefox, IE10 and Chrome.
|
My fail.
Didn't use `insertBefore` correctly - I didn't read jQuery documentation properly.
Fix has been pushed - all is well now in the world.
|
stackexchange-meta
|
{
"answer_score": 9,
"question_score": 19,
"tags": "bug, status completed, images, uploader"
}
|
How to change the default saved user and password for sites in browser?
A friend borrowed my phone and logged in to a website with it (and logged out). However, after that, his account became my browser's default account for that site. Every time I try to log in to the website, the user and password fields become automatically filled with his user and password. This is very annoying because I have to delete these and type my user id and password repeatedly. Is there any way to change/clear the default id and password?
The browser is Galaxy S stock browser, and the OS version is 2.2.
**[edit]** Another question: Why did his account become the default? I mean, I logged in repeatedly before and after his logging in, but his one-time login gets picked as the default,
|
Lie Ryan’s answer is probably the ultimate solution but it might be worth trying the less severe clear options first. That is, try the browser clear options in the following order: history, cache, all cookie data, form data and finally passwords. One of those lesser options might just resolve the issue, without having to lose all of your saved passwords.
|
stackexchange-android
|
{
"answer_score": 1,
"question_score": 3,
"tags": "browser, accounts"
}
|
Can not delete zip file from ftp server.Only zip files
I'm using `FtpWebRequest`, and I can delete files & folders, upload, create, etc. but I cannot delete .zip files.
I have a recursive function that deletes all files and folders. When it hits a .zip file, the request throws an unknown exception with "System error" error message.
I have wasted half of the day with this issue. Does anyone has any idea why this is happening?
|
The path length was the main issue here. Using **FtpWebRequest** , you dont use command like CWD or PWD, the class resolves the commands for you. After i`ve shortened my paths, i can delete anything i want. The strange thing is that i could create those long named folders, and upload files in them without any kind of issue. The problem was revealed only when i tried to delete them.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, ftp"
}
|
save canvas drawing as data or image for later insertion into html page
A Meteor client code renders a template with `canvas` for client signature. It listens on `mousemove` and draws lines between mouse x,y coordinates of one point to another as it moves, using `context.stroke()`.
How can the signature be saved and inserted in html page later? i.e. data or image would be best practice? Thanks
|
Use a variable
var image = ctx.getImageData(0,0,width,height);
To put it back when you need it:
ctx.putImageData(imgdata, 0,0);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, meteor"
}
|
How to pass NSError to method
I have a method which take the parameter
(void(^)(NSError*))errorCall;
I need to pass errorCall value
-(void)message{
example = [[Example alloc]init]
[example opertationError:void(^)(NSError*))errorCall ];
}
for the below line
[example opertationError:void(^)(NSError*))errorCall];
i need to pass some custom error call which in type of `void(^)(NSError*))errorCall`
Please any one let me know how to pass this kind of error value to the method.
@All
Thanks in advance
|
You can do like this:
void(^aBlock)(NSError *) = ^(NSError *error) {
...
};
[self errorValue:aBlock];
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "iphone, ipad"
}
|
Existe try-with-resource no PHP?
Existe no PHP algo parecido com **try with resource** do Java? Ou tenho que fechar recursos no bloco do `finally` mesmo?
|
Não, em essência não precisa. Primeiro que PHP é uma linguagem de _script_ tudo roda por alguns segundos, quando muito, geralmente é uma fração disto, então não liberar um recurso não faz diferença. E mesmo que precise liberar logo ele até costuma fazer porque o _garbage collector_ dele é baseado em contagem de referência, que permite uma finalização determinística, então assim que o objeto não tem um referência para ele já é coletado e pode liberar os recursos, diferente do Java que tem um coletor de lixo baseado em rastreamento e a liberação só pode ocorrer quando o GC entra em ação, por isso precisa de um outro mecanismo para liberar antes, por isso foi criado o `try-resource`.
Ao contrário do Java, o PHP não tem, acertadamente, ou não tinha a cultura de uso de exceções como em Java. E não precisa fazer para liberar qualquer recurso (em quase todos os casos).
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "php, php 7, try with resources"
}
|
MSMQ C# implementation using service (ServiceBase)
I will be using MSMQ in C# to read messages; and I am putting this in Window Service so on OnStart I will start reading messages using queue.Receive method which would be blocking/synchronous call. And OnEnd method I want to stop the queue with queue.Close(); queue.Dispose().
Is there any drawback of this approach ?
Thanks Ocean
|
This is a fairly common pattern, but it has some drawbacks.
First, you should consider using a thread pool (or the .NET parallel libs in 4.0) to process your messages asynchronously. Whether or not your queue reader can be asynchronous depends a lot on your transaction pattern. Will the processing be atomic?
Second, you should also consider using a timer (System.Timers.Timer) which you start in your OnStart and end in your OnEnd, and which reads one or more messages from the queue on each timer event.
Third, you should seriously consider just using the WCF MSMQ binding, which handles a lot of the complexity of this stuff.
See: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, service, msmq"
}
|
How to convert string numbers that are written in this format: XX:XX:XX into comparable numbers
How would i convert a string like this: 1:13:16 Into a number value? It can go up as high as xx:xx:xx
Hours:minutes:seconds
Example list:
duration: 0:37:29
duration: 0:25:57
duration: 1:10:15
duration: 21:2:55
I need to do some false true comparisons so i need to convert them accurately.
|
Use `split()`, like so:
let duration = '0:37:29';
let [hours, minutes, seconds] =
duration.split(':').map(str => Number.parseInt(str));
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, math, numbers"
}
|
How to get a boolean value into a SELECT operation based on another table?
I have two tables: `Message` and `Attachments` (which represent entity types that have a one-to-many relationship) as follows:
CREATE TABLE message (
messageId ...,
[from]...,
[to]...,
subject...,
body...
);
CREATE TABLE attachments (
messageId...,
filename...
);
I want to SELECT the basic message data and include a bit column to denote whether the message has attachments or not. I am trying to use EXISTS in the operation shown below:
SELECT
M.*,
hasAttachments = EXISTS(SELECT AttachmentId
FROM Attachment
WHERE messageId = M.messageId),
FROM Message M
But this doesn't work - What's the way to do what I'm looking for?
|
I'd do it with a CASE statement:
select
m.*,
hasAttachments = CASE WHEN EXISTS(select * from Attachment where messageId = M.messageId) then 1 else 0 end
from Message M
or
select distinct
m.*,
hasAttachments = CASE WHEN a.AttachmentId is not null then 1 else 0 end
from Message m
left join Attachment a on a.MessageId = m.MessageId
|
stackexchange-dba
|
{
"answer_score": 7,
"question_score": 4,
"tags": "sql server, sql server 2005"
}
|
How to get current timestamp in runtime
There are three statements like below:
print("first time", time.time())
self.wait(5)
print("second time", time.time())
I suppose the difference between "second time" and "first time" will be 5 seconds, however, they are the same, why?
I think the self.wait(5) should be async call, if so, how to get timestame in runtime?
|
If what you want is to print in the terminal the exact second of each moment of the animation you can do something like this (the time is saved in the variable self.time):
class TimeTest(Scene):
def print_time(self):
print("Time:",self.time)
def construct(self):
dot=Dot()
# 0 seconds
self.print_time()
self.play(Write(dot,run_time=2))
# 2 seconds
self.print_time()
self.wait()
# 3 seconds
self.print_time()
self.play(dot.shift,UP,run_time=1)
# 4 seconds
self.print_time()
self.play(FadeToColor(dot,RED,run_time=3))
# 7 seconds
self.print_time()
self.wait()
# 8 seconds
self.print_time()
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "manim"
}
|
How do I style a twitter bootstrap button with a hexadecimal color in Rails 4.2.4
I am a junior developer building my first web application for a client.
The owner is not content with the standard colours of the bootstrap buttons on the home.html.erb and wants a flamboyant colour of pink on one button particularly.
How do I style a twitter bootstrap button with hexadecimal colour using rails 4.2.4
What would the syntax be and what CSS folder from my below list would I use for such:
bootstrap_and_customization.css.scss,
home.css.scss,
pages.scss
|
You can just add it to the `application.css|css.scss`
So if you added a class of `btn btn-pink` to the `button`. I recommend that you add `btn` class so you will inherit the basic styling.
.btn-pink{
color: #FFFFFF; // whatever you want
background-color: ##FF69B4; // whatever you want
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, css, ruby on rails, twitter bootstrap"
}
|
ASP.NET Membership Error
I'm using ASP.NET MVC. I inserted ASP.NET membership tables into my database and i'm getting the error written below. Solution maybe? Thanks.
> The 'System.Web.Security.SqlMembershipProvider' requires a database schema compatible with schema version '1'. However, the current database schema is not compatible with this version. You may need to either install a compatible schema with aspnet_regsql.exe (available in the framework installation directory), or upgrade the provider to a newer version.
|
Did you run the aspnet_regsql.exe file?
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe
I've done this countless times and never got that error. Try doing that.
EDIT:
alt text
Also take a look at this
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "sql server, asp.net membership"
}
|
How can i solve blurry text in windows 10?
When i open any app in my windows 10, the texts and images display in blur, can anyone help me fix it?
:
> Everyone else on the team has failed. It's all down to me now to win the game.
So, whether we're going to win the game now depends solely on me. I'm the deciding factor now.
|
stackexchange-ell
|
{
"answer_score": 3,
"question_score": 3,
"tags": "meaning, meaning in context, phrase meaning"
}
|
What's the fish shell equivalent to `set -o vi` to get vi/vim key bindings to access command history and edit?
I'm one of the _"cursed ones"_ that got their start in `vi` instead of `emacs` so the shell editing commands I am used to are set in bash with `set -o vi` but this doesn't work in the fish shell.
How can I enable `vi` / `vim` style key commands in the friendly interactive shell that runs when you install `fish` from <
|
There is a command in `fish` to enable this one time and that command is:
fish_vi_key_bindings
To set this at every start up for all instances of the shell, create a startup file if it doesn't exist (or touch the date in case it exists) and then add that command to the startup file.
mkdir -p ~/.config/fish
touch ~/.config/fish/config.fish
echo fish_vi_key_bindings >> ~/.config/fish/config.fish
This is well documented on Stack Overflow as well, but I figured a clear answer here would help some people find the setup sooner. <
|
stackexchange-apple
|
{
"answer_score": 3,
"question_score": 2,
"tags": "macos, command line, bash, fish, homebrew"
}
|
C++ exceptions in main
My class Person has different files as attributes.
class Person {
private:
fstream history;
fstream familyTree;
public:
Person() {
history.open("history.dat");
familyTree.open("tree.dat");
}
}
I need my program to return different values if any of the files couldn't be opened.
If history didn't open, return 1, if familyTree didn't open, return 2.
1) Is using exceptions the only solution for this?
2) Where are the exceptions launched?
3) Is it wrong if I catch exceptions in main?
|
You could throw exceptions in your constructor and catch them in main. Or you could catch the exceptions in your constructor and fix it so that the class can be correctly initialised whatever happens.
To make your class more testable, the constructor should do as little work as possible. I would have two methods:
bool readHistory (std::string fileName)
bool readFamillyTree (std::string fileName)
instead of trying to do that in the constructor. They would return true if the file could be read and was sane. You could have a overloaded constructor that called those methods. As was pointed in the comments, the constructor should return a usable object. I am assuming that those files are not necessary for the object to function. This could be erroneous.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c++, exception"
}
|
append in middle of NSString in iPhone programming
how to append the value of string in between NSString?
for example:
NSString* str1 = @"Hello";
NSString* str2 = @"Hi.."/*add contents of str1*/@"how r u??";
please tell me how to achieve this??
|
(Append always means add to the end. That's inserting a string in the middle.)
If you simply want to construct a literal string, use
#define STR1 @"Hello"
NSString* str2 = @"Hi..." STR1 @" how r u??";
To insert it in run time you need to convert str2 into a mutable string and call `-insertString:atIndex:`.
NSMutableString* mstr2 = [str2 mutableCopy];
[mstr2 insertString:str1 atIndex:4];
return [mstr2 autorelease];
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "iphone, nsstring"
}
|
D'Alembert Principle Intuitive Understanding
Does Alembert work for systems of rigid bodies? My question comes from this image. (sorry for the poor drawing!)
^2 - qgm$$
Therefor: $$\frac{d}{dt}\left(\frac{\partial \mathcal{L}}{\partial \dot{q}}\right) = \frac{\partial \mathcal{L}}{\partial q} \implies m\ddot{q} + \frac{I}{R^2}\ddot{q}=-gm$$
Now solve for $\ddot{q}$: $$\ddot{q}=\frac{-gm}{m+\frac{I}{R^2}}$$
|
stackexchange-physics
|
{
"answer_score": 2,
"question_score": 2,
"tags": "homework and exercises, rotational dynamics, acceleration, rigid body dynamics, string"
}
|
Number of DB connection using
We are using spring, jpa, hibernate, oracle and java for our web application. While deploying our web application, it uses certain amount of connection from the DB. So i need to find the following
1. Total number of available connection
2. number of connection currently using
3. number of free connection.
Is it possible? Any help is appreciated. Thanks in advance. When I look in the net, i got the idea of find the above in oracle db as the Admin privileged user. But I need to do it in our application or the external program.
|
use the MyOra tool which has all the key features regarding to DB the developer expect. < and may try with the following oracle query <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, spring, hibernate, jpa, oracle11g"
}
|
How to set date picker initial value?
I have a date_picker from toedter.com from jcalendar package which are swing components. How can I set an initial value to it? I'm using netbeans.
I added the date_picker on design view and tried this on my source code :
UtilDateModel model = new UtilDateModel();
model.setDate(2014, 8, 24);
model.setSelected(true);
but I've been playing around where to put it still doesn't seem to work.
Any idea guys?
|
You can try this out :
String dateValue = "initial date value"; // must be in (yyyy- mm- dd ) format
Date date = new SimpleDateFormat("yyyy-mm-dd").parse(dateValue);
jDateChooser.setDate(date);
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "java, netbeans, jcalendar"
}
|
A question based on analyticity of entire functions
This particular question was asked in quiz yesterday and I was unable to solve it.
> Suppose f and g are entire functions and g(z) $\neq$0 for all z $\epsilon \mathbb{C} $ . If |f(z) |$\leq$ |g(z) | , the which one of them is true.
1.f is a constant function.
2.f(0) =0 .
3.for some C $\epsilon \mathbb{C} $ , f(z) = C g(z) .
4.f(z) $\neq$ 0 for all z $\epsilon \mathbb{C} $ .
4 th option can be removed by taking f(z) =0 and g(z) =2 .
But I am unable to find any way to remove rest of options.
|
Simply consider the function $z \mapsto \frac{f(z)}{g(z)}$. Since, $g(z) \ne 0, \forall z \in \Bbb C$ we have that this map is entire and as $|f(z)| \le |g(z)|$ we have that our map $z \mapsto \frac{f(z)}{g(z)}$ has absolute value bounded by 1 $\forall z \in \Bbb C$, hence Liouville's theorem gives (3).
(1) and (2) aren't true by taking $f(z)=g(z)=e^z$
(4) isn't true by taking $f \equiv 0$ and $g \equiv 1$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "complex analysis, entire functions"
}
|
Change SQL Server authentication mode using script
I am wondering how can someone change the sqlserver authentication mode by just a script?
I need a script to run in query window and change the authentication to mixed mode with it. Any idea?
|
For Windows only mode:
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 1
Use `2` instead of `1` for mixed authentication.
You'll have to restart SQL Server after changing this setting. You can't do that from T-SQL. From the command prompt, it's something like `net stop mssqlserver` then `net start mssqlserver`.
|
stackexchange-stackoverflow
|
{
"answer_score": 34,
"question_score": 17,
"tags": "sql server, sql server 2008 r2"
}
|
Why wysiwyg plugin in magento gets me broken links?
When I try to insert an image to the wysiwyg editor in Magento it places the right variable of the image path in the media directory.
But, wysigyg doesn't find the right path/url, example:
I inserted:
<p><img src="{{media url="wysiwyg/blog/Screen_Shot_2013.png"}}" alt="" /></p>
But, in the preview it gets me the next broken src:
<img src=" alt="" data-mce-src="
And of course, it doesn't show the image. Also this happens with links and other media files.
|
System -> Configuration -> General -> Content Management -> Use Static URLs for Media Content in WYSIWYG for Catalog to Yes
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "image, magento, media, wysiwyg, broken links"
}
|
Recreating the control file
I have experienced a problem with flashback and the solution is to recreate the control file (the error was ORA-01207).
So to do this I tried
alter database backup controlfile to trace as '/tmp/trace.sql';
This creates a file that instructs one to either use set one or set two. i.e. with or without resetlogs.
How does one determine what set is the most applicable? Is there any tests that one needs to perform to find out?
|
From /tmp/trace.sql:
> The first set opens the database with the NORESETLOGS option and should be used only if the current versions of all online logs are available. The second set opens the database with the RESETLOGS option and should be used if online logs are unavailable.
If you're only recreating the controlfile you should be able to perform a complete recovery. i.e. without resetlogs. If you are missing some online redo logs or if they are not complete, then it will be a partial recovery, and RESETLOGS will be required.
|
stackexchange-dba
|
{
"answer_score": 1,
"question_score": 2,
"tags": "oracle 12c"
}
|
How to allow user to vote once per day not for last 24hrs?
I am trying to create function that allow users to vote only once in a day. For this I have created `ratingTimestamp` field in table in which I am inserting the current timestamp value at the voting time.
And for validating the users that he can vote only once per day. I am using this MySQL query:
SELECT count( * ) AS votecount
FROM ratings AS e
WHERE e.userId =5
AND e.ratingTimestamp >= NOW( ) - INTERVAL 1
DAY
The problem is that this query giving me `votecount` on 24hrs basis but I want it on the basis of date only.
Like if user voted on 12-03-2014 11:59:00 AM and again he tried for voting at 13-03-2014 4:00PM he can vote but with using the above query it is not possible because it is giving me vote count 1 for this case because it is counting the last 24hrs from 4:00PM.
|
I think You should use something like this:
$sql="SELECT count( * ) AS votecount FROM ratings WHERE DATE(e.ratingTimestamp) = CURDATE()";
OR you can try through PHP
$sql="SELECT count( * ) AS votecount FROM ratings WHERE e.ratingTimestamp >= '".strtotime("today")."' AND e.ratingTimestamp < '".strtotime("tommorow")";
OR alternatively look into this link
Retrieve records by current date from MySQL
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "php, mysql, sql, wordpress"
}
|
Mac questions: installing TrueCrypt and Windows 7
I'm about to buy a Mac laptop, but I need to be able to use Windows 7 as well + encrypt the HDD with TrueCrypt (or a better alternative for the mac).
My questions are:
1. How well does Windows 7 perform under boot camp?
2. Will I be able to encrypt the whole HDD (with TrueCrypt or whatever else) and still use boot camp to dual-boot?
Your help is much appreciated
|
1) Windows 7 runs at full speed under bootcamp. Bootcamp is not an emulator or virtual machine, simply a utility which makes it easier to install Windows - otherwise your intel-based Mac is not that different from any other PC laptop.
2) According to this document and this question, Truecrypt has issues with Windows not being the first partition when doing a full drive encryption because it expects Windows to be the first partition on the drive, and people haven't been too successful even with installing a custom bootloader. I would recommend using Windows 7's Bitlocker Drive encryption if your version has this feature if you wish to dualboot both windows and Macos x.
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 0,
"tags": "windows 7, mac, multi boot, encryption, boot camp"
}
|
Count variable in Python function
def prime_numbers(number_list): prime_list = []` for number in number_list: count = 0 for prime in range(1, number): if number % prime == 0: count += 1 if count == 1: prime_list.append(number)
print(prime_list)
prime_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13, 21, 19])`
|
Count here is used as a flag.
when it gets to 1, it means that the number is divisible by another number and hence not a prime
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "variables"
}
|
Downloading folders from Google Cloud Storage Bucket
I'm new to Google Cloud Platform.I have trained my model on datalab and saved the model folder on cloud storage in my bucket. I'm able to download the existing files in the bucket to my local machine by doing right-click on the file --> save as link. But when I try to download the folder by the same procedure as above, I'm not getting the folder but its image. Is there anyway I can download the whole folder and its contents as it is? Is there any gsutil command to copy folders from cloud storage to local directory?
|
You can find docs on the gsutil tool here and for your question more specifically here.
The command you want to use is:
gsutil cp -r gs://bucket/folder .
|
stackexchange-stackoverflow
|
{
"answer_score": 39,
"question_score": 26,
"tags": "google cloud platform, google cloud storage"
}
|
What is the meaning of the line "Upon a homely object Love can wink" in this context
What's the meaning of the last line of this extract from Shakespeare's _Two Gentlemen of Verona_?
> _Valentine._ This is the gentleman I told your ladyship
> Had come along with me, but that his mistress
> Did hold his eyes lock'd in her crystal looks.
>
> _Silvia._ Belike that now she hath enfranchised them
> Upon some other pawn for fealty.
>
> _Valentine._ Nay, sure, I think she holds them prisoners still.
>
> _Silvia._ Nay, then he should be blind; and, being blind
> How could he see his way to seek out you?
>
> _Valentine._ Why, lady, Love hath twenty pair of eyes.
>
> _Thurio._ They say that Love hath not an eye at all.
>
> _Valentine._ To see such lovers, Thurio, as yourself:
> **_Upon a homely object Love can wink_**.
|
_Wink_ here has the sense _close the eyes_ \- the same sense is in play when we say that an authority _winks at_ a violation of some regulation, pretends not to see it.
To paraphrase this very "conceited" dialogue in More or Less Fully Modern English:
> Valentine: Love has twenty pairs of eyes.
> Thurio: What I've always heard is that Love has no eyes at all.
> Valentine: Well, of course when it looks at you; **_Love can close its eyes when
> it sees something ugly._**
|
stackexchange-english
|
{
"answer_score": 4,
"question_score": 4,
"tags": "poetry"
}
|
ref keyword example in .NET framework library
`DateTime.TryParse` method has a `DateTime` `out` parameter.
public static bool TryParse(string s, out DateTime result)
Is there any such usage of the `ref` keyword in .NET framework?
|
Yes, for example the various overloads of `Interlocked.Exchange`:
public static double Exchange(
ref double location1,
double value
)
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "c#, .net"
}
|
Ionic: Why the detected device language is 'zz-ZZ'
In ionic `navigator.language` returns `en-US` on the browser and `zz-ZZ` on my Android device.
I've read that it is called Pseudolocalization.
Why does it happen? How can I get the real device language?
|
You should inject the `$locale` service and retrieve the device language using `$locale.id`
* * *
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ionic framework, localization, pseudolocalization"
}
|
Moved from bash to zsh - some commands / binaries not recognised
I've recently started using zsh. I notice some commands which work in bash no longer work in zsh. In particular, I'm using _virtualenv_ with _virtualenvwrapper_ for Python virtual environments, which has the command _workon_ to change the current virtual environment. When I run bash, it recognises this command, but when running zsh, this command is not recognised.
Where does the shell look for these binaries? How can I point zsh to this binary when I use this or similar commands?
To clarify, my default shell is now zsh, when I enter _bash_ to start running bash, the command is recognised, and when I enter _zsh_ it is no longer recognised. The path is therefore the same when running both commands
Running Linux Mint 19.3
|
The command `workon` is defined in a script to be _sourced_ by the shell. With bash, you typically edit `.bashrc` or `.profile` to make it happen whenever the shell is opened.
You can do the same for zsh, but you need to carry over the lines from the file you edited to a different file, e.g. `.zprofile`.
See < and < for more information.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linux, bash, zsh, linux mint"
}
|
Change value of parameter inside method, is this an anti-pattern?
So something like this
public void MyMethod(object parameter)
//....
BuildSomething(parameter);
BuildLayers(parameter);
BuildOtherStuff(parameter);
}
public void BuildSomething(object parameter)
{
//...
parameter.SomeProperty = "sadsd";
//...
}
If this is an anti pattern, what is it called? The problem (possibly) is that you are implicitly changing _parameter_ and using the changed value.
**I just want to know what is this anti-pattern know as**
Thanks
|
It is a side effect.
These are normally not good and considered to be a code smell as it makes it difficult to reason about and understand code.
However, this pattern is sometimes useful.
C# codified the `ref` and `out` keywords _specifically_ to show that a method is expected to have side effects.
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 13,
"tags": "c#, anti patterns"
}
|
KeyError when filtering excel data with pandas
I am trying to read and filter from excel data in Python. I used the code below:
import pandas as pd
import numpy as np
df = pd.read_excel('file.xlsx')
df['apples'] = (pd.cut(df['apples'],bins=[-np.inf,2,5,np.inf],labels=['WOW','ok','BOB']))
print(df)
This is my excel file
But KeyError: 'apples' occurs. Do you have any advice about how can I fix this?
|
There is problem you have header with `2` rows, so by default columns of `DataFrame` are created by first row.
So need skip this first row by:
df = pd.read_excel('file.xlsx', skiprows=1)
Or:
df = pd.read_excel('file.xlsx', header=1)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python, excel, pandas"
}
|
Authenticate user without using factory in unit testing
I am new to unit testing. I want to authenticate a user without using Factory. I want my testing code to be simple. I don't know how to use the Factory. Here is my code :
public function loginVerify()
{
$user = factory('App\User')->create();
}
|
the first thing that you have to do is follow the naming convention
Change
public function loginVerify()
{
$user = factory('App\User')->create();
}
to
public function testLoginVerify()
{
$user = factory('App\User')->create();
}
always use the test as a prefix for your testing function name. and now as we look at your question, you can simply do this...
public function testLoginVerify()
{
$user_details = [
'email' => '[email protected]', // the email of a particular user
'password' => 'password' // the password of that user
];
$this->post('/login', $user_details)->assertRedirect('/home');
}
This is the very simplest way to do this.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "laravel"
}
|
Is a compact triangulated surface obtained by edge-pairing on a polygon?
I guess that one can make the compact surface by edge-pairing. I'm trying to rearrange the triangles so that they could be considered as parts of a disk.
Let $S=\bigcup_{i=1}^n T_i$. Then we are able to reorder these triangles so that $\bigcup_{i=1}^j T_i$ and $T_{j+1}$ shares at least one edge, $e_j$. By using mathematical induction, I want to show the quotient space of $\bigcup_{i=1}^j T_i$ obtained after gluing $e_1,\cdots,e_{j-1}$ is a topological disk.
However there are two ways of gluing the edges. One is just gluing one edge of a polygon and that of a triangle not in the polygon. The other one is gluing two distinct edges of the polygon. How can I distinguish
How can I use the induction by integrating the above 2 ways? Or is there easier proof without using the mathematical induction?
Any help will be appreciated.
|
Construct a graph which has one vertex at the center of each triangle and in which two vertices are connected iff the corresponding triangles share a side (this is called the dual graph for the triangulation)
In this graph construct an arbitrary spanning tree. Now cut the surface along the sides of the triangles which do _not_ correspond to sides in the spanning tree. You get a disk, and clearly the surface can be reobtained by identifying things in its boundary.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "algebraic topology, triangulation"
}
|
Ethereum Name Service (ENS) is case-sensitive?
Are the ENS addresses case-sensitive?
Making different example.eth from ExAmple.ETH?
If I'm going to bid on a name I must pay attention on that?
|
Just to add to the previous answer, I believe ENS implements RFC5891 section 4, which has this to say about case sensitivity:
> Labels MUST be compared using equivalent forms: either both A-label forms or both U-label forms. Because A-labels and U-labels can be transformed into each other without loss of information, these comparisons are equivalent (however, in practice, comparison of U-labels requires first verifying that they actually are U-labels and not just Unicode strings). **A pair of A-labels MUST be compared as case-insensitive ASCII (as with all comparisons of ASCII DNS labels).** U-labels MUST be compared as-is, without case folding or other intermediate steps. While it is not necessary to validate labels in order to compare them, successful comparison does not imply validity. In many cases, not limited to comparison, validation may be important for other reasons and SHOULD be performed.
(See comments from EIP-162.)
|
stackexchange-ethereum
|
{
"answer_score": 5,
"question_score": 5,
"tags": "addresses, ens"
}
|
Stop music from another view controller
I have an app with music , you can play music in 2 methods -> click on cell and another view controller is opening or click on a button and the music is playing .
How can i do that only one sound to be playing ?
I was trying this : `[musicViewContreoller.player stop]`. I synthesize player. but is not working . any ideea ?
|
I solved this by making the player a propetry in AppDelegate and then i use this :
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.player stop];
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ios, objective c, avaudioplayer"
}
|
Keep getting a error when I try and sort a list, says "TypeError: '<' not supported between instances of 'str' and 'int'"
toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]
prices = [2, 6, 1, 3, 2, 7, 2]
num_two_dollar_slices = prices.count(2)
print(num_two_dollar_slices)
num_pizzas = len(toppings)
print(num_pizzas)
print("We sell "+ str(num_pizzas)+" different kinds of pizza!")
pizza_and_prices = [2, "pepperoni", 6, "pineapple", 1, "cheese", 3, "sausage", 2, "olives", 7, "anchovies", 2, "mushrooms"]
print(pizza_and_prices)
pizza_and_prices.sort()
print(pizza_and_prices)
What do I need to change in order for my list of pizza_and_prices to be sorted into alphabetical order?
|
The problem is, you have both strings and integers as part of the same list. When python is trying to sort them, it is not able to, because it can't compare strings with int. Hence, you should try using a 2D list. Like this.
pizza_and_prices = [[ 6,"pineapple"], [2, "pepperoni"]]
pizza_and_prices.sort(key=lambda pp:pp[0])
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "python"
}
|
How can I quickly solve this query?
I have one table which contains 3 fields namely code, name, rperson. It has following data:
code name rperson
100 anil 100
101 babu 100
102 sajad 100
103 Rajesh 102
104 roy 102
I want a table with following output:
name rperson
anil anil
babu anil
sajad anil
Rajesh sajad
roy sajad
|
select a.name as name,b.name as represon from table1 a
inner join table1 b on a.code=b.rperson
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -12,
"tags": "sql"
}
|
How to resolve Castle.Windsor and MoQ version conflicts for Castle.Core assembly
In my project I need to use simultaneously Castle.Windsor and Moq dlls. Windsor requires Castle.Core also to be referenced in the project.
Problem starts when I try to use methods from Castle.Core: _`Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(...);`_
**Problem1:** If I use Moq.dll from NET40 folder, I got built error "The type 'Castle.DynamicProxy.Generators.AttributesToAvoidReplicating' exists in both '...\Windsor\dotNet40\Castle.Core.dll' and '...\MoQ\NET40\Moq.dll'"
**Problem2:** If I use Moq.dll from "NET40-RequiresCastle" folder, which is logically in my situation, I got versions conflict - Moq.dll uses Castle.Core, Version=2.5.0.0, but Windsor uses Castle.Core, Version=2.5.1.0
|
Problem can be solved using assembly binding - App.config:
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Castle.Core" publicKeyToken="407dd0808d44fbdc" />
<bindingRedirect oldVersion="1.0.0.0-2.5.0.0" newVersion="2.5.1.0" />
</dependentAssembly>
</assemblyBinding>
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 4,
"tags": "castle windsor, moq, castle"
}
|
terminate script of another user
On a linux box I've got a python script that's always started from predefined user. It may take a while for it to finish so I want to allow other users to stop it from the web.
Using kill fails with Operation not permitted.
Can I somehow modify my long running python script so that it'll recive a signal from another user? Obviously, that another user is the one that starts a web server.
May be there's entirely different way to approach this problem I can't think of right now.
|
If you set up your python script to run as a deamon (bottom of page under Unix Daemon) on your server (which sounds appropriate), and you give the apache user permissions to execute the init.d script for the service, then you can control the service with php code similar to this (from here \- the service script name in this case is 'otto2'):
<?
$otto = "/usr/etc/init.d/otto2 ";
if( $_GET["action"] ) {
$ret = shell_exec( $otto.$_GET["action"] );
//Check your ret value
}
else {
?>
<a href="<?=$PHP_SELF?>?action=start">Start </a>
<a href="<?=$PHP_SELF?>?action=stop">Stop </a>
<?
}
?>
The note on that is 'really basic untested code' :)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "python, linux, signals, kill"
}
|
ImportError: No module named 'tensorflow.contrib.data'
My tensorflow version is 1.1.0
I try to import some file:
**strong textfrom tensorflow.contrib.data import Dataset, Iterator**
and got error :
**ImportError: No module named 'tensorflow.contrib.data'**
So, what is solution of this?
|
**tf.contrib.data** has been deprecated and been removed (Check here). So, in order to import "Dataset" and "iterator", follow the following steps:
1. You need to upgrade the tensorflow version using: `sudo pip3 install --upgrade tensorflow`. Check the installation guide here
2. Open the python terminal and type
`import tensorflow as tf`
`dataset = tf.data.Dataset`
Hope it will help.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "tensorflow"
}
|
__init__() got an unexpected keyword argument 'required'
For some reason, Django is not letting pass the parameter `required=False` to my form fields.
This is my form:
class InstrumentSearch(forms.ModelForm):
groups = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, required=False)
time = forms.TimeInput(required=False)
date = forms.DateField(required=False)
notes = forms.TextInput(required=False)
The error is on the line
time = forms.TimeInput(required=False)
According to the Django Documentation here, this should absolutely work.
|
Looks to me like TimeInput inherits from Widget (via TextInput), which accepts attributes in one dictionary as the `attrs` argument. The examples with TextInput show use of required:
>>> name = forms.TextInput(attrs={'required': False})
By contrast, Field subclasses such as TimeField and CharField do accept keyword arguments like you use.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "python, django, forms, required"
}
|
If I want to spin a disc or rod with an objective of high tip/edge velocity (of .1c) what are my limitations?
What are our limitations on being able to spin a disc or rod to create a relativistically fast tip/edge speed?
My thoughts are you should be able to increase the radius of the spinning object to offset the growing tensile strain as you increase RPMs, would this increase be so massive that it would not feasible to build?
I was surprised that I couldn't find experiments doing something like this for the purpose of testing special relativity, the highest speed I could find for a massive spinning object was for a fly-wheel with and edge speed going a few Mach (still impressive, I just must be missing something as to why we haven't done faster).
|
there simply are no materials strong enough to withstand the tensile stresses caused by spinning at relativistic speeds. if you were to do the calculation, you would see that no experiment is necessary to establish that fact. If you were to try the experiment anyway, be warned that a spinning flywheel contains an immense amount of stored energy which gets released in an instant when the flywheel explodes under stress. the flywheel is converted into a bomb and its broken pieces become shrapnel.
|
stackexchange-physics
|
{
"answer_score": 1,
"question_score": 0,
"tags": "special relativity, velocity"
}
|
Aptana / Git: How to "forget" unstaged changes
I'm new to Git,
Made some local changes that I don't want to commit but do want to keep locally. How do I make Git in Aptana "forget" these changes and remove them from the unstaged changes menu?
Thanks
|
git reset
or:
git reset (filenames)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "git, aptana"
}
|
Conversion Failed when converting date and/or time
I am running into an issue. I get the Conversion failed error on the code sniped below.
I can't seem to pinpoint why this is happening, in my Dev environment I do not get the error and everything runs smoothly.
Dim PrdDate As Date
SQL.ReturnRead = 0
PrdDate = dtpDataInput.Value.Date
MsgBox(PrdDate)
SQL.ReadQuery("SELECT CAST(DATEDIFF(second, TimeDown, TimeUp) / 60 / 60 % 24 AS NVARCHAR(50)) + '.'
+ CAST(DATEDIFF(second, TimeDown, TimeUp) / 60 % 60 AS NVARCHAR(50)) as HrsDown From UDOData
WHERE (cast(TimeDown AS DATE) = '" & PrdDate & "'
AND CAST(TimeUp AS DATE) = '" & PrdDate & "') and FleetNo = '" & FleetStr & "'")
UDOHRS = SQL.ReturnRead
I have checked the regional settings on the live environment and all seems ok.
Thank you for everyone's help
|
When formatting for SQL Server it's better to always format it as YYYYMMDD.
Just use
WHERE (cast(TimeDown AS DATE) = '" & PrdDate.ToString("yyyyMMdd") & "'
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sql, vb.net"
}
|
how do I add a test web service to my project in Visual Studio?
I have a test web service replicating a live web service that hasn't been made public yet (It will be public when the app is released).
I added a new ASP.NET Web Service Application to my solution. Now when I try and add a web reference from the main project and choose "Browse To Web services in this solution" it doesn't find the test web service.
Am I missing an important step here?
|
Maybe the webservice you're trying to connect to isn't running . Do an F5, verify that the service has started by checking the address in the browser then try to add the refference again.
If it doesn't work, just specify the address by hand.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "visual studio, web services"
}
|
How to disable child form controls?
I have a login which have admin and user rights.
If admin- i can access all the forms and controls. \--OK
If user- i can only access limited forms and controls. I have Mdi parent and other forms.
\--NOT OK
I can only disable toolstrip menu on MDI parent but i need to disable controls on the other childforms also.
like butttons/textboxes etch..
|
There are many ways you can do this:
* When opening/loading the control, pass the login rights to the child control and have the OnLoad method set the visibility
* Add a public method on your child form to hide the control. The parent could then call this method
* Make the controls public and access them directly from the parent (i.e. `childForm.ControlToHide.Visible = false`). Gets the job done but is not recommended
Lots of other ways too, these are simply the "easy" ones.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#"
}
|
PHP array(3,5,6,7,8,11) how do we know the missing values are 1,2,4,9,10
I got a an array like this $ids = array(3,7,6,5,1,8,11) . How do we know the missing values are 2,4,9,10 ?
My expecting $ids values 1,2,3,4,5,6,7,8,9,10,11 and order doesn't matter, it could be 3,5,6,1,2,4,8,9,10,11.
I don't need to fill my array with the missing values I just want to know who's missing
|
$numbers = array(3,5,6,7,8,11);
$missing = array();
for ($i = 1; $i < max($numbers); $i++) {
if (!in_array($i, $numbers)) $missing[] = $i;
}
print_r($missing); //1,4,9,10
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 5,
"tags": "php"
}
|
docview in emacs: refreshing dvi content automatically
Is there a way Emacs can automatically refresh the buffer showing the dvi right after my LaTeX compilation? Thank you.
|
Use interactive function:
auto-revert-mode
to enable reloading when the file changes.
|
stackexchange-stackoverflow
|
{
"answer_score": 21,
"question_score": 12,
"tags": "emacs, latex, docview"
}
|
Assigning a variable the file path from a user input Python 2.7
I have a rather large script where I have set a few different files with direct paths. An example would be:
path1 = "C:/temp/"
path2 = "C:/users/<username>/My Documents/test.txt"
Essentially, I would like to set these variables to the file and/or folder path based on a user input. Is it possible to make the user browse to a location and then take that input path and place it into a variable?
Thanks
|
The `tkFileDialog` module has methods that allow the user to browse and select directories and files. Namely, `askdirectory` and `askopenfilename`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python 2.7, user controls, user input, filepath"
}
|
ios EXC_BAD_ACCESS on an implementation
@implementation ContentView // <-- EXC_BAD_ACCESS on this line
log of `self` from the breakpoint:
<ContentView: 0x96a4690; frame = (0 0; 0 0); transform = [0, 0, 0, 0, 0, 0]; alpha = 0; autoresize = RM+BM; autoresizesSubviews = NO; layer = (null)>
What's going on here? Is my object gone?
|
I wrote this to explain EXC_BAD_ACCESS
<
Basically, it happens because you are using memory that is not mapped to your process. This usually happens because you are accessing released objects or the heap is corrupt. The line of code you show is not executable -- it doesn't result in the "memory use" that could trigger this error.
To help debug it:
1. Run an Analyze and fix everything it flags
2. Turn on Zombies and see if it complains that you are sending a message to a released object.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ios, implementation, exc bad access"
}
|
Updating to CM11 - (Status 7) Installation aborted (i9300)
I'm trying to install CM11 onto my Samsung Galaxy S3 (i9300) so I can have the new Google Camera and Chrome Remote Desktop apps.
I tried to install initially via the usual update menu, but got an error and it went to ClockworkRecovery Mod. After much messing around, I downloaded this zip and put it onto an SD card and tried to install it using CWM but I get the following error:
> Error in cm-11-2014005-SNAPSHOT-M5-i9300.zip (Status 7) Installation aborted
Any ideas please? It sucks being without a phone, and I don't want to wipe everything and start again if I can help it since I'm pretty sure I have things on there that aren't backed up (that'll be my first job when I get this working again!)
Thanks :)
|
I hate to answer my phone question on here, but finally sorted it! Thanks to Adach1979 for pointing me towards a useful resource too.
In the end I had to put CM10.2 onto the SD card and install that using CWM - it wiped all of my data (urgh) but at least the phone was working again.
I then used Cyanogenmod's fantastic installer to get the latest version - <
I then had issues where the USB kept disconnecting, apparently this is common on Samsung devices and I managed to fix it by using Zadig and these instructions - <
And now, almost 4 hours after I started, CM11 is finally installed on my phone! :)
|
stackexchange-android
|
{
"answer_score": 1,
"question_score": 3,
"tags": "cyanogenmod, clockworkmod recovery, boot"
}
|
How to get the .config from a Linux kernel image?
I have a Linux kernel image in elf format and I want to find out what `.config` file was used to build this kernel. When I do an **objdump** of the image, I see a section called `kernel_config_data` that contains text but does not look like the config file. Is there a way to retrieve this information?
|
Assuming your kernel was built with the IKCONFIG option, you can use the `scripts/extract-ikconfig` tool to extract the original `.config` file.
Alternately, you can boot that kernel and find the embedded configuration in `/proc/config.gz`.
|
stackexchange-stackoverflow
|
{
"answer_score": 44,
"question_score": 29,
"tags": "linux, linux kernel, kbuild"
}
|
The Revenge of the Post-Christmas - Christmas Movie Rebuses
Rather enjoyed my first outing as a poser in Post-Christmas - Christmas Movie Rebuses so I have made some more. Hopefully these should be a little trickier!

The third one:
> Ghost bust ERs Two = **Ghostbusters II**
Oh no... is the second one:
> The most famous Christmas movie of all, **It's a Wonderful Life**? Awe = wonder, heart is a symbol of life, or a life in many video games, since awe fills the heart, it's a wonder-full life!
And the first one thanks to DooplissForce is:
> **A Christmas Carol** the image depicts the set for the UK show Countdown, and the figure is in the role once filled by Carol Vorderman, hence, with the Santa hat is a Christmas Carol.
|
stackexchange-puzzling
|
{
"answer_score": 8,
"question_score": 11,
"tags": "rebus, movies, seasonal"
}
|
Adding small png image to DynamoDB
I would like to store some small png images in Amazon DynamoDB table. There isn't a file field in the items for a table. Anyone know how to do this. I would like to store it via the web console and then read it from an iOS app. I just can't see any way of uploading a file to the console.
Thanks
|
You aren't going to be able to do that via the console. You could store the png as binary data in the table, but honestly that probably is going to be more trouble than it's worth.
The common pattern for associating files with a DynamoDB record is to store the file in S3 and store the key or URL of that file in DynamoDB.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "amazon web services, amazon dynamodb"
}
|
Embedded Google calendar not displaying unless logged into Google account
I'm trying to embed my Google calendar using an iframe in a small website that I am making, but it seems I can only see the calendar when I am logged into a Google account. If I log out of my Google profiles and then open the page, I just get an empty iframe.
I know it's possible because I've seen other websites display calendars when I'm not logged onto Google, but looking at their code I can't see any difference to what I've got.
I'm getting the error:
Refused to display 'googleCalendarLinkHere' in a frame because it set 'X-Frame-Options' to 'DENY'.
|
Set your calendar to be publicly viewable.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "iframe, calendar, google calendar api"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.