text
stringlengths 8
267k
| meta
dict |
---|---|
Q: 2D Array - C vs Java What is the difference between a Dynamic 2D Array in C (int **arr) and A 2D Array in Java (int [][]arr) ?
Is a 2D Array in C/C++ similar to a 2D Array in Java?
A: The answer will change according to part you want to compare.
In Java, arrays are objects that have methods and attributes, however in C/C++ they are not objects.
Both of them similar in a way that array dimension can be different. I mean arr[0] can be 3-dimensional, arr[1] 5-dimensional, etc.
Java is checking array bounds therefore will throw exceptions if you try to reach an index outside of the array boundaries, however in C/C++ no exception will be thrown however, you might end up with an "segmentation fault".
A: Very much similar. Of course, arrays in Java are full-fledged objects instead of "bare" sequences of the constituent types, but multi-dimension arrays are done effectively the same way, with an array of pointers to arrays.
A: Yes, they are quite similar. The benefit of the java arrays is that you cannot access a cell that doesn't exist (you get an ArrayOutOfBoundsException).
I think the important bit is that both are references to an array, so there's no duplication/cloning of the arrays when you pass them to a method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Packages in Servlets In Apache tomcat, there was a project created that included Servlets to service the incoming requests. Java class files were kept under
WEBINF\classes\com\example\web
Why do the Java files need to include "package com.example.web" statement so that their compiled classes may be kept in com\example\web folder? Tomcat container can easily locate the class files because of the Servlet mappings.
Why is this package statement necessary?
A: Because that's how the language works. You specify exactly which classes you import in order to avoid ambiguities.
Imagine the common scenario when you have two classes with the same name, but different package. Which one should be picked?
A: For a namespace. Apart from allowing you to have two different classes by the same names (yet making them resolvable), namespaces also help in having a logical group of classes together. I know I'd look at a util package for utility classes, a domain package for entities, a dao package for data-access classes. Imagine having them all under one hood without multiple packages. Wouldn't that be a mess ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make object move up/down 315 degree slope based on working code from 45 degree slope Alright, so I need to know how to move a object up/down a 315 degree slope based on the code i have for moving said object up/down 45 degree slope. Currently the object moves up/down the 315 degree slope like it's 45 degrees, which is the wrong way (going up and right when he should be going down and right).
Here is the code:
//you're in a double for loop going through every tile in the map, the int's being used are x, and y
//check if the tile is a slope
if (lv.type[lv.tile[x, y]] == Tiles.SLOPE)
{
//create a rectangle collision box
Rectangle tileCol = new Rectangle(x * lv.tileSize, (y * lv.tileSize), lv.tileSize, lv.tileSize + 1);
//if player collision "col" collides with "tileCol" and you haven't done this before this itteration (only happens once per full double loop)
if (col.Intersects(tileCol) && !onSlope)
{
//get the angle of the tile
float angle = lv.angle[lv.tile[x, y]];
//get the x distance of how far away the player's right is inside the tile
float dist = (col.X + col.Width) - tileCol.X;
//constructs the opposite of a right triangle
float opposite = (float)(Math.Tan(MathHelper.ToRadians(angle)) * (dist));
if (angle < 90)
{
//if player's right is less then or equal to tile's right
if (col.X + col.Width <= tileCol.X + tileCol.Width)
{
//place player on slope. this works properly
pos.Y = tileCol.Y - opposite;
//tell the program we don't wanna go through this again until the next full loop starts.
onSlope = true;
}
}
else if (angle > 90)
{
if (col.X >= tileCol.X)
{
//this is where the error is.
pos.Y = tileCol.Y + lv.tileSize + (dist * -1);
onSlope = true;
}
}
}
}
A: I don't fully understand your code because the way it's written, your player's position.Y in the "working" if loop is decremented from the top of the tile, effectively placing him near the top of the rectangle when he's supposed to be going up from the bottom of the slope. But - based on the code above, the following should work for all angles:
// Check if the tile is a slope
if (lv.type[lv.tile[x, y]] == Tiles.SLOPE)
{
// Create rectangle collision that is the same size as the tile
Rectangle tileCol = new Rectangle(x * lv.tileSize, y * lv.tileSize, lv.tileSize, lv.tileSize + 1);
// If player collision "col" standing on "tileCol"
if (col.Intersects(tileCol) && !onSlope)
{
// Get the angle of the tile
float angle = lv.angle[lv.tile[x, y]];
// Get the x distance of how far away the player's right is inside the tile
float dist = col.Right - tileCol.X;
// Figure out how far to offset the player
float offset = (float)(Math.Tan(MathHelper.ToRadians(angle)) * (dist));
// If player's right is less then or equal to tile's right
if (col.Right <= tileCol.Right)
{
if (angle % 180 < 90)
{
pos.Y = tileCol.Bottom + offset;
onSlope = true;
}
else if (angle % 180 > 90)
{
pos.Y = tileCol.Top + offset;
onSlope = true;
}
}
}
45 degrees = 1/8 Pi. 315 degrees = 7/8 Pi. The tangent functions give you 1 and -1 respectively depending on the slope, and offset the character accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Core Data information in application I have an app that I'm building where it has some data built into it that is contained in a core data data model. When I run the app to the simulator, the data is there and everything is peachy.
However, when I deploy the app to the device (an iPad), the app works fine, except there is no data.
Seems like a no brainer, but can't seem to find a switch or check box or anything to tell xcode to deploy the data along with the model.
Update:
The suggested duplicate didn't really help me. I'm not sure I entirely understand what needs to be done. I have the sqllite db with my initial set of data, do I need to load that into core data every time I launch the app?
Also, what about data that the users edits/adds/deletes?
Does that then get lost or is that allowed to stay in core data?
A: What you need to do is prepare an initial set of data as per the duplicate question above.
The database file will be bundled with your app. That location - in the main bundle - will be different to the deployed location. In projects I've worked in, we use the application documents directory to be the deployed location.
So, the logic goes as follows. In your app delegate, in the didFinishLaunchingWithOptions method, check to see if the .sqlite file exists in your application documents directory. If it doesn't get the file from your main bundle and copy it to that location.
From that point on, use that file for all your database operations.
That's how you include a preloaded database in your app.
Now, what about creating the preloaded database in the first place? For that, you should create another target in your project. That target will create the database based upon the data model, and populate it with your initial data. Once it's created, you should drag and drop that file back onto Xcode so that it's included in your app's resources bundle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Amazon EC2 EBS IO Count is high I am running Ubuntu 11.04 +Apache +Mysql +php on free micro tier of Amazon EC2, complete root is attached to EBS.. The db size of mysql is 700 MB.. but in just 45 hours of running the instance.. I/O count is 713,136... ??
I have installed phpbb on my website and it is getting around 4000 pageview/day. how can I optimize the I/O..
A: You can use APC (Alternate PHP Caching) so that there is no I/O request for cached pages.
If anybody else has better idea please post it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: append date to osql made backup with batch thumbs up for this forum and am glad there's so many volunteers around on line.
I'm not familiar with batch, so maybe someone would be so kind to enlighten me with answer. Be very thankfull.
I try to backup many sql db with osql and then rename them with appended date ( and time)( .bak to .dat is optional too)
wanna have all code in one batch so that I would be able to schedule it
Found the way to backup sql db with osql and it works fine.
Also found the way to rename file in batch code and it works fine too.
But when I try to join two of them together it backups files but with no rename part. I'm stucked and seems to not find the way out of this hole.
Can someone help me, please, my eyes cannot see over that obstacle.
:: BAT file
echo off
osql -U** -P** -Sserver\SQLEXPRESS2005 -ddb -u -w250 -n -l 30 -iback.txt -ooutput.txt
FOR /F "TOKENS=1,2*" %%A IN ('DATE/T') DO SET DATE=%%B
SET DATE=%DATE:/=%
FOR /F "TOKENS=*" %%A IN ('TIME/T') DO SET TIME=%%A
SET TIME=%TIME::=%
set TODAY=%DATE%%TIME%
echo %TODAY%
rename "C:\back\TEST.bak" "TEST%TODAY%.dat"
@echo on
Thanks in advance
A: %DATE% and %TIME% are system environment variables and should not be reset. You should use different variables.
I like this approach:
:: BAT file
echo off
osql -U** -P** -Sserver\SQLEXPRESS2005 -ddb -u -w250 -n -l 30 -iback.txt -ooutput.txt
FOR /f "tokens=2,3,4 delims=/ " %%a in ('echo %DATE%') do (
set "Month=%%a"
set "Day=%%b"
set "Year=%%c"
)
FOR /f "tokens=1,2,3,4 delims=:." %%a in ('echo %TIME%') do (
set "HOUR=%%a"
set "MINUTE=%%b"
set "SECOND=%%c"
set "HUNDREDTHS=%%d"
)
SET Today=%YEAR%%MONTH%%DAY%%HOUR%%MINUTE%%SECOND%%HUNDREDTHS%
echo %TODAY%
rename "C:\back\TEST.bak" "TEST%TODAY%.dat"
@echo on
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: eclipse ee servlet tomcat doPost http405 I'm trying to go a post from HTML to Java Servlet using eclipse ee and tomcat starting the server through eclipse.
But I am getting:
HTTP Status 405 - HTTP method POST is not supported by this URL
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
<form method="POST" action="AddHost">
Host name : <input name="hostname" type="text"><br>
Genre : <input name="genre" type="text" ><br>
<input type="submit" value="add host">
</form>
</body>
</html>
This is the servlet:
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
@WebServlet("/AddHost")
public class Addhost extends HttpServlet {
public void doPost(HttpServletResponse res,HttpServletRequest req) throws IOException{
String hostname = req.getParameter("hostname");
String genre = req.getParameter("genre");
}
public void doGet(HttpServletResponse res,HttpServletRequest req) throws IOException{
doPost(res,req);
}
A: You have used bad signature of method doPost and instead of overriding, you are overloading
From javadoc HttpServlet contains:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
So you should change this:
public void doPost(HttpServletResponse res,HttpServletRequest req)
to this:
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
@Override annotation is not necessary but strongly recommended to avoid such mistakes.
edited:
I added override annotation like mth suggested
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Show time tag in SSRS Parameter I have an SSRS report with two parameters: StartTime and EndTime. I have default values on the parameters to be set as the current date at 12:00am and the previous day at 12:00am.
However, since 12am is the default time on SSRS, it will not show in the parameter selection. What you see is, for example, '9/29/2011'. If there were to be a time other than 12:00am, you would see '9/29/2011 12:45:00.' Is it possible to get the report parameters to populate at 12am and still show the time? The reason I want this is because, although I know that it's possible to set a time, those using the report may assume you can only choose the date.
I feel like I did a pretty bad job explaining this. Here is a picture of what I have and what I want. I modified the EndTime to look like how I want it to look (by typing it in after the report was ran)
A: I just tested this in SSRS 2008R2 BIDS: If I add a millisecond to the datetime, you'll get the time displayed as you want. I.E. set the default value to:
=DateTime.Parse("October 2, 2011, 12:00:00.001")
If this millisecond causes you problems elsewhere in the report, then test for this value and subtract a millisecond back out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Import picture and save to isolated storage WP7 I am currently working on a project where the user needs to select a image from there photo gallery and import it. Using the following code I am able to import the picture but I have a few questions.
*
*What is the image named upon import?
*Where is the image located once imported
*Is it possible to save that image and reload it when the app is opened again (ie using isolated storage)
Heres the code from a tutorial
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.IO;
using System.Windows.Media.Imaging;
namespace PhoneApp4
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
PhotoChooserTask selectphoto = null;
private void button1_Click(object sender, RoutedEventArgs e)
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BinaryReader reader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
}
}
}
}
A: *
*The PhotoResult contains OriginalFileName.
*When the PhotoChoserTask completes PhotoResult.ChosenPhoto gives you a stream to the data for the photo.
*Yes at that point you can store the image in isolated storage.
private void Pick_Click(object sender, RoutedEventArgs e)
{
var pc = new PhotoChooserTask();
pc.Completed += pc_Completed;
pc.Show();
}
void pc_Completed(object sender, PhotoResult e)
{
var originalFilename = Path.GetFileName(e.OriginalFileName);
SaveImage(e.ChosenPhoto, originalFilename, 0, 100);
}
public static void SaveImage(Stream imageStream, string fileName, int orientation, int quality)
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
var fileStream = isolatedStorage.CreateFile(fileName);
var bitmap = new BitmapImage();
bitmap.SetSource(imageStream);
var wb = new WriteableBitmap(bitmap);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, orientation, quality);
fileStream.Close();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: tar/bzip files without including the folder structure sample setup: folder structure
/folder1/folder2/folder3
folder3 has 2 files:
*
*sample.backups.tar
*sample
My objective to run a script that bzips sample and appends it to sample.backups.tar, remove the compressed file outside bzip.
I wrote the following lines
folder3Path=#full path for folder3
samplePath=#full path with file name for sample file
compressedSamplePath=#full path with file name for bzipped sample file to be created
sampleBackupsPath=#full path with file name for sample.backups.tar
tar -jcf $compressedPath sample
tar -r --file=$sampleBackupsPath $compressedSamplePath --remove-files
The result was that inside sample.backups.tar I have the file structure /folder1/folder2/folder3/sample.tar.bz2.
I don't want the folder structure there; I want only sample.tar.bz2 to be in that file, without the folders. How would I accomplish that?
Things tried:
tar -jcf $compressedPath sample
tar -C $folder3Path -r --file=$sampleBackupsPath $compressedSamplePath --remove-file
Attempted to change the folder to compressed sample file, but it still gives me the folder structure
Note:
For the requirement I have, I need to use absolute and full paths for all name references.
I am using append mode for tar as I need to use the same tar to store multiple bzips.
A: did you try:
`tar -jcf $compressedPath sample`
filename=$(basename $compressedSamplePath)
`tar -r --file=$sampleBackupsPath $filename --remove-files`
A: `tar -C $folder3Path -jcf $compressedSamplePath sample`
`tar -C $folder3Path -r --file=$sampleBackupsPath $compressedSampleName`
`rm $compressedSamplePath`
I ended up solving the problem in the above fashion, but I dont understand why the following would not work.
`tar -C $folder3Path -r --file=$sampleBackupsPath $compressedSampleName --remove-files`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I view the SQL command sent by .SaveChanges() For debugging purposes, I'd like to view the SQL command that is being sent to my database when I call .SaveChanges() on my container object. Is there a way to spy that value?
Thanks in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to implement a longtouch with a ListView? How do I implement a long touch event into my ListView? The only useful MotionEvents I see are ACTION_DOWN and ACTION_UP (there's no ACTION_STILL_DOWN event).
A: implement the OnItemLongClickListener interface in your ListActivity or you can use
getListView().setOnItemLongClickListener(new OnItemLongClickListener(){})
in the inner class way
A: ListActivity has a ListView, which you can get with:
ListView lv = getListView();
Then you can create a listener like so:
lv.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick( AdapterView<?> av, View v, int pos, long id ) {
onLongListItemClick(v,pos,id);
return false;
}
} );
You then create your handler method:
protected void onLongListItemClick(v,pos,id) {
Log.i( TAG, "onLongListItemClick id=" + id );
}
Take a look at this discussion from the Android Developers google group
A: Try setting OnLongClickListner on listview. See this.
A: You can implement base-adapter or array-adapter for fix your issue
In getView() method of adapter you will get view onject and on view object you can set all event like click, Touch, LongTouch and more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why is this not context free grammar? I vaguely recall { a^n b^n c^n is, n>=0 } not context free.
But isn't the following a valid context free grammar that captures the above
S -> abcS
S -> null
Quoting Wikipedia:
"In formal language theory, a context-free grammar (CFG) is a formal grammar in which every production rule is of the form
V → w
where V is a single nonterminal symbol, and w is a string of terminals and/or nonterminals (w can be empty)."
A: S -> abcS produces something like that (abc)^n not a^n b^n c^n
A: You've written a production rule that generates abc^n, not a^n b^n c^n.
A: For n=2 shouldn't the production be: aabbcc? But wouldn't your example grammar produce abcabc?
A: Just in case you are wondering why it's not a context free grammar, here's a quick explanation:
A context free grammar is a grammar that can be recognized by a push-down automaton, which is a finite state automaton with the addition of a stack.
An example of a CFG is a^n b^n. If you think about it, we can push a token on our stack for every 'a' that we see and pop a token off the stack for every 'b' we see. We will fail at any point if we
- push a token after popping (a 'b' followed by an 'a')
- finish processing the string but we still have tokens on the stack (more 'a's than 'b's)
- try to pop an empty stack (more 'b's than 'a's)
If you think about how to recognize a^n b^n c^n with a push-down automaton, you will probably realize that is impossible after some playing around.
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Define "custom" integer-based type? I have a program that is interfacing with an external library that, among other things, has an unsigned 12-bit value packed in a larger struct.
This used to be 8 bits, so we simply marshaled it as a byte.
Now that it's 12 bits... I can use a ushort, but that opens up issues of (a) range checking and (b) marshaling.
Is there a simple way of implementing a constrained numeric type like this, where I don't have to override every assignment and comparison method?
A: Try this (this example shows a custom Int64 type)
public class MyCustomInt64 : CustomValueType<MyCustomInt64, Int64>
{
private MyCustomInt64(long value) : base(value) {}
public static implicit operator MyCustomInt64(long value) { return new MyCustomInt64(value); }
public static implicit operator long(MyCustomInt64 custom) { return custom._value; }
}
Implement what you like in the constructor to apply constriants.
Usage
MyCustomInt64 myInt = 27; //use as like any other value type
And here is the reusable base custom value type (add more operators if needed)
public class CustomValueType<TCustom, TValue>
{
protected readonly TValue _value;
public CustomValueType(TValue value)
{
_value = value;
}
public override string ToString()
{
return _value.ToString();
}
public static bool operator <(CustomValueType<TCustom, TValue> a, CustomValueType<TCustom, TValue> b)
{
return Comparer<TValue>.Default.Compare(a._value, b._value) < 0;
}
public static bool operator >(CustomValueType<TCustom, TValue> a, CustomValueType<TCustom, TValue> b)
{
return !(a < b);
}
public static bool operator <=(CustomValueType<TCustom, TValue> a, CustomValueType<TCustom, TValue> b)
{
return (a < b) || (a == b);
}
public static bool operator >=(CustomValueType<TCustom, TValue> a, CustomValueType<TCustom, TValue> b)
{
return (a > b) || (a == b);
}
public static bool operator ==(CustomValueType<TCustom, TValue> a, CustomValueType<TCustom, TValue> b)
{
return a.Equals((object)b);
}
public static bool operator !=(CustomValueType<TCustom, TValue> a, CustomValueType<TCustom, TValue> b)
{
return !(a == b);
}
public static TCustom operator +(CustomValueType<TCustom, TValue> a, CustomValueType<TCustom, TValue> b)
{
return (dynamic) a._value + b._value;
}
public static TCustom operator -(CustomValueType<TCustom, TValue> a, CustomValueType<TCustom, TValue> b)
{
return ((dynamic) a._value - b._value);
}
protected bool Equals(CustomValueType<TCustom, TValue> other)
{
return EqualityComparer<TValue>.Default.Equals(_value, other._value);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((CustomValueType<TCustom, TValue>)obj);
}
public override int GetHashCode()
{
return EqualityComparer<TValue>.Default.GetHashCode(_value);
}
}
A: You should create a struct that overrides the implicit conversion operator:
struct PackedValue {
private PackedValue(ushort val) {
if(val >= (1<<12)) throw new ArgumentOutOfRangeException("val");
this._value = val;
}
private ushort _value;
public static explicit operator PackedValue(ushort value) {
return new PackedValue(value);
}
public static implicit operator ushort(PackedValue me) {
return me._value;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Showing a pop up window when someone likes my fb page My client wants to display popup window with some coupon codes when some one clicks the like button of his shops facebook fan page. He is currently using the static fbml. I never worked with fb pages before. So know nothing about there api. I prefer javascript if possible. Or for anything else please explain step by step. Thank you in advance.
A: There is only one way to do this. With a landing page and it checks to see if the page is liked or not. You are going to have to create an application by going to http://developers.facebook.com/apps. Tis will allow you to create a new landing page. You will need a server to host it on or use the free cloud service that they now provide. The app will need to be created with one of the SDK's from https://developers.facebook.com/docs/sdks/. With PHP to check if someone likes the page you use code like
<?php
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {?>
Page Liked - Display HTML
<?php } else { ?>
Dont Like Page - display html
<?php }
}
?>
Now from here you can create any page to display what ever content you pretty much wish.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can you add an ID to dynamically generated href? how can you add an ID to a link generated like this?
function addElement(list, pos) {
var linkUrl = productList.products[pos].productLink;
var linkItem = document.createElement('a');
linkItem.setAttribute('href', linkUrl);
The previous code generates the following link
<a href="***/details.page?productId=3"><img src="***/topseller_main_en_1.png"></a>
A: Try this:
function addElement(list, pos) {
var linkUrl = productList.products[pos].productLink;
var linkItem = document.createElement("a");
if (linkItem){
linkItem.id = "foo";
linkItem.href = linkUrl;
}
}
You can also do this in jQuery like this:
function addElement(list, pos) {
var linkUrl = productList.products[pos].productLink;
var linkItem = document.createElement("a");
if (linkItem){
linkItem.attr({ id : "foo", href : linkItem });
}
}
Here's an even shorter way:
$("<a>").attr({ id : "foo", href : linkUrl });
Then just append it to an element in the document.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: move magento db to another server I have a Magento website, from the cpanel I created db backup and saved it to my pc, but I don't know how to import it to my new magento website.
P.S: the old hosting is now expired and I have only this db backup.
A: I've found exporting the Magento database through cpanel/phpmyadmin tends to have more problems with key conflicts than exporting through the command line. But since your hosting is expired we'll have to make do with what you have.
You'll need to edit the sql file inside the .sql.gz file (extract with any zipping program).
Add this line at the start of the sql file
SET FOREIGN_KEY_CHECKS = 0;
And then add
SET FOREIGN_KEY_CHECKS = 1;
Then try importing into an empty db again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: rails 3; activerecord; where; NOT EQUAL condition comparison between two columns in database Is there some way of comparing two columns in a database using where?
Say, I have two columns for user that tells:
*
*city_of_birth
*favourite_city
And I would like a list of users that have favourite_city that is different from city_of_birth.
I was hoping something like this would work.
@users = User.where(
:city_of_birth != :favourite_city
).all
Running this results in
undefined method `where' for nil:NilClass
There are similar questions asked about using conditional statements for where, but none of them were about conditional statements about the columns in database itself.
Thank you in advance for the help.
A: The error relates to the constant User not being defined, however to answer your question about the where method...
:city_of_birth != :favourite_city
This will always be true, so your actually calling where like this...
User.where(true)
This won't do much I'm afraid. I think you maybe getting this confused with the hash condition syntax which can be used. That also won't be of much use to you. You would need to use a string condition like this...
User.where('users.city_of_birth != users. favourite_city')
This is effectively just a snippet of SQL that will eventually be included in the final statement sent to the database.
A: This error is stating that User isn't defined -- either you have the wrong class name, or it's not being loaded into your environment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: sqlite statement not ok... why? - iphone I've been working on incorporating a sqlite db in my iPhone app. The database has been created, and I have successfully inserted elements into the database. Now, when I try to select from the db, my prepare statement is not meeting the requirement of SQLITE_OK. Here is the code where I create the database:
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS EXPENSES (id integer primary key autoincrement, unix_date integer, date_time text, purpose text, start_mile text, end_mile text, distance text, fees text, party_id integer)";
and here is the code I am using to extract the data:
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
printf("in getExpense\n");
//expenses = [[NSMutableArray alloc] init];
if (sqlite3_open(dbpath, &expenseDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM EXPENSES"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(expenseDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
printf("right before the while loop\n");
while (sqlite3_step(statement) == SQLITE_ROW)
{
printf("in the while loop\n");
VehicleExpense *expense = [[VehicleExpense alloc] init];
NSInteger *newTimeStamp = sqlite3_column_int(statement, 1);
NSString *newDate = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
NSString *newPurpose = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)];
NSString *newStart = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 4)];
NSString *newEnd = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 5)];
NSString *newDistance = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 6)];
NSString *newFees = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 7)];
NSInteger *newPartyId = sqlite3_column_int(statement, 8);
expense.unix_date = newTimeStamp;
expense.date = newDate;
expense.purpose = newPurpose;
expense.start_mile = newStart;
expense.end_mile = newEnd;
expense.distance = newDistance;
expense.fees = newFees;
expense.party_id = newPartyId;
[expenses addObject: expense];
printf("expense add");
[newDate release];
[newPurpose release];
[newStart release];
[newEnd release];
[newDistance release];
[newFees release];
[expense release];
expense_count++;
}
sqlite3_finalize(statement);
}else{
printf("the prepare statement is not ok\n");
}
sqlite3_close(expenseDB);
}else{
printf("couldn't open the db\n");
}
The second if-statement keeps failing for some reason?
Any ideas?
A: printf("the prepare statement is not ok\n"); is not really helpful at all. Try something like
NSLog(@"prepare failed (%s)", sqlite3_errmsg(expenseDB));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can not populate drop down list using hibernate query in spring mvc Here is my controller. In this I am using the reference data to send the List to my JSP page. Read the list into countryList which contains list of all country names populated using hibernate query
@SuppressWarnings("deprecation")
public class customerController extends SimpleFormController {
public customerController() {
setCommandClass(customer.class);
setCommandName("customer");
}
private customerDAO customerDAO;
public void setcustomerDAO(customerDAO customerDAO) {
this.customerDAO = customerDAO;
}
@Override
protected ModelAndView onSubmit(Object command) throws Exception {
customer customer = (customer) command;
customerDAO.savecustomer(customer);
return new ModelAndView("customerSuccess");
}
@Override
protected Map referenceData(HttpServletRequest request) throws Exception {
Map referenceData = new HashMap();
List countryList = customerDAO.listCountries();
referenceData.put("country", countryList);
return referenceData;
}
public ModelAndView redirect(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelMap modelMap = new ModelMap();
return new ModelAndView("customer", modelMap);
}
}
Here is my DAO implementation:
public class customerDAOImpl implements customerDAO {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
@Override
public void savecustomer(customer customer) {
hibernateTemplate.saveOrUpdate(customer);
}
@Override
@SuppressWarnings("unchecked")
public List<customer> listcustomer() {
return hibernateTemplate.find("from customer");
}
@Override
@SuppressWarnings("unchecked")
public List<countries> listCountries() {
return hibernateTemplate.find("from customer.countries");
}
}
Here is my JSP code:
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<form:form commandName="customer" name="customer" method="post">
<tr>
<td align="right" class="para">Country:</td>
<td align="left"><span id="spryselect2">
<form:select path="country" id="country">
<form:options items="${country}" itemValue="country_id" itemLabel="name" />
</form:select>
<span class="selectRequiredMsg">Please select country.</span></span></td>
</tr>
But nothing is getting populated into the drop down.
A: Name the list of countries something representing multiple countries, like, say, "countries".
There's also a customer country property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ruby version mismatch when deploying war over tomcat I am using Rvm and have install jruby-1.6.4 (with ruby 1.9.2)
i use warbler to create the war file and deploy it over tomcat-6.0.4
the problem is while i run the application the tomcat logs shows ruby version used as 1.8.7
I checked the version of ruby thru rvm list and it shows the right version (1.8.7)
When i downgrade teh jruby to use 1.8.7 (by using JRUBY_OPTS=--1.8.7 the application works like charm
any idea on how to ensure that ruby version 1.9.2 is used by tomcat
Vivek
A: Try setting the Java property jruby.compat.version to 1.9 in Tomcat.
A: Inside warble.rb (created when/if you call >warble config)
Warbler::Config.new do |config|
# stuff before
config.webxml.jruby.compat.version = "1.9"
# stuff after
end
This config (and a lot more) will actually already be present, yet commented out when the warble.rb file is generated.
http://caldersphere.rubyforge.org/warbler/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: if / else simplification to ternary operator Can this be done for the code below. Problem I see is that there are two statements in the else clause and I couldn't figure out a way to fit in the echo...I need to return a 1 or a 0. Perhaps someone knows a trick?
function empty_user($c)
{
if((int)!in_array('',$this->a,TRUE))
{
return 1;
}
else
{
echo $c;
return 0;
}
}
A: you generally shouldn't use ternary operators to determine execution order, but also, no, you won't be able to convert the if/else you've got there.
A: You can't use a ternary operator if you want more than one operation in either block, but the question is why would you want to? It is much clearer and easier to update if you have full blocks that you can continue to add code to.
A: No ternary =/. Although you can simplify this a lot because once the function returns, it stops interpreting the function anyway, so you can eliminate the else.
function empty_user($c) {
if ((int)!in_array('',$this->a,TRUE)) return 1;
echo $c;
return 0;
}
A: in_array returns a bool which is perfect for an if statement - there is no need to cast it to an int.
function empty_user($c)
{
if (in_array('',$this->a,TRUE))
{
echo $c;
return 0;
}
return 1;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting the "like" button to appear on ALL of my web site's pages I have been able to ge the "like" button to appear on my home page, but cannot get it to show up on ALL my pages on the site. I have tried copying & pasting this code:
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo urlencode('http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']) ?>&layout=standard&show_faces=true&width=450&action=like&colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:450px; height:px"></iframe>
I found this code here:
http://www.greenlabeldesign.com.au/2010/04/inserting-the-facebook-like-feature-on-your-website/
Any suggestions on how to implement this feature?
My web site is www.connieskids.com
A: You need to include facebooks javascript file on all pages:
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error with logging users on facebook I have an app on facebook, and I log the users on my database (a script checks if the user is already on the db, if not, it adds him). The users table has only one field - "userid", which is a primary key.
The script that checks if the user is already registered in the db is:
$selectuser = $db->query("SELECT * FROM `predictorusers` WHERE `userid`='$user'");
if ($db->countRows($selectuser) == 0)
$db->query("INSERT INTO `predictorusers` (`userid`) VALUES ('$user')");
Now to the problem: I don't know why, but with a specific user (for most users if works just fine) it inserts the id 2147483647 (which doesn't even exist on facebook!!), and when he enters the app again, he gets the following message:
Duplicate entry '2147483647' for key 1
Like it's trying to add it again even though it already exists in the db!!
Can anyone figure it out?
A: It is regarding the definition of the field in MySQL. I am sure your field is set to be of INT type.
Duplicate entry '2147483647' for key 1 == maximum number for this type in MySQL.
So when a FB ID is larger than this, MySQL will set this as the maximum permitted, thus giving you duplicates when the ID is large, as the entry must be unique.
Change the field to VARCHAR(255) and your problem will be resolved.
ALTER predictorusers ALTER COLUMN userid VARCHAR(255) NULL
A: use BIGINT (20) instead as the datatype. The FB IDs are too big.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java JFrame / Canvas doesn't repaint A mouse listener calls repaint() and I can see that it does actually go past the drawing part because I see globalcounter incremented in the output of System.out.println(). On the screen, however, I don't see any change until I minimize the window and maximize again, resize it, or move it out of the visible screen area and back in. Obviously I'd like it to update without my intervention.
class GUI extends javax.swing.JFrame {
int globalcounter=0;
class MyCanvas extends Canvas {
@Override
public void paint(Graphics g) {
globalcounter++;
g.drawString(globalcounter,100,100);
System.out.println(globalcounter);
}
}
}
(Originally I was loading an image from a file that got constantly updated (webcam) and painting it on the canvas. When I dragged it partly out of the visible screen area and back in, the part that has been 'outside' was refreshed, the rest not.)
revalidate() instead of repaint() didn't change anything.
I know this post is a duplicate to Java repaint not working correctly but when I posted it there it was deleted.
A: Why are you adding an AWT component, Canvas, to a Swing component, JFrame? You should stick with Swing components only. And also do you know the size of your MyCanvas, and how have you added it to the JFrame as you don't show this code.
Consider
*
*using a JPanel instead of a Canvas object,
*drawing in its paintComponent method,
*showing us an sscce if you're still stuck.
*And also, if all you're doing is drawing text, use a JLabel rather than drawing in paint/paintComponent, and change its text with its setText(...) method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Email address links for user I have a database system to keep track of students. This is used by a few other people in the office who are not tech savvy.
I need to be able to email about 120 students at one time. Given the character limit on URLs/browsers/what have you, using mailto is not an option; the character count is 2878.
Using a PHP form would make the most sense, but my unsavvy coworkers need to send email from Outlook. Mainly so their sent mail reflects every message they've sent out.
Any ideas?
A: If the set of recipients is reasonably stable, the standard tool for this is a mailing list. A closed mailing list can be set up on your mail server, or you can use something like Google Groups to create a closed list where people can enroll and unsubscribe as they see fit.
A: I think you could make it in php sending two emails:
*
*One email to the receiver.
*One email to the sender
You just need a rule in every Outlook that put the second email on the sent folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getElementsByClassName returns [] instead of asynchronous appended node (I ask my question again after the first one was terribly formulated)
I face the following problem:
<div class="testA" id="test1"></div>
The above written element is predefined. I now load a xml tree via XMLHttpRequest & Co. delivering the following response:
<response>
<div class="colorSelector" id="0-0">
<div class="gbSelector" id="1-0">
<table style="none" id="2-0"></table>
</div>
</div>
</response>
I now append the first div using
request.responseXML.getElementsByTagName("response")[0]
.getElementsByTagName("div")[0]
into the predefined div
<div class="testA" id="test1">
The final document looks like this (checked using development tools):
<div class="testA" id="test1">
<div class="colorSelector" id="0-0">
<div class="gbSelector" id="1-0">
<table style="none" id="2-0"></table>
</div>
</div>
</div>
When I now try to get the element <div class="colorSelector" id="0-0"> using getElementById("0-0") I get the expected result.
But using getElementsByClassName("colorSelector") returns [].
Did I miss something? Is it probably a leftover of the fact the nodes were of type Element and not HTMLElement?
A: colorSelector is commented out. JavaScript only works within the DOM, and commented out portions aren't in the DOM.
A: Since you said that your getElementById("0-0") is successful, then clearly you don't actually have the nodes commented out.
I'm guessing you're doing:
document.getElementById("0-0").getElementsByClassName('colorSelector');
...which will not work because the element selected by ID does not have any descendants with that class.
Since you show HTML comments in the markup, I'd also wonder if you have some different element on the page with the ID "0-0". Take a look for that.
If your nodes are actually commented out, you'll need to first select the comment, and replace it with the markup contained inside:
var container = document.getElementById('test1'),
comment = container.firstChild;
while( comment && comment.nodeType !== 8 ) {
comment = comment.nextSibling;
}
if( comment ) {
container.innerHTML = comment.nodeValue;
}
...resulting in:
<div class="testA" id="test1">
<div class="colorSelector" id="0-0">
<div class="gbSelector" id="1-0">
<table style="none" id="2-0"></table>
</div>
</div>
</div>
...but there again, this doesn't seem likely since your getElementsById does work.
A: <!--<div class="colorSelector" id="0-0">
<div class="gbSelector" id="1-0">
<table style="none" id="2-0"></table>
</div>
</div>-->
The above code is gray for a reason: it's a comment. Comments aren't parsed by the browser at all and have no influence on the page whatsoever.
You'll have to parse the HTML, read the comments, and make a new DOM object with the contents of the comment.
A: Please describe what you are doing with the returned results. There is a significant difference between a nodeList and a node, nodeLists are LIVE.
So if you assign a nodeList returned by getElementsByClassName() (or similar) to a variable, this variable will change when you remove the nodes inside the nodeList from the DOM.
A:
I now append the first div
How do you do that? What you have in the responseXML are XML elements, and not HTML elements.
*
*You shouldn't be able to appendChild them into a non-XHTML HTML document;
*actually you shouldn't be able to appendChild them into another document at all, you're supposed to use importNode to get elements from one document to another, otherwise you should get WRONG_DOCUMENT_ERR;
*even if you managed to insert them into an HTML due to browser laxness, they're still XML elements and are not semantically HTML elements. Consequently there is nothing special about the class attributes; just having that name doesn't make the attribute actually represent a class. getElementsByClassName won't return elements just because they have attributes with the name class; they have to be elements whose language definition associates the attributes with the concept of classness (which in general means HTML, XHTML or SVG).
(The same should be true of the id attributes; just having an attribute called id doesn't make it conceptually an ID. So getElementById shouldn't be working. There is a way to associate arbitrary XML attributes with ID-ness, which you don't get with class-ness, by using an <!ATTLIST declaration in the doctype. Not usually worth bothering with though. Also xml:id is a special case, in implementations that support XML ID.)
You could potentially make it work if you were using a native-XHTML page by putting suitable xmlns attributes on the content to make it actual-XHTML and not just arbitrary-XML, and then using importNode. But in general this isn't worth it; it tends to be simpler to return HTML markup strings (typically in JSON), or raw XML data from which the client-side script can construct the HTML elements itself.
A: Here's a way to do it for Firefox, Opera, Chrome and Safari. Basically, you just do div.innerHTML = div.innerHTML to reinterpret its content as HTML, which will make that class attribute from the XML file be treated as an HTML class name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script>
window.addEventListener("DOMContentLoaded", function() {
var div = document.getElementsByTagName("div")[0];
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var doc = this.responseXML;
div.appendChild(document.importNode(doc.getElementsByTagName("response")[0].getElementsByTagName("div")[0], true));
div.innerHTML = div.innerHTML;
alert(document.getElementsByClassName("colorSelector").length);
}
};
req.open("GET", "div.xml");
req.send();
}, false);
</script>
</head>
<body>
<div class="testA"></div>
</body>
</html>
Remove the this.status === 200 if you're testing locally in browsers that support xhr locally.
The importNode() function doesn't seem to work in IE (9 for example). I get a vague "interface not supported" error.
You could also do it this way:
var doc = this.responseXML;
var markup = (new XMLSerializer()).serializeToString(doc.getElementsByTagName("response")[0].getElementsByTagName("div")[0]);
div.innerHTML = markup;
as long as the markup is HTML-friendly as far as end tags for empty elements are concerned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SQL INNER JOIN on Text Columns I have two tables (equipment & software) that I want to do an INNER JOIN on. They both have a field called EQCN. It is a text field. I get the following error:
The data types text and text are incompatible in the equal to operator.
There has to be a way around this.
A: Change the data types for these columns to varchar(max).
From Microsoft:
ntext, text, and image data types will be removed in a future version
of Microsoft SQL Server. Avoid using these data types in new
development work, and plan to modify applications that currently use
them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
A: Although this is odd, Microsoft suggests doing an indirect comparison on a text or ntext using something like SUBSTRING. Example:
SELECT *
FROM t1
JOIN t2 ON SUBSTRING(t1.textcolumn, 1, 20) = SUBSTRING(t2.textcolumn, 1, 20)
This of course raises a whole other set of issues like, what if the first # of characters are identical, etc. I would suggest going the route of changing the type if you can first, rather than take this advice.
Source
A: Doing a join on a TEXT field would be VERY slow, even if it did work. Perhaps use:
CONVERT(varchar, myColumnName) = 'my value'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Messaging Script - Text isn't uploading when queried I have a simple messaging script that allows the Admin to send pre-defined messages to the users.
The two fields that seem to prevent the query from completion are the subject and body - the formats within the database are both 'text' with default set to NULL. Correlation has been set to latin1_swedish_ci for some reason.
I know these are the error's as if I make them NULL when inserting them into the database, the entire query is successful.
The query is triggered on a button press (The fault isn't here as I have queries above that work perfectly).
The two variables are defined as such:
$subject = "You have a new message!";
$body = "<a href='?page=update'>click here to see it.</a>";
With the mysql query following:
mysql_query("INSERT INTO message VALUES(NULL, '$user_id', '$list_id', $subject , $body, '0', '$query_date_user', '1')");
I have seen a few tutorials on messaging scripts and they all appear to not have any other factors that i have missed out.
Any help would be hugely appreciated.
Many thanks in advance.
A: Put quotes around $subject and $body
mysql_query("INSERT INTO message VALUES(NULL, '$user_id', '$list_id', '$subject' , '$body', '0', '$query_date_user', '1')");
Thanks Marc B.! Indeed he needs to escape the single quotes in $body too.
A: You're causing a syntax error with the single quotes (') in your $body variable. Since you don't have any error handling on the query call, you will not see the messages mysql would be screaming at you.
Your code should be:
$subject = mysql_real_escape_string("You have a new message!");
$body = mysql_real_escape_string("<a href='?page=update'>click here to see it.</a>");
$sql = "INSERT INTO message VALUES(NULL, '$user_id', '$list_id', '$subject' , '$body', '0', '$query_date_user', '1')";
mysql_query($sql) or die(mysql_error());
Note the quotes around the variables inside the query string as well. You cannot insert a raw string into an SQL query and expect it to work.
BIG NOTE: adding or die(mysql_error()) during your development process helps catch these kinds of errors. If'd you been doing this from the get-go, you'd have seen immediately that there's a problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Installing Pygame and Pymunk on Mac OS X 10.6 I have not been able to install Pymunk and Pygame for the same version of python. I have tried binaries, source installs, fink, and Macports, for system python, python 2.6, and python 2.7, with 32 and 64 bit versions.
In some cases the pymunk unit tests cause a segmentation fault, in some cases I get symptoms similar to Issue 42, and in some I cannot import pymunk because libchipmunk.dylib is an incompatible architecture.
When I can install pymunk, I cannot install or compile pygame with extended image (pygame.image.get_extended() == 0) or font support, which largely defeats the purpose of using pygame and pymunk together. On some versions of python, such as 2.7 64 bit, I get
building 'pygame.imageext' extension
gcc-4.0 -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch ppc -arch x86_64 -g -O2 -DNDEBUG -g -O3 -Ddarwin -I/Library/Frameworks/SDL.framework/Versions/Current/Headers -I/Library/Frameworks/SDL_image.framework/Versions/Current/Headers -I/usr/local/include -I/usr/local/include -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/imageext.c -o build/temp.macosx-10.5-fat3-2.7/src/imageext.o
/usr/libexec/gcc/powerpc-apple-darwin10/4.0.1/as: assembler (/usr/bin/../libexec/gcc/darwin/ppc/as or /usr/bin/../local/libexec/gcc/darwin/ppc/as) for architecture ppc not installed
Installed assemblers are:
/usr/bin/../libexec/gcc/darwin/x86_64/as for architecture x86_64
/usr/bin/../libexec/gcc/darwin/i386/as for architecture i386
lipo: can't open input file: /var/tmp//ccuP0D3r.out (No such file or directory)
error: command 'gcc-4.0' failed with exit status 1
When importing pygame, I sometimes get:
from pygame.base import *
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so, 2): no suitable image found. Did find:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: no matching architecture in universal wrapper
I haven't had any issues on Ubuntu or Windows, so I think the problem is OS X-specific.
I am somewhat new to makefiles and compile flags, and I have been trying to set up these two modules for three days, so if someone could provide me with a detailed installation procedure that actually works for them, including the relevant .bash_profile and environment variables, I would be extremely grateful.
Edit: I reinstalled python, pygame, and chipmunk+pymunk, and this is the error I am getting with Python 2.7 (32 bit):
$ python2.7-32 flipper.py
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
2011-10-03 19:03:08.862 Python[3683:60f] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
Traceback (most recent call last):
File "flipper.py", line 35, in <module>
space.add_static(static_lines)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 288, in add_static
self.add_static(oo)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 285, in add_static
self._add_static_shape(o)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 327, in _add_static_shape
assert static_shape._hashid_private not in self._static_shapes, "shape already added to space"
AssertionError: shape already added to space
Edit 2: Despite changing the setup.py file to only link for 32-bit, I am getting some odd behavior:
$ sudo python setup.py build_chipmunk
running build_chipmunk
compiling chipmunk...
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/chipmunk.c -o chipmunk_src/chipmunk.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpArbiter.c -o chipmunk_src/cpArbiter.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpArray.c -o chipmunk_src/cpArray.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBB.c -o chipmunk_src/cpBB.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBBTree.c -o chipmunk_src/cpBBTree.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBody.c -o chipmunk_src/cpBody.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpCollision.c -o chipmunk_src/cpCollision.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpHashSet.c -o chipmunk_src/cpHashSet.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpPolyShape.c -o chipmunk_src/cpPolyShape.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpShape.c -o chipmunk_src/cpShape.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpace.c -o chipmunk_src/cpSpace.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceComponent.c -o chipmunk_src/cpSpaceComponent.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceHash.c -o chipmunk_src/cpSpaceHash.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceQuery.c -o chipmunk_src/cpSpaceQuery.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceStep.c -o chipmunk_src/cpSpaceStep.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpatialIndex.c -o chipmunk_src/cpSpatialIndex.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSweep1D.c -o chipmunk_src/cpSweep1D.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpVect.c -o chipmunk_src/cpVect.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpConstraint.c -o chipmunk_src/constraints/cpConstraint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpDampedRotarySpring.c -o chipmunk_src/constraints/cpDampedRotarySpring.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpDampedSpring.c -o chipmunk_src/constraints/cpDampedSpring.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpGearJoint.c -o chipmunk_src/constraints/cpGearJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpGrooveJoint.c -o chipmunk_src/constraints/cpGrooveJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpPinJoint.c -o chipmunk_src/constraints/cpPinJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpPivotJoint.c -o chipmunk_src/constraints/cpPivotJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpRatchetJoint.c -o chipmunk_src/constraints/cpRatchetJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpRotaryLimitJoint.c -o chipmunk_src/constraints/cpRotaryLimitJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpSimpleMotor.c -o chipmunk_src/constraints/cpSimpleMotor.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpSlideJoint.c -o chipmunk_src/constraints/cpSlideJoint.o
cc -dynamiclib -arch i386 chipmunk_src/chipmunk.o chipmunk_src/cpArbiter.o chipmunk_src/cpArray.o chipmunk_src/cpBB.o chipmunk_src/cpBBTree.o chipmunk_src/cpBody.o chipmunk_src/cpCollision.o chipmunk_src/cpHashSet.o chipmunk_src/cpPolyShape.o chipmunk_src/cpShape.o chipmunk_src/cpSpace.o chipmunk_src/cpSpaceComponent.o chipmunk_src/cpSpaceHash.o chipmunk_src/cpSpaceQuery.o chipmunk_src/cpSpaceStep.o chipmunk_src/cpSpatialIndex.o chipmunk_src/cpSweep1D.o chipmunk_src/cpVect.o chipmunk_src/constraints/cpConstraint.o chipmunk_src/constraints/cpDampedRotarySpring.o chipmunk_src/constraints/cpDampedSpring.o chipmunk_src/constraints/cpGearJoint.o chipmunk_src/constraints/cpGrooveJoint.o chipmunk_src/constraints/cpPinJoint.o chipmunk_src/constraints/cpPivotJoint.o chipmunk_src/constraints/cpRatchetJoint.o chipmunk_src/constraints/cpRotaryLimitJoint.o chipmunk_src/constraints/cpSimpleMotor.o chipmunk_src/constraints/cpSlideJoint.o -o pymunk/libchipmunk.dylib
$ python2.7-32
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymunk
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
>>> s = pymunk.Space()
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
>>> c1 = pymunk.Circle(s.static_body, 1)
>>> s.add(c1)
>>> c2 = pymunk.Circle(s.static_body, 2)
>>> s.add(c2) #No error!
$ sudo python setup.py install
$ python2.7-32 unittests.py
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
testing pymunk version 2.0.0
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
FFFFSegmentation fault
$ python2.7-32 flipper.py
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
2011-10-04 13:49:45.653 Python[6430:60f] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
Traceback (most recent call last):
File "flipper.py", line 35, in <module>
space.add_static(static_lines)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 288, in add_static
self.add_static(oo)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 285, in add_static
self._add_static_shape(o)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 327, in _add_static_shape
assert static_shape._hashid_private not in self._static_shapes, "shape already added to space"
AssertionError: shape already added to space
Edit 3: Chipmunk now built and linked for x86, but I am getting the same errors:
$sudo python2.7-32 setup.py build_chipmunk
running build_chipmunk
compiling chipmunk...
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/chipmunk.c -o chipmunk_src/chipmunk.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpArbiter.c -o chipmunk_src/cpArbiter.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpArray.c -o chipmunk_src/cpArray.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBB.c -o chipmunk_src/cpBB.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBBTree.c -o chipmunk_src/cpBBTree.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBody.c -o chipmunk_src/cpBody.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpCollision.c -o chipmunk_src/cpCollision.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpHashSet.c -o chipmunk_src/cpHashSet.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpPolyShape.c -o chipmunk_src/cpPolyShape.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpShape.c -o chipmunk_src/cpShape.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpace.c -o chipmunk_src/cpSpace.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceComponent.c -o chipmunk_src/cpSpaceComponent.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceHash.c -o chipmunk_src/cpSpaceHash.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceQuery.c -o chipmunk_src/cpSpaceQuery.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceStep.c -o chipmunk_src/cpSpaceStep.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpatialIndex.c -o chipmunk_src/cpSpatialIndex.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSweep1D.c -o chipmunk_src/cpSweep1D.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpVect.c -o chipmunk_src/cpVect.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpConstraint.c -o chipmunk_src/constraints/cpConstraint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpDampedRotarySpring.c -o chipmunk_src/constraints/cpDampedRotarySpring.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpDampedSpring.c -o chipmunk_src/constraints/cpDampedSpring.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpGearJoint.c -o chipmunk_src/constraints/cpGearJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpGrooveJoint.c -o chipmunk_src/constraints/cpGrooveJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpPinJoint.c -o chipmunk_src/constraints/cpPinJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpPivotJoint.c -o chipmunk_src/constraints/cpPivotJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpRatchetJoint.c -o chipmunk_src/constraints/cpRatchetJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpRotaryLimitJoint.c -o chipmunk_src/constraints/cpRotaryLimitJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpSimpleMotor.c -o chipmunk_src/constraints/cpSimpleMotor.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpSlideJoint.c -o chipmunk_src/constraints/cpSlideJoint.o
cc -dynamiclib -arch i386 chipmunk_src/chipmunk.o chipmunk_src/cpArbiter.o chipmunk_src/cpArray.o chipmunk_src/cpBB.o chipmunk_src/cpBBTree.o chipmunk_src/cpBody.o chipmunk_src/cpCollision.o chipmunk_src/cpHashSet.o chipmunk_src/cpPolyShape.o chipmunk_src/cpShape.o chipmunk_src/cpSpace.o chipmunk_src/cpSpaceComponent.o chipmunk_src/cpSpaceHash.o chipmunk_src/cpSpaceQuery.o chipmunk_src/cpSpaceStep.o chipmunk_src/cpSpatialIndex.o chipmunk_src/cpSweep1D.o chipmunk_src/cpVect.o chipmunk_src/constraints/cpConstraint.o chipmunk_src/constraints/cpDampedRotarySpring.o chipmunk_src/constraints/cpDampedSpring.o chipmunk_src/constraints/cpGearJoint.o chipmunk_src/constraints/cpGrooveJoint.o chipmunk_src/constraints/cpPinJoint.o chipmunk_src/constraints/cpPivotJoint.o chipmunk_src/constraints/cpRatchetJoint.o chipmunk_src/constraints/cpRotaryLimitJoint.o chipmunk_src/constraints/cpSimpleMotor.o chipmunk_src/constraints/cpSlideJoint.o -o pymunk/libchipmunk.dylib
$ sudo python2.7-32 setup.py install
running install
running build
running build_py
copying pymunk/libchipmunk.dylib -> build/lib/pymunk
running install_lib
copying build/lib/pymunk/libchipmunk.dylib -> /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk
running install_egg_info
Removing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk-2.0.0-py2.7.egg-info
Writing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk-2.0.0-py2.7.egg-info
$ python2.7-32 flipper.py
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
2011-10-05 01:15:15.972 Python[3183:60f] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
Traceback (most recent call last):
File "flipper.py", line 35, in <module>
space.add_static(static_lines)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 288, in add_static
self.add_static(oo)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 285, in add_static
self._add_static_shape(o)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 327, in _add_static_shape
assert static_shape._hashid_private not in self._static_shapes, "shape already added to space"
$ python2.7-32 unittests.py
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
testing pymunk version 2.0.0
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
FFFFSegmentation fault
Edit 4: Verification of versions and executable types:
$ file /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib: Mach-O dynamically linked shared library i386
$ file "$( "$(which python2.7-32)" -c "import sys;print(sys.executable)" )"
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: Mach-O universal binary with 2 architectures
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python (for architecture i386): Mach-O executable i386
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python (for architecture x86_64): Mach-O 64-bit executable x86_64
$ python2.7-32 -c "import sys;print('%x'%sys.maxint)"
7fffffff
Thanks in advance,
Julian Ceipek
A: (I am the developer of pymunk)
I would suggest you start by getting pygame working. When you have pygame working on a specific python version, then move over and try to get pymunk working on that same version.
When you try with pymunk, the best way to get it working is
*
*Get version directly from svn (tags/pymunk-2.0.0 contains the release version). Unfortunately the zip source distribution of 2.0.0 does not contain the chipmunk sources you need for compiling.
*When you have pymunk including the sources, try compiling chipmunk with build_chipmunk (make sure you do this step with the same python version as you want to run it with)
python setup.py build_chipmunk
*Hopefully you should now be able to run pymunk.
If this doesnt work its a bit more tricky.
If you're up for some experimenting you can try to modify the setup script to only build chipmunk in 32bit mode (by default it embeds both 32 and 64 bit versions into the dylib file on OSX). That way you will be sure it loads the 32 bit version.
In the setup.py file, http://code.google.com/p/pymunk/source/browse/tags/pymunk-2.0.0/setup.py
edit line 53 from:
compiler_preargs += ['-arch', 'i386', '-arch', 'x86_64']
into
compiler_preargs += ['-arch', 'i386']
and you will also need to edit line 66 from:
compiler.set_executable('linker_so', ['cc', '-dynamiclib', '-arch', 'i386', '-arch', 'x86_64'])
into
compiler.set_executable('linker_so', ['cc', '-dynamiclib', '-arch', 'i386'])
Then run
>python2.7-32 setup.py build_chipmunk
To test if it works you dont need to install the whole thing, you can try directly from the same folder:
>python
>>> import pymunk
>>> s = pymunk.Space()
>>> c1 = pymunk.Circle(s.static_body, 1)
>>> s.add(c1)
>>> c2 - pymunk.Cricle(s.static_body, 2)
>>> s.add(c2) #this line will fail if it still doesnt work
If you still have problem, then the output of this would be helpful (basically Im almost out of ideas here..)
First, run the file tool on the dylib file:
> file /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib
Then you can also verify what python is using:
> file "$( "$(which python2.7-32)" -c "import sys;print(sys.executable)" )"
And finally verify that the python version is indeed 32bit
> python2.7-32 -c "import sys;print('%x'%sys.maxint)"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ruby on Rails: How to have ActiveRecord callback load a shared variable between callbacks I have a couple of before_save and after_save callbacks that need to share an instance of an object between each other in a Ruby on Rails project. I thought that adding an additional method called load_object where I load the object into an instance variable would do the trick. This worked fine for the before_save validations, but the object didn't persist to the after_save chain of methods. Is there anyway to make sure it's around for both sets while keeping my code DRY?
A: that's strange, the callbacks run on the same instance, and any instance variable should still be available (though not persisted). but you can always use an around_save callback
around_save :do_something
def do_something
#beforesave things
yield
#aftersave things
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is wrong with these @font-face fonts in IE9? For some reason, when I view this page in IE9, all of the @font-face fonts look way smaller than they should, and maybe like a different typeface too. As far as I can tell, everything about my syntax should be cooperating with IE9. Others have had trouble replicating the issue, so maybe it is something in my Windows font settings? Either way, if you want to try to replicate what I am seeing, I am running IE9 on Windows 7 64bit.
EDIT: I'm not sure if this is a problem with the page, or a problem with my browser. Either way, I need to get it fixed.
A: @font-face {
font-family: 'MyWebFont';
src: url('webfont.eot'); /* IE9 Compat Modes */
src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('webfont.woff') format('woff'), /* Modern Browsers */
url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */
url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}
Usage Example:
@font-face {
font-family: MyFont;
src: url(http://mysite/fonts/MyFont.ttf)
format("embedded-opentype");
}
p {font-family: MyFont, serif;
}
A: Looks the same for me in IE9 as other browsers, none are using the embedded font due to its different name (HelveticaMD vs the actual name in use in the CSS, Helvetica.)
It looks like your “wrong” screenshot is of a browser trying to actually use the embedded font, whereas the “right” screenshot is just the default font. If that's what you want, just get rid of the font embedding stuff.
A: .woff solves the problem in IE9. I've used .eot for chrome & firefox. And .woff for IE9. Now the 3 browsers are working fine and showing the same results. Following is the code in CSS. @font-face {font-family: 'cert_fonts'; src: url('../fonts/GoudyTrajan.eot') format('eot'); src: url('../fonts/GoudyTrajan.woff') format('woff'); font-weight: normal; font-style: normal;}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Play Sound file without importing winmm.dll or microsoft.visualbasic.dll I am writing a program using Delphi prism. The goal is to be able run on windows and linux (mono) from the same project. So, at this point I need to have a way of playing a sound file for windows and linux(mono) without having to import winmm.dll or microsoft.visualbasic.dll.
Since I need this to work on mono also, I don't want to use visualbasic.dll. In the past, it gave me all kinds of issues.
Are there ways to play sound file without using these dll files?
UPDATE
No matter how the soundplayer is instantiated and used, it always works fine under windows OS, whereas on Linux under mono it sometimes plays and other times it just won't play at all.
First Version:
var thesound := new SoundPlayer;
if Environment.OSVersion.Platform = Environment.OSVersion.Platform.Unix then
thesound.SoundLocation := '/sounds/Alarms.wav'
else
thesound.SoundLocation:='\sounds\Alarms.wav';
thesound.Load;
thesound.PlayLooping;
Second Version
var sp := new SoundPlayer(new FileStream("/sounds/Alarms.wav", FileMode.Open, FileAccess.Read, FileShare.Read));
sp.PlayLooping;
A: You can use System.Media.SoundPlayer. This is implemented by Mono.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using a specific Firefox profile in Selenium WebDriver in C# I am trying to use a profile I already have set up for firefox with selenium 2 but there is no documentation for C#. The code I have attempted is as follows:
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile(profileName);
driver = new FirefoxDriver(profile);
Code that I have seen that is comparible in Java uses ProfilesIni instead of FirefoxProfileManager, but that is not available in C#. When setting up the driver in this way the selenium profile used has all the default settings instead of the settings specified in the profile I am trying to point to.
I am not sure that I am using the correct methods to retrieve the profile, but if anyone has used Selenium 2 with C#, any information would be helpful.
A: We use such method to load default firefox profile (you can create custom profile and load it):
private IWebDriver driver;
string pathToCurrentUserProfiles = Environment.ExpandEnvironmentVariables("%APPDATA%") + @"\Mozilla\Firefox\Profiles"; // Path to profile
string[] pathsToProfiles = Directory.GetDirectories(pathToCurrentUserProfiles, "*.default", SearchOption.TopDirectoryOnly);
if (pathsToProfiles.Length != 0)
{
FirefoxProfile profile = new FirefoxProfile(pathsToProfiles[0]);
profile.SetPreference("browser.tabs.loadInBackground", false); // set preferences you need
driver = new FirefoxDriver(new FirefoxBinary(), profile, serverTimeout);
}
else
{
driver = new FirefoxDriver();
}
A: We had the same problem that the profile wouldn't load. The problem is in FirefoxProfile (line 137). It only looks for user.js and the profile from Firefox is actually prefs.js
137>> File prefsInModel = new File(model, "user.js");
Hack solution: rename prefs.js --> user.js
A: The following worked for me. I had to specifically set the "webdriver.firefox.profile" preference in order to get it to work.
var allProfiles = new FirefoxProfileManager();
if (!allProfiles.ExistingProfiles.Contains("SeleniumUser"))
{
throw new Exception("SeleniumUser firefox profile does not exist, please create it first.");
}
var profile = allProfiles.GetProfile("SeleniumUser");
profile.SetPreference("webdriver.firefox.profile", "SeleniumUser");
WebDriver = new FirefoxDriver(profile);
A: I have the same issue, it is not a duplicate.
I am using the following which works
private IWebDriver Driver;
[Setup]
public void SetupTest()
{
string path = @"C:\Users\username\AppData\Local\Mozilla\Firefox\Profiles\myi5go1k.default";
FirefoxProfile ffprofile = new FirefoxProfile(path);
Driver = new FirefoxDriver(ffprofile);
}
A: After using the aforementioned answers I had no result, so I tried the following alternate way:
First, create the desired profile by typing about:profiles on Firefox address bar.
Second, the C# code. Note that the profile name we created on first step is passed as an argument.
public IWebDriver driver { get; set; }
public Selenium(String nombrePefil)
{
if (this.driver == null)
{
FirefoxOptions options = new FirefoxOptions();
options.AddArgument("--profile " + nombrePefil);
this.driver = new FirefoxDriver(options);
}
}
A: I also encountered the same issue, and after searching and trying many different combinations I was able to get Selenium to load a specific profile when using the RemoteWebDriver.
Grid configuration
I launch the HUB using a batch file containing the following
"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar C:\Downloads\Selenium\selenium-server-standalone-2.20.0.jar -role hub -maxSession 50 -Dwebdriver.firefox.profile=Selenium
I launch one or more nodes using a batch file containing the following (each node has a unique port number):
"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar selenium-server-standalone-2.20.0.jar -role node -hub http://127.0.0.1:4444/grid/register -browser browserName=firefox,platform=WINDOWS,version=11.0,maxInstances=2 -maxSession 2 -port 5555 -Dwebdriver.firefox.profile=Selenium
The key here is the last part of those commands, which needs to match the name of the custom profile you have created.
Code to create WebDriver instance
private readonly Uri _remoteWebDriverDefaultUri = new Uri("http://localhost:4444/wd/hub/");
private IWebDriver CreateFireFoxWebDriver(Uri remoteWebDriverUri)
{
var desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.SetCapability(CapabilityType.BrowserName, "firefox");
desiredCapabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
desiredCapabilities.SetCapability(CapabilityType.Version, "11.0");
var drv = new RemoteWebDriver(remoteWebDriverUri ?? _remoteWebDriverDefaultUri, desiredCapabilities);
return drv;
}
NOTE: The capabilities need to match those of the nodes you are running in the grid.
You can then call this method passing in the Uri of the hub, or null to default to localhost.
A: Seems fine with the Roaming profile rather than the local profile.
string path = @"C:\Users\username\AppData\Roaming\Mozilla\Firefox\Profiles\myi5go1k.default";
FirefoxProfile ffprofile = new FirefoxProfile(path);
Driver = new FirefoxDriver(ffprofile);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Can this possibly work to generate forms in Symfony 1.4? I'm currently attempting to generate form elements in Symfony based on the application's model. I know the code below is invalid, but I'm hoping it shows what I'm trying to do. I've really hit a wall with it... I can't seem to wrap my head around how I'd utilize the form library to accomplish this.
$formElementArray = FormElementsTable::getInstance()->getElementList($advertiserID);
$formElements = array();
foreach ($formElementArray as $formElement)
{
$formElements['name'] . => new sfWidgetForm.$formElements['type'] . (array('label' => $formElements['label'])),
}
$this->setWidgets(array($formElements));
My concern right now is that this isn't possible and I should abandon the idea, perhaps write a symfony component which produces forms from the model. That would actually be fairly simple, but I suppose I'd just like to stay as deep within the framework as possible for several reasons.
Thanks for any input.
edit: A bit more information...
The purpose is to be able to populate a form with whatever elements appear in a certain row of the database. For example, perhaps advertiserX needs a name, sex, and hair colour field, while advertiserY needs a name, sex, weight, and eye colour field. I need to be able to produce those on the fly, ideally with symfony's form features available.
Solution
This is how the form is configured...
public function configure()
{
$elements = Doctrine_Core::getTable('FormFields')->getElementsById(0);
foreach ( $elements as $element )
{
$widgetName = $this->getWidgetName($element);
$args = $this->getConstructorArguments($element);
$widgets[$element->name] = new $widgetName($args);
$validatorName = 'sfValidatorString';
$validators[$element->name] = new $validatorName(array('required' => false));
}
$this->setWidgets($widgets);
$this->setValidators($validators);
}
Simple, right? I shouldn't have over thought it so much.
A: It is best pratice to generate forms from your model, because if you change your models, you'll probably want to change your forms too. Doctrine and Propel both support this, so don't reinvent the square wheel : use what already exists ;)
UPDATE
In your case, maybe the model can be the same for all the advertisers, and all you need to do is extend the form to make the small variations appear in the forms. Your classes will call parent methods of the generated form, and slightly change widgets and validators.
A: If you intend to store the data sent when filling the user form (not the form form), then I think you should use a NoSQL system because your schema is dynamic (it changes when the advertiser changes). Read this blog post to learn more about them. Also read this SO post to learn what can be used with symfony.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: T-SQL - get value between two dates I just watched such an example which shows how to get all cols by date here it is...
DECLARE @MyGetDate DATETIME
SELECT @MyGetDate = '2 Mar 2003 21:40'
SELECT *
FROM @Table
WHERE convert(varchar, @MyGetDate, 14) BETWEEN convert(varchar, startDate, 14) AND convert(varchar, endDate, 14)
... but the thing is I was trying to modify it as to get values within past 50 minutes. Here it is
SELECT value, my_date_col
FROM myTable
WHERE convert(varchar, my_date_col, 14) BETWEEN convert(varchar, dateadd(minute, -50, getdate()), 14) AND convert(varchar, getdate(), 14)
But it doesn't work :( So my question is how to use col my_date_col in such kind of statement?
Any useful comment is appreciated
A: I assume your my_date_col is DateTime column, then you don't need the casting. Casting is needed because the sample uses string representation of dates.
DECLARE @date DATETIME
SET @date = GETDATE()
SELECT value, my_date_col
FROM myTable WHERE my_date_col BETWEEN dateadd(minute, -50, @date) AND @date
A: This should work just fine, assuming my_date_col is a DATETIME:
SELECT value, my_date_col
FROM myTable
WHERE my_date_col BETWEEN dateadd(minute, -50, getdate()) AND getdate()
If nothing is returned, there are no rows with a my_date_col in the last 50 minutes.
A: Get rid of the CONVERT statements, you want to compare dates, not varchars.
SELECT value, my_date_col
FROM myTable
WHERE my_date_col BETWEEN dateadd(minute, -50, getdate()) AND getdate(), 14
A: select value1, date_column from @Table
WHERE date_column between date1 and date2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself? The following shows that "0" is false in Javascript:
>>> "0" == false
true
>>> false == "0"
true
So why does the following print "ha"?
>>> if ("0") console.log("ha")
ha
A: // I usually do this:
x = "0" ;
if (!!+x) console.log('I am true');
else console.log('I am false');
// Essentially converting string to integer and then boolean.
A: Your quotes around the 0 make it a string, which is evaluated as true.
Remove the quotes and it should work.
if (0) console.log("ha")
A: It's according to spec.
12.5 The if Statement
.....
2. If ToBoolean(GetValue(exprRef)) is true, then
a. Return the result of evaluating the first Statement.
3. Else,
....
ToBoolean, according to the spec, is
The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:
And that table says this about strings:
The result is false if the argument is the empty String (its length is zero);
otherwise the result is true
Now, to explain why "0" == false you should read the equality operator, which states it gets its value from the abstract operation GetValue(lref) matches the same for the right-side.
Which describes this relevant part as:
if IsPropertyReference(V), then
a. If HasPrimitiveBase(V) is false, then let get be the [[Get]] internal method of base, otherwise let get
be the special [[Get]] internal method defined below.
b. Return the result of calling the get internal method using base as its this value, and passing
GetReferencedName(V) for the argument
Or in other words, a string has a primitive base, which calls back the internal get method and ends up looking false.
If you want to evaluate things using the GetValue operation use ==, if you want to evaluate using the ToBoolean, use === (also known as the "strict" equality operator)
A: Tables displaying the issue:
and ==
Moral of the story use ===
table generation credit: https://github.com/dorey/JavaScript-Equality-Table
A: The reason is because when you explicitly do "0" == false, both sides are being converted to numbers, and then the comparison is performed.
When you do: if ("0") console.log("ha"), the string value is being tested. Any non-empty string is true, while an empty string is false.
Equal (==)
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
(From Comparison Operators in Mozilla Developer Network)
A: It is all because of the ECMA specs ... "0" == false because of the rules specified here http://ecma262-5.com/ELS5_HTML.htm#Section_11.9.3 ...And if ('0') evaluates to true because of the rules specified here http://ecma262-5.com/ELS5_HTML.htm#Section_12.5
A: == Equality operator evaluates the arguments after converting them to numbers.
So string zero "0" is converted to Number data type and boolean false is converted to Number 0.
So
"0" == false // true
Same applies to `
false == "0" //true
=== Strict equality check evaluates the arguments with the original data type
"0" === false // false, because "0" is a string and false is boolean
Same applies to
false === "0" // false
In
if("0") console.log("ha");
The String "0" is not comparing with any arguments, and string is a true value until or unless it is compared with any arguments.
It is exactly like
if(true) console.log("ha");
But
if (0) console.log("ha"); // empty console line, because 0 is false
`
A: This is because JavaScript uses type coercion in Boolean contexts and your code
if ("0")
will be coerced to true in boolean contexts.
There are other truthy values in Javascript which will be coerced to true in boolean contexts, and thus execute the if block are:-
if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)
A: This is the reason why you should whenever possible use strict equality === or strict inequality !==
"100" == 100
true because this only checks value, not the data type
"100" === 100
false this checks value and data type
A: It's PHP where the string "0" is falsy (false-when-used-in-boolean-context). In JavaScript, all non-empty strings are truthy.
The trick is that == against a boolean doesn't evaluate in a boolean context, it converts to number, and in the case of strings that's done by parsing as decimal. So you get Number 0 instead of the truthiness boolean true.
This is a really poor bit of language design and it's one of the reasons we try not to use the unfortunate == operator. Use === instead.
A: The "if" expression tests for truthiness, while the double-equal tests for type-independent equivalency. A string is always truthy, as others here have pointed out. If the double-equal were testing both of its operands for truthiness and then comparing the results, then you'd get the outcome you were intuitively assuming, i.e. ("0" == true) === true. As Doug Crockford says in his excellent JavaScript: the Good Parts, "the rules by which [== coerces the types of its operands] are complicated and unmemorable.... The lack of transitivity is alarming." It suffices to say that one of the operands is type-coerced to match the other, and that "0" ends up being interpreted as a numeric zero, which is in turn equivalent to false when coerced to boolean (or false is equivalent to zero when coerced to a number).
A: if (x)
coerces x using JavaScript's internal toBoolean (http://es5.github.com/#x9.2)
x == false
coerces both sides using internal toNumber coercion (http://es5.github.com/#x9.3) or toPrimitive for objects (http://es5.github.com/#x9.1)
For full details see http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/
A: I have same issue, I found a working solution as below:
The reason is
if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, ""empty string, false, NaN
never use number type like id as
if (id) {}
for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.
So for id type, we must use following:
if ((Id !== undefined) && (Id !== null) && (Id !== "")){
} else {
}
for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.
if (string_type_variable) { }
A: In JS "==" sign does not check the type of variable. Therefore, "0" = 0 = false (in JS 0 = false) and will return true in this case, but if you use "===" the result will be false.
When you use "if", it will be "false" in the following case:
[0, false, '', null, undefined, NaN] // null = undefined, 0 = false
So
if("0") = if( ("0" !== 0) && ("0" !== false) && ("0" !== "") && ("0" !== null) && ("0" !== undefined) && ("0" !== NaN) )
= if(true && true && true && true && true && true)
= if(true)
A: I came here from search looking for a solution to evaluating "0" as a boolean.
The technicalities are explained above so I won't go into it but I found a quick type cast solves it.
So if anyone else like me is looking to evaluate a string 1 or 0 as boolean much like PHP. Then you could do some of the above or you could use parseInt() like:
x = "0";
if(parseInt(x))
//false
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "276"
} |
Q: How php/mysqli ( prepared statements + bind params ) protect against SQL Injection? How php/mysqli ( with prepared statements + bind params ) protect against SQL Injection ?
Mysqli applies only "real_escape_string" for variables or do something else?
May i say that the function below is totally useless when using mysqli + prepared statements + bind params ?
function no_injection ( $data ) {
$data = trim(strip_tags($data)); // no htm in this case.
$data = get_magic_quotes_gpc() == 0 ? addslashes($data) : $data; // useless.
$data = preg_replace("@(--|\#|;)@s", """, $data); // <--- USELESS ?
return $data;
}
Thanks
A: addslashes() is NOT unicode aware. There's a fair number of unicode sequences that look like normal text, but turn into different things when processed by non-unicode aware code, allowing a malicious user to construct a "valid" unicode string that comes an SQL injection attack once addslashes trashes the string.
The same goes for your regex. You've not enabled unicode mode, so it can potentially allow malicious unicode characters to leak through and become regular iso8859 chars that'll break the query.
Beyond that, each database has its own escaping requirements. MySQL understands and honors the backslash for escaping, so ' becomes \'. But another database might use '' as the escaped ', and applying a MySQL escape sequence for that database will be useless.
Prepared statements allow a complete separation of query and data. When you write your own query manually, the DB server has absolutely no way of knowing that a part of the query string is potentially malicious and treat it specially. It just sees a query string.
With prepared statements, the query body and the data going into the query are kept separate up until they reach the database server, and the db server can handle the escaping itself.
In real world terms, it's the difference between handing someone a loaf of poisoned bread, and handing them a basket of milk, eggs, flour, bottle of poison, yeast, etc... There's no way to tell there's poison in the bread until after you've eaten it and drop dead. While with the ingredients (aka prepared statement), the DB server will see that bottle of poison and know how to handle it.
A: It also caches the queries which will increase performance with more "calls".
-> http://dev.mysql.com/doc/refman/5.1/en/c-api-prepared-statements.html
-> Should I use prepared statements for MySQL in PHP PERFORMANCE-WISE?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding init.d service (chkconfig / autocomplete in shell) I've made a startup script, (i.e. myserviced) and put it in /etc/init.d/
I ran
chkconfig --add myserviced
I can start/stop/restart the service just find using:
service myserviced start
etc. However, I notice that when I type "service" and then do TAB (to get a list of possible completions), I don't see myserviced in the list of possible completions (it lists all the other services). How do I add myserviced to the auto-completion list?
This is in zsh on RHEL.
Thanks
A: Make sure myserviced is "executable." (i.e., chmod +x /etc/init.d/myserviced)
The completion lists all executable files in /etc/init.d, while service itself may work regardless of the permission.
A: you can use the following command to add all listed scripts in /etc/init.d/ to the service command:
complete -W "$(ls /etc/init.d/)" service
-W will create word list from the ($)specified path which 'service' will use for auto-complete.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to change the highlighted color of a tabbaritem? I am trying to change the highlighted color of the tabBarItem just like the Viber app does. I don't want to change the color of all the Bar, just the highlighted color.
I have read a lot posts here, but none of them explained how to do only this modification.
Does someone know how to do this? There is many apps that have customized colors!
A: Currently, with iOS4, this type of customization is not possible with a standard UITabBar. Most applications that have customized UITabBars actually create their own. Check out CocoaControls for some drop in third-party solutions you could use.
A: Have you tried:
UIView *bg = [[[UIView alloc] initWithFrame:CGRectMake(0,0,320,49)] autorelease];
[bg setBackgroundColor:[UIColor redColor]];
[self.tabBarController.tabBar insertSubview:bg atIndex:1];
That code initially creates a background view for the tabBar and sets it's colour to red.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple Facebook Canvas Applications within same web application - CanvasAuthorizeAttribute I am having a problem with running multiple Facebook applications under a single Web application.
Similar to this problem:
Multiple facebook apps under one web application
I do like the solution suggested here, however the CanvasAuthorizeAttribute uses the FacebookApplication.Current internally and this is a static instance of the FB application within the Web application.
I can't call the .SetApplication method within the controller as I will have concurrency issues.
It would be nice if the FacebookApplication.Current called the Func that is passed into the .SetApplication instead of just calling inside of the .SetApplication.
That way I could pass a function that does my logic for retrieving the correct FB application.
Am I missing something that is already in the SDK?
A: You can always have your own logic at http://facebook.stackoverflow.com/questions/4931240/multiple-facebook-apps-under-one-web-application/4936703#4936703
private IFacebookApplication Current
{
get
{
var url = HttpContext.Current.Request.Url;
var app = GetSettingsForUrl(url);
// put your custom logic here and return the appropriate IFacebookApplication
return app;
}
}
But you should do this during Application_Start where it is still running on a single thread and not in Controller.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to send video stream to soap web service I need to send recorded video stream to web service.
I'm doing encoding video stream using Base 64 but im getting out of memory exception. So I'm thinking another way to do this.
I searched for this but I can't find any reference link.
Is there another way to send the video that I can use?
A: Byte64 encoding alone expands data sizes to 4/3 their original size. On a video file this is an exceptional amount of overhead. Most likely you haven't seen any links on this topic due to the inability to use such a solution on any current infrastructure.
I'd highly recommend that you start looking into prepackaged transcoding solutions for your needs until you have a better understanding of this problem domain. Otherwise you are going to have a hard time finding people who want to take up your questions on stack overflow for fear of being downvoted when they have to explain to you that your entire premise is flawed and can be proven so mathematically.
For example let's assume that you are trying to push standard definition video (640x480) at 30 frames per second. Let's also say that the video is in the standard RGB format with 8 bits per color band, 24 bits per pixel. The math for this would be:
width x height x bytes per pixel x frame per second x Byte64 overhead = bytes per second
640 x 480 x 3 x 30 x 4/3 = 36,864,000
35MB per second
Remembering that most throughput measurements are in mega bits per second rather than mega bytes per second this translates to 281.25Mb/s. With those kind of bandwidth needs you are going to have a hard time finding a wireless connection that can meet your data needs and face quite a real threat of saturating a hardwired network connection. At the present time you need to compress your video files and you need to use something other than soap or use SOAP extensions like MTOM which allow data streaming.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linq, OrderByDescending, First, and the nefarious DefaultIfEmpty Hopefully this is a simple matter of me not understanding something basic. Below are two Linq statements from an application I'm working on.
EDMXModel.Classes.Period p1 = entities.Periods.DefaultIfEmpty(null).OrderByDescending(ap => ap.UID).First();
EDMXModel.Classes.Period p2 = entities.Periods.OrderByDescending(ap => ap.UID).DefaultIfEmpty(null).First();
entities.Periods is a set containing two Period objects, each with a unique UID.
According to everything I understand, p1 and p2 should be the same.
In my environment, however, they are not.
p1 is correct (i.e. it is equal to the Period object with the largest UID in the set).
p2, however, is not correct (i.e. it is equal to the other Period in the set).
Any ideas?
A: DefaultIfEmpty() on Linq to Entities does not guarantee to maintain the order established by OrderByDescending(), (also see here) the order should always be last and that is why the first case works - but you shouldn't use either in my opinion - this is exactly what FirstOrDefault() is for:
EDMXModel.Classes.Period p1 = entities.Periods
.OrderByDescending(ap => ap.UID)
.FirstOrDefault();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Can I create nested classes when using Linq-To-Entities? I'm still learning Entity Framework and Linq-To-Entities, and I was wondering if a statement of this kind is possible:
using (var context = new MyEntities())
{
return (
from a in context.ModelSetA.Include("ModelB")
join c in context.ModelSetC on a.Id equals c.Id
join d in context.ModelSetD on a.Id equals d.Id
select new MyModelA()
{
Id = a.Id,
Name = a.Name,
ModelB = new MyModelB() { Id = a.ModelB.Id, Name = a.ModelB..Name },
ModelC = new MyModelC() { Id = c.Id, Name = c.Name },
ModelD = new MyModelD() { Id = d.Id, Name = d.Name }
}).FirstOrDefault();
}
I have to work with a pre-existing database structure, which is not very optimized, so I am unable to generate EF models without a lot of extra work. I thought it would be easy to simply create my own Models and map the data to them, but I keep getting the following error:
Unable to create a constant value of type 'MyNamespace.MyModelB'. Only
primitive types ('such as Int32, String, and Guid') are supported in
this context.
If I remove the mapping for ModelB, ModelC, and ModelD it runs correctly. Am I unable to create new nested classes with Linq-To-Entities? Or am I just writing this the wrong way?
A: What you have will work fine with POCOs (e.g., view models). Here's an example. You just can't construct entities this way.
Also, join is generally inappropriate for a L2E query. Use the entity navigation properties instead.
A: I have created your model (how I understand it) with EF 4.1 in a console application:
If you want to test it, add reference to EntityFramework.dll and paste the following into Program.cs (EF 4.1 creates DB automatically if you have SQL Server Express installed):
using System.Linq;
using System.Data.Entity;
namespace EFNestedProjection
{
// Entities
public class ModelA
{
public int Id { get; set; }
public string Name { get; set; }
public ModelB ModelB { get; set; }
}
public class ModelB
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ModelC
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ModelD
{
public int Id { get; set; }
public string Name { get; set; }
}
// Context
public class MyContext : DbContext
{
public DbSet<ModelA> ModelSetA { get; set; }
public DbSet<ModelB> ModelSetB { get; set; }
public DbSet<ModelC> ModelSetC { get; set; }
public DbSet<ModelD> ModelSetD { get; set; }
}
// ViewModels for projections, not entities
public class MyModelA
{
public int Id { get; set; }
public string Name { get; set; }
public MyModelB ModelB { get; set; }
public MyModelC ModelC { get; set; }
public MyModelD ModelD { get; set; }
}
public class MyModelB
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyModelC
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyModelD
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Create some entities in DB
using (var ctx = new MyContext())
{
var modelA = new ModelA { Name = "ModelA" };
var modelB = new ModelB { Name = "ModelB" };
var modelC = new ModelC { Name = "ModelC" };
var modelD = new ModelD { Name = "ModelD" };
modelA.ModelB = modelB;
ctx.ModelSetA.Add(modelA);
ctx.ModelSetB.Add(modelB);
ctx.ModelSetC.Add(modelC);
ctx.ModelSetD.Add(modelD);
ctx.SaveChanges();
}
// Run query
using (var ctx = new MyContext())
{
var result = (
from a in ctx.ModelSetA.Include("ModelB")
join c in ctx.ModelSetC on a.Id equals c.Id
join d in ctx.ModelSetD on a.Id equals d.Id
select new MyModelA()
{
Id = a.Id,
Name = a.Name,
ModelB = new MyModelB() {
Id = a.ModelB.Id, Name = a.ModelB.Name },
ModelC = new MyModelC() {
Id = c.Id, Name = c.Name },
ModelD = new MyModelD() {
Id = d.Id, Name = d.Name }
}).FirstOrDefault();
// No exception here
}
}
}
}
This works without problems. (I have also recreated the model from the database (which EF 4.1 had created) in EF 4.0: It works as well. Not surprising since EF 4.1 doesn't change anything in LINQ to Entities.)
Now the question is why you get an exception? My guess is that there is some important difference in your Models or ViewModels or your query compared to the simple model above which is not visible in your code example in the question.
But the general result is: Projections into nested (non-entity) classes work. (I'm using it in many situations, even with nested collections.) Answer to your question title is: Yes.
A: What Craig posted does not seem to work for nested entities. Craig, if I am misunderstood what you posted, please correct me.
Here is the workaround I came up with that does work:
using (var context = new MyEntities())
{
var x = (
from a in context.ModelSetA.Include("ModelB")
join c in context.ModelSetC on a.Id equals c.Id
join d in context.ModelSetD on a.Id equals d.Id
select new { a, b, c }).FirstOrDefault();
if (x == null)
return null;
return new MyModelA()
{
Id = x.a.Id,
Name = x.a.Name,
ModelB = new MyModelB() { Id = x.a.ModelB.Id, Name = x.a.ModelB..Name },
ModelC = new MyModelC() { Id = x.c.Id, Name = x.c.Name },
ModelD = new MyModelD() { Id = x.d.Id, Name = x.d.Name }
};
}
Since Entity Framework can't handle creating nested classes from within the query, I simply returned an anonymous object from my query containing the data I wanted, then mapped it to the Model
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why isn't -moz-animation working? The following CSS works fine in Webkit. Haven't checked it in Opera, but I know it's not working in Firefox. Can anybody tell me why?
The correct classes are definitely getting applied to my HTML (inspected it with Firebug, and I do see the -moz-animation: 500ms ease 0s normal forwards 1 arrowRotateDot property on .arrow).
This also doesn't work in IE9, although I did originally have -ms-animation:... and -ms-transform:.... I thought it was supposed to work in IE9, but when it didn't I just assumed that IE didn't support these yet. However, now that it's not working in Firefox, maybe something else is going on.
.page.updatesPodcasts > .mainContent > .content .contentUpdates .disc.dot .dvd .arrow {
-webkit-animation: arrowRotateDot 500ms forwards;
-moz-animation: arrowRotateDot 500ms forwards;
-o-animation: arrowRotateDot 500ms forwards;
animation: arrowRotateDot 500ms forwards;
}
.page.updatesPodcasts > .mainContent > .content .contentUpdates .disc.f2 .dvd .arrow {
-webkit-animation: arrowRotateF2 500ms forwards;
-moz-animation: arrowRotateF2 500ms forwards;
-o-animation: arrowRotateF2 500ms forwards;
animation: arrowRotateF2 500ms forwards;
}
@-webkit-keyframes arrowRotateDot {
100% {
left:-18px; top:182px;
-moz-transform: scale(1) rotate(-30deg);
-webkit-transform: scale(1) rotate(-30deg);
-o-transform: scale(1) rotate(-30deg);
transform: scale(1) rotate(-30deg);
}
}
@-webkit-keyframes arrowRotateF2 {
0% {
left:-18px; top:182px;
-moz-transform: scale(1) rotate(-30deg);
-webkit-transform: scale(1) rotate(-30deg);
-o-transform: scale(1) rotate(-30deg);
transform: scale(1) rotate(-30deg);
}
100% {
left:115px; top:257px;
-moz-transform: scale(1) rotate(-90deg);
-webkit-transform: scale(1) rotate(-90deg);
-o-transform: scale(1) rotate(-90deg);
transform: scale(1) rotate(-90deg);
}
}
A: Your animations are not working in Firefox because you are using @-webkit-keyframes, which only applies to Webkit browsers, i.e. Chrome and Safari. The (somewhat) cross-browser way to do animation keyframes is:
@keyframes animationName {
/* animation rules */
}
@-moz-keyframes animationName {
/* -moz-animation rules */
}
@-webkit-keyframes animationName {
/* -webkit-animation rules */
}
Opera and Internet Explorer do not currently support the @keyframes rule.
A: Skyline is correct. Firefox does not support this, so you will need additional code to get the same or similar effects if they exist without webkit.
Also, here is some additional information that might help you with your code or help you in deciding where to go from this point with your code if adding additional code is not an option (I ended up changing how I code to keep from being overwhelmed with code):
http://caniuse.com/#
http://www.quirksmode.org/webkit.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Timer start/stop parameters I've made leaps and bounds in skill and progress since joining this community. You all are a huge help. I'm having trouble with giving a timer that I've implemented certain parameters for when it starts and stops.
I either get errors saying "the local variable timer may not have been initialized" or I get no errors, but nothing happens. Maybe I have the timer in the wrong place?
If I put timer.start(); in the constructor too everything works fine, but then the timer has to start when the program is initialized. I would really like to have the timer not start until a certain parameter is met. Say, for instance, until the int p1Laps=1; but if I place timer.start(); into an if-statement in the constructor (i.e. if(p1Laps>=1) { timer.start(); } the timer doesn't ever start.
I've tried placing timer.start(); in various places and have either gotten no response or generated an error about the lack of local variable timer.
A second, somewhat related problem I have is the inability to put any parameters in place to call on timer.stop(); without getting the aforementioned "local variable timer may not have been initialized" error. I've left timer.stop(); where I think it needs to be in the code, but it receives that error.
So in short, I want to be able to tell the timer to start when a parameter is met, namely when a player has completed a lap. And I want to be able to tell the timer to stop when it reaches a value.
Thanks in advance for the great advice I'm sure I'll receive. Note: this is not the whole code, just relevant information.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
public class RacerDoom extends JFrame {
int counter = 0;
int p1Laps = 0;
public RacerDoom() {
//create JFrame
super("Racer Doom Squared");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//set up Timer
final Timer timer=new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(counter>=10) {
timer.stop(); //error here reads "local variable timer may
//not have been initialized"
}
else{
counter++;
}
System.out.println(counter);
}
});
//inner class threads
Move1 m1 = new Move1();
m1.start();
//start timer
if(p1Laps>=1) {
timer.start(); //error here is that timer will not start when
//p1Laps>=1
}
}
private class Move1 extends Thread implements KeyListener {
public void run() {
addKeyListener(this);
while(true) {
try {
repaint();
//collisions
if(p1.intersects(finishtop)&&p1Direction==UP&&p1cross!=true){
p1cross=true;
p1Laps++;
p1Boost++;
counter=0;
System.out.println(p1Laps);
}
if(p1.intersects(finishtop)==false) {
p1cross=false;
}
public static void main (String [] args) {
new RacerDoom();
}
}
A: As you want to start and stop the timer at different places in the code you should make it member variable. This will fix the problem where you are trying to stop the timer inside the action listener.
The variable p1Laps will not change in the constructor (after you have initialized it to 0) so you need to start the timer where you change the value of plLaps. I am not sure if it is safe to call timer.start() from another thread (Move1). So it may be safer to start timer with SwingUtilities.invokeLater().
A: Quick fix:
Rather than
timer.stop();
Do
((Timer)e.getSource()).stop();
The ActionEvent's getSource method will return a reference to the object that calls the actioPerformed method (the Timer), so this should work.
There may be other issues with your code including your background thread without a Thread.sleep(...), your use of KeyListeners rather than Key Binding, your adding a KeyListener in a background thread,...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: HTML tags in RTL forms I store some RTL language strings - which have some HTML tags embedded - in a DB. When I echo these strings on an HTML page these are rendered correctly. However, when I place these same strings in a <textarea> the HTML tags are all messed up.
Here below is an example (you'll need to copy paste it in an HTML file). As you can see the tags are rendered corrrectly in the <div> but are totally messed up in the <textarea>.
Does anybody know how to ensure that even visually the tags look correct? I am placing this text in a textarea for editing so it needs to be correct.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
<html dir="ltr">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div dir="rtl">اسحب هذه الرسالة إلى اعلى الصفحة و <strong><a href="javascript:void(0);" id="demo-start">اضغط هنا</a></strong> لتبدأ.</div>
<br />
<textarea dir="rtl" rows="12" cols="50">اسحب هذه الرسالة إلى اعلى الصفحة و <strong><a href="javascript:void(0);" id="demo-start">اضغط هنا</a></strong> لتبدأ.</textarea>
</body>
</html>
Note
Somehow I believe it has to do with the ‎ or ‏ mark, but I have no idea how.
A: Change the dir attribute of the textarea to ltr. It will format fine.
jsfiddle of the updated markup.
A: If you're not sure of the content of your textarea, you can use dir="auto" in your textarea. This will make the browser render the text either LTR or RTL based on the first strong character.
Both of these will render the internal text correctly:
<textarea dir="auto">This is an LTR line.</textarea>
<textarea dir="auto">זוהי שורת ימין לשמאל.</textarea>
See the jsFiddle here
The only problem you may run into are mixed strings; if one of your inputs displays even a single strong character in English followed by RTL text, the textbox will render LTR, which will display the rest of the string as a bit mangled.
If you run into this problem, you will have to work with a javascript (or back-end) code to calculate the majority of strong characters in your string and attach a dir="ltr" or dir="rtl" accordingly.
For the most part, setting dir="auto" on your textboxes should work for most cases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Objective C - Creating Angles From Current Time I'm trying to write code to draw a clock on the screen of an iOS device. I need to get the angle of a line (seconds, minutes, hours hands of clock) from the current time. My code accurately grabs the time, but for some reason, all of the angles I receive end up being the same (no matter what time it is).
If it helps, the angle I am constantly receiving is:
-1.5707963267948966
Here is the code I use to get the angles:
secondsTheta = ((seconds/60) * (2 * M_PI)) - (M_PI / 2);
minutesTheta = ((minutes/60) + (seconds/3600)) * (2 * M_PI) - (M_PI / 2);
hoursTheta = ((hours/12) + (minutes/720) + (seconds/43200)) * (2 * M_PI) - (M_PI / 2);
My thought is that something is funky with M_PI, but I don't know what would be...but as I said, the seconds, minutes, and hours variables are correct. They are declared in my header file as ints, and I know that [NSDateComponents seconds](etc) returns an NSInteger, but I don't think that should matter for this basic math.
A: Since the seconds, minutes, and hours variables are declared as ints the division will not give you the correct values. An int divided by another init will result in an int, what is needed for the result is a float. In order to have the compiler use floating point arithmetic it is necessary that one of the operands be a floating point format number (float).
Example: 10 seconds divided by 60 (10/60) will use integer math and result in 0.
Example: 10.0 seconds divided by 60 (10/60) will use floating point math and result in 0.1.66666667.
Example:
secondsTheta = ((seconds/60.0) * (2 * M_PI)) - (M_PI / 2);
or
secondsTheta = (((float)seconds/60) * (2 * M_PI)) - (M_PI / 2);
A: Your seconds, minutes and hours are ints. Dividing ints by ints does integer arithmetic and truncates the values, so
seconds/60
will always give you 0. Objective C inherits this behavior from C and this is fairly common behavior among programming languages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Programmatically implementing callbacks with JS/jQuery So, I'm writing a web app. Pretty much everything is done client-side, the server is but a RESTful interface. I'm using jQuery as my framework of choice and implementing my code in a Revealing Module Pattern.
The wireframe of my code basically looks like this:
(function($){
$.fn.myplugin = function(method)
{
if (mp[method])
{
return mp[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === 'object' || ! method)
{
return mp.init.apply(this, arguments);
}
else
{
$.error('Method ' + method + ' does not exist on $.myplugin');
}
};
var mp =
{
init : function( options )
{
return this.each(function()
{
// stuff
}
},
callbacks : {},
addCallback : function(hook_name, cb_func, priority)
{
// some sanity checking, then push cb_func onto a stack in mp.callbacks[hook_name]
},
doCallbacks : function(hook_name)
{
if (!hook_name) { hook_name = arguments.callee.caller.name; }
// check if any callbacks have been registered for hook_name, if so, execute one after the other
}
};
})(jQuery);
Pretty straightforward, right?
Now, we're able to register (multiple, hierarchical) callbacks from inside as well as from outside the application scope.
What is bugging me: To make the whole thing as extensible as possible, I'd have to resort to something along these lines:
foo : function() {
mp.doCallbacks('foo_before');
// do actual stuff, maybe some hookpoints in between
mp.doCallbacks('foo_after');
}
Every single function inside my app would have to start and end like that. This just doesn't seem right.
So, JS wizards of SO - what do?
A: I might have not understood the question correctly, because I don't see why you don't add the code to call the callbacks directly in the myplugin code:
$.fn.myplugin = function(method)
{
if (mp[method])
{
var params = Array.prototype.slice.call(arguments, 1), ret;
// you might want the callbacks to receive all the parameters
mp['doCallbacks'].apply(this, method + '_before', params);
ret = mp[method].apply(this, params);
mp['doCallbacks'].apply(this, method + '_after', params);
return ret;
}
// ...
}
EDIT:
Ok, after reading your comment I think another solution would be (of course) another indirection. That is, have an invoke function that's being used from the constructor as well as the other public methods for calls between themselves. I would like to point out that it will only work for the public methods, as attaching to private methods' hooks breaks encapsulation anyway.
The simple version would be something like this:
function invoke(method) {
var params = Array.prototype.slice.call(arguments, 1), ret;
// you might want the callbacks to receive all the parameters
mp['doCallbacks'].apply(this, method + '_before', params);
ret = mp[method].apply(this, params);
mp['doCallbacks'].apply(this, method + '_after', params);
}
$.fn.myplugin = function() {
// ...
invoke('init');
// ...
};
But, I've actually written a bit more code, that would reduce the duplication between plugins as well.
This is how creating a plugin would look in the end
(function() {
function getResource() {
return {lang: "JS"};
}
var mp = NS.plugin.interface({
foo: function() {
getResource(); // calls "private" method
},
bar: function() {
this.invoke('foo'); // calls "fellow" method
},
init: function() {
// construct
}
});
$.fn.myplugin = NS.plugin.create(mp);
})();
And this is how the partial implementation looks like:
NS = {};
NS.plugin = {};
NS.plugin.create = function(ctx) {
return function(method) {
if (typeof method == "string") {
arguments = Array.prototype.slice.call(arguments, 1);
} else {
method = 'init'; // also gives hooks for init
}
return ctx.invoke.apply(ctx, method, arguments);
};
};
// interface is a reserved keyword in strict, but it's descriptive for the use case
NS.plugin.interface = function(o) {
return merge({
invoke: NS.plugin.invoke,
callbacks: {},
addCallback: function(hook_name, fn, priority) {},
doCallbacks: function() {}
}, o);
};
NS.plugin.invoke = function(method_name) {
if (method_name == 'invoke') {
return;
}
// bonus (if this helps you somehow)
if (! this[method]) {
if (! this['method_missing') {
throw "Method " + method + " does not exist.";
} else {
method = 'method_missing';
}
}
arguments = Array.prototype.slice.call(arguments, 1);
if (method_name in ["addCallbacks", "doCallbacks"]) {
return this[method_name].apply(this, arguments);
}
this.doCallbacks.apply(this, method_name + '_before', arguments);
var ret = this[method_name].apply(this, arguments);
this.doCallbacks.apply(this, method_name + '_after', arguments);
return ret;
};
Of course, this is completely untested :)
A: you are essentially implementing a stripped-down version of the jQueryUI Widget factory. i'd recommend using that functionality to avoid having to roll this yourself.
the widget factory will auto-magically map strings to method calls, such that:
$("#foo").myPlugin("myMethod", "someParam")
will call myMethod on the plugin instance with 'someParam' as an argument. Additionally, if you fire a custom event, users can add callbacks by adding an property to the options that matches the event name.
For example, the tabs widget has a select event that you can tap into by adding a select property to the options during initialization:
$("#container").tabs({
select: function() {
// This gets called when the `select` event fires
}
});
of course, you'll need to add the before and after hooks as events to be able to borrow this functionality, but that often leads to easier maintenance anyhow.
hope that helps. cheers!
A: You can write a function that takes another function as an argument, and returns a new function that calls your hooks around that argument. For instance:
function withCallbacks(name, func)
{
return function() {
mp.doCallbacks(name + "_before");
func();
mp.doCallbacks(name + "_after");
};
}
Then you can write something like:
foo: withCallbacks("foo", function() {
// Do actual stuff, maybe some hookpoints in between.
})
A: Basically I prefer to avoid callbacks and use events instead. The reason is simle. I can add more than one functions to listen given event, I don't have to mess with callback parameters and I don't have to check if a callback is defined. As far as all of your methods are called via $.fn.myplugin it's easy to trigger events before and after method call.
Here is an example code:
(function($){
$.fn.myplugin = function(method)
{
if (mp[method])
{
$(this).trigger("before_"+method);
var res = mp[method].apply(this, Array.prototype.slice.call(arguments, 1));
$(this).trigger("after_"+method);
return res;
}
else if (typeof method === 'object' || ! method)
{
return mp.init.apply(this, arguments);
}
else
{
$.error('Method ' + method + ' does not exist on $.myplugin');
}
};
var mp =
{
init : function( options )
{
$(this).bind(options.bind);
return this.each(function()
{
// stuff
});
},
foo: function() {
console.log("foo called");
}
};
})(jQuery);
$("#foo").myplugin({
bind: {
before_foo: function() {
console.log("before foo");
},
after_foo: function() {
console.log("after foo");
}
}
});
$("#foo").myplugin("foo");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: HorizontalAlignment on image not working in PdfPCell in itextsharp I am adding a image in PdfPCell and i want that to be center aligned. For that i used following code but its not working
PdfPTable Outertable = new PdfPTable(1);
PdfPCell celltop = new PdfPCell(new Phrase(" "));
iTextSharp.text.Image img10 = iTextSharp.text.Image.GetInstance(@"F:\TestPDFGenerator\TestPDFGenerator\TestPDFGenerator\Sumit.JPG");
img10.ScaleAbsolute(50, 1);
celltop.AddElement(img10);
celltop.HorizontalAlignment = Element.ALIGN_CENTER;
Outertable.AddCell(celltop);
please can you tell where i am wrong
Thanks
A: You need to set the alignment on the image, not the cell:
img10.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: jQuery UI issues with tables in dialogs I have a jQuery UI dialog to which I applied a padding, and inside the dialog I have a long table. I then configure the dialog to be of limited height in order to have a scrollbar.
It seems that whenever a nowrap is applied to the table cells, the padding to the right of the table is covered by the scrollbar. If I remove the nowrap, it works fine.
Here is an editable example:
http://jsbin.com/okolap/4/edit
A: It seems that it only happens when you set the dialog's width to auto.
One workaround is to set the table's width to 100% and reset the dialog's width to a fixed length. The length needs to add a padding equal or larger than the width of the scroll bar. For example:
var newWidth = $('.Dialog').width() + 50;
$('.Dialog').width(newWidth);
See this in action: http://jsbin.com/okolap/10/.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Change aspects of page with PHP I'm trying to make my PHP code update parts of my HTML when executed, and I'm not really sure how to do it without relying heavily on javascript and hidding divs etc.
It works in a way that when the user clicks the "tick" or "cross", it updates a database and hides a div whilst showing another. This DB is queried on page load, and a voting bar is loaded with the current total ticks and crosses. There is then a % width set on those bars depending on how many votes each side has.
I've currently got:
<div id="voting">
<a href="#" onClick="updatelikes();">
<img src="/images/tick.png" width="250px" />
</a>
<a href="#" onClick="updatedislikes();">
<img src="/images/cross.png" width="250px" />
</a>
</div>
<div id="votingoff" style="display:none;">
<img src="/images/tick.png" width="250px" />
<img src="/images/cross.png" width="250px" />
</div>
and
function updatelikes() {
$.get("updatelikes.php");
voting = document.getElementById('voting');
voting.style.display="none";
votingoff = document.getElementById('votingoff');
votingoff.style.display="";
return false;
}
function updatedislikes() {
$.get("updatedislikes.php");
voting = document.getElementById('voting');
voting.style.display="none";
votingoff = document.getElementById('votingoff');
votingoff.style.display="";
return false;
}
This works in that it removes one from display, and shows the other one. However, I feel this code is a bit clunky, and I'd like for the "voting bar" to have its width changed and have the values updated. Since the HTML code is generated at page load by the PHP script, I don't know how to update it when "updatelikes.php" or "updatedislikes.php" is loaded, since I feel I would have to have another div that is hidden, then added to it, then show it, and hide the other. I think this could be a clunky, and maybe even slow on some user computers.
Any input is much appreciated, as I'm just totally lost now!
A: I see you are already using JQuery to access "updatelikes.php" and "updatedislikes.php". You can easily have a value returned to your javascript functions from your php pages:
$.get('updatedislike.php', function (response) {
//Logic in here
});
So in the Like/Dislike you could get the total votes from the database and return it to your javascript function, and then the "response" argument will have whatever you returned from your php function. After the value is returned you can simply re-call whatever you call at page load (in case you return/do exactly what you do when the page is loaded at first).
Here you can find how to return values from your php files to your jquery/javascript functions.
Good luck!
Hanlet
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Save pdf form in mysql Is there a tool/software that I can use for clients to save their pdf form online. Example: I have e generic fill-able pdf form online, have them fill it out online and save it on the fly. Is there something like that out there?
A: It is possible but why save it in the database? You could probably save it on the filesystem as well?
-> store a pdf in mysql
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Symfony2+Behat+Mink: how should I refactor? in this tutorial is proposed this file system:
XXXBundle
|---Features
| |----FeaturesContext.php
|---ProductCategoryRelation.feature
where FeaturesContext.php is the file that stores the functions
//FeaturesContext.php
/**
* Feature context.
*/
class FeatureContext extends BehatContext
{
/**
* @Given /I have a category "([^"]*)"/
*/
public function iHaveACategory($name)
{
$category = new \Acme\DemoBundle\Entity\Category();
$category->setName($name);
...
And inside ProductCategoryRelation.feature is proposed to write the features and the scenarios:
Feature: Product Category Relationship
In order to setup a valid catalog
As a developer
I need a working relationship
This being the feature, we now need the scenarios to be defined.
Scenario: A category contains a product
Given I have a category "Underwear"
...
But if my app is growing up, how should refactor for example FeaturesContext.php?
A: You might use subcontexts to split step definitions into multiple context classes: http://docs.behat.org/guides/4.context.html#using-subcontexts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to refactor helper methods in RSpec files? I am using Ruby on Rails 3.1.0 and the rspec-rails 2gem. I would like to refactor the following code (I have intentionally omitted some code and I have given meaningful names in order to highlight the structure):
describe "D1" do
# Helper method
def D1_Method_1
...
end
context "C1" do
# Helper methods
def D1_C1_Method_1
session.should be_nil # Note: I am using the RoR 'session' hash
D1_Method_1 # Note: I am calling the 'D1_Method_1' helper method
...
end
def D1_C1_Method_2
...
end
it "I1" do
D1_Method_1
...
end
it "I2" do
...
D1_C1_Method_1
D1_C1_Method_2
end
end
context "C2" do
# Helper methods
def D1_C2_Method_1
...
end
def D1_C2_Method_2
...
end
it "I1" do
D1_Method_1
...
end
it "I2" do
...
D1_C2_Method_1
D1_C2_Method_2
end
end
end
What can\should I make in order to refactor the above code?
P.S.: I have tried to extract helper methods in an external module (named Sample) but, for example relating to the D1_C1_Method_1 method (that contains the RoR session), I get the following error when I run the spec file:
Failure/Error: session.should be_nil
NameError:
undefined local variable or method `session' for Sample:Module
A: Have you tried to include the helpers as an external module?
require 'path/to/my_spec_helper'
describe "D1" do
include MySpecHelper
...
end
And now the helper:
# my_spec_helper.rb
module MySpecHelper
def D1_C1_Method_1
session.should be_nil
...
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Ruby Concept - Yield Working my way through Ruby concepts right now. Coming from a VB background, there are some concepts I don't quite grasp yet. Yield is one of them. I understand how it works in a practical sense, but fail to see the significance of Yield, or when and how I would use it to its full potential.
A: Yield is part of a larger system of closures in Ruby. It is a very powerful part of the language and you will find it in every Ruby script you encounter.
http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
A: It's good to have an understanding of how yield works but I seldom use it and thought that the same was true for others. The comments to this answer could indicate otherwise.
Ruby's yield statement hands over the control to a block given to the method. After the block has finished the control is returned to the method and it keeps on executing the statement directly after the yield.
Here's a variant of the overused Fibonacci sequence
def fib(upto)
curr, succ = 1, 1
while curr <= upto
puts "before"
yield curr
puts "after"
curr, succ = succ, curr+succ
end
end
You then call the method with something like
fib(8) {|res| puts res}
and the output will be
before
1
after
before
1
after
before
2
after
before
3
after
before
5
after
before
8
after
A: Good reading: http://blog.codahale.com/2005/11/24/a-ruby-howto-writing-a-method-that-uses-code-blocks/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Drupal Filefield User Permissions Granularity I have a Drupal 6 site with a node type that has an optional, unlimited value, Imagefield (Filefield/CCK) setup. The node type's content permissions are set to allow all authenticated users to be able to edit those nodes, which is great. Users can edit a node and attach images to the Imagefield, also great.
However, when a user is editing one of these nodes, they are also able to edit/delete Imagefield images uploaded by other users. How can I prevent a user from editing and/or deleting Imagefield images that were not uploaded by themselves?
A: Thanks to a few folks in the #drupal-support channel on IRC, I was able to get an answer to this question. Here is an example module based solution:
function my_module_form_alter(&$form, &$form_state, $form_id) {
global $user;
switch ($form['type']['#value']) {
case "my_content_type":
if (user_access("administer nodes")) { break; }
foreach (array_keys($form['field_my_images']) as $key) {
if (!is_numeric($key)) { continue; }
if ($form['field_my_images'][$key]['#default_value']['fid']) {
if ($form['field_my_images'][$key]['#default_value']['uid'] != $user->uid) {
$form['field_my_images'][$key]['#access'] = false;
}
}
}
break;
}
}
I feel silly now that I realize my whole problem was because I was accessing e.g. :
$form['#node']->field_my_images
instead of:
$form['field_my_images']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make Jasper Reports programmatically determine the Name of Columns within the report it self? I am generating a report with that will have a 7 columns where the last 6 should have the the last 6 months listed. So as of the time of this writing it should be:
NAME -> September -> August -> July -> June -> May -> April
ss the column headers. I am trying to avoid having to pass them in as parameters, and am trying to get Jasper Reports to figure it out at runtime. I can get the first month pretty easily using a Text Field Expression. It looks like:
new java.text.SimpleDateFormat("MMMMM").format(new Date())
The issue comes in with the other months. I initially tried
new java.text.SimpleDateFormat("MMMMM").format(java.util.Calendar.getInstance().add(Calendar.MONTH, new Integer("-1)).getTime())
This does not work since Calendar.add does not return a Calendar instance. I then tried using a variable and then a combination of variables which also did not work.
How to make Jasper Reports programmatically determine the Name of Columns within the report it self?
A: I think the best approach to solving this problem is to use Commons Lang. That package provides utilities to make calculations like this very easy. By adding one extra jar you can then use expressions like this:
DateUtils.addMonths(new Date(),-1)
I find that easier to maintain than first creating a helper Calendar class and then using the ternary operator but ignoring its results.
$P{cal}.add(Calendar.MONTH, -1)
? null : $P{cal}.getTime()
If you ever need to generalize the solution then it's a lot easier to get a Date back from a SQL query than to get a Calendar. So you can quickly change to "DateUtils.addMonths($F{MyDate},-1)". Initializing a Calendar to match a date returned by a query isn't nearly as simple. But of course there's a certain benefit to not having to add one more .jar file. So sometimes that ternary operator technique is the quickest way to get things done.
I wrote about using the Commons Lang approach a couple of years ago here: http://mdahlman.wordpress.com/2009/09/09/jasperreports-first-dates/
A: I also needed a certain format for the previous month. I ended up combining the other two answers:
new java.text.SimpleDateFormat("yyyyMM").format(
org.apache.commons.lang3.time.DateUtils.addMonths(
new java.util.Date(),
-6
)
)
This way I don't need to add another parameter. Adding the Commons Lang jar is a non issue for me since JasperServer 5.5 comes with version 3.0 out of the box.
I hope this helps someone who stumples upon this page, just like I did.
A: I found a working solution that is pretty ingenious (no I did not come up with it). I found it here. The gist of it is create a parameter called call, with a default value of:
Calendar.getInstance()
and un-check the option 'Use as a prompt'. Then in your text field expression you would do:
new java.text.SimpleDateFormat("MMMMM").format(
(
$P{cal}.add(Calendar.MONTH, -1)
? null : $P{cal}.getTime()
)
)
What happens is it will set the default value for the calendar instance, then execute the add method, which will resolve to false, so then it will then return the result from getTime() method which gets formatted how I want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: injecting arabic text in div at runtime as ajax responce shows weired characters I have a php page which supports arabic text properly.
I am using ajax to get some arabic text from server.php file but when i try to create dynamic div and put ajax responce (which is mixture of numbers and arabic text) in it...it doesnt work and shows me some unreadable dark squares like this ����� �� ��� ����
Whats the problem ? how to solve it ?
Thanks in advance
http://www.amitpatil.me/demos/op.png
A: Are you using mysql on that page? if so use:
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $connection);
// Set the active MySQL database
mysql_query("SET NAMES 'utf-8'");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Puzzled using codeigniter on shared hosting server This ones a new on me. I'm transferring a site I made in codeigniter to a godaddy shared hosting server. I can get to the home page with:
http://www.example.com
But when I try to go to the other pages like:
http://www.example.com/about-us/
It throws me this error message:
Not Found
The requested URL /example/index.php/about-us/ was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
If I use:
http://www.example.com/index.php/about-us/
The page appears as clear as day.
I have looked up CI workaround , but my site is more of static pages then dynamic pages.
Overall, my question is, what am I doing wrong and does this have anything to do with having a godaddy shared hosting account?
.htaccess
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
CI Config file
$config['base_url'] = '';
$config['index_page'] = '';
$config['uri_protocol'] = 'QUERY_STRING';
CI autoload file
$autoload['helper'] = array('url');
09-30-2011 Update:
In the .htaccess use:
# Options
Options -Multiviews
Options +FollowSymLinks
#Enable mod rewrite
RewriteEngine On
#the location of the root of your site
#if writing for subdirectories, you would enter /subdirectory
RewriteBase /
#Removes access to CodeIgniter system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#This last condition enables access to the images and css
#folders, and the robots.txt file
RewriteCond $1 !^(index\.php|images|robots\.txt|css)
RewriteRule ^(.*)$ index.php?/$1 [L]
In the CI config file:
$config['index_page'] = "";
$config['uri_protocol'] = "AUTO";
Source: codeigniter.com/wiki/Godaddy_Installaton_Tips
A: It's an .htaccess issue. Try changing your .htaccess file to:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?$1 [L]
A: Your updated .htaccess is right. you need a small change in it.
change below line in your .htaccess file:
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
and in your config.php
$config['uri_protocol'] = 'QUERY_STRING';
A: This is not a godaddy solution, but same error on my WAMP localhost...
I had a simple fix to this, which started to occur after I upgraded my WAMPserver. It had set up a new apache config and it had turned off the rewrite_module.
To fix, I just left click wamperver icon->Apache->Apache Modules->rewrite_module and make sure that is ticked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to average data from 7AM to 7PM of one day in SQL 2005?
Possible Duplicate:
How to average/sum data in a day in SQL Server 2005
I have a set of data which is called Dryer_Data. This data is recorded every minute. I need to average it Dayshift: from 7:40AM to 7:40PM everyday, and Nightshift from 7:40PM to 7:40AM the next day
timestamp Temperature
02/07/2011 12:01:00 AM 1246
02/07/2011 12:02:00 AM 1234
02/07/2011 12:03:00 AM 1387
02/07/2011 12:04:00 AM 1425
02/07/2011 12:05:00 AM 1263
...
02/07/2011 11:02:00 PM 1153
02/07/2011 11:03:00 PM 1348
02/07/2011 11:04:00 PM 1387
02/07/2011 11:05:00 PM 1425
02/07/2011 11:06:00 PM 1223
....
03/07/2011 12:01:00 AM 1226
03/07/2011 12:02:00 AM 1245
03/07/2011 12:03:00 AM 1384
03/07/2011 12:04:00 AM 1225
03/07/2011 12:05:00 AM 1363
I did do something like
For NIGHTShift:
Select CONVERT(char(10), timestamp, 121), average(temperature)
From Drye_data
Group by CONVERT(char(10), timestamp, 121)
Having CONVERT(char(10), timestamp, 121) BETWEEN DATEADD(minute, 40, DATEADD(hour, 19, @selectdate)) AND DATEADD(minute, 40, DATEADD(hour, 31, @selectdate)))
I believe it only gives me data that from 12AM to 7:40AM.
For DAYShift I did:
Select CONVERT(char(10), timestamp, 121), average(temperature)
From Drye_data
Group by CONVERT(char(10), timestamp, 121)
Having CONVERT(char(10), timestamp, 121) BETWEEN DATEADD(minute, 40, DATEADD(hour, 7, @selectdate)) AND DATEADD(minute, 40, DATEADD(hour, 19, @selectdate)))
Of course, it doesn't give me any value.
Or instead of using CONVERT, I used DATEADD(hour, DATEDIFF(hour, 0, timestamp), 0), it gives the answer of every hour (multiple answer for every hour). But I only need 1 result.
Or when I used DATEADD(day, DATEDIFF(day, 0, timestamp), 0), it gives me the same answer with CONVERT.
Please help.... THANK YOU VERY MUCH.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: webservice hosted on iis7.5 has one webmethod invoked every 5 minutes exactly by a "ghost" I am a .Net developer encountering behavior of my ASMX webservice on an IIS 7.5 machine for the first time. It is a staging server so I know I am the only one using it.
Strange behavior as follows:
*
*There are 5 webmethods in this WS meant to be called by web client code
*(to my knowledge) there is no such thing as "default" webmethod for a WS
*each one of the webmethods writes an entry to the Windows event application log upon entry
*the event log entry shows which webmethod called and some other stuff
*if I leave things idle, one of the webmethods gets called every 5 minutes EXACTLY
I've looked briefly at the rapid-fail protection feature thinking this might be it. It is currently enabled and set to 5 minutes but the other aspects of it don't seem to apply.
I changed it to DISABLED and restarted IIS but it still behaves in the above strange way. I am confused what this could be...
[WebMethod(Description = "Search TRIM by parsing CF's WebDrawer string for search criteria")]
public string SearchCF(string trimURL
, string CFSearchString
, string CallerPC = "not specified"
, string RequestorID = "not specified")
{
#if DEBUG
string d = String.Format("SearchCF: trimURL={0}, CFSearchString={1}, Identity={2}, CallerPCname={3}, RequestorIdentity={4} "
, trimURL, CFSearchString, GetUserInfo(), CallerPC, RequestorID);
LogDebuggingInfo(d, 500);
#endif
A: This very strange condition described above was solved by installing the standalone version of .Net Framework 4.0 (64bit version) to this server. This was followed by installing ASP.NET 4.0 by running:
o navigate to C:\Windows\Microsoft.NET\Framework64\v4.0.30319
o in cmd prompt (run as Administrator) execute:
• aspnet_regiis.exe –i
• iisreset
o reconfigure both the client site and the site hosting the webservice to run ASP.NET 4.0 (resulted in significant reduction of the number of entries in web.config
I checked out the other suggestions above before trying the above sequence which fixed it.
A: Answer involves applying upgrades. Please see how I fixed this at:
webservice hosted on iis7.5 has one webmethod invoked every 5 minutes exactly by a "ghost"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Browscap.ini throwing an error when loading PHP (command line - PHP_CLI) I have a cronjob that summarize browser statistics. This cronjob loads data and then use the get_browser() PHP function to parse the browser information.
Here's what I did:
cd /etc/php5/cli/conf.d
me@ubutnu:/etc/php5/cli/conf.d$ sudo wget http://browsers.garykeith.com/stream.asp?Lite_PHP_BrowsCapINI -O browscap.ini
2011-09-30 15:14:18 (890 KB/s) - `browscap.ini' saved [185384/185384]
Then the cronjob run:
php /usr/local/cron/summarizeStats.php --option=browserStats --date=yesterday
and I get this error:
PHP: syntax error, unexpected $end, expecting ']' in /etc/php5/cli/conf.d/browscap.ini on line 51
What am I doing wrong? Thanks
A: There is seemingly right now an error with those browsecap files. They seem to contain unescaped semicolons ";" in the browser spec. You can fix that using this little script:
<?php
$browsecap = file('browscap.ini');
foreach( $browsecap as &$row )
if ( $row[ 0 ] == '[' )
$row = str_replace( ';', '\\;', $row );
file_put_contents( 'fixed_browscap.ini', $browsecap );
A: A little bit late, but there are still problems with using file without modifications. I'm using following script to download and change browscap.ini so it can work on my server.
#!/bin/sh
url="http://browscap.org/stream?q=PHP_BrowsCapINI"
curl -L -o browscap.ini ${url}
sed -I "" -E 's/;/\\;/g' browscap.ini
sed -I "" -E 's/[\\;]{40}/;;;/g' browscap.ini
sed -I "" -E "s/\'/\\\'/g" browscap.ini
mv browscap.ini /usr/local/etc/php/browscap.ini
Explanation
*
*1st sed is escaping every ; with \'
*2nd sed is returning comments to previous state (slow), replacing just 4 or 5 semicolons will cause error because there is some section with string like this (;;;;). This could be optimised with something like ^\; in search part, and just single ; in replace part, need to test that before I put
*3rd sed is escaping single quote used in "Let's encrypt..." sections and in couple other places like this '*'
Don't forget to adjust your browscap.ini finial destination. Also there is no need for Apache or PHP restart after update, so put this script somewhere and setup cron job.
A: sed can be used to escape the semi-colon like so:
sed 's/;/\\\;/g' browscap.ini > browscap_escape.ini
This will catch all the comments as well but you could use sed again to catch those.
As described here github.com/browscap/browscap/issues/119
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to predict when next event occurs based on previous events? Basically, I have a reasonably large list (a year's worth of data) of times that a single discrete event occurred (for my current project, a list of times that someone printed something). Based on this list, I would like to construct a statistical model of some sort that will predict the most likely time for the next event (the next print job) given all of the previous event times.
I've already read this, but the responses don't exactly help out with what I have in mind for my project. I did some additional research and found that a Hidden Markov Model would likely allow me to do so accurately, but I can't find a link on how to generate a Hidden Markov Model using just a list of times. I also found that using a Kalman filter on the list may be useful but basically, I'd like to get some more information about it from someone who's actually used them and knows their limitations and requirements before just trying something and hoping it works.
Thanks a bunch!
EDIT: So by Amit's suggestion in the comments, I also posted this to the Statistics StackExchange, CrossValidated. If you do know what I should do, please post either here or there
A: I'll admit it, I'm not a statistics kind of guy. But I've run into these kind of problems before. Really what we're talking about here is that you have some observed, discrete events and you want to figure out how likely it is you'll see them occur at any given point in time. The issue you've got is that you want to take discrete data and make continuous data out of it.
The term that comes to mind is density estimation. Specifically kernel density estimation. You can get some of the effects of kernel density estimation by simple binning (e.g. count the number events in a time interval such as every quarter hour or hour.) Kernel density estimation just has some nicer statistical properties than simple binning. (The produced data is often 'smoother'.)
That only takes care of one of your problems, though. The next problem is still the far more interesting one -- how do you take a time line of data (in this case, only printer data) and produced a prediction from it? First thing's first -- the way you've set up the problem may not be what you're looking for. While the miracle idea of having a limited source of data and predicting the next step of that source sounds attractive, it's far more practical to integrate more data sources to create an actual prediction. (e.g. maybe the printers get hit hard just after there's a lot of phone activity -- something that can be very hard to predict in some companies) The Netflix Challenge is a rather potent example of this point.
Of course, the problem with more data sources is that there's extra legwork to set up the systems that collect the data then.
Honestly, I'd consider this a domain-specific problem and take two approaches: Find time-independent patterns, and find time-dependent patterns.
An example time-dependent pattern would be that every week day at 4:30 Suzy prints out her end of the day report. This happens at specific times every day of the week. This kind of thing is easy to detect with fixed intervals. (Every day, every week day, every weekend day, every Tuesday, every 1st of the month, etc...) This is extremely simple to detect with predetermined intervals -- just create a curve of the estimated probability density function that's one week long and go back in time and average the curves (possibly a weighted average via a windowing function for better predictions).
If you want to get more sophisticated, find a way to automate the detection of such intervals. (Likely the data wouldn't be so overwhelming that you could just brute force this.)
An example time-independent pattern is that every time Mike in accounting prints out an invoice list sheet, he goes over to Johnathan who prints out a rather large batch of complete invoice reports a few hours later. This kind of thing is harder to detect because it's more free form. I recommend looking at various intervals of time (e.g. 30 seconds, 40 seconds, 50 seconds, 1 minute, 1.2 minutes, 1.5 minutes, 1.7 minutes, 2 minutes, 3 minutes, .... 1 hour, 2 hours, 3 hours, ....) and subsampling them via in a nice way (e.g. Lanczos resampling) to create a vector. Then use a vector-quantization style algorithm to categorize the "interesting" patterns. You'll need to think carefully about how you'll deal with certainty of the categories, though -- if your a resulting category has very little data in it, it probably isn't reliable. (Some vector quantization algorithms are better at this than others.)
Then, to create a prediction as to the likelihood of printing something in the future, look up the most recent activity intervals (30 seconds, 40 seconds, 50 seconds, 1 minute, and all the other intervals) via vector quantization and weight the outcomes based on their certainty to create a weighted average of predictions.
You'll want to find a good way to measure certainty of the time-dependent and time-independent outputs to create a final estimate.
This sort of thing is typical of predictive data compression schemes. I recommend you take a look at PAQ since it's got a lot of the concepts I've gone over here and can provide some very interesting insight. The source code is even available along with excellent documentation on the algorithms used.
You may want to take an entirely different approach from vector quantization and discretize the data and use something more like a PPM scheme. It can be very much simpler to implement and still effective.
I don't know what the time frame or scope of this project is, but this sort of thing can always be taken to the N-th degree. If it's got a deadline, I'd like to emphasize that you worry about getting something working first, and then make it work well. Something not optimal is better than nothing.
This kind of project is cool. This kind of project can get you a job if you wrap it up right. I'd recommend you do take your time, do it right, and post it up as function, open source, useful software. I highly recommend open source since you'll want to make a community that can contribute data source providers in more environments that you have access to, will to support, or time to support.
Best of luck!
A: I really don't see how a Markov model would be useful here. Markov models are typically employed when the event you're predicting is dependent on previous events. The canonical example, of course, is text, where a good Markov model can do a surprisingly good job of guessing what the next character or word will be.
But is there a pattern to when a user might print the next thing? That is, do you see a regular pattern of time between jobs? If so, then a Markov model will work. If not, then the Markov model will be a random guess.
In how to model it, think of the different time periods between jobs as letters in an alphabet. In fact, you could assign each time period a letter, something like:
A - 1 to 2 minutes
B - 2 to 5 minutes
C - 5 to 10 minutes
etc.
Then, go through the data and assign a letter to each time period between print jobs. When you're done, you have a text representation of your data, and that you can run through any of the Markov examples that do text prediction.
A: If you have an actual model that you think might be relevant for the problem domain, you should apply it. For example, it is likely that there are patterns related to day of week, time of day, and possibly date (holidays would presumably show lower usage).
Most raw statistical modelling techniques based on examining (say) time between adjacent events would have difficulty capturing these underlying influences.
I would build a statistical model for each of those known events (day of week, etc), and use that to predict future occurrences.
A: I think the predictive neural network would be a good approach for this task.
http://en.wikipedia.org/wiki/Predictive_analytics#Neural_networks
This method is also used for predicting f.x. weather forecasting, stock marked, sun spots.
There's a tutorial here if you want to know more about how it works.
http://www.obitko.com/tutorials/neural-network-prediction/
A: Think of a markov chain like a graph with vertex connect to each other with a weight or distance. Moving around this graph would eat up the sum of the weights or distance you travel. Here is an example with text generation: http://phpir.com/text-generation.
A: A Kalman filter is used to track a state vector, generally with continuous (or at least discretized continuous) dynamics. This is sort of the polar opposite of sporadic, discrete events, so unless you have an underlying model that includes this kind of state vector (and is either linear or almost linear), you probably don't want a Kalman filter.
It sounds like you don't have an underlying model, and are fishing around for one: you've got a nail, and are going through the toolbox trying out files, screwdrivers, and tape measures 8^)
My best advice: first, use what you know about the problem to build the model; then figure out how to solve the problem, based on the model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Can a texbox click event be captured? Sorry to bother you again on this problem.
The solution I accepted from James Johnson didn't actually work because, it prevents me from entering any data into the textbox which is not what we want.
We would like to diplays the message as a help info only. In other words, we would just like to advise the the user to tick the checkbox if s/he wishes to receive an email.
Below is what I have come up with based on the reference hel from Rob.
This works. The only assistance I would like to get your help on is to get the message to open up in a a new window. THe sample message I am using is Focus Fire.
Can you please help?
THis is the latest code:
<head>
<style type="text/css">span id='1' {display:none;}</style>
<script type="text/javascript" src="jqueryMsg.js"></script>
</head>
<asp:TextBox ID="chck1" runat="server" Width="75px"></asp:TextBox>
<span id='1'>focus fire</span>
<script type="text/javascript">window.onload = (function () {
try{ $("input:text").focus(function () {
$(this).next("span").css('display','inline').fadeOut(1000); });
}catch(e){}});</script>
A: Add the ClientIDMode-attribute to you text box so that JavaScript can access it via the ID without fiddling with the ctrwhateverstrangeidaspnetproduces:
<asp:TextBox ID="instruct" runat="server" Width="75px" ClientIDMode="static">
And then handle the Click-Event (this example is using jQuery, you can use raw JavaScript as well):
$(document).ready(function() {
$('#instruct').click(function() {
alert('.click()-handler called.');
});
});
A: One way is to add it in your codebehind in the Page Load event such as:
instruct.Attributes.Add("onclick", "yourJavascriptFunction();")
The reason for adding in the Page Load event is added Attributes are lost during postback.
A: Look into the onFocus() event handler for JavaScript which will execute a provided function when focusing on the desired textbox, as this method will work if the user clicks or tabs to the desired textbox.
Or you can use focus() in jQuery:
$('#instruct').focus(function(){
// Insert desired response here
alert('Your instructions');
});
A: You could wrap the textbox in a SPAN, and add a onmouseover event to the span.
<span onmouseover="alert('This is a TextBox');"><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></span>
A: Or you could use the onFocus event instead (in case the user tabs to the textarea instead of clicking on it, I'm assuming you want to display your message then as well):
$('textarea').focus(function(){
alert('hi');
}):
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do i get this IF statement working? Fixed a lot of it, getting an error during the myInt declaration, saying it cannot find the parse method. I've added the imports NetBeans mentioned along with it but still nothing. Here's the updated code:
import java.util.Scanner;
import java.lang.Integer;
import java.lang.String;
public class Salary {
int salary;
int sales;
public static void main(String[] args) {
Scanner input = new Scanner ( System.in );
double Salary;
Salary salary = new Salary();
System.out.print( "Please enter the amount of items sold by the employees:");
String sales = input.nextLine();
String salesArray[] = sales.split(" ");
Integer myInt = Integer.parse(salesArray[i]);
for(int i=0; i<salesArray.length; i++){
System.out.print(salesArray[i] + " ");
if (Integer.parseInt(salesArray[i]) <= 0) {
System.out.println("Please enter a value greater than zero");}
else {
Salary = (myInt * 0.09) + 200; }
}
}
}
Thanks a lot for all the help, I really appreciate it.
A: You will likely want to parse the string to an integer before trying to perform mathematical operations on it (less than or equal to, in this case). You may wish to try something like:
import java.util.Scanner;
public class Salary {
double salary;
int sales;
public static void main(String[] args) {
Scanner input = new Scanner ( System.in );
Salary salary = new Salary();
System.out.print( "Please enter the amount of items sold by the employees:");
String sales = input.nextLine();
String salesArray[] = sales.split(" ");
for(int i=0; i<salesArray.length; i++){
Integer myInt = Integer.parse(salesArray[i]);
System.out.print(myInt + " ");
if (myInt <= 0) {
System.out.println("Please enter a value greater than zero");}
else {
salary = (myInt * 0.09) + 200; }
}
}
}
Your solution checked to see if the string was equal to the integer 0, which it never will be, since it is a string being compared to an integer. Even if you checked salesArray[i].equals("0"), this would still only mean it exactly equals "0", disregarding equivalent forms like "000" or "0.0". You also stated in your question that you wanted a "less than or equal to" relation, not an "equals" relation. Doing a string comparison will only be true if the string was exactly "0".
A: The salesArray is array of strings. The equals method should take a string, that is: salesArray[i].equals("0")
But the proper way is to use Integer.parseInt(..)
A: if (Integer.parseInt(salesArray[i]) <= 0 ) {
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android LinearLayout within LinearLayout? I tried to make a simple layout like so
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello" />
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="world" />
</LinearLayout>
Only the first TextView ("hello") is displayed. What am I doing wrong?
A: Make layout_height of inner layout wrap_content.
A: Your second LinearLayout is set to fill_parent in the layout's height. This is causing it to push out everything that's below it that was placed into the first LinearLayout. Change it to wrap_content and it should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Haskell OpenGL won't open in Ubuntu This one is a bit weird, but I will start at the beginning:
As far as I gathered, there are 3 ways to open up an OpenGL window in Haskell: GLUT, GLFW and SDL. I don't want to use GLUT at all, because it forces you to use IORefs and basically work in the IO monad only. So I tried GLFW and made a little thingie on my laptop, which uses Xubuntu with the XFCE desktop system.
Now I was happy and copied it to my desktop, a fairly fresh installed standard Ubuntu with Unity, and was amazed to see nothing. The very same GLFW code that worked fine on the laptop was caught in an endless loop before it opened the window.
Right then I ported it all to SDL. Same code, same window, and SDL crashes with
Main.hs: user error (SDL_SetVideoMode
SDL message: Couldn't find matching GLX visual)
I have checked back with SDLgears, using the same method to open a window, and it works fine. Same with some other 3D application, and OpenGL is enabled fine.
What baffles me is that it works under a XUbuntu but not on an Ubuntu. Am I missing something here? Oh, and if it helps, the window opening function:
runGame w h (Game g) = withInit [InitVideo] $ do
glSetAttribute glRedSize 8
glSetAttribute glGreenSize 8
glSetAttribute glBlueSize 8
glSetAttribute glAlphaSize 8
glSetAttribute glDepthSize 16
glSetAttribute glDoubleBuffer 1
_ <- setVideoMode w h 32 [OpenGL, Resizable]
matrixMode $= Projection
loadIdentity
perspective 45 (fromIntegral w / fromIntegral h) 0.1 10500.0
matrixMode $= Modelview 0
loadIdentity
shadeModel $= Smooth
hint PerspectiveCorrection $= Nicest
depthFunc $= Just Lequal
clearDepth $= 1.0
g
A: This error message is trying to tell you that your combination of bit depths for the color, depth and alpha buffers (a "GLX visual") is not supported. To see which ones you can use on your system, try running glxinfo.
$ glxinfo
...
65 GLX Visuals
visual x bf lv rg d st colorbuffer sr ax dp st accumbuffer ms cav
id dep cl sp sz l ci b ro r g b a F gb bf th cl r g b a ns b eat
----------------------------------------------------------------------------
0x023 24 tc 0 32 0 r y . 8 8 8 8 . . 0 24 8 16 16 16 16 0 0 None
0x024 24 tc 0 32 0 r . . 8 8 8 8 . . 0 24 8 16 16 16 16 0 0 None
0x025 24 tc 0 32 0 r y . 8 8 8 8 . . 0 24 0 16 16 16 16 0 0 None
0x026 24 tc 0 32 0 r . . 8 8 8 8 . . 0 24 0 16 16 16 16 0 0 None
0x027 24 tc 0 32 0 r y . 8 8 8 8 . . 0 24 8 0 0 0 0 0 0 None
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: A way to pass in a constant list into a cmake macro? I have a CMake macro like so:
macro( foo a b )
list( FIND b ${a} is_found )
endmacro()
And I try to call it like so:
foo( "test" foo;bar;test )
This doesn't work. Also this does not work:
foo( "test" "foo;bar;test" )
In all cases I get is_found equal to -1, when in fact it should have been found. How can I pass in a list on-the-fly like I want to?
A: This happens because parameters of a macro and special values such as ARGN are not variables in the usual CMake sense. They are string replacements much like the c preprocessor would do with a macro.
You can copy input arguments to the variable and next pass that variable to list find:
macro( foo a )
set( b "${ARGN}" )
list( FIND b "${a}" is_found )
endmacro()
As result all the following variants work:
foo(test foo bar test foo )
foo("test" foo bar test foo )
foo(test foo;bar;test;foo )
foo("test" foo;bar;test;foo )
foo(test "foo;bar;test;foo" )
foo("test" "foo;bar;test;foo" )
Update, more generic version - search in several lists separated by "NEXTLIST" word:
macro( foo a )
set( is_found )
set( foo_current_list )
foreach( arg ${ARGN} )
if( arg STREQUAL "NEXTLIST" )
list( FIND foo_current_list "${a}" foo_is_found )
list( APPEND is_found ${foo_is_found} )
set( foo_current_list )
else()
list( APPEND foo_current_list ${arg} )
endif()
endforeach()
list( FIND foo_current_list "${a}" foo_is_found )
list( APPEND is_found ${foo_is_found} )
unset( foo_is_found )
unset( foo_current_list )
endmacro()
foo (test bar bar bar NEXTLIST foo test NEXTLIST test test x test)
message( "${is_found}" ) #-1;1;0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Flask's @before_request executes more than once I added an app.logger.error('test') inside my @app.before_request and noticed that there are up to 8 lines of test in my log per request, even if it's just abort(500). I just can't seem to find out why, what could cause this?
A: If you run with app.debug = True and serve media files (images, css, js etc.) from Flask, they also count as full requests. If that is not the case, then please provide some more information about your setup.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to make sbt `console` use -Yrepl-sync? New in Scala 2.9.1 is the -Yrepl-sync option, which prevents each REPL line from being run in a new thread:
scala -Yrepl-sync
When I run console from sbt, how do I have it pass this in?
A: Short answer:
set scalacOptions in (Compile, console) += "-Yrepl-sync"
How to discover this:
~/code/scratch/20110930 sbt
[info] Loading global plugins from /Users/jason/.sbt11/plugins
[info] Set current project to default-9c7c16 (in build file:/Users/jason/code/scratch/20110930/)
> inspect console
[info] Task: Unit
[info] Description:
[info] Starts the Scala interpreter with the project classes on the classpath.
[info] Provided by:
[info] {file:/Users/jason/code/scratch/20110930/}default-9c7c16/compile:console
[info] Dependencies:
[info] compile:compilers(for console)
[info] compile:full-classpath
[info] compile:scalac-options(for console)
[info] compile:initial-commands(for console)
[info] compile:streams(for console)
[info] Delegates:
[info] compile:console
[info] *:console
[info] {.}/compile:console
[info] {.}/*:console
[info] */compile:console
[info] */*:console
[info] Related:
[info] test:console
> set scalaVersion := "2.9.1"
[info] Reapplying settings...
[info] Set current project to default-9c7c16 (in build file:/Users/jason/code/scratch/20110930/)
> set scalacOptions in (Compile, console) += "-Yrepl-sync"
[info] Reapplying settings...
[info] Set current project to default-9c7c16 (in build file:/Users/jason/code/scratch/20110930/)
> console
[info] Updating {file:/Users/jason/code/scratch/20110930/}default-9c7c16...
[info] Done updating.
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :power
** Power User mode enabled - BEEP BOOP SPIZ **
** :phase has been set to 'typer'. **
** scala.tools.nsc._ has been imported **
** global._ and definitions._ also imported **
** Try :help, vals.<tab>, power.<tab> **
scala> settings
res1: scala.tools.nsc.Settings =
Settings {
-classpath = /Users/jason/code/scratch/20110930/target/scala-2.9.1/classes:/Users/jason/.sbt11/boot/scala-2.9.1/lib/scala-compiler.jar:/Users/jason/.sbt11/boot/scala-2.9.1/lib/jansi.jar:/Users/jason/.sbt11/boot/scala-2.9.1/lib/jline.jar
-d = .
-Yrepl-sync = true
-encoding = UTF-8
-bootclasspath = /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsfd.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar:/System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/Resources/Java/JavaRuntimeSupport.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/ui.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/laf.jar:/System/Librar...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: @Html.DropDownList width Q: How to set width for @Html.DropDownList (and not in css)?
@Html.DropDownList("ListId", String.Empty, new {style="width: 250px;"}) @* no go!*@
A: The second argument of the DropDownList helper must be an IEnumerable<SelectListItem>. You are passing a string (an empty one to be more precise). So in order to use this helper you will have to respect its signature:
@Html.DropDownList(
"ListId",
Enumerable.Empty<SelectListItem>(),
new { style = "width: 250px;" }
)
Obviously generating an empty dropdown list is of little use. You probably have a view model (you should by the way) that you want to use to bind to:
@Html.DropDownList(
"ListId",
Model.MyList,
new { style = "width: 250px;" }
)
and of course because you have a view model you should prefer to use the DropDownListFor helper:
@Html.DropDownListFor(
x => x.ListId,
Model.MyList,
new { style = "width: 250px;" }
)
and finally to avoid cluttering your HTML with styles you should use an external CSS:
@Html.DropDownListFor(
x => x.ListId,
Model.MyList,
new { @class = "mycombo" }
)
where in your external CSS you would define the .mycombo rule:
.mycombo {
width: 250px;
}
Now you have what I consider a proper code.
A: You should use the View Model approach. However the lazy way out is just to give the 2nd parameter a null.
@Html.DropDownList("ListId", null, new {style="width: 250px;"})
A: @Html.DropDownListFor(model => model.Test,
new SelectList(new List<YourNamespace.Modelname>(), "Id", "Name"),
null, new { @id = "ddlTest", @style="width: 250px;" })
A: There is a jquery technique that allows you to set the width without having to deal with the @Html.DropDownList constructor.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#ListId").width(300);
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Java constructing an http request message I asked a similar question in another thread but I think I'm just having trouble getting the syntax right at this point. I basically want to open a socket in Java, send a HTTP request message to get the header fields of a specific web page. My program looks like this so far:
String server = "www.w3.org";
int port = 80;
String uri = "/Protocols/rfc2616/rfc2616-sec5.html#sec5.1"
Socket socket = new Socket(server, port);
PrintStream output = new PrintStream(socket.getOutputStream());
BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output.println("HEAD " + uri + " HTTP/1.1");
//String response = "";
String line = "";
while((line = socketInput.readLine()) != null){
System.out.println(line);
}
socketInput.close();
socket.close();
It doesn't really work. Or it doesn't work for all websites. If someone could just tell me the immediate problems with what I'm doing, that would be great. Thank you!
A: Change
output.println("HEAD " + uri + " HTTP/1.1");
to
output.println("HEAD " + uri + " HTTP/1.1");
output.println("Host: " + server);
output.println();
You have to send the Host header because usually there are more than one virtual host on one IP address. If you use HTTP/1.0 it works without the Host header.
A: I would use some higher-level component, like HttpURLConnection (see here) or apache http components.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery shoutbox IE error Hey I have some jquery/ajax code for a shoutbox and the problem I am having is that in IE when I had the form tags around the input message and submit button in the html code, upon pressing the enter key in the message box it was reloading the page, this was not occuring in other browsers, so I removed the form because it was not needed, and the enter key is now submitting the message in IE but not in chrome or firefox. Is there a way I can have both an onclick event and enter event together to correct this? at the moment once the button is clicked the button is disabled for 2 seconds and then renabled, I need this to also happen if the enter button is pressed.
I know I have a lot of inline css for the shoutout box but its just a testing version at the moment, I will tidy that up once its completed.
Any help is much appreciated.
I had the form tag like so
<form method="POST" action=""/>
<div id="shoutout" style="position:absolute; height:auto; overflow-x:hidden; overflow-y:hidden; float:right; right:10px; background-color:#121212; color:#FFFFFF; font-size:14px; width:305px; padding-left:1px; padding-right:1px; padding-bottom:1px; font-family: Arial, Helvetica, sans-serif;">
<h2>Shout Out!</h2>
<strong>Message:</strong>
<input type="text" id="message" name="message"/>
<input type="submit" id="submit" value="Submit"/>
<div id="messagecontainer" style="position:relative; height:240px; overflow-x:hidden; overflow-y:auto; background-color:#F5F5F5; color: #F6221D; font-size:12px; width:305px; margin-top:5px;">
<div id="shoutmessages" style="position:relative; word-wrap: break-word; padding-left:5px; width:auto; height:auto; overflow-y:hidden; overflow-x:hidden;">
</div>
</div>
</div>
//JQUERY AJAX CODE BELOW
<script type="text/javascript">
$(function(){
refresh_shoutbox();
setInterval("refresh_shoutbox()", 10000);
var running = false;
$("#message").keypress(function(e){
if (e.which == 13 && running === true){
return false;
}
});
$("#submit").click(function(){
if ($("#message").val() != ''){
running = true;
$("#submit").attr("disabled","disabled");
setTimeout(function(){
$("#submit").removeAttr("disabled")
running = false;
}, 2000);
}else{
return false;
}
var name = $("#name").val();
var message = $("#message").val();
var data = 'name=' + name + '&message=' + message;
$.ajax({
type: "POST",
url: "shout.php",
data: data,
success: function(html){
$("#shoutmessages").slideToggle(0, function(){
$(this).html(html).slideToggle(0);
$("#message").val("");
});
}
});
return false;
});
});
function refresh_shoutbox(){
var data = 'refresh=1';
$.ajax({
type: "POST",
url: "shout.php",
data: data,
success: function(html){
$("#shoutmessages").html(html);
}
});
}
A: Since all this is done via AJAX anyway, you may find it easier just to not include the <form> element at all.
That way, you avoid all of the annoying browser-specific behaviors that occur with form elements in a <form>- like automatically submitting forms if a <button> is pressed.
You said when you removed it in the other browsers, the enter key didn't work- did you receive any errors from the Chrome or Safari JS debug console, for example?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ODP.NET doesn't work System.Data.OracleClient does We are switching from the obsolete System.Data.OracleClient. I have switched all the references in the ASP.NET 2.0 code, however when I try to access the database server using ODP.NET calls I get ORA-12154: TNS:could not resolve the connect identifier specified. This works when I use System.Data.OracleClient on the same machine. Any suggestions about what is going wrong here?
A: You can avoid a dependency on Tnsnames.ora altogether, and go for the "independent" connection string in format:
Data Source =(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID))); User Id =myUsername; Password =myPassword;
BTW, you can look at connectionstrings.com/oracle for a quick, in-your-face list of supported connection string formats.
A: It sounds like your client install doesn't have your TNS names setup correctly. If you just installed ODP.NET on this machine, you probably just installed another Oracle client, and have yet to configure it.
A: Copy the TNSNAMES.ORA from the /NETWORK/ADMIN directory in the Oracle home where the OracleClient was installed and copy over to the new /NETWORK/ADMIN directory where ODP.NET is installed.
http://www.oracle.com/technetwork/topics/dotnet/odt-faq-085407.html#ORA-12154:_TNS:could_not_resolve_the
Christian Shay
Oracle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: overflow-y for ul, scroll down the list I have a problem with my menu. I only want four menu items to appear at any time, meaning that if there’s an overflow, it’ll be clipped, and the user will have to scroll down.
I tried setting overflow-y, hoping to see it get clipped, but instead, a horizontal scroll bar appears.
HTML
<link rel="stylesheet" href='http://donysukardi.com/ltw/css/blueprint/screen.css' type="text/css" media="screen, projection" />
<link rel="stylesheet" href='http://donysukardi.com/ltw/css/blueprint/print.css' type="text/css" media="print" />
<div class="container">
<div id="menu">
<ul>
<li><a href="#" id="profile">profile</a>
<ul>
<li><a href="#!profile/overview.html" id="overview">overview</a></li>
<li><a href="#" id="partners">partners</a>
<ul>
<li><a href="#!profile/partners/lim.html" id="lim">Lim Hong Lian</a></li>
<li><a href="#!profile/partners/teo.html" id="teo">Teo Su Seam</a></li>
<li><a href="#!profile/partners/marina.html" id="marina">Marina Baracs</a></li>
</ul>
</li>
<li><a href="#" id="associates">associates</a>
<ul>
<li><a href="#!profile/associates/yang.html" id="yang">Jocelyn Yang Liwan</a></li>
<li><a href="#!profile/associates/tsai.html" id="tsai">Tsai Ming Ming</a></li>
</ul>
</li>
<li><a href="#!profile/team.html" id="team">team</a></li>
</ul>
</li>
<li><a href="#">projects</a>
<ul>
<li><a href="#">featured projects</a>
<ul>
<li><a href="#">HELLO</a></li>
</ul>
</li>
<li><a href="#">project list</a>
<ul>
<li><a href="#">current</a>
<ul>
<li><a href="#!project/current/all">all</a></li>
<li><a href="#!project/current/urban">urban</a></li>
<li><a href="#!project/current/resort">resort</a></li>
<li><a href="#!project/current/spa">spa</a></li>
<li><a href="#!project/current/restaurant">restaurant</a></li>
<li><a href="#!project/current/restaurant">others</a></li>
</ul>
</li>
<li><a href="#">completed</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">publications</a>
<ul>
<li><a href="#">books</a></li>
<li><a href="#">magazines</a></li>
</ul>
</li>
<li><a href="#">contacts</a>
<ul>
<li><a href="contact_singapore.html">Singapore</a></li>
<li><a href="contact_milan.html">Milan</a></li>
<li><a href="contact_beijing.html">Beijing</a></li>
</ul>
</li>
</ul>
</div>
</div>
CSS
#menu ul
{
list-style-type:none;
position:absolute;
padding: 5px 0px;
margin:0px;
width:100px;
}
#menu
{
position:relative;
border-top-color:#afafaf;
border-top-style:solid;
border-top-width: thin;
font-size: 11px;
margin-top:5px;
height:80px;
}
#menu ul ul
{
display:none;
position:absolute;
padding:5px 0px;
left:150px;
top:0px;
height:80px;
}
Javascript (jQuery)
$(document).ready(function(){
$('#menu ul li a').click(function(){
if(!$(this).hasClass('current'))
{
var relatives = $(this).parent().siblings();
relatives.find('ul').css('left',150).hide();
relatives.find('.current').removeClass('current');
$(this).siblings().animate({'left':'-=20', 'opacity':'toggle'},'slow');
$(this).addClass('current');
if($(this).attr("href") != "#"){
var url = $(this).attr("href").split('#!')[1];
$('#content').slideUp('slow', function(){$(this).load(url, function(){$(this).slideDown('slow')});})
window.location = base_url+url;
}
}
$(this).parent().siblings().find('.black').removeClass('black');
$(this).addClass('black');
return false;
});
})
Demo on JS Fiddle.
Here is a screenshot: I only want “all”, “urban”, “resort”, and “spa” to appear initially.
A: Not sure you can limit the number of elements, but you can set the height and set the overflow to auto, so if it's higher then specified width there will be a scrollbar.
<ul class="inner-ul">
<li><a href="#!project/current/all">all</a></li>
<li><a href="#!project/current/urban">urban</a></li>
<li><a href="#!project/current/resort">resort</a></li>
<li><a href="#!project/current/spa">spa</a></li>
<li><a href="#!project/current/restaurant">restaurant</a></li>
<li><a href="#!project/current/restaurant">others</a></li>
</ul>
.inner-ul {
height:50px;
overflow-y: auto;
}
A: Hard to tell from the question and fiddle (and I can't see the image) but I think you need
overflow-x: auto;
Here's a good resource for overflow: http://www.brunildo.org/test/Overflowxy2.html
A: Change height to 70px and add "overflow:auto;" to your menu css statement
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Create_table method/block I come from a java/c++ background and I just started learning Ruby. I am having problems understanding blocks attached to methods. This is a method used to migrate a database.
create_table :model_names do |t|
t.string :name
t.string :address
t.timestamps
end
My question is: when I use the rake db:migrate command. Does that call the create_table method and pass a TableDefinition object to it, which I grab as |t| and set that object attributes in my block?
A: When you pass a block to a method, as is the case in the example here, it is up to the method to decide how and if that block is used. You will need to read the documentation and/or source code of the method to understand what parameters your block will need, if any.
In the case of create_table, an object is prepared and passed to you by the create_table method itself. rake and the associated task have nothing to do with it at this point, they are only used as a launch mechanism.
It's important to keep in mind that Ruby blocks can be called zero or more times, either immediately or in the future. This means you can't be sure if your block will be called right away, later on, or never, or how many times it will be called. The only expectation you can have is established by the method you send the block to.
You can even pass blocks to methods that don't want them where nothing will happen since that method never exercises your block with a yield.
Blocks can be a bit confusing at first unless you come from a language that has a similar construct. JavaScript programmers will be familiar with passing in function objects, which is basically all you're doing here, though in Ruby terms it's a Proc that's being sent in as an implicit argument.
In a more JavaScript flavored example, this would look like:
create_table('model_names', function(t) {
t.string('name');
t.string('address');
t.timestamps();
});
Spelled out like this it's obvious you're simply sending in a function, and it is up to the create_table function to execute it. Ruby is structured in such a way that at a glance it might seem like that block gets executed right away, but there is a big difference between declaring a block with do ... end and begin ... end.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to connect to a device on network with c# I have a device on my network that controls a piece of hardware. I can control it with my browser like: http://xx.xx.xx.xxx/setvalue.html?Address_Value_Array={someValueToSendToDevice}
I do not need any form of a response from the device. I'm wondering what is the usual way to accomplish this sort of thing in c#. Thank you.
A: I would just use a System.Net.WebClient:
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.DownloadString("http://xx.xx.xx.xxx/setvalue.html?Address_Value_Array={someValueToSendToDevice}");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Git --bare ... Why does fetch not always show the most recent commits? I have a few GIT repos that I mirrored locally to show up in my JIRA instance, but I have noticed some (to me) strange behaviour.
I have a repo, we will call this "myrepo". If I do a git clone, and git pull, I always get the most recent commits.
However, when I do a git clone --bare, when I do a "git fetch" from my bare repository, I do not get the newer commits showing up in my "git log".. Why is this?
A: The fetch isn't moving your HEAD. Therefor, the log is only showing you the history from where HEAD was before the fetch. Try git log -all. This will show you the history of all branches, including the remote one you fetched in.
Also git log remoteBranchName will work if you know the name of the remote branch you are interested in.
If you want all everything to be in sync with the remote master, you have to run either
git fetch, then git merge or just run git pull which is the same as running fetch and merge. If you prefer a specific branch - ex. master - git pull origin master
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I can't seem to figure out how to center align my table <table border="0" align="center">
<tbody>
<tr>
<td>Cell1</td>
<td>Cell1</td>
</tr>
<tr>
<td>Cell1</td>
<td>Cell1</td>
</tr>
<tr>
<td>Cell1</td>
<td>Cell1</td>
</tr>
<tr>
<td>Cell1</td>
<td>Cell1</td>
</tr>
</tbody>
</table>
I am not good with coding. I've tried but cannot figure it out. Your help would be greatly appreciated.
A: Try this:
<div style="width: 100%; text-align: center;">
<!-- Your table here -->
</div>
A: // CSS:
#container {
text-align:center; // needed if you expect IE 5
}
.centered {
margin:0px auto; // this sets left/right margin to auto and
// centers the element
}
// HTML:
<div id="container">
<table class="centered" border="0">
...
</table>
</div>
Or if you want to style inline:
<div style="text-align:center;">
<table style="margin:0px auto;" border="0">
...
</table>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Model with recursive self relation in Django's admin Say we have a model with two self-recursive relations:
class Article(Item): # Item in this case is an abstract class
date = models.DateField()
parent = models.OneToOneField('self', null=True, blank=True)
subatricles = models.ForeignKey('self', null=True, blank=True, related_name='subs')
Article acts here as a node - it can has many children (if supplied) and one parent (if any). However, when I register my model in Django's admin my subatricles are shown as "one-to-one' - in both cases there are choice boxes but in the latter multiple values cannot be selected, though.
How can I add children via the admin pane to this Article object and later list them?
What I would like to have is this:
instead of normal drop-down.
Thanks.
A: You only need one field parent with subarticles as related_name to provide the reverse lookup:
class Article(Item): # Item in this case is an abstract class
date = models.DateField()
parent = models.ForeignKey('self', null=True, blank=True, related_name='subarticles')
so if you have an article object and you want to get its parent, use:
article.parent
if you want to get its children, you use:
article.subarticles
In the admin interface to show the subarticles the easiest way is to use the InlineModelAdmin:
class ArticleInline(admin.StackedInline):
model = Article
class ArticleAdmin(admin.ModelAdmin):
inlines = [
ArticleInline,
]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: django querysets + memcached: best practices Trying to understand what happens during a django low-level cache.set()
Particularly, details about what part of the queryset gets stored in memcached.
First, am I interpreting the django docs correctly?
*
*a queryset (python object) has/maintains its own cache
*access to the database is lazy; even if the queryset.count is 1000,
if I do an object.get for 1 record, then the dbase will only be
accessed once, for that 1 record.
*when accessing a django view via apache prefork MPM, everytime that
a particular daemon instance X ends up invoking a particular view that includes something
like "tournres_qset = TournamentResult.objects.all()",
this will then result, each time, in a new tournres_qset object
being created. That is, anything that may have been cached internally
by a tournres_qset python object from a previous (tcp/ip) visit,
is not used at all by a new request's tournres_qset.
Now the questions about saving things to memcached within the view.
Let's say I add something like this at the top of the view:
tournres_qset = cache.get('tournres', None)
if tournres_qset is None:
tournres_qset = TournamentResult.objects.all()
cache.set('tournres', tournres_qset, timeout)
# now start accessing tournres_qset
# ...
What gets stored during the cache.set()?
*
*Does the whole queryset (python object) get serialized and saved?
*Since the queryset hasn't been used yet to get any records, is this
just a waste of time, since no particular records' contents are actually
being saved in memcache? (Any future requests will get the queryset
object from memcache, which will always start fresh, with an empty local
queryset cache; access to the dbase will always occur.)
*If the above is true, then should I just always re-save the queryset
at the end of the view, after it's been used throughout the vierw to access
some records, which will result in the queryset's local cache to get updated,
and which should always get re-saved to memcached? But then, this would always
result in once again serializing the queryset object.
So much for speeding things up.
*Or, does the cache.set() force the queryset object to iterate and
access from the dbase all the records, which will also get saved in
memcache? Everything would get saved, even if the view only accesses
a subset of the query set?
I see pitfalls in all directions, which makes me think that I'm
misunderstanding a whole bunch of things.
Hope this makes sense and appreciate clarifications or pointers to some
"standard" guidelines. Thanks.
A: Querysets are lazy, which means they don't call the database until they're evaluated. One way they could get evaluated would be to serialize them, which is what cache.set does behind the scenes. So no, this isn't a waste of time: the entire contents of your Tournament model will be cached, if that's what you want. It probably isn't: and if you filter the queryset further, Django will just go back to the database, which would make the whole thing a bit pointless. You should just cache the model instances you actually need.
Note that the third point in your initial set isn't quite right, in that this has nothing to do with Apache or preforking. It's simply that a view is a function like any other, and anything defined in a local variable inside a function goes out of scope when that function returns. So a queryset defined and evaluated inside a view goes out of scope when the view returns the response, and a new one will be created the next time the view is called, ie on the next request. This is the case whichever way you are serving Django.
However, and this is important, if you do something like set your queryset to a global (module-level) variable, it will persist between requests. Most of the ways that Django is served, and this definitely includes mod_wsgi, keep a process alive for many requests before recycling it, so the value of the queryset will be the same for all of those requests. This can be useful as a sort of bargain-basement cache, but is difficult to get right because you have no idea how long the process will last, plus other processes are likely to be running in parallel which have their own versions of that global variable.
Updated to answer questions in the comment
Your questions show that you still haven't quite grokked how querysets work. It's all about when they are evaluated: if you list, or iterate, or slice a queryset, that evaluates it, and it's at that point the database call is made (I count serialization under iterating, here), and the results stored in the queryset's internal cache. So, if you've already done one of those things to your queryset, and then set it to the (external) cache, that won't cause another database hit.
But, every filter() operation on a queryset, even one that's already evaluated, is another database hit. That's because it's a modification of the underlying SQL query, so Django goes back to the database - and returns a new queryset, with its own internal cache.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: AsyncTask and Background Thread when to Use What is the difference between AsyncTask and Background Thread. Which should be preferred or any scenarios to use these?
What I am trying to achieve right now is Will be sending request to server when user goes on a specific activity and display the data received on the same activity? The data received may be images or some text which I need to display in TextView or ListView.
A: There is no difference. A AsyncTask is a background thread. It's an implementation which helps you to perform tasks in background. Read its documentation and you will see ;-)
A: An AsyncTask is basically a wrapper class for a Java thread. It provides a convenient mechanism for executing one-time blocking operations. Background threads are more useful when you have a task that's long-lasting and/or permanent to the entire course of the Activity (although I suppose you could implement AsyncTask to be permanent and just update the UI through the progress mechanism).
In your case, I would implement an AsyncTask. Do your request in doInBackground() then update the UI in onPostExecute().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: php multidimensional sort I have an a couple of arrays like so.
Array
(
[state] => Array
(
[0] => WA
[1] => CA
[2] => CA
[3] => NV
[4] => MO
[5] => CA
[6] => CA
[7] => CA
[8] => CT
[9] => FL
[10] => FL
[11] => ID
[12] => ID
[13] => IN
[14] => MN
[15] => MN
[16] => NE
[17] => NY
[18] => TX
[19] => TX
[20] => WI
)
[counties] => Array
(
[0] => King, Snohomish
[1] => Contra Costa
[2] => Los Angeles
[3] => Clark
[4] => Jackson
[5] => Tulare
[6] => Sacramento
[7] => Riverside
[8] => New Haven
[9] => Pinellas
[10] => Lake
[11] => Canyon
[12] => Ada
[13] => Tippecanoe, White, Carroll
[14] => Crow Wing, Cass
[15] => Blue Earth
[16] => Douglas
[17] => Rockland
[18] => Webb
[19] => Harris
[20] => Waukesha, Milwaukee, Washington
)
[zipcodes] => Array
(
[0] => 98004, 98005, 98006, 98007, 98008, 98011, 98012, 98102, 98105, 98112, 98136, 98025, 98033, 98034, 98083
[1] => 94530, 94804, 94805, 94803, 94806, 94564, 94547
[2] => 91381, 91384, 91354, 91355, 91321, 91387, 91351, 91390, 91350
[3] => 89002, 89009, 89011, 89012, 89014, 89015, 89016, 89128, 89048, 89052, 89053, 89060, 89061, 89074, 94588, 89102, 89105, 89108, 89109, 89111, 89112
[4] => 64055, 64056, 64057, 64052, 64064, 64050, 64058, 64014, 64015, 64029, 64063, 64081, 64082, 64086, 64133
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
[10] =>
[11] =>
[12] =>
[13] =>
[14] =>
[15] =>
[16] =>
[17] =>
[18] =>
[19] =>
[20] =>
)
)
I am trying to sort by zipcodes then by state then by counties. The problem I am having is getting the zipcodes to display in ascending order by the first zip in the string. So the order would be
64055, 64056, ...
89002, 89009, ...
91381, 91384, ...
94530, 94804, ...
Here are my current results.
WA,TL-WA-150,150,King, Snohomish,98004, 98005, 98006, 98007, 98008, 98011, 98012, 98102, 98105, 98112, 98136, 98025, 98033, 98034, 98083
CA,HD-CA-125,125,Contra Costa,94530, 94804, 94805, 94803, 94806, 94564, 94547
CA,DH-CA-125,150,Los Angeles,91381, 91384, 91354, 91355, 91321, 91387, 91351, 91390, 91350
NV,CM1-NV-150,150,Clark,89002, 89009, 89011, 89012, 89014, 89015, 89016, 89128, 89048, 89052, 89053, 89060, 89061, 89074, 94588, 89102, 89105, 89108, 89109, 89111, 89112
MO,CJ-MO-150,150,Jackson,64055, 64056, 64057, 64052, 64064, 64050, 64058, 64014, 64015, 64029, 64063, 64081, 64082, 64086, 64133
CA,GR6-CA-150,150,Tulare,
CA,SSJ-CA-150,150,Sacramento,
CA,LM1-CA-150,150,Riverside,
CT,TAMRM-CT-150,150,New Haven,
FL,GG-FL-150,150,Pinellas,
My question is how can I get the zipcodes to sort ascending?
I am using this for sorting right now.
sortDataSet($difarray, 'zipcodes', SORT_DESC, SORT_NUMERIC, 'state', SORT_ASC, SORT_STRING,'counties', SORT_DESC, SORT_STRING);
function sortDataSet(&$dataSet) {
$args = func_get_args();
$callString = 'array_multisort(';
$usedColumns = array();
for($i = 1, $count = count($args); $i < $count; ++$i) {
switch(gettype($args[$i])) {
case 'string':
$callString .= '$dataSet[\''.$args[$i].'\'], ';
array_push($usedColumns, $args[$i]);
break;
case 'integer':
$callString .= $args[$i].', ';
break;
default:
throw new Exception('expected string or integer, given '.gettype($args[$i]));
}
}
foreach($dataSet as $column => $array) {
if(in_array($column, $usedColumns)) continue;
$callString .= '$dataSet[\''.$column.'\'], ';
}
eval(substr($callString, 0, -2).');');
}
A: So I am assuming that you have an array with three arrays, of states, counties, and zipcodes.
I also assume that your array containing these arrays is called $data, so substitute the name of your array there.
I believe your original array is setup like this.
$data = array(
'state' => array
(
'WA',
'CA',
'CA',
'NV',
'MO',
'CA',
'CA',
'CA',
'CT',
'FL',
'FL',
'ID',
'ID',
'IN',
'MN',
'MN',
'NE',
'NY',
'TX',
'TX',
'WI'
),
'counties' => array
(
'King, Snohomish',
'Contra Costa',
'Los Angeles',
'Clark',
'Jackson',
'Tulare',
'Sacramento',
'Riverside',
'New Haven',
'Pinellas',
'Lake',
'Canyon',
'Ada',
'Tippecanoe, White, Carroll',
'Crow Wing, Cass',
'Blue Earth',
'Douglas',
'Rockland',
'Webb',
'Harris',
'Waukesha, Milwaukee, Washington'
),
'zipcodes' => array
(
'98004, 98005, 98006, 98007, 98008, 98011, 98012, 98102, 98105, 98112, 98136, 98025, 98033, 98034, 98083',
'94530, 94804, 94805, 94803, 94806, 94564, 94547',
'91381, 91384, 91354, 91355, 91321, 91387, 91351, 91390, 91350',
'89002, 89009, 89011, 89012, 89014, 89015, 89016, 89128, 89048, 89052, 89053, 89060, 89061, 89074, 94588, 89102, 89105, 89108, 89109, 89111, 89112',
'64055, 64056, 64057, 64052, 64064, 64050, 64058, 64014, 64015, 64029, 64063, 64081, 64082, 64086, 64133',
'','','','','','','','','','','','','','','',''
));
So, this is my solution:
//make our own array with state, counties, and zips living together.
$sortData=array();
foreach($data['state'] as $key =>$thisState){
//first sort the zipcode string itself.
$zipcodeArray = explode(", ",$data['zipcodes'][$key]);
sort($zipcodeArray,SORT_NUMERIC);
$zipcodeString = implode(", ",$zipcodeArray);
$pusharray=array('state'=>$thisState,'county'=>$data['counties'][$key],'zipcode'=>$zipcodeString);
array_push($sortData,$pusharray);
}//foreach
$states=array();
$counties=array();
$zipcodes=array();
foreach ($sortData as $key => $row) {
$states[$key] = $row['state'];
$counties[$key] = $row['county'];
$zipcodes[$key] = $row['zipcode'];
}//
$index=0;
array_multisort($zipcodes, SORT_NUMERIC, SORT_ASC, $states, SORT_ASC, $counties, SORT_ASC, $sortData);
function blank($var)
{
if (empty($var['zipcode'])){return true;}else{return false;}
}
function zipcodeString($var)
{
if (!(empty($var['zipcode']))){return true;}else{return false;}
}
$noZipcodeChunk=(array_filter($sortData, "blank"));
$zipcodeChunk=(array_filter($sortData, "zipcodeString"));
$finalArray = array_merge($zipcodeChunk,$noZipcodeChunk);
foreach ($finalArray as $datum){
echo $datum['state'].' '.$datum['county'].' '.$datum['zipcode'].'<br>';
}
And I think this is what you area looking for:
MO Jackson 64014, 64015, 64029, 64050, 64052, 64055, 64056, 64057, 64058, 64063, 64064, 64081, 64082, 64086, 64133
NV Clark 89002, 89009, 89011, 89012, 89014, 89015, 89016, 89048, 89052, 89053, 89060, 89061, 89074, 89102, 89105, 89108, 89109, 89111, 89112, 89128, 94588
CA Los Angeles 91321, 91350, 91351, 91354, 91355, 91381, 91384, 91387, 91390
CA Contra Costa 94530, 94547, 94564, 94803, 94804, 94805, 94806
WA King, Snohomish 98004, 98005, 98006, 98007, 98008, 98011, 98012, 98025, 98033, 98034, 98083, 98102, 98105, 98112, 98136
CA Riverside
CA Sacramento
CA Tulare
CT New Haven
FL Lake
FL Pinellas
ID Ada
ID Canyon
IN Tippecanoe, White, Carroll
MN Blue Earth
MN Crow Wing, Cass
NE Douglas
NY Rockland
TX Harris
TX Webb
WI Waukesha, Milwaukee, Washington
A: Here is code that might help you
$array = array(
'zipcodes' => array(
'98004, 98005, 98006, 98007, 98008, 98011, 98012, 98102, 98105, 98112, 98136, 98025, 98033, 98034, 98083',
'94530, 94804, 94805, 94803, 94806, 94564, 94547',
'91381, 91384, 91354, 91355, 91321, 91387, 91351, 91390, 91350',
'89002, 89009, 89011, 89012, 89014, 89015, 89016, 89128, 89048, 89052, 89053, 89060, 89061, 89074, 94588, 89102, 89105, 89108, 89109, 89111, 89112',
'64055, 64056, 64057, 64052, 64064, 64050, 64058, 64014, 64015, 64029, 64063, 64081, 64082, 64086, 64133',
),
'state' => array(
'WA', 'CA', 'FL'
),
'counties' => array(
'Lake', 'King, Snohomish'
)
);
foreach ($array as $key => $value) {
sort($array[$key]); // sort array from lowest to highest http://nz.php.net/manual/en/function.sort.php
// or reverse sort using arsort http://nz.php.net/manual/en/function.arsort.php
}
You can use the $key to decide which sort function to use
foreach ($array as $key => $value) {
if ($key == 'zipcodes') {
sort($array[$key]);
} else {
arsort($array[$key]);
}
}
A: I have used this class: http://www.php.net/manual/en/function.uksort.php#71152
It's easy to use and easily extended for customization.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can't initialize struct with nested pointers to other structs I'm using a third party library which defines this struct:
typedef struct
{
unsigned short nbDetectors;
//! structure of detector status
struct DetectorStatus
{
unsigned int lastError; //< last detector internal error
float temperature; //< detector temperature
detector_state state; //< detector state
unsigned short mode; //< detector mode
struct EnergyStatus
{
power_source powerSource; //< front-end power source
frontend_position frontendPosition; //< front-end position relative to the docking station
struct BatteryStatus
{
bool present; //< battery present or not in the detector
unsigned short charge; //< charge level of the battery (in %)
float voltageLevel; //< battery voltage level
float temperature; //< temperature of the battery
unsigned short chargeCycles; //< number of charge/discharge cycles
unsigned short accuracy; //< Expected accuracy for charge level (in %)
bool needCalibration;
} batteryStatus;
} * energyStatus;
struct GridStatus
{
detector_grid grid;
} * gridStatus;
} * detectorStatus;
} HardwareStatus;
This struct is used by the library as data passed by one of its callbacks. So it's the library which fills it up, I just read it. So far, so good.
But now I'm writing an emulator for the device handled by this library, so now I have to fill up one of these structs and I can't get it right.
I tried this:
HardwareStatus status;
status.detectorStatus->temperature = 20 + rand() % 10;
e.data = &status;
m_pContext->EventCallback( EVT_HARDWARE_STATUS, &e );
When I compiled, I got:
warning C4700: uninitialized local variable 'status' used
Then I realized... The pointers inside the struct are pointing to garbage, nice catch Visual Studio! So then I tried to start by declaring an instance of the innermost struct (BatteryStatus), but that wouldn't compile... because it's not typedef'd (it says the BatteryStatus type is not defined)? So I got stumped... How do I fill the struct up?
A: You could value-iniitialize it:
HardwareStatus status = {};
If you want to instantiate a BatteryStatus, you can do that by fully qualifying the name:
HardwareStatus::DetectorStatus::EnergyStatus::BatteryStatus bs;
A: if you want to have everything on the stack this should do it:
// Getting structs on the stack initialized to zero
HardwareStatus status = { 0 };
HardwareStatus::DetectorStatus detectorStatus = { 0 };
HardwareStatus::DetectorStatus::EnergyStatus energyStatus = { 0 };
HardwareStatus::DetectorStatus::GridStatus gridStatus = { 0 };
// "Linking" structs
detectorStatus.energyStatus = &energyStatus;
detectorStatus.gridStatus = &gridStatus;
status.detectorStatus = &detectorStatus;
// Now you can fill and use them
status.detectorStatus->temperature = 20 + 3 % 10;
//...
A: did you try memset'ing the struct to 0 ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is my JavaScript statement correct or not? I need to know my JavaScript sentence is correct or not? I am very much confused with the single quotes and plus symbols.
document.f.SQL.value ='\('+
document.f.SQL.value + a[i] +
' >= \''+ document.f[a[i]+"_A"].value +
'\' AND '+ a[i] +' <= \''+
document.f[a[i]+"_B"].value +
'\) or DATEADD'+'\('+
'dd, 0, DATEDIFF'+'\('+
'dd, 0,'+ a[i] +'\)) = \''+
document.f[a[i]].value +
'\'';
A: I pasted your code in Closure Compiler and used the which gave no errors, so the syntax is correct. The generated code is:
document.f.SQL.value = "(" + document.f.SQL.value + a[i] + " >= '" + document.f[a[i] + "_A"].value + "' AND " + a[i] + " <= '" + document.f[a[i] + "_B"].value + ") or DATEADD" + "(" + "dd, 0, DATEDIFF" + "(" + "dd, 0," + a[i] + ")) = '" + document.f[a[i]].value + "'";
The options I used for this:
*
*Optimization: Whitespace only
*Formatting: Pretty print
Try to avoid such complex lines. Make use of variables. The same result could be achieved with the below:
var old = document.f.SQL.value + a[i];
var sql_a = document.f[ a[i] + "_A" ].value;
var sql_b = document.f[ a[i] + "_B" ].value;
var whatever = document.f[ a[i] ].value;
// (old) >= 'sql_a' AND
var sql = "(" + old + ") >= '" + sql_a + "' AND ";
// A <= 'sql_b')
sql += a[i] + " <= '" + sql_b + "') "
// or DATEADD(dd, 0, DATEDIFF(dd, 0, A)) = 'whatever'
sql += "or DATEADD(dd, 0, DATEDIFF(dd, 0, " + a[i] + ")) = '" + whatever + "';
document.f.SQL.value = sql;
The point is, try to split the string in smaller parts. I did not split the queries in smaller parts above, that's up to you.
A: If you need single quotes in your string and no double quotes (inside it) then use double quotes to delimit your string and you won't need to escape your single quotes.
I usually prefer single quotes to delimit strings in JavaScript especially when I tend to be working on HTML strings because I prefer double quotes for attributes. You can use either the single quote or double quote though, there's no functional difference like there is in PHP or other languages.
Your expression is quite difficult to read. Consider simplifying it, putting it into several instructions or finding/writing a reusable token substitution routine of some sort.
The escaping of brackets \( looks unnecessary, and concatenating two string literals too ' + '.
Expressions like document.f[a[i]+"_A"].value would be easier to read if they were assigned to meaningfully named variables before you used them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-7"
} |
Q: Is there an updated version of "Improving .NET Application Performance and Scalability"? I'm looking for an updated version of this article: Improving .NET Application Performance and Scalability.
The message on this page states:
Retired Content
This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.
I'm looking for either an update of this article or a collection of articles with the same emphasis.
A (recent) book on .NET performance and scalability is also acceptable.
A: Microsoft Application Architecture Guide (From the Microsoft Patterns and Practices Team)
http://www.amazon.co.uk/Microsoft-Application-Architecture-Patterns-Practices/dp/073562710X/ref=pd_sim_b_8
That's the one you're are looking for.
Excellent book ... happy reading :-)
A: A quick Google check and wording of that statement indicates no, but perhaps the blog of one of the authors may help? Esp. his "Performance" tag?
http://blogs.msdn.com/b/jmeier/archive/tags/performance/
A: It doesn't appear that an updated article exists. However, I wouldn't let the retired content disclaimer discourage you from reading the article and heeding it's advice. While some information may be outdated and some links might be invalid, there is probably a lot of useful information that still applies.
Technology will always continue to improve, but the basics of good programming rarely change.
A: Here are a few that I've looked at in the past.
http://channel9.msdn.com/Blogs/pdc2008/TL24
http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx
A: Some of the same information, particularly in regard to testing, can be found in the 2007 J.D. Meier series, "Performance Testing Guidance for Web Applications" series.
The patterns & practices Application Architecture Guide 2.02 also mentioned above from October 2009 contains some of the architectural information.
Enterprise and cloud based development guides are gathered here. In particular the 2013, 273 page Book Download: Data Access for Highly-Scalable Solutions: Using SQL, NoSQL, and Polyglot Persistence5 has some very useful information.
And the 2012, Developing Multi-tenant Applications for the Cloud, 3rd Edition - Book Download
A: You can also look into Iqbal Khan's articles on improving .net application's performance and scalability using distributed caching solutions like NCache here:
http://msdn.microsoft.com/en-us/magazine/ff714590.aspx
http://msdn.microsoft.com/en-us/magazine/dd942840.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Auto-Full Screen for a Youtube embed I have a Youtube video embeded on a webpage.
Is it possible to have the video go full screen when the user presses play, using the HTML5 iframe with Youtube's API?
Using the Chromeless player is not an option as the website is intended for iPads.
A: This isn't possible with the youtube embed code or the youtube javascript API as far as I know. You would have to write your own player to have this functionality.
Doing some reading it looks like you can use the chromeless youtube player and it will resize itself to the width and height of its parent element.
That means that if you use the chromeless player you can resize the div with javascript with the play event is triggered.
A: Update November 2013: this is possible - real fullscreen, not full window, with the following technique. As @chrisg says, the YouTube JS API does not have a 'fullscreen by default' option.
*
*Create a custom play button
*Use YouTube JS API to play video
*Use HTML5 fullscreen API to make element fullscreen
Here's the code.
var $ = document.querySelector.bind(document);
// Once the user clicks a custom fullscreen button
$(playButtonClass).addEventListener('click', function(){
// Play video and go fullscreen
player.playVideo();
var playerElement = $(playerWrapperClass);
var requestFullScreen = playerElement.requestFullScreen || playerElement.mozRequestFullScreen || playerElement.webkitRequestFullScreen;
if (requestFullScreen) {
requestFullScreen.bind(playerElement)();
}
})
A: No, this isn't possible, due to security concerns.
The end user has to do something to initiate fullscreen.
If you were to run an Adobe AIR application, you can automate the fullscreen activation w/o having end user do anything. But then it would be a desktop application, not a webpage.
A: I thought I would post an easier updated method to solving this one using html5.
.ytfullscreen is the name of the button or whatever you want clicked.
#yrc-player-frame-0 is going to be the name of your iframe.
jQuery(".ytfullscreen").click(function () {
var e = document.getElementById("yrc-player-frame-0");
if (e.requestFullscreen) {
e.requestFullscreen();
} else if (e.webkitRequestFullscreen) {
e.webkitRequestFullscreen();
} else if (e.mozRequestFullScreen) {
e.mozRequestFullScreen();
} else if (e.msRequestFullscreen) {
e.msRequestFullscreen();
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: How to exclude fields form being indexed with Sitecore search (new method) How can I specify which fields to index with lucene indexing with Sitecore (new method)?
For example I'd like to index only the fields 'title' and 'text'. There seems to be a IndexAllField parameter that can be set to False but how can I set which fields needs to be indexed?
I'm using Sitecore.Search.Crawlers.DatabaseCrawler.
A: Are you using the Advanced Database Crawler? If so, there are sections you can add to include specific fields by their GUIDs and exclude specific fields by their GUIDs. Below I've provided a snippet where the hint attribute of the <include> node defines whether the fields should be included or excluded
<master type="Sitecore.SharedSource.Search.Crawlers.AdvancedDatabaseCrawler,Sitecore.SharedSource.Search">
<Database>master</Database>
<Root>/sitecore/content</Root>
<IndexAllFields>false</IndexAllFields>
<include hint="list:IncludeField">
<!-- some field you'd want to include -->
<fieldId>{8CDC337E-A112-42FB-BBB4-4143751E123F}</fieldId>
</include>
<include hint="list:ExcludeField">
<!-- __revision field -->
<fieldId>{8CDC337E-A112-42FB-BBB4-4143751E123F}</fieldId>
<!-- __context menu field -->
<fieldId>{D3AE7222-425D-4B77-95D8-EE33AC2B6730}</fieldId>
<!-- __security field -->
<fieldId>{DEC8D2D5-E3CF-48B6-A653-8E69E2716641}</fieldId>
<!-- __renderings field -->
<fieldId>{F1A1FE9E-A60C-4DDB-A3A0-BB5B29FE732E}</fieldId>
</include>
You can see a sample search config for the Advanced Database Crawler on SVN.
A: If you are using the Standard Sitecore DatabaseCrawler I would suggest you create a custom crawler that inherits from the Sitecore Database crawler and then override the AddAllFieldsMethod. Then just configure your index to use your custom crawler
You can look at the source code for the Advanced Database Crawler for an example of how that can be done. Something like this: (NOTE THIS HAS NOT BEEN TESTED)
public class DatabaseCrawler : Sitecore.Search.Crawlers.DatabaseCrawler
{
protected override void AddAllFields(Lucene.Net.Documents.Document document, Sitecore.Data.Items.Item item, bool versionSpecific)
{
if(IndexAllFields)
{
base.AddAllFields(document, item, versionSpecific);
}
else
{
var fieldsToIndex = new List<string>() {"title", "Text"};
foreach (var field in fieldsToIndex)
{
var scField = item.Fields[field];
document.Add(new LuceneField(scField.Key, scField.Value, LuceneField.Store.NO, LuceneField.Index.UN_TOKENIZED));
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Do I have to clear events from the DOM if an element is removed? Let's say I have a page that loads pages dynamically. As each page loads into the DOM, events for the elements in that page are added.
If the user loads another page, the elements loaded previously will be removed from the DOM. Naturally, because the elements themselves no longer exist, any events mapped to those elements cease to function.
However, are they also removed? Or are they sitting in the user's memory, taking up space?
Follow-up:
Were a function defined as such:
var event = $('foobar').addEvent('click', function() {
alert(1);
});
One could easily remove the event with event = null (or so I'd assume!)...
but what if the event were not saved to a local variable?
$('foobar').addEvent('click', function() {
alert(1);
});
Thanks!
A: Interesting question... have a read of this: https://developer.mozilla.org/en/DOM/element.addEventListener#Memory_issues
To remove the event listener using jQuery, see http://api.jquery.com/unbind/
A: I have found that older versions of IE seems to have issues with adding and removing lots of elements with events binded to them. The main cause is circular references that cannot be garbage collected. You can find more information here: http://msdn.microsoft.com/en-us/library/Bb250448
Setting to null will not remove the event, it would just remove the reference to the event. You need to use both element.removeEventListener and element.detachEvent (depending on browser), or if you are using jquery unbind should work.
Also, there are tools available to detect leaks, this one works well (according to coworker): http://blogs.msdn.com/b/gpde/archive/2009/08/03/javascript-memory-leak-detector-v2.aspx
A: first of all. what? this makes no sense:
var event = $('foobar').addEvent('click', function() {
alert(1);
});
it does not save the event into a local variable as you seem to think. it saves a reference to the foobar element object into the event variable - most mootools element methods will return this for chaining, which is the element itself and not the result of the method (unless it's a getter like '.getStyle').
it then depends on how you get rid of the element what happens next. first off, element.destroy, found here: https://github.com/mootools/mootools-core/blob/master/Source/Element/Element.js#L728
it will remove the element from the dom and from memory, and empty it in a safe way. it will be reliant on the browser's GC to clean up once it's gone, mootools won't do any spectacular GC for you for the element itself but it does run the special clean function on the child nodes as well: var children = clean(this).getElementsByTagName('*');.
the clean method also gets rid of any event handlers and storage attached to the child elements of the div.
THEN. events added by mootools go into element storage. Element storage is in an object behind a closure which the element proto uses. To test it, we will re-implement it and make it puncturable (a global object called storage) so we can check what happens to the reference after the parent is gone:
http://jsfiddle.net/dimitar/DQ8JU/
(function() {
var storage = this.storage = {}; // make it puncturable
var get = function(uid){
return (storage[uid] || (storage[uid] = {}));
};
Element.implement({
retrieve: function(property, dflt){
var storage = get($uid(this)), prop = storage[property];
if (dflt != null && prop == null) prop = storage[property] = dflt;
return prop != null ? prop : null;
},
store: function(property, value){
var storage = get($uid(this));
storage[property] = value;
return this;
},
eliminate: function(property){
var storage = get($uid(this));
delete storage[property];
return this;
}
});
})();
// read it.
var link = document.getElement("a");
var uid = link.uid; // will reference the mootools unique id for it
// add an event handler
link.addEvent("click", function(e) {
console.log("hi");
this.destroy();
// see what's left in storage for that element.
console.log(storage[uid]);
// storage should be empty.
console.log(storage);
});
link.getFirst().addEvent("mouseenter", function() {
console.log("over");
});
// check to see if it is there via element storage API.
console.log(link.retrieve("events").click);
// check to see if it's there via our puncture
console.log(this.storage[uid]);
// see all events in storage, inc child element:
console.info(this.storage);
what all this proves is, mootools cleans up all you need cleaned. as long as you don't use any inline onclick= stuff on elements you work with, you're going to be fine. Between mootools' garbage collection and the browser, you are well covered. just be aware you can stack up multiple events on a single element if the callbacks are anonymous.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: YUI3 Datasource to return custom Object How can I get the YUI3 sendRequest applied to a Datasource to return predefined objects, instead of plain ones?
For example, I have this Base class with its methods:
function Student(id, name){
this.id = id;
this.name = name;
}
Context.prototype.setId = function(id){ this.id = id; };
Context.prototype.setName = function(name){ this.name = name; };
Context.prototype.getId = function(){ return this.id; };
Context.prototype.getName = function(){ return this.name; };
And I have this code that retrieves data from an API, normalizes it and returns data as objects:
var studApiDataSource = new Y.DataSource.Get({source: API_URL});
studApiDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: "response.student",
resultFields: ["id","name"]
}
});
var myCallback = function(e) {
Y.Array.each(e.response.results, function(stud){
Y.log(stud.id+' '+stud.name);
}
}
studApiDataSource.sendRequest({
request: "?cmd=getStudents",
callback: {
success: myCallback,
failure: function (e) { }
}
});
The array of objects retrieved by studApiDataSource.sendRequest() and passed to myCallback are normal objects, with id and name properties. However, I want these to be Student objects, with their member functions too (getId, getName etc)
A: I'm not sure I fully understand, but you could do something like the following.
var studentJSON = "{\"id\": 17, \"name\":\"my name is\"}";
function Student(obj){
this.name = obj.name;
this.id = obj.id;
}
Student.prototype.setId = function(id){ this.id = id; };
Student.prototype.setName = function(name){ this.name = name; };
Student.prototype.getId = function(){ return this.id; };
Student.prototype.getName = function(){ return this.name; };
YUI().use('json-parse', 'json-stringify', function (Y) {
try {
var stud = new Student(Y.JSON.parse(studentJSON));
alert(stud.getId());
}
catch (e) {
alert(e);
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: playing video iphone - mpmovieviewcontroller I'm playing video with MPMoviePlayerViewController. I get video url from web service. But first I select video quality with AlertView. For example 240p 360p 480p… All video plays except 240p. MPMoviePlayerView appears and then disappears with notification MPMovieFinishReasonPlaybackEnded. I try to play url of 240p video in simulator, everything is perfect but in device it's not playing. I receive MPMovieFinishReasonPlaybackEnded all the time. If I select 360p or more, everything is good. Here is some code:
-(void) playVideoFromURL:(NSString *) url
{
NSLog(@"%@",url); //URL is valid! Browser plays it
if (!videoPlayerView) {
NSURL *fURL = [NSURL URLWithString:url];
videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:fURL];
videoPlayer = videoPlayerView.moviePlayer;
[videoPlayer prepareToPlay];
}
}
It doesn't play even from the local folder. This is an iPhone app, my device is iPad 2!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: gem 1.8.10 error I just setup an EC2 instance on ubuntu and installed ruby 1.9.2. I also updated the rubygems by executing gem update --system. Once the installation was done, I typed gem -v and I got the following error
Invalid gemspec in [/usr/local/lib/ruby/gems/1.9.1/specifications/tilt-1.3.3.gemspec]: invalid date format in specification: "2011-08-25 00:00:00.000000000Z"
Invalid gemspec in [/usr/local/lib/ruby/gems/1.9.1/specifications/rack-cache-1.0.3.gemspec]: invalid date format in specification: "2011-08-27 00:00:00.000000000Z"
1.8.10
A: I had the same problem. You must delete everything except the actual date (not time).
As such, "2011-08-25 00:00:00.000000000Z" should become "2011-08-25". That will fix the annoying messages, as well as allow 'gem' to see that those are installed.
By the way, a newer rack-cache (1.1 vs 1.0.3) is available that does not have this problem. However, since gem doesn't think 'rack-cache' is installed, you'll have to manually delete all of the files. You can do that using:
sudo find /usr/local/lib/ruby/gems/1.9.1/ -name 'rack-cache-1.0.3' -exec rm -fR {} \;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rendering image on the mobile browser? i am creating a mobile site, now my problem is the images are getting render when i run the site on PC, and also while running the site on IPhone, but when it comes to Opera Browser for any symbian based mobile, the images are not at all rendering..
i am using asp:Image control on the site.. is this causing it not to be displayed on mobile.
if yes, then whats the equivalent for the mobile control. and also i want to resize the image as per the aspect ratio almost all the images are big in dimension.
Please anyone have any idea for the same, i will appreciate it.
A: If you wish to have your pages and images resize automatically based on the size of the device on which they are being viewed, you might find an answer with Zurb Foundation. I use it in almost all of my web "responsive web design" projects now.
http://foundation.zurb.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Django returns blank pages Suddenly I started getting HTTP 200 with zero byte content for every request handled by Django.
This problem has appeared in past, too, and seemed to randomly disappear.
I see a debug view when I make syntax errors, but if the code executes fine, I get a blank page.
I tried resetting Apache, moving project directory, removing .pyc's—what next?
A: This mistake scores highest on stupidness * impact measure among all I've ever made.
I upload changes to our server via SFTP, and I got a short connection outage during last round of changes. Apparently, it happened exactly the moment I was uploading base.html, the base template for them all. The file was overwritten as zero byte empty file, and Django was correctly serving it.
Two things I've learned:
*
*to never trust SFTP clients;
*to inspect diff with HEAD when a problem occurs.
A: This just happened to me again. (I guess I'm lucky!)
I haven't found the cause but was able to recover by stopping and then starting Apache:
sudo apache2ctl stop
sudo apache2ctl start
Apparently, this isn't the same as restarting (sudo apache2ctl start) which didn't help at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I bind a custom UserControl to the current item inside a ItemTemplate? I have a ListBox that is data bound to an ObservableCollection.
Inside the DataTemplate, I have this custom user control that I want to bind to the current item.
How do I do that?
What should the binding path be?
Model:
private ObservableCollection<MyItem> _items;
public ObservableCollection<MyItem> Items
{
get { return _items; }
set
{
if (_items.Equals(value))
return;
_items = value;
RaisePropertyChanged("Items");
}
}
XAML:
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock TextWrapping="Wrap" Text="{Binding Id}" Margin="2"/>
<TextBlock TextWrapping="Wrap" Text="{Binding Name}" Margin="2"/>
<uc:MyControl MyValue="{Binding <WHATSHOULDTHISBE>, Mode=TwoWay}" Margin="2"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
User control:
public partial class MyControl : UserControl
{
public MyItem MyValue
{
get { return (MyItem)GetValue(MyProperty); }
set { SetValue(MyProperty, value); }
}
public static readonly DependencyProperty MyProperty = DependencyProperty.Register("MyValue",
typeof(MyItem), typeof(MyControl),
new PropertyMetadata(
new PropertyChangedCallback(PropertyChanged)));
public MyControl()
{
InitializeComponent();
}
private static void PropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
MyControl c = obj as MyControl;
if (c != null)
{
// TODO: do something here
}
}
}
A: MyControl.DataContext property would already be bound to your item view model in this case.
A: Your MyItem is the data context - if you want to bind to some member of My Item then its:
Binding Path=my_item_member
To bind to MyItem in its entirety I think you want:
Binding Path=.
Your might also need a DataTemplate for your control (in addition to the you have for the ListBoxItems) that maps the MyItems members to your control fields.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: mysqli query generates 500 internal server error $mysql_connection = new mysqli(blah blah blah..
$query = "SELECT * FROM posts ORDER BY id DESC";
$result = $mysql_connection->query($query);
That little last instruction here generates a 500 Internal Server Error in my site, I didn't posted the whole code because I didn't want to make you stay hours to read it.
I tested it by printing something after every instruction that may have caused the error, and when it reaches the query part, id stops.
I'm a very beginner in PHP, so sorry if it's a dumb question.
So, any little hint will be very appreciated.
A: it looks like the connection is not going through for some reason
can you add this to your code and post the output
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
A: look at the error log. there should be some more info as to why it's failing. if still unable to fix problem, post the error log entry here so we can help you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AVAssetReader fails after the app is put in the background, why? I have playback working with AVAssetReader and iPod library and when I put the the app in the background it will continue reading in audio to the playback buffer but when it gets to the end of a song and starts reading on the next song it fails when startReading is called. I get the following error details.
Error Domain=AVFoundationErrorDomain Code=-11800 "The operation couldn’t be completed. (AVFoundationErrorDomain error -11800.)" UserInfo=0x1bfc20 {NSUnderlyingError=0x113e00 "The operation couldn’t be completed. (OSStatus error -12985.)"}
{
NSUnderlyingError = "Error Domain=NSOSStatusErrorDomain Code=-12985 \"The operation couldn\U2019t be completed. (OSStatus error -12985.)\"";
}
Is there a limitation on AVAssetReader that I do not know about?
A: NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
UInt32 doSetProperty = 1;
OSStatus tStatus = AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers,
sizeof (doSetProperty),
&doSetProperty
);
NSLog(@"AVAudioSession AudioSessionSetProperty status is %@", tStatus);
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
[[AVAudioSession sharedInstance] setDelegate:self];
NSLog(@"AVAudioSession setActive Error is %@", sessionError);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Add same subview multiple times to view I don't know if this is possible, but what I would like to do is add a subview several times to the view. I have tried something like this:
[self.view addSubview: newView];
newView.center = CGPointMake(160, 100);
[self.view addSubview: newView];
newView.center = CGPointMake(160, 200);
[self.view addSubview: newView];
All this does is move newView around, without adding new ones. Any ideas?
I also tried this:
[self.view addSubview:newView];
UIView *anotherView = newView;
anotherView.center = CGPointMake(160, 100)
[self.view addSubview:anotherView];
Edit
Here's a solution I've learned with time
Another way to solve the problem would be to make a separate nib containing the view and add instances of the nib several times. A good template to work off to implement this solution is to do it the same way a custom UITableViewCell is used in the cellForRowAtIndexPath method.
A: A view can only be contained in a single parent view's hierarchy. As soon as you add it to a new one, it is removed from the previous one. In this case, it is being removed and added back to the same view's hierarchy. You would need to make a copy of the sub-view to have it appear multiple times.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: JCrop doesn't save selection when image size is changed I am using jcrop for the first time. ANd I have a problem with image size and cropping. When user upload image 1366x768 or larger I preview it on my page. I also have crop selection preview and it works fine. When I submit positions it crops fine (it's when I use original image size).
But I don't want to display so large original images on page. User must see original image, preview and submit buttons in one view. So I need to make image smaller if image is 1366x768 I wan't to display it like 683x368. But here is the problem. When I set width and height on image tag crop not works fine anymore. I paste my code and image preview of my problem:
jQuery(window).load(function () {
jQuery('#cropbox').Jcrop({
onChange: showPreview,
onSelect: showPreview,
setSelect: [0, 0, 540, 300],
allowResize: true,
aspectRatio: 2
});
});
function showPreview(coords) {
if (parseInt(coords.w) > 0) {
var rx = 540 / coords.w;
var ry = 300 / coords.h;
jQuery('#preview').css({
width: Math.round(rx * 683) + 'px',
height: Math.round(ry * 368) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
$('#x').val(coords.x);
$('#y').val(coords.y);
$('#w').val(coords.w);
$('#h').val(coords.h);
}
</script>
</head>
<body>
<div>
<p style="width: 540px; height: 300px; overflow: hidden; float:left;">
<img id="preview" src="../../Content/Images/Full/Leopard.jpg" />
</p>
<p style="float:left;">
<img id="cropbox" width="683px" height="368px" src="../../Content/Images/Full/Leopard.jpg" />
</p>
<p>
@using (@Html.BeginForm("PostPicture", "Home"))
{
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<button type="submit">
Send</button>
}
</p>
This is second error: After I multiply X and Y with 2.
This is asp.net back end code:
public ImageResult PostPicture(int x, int y, int h, int w)
{
x = x * 2;
y = y * 2;
Image image = Image.FromFile(Path.Combine(this.Request.PhysicalApplicationPath, "Content\\Images\\Full\\Leopard.jpg"));
Bitmap cropedImage = new Bitmap(w, h, image.PixelFormat);
Graphics g = Graphics.FromImage(cropedImage);
Rectangle rec = new Rectangle(0, 0,
w,
h);
g.DrawImage(image, rec, x, y, w, h, GraphicsUnit.Pixel);
image.Dispose();
g.Dispose();
string savedFileName = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Content", "Images", "Full",
Path.GetFileName("cropped.jpg"));
cropedImage.Save(savedFileName);
return new ImageResult { Image = cropedImage, ImageFormat = ImageFormat.Jpeg };
}
A: Maybe try setting the image size in css style attribute:
<img id="cropbox" style="width:683px;height:368px" src="../../Content/Images/Full/Leopard.jpg" />
Perhaps a better solution is to resize the image on the server to your desired dimensions, then display the resized image to the user instead of the full original image. This will also reduce download time for the browser since the image will be smaller.
A: You'll have to adjust the crop coordinates that are passed. You need to adjust them according to the ratio by which you resized your image for preview. So if you shrank your image preview to 50% of what it was originally, the actual coordinates of the crop will be twice what they come in as or (x*2, y*2).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.