I'm having trouble simplifying this conditional statements logic. Is there a more effervescent way of writing this?
if(($x || $a) && ($x || $y))
{
if($x){
return true;
}
}
return false;
I've had some trouble getting my Rails app to connect to PostgreSQL so I decided to just say screw it and use SQLite for now. (I'm using the tutorial here: http://guides.rubyonrails.org/getting_started.html)
I started a BRAND NEW, fresh Rails app from this tutorial. When I visit my app in the browser after deleting public/index.html, I get this the first time:
Please install the pg adapter: `gem install activerecord-pg-adapter` (no such file to load -- active_record/connection_adapters/pg_adapter)
That's odd to me because I'm not mentioning PostgreSQL anywhere. Here's my databases.yml:
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000
To make things more confusing, I only get that "pg adapter" error on the first load. For every subsequent page request, I get this error:
ActiveRecord::ConnectionNotEstablished
So even though I removed all mention of PostgreSQL, I'm still getting errors. What could be going on?
I constantly hear from other people about how much of the stuff they've used to customize their *nix setup they've shamelessly stolen from other people. So in that spirit, I'd like to start a place to share that stuff here on SO.
Here are the rules:
DON'T POST YOUR ENTIRE DOTFILE. Instead, just show us the cool stuff.
One recipe per answer
You may, however, post multiple versions of your recipe in the same answer. For example, you may post a version that works for bash, a version that works for zsh, and a version that works for csh in the same answer.
State what shells you know your recipe will work with in the answer.
Let's build this cookbook as a team. If you find out that an answer works with other shells other than the one the author posted, edit it in. If you like an idea and rewrite it to work with another shell, edit the modified version in to the original post.
Give credit where credit is due. If you got your idea from someone else, give them credit if possible.
And for those of you (justifiably) asking "Why do we need another one of these threads?":
Most of what I've seen is along the lines of "post your entire dotfile." Personally, I don't want to try to parse through a person's entire dotfile to figure out what I want. I just want to know about all the cool parts of it.
It's helpful to have a single dotfile thread. I think most of the stuff that works in bash will work in zsh and it may be adapted to work with csh fairly easily.
say you have 3 models : user, hair_color, and eye_color
user hasOne hair_color
user also hasOne eye_color
however
var $hasOne = 'hair_color';
var $hasOne = 'eye_color';
obviously wont work. So how do you implement many hasOne relationships in a single model?
I assume the answer is in the cookbook, Im going over that area now, I suspect it has something to do with passing an array to $hasOne, but no example of doing this.
Given two points in a 2D plane, and a circle of radius r that intersects both of those points, what would be the formula to calculate the centre of that circle?
I realise there would two places the circle can be positioned. I would want the circle whose centre is encountered first in a clockwise direction when sweeping the line that joins the two points around one of those points, starting from an arbitrary angle. I guess that is the next stage in my problem, after I find an answer for the first part.
I'm hoping the whole calculation can be done without trigonometry for speed. I'm starting with integer coordinates and will end with integer coordinates, if that helps.
I have a project that I am working on that uses a little image to mark a record as a favorite on multiple rows in a table. The data gets pulled from a DB and the image is based on whether or not that item is a favorite. One image for a favorite, a different image if not a favorite. I want the user to be able to toggle the image and make it a favorite or not. Here's my code:
$(function () {
$('.FavoriteToggle').toggle(
function () {
$(this).find("img").attr({src:"../../images/icons/favorite.png"});
var ListText = $(this).find('.FavoriteToggleIcon').attr("title");
var ListID = ListText.match(/\d+/);
$.ajax({
url: "include/AJAX.inc.php",
type: "GET",
data: "action=favorite&ItemType=0&ItemID=" + ListID,
success: function () {}
});
},
function () {
$(this).find("img").attr({src:"../../images/icons/favorite_not.png"});
var ListText = $(this).find('.FavoriteToggleIcon').attr("title");
var ListID = ListText.match(/\d+/);
$.ajax({
url: "include/AJAX.inc.php",
type: "GET",
data: "action=favorite&ItemType=0&ItemID=" + ListID,
success: function () {}
});
}
);
});
Works great if the initial state is not a favorite. But you have to double click to get the image to change if it IS a favorite initially. This causes the AJAX to fire twice and essentially make it a favorite then not a favorite before the image responds. The user thinks he's made it a favorite because the image changed, but in fact, it's not. Help anybody?
I would like to have users click a link that then selects the html text in another element (NOT an input). By "select" I mean the same way you would select text by dragging your mouse over it. This has been a bear to research because everyone talks about "select" or "highlight" in other terms.
Is this possible?
My code so far is thus:
html:
<a href="javascript:" onclick="SelectText('xhtml-code')">Select Code</a>
<code id="xhtml-code">Some Code here </code>
js (jquery):
function SelectText(element) {
$("#" + element).select();
}
but it doesn't work. Am I missing something blatantly obvious?
Thanks
Brand new to C. I am trying to dynamically allocate the array frags2 of size numberOfFrags and copy over the contents of the original array to it. I have tried numerous approaches and searching and do not understand what is going wrong here. Sizeof on the new array returns 0 instead of what I thought I malloc'd. Any help would be much appreciated!
int main(int argc, const char* argv[]) {
char* frags[MAX_FRAG_COUNT];
FILE* fp = fopen(argv[1], "r");
int numberOfFrags = ReadAllFragments(fp, frags, MAX_FRAG_COUNT);
fclose(fp);
char** frags2 = (char**)malloc(numberOfFrags * sizeof(char*));
for (int i = 0; i < numberOfFrags; i++) {
frags2[i] = frags[i];
}
qsort(frags2, sizeof(frags2) / sizeof(char *), sizeof(char*), cstring_cmp);
I want to put a circled number on a graph as a marker near (but not on) a point. Sounds easy, but I also want to be invariant of zoom/aspect ratio changes.
Because of this invariant, I can't draw a circle as a line object (without redrawing it upon rescale); if I use a circle marker, I'd have to adjust its offset upon rescale.
The simplest approach I can think of is to use the Unicode or Wingdings characters ① ② ③ etc. in a string for the text() function. But unicode doesn't seem to work right, and the following sample only works with ① and not for the other numbers (which yield rectangle boxes):
works:
clf; text(0.5,0.5,char(129),'FontName','WingDings')
doesn't work (should be a circled 2):
clf; text(0.5,0.5,char(130),'FontName','WingDings')
What gives, and can anyone suggest a workaround?
If I use a statement in my code like
int[] a = new int[42];
does it initialized the array to anything in particular? (e.g. 0) I seem to remember this is documented somewhere but I am not sure what to search for.
Hello,
I was taking a look at this tutorial here to prevent animation buildups:
http://www.learningjquery.com/2009/01/quick-tip-prevent-animation-queue-buildup
My situation:
I am doing a double animation like this below, and would like the prevent the animation build up. Since I have 2 animations going, it seems it ignores the .stop(). What can be done to prevent this? I have tried .stop() on both .animate and if I do that it stops animating...
$(document).ready(function() {
$('#element').hover(function() {
$(this).stop()
.animate(
{ left: 200 }, {
duration: 'slow',
})
.animate(
{ top: 200 }, {
duration: 'slow',
});
} , function() {
$(this).stop()
.animate(
{ left: 0 }, {
duration: 'slow',
})
.animate(
{ top: 0 }, {
duration: 'slow',
});
});
});
Any help will be greatly aprecaited!!
I need to create a custom route to list all the rooms in a given building. So, I want the url to look something like this:
/Building/1000/Room
Which would list all the rooms in Building 1000.
Is this the correct mapping for the route (to call the IndexByBuilding method in RoomController)?
routes.MapRoute(
"RoomsByBuilding",
"Building/{id}/Room",
new { controller = "Room", action = "IndexByBuilding", id = "" }
);
I have a question regarding the use of the MVC framework for a blackjack game im writing in java. As I understand, my model would be a class that stores the state of the game, and more specifically, each players hand. Within the model class, I would have an array of listeners, which would be notified each time the game state changes (ie a player has drawn a new card).
These listeners would be my viewer, which is the class that handles the display of the game. This class would implement the ActionListener interface, and each time the model changes, it would call/"notify" my viewer's actionPerformed method.
My question is as follows:
I intend to have two JPanels, each devoted to displaying the respective player's hand. As a player draws a new card, a new ImageIcon would be added to the panel. My question is how would the viewer class know what card has been added to the player's hand?
I suppose I could store the player's hand before a notify event, and then upon the notification event, compare the new state with the old, to find out what has changed. I'm a complete novice here, so I could be completely wrong, but it seems a bit tedious to do this.
Is there a more efficient/common way of detecting what has changed in the model between the before and after state? Another solution would be to redraw the entire panel each time the notification occurs? Would this be a better idea?
I have been pulling my hair out trying to get Chrome to style my search input with a background image. Firefox has no problem, but I fear it's because it treats the input as a regular text input. Is this simply not possible?
Try this as a demo:
<input type="search" />
?input[type="search"] {
background: transparent
url(http://google.com/intl/en_ALL/images/srpr/logo1w.png) no-repeat 0 0;
}??????
If it worked correctly, it should put Google's logo (or part of it) as the background image for the "Search" input. But as you will see when you look at this in Chrome, it DOES NOT WORK. Any ideas, or is this just one of HTML5's quirks? :\
Hi guys.
I am new to Python so please don't flame me if the question is too basic :)
I have read that Python is executed from top - to - bottom.
If this is the case, why do programs go like this:
def func2():
def func1(): #call func2()
def func() #call func1()
if __name__ == '__main__': call func()
So from what I have seen, the main function goes at last and the other functions are stacked on top of it.
Am I wrong in saying this? If no, why isn't the main function or the function definitions written from top to bottom?
I'm implementing Bagwell's Ideal Hash Trie in Haskell. To find an element in a sub-trie, he says to do the following:
Finding the arc for a symbol s,
requires ?nding its corresponding bit
in the bit map and then counting the
one bits below it in the map to
compute an index into the ordered
sub-trie.
What is the best way to do this? It sounds like the most straightforward way of doing this is to select the bits below that bit and do a population count on the resulting number. Is there a faster or better way to do this?
As the title implies how can I create a new log file each day in C#? Now the program may not necessarily run all day and night but only get invoked during business hours. So I need to do two things.
1) How can I create a new log file each day? The log file will be have the name in a format like MMDDYYYY.txt
2) How can I create it just after midnight in case it is running into all hours of the night?
I have a lot of data stores in my app on my provisioned device, and I want to do additional testing on my computer which is much faster than using the device. What is the best way to transfer the data store into the iPhone simulator so I can access it on the computer?
Hi,
I just saw I can set call forwarding in gsm settings on my mobile, will my mobile make this phone call thus anyone that will call me will cost me more money because my mobile will call this new phone? or is it done on the "Sever" side, so it wont cost me money? (not on my mobile...)
Thanks
Here's the query:
INSERT INTO jobemails (jobid, to, subject, message, headers, datesent) VALUES ('340', '[email protected]', 'We\'ve received your request for a photo shoot called \'another\'.', 'message', 'headers', '2010-04-22 15:55:06')
The datatypes are all correct, it always fails at the subject, so it must be how I'm escaping the values, I assume.
I'm sure one of you will see my idiot mistake right away. A little help?
I wrote a source-removal algorithm to sort some dependencies between tables in our database, and it turns out we have a cycle. For simplicity, let's say we have tables A, B, C, and D. The edges are like this:
(A, B)
(B, A)
(B, C)
(C, D)
(D, A)
As you can see, there are two cycles here. One is between A and B and another is between all four of them. Will this type of sort always choke on the largest cycle? Or is that not necessarily the case?
I pretty much stated what I have to ask. But is taking all of your external .js files and putting them before the closing body tag on your master pages okay on an asp.net website?
I'm just going off of what yslow and google speed have been showing. I can't combine these javascripts, so I'm trying to load them "after page load", but doing so makes them useless; some of my jquery things don't work.
I moved my .js files above the opening body tag, and they work. What am I doing wrong? And what could I do to load my .js files after page load? Thanks for any advice anybody can offer!
I need help in trying to use curl to post data to a page and retrieve the results after the form has been submitted.
I created a simple form:
<form name="test" method="post" action="form.php">
<input type="text" name="name" size="40" />e
<input type="text" name="comment" size="140" />
<input type="submit" name="submit" value="submit" />
</form>
In addition, I have php code to handle this form in the same page. All it does is echo back the form values.
The curl that I have been using is this:
$h = curl_init();
curl_setopt($h, CURLOPT_URL, "path/to/form.php");
curl_setopt($h, CURLOPT_POST, true);
curl_setopt($h, CURLOPT_POSTFIELDS, array(
'name' = 'yes',
'comment' = 'no'
));
curl_setopt($h, CURLOPT_HEADER, false);
curl_setopt($h, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($h);
When I launch the page with the curl code in it, I get the form.php page contents but it doesn't not show
the variables that PHP should have echo'd when the form is submitted.
would appreciate any help with this.
Thanks.
Ok, that sounds really confusing. What I’m trying to do is this. I’ve got a function that uploads/resizes photos to the server. It stores the paths in the DB. I need to attach the id of the business to the row of photos.
Here’s what I have so far:
function get_bus_id() {
$userid = $this->tank_auth->get_user_id();
$this->db->select('b.id');
$this->db->from ('business AS b');
$this->db->where ('b.userid', $userid);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
}
That get’s the id of the business. Then, I have my upload function which is below:
/* Uploads images to the site and adds to the database. */
function do_upload() {
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->gallery_path,
'max_size' => 2000
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->gallery_path . '/thumbs',
'maintain_ratio' => true,
'width' => 150,
'height' => 100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$upload = $this->upload->data();
$bus_id = $this->get_bus_id();
$data = array(
'userid' => $this->tank_auth->get_user_id(),
'thumb' => $this->gallery_path . '/thumbs/' . $upload['file_name'],
'fullsize' => $upload['full_path'],
'busid'=> $bus_id['query'],
);
echo var_dump($bus_id);
$this->db->insert('photos', $data);
}
The problem I’m getting is the following:
A PHP Error was encountered
Severity: Notice
Message: Undefined index: id
Filename: models/gallery_model.php
Line Number: 48
I’ve tried all sorts of ways to get the value over, but my limited knowledge keeps getting in the way. Any help would be really appreciated.
I'm trying to make sure my Java application takes reasonable steps to be robust, and part of that involves shutting down gracefully. I am reading about shutdown hooks and I don't actually get how to make use of them in practice.
Is there a practical example out there?
Let's say I had a really simple application like this one below, which writes numbers to a file, 10 to a line, in batches of 100, and I want to make sure a given batch finishes if the program is interrupted. I get how to register a shutdown hook but I have no idea how to integrate that into my application. Any suggestions?
package com.example.test.concurrency;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class GracefulShutdownTest1 {
final private int N;
final private File f;
public GracefulShutdownTest1(File f, int N) { this.f=f; this.N = N; }
public void run()
{
PrintWriter pw = null;
try {
FileOutputStream fos = new FileOutputStream(this.f);
pw = new PrintWriter(fos);
for (int i = 0; i < N; ++i)
writeBatch(pw, i);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally
{
pw.close();
}
}
private void writeBatch(PrintWriter pw, int i) {
for (int j = 0; j < 100; ++j)
{
int k = i*100+j;
pw.write(Integer.toString(k));
if ((j+1)%10 == 0)
pw.write('\n');
else
pw.write(' ');
}
}
static public void main(String[] args)
{
if (args.length < 2)
{
System.out.println("args = [file] [N] "
+"where file = output filename, N=batch count");
}
else
{
new GracefulShutdownTest1(
new File(args[0]),
Integer.parseInt(args[1])
).run();
}
}
}