text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Replace a string at a fixed position in a text file with the output of a command with cmd I wants to replace the QUICKSERVER string in line 3 of my text file which is located at c:\BR.txt with the output from the hostname command in Windows CMD. hostname is a Windows command which returns the system name.
C:\>hostname
QUICKSERVER
my text file is:
userName=Administrator
password=
CMS=QUICKSERVER:6400
authentication=secEnterprise
Please find the command which I can execute in the Windows command line to replace the hostname with QUICKSERVER.
A: The host name can also be found in the %computername% environment variable, so you don't need the hostname command.
@echo off
setlocal enabledelayedexpansion
for %%L in (c:\br.txt) do (
set "LINE=%%L"
set "LINE=!LINE:QUICKSERVER=%COMPUTERNAME%!"
echo !LINE!
) > C:\br2.txt
move /y C:\br2.txt c:\br.txt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 3 Tier Architecture - data tier just stores data only? Does the data tier verify any of the user's input? or does it just store data?
Example - User adds email to his profile.
Is this right?
Presentation Tier
- Verify Email format is valid (client side)
Logic tier
*
*Verify Email format is valid (again?)
*Set Email type (ie is Primary email?)
*Check record limit allowed to store email
Data:
*
*Store the email record
Logic:
*
*Send Notification to presentation tier
*Send Notification via Email
A: Note :
Data layer task is to connect with the database and to perform CRUD operation if you want to apply extra validation logic than you must do it in the logical layer
You architecture changes
Presentation Tier -
*
*Verify Email format is valid (client side)
Logic tier
*
*Verify Email format is valid (again?) - No need to do it again
*Set Email type (ie is Primary email?)
*Check record limit allowed to store email
Data Layer:
*
*allow to connect with the database
*perform CRUD operation
Data Store i.e DataBase
*
*Store the email record
Return
DataLyer
*
*Informs logic layer data inserted propertly
Logic Layer:
*
*Send Notification to presentation tier either data inserted/updated properly
*Send Notification via Email if Data Inserted/Updated properly else log error
A: Every layer has its own set of contracts with outside world.
You shouldn't do or not do something based on assumption that it may have been done on earlier layer (like validation)
However DataLayer doesn't verify email address formats. Its not part of its responsibilities. It shouldn't even understand what an email looks like except for a fact that it is string of some specific length.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to avoid the naming conflict b/w uploaded files A web application uploads files (images only) from client to server location no any DB and also save the same file/files from server to client's machine.
Process 1. upload a file <input type="file /">
2. save files into server predifined location : java
3. download the same files from server to client's machine by clicking on save button
problem : let suppose there are two users and they are uploading different files with same name at same time in predifined (or programmed) server's folder.
then how should i avoid this kind of naming conflict & how to programmed for, which file belongs to whom (client) .
possible sol'n : during uploading the file from client to server, create one folder for each client and save the file into specifiec newly created folder.
please note that there is no any Database in application. please suggest any better
Environment : java servlet Apache-tomcat 6.0 xhtml
A: Use HttpServletReqeust.getSession() method to get client's unique session and then HttpSession.getId() to get session's identifier which you can use in directory/file name construction.
A: create one folder for each client/user.
Seems like the obvious solution to me. Using session id will result in many more directories being created. If the server saved images are to be used later(which I assume they are, otherwise whats the point of saving them). Having a directory structure based on usernames(or similar) would be much less painful to navigate than anything else.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript function not working cross-browser. This is my javascript function that is working in chrome and FF5 but not working in IE.
function createContorl() {
var parentDiv = document.createElement("div");
parentDiv.setAttribute("class", "ModelProgressDiv");
parentDiv.setAttribute("Id", "ProgressDiv");
var innerContent = document.createElement("div");
innerContent.setAttribute("class", "ModalProgressDivContent");
var img = document.createElement("img");
img.setAttribute("src", "images/loading_large.gif");
parentDiv.appendChild(innerContent);
innerContent.appendChild(img);
document.body.appendChild(parentDiv);
}
A: setAttribute is broken in IE unless you are using a very recent version in Standards Mode. It sets properties instead of attributes so it fails when the property doesn't have the same name as the attribute. Don't use it.
parentDiv.className = "ModelProgressDiv"; // etc
A: Your code works fine on IE8: see this fiddle
BTW, please check the in the function name createContorl but that would cause problem in all browsers.
Perhaps, you should explain when you say "not working in IE".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Outlook 2010 addin C# public methods I need to develop an Outlook 2010 add-in and I am new to Visual Studio and C#, as I mostly use PHP and JavaScript. I am using Visual Studio 2010 and I've created a project using built-in Outlook 2010 add-in template. Consider the folowing code:
// file ThisAddIn.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
namespace OutlookAddIn1
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
public string displayCount()
{
Outlook.MAPIFolder inbox = this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
Outlook.Items unreadItems = inbox.Items.Restrict("[Unread]=true");
return string.Format("Unread items in Inbox = {0}", unreadItems.Count);
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
// file Ribbon1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
namespace OutlookAddIn1
{
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
// call ThisAddIn.displayCount() here
}
}
}
The question is, how do I call public methods from ThisAddIn class in Ribbon1 class or anywhere else? I know that I need an object reference, but how can I find out the name of an instance? I can't see an instance of ThisAddIn being created anywhere in existing files. Or do I misunderstand the concept and it should be done in other ways? I would appreciate any advice or links to information on creating Office add-ins too.
A: In VSTO projects, an auto-generated sealed class called Globals is available from anywhere within your project. Globals contains a number of public or internal static properties, one of which is ThisAddIn (of type ThisAddIn, appropriately enough). Instead of the above, your code would then look something like below.
In Ribbon1.cs:
public void DoSomethingOnRibbon(Office.IRibbonControl control)
{
string count = Globals.ThisAddIn.displayCount();
...
}
Hope that helps.
A: I use a static member variable (with an associated static getter) that is set upon initialization of the add-in: then I can access it as Core (choose name as appropriate) from anywhere in the code-base. Of course, I try to pass around the add-in object if it is available in context, but sometimes it's hard to do.
The class is instantiated automatically by the add-in container/loader (it is really exposed as a COM component, at least this is how it works in ADX :).
Happy coding.
The code might look something like this:
// inside ThisAddIn class
public static ThisAddIn Active {
get;
private set;
}
// inside ThisAddIn_Startup
Active = this;
// later on, after add-in initialization, say in Ribbon1.button1_Click
ThisAddIn.Active.displayCount();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to return from user define method to delegate method I'm implementing the in-app purchase. And I got the problem while executing the delegate methods of store kit.
Here is my code as following:
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSLog(@"Received products results...");
NSLog(@"response.products.......%@",response.products);
self.products = response.products;
self.request = nil;
proUpgradeProduct = [_products count] == 1 ? [[_products objectAtIndex:0] retain] : nil;
if (proUpgradeProduct)
{
NSLog(@"Product title: %@" , proUpgradeProduct.localizedTitle);
NSLog(@"Product description: %@" , proUpgradeProduct.localizedDescription);
NSLog(@"Product price: %@" , proUpgradeProduct.price);
NSLog(@"Product id: %@" , proUpgradeProduct.productIdentifier);
}
NSLog(@"products.....%@",_products);
for (NSString *invalidProductId in response.invalidProductIdentifiers)
{
NSLog(@"Invalid product id: %@" , invalidProductId);
}
[[NSNotificationCenter defaultCenter] postNotificationName:kProductsLoadedNotification object:_products];
[self buyProductIdentifier:proUpgradeProduct.productIdentifier];
}
- (void)buyProductIdentifier:(NSString *)productIdentifier {
if ([SKPaymentQueue canMakePayments])
{
NSLog(@"Buying %@...", productIdentifier);
SKPayment *payment = [SKPayment paymentWithProductIdentifier:productIdentifier];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"StoreKit" message:@"You are not authorised to purchase from AppStore"
delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased:
[self completeTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
[self failedTransaction:transaction];
break;
case SKPaymentTransactionStateRestored:
[self restoreTransaction:transaction];
default:
break;
}
}
}
Control is not shifting to - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions in (void)buyProductIdentifier:(NSString *)productIdentifier - method.
What should I do?
A: *
*You should set SKPaymentTransactionObserver of defaultQueue:
[[SKPaymentQueue defaultQueue] addTransactionObserver:manager];
*Method paymentQueue:updatedTransactions: will be called only after StoreKit did end working with transaction(s) in your defaultQueue : when user canceled or purchased (or transaction was restored) the product.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to catch a nested exception in java I'm using Apache Xalan (v.2.7.1) to translate XML to XHTML in Apache Tomcat (v6.0.32). Sometimes the loading gets cancelled by the client and the following exception is thrown:
javax.xml.transform.TransformerException: org.apache.xalan.xsltc.TransletException: ClientAbortException: java.io.IOException
at org.apache.xalan.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:636)
at org.apache.xalan.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:303)
...
I would like to catch the ClientAbortException-exception, so that it doesn't spam the log. However, how can I check if the exception is nested inside the ClientAbortException? I tried something like this:
...
} catch (Exception e) {
if (e.getCause() != null && e.getCause().getCause() instanceof org.apache.catalina.connector.ClientAbortException) {
//do nothing
} else {
throw e;
}
} finally {
...
But it only gives me a nullpointerexception as the first getCause doesn't have a getCause. Any ideas?
A: Use the ExceptionUtils.getRootCause(Throwable) method in Apache Commons-lang, it will traverse the cause chain for you.
A: If getCause() is returning null, then the javax.xml.transform.TransformerException doesn't actually have a cause. When the Exception is created, you need to specify the cause, and they probably haven't done this. You probably can't do anything about that.
You can check if the
One method could just be to use a String match on Exception@getMessage:
...
} catch (Exception e) {
if (e.getMessage().contains("ClientAbortException:")) {
// at least log the error, in case you've got something wrong
} else {
throw e;
}
} finally {
...
However, this may be unreliable, for the obvious reason that it depends upon the text of the message.
EDIT: Thinking about it, you may find out in production that catching this exception is a bad idea, or that you've got the code wrong, so adding a method to turn on or off this behaviour may be a good idea:
...
} catch (Exception e) {
if (System.getProperty("abort.when.ClientAbortException") == null && e.getMessage().contains("ClientAbortException:")) {
// at least log the error, in case you've got something wrong
...
Then you at least have the option of turning off the code. The System.getProperty is just an example.
A: Use Like this. it's working fine.
catch (Exception e) {
if (e.getCause() != null && e.getCause() instanceof org.apache.catalina.connector.ClientAbortException) {
//do nothing
} else {
throw e;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Error updating database PHP After submitting a payment form (credit cards, etc) to our payment gateway, we receive the "response_code" 1 when the payment is approved. We then use the following code to update a user's info in the database to reflect the approved transaction.
However, about every 1 out of 10 times, a user's info simply will not update even though the transaction returned an approved response. Is anything clearly wrong with this code? Or perhaps the response_code does not equal 1 for some reason?
<?php
session_start();
if ($_GET['response_code'] == 1)
{
require('scripts/global.php'); //connect to database
$email = $_SESSION['email'];
$level = 3;
$transaction_id = "" . htmlentities($_GET['transaction_id']);
mysql_query ("UPDATE `users` SET level = '$level', trans_id = '$transaction_id' WHERE `email` = '$email'"); //update user info
$error = "false";
}
else
{
$noerror = "true";
$message = "Sorry, an error occurred: " . htmlentities($_GET['response_reason_text']);
}
?>
A: Probably because there has been a session timeout? The WHERE uses the e-mail address, if this is not valid (not there) then you probably won't get an update.
Maybe you should check for transaction ID (or similar). I guess you've got something like that before the transaction starts?
edit: Also store if an error occurs, and try to store variables you need too. This makes it a lot easier to pinpoint the problem. Use a logfile for this for example.
A: Beyond the obvious security holes, you're not checking the results of your query. Try using mysql_error() and mysql_affected_rows() to see whether anything was updated. When either indicates something unusual, you'll also want to see the exact text of the query that ran. Things to check:
*
*Was $email empty?
*Did $transaction_id or $email have any apostrophes?
*Do you have duplicate email addresses in the database?
*Had the user already been set to level 3?
*Did you lose connection to the database?
*Did your script get called at all?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL trigger, insert into statement I have two sql tables called scan_sc and rescan_rsc. The scan table looks like this:
CREATE TABLE scan_sc
(
id_sc int(4),
Type_sc varchar(255),
ReScan_sc varchar(255),
PRIMARY KEY (id_sc)
)
When a scan a document I insert a row into the scan table. If the result of this scanning is poor I have to do a rescan, and therefore I have a rescan table.
CREATE TABLE rescan_rsc
(
id_rsc int(4),
Scan_rsc varchar(255),
PRIMARY KEY (id_rsc)
)
The problem is, I want to have a trigger that will fill in the column ReScannet_sc with an "x", in the scan_sc table, so I can see that there has been some problems here.
The trigger has to do it where the id from the rescan table is the same as in the scan table.
Hope you all understand my question.
Thanks in advance.
A: Do you really need the ReScan_sc column and the trigger?
With a simple JOIN, you can find out the records in your scan_sc table that have been re-scanned, without using the ReScan_sc column at all.
There are several possibilities:
Show all scans, with an additional column with the Rescan ID, if any:
SELECT scan_sc.*, rescan_sc.id_rsc
FROM scan_sc
LEFT JOIN rescan_sc ON scan_sc.id_sc = rescan_sc.id_rsc
Show only the scans which have been re-scanned:
SELECT scan_sc.*
FROM scan_sc
INNER JOIN rescan_sc ON scan_sc.id_sc = rescan_sc.id_rsc
(I assume that id_sc and id_rsc are the primary keys and that PRIMARY KEY (id_sd) is a typo, like marc_s pointed out in his comment)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't get Notification after connecting serial dock connector between iPhone and iMac Is it possible to connect iMac to iPhone through the dock connector ? Also I am using the EAAccessory framework but I am not get any notifications when I connect the serial cable to iPhone. If any one knows about this please give me a suggestion.
A: There seems to be a lot of confusion regarding EAAccessoryManager and the accompanying classes. These are only for use with MFI sanctioned hardware i.e. those manufacturers that have taken the time to follow the MFI program and integrate the requisite hardware into their device.
The use of a chip and the establishment of a protocol allows for the facilitation of a communication stream between the app and the device.
Sam is correct in his statement but there is no need to jailbreak your app in order to bypass the MFI program however, you will not be able to submit to the App Store if you follow the procedure I am about to briefly outine:
*
*Obtain all of the header files for the IOKit iOS OpenSource Browser
*Add them to your solution
*Include the IOKit.h framework
*Head to http://www.arduino.cc/playground/Interfacing/Cocoa#IOKit for an example of how to use IOKit and icotl commands to achieve what you require
I have successfully implemented IOKit operations on an iOS device so this is definitely possible as long as you are willing to forego submission to the App Store.
A: Raj..
for get notification for connection accessory first of you have to register your accessory to MFI. otherwise you have to jailbreak your iPhone. for jail break check this code
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
static struct termios gOriginalTTYAttrs;
static int OpenSerialPort()
{
int fileDescriptor = -1;
int handshake;
struct termios options;
// Open the serial port read/write, with no controlling terminal, and don't wait for a connection.
// The O_NONBLOCK flag also causes subsequent I/O on the device to be non-blocking.
// See open(2) ("man 2 open") for details.
fileDescriptor = open("/dev/tty.iap", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fileDescriptor == -1)
{
printf("Error opening serial port %s - %s(%d).\n",
"/dev/tty.iap", strerror(errno), errno);
goto error;
}
// Note that open() follows POSIX semantics: multiple open() calls to the same file will succeed
// unless the TIOCEXCL ioctl is issued. This will prevent additional opens except by root-owned
// processes.
// See tty(4) ("man 4 tty") and ioctl(2) ("man 2 ioctl") for details.
if (ioctl(fileDescriptor, TIOCEXCL) == -1)
{
printf("Error setting TIOCEXCL on %s - %s(%d).\n",
"/dev/tty.iap", strerror(errno), errno);
goto error;
}
// Now that the device is open, clear the O_NONBLOCK flag so subsequent I/O will block.
// See fcntl(2) ("man 2 fcntl") for details.
if (fcntl(fileDescriptor, F_SETFL, 0) == -1)
{
printf("Error clearing O_NONBLOCK %s - %s(%d).\n",
"/dev/tty.iap", strerror(errno), errno);
goto error;
}
// Get the current options and save them so we can restore the default settings later.
if (tcgetattr(fileDescriptor, &gOriginalTTYAttrs) == -1)
{
printf("Error getting tty attributes %s - %s(%d).\n",
"/dev/tty.iap", strerror(errno), errno);
goto error;
}
// The serial port attributes such as timeouts and baud rate are set by modifying the termios
// structure and then calling tcsetattr() to cause the changes to take effect. Note that the
// changes will not become effective without the tcsetattr() call.
// See tcsetattr(4) ("man 4 tcsetattr") for details.
options = gOriginalTTYAttrs;
// Print the current input and output baud rates.
// See tcsetattr(4) ("man 4 tcsetattr") for details.
printf("Current input baud rate is %d\n", (int) cfgetispeed(&options));
printf("Current output baud rate is %d\n", (int) cfgetospeed(&options));
// Set raw input (non-canonical) mode, with reads blocking until either a single character
// has been received or a one second timeout expires.
// See tcsetattr(4) ("man 4 tcsetattr") and termios(4) ("man 4 termios") for details.
cfmakeraw(&options);
options.c_cc[VMIN] = 1;
options.c_cc[VTIME] = 10;
// The baud rate, word length, and handshake options can be set as follows:
cfsetspeed(&options, B19200); // Set 19200 baud
options.c_cflag |= (CS8); // RTS flow control of input
printf("Input baud rate changed to %d\n", (int) cfgetispeed(&options));
printf("Output baud rate changed to %d\n", (int) cfgetospeed(&options));
// Cause the new options to take effect immediately.
if (tcsetattr(fileDescriptor, TCSANOW, &options) == -1)
{
printf("Error setting tty attributes %s - %s(%d).\n",
"/dev/tty.iap", strerror(errno), errno);
goto error;
}
// Success
return fileDescriptor;
// Failure "/dev/tty.iap"
error:
if (fileDescriptor != -1)
{
close(fileDescriptor);
}
return -1;
}
int main(int args, char *argv[])
{
int fd;
char somechar[8];
fd=OpenSerialPort(); // Open tty.iap with no hardware control, 8 bit, BLOCKING and at 19200 baud
if(fd>-1)
{
write(fd,"*",1); // Write handshaking message over serial
///////////////////////////////////////////////////////////////////////////////////////////////////
// After this, our device or our PC program should be strobing serial ground to gain access to the Iphone Serial Line
//////////////////////////////////////////////////////////////////////////////////////////////////
read(fd,&somechar[0],1); // Read 1 byte over serial. This will block (wait) untill the byte has been received
if(somechar[0]=='*') // Check if this byte is a "handshaking" message
{
printf("Serial connection established!\n"); // If it is, we have established a connection to the device and can freely read/write over serial!
while(1) // Do this forever or untill someone presses CTRL+C
{
read(fd,&somechar[0],1); // Read a character over serial!
putchar(somechar[0]); // Write the character to the Terminal!!
}
}
}
return 0;
}
A: If you connect your iPhone to an iMac and you have either iTunes or Xcode running, you would be able to see that the iPhone is connected.
In Xcode, go to the Organizer window. In iTunes, look under the Devices in the left-hand column.
The EAAccessory framework, which I have not used, should have nothing to do with this.
A: Here is the answer: Launch specific app when external accessory attached - not all accessories can signal to launch app when they are connected. I think that ordinal USB cable also can't.
About IOKit: You can add nesessary files from Xcode itself - open Xcode.app package. IOKit framework is located in Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks
simply copy absent files (or make link) to
Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/System/Library/Frameworks/IOKit.framework
and to
Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.0.sdk/System/Library/Frameworks/IOKit.framework
and also for all simulator platforms
You should know that not all functions of IOKit can work on real device (but they work under simulator) due to iOS sandbox security.
But You can work with IORegistry well. My first project on iOS was implemetation of the IORegistryExplorer.
Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: paperclip - converting tiff images into jpg or png I'm using paperclip to allow user to upload images and I want to convert an image into jpg/png
only if it's a tiff image.
I am using the following code in my image.rb:
validates_attachment_presence :data
validates_attachment_content_type :data,
:content_type => ['image/jpeg', 'image/pjpeg',
'image/jpg', 'image/png', 'image/tif', 'image/gif'], :message => "has to be in a proper format"
I would like to know if it is possible to convert tiff images into jpg or png when uploading them.
Thanks a lot
A: Finally found a solution. Thought it might be helpful to somebody else.
In the image.rb, enter the following lines of code:
:styles => {
:thumb => ["150x172#",:jpg],
:large => ["100%", :jpg]
}
This will create 2 additional folders in the main image folder, thumb and large. If you want to display the images (which were tiff originally), simply display the jpeg version found in the 'large' folder.
Note that the original tiff images will still be stored in the 'original' folder under the main image folder.
Cheers
A: Tanya your solution is good. However if you don't care about the file type, you can store all images as jpg by passing the :original option as well. Example:
:styles => {
....
:original => ["100%", :jpg]
}
That will help ensure nowhere where the file is called will you run into issues.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Search with Jquery checkbox array through a many-many MySql db? I've been slowly learning and building my little search system - however I seem stuck at this tough question.
I have a many-many relation database of events. Each event can have multiple music styles stored in the events_music_styles table. The events_music_styles table has it's own ID column, EVENT_ID and MUSIC_STYLE_ID.
How can I search (through the use of a checkbox array) for music styles in the events table when the music styles and events are referenced in another table all together?
This is what I have so far:
HTML
<input type="checkbox" class="group1" id="checkbox1" value="latino">Latino<BR />
<input type="checkbox" class="group1" id="checkbox2" value="rock">Rock<BR />
<input type="checkbox" class="group1" id="checkbox3" value="oldies">Oldies<BR />
<input type="checkbox" class="group1" id="checkbox4" value="reggae">Reggae<BR />
<div id="AnswerField"></div>
Jquery
var VarDancingTo = new Array();
$('.group1:checked').each(function () {
VarDancingTo[VarDancingTo.length] = $(this).val();
});
$("#AnswerField").text( VarDancingTo.join(', '));
and a simple PHP table with my complete database (if that's of any help)
$query = 'SELECT e.ID, e.EVENT_NAME, e.EVENT_DATE, e.ENTRANCE_PRICE, v.BEER_PRICE, v.WINE_PRICE, v.SPIRITS_PRICE, v.VENUE_NAME, l.LOCATION, GROUP_CONCAT(ms.MUSIC_STYLE_NAME) as `Styles`'.
' FROM events AS e'.
' INNER JOIN venues as v ON e.VENUE_LOCATION = v.ID'.
' INNER JOIN locations AS l ON e.VENUE_LOCATION = l.ID'.
' INNER JOIN events_music_styles AS ems ON e.ID = ems.EVENT_ID'.
' INNER JOIN music_styles AS ms ON ms.ID = ems.MUSIC_STYLE_ID'.
' GROUP BY e.ID';
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Here's the relations between the tables:
Here are the create table statements:
SET FOREIGN_KEY_CHECKS=0;
-- Drop table locations
DROP TABLE IF EXISTS `locations`;
CREATE TABLE `locations` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`LOCATION` varchar(50),
`LOCATION_SK` varchar(50) CHARACTER SET utf8,
PRIMARY KEY(`ID`)
)
ENGINE=INNODB;
-- Drop table music_styles
DROP TABLE IF EXISTS `music_styles`;
CREATE TABLE `music_styles` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`MUSIC_STYLE_NAME` varchar(50),
`MUSIC_STYLE_NAME_SK` varchar(50) CHARACTER SET utf8,
PRIMARY KEY(`ID`)
)
ENGINE=INNODB;
-- Drop table venue_types
DROP TABLE IF EXISTS `venue_types`;
CREATE TABLE `venue_types` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`TYPE_NAME` varchar(50),
`TYPE_NAME_SK` varchar(50) CHARACTER SET utf8,
PRIMARY KEY(`ID`)
)
ENGINE=INNODB;
-- Drop table venues
DROP TABLE IF EXISTS `venues`;
CREATE TABLE `venues` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`VENUE_TYPE` int(11),
`VENUE_LOCATION` int(11),
`VENUE_NAME` varchar(50),
`ADDRESS` varchar(255),
`ICON_URL` varchar(100),
`PAGE_URL` varchar(100),
`LAT` int(100),
`LNG` int(100),
`VENUE_CLOSE_T_MO` varchar(50),
`VENUE_CLOSE_T_TU` varchar(50),
`VENUE_CLOSE_T_WE` varchar(50),
`VENUE_CLOSE_T_TH` varchar(50),
`VENUE_CLOSE_T_FR` varchar(50),
`VENUE_CLOSE_T_SA` varchar(50),
`VENUE_CLOSE_T_SU` varchar(50),
`BEER_PRICE` int(11),
`WINE_PRICE` int(11),
`SPIRITS_PRICE` int(11),
`IF_COFFEE` int(1) DEFAULT '1',
`IF_DRAFT_BEER` int(1) DEFAULT '0',
`IF_TEA` int(1) DEFAULT '1',
`IF_HOT_CHOCOLATE` int(1) DEFAULT '0',
`IF_BILLIARD` int(1) DEFAULT '0',
`IF_HOOKAH` int(1) DEFAULT '0',
`IF_OUTDOOR_PATIO` int(1) DEFAULT '0',
`IF_OUTDOORS` int(1) DEFAULT '0',
`IF_NON_SMOKING_AREA` int(1) DEFAULT '0',
PRIMARY KEY(`ID`),
CONSTRAINT `Ref_01` FOREIGN KEY (`VENUE_TYPE`)
REFERENCES `venue_types`(`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `Ref_02` FOREIGN KEY (`VENUE_LOCATION`)
REFERENCES `locations`(`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE=INNODB;
-- Drop table events
DROP TABLE IF EXISTS `events`;
CREATE TABLE `events` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`VENUE_LOCATION` int(11),
`EVENT_NAME` varchar(50),
`EVENT_DATE` date,
`EVENT_NAME_SK` varchar(50) CHARACTER SET utf8,
`EVENT_DESC` varchar(255),
`EVENT_DESC_SK` varchar(255) CHARACTER SET utf8,
`IMAGE_URL` varchar(255),
`EVENT_URL` varchar(255),
`START_TIME` varchar(50),
`END_TIME` varchar(50),
`IF_ENTRANCE` int(1) DEFAULT '0',
`ENTRANCE_PRICE` int(11) DEFAULT '0',
PRIMARY KEY(`ID`),
CONSTRAINT `Ref_03` FOREIGN KEY (`VENUE_LOCATION`)
REFERENCES `venues`(`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE=INNODB;
-- Drop table events_music_styles
DROP TABLE IF EXISTS `events_music_styles`;
CREATE TABLE `events_music_styles` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`EVENT_ID` int(11),
`MUSIC_STYLE_ID` int(11),
PRIMARY KEY(`ID`),
CONSTRAINT `Ref_05` FOREIGN KEY (`MUSIC_STYLE_ID`)
REFERENCES `music_styles`(`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `Ref_06` FOREIGN KEY (`EVENT_ID`)
REFERENCES `events`(`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE=INNODB;
SET FOREIGN_KEY_CHECKS=1;
A: You might want to make the pair of foreign keys (EVENT_ID, MUSIC_STYLE_ID) in your events_music_styles a unique index, otherwise you'll be able to associate the same style with the same event multiple times.
CREATE UNIQUE INDEX index_name
ON events_music_styles (EVENT_ID, MUSIC_STYLE_ID);
As for getting the events plus the list of associated music types, I suspect you'll have to do some processing of the data in the front-end (javascript, PHP, whatever else you're using). The GROUP BY approach won't work, because you'll only get one style per event. This will require a bit of rewriting of your query, and somewhat more rewriting of your query fetching logic to format the data as needed.
$query = '
SELECT
e.ID,
e.EVENT_NAME,
e.EVENT_DATE,
e.ENTRANCE_PRICE,
v.BEER_PRICE,
v.WINE_PRICE,
v.SPIRITS_PRICE,
v.VENUE_NAME,
l.LOCATION,
ms.MUSIC_STYLE_NAME
FROM events AS e
INNER JOIN venues as v ON e.VENUE_LOCATION = v.ID
INNER JOIN locations AS l ON e.VENUE_LOCATION = l.ID
INNER JOIN events_music_styles AS ems ON e.ID = ems.EVENT_ID
INNER JOIN music_styles AS ms ON ms.ID = ems.MUSIC_STYLE_ID;';
if ($result = mysql_query ($query))
{
$eventDetails = array ();
// I think keys always end up lowercase when returned by MySQL so I'm using lower case key names here. If it doesn't work then try with upper case.
while ($row = mysql_fetch_assoc ($result))
{
// Add the event details to the results if they don't already exist in the array
if (!array_key_exists ($row ['id'], $eventDetails))
{
$eventDetails [$row ['id']] = array (
'ID' => $row ['id'],
'EVENT_NAME' => $row ['event_name'],
'EVENT_DATE' => $row ['event_date'],
// Insert your other columns here
'STYLES' => array ($row ['music_style_name'])
);
}
// As we've already seen this event before we only need to add the musical style from this row to the result
else
{
$eventDetails [$row ['id']]['STYLES'][] = $row ['music_style_name'];
}
}
}
else
{
// Error handling logic here
}
This should produce an array like the one below:
array (
1 => array (
'ID' => 1,
'EVENT_NAME' => 'Some event name',
'EVENT_DATE' => '11/11/2011',
'STYLES' => array (
0 => 'rock',
1 => 'jazz'
)
),
2 => array (
'ID' => 2,
'EVENT_NAME' => 'Some other event name',
'EVENT_DATE' => '22/11/2011',
'STYLES' => array (
0 => 'rock',
1 => 'techno',
2 => 'dance'
)
),
// ...
n => array (
'ID' => n,
'EVENT_NAME' => 'Yet another event',
'EVENT_DATE' => '12/12/2012',
'STYLES' => array (
0 => 'classical',
1 => 'prog rock',
2 => 'folk'
)
)
)
Alternatively, if you just want a comma-separated list for the genres, you can create a string for STYLES instead of an array, and do a string concat each time through the loop instead of adding the style to an array.
NOTE: As I don't have access to a full database of your data and have no time to build a mockup database, I've not tested the above code. It ought to work but I can't make any promises. Hopefully, even if it doesn't work it should still serve as a guide regarding how to do what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Autoadvancing gallery animation I have a Gallery widget set up to auto advance every 10000ms. However the transition between views is instantaneous and I would prefer to have a transition.
My advancing method is like so:
private void tickerAdvance() {
int selectedItemPosition = mTickerGallery.getSelectedItemPosition();
if (selectedItemPosition + 1 == mTickerGallery.getCount()) {
mTickerGallery.setSelection(0, true);
} else {
mTickerGallery.setSelection(selectedItemPosition + 1, true);
}
}
I was under the impression that setting the animation to true would cause it to animate between states. In my XML I've also added animationDuration="500", however the transition still pops between states instantly.
A: The problem is because you have used the setSelection() which obviously won't give you the feel of an Gallery being scrolled. SO instead of using setSelection() you have to override the onScroll() of gallery.
Here is how you do it.
Assuming that you have made the necessary steps for auto advancing periodically, now do this code.
MotionEvent e1, e2;
gallery.onScroll(e1, e2, scroll_limit , 0); //scroll limit is your integer variable for scroll limit.
A: The answer I came up with is that the Gallery API is terribly non-extensible. There are multiple package private or private methods that would unlock this functionality without a kludge including moveNext, FlingRunnable.startwithdistance, and scrollToChild. Alas, they are all unavailable.
Instead the best answer I was able to come up with was to override setSelection to get all the behaviors I needed. In the setSelection method I reverse the deceleration algorithm to calculate a velocity for a calculated distance and then call onFling. This is a nasty kludge could be made a ton better by making any of the above methods protected or public (I can't fathom a reason why at least moveNext and scrollToChild shouldn't be).
A: i had a similar task to make item to item animation and i decided to choose gallery, so i tried a lot of things, but the best way is to subclass gallery and add this:
boolean avoidSound = false;
public void showNext() {
avoidSound = true;
this.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
}
public void playSoundEffect(int soundConstant) {
if (avoidSound) {
avoidSound = false;
} else {
super.playSoundEffect(soundConstant);
}
}
just call showNext() and it will do an animation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JBoss6 with REST client (jersey-client) I want to consume a REST service in my web app (.war with 6.0.0.Final), but have problems adding jersey-client libs:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.9.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
With this configuration I get the following error during JBoss startup:
08:11:28,297 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].
[localhost].[/test]] Exception starting filter Resteasy:
java.lang.ClassCastException: com.aht.erp.web.rest.JaxRsActivator
cannot be cast to javax.ws.rs.core.Application
My webapp has an activated JAX-RS with the following annotation:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/rest")
public class JaxRsActivator extends Application {}
If I don't add the dependecy my war starts fine, but of course I get a NoClassDefFoundError: com/sun/jersey/api/client/config/ClientConfig when the jersey-client is called. By excluding jersey-core I get this error: NoClassDefFoundError: com/sun/jersey/core/util/FeaturesAndProperties.
A: I believe the problem is that you are trying to mix two different jax-rs implementations in your web app. For your RESTful resource you are using RESTEasy, while on the client side you want to use Jersey - all utilized by the same jar. However the Jersey client depends on Jersey core, which conflicts with RESTEasy. So, you'll either have to rely on RESTEasy client API, or switch to Jersey for your server-side as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: XSLT not working correctly to remove an element Given the following XML file:
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Fragment>
<DirectoryRef Id="INSTALLLOCATIONAGENT">
<Component Id="cmp140DC3A98DEC1F1F528260F1806A3999" Guid="*">
<File Id="fil57A7BE096A39C9A45B8306DDA29D5B2E" KeyPath="yes" Source="SourceDir\Program.exe" />
</Component>
<Component Id="cmpD2075C288DC3B6998C8A7C7E7DF78EB7" Guid="*">
<File Id="filD8C1A7C27FA3DCB1A863FC3F0420B444" KeyPath="yes" Source="SourceDir\System.Data.SqlServerCe.dll" />
</Component>
<Directory Id="dir1377A3F5233B835FB05556A0B1386070" Name="amd64">
<Component Id="cmp41C2DD9BFF63ABDC86410CFD8251F745" Guid="*">
<File Id="fil87F68441B60D7259CD41A2CDB411AFC6" KeyPath="yes" Source="SourceDir\amd64\sqlcecompact40.dll" />
</Component>
<Component Id="cmpAA3318DF657EDDE7DF58C4CF51DEE2A9" Guid="*">
<File Id="fil97009E86AAFE6C33EF01BF2EBF205249" KeyPath="yes" Source="SourceDir\amd64\sqlceer40EN.dll" />
</Component>
<Component Id="cmp2DD5FBEDECB367F9B56953EBE56D9AEA" Guid="*">
<File Id="fil42F87CDC8C959316EC83D9271E737C38" KeyPath="yes" Source="SourceDir\amd64\sqlceme40.dll" />
</Component>
</Directory>
</Directory>
</DirectoryRef>
</Fragment>
<Fragment>
<ComponentGroup Id="RetailClub.Agent_Project">
<ComponentRef Id="cmpFFCDA0633C7840EACD8A6CEEFA6EC93A" />
<ComponentRef Id="cmp96A706AAAB79BB01C9E42BBE9D4DD252" />
<ComponentRef Id="cmpF2F2F70F2405BCD6BBBB9579CE9EF19B" />
<ComponentRef Id="cmpF292744916F0F54B44B137EF41E6B160" />
<ComponentRef Id="cmpFAA31CC5660D6586E79ECC5D008CB730" />
<ComponentRef Id="cmp9D128034819C12206F13D1EEAABC27A3" />
<ComponentRef Id="cmpA4ED042A16E7DD31342DA0D47DC7E455" />
<ComponentRef Id="cmpD531F67ABC1E63E8DB26A6F38D95B212" />
<ComponentRef Id="cmp7A771F6C7D7E3E3DD707534E56E6A872" />
<ComponentRef Id="cmpC60669855D22EE54FCA4855DF53BA0E7" />
<ComponentRef Id="cmp6A8D269A1F473E6F4B091023BC661C5A" />
<ComponentRef Id="cmpBB8EE28B3ECA91AC087B9D6D365FB19F" />
<ComponentRef Id="cmpA19E7221E858827A2E5A08010A1AB80A" />
<ComponentRef Id="cmp140DC3A98DEC1F1F528260F1806A3999" />
<ComponentRef Id="cmpAC61AD2134F0DA7E4A92C673648AAF1F" />
<ComponentRef Id="cmp71A3488860AA96C23B2B73BE84AD944D" />
<ComponentRef Id="cmpD79B6BCF2C02DFE7B4D089414E982035" />
<ComponentRef Id="cmp6336B810161B473EFA5920B8ACA2101D" />
<ComponentRef Id="cmpD2075C288DC3B6998C8A7C7E7DF78EB7" />
<ComponentRef Id="cmp625073995F3B29478ACC5A45E5005184" />
<ComponentRef Id="cmp6919DDAC4EF84609E800F79B84ACE037" />
<ComponentRef Id="cmpD411331F9F18AC0A62F4D342193C578B" />
<ComponentRef Id="cmp41C2DD9BFF63ABDC86410CFD8251F745" />
<ComponentRef Id="cmpAA3318DF657EDDE7DF58C4CF51DEE2A9" />
<ComponentRef Id="cmp2DD5FBEDECB367F9B56953EBE56D9AEA" />
<ComponentRef Id="cmpD6209C86C787D37B2BC10491715961A4" />
<ComponentRef Id="cmpDEFFF257D183C61CF106691B502C9B92" />
<ComponentRef Id="cmpAE88027B6D0222521E0ABA368319FF67" />
<ComponentRef Id="cmpF2490B3F3B6C3AFDCCE0B7D9E04B1307" />
<ComponentRef Id="cmpC3992B351478947A4EC528039072EE48" />
<ComponentRef Id="cmp70020D3E903A3C6460350DB8EDA762AE" />
<ComponentRef Id="cmp09907E3F88C8846C5036ED1B4E1E81DF" />
<ComponentRef Id="cmpB35A402A2163C959687B4BA4121F079A" />
<ComponentRef Id="cmp775993523FE108E37468C65AD0ACB4B4" />
<ComponentRef Id="cmp05F27393E5D1CAA313305B4861210845" />
<ComponentRef Id="cmp7FF316CEF60AD840CF18827C447F6127" />
<ComponentRef Id="cmpF6ECEDC852A8809386FCE1F6FD6BF773" />
<ComponentRef Id="cmp359949C0EE3700CD3FEDC58C2938CA02" />
<ComponentRef Id="cmpF07C3AB85632B07E2F0F35C8E102F750" />
<ComponentRef Id="cmp9BF2FC39D1074790EA6D5E031D4E9665" />
<ComponentRef Id="cmp781555C9539D6B197CC3E2862D633313" />
<ComponentRef Id="cmpA3348368AD2302BEA9380BFC071D019F" />
<ComponentRef Id="cmp976CCA18B7D5A52752D172D9F1B353E5" />
<ComponentRef Id="cmpD67BE195D2659B6309E067CEFCEBA782" />
<ComponentRef Id="cmpF8865B27ABD17AFD84B4C6DA99BA5982" />
<ComponentRef Id="cmp9DA6349D71DB330B293596A73268CCA4" />
<ComponentRef Id="cmpD6C59BB2981DADF2241DC165EDF05FD8" />
<ComponentRef Id="cmp0B8BBF1185264AB2CE511BAFC03E2F1B" />
</ComponentGroup>
</Fragment>
</Wix>
I would like to remove the Component Element and related ComponentRef that contains the Source attribute "SourceDir\Program.exe".
I therefore apply the following XSLT, based on other SO accepted answer:
Removing related elements using XSLT 1.0
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:key name="configComponent"
match="Component[File/@Source[substring(.,
string-length() - string-length('exe') + 1) = 'exe']]"
use="@Id" />
<xsl:template match="Component[key('configComponent', @Id)]" />
<xsl:template match="ComponentRef[key('configComponent', @Id)]" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
The result is the same original XML with no elements removed.
I am using http://www.xmlper.com/ to test.
Any ideas as to why it is not working?
Regards
A: I think it's all about XML namespaces.
Try the following:
*
*add an XML namespace for WiX elements:
xmlns:wix="http://schemas.microsoft.com/wix/2006/wix"
*
*prefix each WiX element in the XSLT stylesheet with wix:, like this:
<xsl:template match="wix:Component[key('configComponent', @Id)]" />
I don't think this is optimal or the "right" way to it, but it works for me :-)
A: <?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
exclude-result- prefixes="msxsl"
xmlns:wix="http://schemas.microsoft.com/wix/2006/wi">
<!-- Copy all attributes and elements to the output. -->
<xsl:template match="@*|*">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:apply-templates select="*" />
</xsl:copy>
</xsl:template>
<xsl:output method="xml" indent="yes" />
<xsl:key name="exe-search"
match="wix:Component[contains(wix:File/@Source, 'Program.exe" use="@Id" />
<xsl:template match="wix:Component[key('exe-search', @Id)]" />
<xsl:template match="wix:ComponentRef[key('exe-search', @Id)]" />
</xsl:stylesheet>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Calling Javascript on Client click event of Ajax tab panel I want to perform some check after OnClientClick event of Tab Panel in a Javascript function. If my conditions return true I want to allow tab change otherwise want to restrict user on same tab without posting back. PFB code block.
Any help will be great...
<cc1:TabContainer ID="tabContainer" runat="server" AutoPostBack="false"
BackColor="Red" CssClass="ajax__tab_yuitabview-theme">
<cc1:TabPanel runat="server" HeaderText="A" ID="tbPrograms" OnClientClick="ClickMe;return false">
<ContentTemplate>
Tab1
</ContentTemplate>
</cc1:TabPanel>
Tab2
<ContentTemplate>
<uc2:EmployerResources ID="B" runat="server" />
</ContentTemplate>
</cc1:TabPanel>
Tab3
<ContentTemplate>
<uc3:ExternalResources ID="C" runat="server" />
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
A: Give only the name of the javascript function like tabPanel1.OnClientClick="MyJavascriptFunction" and not like this tabPanel1.OnClientClick="MyJavascriptFunction()"
A: Did you try:
onclientactivetabchanged="ClickMe;return false"
A: add clickme function in attributes of tab panel
at the loading of page
like
tbPrograms.Attributes.Add("onClick","ClickMe(); return false;");
I hope this will work
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: unable to automatically debug wcf service I am new to WCF. I have created one sample service to insert the record into the customer table. when running the application i am getting an error - "Unable to automatically debug 'Home.Service'. The remote procedure could not be debugged. This usually indicates that debugging has not been enabled on the server."
I am using VS 2010.
Can somebody help me pls
The web.config code (as in comment):
<compilation debug="true" targetFramework="4.0">
<!--<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>-->
</compilation>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Remove the blank spaces I have an external text file with a list of numbers like this:
35454
54545
45444
I want to output it like this:
'35454'
'54545'
'45444'
I would post my code, but Stack Overflow keeps giving me errors and cutting off my code when I try to post it.
A: It appears you mean that there's trailing spaces after the numbers?
You're looking for trim()
http://php.net/manual/en/function.trim.php
A: I'm not sure exactly what you mean but this will do assuming that text.txt contains the values
$vals = file('text.txt');
foreach($vals as $v){
echo '\''.trim($v).'\'<br />';
}
To remove blank spaces at the beginning and the end you can use trim or to remove all spaces something like $num = str_replace(' ','',$num); could work
A: If those strings always are numbers, you you can cast them to int like
var_dump((int)' 42 ');
which will output
int(42)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Check actionscript 3 variable type? i have two objects [object MovieClip] [object ContentDisplay]
i have to differentiate them abut i can't find a method in as3 check variable type, like in php have is_int...
A: getQualifiedClassName(obj); returns class name of given object
You can also check if object is for example a movieclip: if (obj is MovieClip) {/* do something */}
A: A similar strategy to is_int() would be to use the is keyword like this:
var mc:MovieClip = new MovieClip();
trace(mc is MovieClip); // true
trace(mc is String); // false
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to fix firefox connection untrusted Firefox gives me connection untrusted for SSL https, and why is that, Chrome shows https in green so, chrome OK, firefox not, why ?
A: when i install ff 16.0.2, i seem to have same prob with you(untrusted connection especially firefox addon)..For me, it basically cause by my nod32 antivirus, i try go to setting>protocol filtering>ssl>certificates>untick "add the root certificate to known browser''(make sure ff really close)..then tick it again and click OK..done
A: Please check this:
https://developer.mozilla.org/En/Displaying_web_content_in_an_extension_without_security_issues
A: I thing you can bypass the warning:
You can tell Firefox to bypass these certificate warnings. You should only bypass the warning if you're sure that the site is legitimate. Legitimate public sites will not ask you to do this. An invalid certificate can be an indication of a web page that will defraud you or steal your identity.
1.On the warning page, click Or you can add an exception....
2.Click Add Exception.... The Add Security Exception dialog will appear.
3.Click Get Certificate.
4.Read the text describing the problems with this site.
5.Click Confirm Security Exception if you want to trust the site.
http://support.mozilla.com/en-US/kb/Secure%20Connection%20Failed
http://support.mozilla.com/en-US/kb/Firefox%20cannot%20connect%20securely%20because%20the%20site%20uses%20an%20older%20insecure%20version%20of%20the%20SSL%20protocol
If any of these TS won't work, then try to update to FF V7. Don't forget to file a bug in bugzilla with all the necessary information.
A: However if you wish to access sites without accepting the certificate each time, use the add-on skip-cert-error "https://addons.mozilla.org/en-US/firefox/addon/skip-cert-error"
A: I had this weird issue "Your connection is not secure" whereas Chrome works like a charm.
Actually, it is because i let the corporate pac script to manage the proxy setup ticking the option "use system proxy settings". Actually, Firefox don't like it !
When i switch back to the manual proxy settings, all get back to work.
Of course, you need to known proxy params.
Go & surf ...
A: Change your Date to current date :D
I had same issue
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Extending Django-Registration: Getting error on setting url.py am trying to follow the answers provided in Django-Registration & Django-Profile, using your own custom form and Creating a Django Registration Form by Extending Django-Registation Application to extend the django-registration form. I added the following code in url.py
url(r'^accounts/register/$', register, {'backend': 'registration.backends.default.DefaultBackend','form_class': UserRegistrationForm}, name='registration_register'),
(r'^accounts/', include(regUrls)),
but now whenever i access http://localhost:8000/accounts/register/ am getting the following error
register() got an unexpected keyword argument 'form_class'
Please help me out. Why am i getting this error? I goggled a lot but still i could not figure out a solution.
A: That dictionary in your urls.py entry gets passed as keyword arguments to the view function, register, when you access the page. register doesn't have a keyword argument form_class.
If the register your first link is referring to is the register from the second, the first link is wrong. Because that register doesn't accept that keyword arg. One answer seems to define a different register method, but I think that might be something else(?)
If you understand what the form_class is supposed to be passed to, you could just add the kwarg to register manually too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there any way to authenticate a user using cookies in asp.net using form authentication Is there any way to authenticate user through Cookies....
A: That's exactly what the Forms Authentication module in ASP.NET uses to track authenticated users.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you differentiate private member variable in objective-c? for private methods,
I could use
@interface MyClass(PrivateMethods)
- (void) _foo;
@end
How do you declare a private member variable in objective c?
A: http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocDefiningClasses.html#//apple_ref/doc/uid/TP30001163-CH12-TPXREF127
@interface MyClass : Superclass {
@private
NSString * privateString;
}
@end
A: You can declare it as follows..
@private //variable;
Check this question out.
Question- private-instance-variable
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to change the RatingBar direction? Does anyone knows if its possible to make the RatingBar go from right-to-Left instead of left to right, or have an idea how to do it?
A: You can use android:rotation="180" in your Ratingbar to rotate it
i used this way on my read-only Ratingbars, i dont know if this will effect interacting with the Ratingbar.
A: Use attribute android:scaleX="-1"
OR
package com.example.selection;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RatingBar;
public class InvertRatingBar extends RatingBar {
public InvertRatingBar(Context context) {
super(context);
}
public InvertRatingBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public InvertRatingBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int width = this.getMeasuredWidth();
event.setLocation(width - event.getX(), event.getY());
return super.onTouchEvent(event);
}
@Override
protected synchronized void onDraw(Canvas canvas) {
int width = this.getMeasuredWidth();
Matrix matrix = canvas.getMatrix();
matrix.preTranslate(width, 0);
matrix.preScale(-1.f, 1);
canvas.setMatrix(matrix);
super.onDraw(canvas);
}
}
A: You have to customize the RatingBar..
However you just have to play tricks with displaying RatingBar Images & then some sort of reverse calculations.
Trick will be displaying reverse Images in RatingBar.. swap selected and unselected images in RatingBar.
Allow user to rate on RatingBar. You have to swap selected and unselected calculations. I mean you have to do reverse calculations.
Complete Working example of custom RatingBar on StackOverflow answered by me only.
Download RatingBar icons from here : http://developer.android.com/guide/practices/ui_guidelines/icon_design.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: java: find RSS file(s) of a website I am writing a java application; using Rome lib for reading RSS feeds of a RSS file of a website. I can read and manage feeds using Rome but I can not find the exact URL path of RSS file. I know there is a line like this in html file specifying the RSS xml file url:
<link rel="alternate" type="application/rss+xml" href="/rss.ashx" title="Rss feed for yourdomain.com" />
what is a clean way to find RSS file, url path in java?
thank you all
A: You could use a xpath expression on the html page to get the <link />-Node and extract the href attribute. Out of the box this will only work on wellformed XHTML pages. Maybe you need to fix the document before applying the xpath.
Or you use something like http://jsoup.org/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Member Mapping specified is not valid.Error in ADO.net Entity Framework when add new column in database? I am very new to ADo.net entity framework and i am getting the following error
The type 'Edm.Byte' of the member 'IsActive' in the conceptual side type
NopSolutions.NopCommerce.BusinessLogic.Data.Language' does not match with the type
System.Boolean' of the member 'IsActive' on the object side type NopSolutions.NopCommerce.BusinessLogic.Directory.Language'.
as far i understand that there is some missing to relating the data type of edm and object
but i made a column in database table which is bit type and in langauge.cs i declare the property of
public bool IsActive { get; set; }
any details needed i can post here
EDIT :
as i google around i found this question on stackoverflow
et-model-property-to-boolean-in-entity-framework which is changing the Byte to Boolean for mapping tinyint
but in my case i have in database is also the bit.
A: Assuming that you have an .edmx-file you can modify. Open it in an XML-editor and search for the <edmx:ConceptualModels>-element. This should contain the definition of your entities, look for the <EntityType Name="Language">-element, which should declare something like this:
<Property Name="IsActive" Type="Byte" Nullable="false" />
Change the Type-attribute to Boolean.
I'm pretty sure that you could also do this in the designer, but if you don't have direct access to the .edmx let me know and we figure something out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to detect array equality in JavaScript? There are two arrays in JavaScript, they are both in the following format:
[{'drink':['alcohol', 'soft', 'hot']}, {'fruit':['apple', 'pear']}];
I need to detect if the two arrays are equal or not. they are considered equal if they contain the same elements in a different order. How can I make that?
A: *
*Check the length of both arrays
*Loop through the first array, compare each variable to the second array.
If 1 and 2 are both the same, your array is equal.
Function to compare objects/arrays:
Looping through true arrays can be achieved through for(var i=0; i<array.length; i++).
Walking through the properties of such an object can be done by for(var i in object).
function recursiveCompare(obj, reference){
if(obj === reference) return true;
if(obj.constructor !== reference.constructor) return false;
if(obj instanceof Array){
if(obj.length !== reference.length) return false;
for(var i=0, len=obj.length; i<len; i++){
if(typeof obj[i] == "object" && typeof reference[j] == "object"){
if(!recursiveCompare(obj[i], reference[i])) return false;
}
else if(obj[i] !== reference[i]) return false;
}
}
else {
var objListCounter = 0;
var refListCounter = 0;
for(var i in obj){
objListCounter++;
if(typeof obj[i] == "object" && typeof reference[i] == "object"){
if(!recursiveCompare(obj[i], reference[i])) return false;
}
else if(obj[i] !== reference[i]) return false;
}
for(var i in reference) refListCounter++;
if(objListCounter !== refListCounter) return false;
}
return true; //Every object and array is equal
}
If you don't understand the function, feel free to request an explanation at the comments.
A: With Javascript, you can't check if arrays are equals, but you can compare them like this:
var arr1 = ['alcohol', 'soft', 'hot'],
arr2 = ['apple', 'pear'],
arr3 = ['soft', 'hot', 'alcohol'];
function isSame(a1, a2){
return !(a1.sort() > a2.sort() || a1.sort() < a2.sort());
}
console.log( isSame(arr1, arr2) ); //false
console.log( isSame(arr1, arr3) ); //true
The sort put all elements in the same order, and if both < and > comparisons are false it means both are the same.
A: Does this answer your question?
How to check if two arrays are equal with JavaScript?
var equal = array1.compareArrays(array2);
A: You can try this JSON.stringify(array1)===JSON.stringify(array2); if you want the order also to be identical in both the arrays.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Return/Cancel Order - Shopping Cart
*
*I have implemented the Custom Shopping Cart in my site. My site
allowed paying the amount in three different checkouts.
a. Google
b. PayPal
c. Authorize.Net
*Once customers place an order they can view their order details and status from Order Management page. I have defined two processes
a. If payment is success - Customer can Return the Order.
b. if payment is declined/pending - Customer can Cancel the Order.
My questions
How can i process the "Cancel Order" if buyer requested. Can i programmatically handle this process and stop the payment process in payment gateway (Google, Paypal and so)
Return Order
*
*a. Can i programmatically handle this process and return the payment
to buyer account from payment gateway (Google, PayPal and so).
b. Buyer can request a return to Merchant. Merchant will process and
return the order manually (Already implemented)
Thanks,
Velu
A: If I understand the questions correctly you are looking for an API to programatically cancel and refund orders.
Please have a look at the Checkout Notification and Order Processing APIs. You can use those APIs to receive order information and update order fulfillment status (e.g charge, ship, refund, cancel). You'll need to implement a service that can communicate with Google's servers.
More information in this doc:
http://code.google.com/apis/checkout/developer/Google_Checkout_XML_API_Processing.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can we differentiate a variable against a pointer variable Yesterday while I was coding in C, my friend asked me pointing to a variable is it pointer or a variable ? I stucked up for a while. I didnt find an aswer to it , I just have to go back and search it and tell him.But I was thinking is there any function to differentiate them.
Can we differentiate a variable against a pointer variable
int a;
sizeof(a); // gives 2 bytes
int *b;
sizeof(b); // gives 2 bytes
// if we use sizeof() we get same answer and we cant say which is pointer
// and which is a variable
Is there a way to find out a variable is a normal variable or a pointer? I mean can someone say that it is a pointer or a variable after looking at your variable that you have declared at the beginning and then going down 1000 lines of your code?
After the comment
I wanted to say explicitly it's a 16 bit system architecture.
A: First, the question "Is it a pointer or a variable" doesn't make much sense. A pointer variable is a variable, just as an integer variable, or an array variable, is a variable.
So the real question is whether something is a pointer or not.
No, there's no function that can tell you whether something is a pointer or not. And if you think about it, in a statically typed language like C, there can't be. Functions take arguments of certain specified types. You can't pass a variable to a function unless the type (pointer or otherwise) is correct in the first place.
A: You mean differentiate them at run time without seeing the code? No, you can't. Pointers are variables that hold memory address. You can't check it at run time. That means, there is no such function isPointer(n) that will return true/false based on parameter n.
A: You can deduce the type from the use.
For example:
char* c;
...
c[0] = 'a';
*c = 'a';
Indexing and dereferencing would let you know it's a pointer to something (or it's an array if defined as char c[SOME_POSITIVE_NUMBER];).
Also, things like memset(c,...), memcpy(c,...) will suggest that c is a pointer (array).
OTOH, you can't normally do with pointers most of arithmetic, so, if you see something like
x = c * 2;
y = 3 / c;
z = c << 1;
w = 1 & c;
then c is not a pointer (array).
A: Three things:
*
*What platform are you using where sizeof(int) returns 2? Seriously
*Pointers are types. A pointer to an int is a type, just like an int is. The sizes of a type and a pointer to that type are sometimes equal but not directly related; for instance, a pointer to a double (on my machine, at least) has size 4 bytes while a double has size 8 bytes. sizeof() would be a very poor test, even if there was a situation where such a test would be appropriate (there isn't).
*C is a strictly typed language, and your question doesn't really make sense in that context. As the programmer, you know exactly what a is and you will use it as such.
A: If you'd like to be able to tell whether a variable is a pointer or not when you see it in the source code, but without going back to look at the declaration, a common approach is to indicate it in the way you name your variables. For example, you might put a 'p' at the beginning of the names of pointers:
int *pValue; /* starts with 'p' for 'pointer' */
int iOther; /* 'i' for 'integer' */
...or even:
int *piSomething; /* 'pi' for 'Pointer to Integer' */
This makes it easy to tell the types when you see the variable in your code. Some people use quite a range of prefixes, to distinguish quite a range of types.
Try looking up "Hungarian notation" for examples.
A: no , you can't.
and what is the usage, as each time u run the code the pointer address will be different ?? however u can subtract two pointers and also can get the memory address value of any pointer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Protocols & delegates
Possible Duplicate:
What is the difference between Notifications, Delegates, and Protocols?
I am new in Objective C. Would like to understand the concept of Protocols and Delegates in a few words. Like under what situation should I consider declaring a Protocol, and then consume it in my classes as delegates or let other classes consume it.
Instead of Protocols why can't I make my classes do the same job?
Thanks for your time.
A: Protocols are like contracts, Your class must implement all methods that are @required, @optional are on the other hand not required.
Instead of Protocols why can't I make my classes do the same job?
You can, but like I wrote above, its a contract. You know that
class
implements the (Required) methods.
delegate is (should be) a weak reference to the class that implements the given protocol.
You are recommended to use the following attribute on your delegateproperty:
@property (assign) id<yourProtocol> delegate;
Notice that you don't retain your delegate. You you (weak) reference because you dont want to get into a retain circle (A retains B, and B retains A).
I hope my explanation helped a bit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JSTL xmlns namespace differences between JSF 1.2 and JSF 2.x? I have a JSF 1.2 based webapp from which I copied the JSTL import
xmlns:c="http://java.sun.com/jstl/core"
You can also find this import in many places on the Internet. I can't remember whether the above worked in my former web project or not, in any case, it does not work in my current JSF 2.0 based webapp. I got a warning from the container saying:
Warning: This page calls for XML namespace http://java.sun.com/jstl/core declared with prefix c but no taglibrary exists for that namespace.
I then changed the import to
xmlns:c="http://java.sun.com/jsp/jstl/core"
... which removed all headaches using <c:forEach> in a JSF/RichFaces-based webapp.
What's the trick here? Have there been any changes to the JSTL import URL from JSF 1.2 to 2.x? Or is the former line generally wrong (in JSF)? What's the difference between the two?
A: Check our JSTL wiki page: https://stackoverflow.com/tags/jstl/info You can get this kind of page whenever you hover the jstl tag below your question until a black box pops up and then click the info link.
It is true that Facelets 1.x and 2.x uses different namespaces for the JSTL tag library. It was less or more a namespace bug in Facelets 1.x and has been fixed for Facelets 2.x.
*
*The real JSTL 1.0 taglib uses the URI http://java.sun.com/jstl/core.
*The real JSTL 1.1/1.2 taglib uses the URI http://java.sun.com/jsp/jstl/core.
*Facelets 1.x uses the URI http://java.sun.com/jstl/core.
*Facelets 2.x uses the URI http://java.sun.com/jsp/jstl/core.
*Facelets 2.2+ uses the URI http://xmlns.jcp.org/jsp/jstl/core.
You can find all Facelets 2.x tags in the Facelets tag library documentation. Facelets don't ship with the full tag set as the real JSTL taglib. Only a few of the <c:xxx> and the full set of <fn:xxx> are copied into Facelets. The <fmt:xxx>, <sql:xxx> and <xml:xxx> tags are not taken over in Facelets.
A: JSTL is now part of EL.
It is not dependent on JSF implementation but depends on what servlet version your servelet container is compliant for.So these must be running of different servers or different versions of same server.
Short answer is from 2.4 upwards which jboss 7 is .
If you go through JSTL doc here you will find out any way.
Other wise here is good link.
And an other one here from BalusC.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: internet explorer 7 css width 100% problem How can I fix this...
Here is my screen on IE7
And here it is on IE8
My css code here is..
#content{
font-family:Arial;
width: 100%;
min-height: 5em;
display: table-cell;
/*vertical-align: middle;*/
text-align: center;
}
#main_content{
font-family:Arial;
position: absolute;
width: 90%;
background-color: #f8f8f8;
left: 50%;
margin-left: -45%;
padding-bottom: 5%;
}
#main_content table{
font-family:Arial;
width: inherit;
border:solid thin #dedede;
border-spacing: 0;
border-collapse:collapse;
text-align:left;
/*margin-bottom: 5%;*/
padding-left: 2px;
}
#main_content table tr td{
font-family:Arial;
border:solid thin #dedede;
background-color: #ffffff;
border-spacing: 0;
border-collapse:collapse;
padding:0;
text-align:left;
padding-left: 2px;
}
#main_content table tr td input, #main_content table tr td select, #main_content table tr td textarea{
font-family:Arial;
width:94%;
text-align:left;
border: none;
margin:0 auto;
padding: 2% 2% 2% 2%;
}
#main_content table tr td select{
font-family:Arial;
width:100%;
}
Sorry about the lengthy post, It's just I've been stuck here for a long time..hehehe
A: I ended up using Hacks thanks to @My Head Hurts. And also I'll try his suggestion of using asterisk(*) for IE7 css.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Timeline plugin issue in Wordpress I tried to use the timeline plugin and post to my timeline using this tutorial. and everything worked as a charm. The problem occurred when I tried to implement the same to my WordPress blog. The timeline plugin doesn't refresh after I authorized the app to add actions to my timeline and sometimes after the refresh, I see the Facebook logo (error page) instead of the plugin. Updating the timeline also doesn't work because of "an active access token must be used to query information about the current user" error.
I tried to use the very same app, so I assume that there is something wrong going on with WordPress. Any idea what it could be?
A: Resolved. A plugin had a reference to the old all.js
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In Prestashop how to uninstall the theme? I have created a theme in Prestashop and installed it, using these steps:
*
*Login as admin
*Go to Module select Administration Tab in that Select Import/export a theme v1.4 by PrestaShop.
*Follow the steps.
Now the problem is I've installed the theme but I can't uninstall the theme. Is there any way to uninstall the theme?
A: You can easily delete it in your FTP client. You should find the files in your /themes directory, just delete the entire folder for that theme.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Selenium testing without browser I use Selenium RC for testing. Now to perform a load test, I want to run parallel test cases.
Is there any way to run them without opening a browser?
A: Try this code:
op = webdriver.ChromeOptions()
op.add_argument('headless')
driver = webdriver.Chrome(options=op)
A: To set up on Centos (do all installation as root)
Install pip Download https://bootstrap.pypa.io/get-pip.py
python get-pip.py
Installing selenium
If you have pip on your system, you can simply install or upgrade the Python bindings:
pip install -U selenium
Alternately, you can download the source distribution from PyPI (e.g. selenium-2.53.1.tar.gz), unarchive it, and run:
python setup.py install
install the program: pyvirtualdisplay
pip install pyvirtualdisplay
yum install Xvfb libXfont Xorg
Then modify your script to add the bold lines within ** and **
**from pyvirtualdisplay import Display**
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
class SeleniumDemo(unittest.TestCase):
def setUp(self):
**self.display = Display(visible=0, size=(800, 600))
self.display.start()**
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "http://www.soastastore.com/"
self.verificationErrors = []
self.accept_next_alert = True
def tearDown(self):`enter code here`
self.driver.quit()
***self.display.stop()***
self.assertEqual([], self.verificationErrors)
A: You can run Selenium headless, take a look at this question/answer: Is it possible to hide the browser in Selenium RC?
Especially for performance load tests, you should have a look at
Apache JMeter.
A: Always follow the Documentation. Here is what selenium doc says. It provide a standalone jar.
*
*Download the standalone jar. And run it with command
java -jar selenium-server-standalone.jar
*Now you will see a stanalone server started.
*Now set up your webdriver like below and rest part will be as it is.
driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities={'browserName': 'htmlunit', 'version': '2', 'javascriptEnabled': True})
*Summary code will be like.
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys
driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities={'browserName': 'htmlunit', 'version': '2',
'javascriptEnabled': True})
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()
A: It is possible, but not with the standard firefox driver / chrome / etc.
You would need to install PhantomJS. Just assign your WebDriver to an instance of phantomJS driver:
driver = webdriver.PhantomJS()
If you run your code now, no browser window will be opened.
A: Chrome now has a headless mode:
op = webdriver.ChromeOptions()
op.add_argument('headless')
driver = webdriver.Chrome(options=op)
A: Since PhantomJS has been deprecated, using headless versions of Firefox would be a viable option.
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
options = Options()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get('https://www.google.com/')
A: You can import Options if you don't want to open a web browser.
from selenium import webdriver # for webdriver
from selenium.webdriver.support.ui import WebDriverWait # for implicit and explict waits
from selenium.webdriver.chrome.options import Options # for suppressing the browser
Then in the code:
option = webdriver.ChromeOptions()
option.add_argument('headless')
driver = webdriver.Chrome(options=option)
And continue with the rest of the program.
A: requirements:
sudo apt-get install xvfb
pip install selenium
pip install PyVirtualDisplay
download chrome driver binary from below link and paste into drivers directory: https://sites.google.com/a/chromium.org/chromedriver/downloads
code:
from selenium import webdriver
from pyvirtualdisplay import Display
with Display(visible=False, size=(800, 600)):
browser = webdriver.Chrome('drivers/chromedriver')
browser.get('https://www.example.com')
print(browser.page_source)
browser.quit()
A: You can simply pass an argument "headless" to test selenium without opening the browser.
op = webdriver.ChromeOptions()
op.add_argument('headless')
driver = webdriver.Chrome(options=op)
This code snippet will provide you exactly what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "58"
}
|
Q: Struts2 annotations (Convention Plugin) I meet an odd problem with struts2 annotation, let me elaborate it first
@Results({
@Result(name = "input", location = "main.jsp"),
@Result(name = "list", location = "list.jsp")
})
public class MainAction extends ActionSupport {
private PortalUser user;
@Autowired
private PortalUserService portalUserService;
public String execute() throws Exception {
return INPUT;
}
@Action("addUser")
public String addUser() throws Exception {
portalUserService.addUser(user);
return listUser();
}
@Action("listUser")
@SkipValidation
public String listUser() throws Exception {
List theUserList = portalUserService.getPortalUserList(null);
ServletActionContext.getRequest().setAttribute("userList", theUserList);
return "list";
}
@Action("modifyUser")
public String modifyUser() throws Exception {
List theUserList = portalUserService.getPortalUserList(null);
ServletActionContext.getRequest().setAttribute("userList", theUserList);
return "list";
}
public void validate() {
if (user != null && StringUtils.isBlank(user.getUserName()))
addFieldError("accountBean.userName", "User name is required.");
System.out.println("validate @@@@@");
}
public PortalUser getUser() {
return user;
}
public void setUser(PortalUser user) {
this.user = user;
}
}
this is the struts2 action class, I configure it correctly and type the url
*
*http://domain/listUser it will list all users
*http://domain/modifyUser it can modify the users
all things go well in tomcat with exploded class files
But when I build with the war file and deploy it into tomcat webapp folder, the page report
there is no action name listUser.
The difference between the two scenario is exploded class files and archived class files that I compile and jar the action and other class files into it.
I was puzzled about this phenomenon.
So any suggestions and advices will be very appreciated!
A: I experiment as followings and conclude it that with struts2 annotation,the action class can't move into jar files,it must be located in your WEB-INF/classes
I acknowledge that the struts2 convention will scan action class in the specific package,so I left only the action classes in WEB-INF/classes/.../action folder ,jar other class files and put it into WEB-INF/lib, it's done
A: By default the plugin does not scan jars or the classpath, solely WEB-INF/classes. You might want to see the plugin's Configuration Reference and look for the value struts.convention.action.includeJars, which lets you list the jars where you also want to look for the files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android SQLite foreign key help needed? // HANDLER
private static final String SCRIPT_CREATE_DATABASE = "create table " + MYDATABASE_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_CONTENT1 + " text not null);";
private static final String SCRIPT_CREATE_DATABASE2 = "create table " + MYDATABASE_TABLE2 + " (" + KEY_ID2 + " integer foreign key autoincrement, " + KEY_CONTENT2 + " text not null, " + KEY_CONTENT3 + " text not null);";
Any ideas what I might be doing wrong?
// ERROR LOG
> 09-29 11:54:40.052: INFO/Database(484): sqlite returned: error
code =
1, msg = near "foreign": syntax error 09-29 11:54:40.052:
ERROR/Database(484): Failure 1 (near "foreign": syntax error) on
0x217ba8 when preparing 'create table MY_TABLE2 (_id2 integer
foreign
key autoincrement, Content2 text not null, Content3 text not
null);'.
09-29 11:54:40.062: DEBUG/AndroidRuntime(484): Shutting down VM
09-29
11:54:40.062: WARN/dalvikvm(484): threadid=1: thread exiting
with
uncaught exception (group=0x4001d800) 09-29 11:54:40.082:
ERROR/AndroidRuntime(484): FATAL EXCEPTION: main 09-29
11:54:40.082:
ERROR/AndroidRuntime(484): java.lang.RuntimeException: Unable to
start
activity ComponentInfo{sep.com/sep.com.SepActivity}:
android.database.sqlite.SQLiteException: near "foreign": syntax
error:
create table MY_TABLE2 (_id2 integer foreign key autoincrement,
Content2 text not null, Content3 text not null); 09-29
11:54:40.082:
ERROR/AndroidRuntime(484): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-29 11:54:40.082: ERROR/AndroidRuntime(484): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-29 11:54:40.082: ERROR/AndroidRuntime(484): at
android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-29
11:54:40.082: ERROR/AndroidRuntime(484): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-29 11:54:40.082: ERROR/AndroidRuntime(484): at
android.os.Handler.dispatchMessage(Handler.java:99) 09-29
11:54:40.082: ERROR/AndroidRuntime(484): at
android.os.Looper.loop(Looper.java:123) 09-29 11:54:40.082:
ERROR/AndroidRuntime(484): at
android.app.ActivityThread.main(ActivityThread.java:4627) 09-29
11:54:40.082: ERROR/AndroidRuntime(484): at
java.lang.reflect.Method.invokeNative(Native Method) 09-29
11:54:40.082: ERROR/AndroidRuntime(484): at
java.lang.reflect.Method.invoke(Method.java:521) 09-29
11:54:40.082:
ERROR/AndroidRuntime(484): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-29 11:54:40.082: ERROR/AndroidRuntime(484): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-29
11:54:40.082: ERROR/AndroidRuntime(484): at
dalvik.system.NativeStart.main(Native Method) 09-29
11:54:40.082:
ERROR/AndroidRuntime(484): Caused by:
android.database.sqlite.SQLiteException: near "foreign": syntax
error:
create table MY_TABLE2 (_id2 integer foreign key autoincrement,
Content2 text not null, Content3 text not null); 09-29
11:54:40.082:
ERROR/AndroidRuntime(484): at
android.database.sqlite.SQLiteDatabase.native_execSQL(Native
Method)
09-29 11:54:40.082: ERROR/AndroidRuntime(484): at
android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1727)
09-29 11:54:40.082: ERROR/AndroidRuntime(484): at
sep.com.handle$SQLiteHelper.onCreate(handle.java:104) 09-29
11:54:40.082: ERROR/AndroidRuntime(484): at
android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:106)
09-29 11:54:40.082: ERROR/AndroidRuntime(484): at
sep.com.handle.openToWrite(handle.java:44) 09-29 11:54:40.082:
ERROR/AndroidRuntime(484): at
sep.com.SepActivity.onCreate(SepActivity.java:38) 09-29
11:54:40.082:
ERROR/AndroidRuntime(484): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-29 11:54:40.082: ERROR/AndroidRuntime(484): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-29 11:54:40.082: ERROR/AndroidRuntime(484): ... 11 more
A: // Creating tables
private static final String SCRIPT_CREATE_DATABASE = "create table " + MYDATABASE_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_CONTENT1 + " text not null);";
private static final String SCRIPT_CREATE_DATABASE2 = "create table " + MYDATABASE_TABLE2 + " (" + KEY_ID2 + " integer autoincrement, " + KEY_CONTENT2 + " text not null, " + KEY_CONTENT3 + " text not null, FOREIGN KEY ("+KEY_ID2+") REFERENCES "+PARENT_TABLE+" ("+PARENT_TABLE_PRIMARY+"));";
Foreign key has references
A: try this ...
String CREATE_MATCH = "CREATE TABLE if not exists "+ TABLE_MATCH
+ "("
+ MatchID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ MatchTeamA + " INTEGER REFERENCES "+TABLE_TEAM+","
+ MatchTeamB + " INTEGER REFERENCES "+TABLE_TEAM+")";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to merge Designer and XAML editors in one window in Visual Studio? How to merge Designer and XAML editors in one window (designer on top of xaml editor) in Visual Studio 2010 when working with WPF project?
Currently, to switch between them I need to use tabs.
A: Click the toggle button in the picture below.
A: There are three tabs above the output toolbar: "Design", an image with two arrows and "XAML". Click on the image (the second tab). In that way, you can switch - if you want the code to be above or under the design editor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Database design for products and product variants I'm building an commerce site and I've been researching different ways to show products with variants. I'm trying to do this for contact lenses and wondering what the best way is.
Products can be either simple, such as a lens case or lens solution that have no variants, or in the case of a contact lens, each lens can have up to three configurable variants, depending on the lens, for the prescription (e.g. Power, Base Curve, Diameter).
In my structure I have simple products as just a product, with no parent. A contact lens will be stored as a product, and each variant will be stored as a separate product referencing its parent, and the variants themselves will be linked using a products_variants table.
I have a structure like:
products
- id
- parent_id
- name
- price
- type_id
- brand_id
type
- id
- name
brand
- id
- name
product_variant_group
- id
- name
product_variant_value
- id
- product_variant_group_id
- value
products_variants (isCrossRef = true for Propel relationships)
- id
- product_id
- product_variant_value_id
My code is quite slow already, and I haven't even started to build the select boxes to select the prescription.
public function getPossibleVariants($productId)
{
$product = ProductQuery::create()->findPk($productId);
$children = $product->getChildren();
$options = array();
foreach ($children as $child) {
if ($child->countProductsVariantss()) {
$variants = $child->getProductVariantValues();
foreach ($variants as $variant) {
$group = $variant->getProductVariantGroup();
$options[$group->getName()][] = $variant->getValue();
}
}
}
ksort($options);
return $options;
}
I'm using propel and Zend Framework. Am I going about this the right way? Most people will need two of the same lens types, but with different prescriptions for each eye. How would I implement this?
I've tried looking at other systems, such as magento and oscommerce. The former confuses me and I find the code messy in the latter. As this is a learning experience, I'd like to do things the best possible way.
Thanks
A: It is better to use one table for all your products and products variants. So that the operations based on products get easier. Ultimately a variant is a product only.
So I would suggest.
products
- id
- parent_id
- name
- price
- type_id
- brand_id
- variant_id
The additional field variant_id should reference the variant group.
It is simpler this way. And you can retrieve all the variants based on variant group id.
I have played with Amazon product API a lot. Their approach is similar to this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Why not open viewController when clicking a table cell in moreViewControllers of UITabBarController? Why not open viewController when clicking a table cell in moreViewControllers of UITabBarController?
When I click cell, cell is highlighted (or selected). But viewController was not shown.
Oh, must I type some code to open viewController? Does not tabBarController open viewController automatically?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I make a variable made out of a string global in python? I'm trying to make a blackjack game.
I've made functions for drawing cards and checking if sum in one's hand exceeds 21 but only for 3 players. That was easy I had 3 lists.
But I want to do it for N number of players so I want to keep my functions and make another one that switches between players and their hands.
def create_hands():
global total_players
for x in range(1, total_players+1):
vars()["hand_%d" % x] = []
print hand_1
I want to create as many hands as in hand_1, hand_2, etc... for as many N players (total_players)
Because of the code above i get an global name 'hand_1' is not defined error
So it all comes down to:
*
*How do I make "hand_%d" % x global ?
*Is there a better way to do it ?
A: Yes, there is a better way. Simply create a list of lists. Playing with vars should be ommited, if possible. It's really hard to read and debug and you will regret that attitude lately. When you create a list like players -> hand -> cards, or even a dict of players like players['player1'][3] for player's one third card, you will be much more happy with that.
A: The problem you are running into is that vars() is an alias for locals(), which has the following comment in the official documentation:
Note: The contents of this dictionary should not be modified;
changes may not affect the values of local and free variables
used by the interpreter.
In other words, adding keys to vars() does NOT necessarily update the local var iables table (which is why you're getting the global name hand_1 is not defined error - vars()[ "hand_1" ] doesn't make hand_1 into a local variable).
As Gandi mentioned, there are far easier ways to do what you are trying to do - use a list of lists or something similar. There are far more conventional ways to solve this problem than creating arbitrarily-named local variables.
A: Yes, it is possible to do that. Replace
vars()["hand_%d" % x] = []
with
globals()["hand_%d" % x] = []
Be warned however that this solution is kinda hackish and can easily lead to problems (difficulty in maintenance, losing track of the spontaneously created variables, etc.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to map 10 bits to 6 bits in C++ (as efficiently as possible)? So I know functionally what I would like to happen, I just don't know the best way to make a computer do it... in C++...
I would like to implement a C++ function that maps a 10 bit sequence to a 6 bit sequence.
Nevermind what the bits stand for right now... There are 2^10 = 1024 possible inputs. There are 2^6 = 64 different outputs. Probably lots of patterns. Obviously lots of patterns. But it's complicated. It's s a known mapping, just a complicated mapping.
The output is just one of 64 possibilities. Maybe they all don't get used. They probably won't. But assume they do.
Right now, I'm thinking a quadruple nested switch statement that just takes care of each of the 1024 cases and takes care of business inline, assigning appropriate values to whatever pointer to whatever structure I passed to this function. This seems to be naive and sort of slow. Not that I've implemented it, but that's why I want to ask you first.
This basic function (mapping) will have to be run at every statement node, often more than once, for as many statements this system wishes to support. I ask you, how do I map 10 bits to 6 bits as efficiently as possible in C++?
I know what the mapping is, I know which inputs of 10 bits go with what output of 6 bits... I could totally hard-code that ... somehow? Multi-switch is so ugly. How can I map my 10 bits to 6 bits?! Neural net? Memory muffin? What would you do?
Note to self: So here is why I am not a fan of the lookup table. Let's assume all inputs are equally likely (of course they are not, and could be ordered more effectively, but still) then it will take on average 512 memory advances of the array to retrieve the output values... It seems that if you make a (global, why not) binary tree 10 levels deep, you cover the 1024 inputs and can retrieve the output in an average of just 10 steps... and maybe less if there are good patterns... given a deterministic function that is run so often, how best to retrieve known outputs from known inputs?
A: I would use a lookup table of 1024 elements. So hard-code that and just access it by index.
This saves the need for a massive switch statement and will probably be much more readable.
A: Depends on your definition of efficiency.
*
*Time-efficient: Look-up table.
*Space-efficient: Use a Karnaugh map.
A: Use a look-up table of size 1024.
A: If you need to map to some particular 6-bit values, use a lookup table of size 64 (not 1024!) after dividing by 16. This will fit into the cache more easily than a 16-times redundant 1024-entry table (and, the 2 extra cycles for a right shift outweight the cost of a possible cache miss by far).
Otherwise, if a simple sequential mapping is fine, just do a divide by 16.
1024/64 = 16, so dividing by 16 (a right shift with compiler optimizations turned on), maps to 6 bits (sequentially). It cannot get more efficient than that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: native XML Database: eXist or Sedna? I'm trying to decide on which native XML database to choose: eXist or Sedna (both are open source)
I'm using cakePHP, Ajax and WAMP for my website.
I will be using the XML database only for reporting purpose coz' i'm having some semi structured data which cannot be stored in MYSQL.
Which one is well documented?
Which one is easier to learn?
which one has better community support such as forums, etc..?
What are the advantages and disadvantages of both of them?
thank you.
A: Also try BaseX, offering a very helpful mailing list and wiki documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: to get the textbox values of the form in user control in splitcontainer
Possible Duplicate:
get the splitcontainer context in user control click event
I have a split container in which right panel, i have a user control on top.I have a left panel which has navigation links.now if i click a link in left side, a form opens below user control.Now if i click view button in user control, a new form should open in right side of panel below user control. also if i have some values in textboxes in form below user control, when i click save button in user cotrol, i should be able to fetch those values in user control button click event.how to do it?
A: You can use public properties(value of textbox.text) in you user control, they will contains your values. Also you can create static class with dictionary values, something like a session in web.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is the variable read from the Scanner method next() or nextDouble() equal to a String or double respectively For example,
If I declare a String variable and a double variable
String d = "dragon";
double = 1.45;
And then I have a text file and on the first line of the file it is...
A dragon is 1.45
So I open the file
{
try {
x = new Scanner(new File("Dragon.txt"));
}
catch(Exception e)
{
System.out.println("Could not find file");
}
}
// And then read in the data, in this case I use hasNext which returns a String.
public void readFileData()
{
while(x.hasNext())
{
// Remember, this is the first line of the text file: A dragon is 1.45
String a1 = x.next(); // al = "A";
String a2 = x.next(); // a2 = "dragon;
// And I test a2 to see it is equal to dragon, however it is not.
if(d == a2)
{
System.out.println("Wow");
}
else
System.out.println("Naw man");
String a3 = x.next();
String a4 = x.next();
// Of course I do the same thing for the a4 variable and of course the String variables are replaced with double and nextdouble() method is used.
Thank you very much in advance to anyone who can help!
A: Use String.equals when comparing strings. == checks if the reference is the same. String.equals tests if the objects are the same.
So instead of if(d==a2) use if(d.equals(a2))
A: Try if (d.equals(a2)), use equals for String comparison.
A: First you're trying to compare reference values, not the contents of the String objects.
As others have noted, you need to use the String.equals(String otherString) method.
Next, you're reading 1.45 in as a String, not a double. These two things are not comparable. You need to read in 1.45 as a double;
String a1 = x.next();
String a2 = x.next();
String a3 = x.next();
double d1 = x.nextDouble();
This would convert your line A dragon is 1.45 to three Strings ('A', 'dragon', 'is') and a double (1.45)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Dynamically load google maps api v3 with namespaced callback function I recently ran across the following problem when lazy loading/dynamically loading the google maps api v3: In order to check whether the api has fully loaded or not, I followed the instructions on google's documentation page. Works fine with a normal function callback name like &callback=initialize in global scope. Also works fine with a function callback that is within a certain namespace like &callback=Namespace.initialize.
Now my function is placed under Namespace.foo[0].initialize ("Namespace" and "foo" are of type object). The problem now is that I can't properly access this function. I tried several ways of building the callback string, each listed below with whatever firebug tells me is not working:
&callback=Namespace.foo[0].initialize
Firebug: NetworkError: 403 Forbidden - <http://maps.googleapis.com/maps/api/js?v=3...&callback=Namespace.foo[0].initialize...>
&callback=Namespace.foo.0.initialize
Firebug: missing ; before statement
Firebug: [Break On This Error] window.Namespace.foo[0].initialize()
&callback=Namespace.foo%5B0%5D.initialize
Firebug: NetworkError: 403 Forbidden - <http://maps.googleapis.com/maps/api/js?v=3...&callback=Namespace.foo[0].initialize...>
I'm thankful for every hint and/or solution!
Background information: What I do might also be interesting. A script is dynamically loading html, css, data and the google maps api into a external webpage (within a web-widget). Now I'm using jQuery's deferred object to queue the different includes such as loading the css/javascript/html first, then receive the data and finally setup the google map within the previously loaded structure. Deferred object performs way better than handling the different steps with callbacks (and much easier too!), but when the jQuery.getScript method is done (loads the google maps api) the success event is fired and deferred.resolve gets returned. Too bad that this probably just handles the authentification (via client-key) and then asynchronously loads the google maps main.js. This pretty much sucks because I need to wait for the api to fully load...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android Video Streaming using Video View (video view not showing automatially) I have managed to stream video from internet using Video View
Uri uri=Uri.parse(videoFileList[0]);
VideoView vv=(VideoView) this.findViewById(R.id.vv);
vv.setVisibility(1);
vv.bringToFront();
vv.setVideoURI(uri);
vv.setMediaController(new MediaController(this));
vv.requestFocus();
But the video page displays as blank at first. Only if I click on the blank space the video view appeares.
Can any body give a solution to display it automatically?
A: Try this. It worked for me.
void playvideo(String url)
{
String link=url;
Log.e("url",link);
view1 = (VideoView) findViewById(R.id.myVideoView);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
MediaController mc = new MediaController(this);
mc.setMediaPlayer(view1);
view1.setMediaController(mc);
view1.setVideoURI(Uri.parse(link));
view1.requestFocus();
view1.start();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SymbolicateCrash is not creating proper de-symbol file I have the dSYM file for build created on client's machine. Client got a crash in build and now I am trying to de-symbol by use of the symbolicatecrash by the simple following command in terminal:
symbolicatecrash myapp_iPod-Touch.crash myapp.app.dSYM > test.txt
but it's not creating any meaningful de-symboled file. and it's giving the follwoing error in terminal:
Can't understand the output from otool
then I found a solution in following link:
iPhone SDK 3.0 and symbolicatecrash not getting along?
but still it's not de-symbolicating the exact memory location to exact code line responsible for crash.
Then I tried some other options too:
Following is the other option but didn't work:
symbolicatecrash.sh -A -v [crashlog-filename] MyApp.dSYM
For reference: http://apptech.next-munich.com/2010/01/symbolicatecrash.html
The best option that helped me is atos command to get the exact code line number of the crash but I want the systematic symbolicatecrash to create the dump.
NOTE: When I create build in my machine and desymbolicate (the my machine created) build's crash log in my machine it creates perfectly good dump file (show's exact memory location VS code line responsible for crash).
A: If you have the DSYM file for the crash then you can use this one:
#!/bin/bash
if [[ $# < 2 ]]
then
echo "Usage: $0 [-arch <arch> (defaults to whatever is specified in the crashlog- file] <dSYM-file> <crashlog-file>"
exit 1
fi
#Get the architecture either from the params or from the crashlog itself
ARCH_PARAMS=''
if [[ "${1}" == '-arch' ]]
then
ARCH_PARAMS="-arch ${2}"
shift 2
else
ARCHITECTURE=$(cat "${2}" | grep -A1 "Binary Images:" | grep 0x | sed -E -n 's/.*(armv[6-9]).*/\1/p')
if [ -n "${ARCHITECTURE}" ]
then
ARCH_PARAMS="-arch ${ARCHITECTURE}"
else
echo "Couldn't determine architecture based on the crashlog. Please specify it by calling $0 -arch <arch> <dSYM-file> <crashlog-file>"
exit
fi
fi
echo "Assuming architecture:" ${ARCHITECTURE}
#Store the other params
SYMBOL_FILE="${1}"
CRASHLOG="${2}"
#Get the identifier out of the crashlog
IDENTIFIER=$(cat "${CRASHLOG}" | egrep -o "^Identifier:[[:space:]]*.*$" | sed 's/^Identifier:[[:space:]]*\(.*\)$/\1/')
echo "Identifier:" $IDENTIFIER
echo
echo
#Iterate through the crashlog files, find the ones that belong to the $IDENTIFIER, sed the address out of those files, symbolicate them with atos and finally replace them back into those line again. Print all other lines untouched.
while read line
do
SYMBOL=$(echo $line | sed -E -n "s/.*(${IDENTIFIER}[[:space:]]*)(0x[[:alnum:]]*).*/\2/p" | atos -o "${SYMBOL_FILE}/Contents/Resources/DWARF/${IDENTIFIER}" ${ARCH_PARAMS})
if [ -n "$SYMBOL" ]
then
echo $line | sed -E "s/(${IDENTIFIER}[[:space:]]*)(0x[[:alnum:]]*)(.*)/\1\2 ${SYMBOL}/"
else
echo $line
fi
done < "${CRASHLOG}"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Codeigniter image resize() thumbnail name issue When I resize an image keeping $config['create_thumb'] = true Codeigniter adds the string "_thumb" in the end of the name of resized image.
What I want ask is, is it possible to add the suffix "_thumb" in the beginning of the image name
example:
original_name.jpg
after resizing:
original_name_thumb.jpg
What I want:
thumb_original_name.jpg
Any kind of help is appreciated!
A: You can try this:
$data = $this->upload->data();
$config['create_thumb'] = false;
$config['new_image'] = 'thumb_'.$data['file_name'];
And if you have other problems with CI image manipulation library, maybe you can try ImageMoo.
A: If u don't want to add the suffix _thumb in thumbnail file name then
use $config['thumb_marker'] = false;
A: this can be achieved by following way
$data = $this->upload->data();
$config['create_thumb'] = false;
$config['new_image'] = 'thumb_'.$data['file_name'];
for more information about re-size image check out following Code.
function special_resize($oldFile, $width, $height)
{
$obj =& get_instance();
$info = pathinfo($oldFile);
out($info);
$tempFile = '/public/files/files/temp/' . $info['filename'] . '-' . $width . 'x' . $height . '.' . $info['extension'];
$newFile = '/public/files/files/cache/' . $info['filename'] . '-' . $width . 'x' . $height . '.' . $info['extension'];
//if image already exists, use it
if(file_exists('.' .$newFile))
return $newFile;
//math for resize/crop without loss
$o_size = _get_size( '/' . $info['dirname'] . '/' . $info['basename']);
$master_dim = ($o_size['width']-$width < $o_size['height']-$height?'width':'height');
$perc = max( (100*$width)/$o_size['width'] , (100*$height)/$o_size['height'] );
$perc = round($perc, 0);
$w_d = round(($perc*$o_size['width'])/100, 0);
$h_d = round(($perc*$o_size['height'])/100, 0);
// end math stuff
/*
* Resize image
*/
$config['image_library'] = 'gd2';
$config['source_image'] = $oldFile;
$config['new_image'] = '.' . $tempFile;
$config['maintain_ratio'] = TRUE;
$config['master_dim'] = $master_dim;
$config['width'] = $w_d + 1;
$config['height'] = $h_d + 1;
$obj->image_lib->initialize($config);
$obj->image_lib->resize();
$size = _get_size($tempFile);
unset($config); // clear $config
/*
* Crop image in weight, height
*/
$config['image_library'] = 'gd2';
$config['source_image'] = '.' . $tempFile;
$config['new_image'] = '.' . $newFile;
$config['maintain_ratio'] = FALSE;
$config['width'] = $width;
$config['height'] = $height;
$config['y_axis'] = round(($size['height'] - $height) / 2);
$config['x_axis'] = 0;
$obj->image_lib->clear();
$obj->image_lib->initialize($config);
if ( ! $obj->image_lib->crop())
{
echo $obj->image_lib->display_errors();
}
$info = pathinfo($newFile);
out($info);
return $newFile;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: TDBListView and TAdvDBListView - showing icons to the items I am stuck with TDBListView and TAdvDBListView and the way to display icons with the displayed items.
I have connected them to ImageList, but i cant find property which to drive connection of the ImageList - image index and the fields which is displayed,
or i am missing something ?
A: You need to create custom renders for the rows and colums.
This is the normal solution in the most of the cases.
A: I found that i need to draw the object manually with the refresh of the elements :'|
I have expected something more suffisticated :|
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django Templates: Comparing current url with {% url xyz %} I am trying change the active selection of my navigation links based on the current page where the user is at.
I am trying to do omething like this:
<li {% if request.get_full_path == {% url profile_edit_personal %} %}class="current"{% endif %}><a href="{% url profile_edit_personal %}">Personal Details</a></li>
Alternatively, I know I could define do something like this:
<li class="{% block current %}{% endblock %}"><a href="{% url profile_edit_personal %}">Personal Details</a></li>
and add a {% block current %}current{% endblock %} to each of the relevant templates but I would prefer something like what Im trying to achieve in the first example if possible
Thanks!
A: This is quite a common requirement so it might be worthwhile writing your own template tag to perform this:
class isCurrentNode(template.Node):
def __init__(self, patterns):
self.patterns = patterns
def render(self, context):
path = context['request'].path
for pattern in self.patterns:
curr_pattern = template.Variable(pattern).resolve(context)
if path == curr_pattern:
return "current"
return ""
@register.tag
def is_current(parser, token):
""" Check if the browse is currently at this supplied url"""
args = token.split_contents()
if len(args) < 2:
raise template.TemplateSyntaxError, "%r tag requires at least one argument" % args[0]
return isCurrentNode(args[1:])
and in your template
{% url about_page as about %}
{% url home_page as home %}
...
<ul>
<li class="{% is_current home %}"><a href="{{ home }}">Home</a></li>
<li class="{% is_current about %}"><a href="{{ about }}">About</a></li>
...
Here's the same idea done slightly differently:
http://gnuvince.wordpress.com/2007/09/14/a-django-template-tag-for-the-current-active-page/
http://www.turnkeylinux.org/blog/django-navbar
A: How about:
<li {% if request.get_full_path == profile_edit_personal.get_absolute_url %}
class="current"{% endif %}><a href="{% url profile_edit_personal %}">
Personal Details</a></li>
where get_absolute_url is as discussed in the Django docs.
Its still probably not the best way to customise active nav menu headers though, there's probably some CSS tricks that can do it without as much code. I'd say more but only had half a cup of coffee this morning..
A: Since you'll probably only need to do this once--in your nav template--it makes more sense to me to keep everything in one place.
First reverse your url names and store them in variables like Timmy suggested, then simply compare them in the template:
{% url 'about_page' as about %}
...
<ul id="nav">
<li class="{% ifequal request.path about %}active{% endifequal %}"><a href="{{about}}">About</a></li>
...
Just make sure you have your request context processor enabled so you have access to the request in the template. Do this by adding django.core.context_processors.debug in your TEMPLATE_CONTEXT_PROCESSORS settings variable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Moving an SVN repository from one PC to another I have an SVN repository for Project A in one PC with Ubuntu OS and another repository for Project B in another PC with Windows OS.
a) I would like to create a new repository with name 'Projects' in windows PC and would like to move the two projects under it and finally have a structure something like:
.Projects
.projectA
.branches
.tags
.trunk
.projectB
.branches
.tags
.trunk
b) Also, I want to restrict users accessing each project (ie, users I, J should have access to project A only...users M, N should have access to project B only...but users X, Y should be able to access both projects)
Please help me to set up this. A detailed step by step explanation is highly appreciated (I'm a novice in this).
Thanks & Regards,
Jazir
A: For a)
Use svnadmin dump on each of the old repositories to put the whole repository in a portable transfer format.
Then use svnadmin load with the --parent-dir parameter to load each of those dumps into your new repository at relevant paths.
b) If you run the VisualSVN software as SVN server you have built in tools to create users and set permissions on folders. If not you have to manually play with the authz-file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Looking for better way to set resizeable background Css3 / HTML / mootools I found some code that allows me to resize browser window and reset image h+w appropriately like so
html {
background: url(css/images/600.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
I'm not clear how to change the background of this element as the following line fails to find the html element
window.addEvent('domready', function () {
$(this).setStyle('background', 'url(css/images/600.jpg) no-repeat center center fixed;');
});
How can I change the background image of the html tag through mootools script? Would it be better to set a class to the html element , if so how do I reference the element by Class?
A: inside the domready function, this is the window element not the html element
should be something like this:
window.addEvent('domready', function () {
this.document.html.setStyle('background', 'url(css/images/600.jpg) no-repeat center center fixed');
});
Hope this helps
BTW: i wouldn't give a style to the html element, it causes problems on IE. It's better to style the body tag or create a wrapper div
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: String is wrong converted to float? (Blitzmax - Reflections) I have a little Problem in Blitzmax.
I try to read an INI-file and if I read floats they are converted in a very strange way.
The line in the file which is concerned looks like that for example:
_fStrength=40.6
The Output of this looks like that:
DebugLog:_fStrength: 40.5999985
The code I use to read that works with reflection and looks like that:
For Local fld:TField = EachIn id.EnumFields()
fld.Set(obj, SearchInFile("TempWeapon" + index, fld.Name(), "Weapons.ini"))
DebugLog(fld.Name() + ": " + String(fld.Get(obj)))
Next
I found out, that this only happens if the number after the "." does not equal's 5 or 0.
I can't explain this behaviour, because if I do not use reflections, it works fine.
Could anyone help me please?
A: As you probably know, your computer stores numbers in binary code, using a limited size. 40.6 expanded in binary is a periodic sequence (101000.1001100110011001100..., infinitely), similarly to what happens when you try to write down the digits of 1/3) repeating and thus can not be represented exactly, so you get rounding errors.
The number of correct digits you get here looks like you are using single-precision floating point numbers, you can push the error further back by going to double, but it won't disappear.
As a reference, you might find Wikipedia on floating point helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What does CF in CFnumber,CFstring etc in xcode application mean? I have minimum exposure to Xcode and i/o kit. I came across terms like CFString, CFNumber etc. Whether this CF have any particular meaning like these strings and numbers inherited from C or like C string or numbers. I just want to know what CF refers to.
Thanks in advance
A: It stands for Core Foundation, which is Apple's C-based API that:
provides the fundamental data types and essential services that
underlie both the Cocoa and Carbon environments on Mac OS X.
A: CFString, CFNumber etc., are declared in Core Foundation Framework, and this makes it obvious that CF is the abbreviation of Core Foundation. We do create objects of those CF types like CF[Type]Ref,
CFStringRef str;
Note that here we not using *, though CFStringRef is a reference type. Most of this CFTypes are "toll-free bridged” with their Core Foundation counter parts. Which means they can be used interchangeably. For example, CFStringRef is "toll-free bridged” with its counter part NSString, and both the following lines are completely valid.
CFStringRef str = (CFStringRef)aNSStringObject; // Valid
NSString *str = (NSString *)aCFStringRefObject; // Valid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Outlook add-in and WPF window I am writing a simple Outlook addin using addin Express. This is for 2007 and 2010 . I have a wpf window I want to launch modally when a ribbon button is pressed in OL .
The code I have right now just does this
MainWindow mw = new MainWindow();
mw.ShowDialog();
and everything seems to work fine. I guess my question is , is it really this easy or is something going to get me in the rear later. Is there no need for any interop of any sort here?
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: object-database: Changing the class hierarchy I am reading me into object oriented databases right know and have to make a little presentation.
Something I don't get and nowhere can find is following problem:
What happens with the data of the database when I change my class hierarchy.
For example I have A extends from C. But then I notice that C has to extend from B and B has to extend from A:
A <|-- C
A <|-- B <|-- C
What happens to the (user) data I stored in the database?
If the database can't be adopted, the data can't be used anymore, right? So when for example I have a social network all data whould be lost and the network has to start all over again... Am I right here or do I miss something?
A: Most object databases have tools for migrating the schema and then updating the objects. Objectivity/DB, for instance, allows the developer to choose whether to migrate all affected objects in a single transaction, migrate them when encountered, or leave them in the old format (e.g. on a read-only device) and present objects in the new format. There's also an extensive Active Schema capability that allows applications to define, populate, use and change object classes dynamically. All of this can be done with a system online.
http://www.objectivity.com/pages/objectivity/active-schema-dynamic-class-declaration.asp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set UITableView cell alpha? I have to set the cells alpha to minimum. I try the following code in cell for row, it's not working.
I've also set opaque but it's still not working. Anyone have an idea about this?
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.alpha =0.5;
A: try this..
cell.contentView.alpha = 0.5;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to write a `<<` operator for boost::tuple? In the sample code below, it shows that boost::tuple can be created implicitly from the first template argument.
Because of that I am not able to write a << operator as it becomes ambiguous.
Also I don't understand why ostringstream& << float is also ambiguous. This does not have any implicit construction. Why does this also give ambiguous error?
#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <sstream>
#include <string>
using namespace std;
class Myclass
{
};
typedef boost::tuple<int,float,Myclass> Mytuple;
ostringstream& operator<<(ostringstream& os_, Mytuple tuple_)
{
float f = tuple_.get<1>();
//os_ << (int)tuple_.get<0>(); // Error because int is implicitly converted into Mytuple. WHYY?
//os_ << tuple_.get<1>(); // No Clue Why this is ambiguous.
//os_ << tuple_.get<2>(); // Error because no matching operator. Fine.
return os_;
}
int main()
{
Mytuple t1;
t1 = 3; // Working because int is implicitly converted into Mytuple!! WHY?
//t1 = 3.0f; // Error because no matching constructor. Fine.
return 0;
}
Error Mesasge:
tupleTest2.C:18: error: ISO C++ says that these are ambiguous, even
though the worst conversion for the first is better than the worst
conversion for the second:
A: The problem is not with the tuple, but with your operator. This works fine :
ostream& operator<<(ostream& os_, Mytuple tuple_)
{
os_ << tuple_.get<0>(); // Error because int is implicitly converted into Mytuple. WHYY?
os_ << tuple_.get<1>(); // No Clue Why this is ambiguous.
//os_ << tuple_.get<2>(); // Error because no matching operator. Fine.
return os_;
}
The problem is that the ostringstream inherit operator<< from ostream, which has this signature : ostringstream& operator<<(ostringstream& os_, Mytuple tuple_) is allowed. Then the
ostream& operator<<(ostream& os, T t)
(change T with all available types in c++, see operator<< reference page
EDIT
Here is a simplified example (without a tuple) :
ostringstream& operator<<(ostringstream& os_, Mytuple tuple_)
{
const int i = tuple_.get<0>();
os_ << i; // error in this line
return os_;
}
and the error is now :
dfg.cpp: In function ‘std::ostringstream& operator<<(std::ostringstream&, Mytuple)’:
dfg.cpp:18: error: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
/usr/lib/gcc/i386-redhat-linux/4.3.0/../../../../include/c++/4.3.0/bits/ostream.tcc:111: note: candidate 1: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]
dfg.cpp:14: note: candidate 2: std::ostringstream& operator<<(std::ostringstream&, Mytuple)
The above error message says : it is not possible to choose between two operators operator<<(ostream&,...) and operator<<(ostringstream&,...). This also raises another question : why on earth do you needoperator<<(ostringstream&,...)`?
A: When you write
os << tuple_.get<0>();
there is no function that matches both parameters. Instead the compiler has a choice to apply an implicit conversion on either parameter
std::ostream << int
or
std::ostringstream << MyTuple
The latter would happen with the boost::tuple constructor that can take any number of arguments up to number of tuple elements. (And with float it fails, because float is convertible to int.)
When overloading stream operators, use the base class as the left hand side (ostream or even basic_ostream<CharT, Traits>.
Edit: You could disambiguate the call by casting the first argument.
ostringstream& operator<<(ostringstream& os_, Mytuple tuple_)
{
static_cast<std::ostream&>(os_) << tuple_.get<0>();
static_cast<std::ostream&>(os_) << tuple_.get<1>();
static_cast<std::ostream&>(os_) << tuple_.get<2>(); // Error because no matching operator. Fine.
return os_;
}
However, overloading the operator with ostringstream is still a bad idea, because it won't work with operator chaining.
MyTuple a, b;
ostringstream ss;
ss << a << ' ' << b;
will invoke:
1) ostringstream& operator<<(ostringstream& os_, Mytuple tuple_)
2) ostream& ostream::operator<<(char)
3) ostream& operator<<(ostream&&, boost::tuple<int,float,Myclass>
A: All those people telling you to use ::std::ostream for the type instead of ::std::ostringstream are absolutely correct. You shouldn't be using ::std::ostringstream that way.
But my main beef with your code is the distressing lack of generality. It only works for one particular tuple type, and not all of them.
So I wrote an operator << for ::std::tuple in C++0x that works for any tuple who's members can be individually written using operator <<. It can probably be translated relatively easily to work with Boost's tuple type. Here it is:
template < ::std::size_t fnum, typename tup_type>
void print_fields(::std::ostream &os, const tup_type &val)
{
if (fnum < ::std::tuple_size<tup_type>::value) {
::std::cerr << "Fred " << fnum << '\n';
os << ::std::get<fnum, tup_type>(val);
if (::std::tuple_size<tup_type>::value > (fnum + 1)) {
os << ", ";
}
print_fields<fnum + 1, tup_type>(os, val);
}
}
template < ::std::size_t fnum, typename... Elements>
class field_printer;
template <typename... Elements>
class field_printer<0, Elements...> {
public:
typedef ::std::tuple<Elements...> tup_type;
static void print_field(::std::ostream &os, const tup_type &val) {
}
};
template < ::std::size_t fnum, typename... Elements>
class field_printer {
public:
typedef ::std::tuple<Elements...> tup_type;
static void print_field(::std::ostream &os, const tup_type &val) {
constexpr auto tupsize = ::std::tuple_size<tup_type>::value;
os << ::std::get<tupsize - fnum, Elements...>(val);
if (fnum > 1) {
os << ", ";
}
field_printer<fnum - 1, Elements...>::print_field(os, val);
}
};
template <class... Types>
::std::ostream &operator <<(::std::ostream &os, const ::std::tuple<Types...> &val)
{
typedef ::std::tuple<Types...> tup_type;
os << '(';
field_printer< ::std::tuple_size<tup_type>::value, Types...>::print_field(os, val);
return os << ')';
}
This prints out the tuple as "(element1, element2, ...elementx)".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there any possible way to obtain the list of android applications in market? I am looking for solution of retrieving the whole list of application name from the market. Is there any way of doing this?
Edited:
I have found this post is very useful for this...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Where to get the Lagoona Compiler and Specification? The Lagoona programming language is supposed to naturally and fully support Component Oriented Programming (and DbC) according to: this article and is implemented in .Net; but I didn't find the compiler, specification nor examples of code for it. Does anyone know where/how to get any/all of those (compiler, specification or code examples)?
A: I found the .Net implementation, its called Lava and there's a "Programming Environment" for it called LavaPE; the two go hand in hand, the LavaPE is synonymous with Lava; which is what Jeff Atwood says in this article that would happen with future languages. I wonder if it'll ever get to mainstream, maybe in a decade, we'll see.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change start time extensible calendar (extjs) I trying an extjs component (extensible calendar)
http://ext.ensible.com/
I want change the start time in day view become 4.30, but the data doesn't show after 23:00.
This is make me crazy T.T
Please, any suggestion please...
A: set the viewStartHour : Integer config of the day view.
Read docs here
A: Set viewStartHour and viewEndHour on fly !!
var cal = Ext.ComponentQuery.query('#app-calendar')[0];
var activeView = cal.getActiveView();
activeView.body.viewStartHour = 6; //you most use an variable!!
activeView.body.viewEndHour = 12;
activeView.body.tpl.viewStartHour = 6;
activeView.body.tpl.viewEndHour = 12;
activeView.body.tpl.constructor();
activeView.body.refresh(false);
Enjoy!!!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XmlSerializer and different field in class and xml attribute I have xml with several items, for example:
<TestObject>
<TestElement1/>
<TestElement2/>
</TestObject>
<TestObject>
<TestElement1/>
<TestElement2/>
</TestObject>
Also I have class:
class TestClass {
public int TestElement1 { get; set; }
public int Element { get; set; }
}
If I do:
XmlSerializer s = new XmlSerializer(typeof(List<TestClass>));
List<TestClass> list = (List<TestClass>)s.Deserialize("myXml.xml");
After it I get list with objects TestClass, but property Element didn't set. How I must change serialization, if I want to set TestElement2 in Element field?
A: You need to decorate the Element property with an [XmlElement] attribute:
[XmlRoot("TestObject")]
class TestClass {
public int TestElement1 { get; set; }
[XmlElement("TestElement2")]
public int Element { get; set; }
}
A: Try XmlElement attribute
public class TaxRates{
[XmlElement(ElementName = "TaxRate")]
public decimal ReturnTaxRate;
}
see Controlling XML Serialization Using Attributes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: locate-file function not found in Emacs? I want to use the locate-file function in Emacs to find files quickly using file names. This link: http://www.gnu.org/software/emacs/elisp/html_node/Locating-Files.html says that there is a command function 'locate-file' for this purpose.
But when I try to use this function using: M-x locate-file it says [No match]. What could be the problem?
Strangely, when the function is present in describe-function!
A: Use icicle-locate or icicle-locate-file, in Icicles.
If you are on GNU/Linux or Unix then use icicle-locate, which takes advantage of the OS command locate, which uses a periodically updated index created by the OS command updatedb. Because of such indexing, locate (and hence icicle-locate) is extremely fast. And because this is Icicles you get the same incremental pattern matching you see in Anything (and more).
A: locate-file is not for interactive use. There are lots of tools for finding files like dired-find.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: using firefinder xpath to find elements I'm using xPath with FireFinder.. but can't seen to get the right xPath to find an element.. Sample html:
<input type="button" onclick="ViewContact('9498')" value="View Contact" class="FormButton">
<input type="button" onclick="ViewContact('9499')" value="View Contact" class="FormButton">
I can find both of these with:
//input[contains(@value,'View Contact')]
But if I want to find just one via the id, like:
//input[contains(@onclick,'ViewContact('9498')')]
won't work, I assume the apostrophes aren't escaped right.. tried without them:
//input[contains(@onclick,'ViewContact(9498)')]
This works:
//input[contains(@onclick,'9498') and contains(@onclick,'ViewContact')]
but i'd rather not have to use 2 clauses.. any way to do this in one contains ?
Duh...Thanks :) At least I didn't use my login :)
Any tools that can help figure this out instead of stubling around trying things ?
A: You can use this XPath:
//input[contains(@onclick,"ViewContact('9498')")]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NSAutoreleasePool in UIViewController life cycle I am working in an app for iPad. It presents several views, so I have to be careful with the memory management.
My problem is related with the autorelease objects. I would like to associate a NSAutoreleasePool to each view controller. Something like this:
MyViewController.h
@interface MyViewController: UIViewController
@property (nonatomic, retain) NSAutoreleasePool *myPool;
MyViewController.m
@implementation MyViewController
@synthesize myPool;
- (void) viewDidLoad {
myPool = [[NSAuroteleasePool alloc] init];
}
- (void) dealloc {
[myPool drain];
}
A NSAutoreleasePool can not be used as a property. I would like to achieve a behavior similar to this. Any idea? Thank you in advance.
EDIT
Thank you for your answers. In response to your questions (I can not answer my question yet):
The viewController will do a lot more of things, will respond to events, etc, etc. What I would like is, after all these operations, release what should be autoreleased. Extending the example:
MyViewController.h
@interface MyViewController: UIViewController
@property (nonatomic, retain) NSAutoreleasePool *myPool;
MyViewController.m
@implementation MyViewController
@synthesize myPool;
- (void) viewDidLoad {
myPool = [[NSAuroteleasePool alloc] init];
}
- (IBAction) whatEver: (id) sender {
UIImage *img = [UIImage imageWithData: ...];
NSString *str = @"MyString";
...
}
- (void) dealloc {
[myPool drain];
}
Here, what would happen with the string and the image? I guess they are retained in the pool, aren't they? I could wait for the release pool in the main method but I guess it will be drained when the application ends.
A: It is completely unnecessary to create local autorelease pools in such case. Are you sure you know how autorelease pools work? What exactly are you trying to achieve?
(After editing the question.) Ah, I see. You don’t understand Cocoa memory management, please read the guide. The main autorelease pool gets drained after each runloop iteration, which makes your local autorelease pools completely useless. Custom autorelease pools are rarely needed, mostly just when you create a lot of objects in a loop or when you are doing stuff in your own thread.
To put it shortly, forget about extra autorelease pools and everything will work fine.
A: This is a very bad idea. Read Using Autorelease Pools and the Memory Management Policy
first.
A: No need to create the Local autorelease pool.in main.m file you have NSAutoreleasepool it will take care of it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to display bitmap from internal storage? I saved my bitmap images in my internal storage but i can't redisplay it. I've been researching for a long time but i've not find yet.
public static void saveImages(Activity activity) throws IOException
{
for (int i=0; i<categories.getItems().length; i++) {
OutputStream os2 = activity.openFileOutput(categories.getItems()[i].getName(),
Context.MODE_WORLD_READABLE);
OutputStreamWriter osw2 = new OutputStreamWriter(os2);
Bitmap bmp = ((BitmapDrawable)categories.getItems()[i].getCategoryImage()).getBitmap();
bmp.compress(Bitmap.CompressFormat.PNG, 90, os2);
osw2.close();
}
}
This code works succesfully to save images. I will redisplay that images from files.
Thank you
A: Try this code: uses openFileInput to fetch the streams you saved and then decodes them:
for (int i=0; i<categories.getItems().length; i++) {
InputStream is = activity.openFileInput(categories.getItems()[i].getName());
Bitmap b = BitmapFactory.decodeStream(is);
// do whatever you need with b
}
A: Try this
File f=new File(yourdir, imagename);
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
A: decode bitmap, and then make a new imageView then add the bitmap to the imageView.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I make this AJAX/PHP work? So I'm new to AJAX (not as new to PHP), and I'm trying to create a login using AJAX to query the PHP file. So, this is the code I'm trying to use.
I have three files. The first one is login_form.php. It contains the login form...
<html>
<head>
<title>Log In</title>
<script language="javascript" src="loginsender.js" />
</head>
<body>
<form method="post" name="loginfrm" onsubmit="formValidator()">
<p id="hint"></p>
<label for="username">Username:</label><input type="text" name="username" id="username" />
<label for="password">Password:</label><input type="password" name="password" id="password" />
<input type="submit" name="submit" value="Log In" />
</form>
</body>
</html>
The next loginsender.js. This is the JavaScript/AJAX file I'm using to send to the PHP script...
function formValidator()
{
if (document.loginfrm.username.value.length < 3 || loginfrm.password.value.length < 3)
{
msg = "Please enter a valid username/password."
document.getElementById("hint").innerHTML=msg;
}
else
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
}
var params = "username=" + document.loginfrm.username.value + "&password=" + document.loginfrm.password.value;
xmlhttp.open("post", "login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
The last one is login.php, which is what I'm using to handle the actual logging in...
<?php
session_start();
require_once("includes/mysql.inc.php");
require_once("includes/functions.inc.php");
$username = sanitize($_POST['username'], true);
$password = sanitize($_POST['password'], true);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($query);
if (mysql_num_rows($result) != 1) // no such user exists
{
echo 'Sorry, no such user exists';
logout();
die();
}
$userData = mysql_fetch_assoc($result);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password));
if ($hash == $userData['password'] && $username == $userData['username']) // successful log in
{
validateUser($userData['username']); // set session data
echo '<meta http-equiv="refresh" content="2; url=index.php" />';
}
else
{
echo 'Sorry, but you entered an incorrect username/password.';
logout();
die();
}
?>
All in all, the goal is to have the user enter their username and password combination in login_form.php and submit it, triggering loginsender.js (and the formValidator() method). This then will query the PHP login script, which will test for a valid user/pass combo, then set it up in the session (or not, if the log in failed). The issue is, no matter what combination I enter, nothing happens, the page refreshes upon clicking submit, but that's it.
**UPDATE 1:
I have edited my login_form page, I've simply put the formValidator function into the script to start with, that way its easier for me to look at rather than flipping between documents.
I also implemented some of the suggestions that were made.
Here it is:
<html>
<head>
<title>Log In</title>
<script type="text/javascript" language="javascript">
function formValidator()
{
if (document.loginfrm.username.value.length < 3 || loginfrm.password.value.length < 3)
{
msg = "Please enter a valid username/password."
document.getElementById("hint").innerHTML=msg;
}
else
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
}
var params = "username=" + document.loginfrm.username.value + "&password=" + document.loginfrm.password.value;
xmlhttp.open("post", "login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
</script>
</head>
<body>
<p id="hint"></p>
<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">
<label for="username">Username:</label><input type="text" name="username" id="username" />
<label for="password">Password:</label><input type="password" name="password" id="password" />
<input type="submit" name="submit" value="Log In" />
</form>
</body>
</html>
A: It doesn't look like you're preventing the default 'submit' action from happening, which since you haven't defined a action for the form is to just POST back to the current page.
Change your form html line to:
<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">
The return false; tells it to NOT do whatever it was going to do for that action.
A: If you don't want the Form-submit-action to refresh the page, return false from your onsubmit script. Otherwise, the browser will do exactly what you tell him in the <form>: a HTTP POST.
A: I think the OnSubmit() function is executed and also the form is really submitted! So you get a blank page which is the output of php script.
Don't make it a html-form and it should work fine.
A: You need to write this to prevent form refresh..
<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">
other than this, your code is fine..
A: try this
<input type="submit" name="submit" value="Log In" onclick="formValidator(); return false;"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android: webview I am trying to wrap a web application say www.xyz.com within a webview using shouldOverrideUrlLoading. I have two activity one that launches the application, this checks all the activity running and determines whether to launch new instance or not and other activity which wraps my application www.xyz.com in the webview.
I'm facing two problems:
*
*When I press the sleep button and then again press it to open the device, or when the application is idle and went to sleep and I press the button to open the device, the application restarts (the webview restarts).
*Also when link in the webapplication which opens someother site say for example www.abc.com doesn't work fine, it works for the first time and opens the site in external browser as desired, however on further click tries to open the site within the webview which is not desired.
I have googled this and found suggestion like the code below:
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("abc")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
return true;
} else {
view.loadUrl(url);
return false;
}
}
However, in my case for the first time the site www.abc.com is opened in external browser but for the second time its open within the webview, i've debugged it in eclipse and found the url value comes the same in subsequent cliks .
A: 1) For the WebView restart problem, you need to add the following lines of code to your activity that contains the WebView
android:launchMode="singleInstance"
android:alwaysRetainTaskState="true"
Also see tutorials on how to save state of WebView in Bundle.
2) For your external browser problem, try
url.equals("www.abc.com")
instead of
url.contains("abc")
Hope that solves your problem :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: php cli not working in my web server I am trying to run a php file in my web server in command line using
php test.php
But it is not working. it runs forever and takes 100% resources.
It was working yesterday and now it is not working.
I tried to debug the process using
strace -p <pid>
and got lots of
times(NULL) = -2058427839
Can anyone help me to debug this? Rebooting and upgrading is my last resort. Please suggest a solution without reboot or upgrade.
A: Try to run your php file in cli without the configuration file using the following command:
php -n <your-filename.php>
and then check whether its working?
A: Place this into your test.php file to check that it is working and to see what is available.
phpinfo();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: App Error:104 illegalArgumentException while running the Blackberry Application i have created one application which parsed the data and it will displyed in ListRow,for that i have created http connection as below.
enter code here
public void run() {
System.out.println("Run Method called");
HttpConnection Conn = null;
InputStream is = null;
try {
System.out.println("Before Connection");
Conn = (HttpConnection) Connector.open("MYURL;deviceside=true" );
System.out.println("HTTP connection called");
//conn = (StreamConnection) Connector.open("http://xyz.com/Verandah/RSS/RSSContent.aspx?CatId=4;deviceside=true");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setCoalescing(true);
DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(is);
when i am running my application i am getting IllegalArgumentException.i have compiled my application and i found i am getting the above exception in this line Document doc = docBuilder.parse(is); am i doing wrong anything wrong while creating a connection? need your suggestion why i am getting exception at this line.
thanks.
A: You forgot to open inputstream over httpconnection before passing it to parse() method.
In your code is == null at this line.
Add this line
is = Conn.getInputStream();
before passing is to parse() method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to write a search method include "Like" such as SQL in J2ME Now I try to write a small method to search in j2me, it works well but I don't know how to write a method like SQL use "Like" in j2me to search recordstore doesn't need match 100% percent.
Example
In my RecordStore there are 2 records
London; Paris; Atlanta;
Paramount; NewYork; Bronx;
*
*When I type on TextField letter "o" it only shows last record
Paramount; NewYork; Bronx
although first record also has "London"
I learned how to write a search method from Java2s dot com
http://www.java2s.com/Tutorial/Java/0430__J2ME/SearchrecordinRecordStore.htm
How to use "Like" in J2me?
A: (expanding on what was discussed in question comments)
Regarding your general question - the answer is no, MIDP 2 API has nothing like SQL LIKE. SQL expressions/statements cannot be used according to RecordStore API.
The way to to search MIDP RecordStore for inexact match (similar to SQL LIKE) is to process the records using regular expressions. Note that regular expressions, in turn, are also not available in MIDP 2 API.
To use regular expressions in MIDP, one would have to write own code for these, or better yet, get some library that does that, eg "regexp-me" open source package:
"Java Me (j2me) regular expression package based on Jakarta Regexp. Regexp-me is CLDC1.0 compatible and has partial Unicode support".
As for the example SearchrecordinRecordStore.htm you mention, it looks like if you correctly ported it then you should get "London".
*
*I mean if your RecordFilter passes at strings containing "o" (case insensitive) and if you enumerated records using that filter then "London" should be there in the enumeration.
Check if you somehow missed "London" when doing the output (btw original example seem to be targeted at displaying a single result). If you use emulator, consider using System.out.println - that way you could re-check the output not only with MIDlet UI but in emulator console.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Serial Port Communication With Mobile Phones I want to connect my mobile phone to PC Using Serial Port. and communicate and send sms to contacts stored in phone memory.How to achieve this in C#.
A: First of all, you are not providing sufficient data to answer this question. Anyway i am writing what i know about this.
I have used two type phones to send sms from the PC and from my micro-controller board, both are with USB connectivity.
In the first case, there is a USB to serial converter inside the data cable, and the USB side is connected to the PC. if you want connect this type phone to PC's serial port, you have to hake the data cable, find out the RX and TX lines which is connected to the phone. Now you can connect the RX,TX and Ground to the serial port, but some times you need a level converter.
In the second case(Currently available phones), the phone itself is a USB device and you can't connect to a serial port. But here the advantage is that, when you install the driver of the phone, you will get one or more Virtual serial port, and from the point of a programmer it is a real serial port. You can send AT commands through this port and get the response.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Title: Read contents from text file dynamically in classic asp I have done the code to write the values I enter in the text box to a text file. Now I want to read those values and assign it to a variable.
The values stored in text file are as follows:
abc.jpg,www.google.com
123.jpg, www.yahoo.com
I want to read the image name in a separate variable and the link in separate variable. As I want to assign those to image rotator code. Please help.
I have used the following code to read the link in the text file: now I want to read the image name from the text file.
Do While Not objTextFile.AtEndOfStream
intLineNumber = intLineNumber + 1
strReadLineText = objTextFile.ReadLine
'response.Write("Hi")
Postion1= InStr(strReadLineText, strSearchText)
Postion2= Postion1 + len(strSearchText)
URLString=Mid(strReadLineText,Postion2+1,len(strReadLineText))
'URLString=Left(strReadLineText,strSearchText)
If strSearchText <> "" And InStr(strReadLineText, strSearchText) > 0 Then
strReadLineText = Replace(strReadLineText, _
strSearchText, _
"<span style=""background-color:yellow;"">" & strSearchText & "</span>")
strLineNumbers = strLineNumbers & intLineNumber & ", "
Exit Do
A: Instead of using InStr, you could use a Split (DevGuru link) which will return an array of the values on each line.
arrVals = Split(strReadLineText, ",")
strImageName = Trim(arrVals(0))
URLString = Trim(arrVals(1))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to launch iPhone app (using Phonegap) on iTunes How do I launch an iPhone app (using Phonegap) on iTunes?
What are the requirements to launch an app on iTunes?
We already have a developer certificate.
A: To get an app onto the iTunes (Apple) App Store, you need to go through iTunesConnect:
http://developer.apple.com/support/resources/itunes-connect.html
I am not sure I know what you mean by Phonegap.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Move div down smoothly while updating in JQuery I was trying to make a list that updates from the top. Every time when new list item is inserted, old items will be moved down together smoothly
So firstly I generate list item every time I click
function addItem(){
$('#public').prepend('<li><div id="item' + i + '" class="tile"></div></li>');
$('#item' + i).fadeIn();
i ++}
then I tried to animate() them down by using the code below:
$('.tile').animate({top:42},500);
Strangely, only the last element will animate down smoothly, other elements will still be squashed down. And there is always 42px white between.
A: I don't see where the variable i gets initialized? I mean, does it increment since you don't pass the variable in the method or retrieve the current value from somewhere. I don't think you need to use the variable anyhow by the way. You can use jQuery to get all siblings and than call the animate on that list of items (of course with an if statement that skips the latest added item).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Changing and retaining changed element in table view titanium Hi, I am developing an Android application using Titanium. For changing image on click I used following code. But the problem is that when I click on image it will change only once (on first click), when I click again it won't show changed image. But in alert it shows the image source is changed. (The changes are not reflecting on screen!!??) Another problem is when I click (the image gets changed), then go on child window and come back. It is not retaining the changes.
var feed_table = Ti.UI.createTableView({minRowHeight:5,hasChild:true});
var data = [];
for (var i=0;i<5;i++)
{
var row = Ti.UI.createTableViewRow({height:'auto',className:"row"});
var username = Ti.UI.createLabel(
{
text:'nilkash',
height:'auto',
font:{fontSize:12, fontFamily:'Helvetica Neue'},
width:'auto',
color:'#000',
textAlign:'left',
top:0,
left:35,
});row.add(username);
var doneCheckbox = Titanium.UI.createImageView(
{
id:'image_'+i,
clickName:'ClickName',
image:'../images/finished-work.png',
width:15,
height:15,
top:32,
left:0,
});row.add(doneCheckbox)
data.push(row);
}
feed_table.setData(data);
feedWin.add(feed_table);
feed_table.addEventListener('click',function(e)
{
if (e.source.clickName == 'ClickName' )
{
if(feed_table.data[0].rows[e.index].children[1].image == '../images/work.png')
{
feed_table.data[0].rows[e.index].children[1].image = '../images/finished-work.png';
}
else if (e.source.clickName == 'ClickName' )
{
feed_table.data[0].rows[e.index].children[1].image = '../images/work.png';
}
}
});
I also used another simple solution just toggling two images.But it also not retaining these changes. Whether it required to again push that changes in to table view? Thanks for help in advance.
A: I had the same problem. In the end I removed the old image and replaced it with a new one on every click event. That's annoying but I found no other solution. The android part of titanium is quite buggy sometimes.
[update]
i modified the old code a little bit:
/* creates our imageView with specific url */
createImage = function(url)
{
var imageView = Ti.UI.createImageView(
{
image:url,
left:0,
top:0,
height:25,
width:25
});
return imageView;
};
/* creates our tableview row with imageView */
addRow = function(_args)
{
var row = Ti.UI.createTableViewRow(
{
height:'auto',
className:"row"
});
var username = Ti.UI.createLabel(
{
text: _args.text || 'user name',
height:'auto',
font:{fontSize:12, fontFamily:'Helvetica Neue', color:'#000'},
width:'auto',
color:'#000',
textAlign:'left',
top:0,
left:35,
});
row.add(username);
/* create initial imageview */
var imageView = createImage(_args.image);
row.add(imageView);
/* custom function to set image */
row.setImage = function(image_url)
{
/* remove the old image */
row.remove(imageView);
imageView = null;
/* add new image */
imageView = createImage(image_url);
row.add(imageView);
};
row.addEventListener('click',function(e)
{
/* on click replace the image */
row.setImage('new/image/path');
};
return row;
}
var user_table = Ti.UI.createTableView({minRowHeight:5.length,hasChild:true});
var data = [];
for (var i=0;i<5.length;i++)
{
var newRow = addRow({
text: 'my text',
image: 'my image url'
});
data.push(newRow);
}
feed_table.setData(data);
feedWin.add(feed_table);
A: I prefer to use use a createView with a background image, it works fine. I use it to simulate CheckBoxes and I have no problems.
A: Please remove your Ti.UI.SIZE in TableView and TableViewRow both height and width... It will work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Custom view in android I need some valuable advice from you guys...
I have a UI where I have to drag objects from one view to another.
I have a rough sketch of this UI below
I think I have to create a custom view for this. I have to drag a square and a ball from bag 1 and bag2 [both bags are scrollable, can contain 10 to 60 items each] and drop it to the closet one by one. and later I have to find the number of items in the closet. The items in the closet must be arranged in a well maintained fashion [may be ...like 6 in a row].
*
*Where should I start?
*How many custom views should I use?
*Is there a simple and effective UI solution for this?
Happy coding..!
A: I would suggest a design with three different GridView objects laid out inside a ViewGroup that supports dragging objects from one GridView to another. The objects would be custom ImageView subclasses so you'd have a place in code to support a drag-and-drop protocol of some sort and because you'd likely want to associate some data that is specific to your application with the objects being dragged.
As for the drag-and-drop protocol, you could consider an adaptation of the Android Launcher drag-and-drop framework or the current drag-drop classes described on the Android developers' website. I don't have much to say about the current drag-drop classes. I have not tried them yet, but understanding them is on my to-do list. However, I have done an adaptation of the Launcher code, and I have written it up on my blog and posted demo apps and source code there. See Drag-Drop for an Android GridView.
With the framework that originated in the Android Launcher, you have a good set of classes and interfaces to work with. Some of the objects include: DragLayer, DragSource, DropTarget, DragController, DragView. The DragLayer is a custom ViewGroup within which all drag-drop operations occur. It delegates handling of all the touch events to a DragController, which is the object that does the actual moving of objects around on the screen. As it does so, it interacts with DropTarget objects to give the user visual feedback that something is being dragged and that a place to drop something is available. A DropTarget is an object where something can be dropped. A DragSource is the interface for objects that can be dragged within the DragLayer. The Launcher framework is a good one because it gives you a way to think about dragging and dropping and how you want to divide up the responsibilities defined by the framework.
The reason I suggest GridViews for your problem is it sounds like you are thinking that way already. The closet has "maybe 6 in a row" so that could be a GridView with one or more rows depending on how screen space you have. A GridView would also work for the container that holds the squares and circles. If that is a good fit, you could study the code in my drag-drop tutorial and see if that makes it easy for you to move objects from one GridView to another.
In my demo program, I ended up with a custom subclass of ImageView that I called an ImageCell. These are views that are on the grid. An ImageCell allows objects to be dragged from them and onto them. For awhile as I worked on the tutorial, I had a custom GridView class too but ended up with the standard GridView. It sounds like you'd want a custom GridView because it sounds like being in the closet is different than being in the other sections. Having it gives you a convenient place for the methods you have not thought of yet.
I hope some of these suggestions prove useful.
A: Depends on the Android version you are targeting. For 11 and above you can use the built in drag and drop functionality, otherwise you are pretty much on your own. I would normally advice you to implement some sort of a long press action that might even allow you to select multiple items and move them in batches, which would be a really simple thing to implement.
If you really need DnD you should check out this example, it should give you some idea on how to make your own implementation.
A: I think that bag1, bag2 and closet can be three instance of the same configurable custom view (let's name it CustomBagView).
CustomBagViews should be responsible for displaying items (using a gridview of imageview for example).
I think those will not need to handle drag & drop directly but they should support
*
*removing and adding elements
*provide a setOnItemTouched(Interface_class) callback setter.
Then you will need to code a Container custom view (let's name it BagContainerView) that will contain the three bags and handle the dragging & dropping from the bags.
You will provide a handleDrag callback to each bag using CustomBagView.setOnItemTouched, then track the finger motion in it.
When the dragging finishes, you must find where it ends, locate the right 'customBagView' and ask it to add the item to its list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: UITabbarController + ABPeoplePickerNavigationController not working properly Currently I am using ABPeoplePickerNavigationController along with UITabbarController and want to open ABPeoplePickerNavigationController in UITabbarController's index 2..
So on viewcontroller at index 2, I had written code like this,
-(void)awakeFromNib
{
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
NSMutableArray *newControllers = [NSMutableArray arrayWithArray: [self.tabBarController viewControllers]];
[picker.navigationBar setBarStyle:UIBarStyleBlackOpaque];
[newControllers replaceObjectAtIndex:2 withObject: picker];
[self.tabBarController setViewControllers: newControllers animated: NO];
[picker release];
}
but when I had written this code, suddenly the title of tabbar changed from contacts to Groups and image not showing..
How can we show the title and image for this tabbar as before....
Please help me to solve this problem..
Thanks in advance...
A: Please write this code in your
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
method after
[self.window addSubview:tabBarController.view];
UITabBarItem *tabItem = [[[self.tabBarController tabBar] items] objectAtIndex:TAB_INDEX];
[tabItem setTitle:@"Contacts"];
tabItem.image = [UIImage imageNamed:@"YOUR IMAGE"];
Happy Coding....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Determine element left of cursor in JavaScript Is it possible determine the character on the left of the cursor's current position?
Basically if the cursor is at, x-45 I'd like to determine if it's prefixed by a { character.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get the list of all "Change Sets" of a user in TFS? I just want to get the list of all change sets of a user in TFS. I want only the id of the change set, and a link to all items which are being checked in as part of that change set.
How can I do that?
A: Besides option presented by Richard, you can also do that from within VS using the "Changesets" option:
It's also possible to do it via the API. I can provide a short snippet, if you're interested.
A: For Visual Studio 2013
*
*Open Source Control Explorer
*Right click on the repository you want to search
*Select Find => Find Changesets
*The "Find Changesets" window will open where you can filter by username.
A: tf hist ‹item› /user:name will filter the history by user, so this could be used to get a complete set of changes for a user, from which the changeset numbers can be extracted.
A: I found a round about way.
You can open a TFS task, and link a Changeset to the task. There you can browse for a changeset using search parameters.
I don't know why this is the only place where this functionality is available, but at least it's there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
}
|
Q: MSDAORA provider not found for asp.net site I've got stuck with strange Oracle connection error on Windows Server 2003 x64 (IIS 6)
While console .Net application that runs onbehalf of administrator successfully connects to Oracle 10g Express via OleDb [Connection string looks like: Provider=MSDAORA;Data Source=server-ip:port;User Id=user;Password=password;]
ASP.NET 4.0 web-site (application pool runs on behalf of administrator too) fails with error:
The 'MSDAORA' provider is not registered on the local machine
Connection string is the same, but it doesn't work for asp.net site. What shall I check?
Thank you in advance!
A: This Social.MSDN link seems to point to the fact that you have x86 drivers installed;
From my viewpoint you have two options:
*
*Convert the app to run on 32bit mode in IIS - Can help if you require assistance. LINK
*Download and try the 64bit version of the drivers. Oracle x64 downloads
A: Another approach would be to enable 32-bit applications for the IIS Application Pool your application is using. I would suggest creating a new application pool specifically for your application making sure to enable 32-bit applications.
You'll likely suffer performance issues but at least you'll be up and running.
A: I have resolved this issue in one of my applications with ASP(MSDAORA connection) - oracle environment with following fix from
http://technet.microsoft.com/en-us/library/cc784046.aspx
following are the steps
To enable IIS 6.0 to run 32-bit applications on 64-bit Windows
1.Open a command prompt and navigate to the %systemdrive%\Inetpub\AdminScripts directory.
2.Type the following command:
cscript.exe adsutil.vbs set W3SVC/AppPools/Enable32BitAppOnWin64 true
3.Press ENTER.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AIMA Framework printing states Considering that AIMA has functions to return the actions/instrumentation followed for a given problem, is there a way to get a list of expanded nodes, or the states which led to the problem's solution? I've scoured the source code and couldn't find much. If anyone has worked with this framework in the past and feels like helping, that'd be great.
A: (Clarification: AIMA means the textbook Artificial Intelligence: A Modern Approach.)
In aima-python, the Node class has a path() method returning the path to reach it from the initial state. Probably aima-java, etc., have something similar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WPF Button Focus error I have modified my wpf button but the problem is when i hit the tab the next button got a rectangle over it and my effect got overrides
any solution ??
A: Set the FocusVisualStyle to null for the control that you don't want focus rectangle to appear on.
<MyControl FocusVisualStyle="{x:Null}" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to check what all URLs are available on a particular server? On a machine, there is a HTTP server running at a particular port. I know some of the pages that are accessible:
http://myothermachine.tx:6566/info
http://myothermachine.tx:6566/status
etc.
The pages that are not accessible will result in 404's.
Is there a way I can find out what all URIs do not result in 404's?
A: No, there is no standard way to do this. There exists no 'universal query' which asks for the machine to respond with a list of all accessible URLs.
However, a couple of things you could try:
*
*Check the machine's documentroot. See what files exist.
*Check the webserver configuration. See what mappings exist.
*Check what applications are deployed on the machine.
*Check if there is a robots.txt
*Check for links to the machine on other sites
*Use a search engine, of the machine is indexed
*Brute-force the machine, trying every possible combination. Not very friendly...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: functional test in playframework fails when adding items to cart I wrote a functional test to check adding items to a shopping cart.For a user to be able to add items to cart,he needs to login.So,I created a method to login the user and another method to add the item.Before and after the addtocart method in test,I am checking the size of content of cart.The addtocart functionality works without any problem when I run the app in dev mode(I can check the db too-which is postgres and not an in memory db).The addtocart fails in test.
the controller method which adds item to cart
public static void addItemToCart(Long productId,Long cartId,String quantity) {
Product product = Product.findById(productId);
ShopCart cart = ShopCart.findById(cartId);
int qty = Integer.parseInt(quantity);
CartItem cartItem = new CartItem(product,qty);
cart.addItem(cartItem);
cart.save();
System.out.println("Controller::addItemToCart()::cart id="+cart.id+" has="+cart.cartItems.size()+" items);
}
my test method is
@Test
public void testUserCanAddItemsToCart() {
Fixtures.loadModels("data.yml");
User user = User.find("byEmail","user@shop.com").first();
loginAsCustomer("user@shop.com","userpass");
ShopCart usercart = new ShopCart(user);
usercart.save();
System.out.println("BEFORE ADD::usercart="+usercart.id+" has :"+usercart.cartItems.size()+" items");
assertTrue(usercart.cartItems.size()==0);
addItemsToCart(usercart);
System.out.println("AFTER ADD::usercart="+usercart.id+" has :"+usercart.cartItems.size()+" items");
assertFalse(usercart.cartItems.size()==0);//why does this fail?
}
private Response addItemsToCart(ShopCart cart) {
Product pdt = Product.find("byIsbn","654-0451160522").first();
assertNotNull(pdt);
System.out.println("addItemsToCart():BEFORE ADD cart="+cart.id+" has="+cart.cartItems.size());
Map<String,String> addtocartParams = new HashMap<String,String>();
addtocartParams.put("cartId", cart.id.toString());
addtocartParams.put("quantity", "2");
String addtocarturl = "/items/addtocart/"+pdt.id.toString();
Response response = POST(addtocarturl,addtocartParams);
System.out.println("addItemsToCart():AFTER ADD cart="+cart.id+" has="+cart.cartItems.size());
return response;
}
The console output I get is
BEFORE ADD::usercart=48 has :0 items
addItemsToCart():BEFORE ADD cart=48 has=0
Controller::addItemToCart()::cart id=48 has=1 items
addItemsToCart():AFTER ADD cart=48 has=0
AFTER ADD::usercart=48 has :0 items
Here, in the controller method, the cart instance (of id=48) has 1 item after it is saved to db.But in the test method ,the cart instance of same id has 0 content.
I commented out the assertFalse method and retrieved the cart from db using the cartId.Even then the cart of same id has 0 content.I can't understand why this is happening..can anyone shed some light?
//test method body ..modified
ShopCart cart = ShopCart.findById(usercart.id);
System.out.println("AFTER ADD::cart="+cart.id+" has :"+cart.cartItems.size()+" items");
assertFalse(cart.cartItems.size()==0);//why does this fail?
A: It fails because the cart instance used by your test method and the cart instance used by the addItemToCart method are different. Each transaction has its own instance of the entity. And JPA doesn't automagically refresh an entity when some other transaction updates the row mapped by this entity.
You should reload the cart from the database after addItemsToCart has been called to check if something has been added to the cart in database.
A: I am a slave to object-oriented thinking, so what I'm wondering is, have you thought about making addItemsToCart() a method of your ShopCart class? I'm envisioning something like:
...
ShopCart usercart = new ShopCart(user);
usercart.addItemsToCart(pdt);
usercart.save();
String addtocarturl = "/items/addtocart/"+pdt.id.toString();
Response response = POST(addtocarturl,addtocartParams);
return response;
It's just easier for me to think about making (or retrieving) a ShopCart object, modifying it, and putting it in the database. That's how I would avoid this.
A: I had the same issue and adding JPA.em().clear() in my test before I get the model from the database solved this issue for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Break up big array into smaller arrays, or break up a big text string into smaller strings - javascript What is the method for breaking up a big array into smaller arrays. Or a big text string into smaller strings in javascript.
Ex: I have a string of 49 words separated by spaces/commas. I want to break it up into smaller strings of 10 words and the 9 remainder string. Same for an 49-element array.
Is there a prebuilt method for this?
TIA
A: To split up a string, use: string.split. If you want to split a string which is separated by a comma, use string.split(',').
When you want to split a string in parts of 10 characters, use:
var string = "15dsck3c rando mstring esjldf bjk";
var match = string.match(/[\S\s]{10}|[\S\s]{0,9}$/g); //{10} = 10 characters;
var listOfWords = Array.apply(null, match);
Splitting an array can be done by using the array.slice method (which does not modify the array).
var arr = ["big", "small", "huge", "wall", "of", "text", "etc", "etc"];
var newList = [];
for(var i=0, len=arr.length; i<len; i+=10){
newList.push(arr.slice(i));
}
//newList is an array consisting of smaller arrays, eg
// [["big", <9 other elements>], [<10 elements>], ...]
A: http://www.w3schools.com/jsref/jsref_slice_array.asp
a more general tutorial.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Gimme this join or that join (MySQL) SELECT COUNT(*) as snitch_count
FROM snitchings
JOIN pimps ON pimps.pimp_id=snitchings.pimp_id
JOIN prostitutes ON prostitutes.prostitute_id=snitchings.prostitute_id
WHERE snitchings.case_id=4538;
This is what I have and it runs but it doesn't seem right (the tables exist but there's no test/dummy data yet so I can't fully know). I believe the above query will return the total sum of snitchings for pimps AND prostitutes, as a pair, for that given case (they're huge cases). But I need the query to return the total sum of snitchings for pimps OR prostitutes. How do I fix that query to do this?
DISCLAIMER: I'm probably exhausted from coding for hours on end, please excuse me if my syntax or explanation is a little wonky
A: No, your query will find lines in snitchings that have a valid pimp_id AND a valid prostitute_id.
Are you sure you need a JOIN? Can table snitchings have invalid values in prostitute_id or pimp_id? Else, this would work:
SELECT COUNT(*) as snitch_count
FROM snitchings
WHERE snitches.prostitute_id IS NOT NULL OR snitches.pimp_id IS NOT NULL
If you do need a join, and both are exclusive, (either a snitch is a prostitute OR a pimp), this should work:
SELECT COUNT(*) as snitch_count
FROM snitchings
LEFT JOIN pimps ON pimps.pimp_id=snitches.pimp_id
LEFT JOIN prostitutes ON prostitutes.prostitute_id=snitches.prostitute_id
WHERE snitchings.case_id=4538 AND
(pimps.pimp_id IS NOT NULL OR prostitutes.prostitute_id IS NOT NULL)
Else, you need to count them seperately (but you could UNION and SUM if you really want to:
SELECT COUNT(*) as snitch_count
FROM snitchings
JOIN pimps ON pimps.pimp_id=snitches.pimp_id
WHERE snitchings.case_id=4538;
SELECT COUNT(*) as snitch_count
FROM snitchings
JOIN prostitutes ON prostitutes.prostitute_id=snitches.prostitute_id
WHERE snitchings.case_id=4538;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android fast pixel access and manipulation I'm trying to port an emulator that i have written in java to android. Things have been going nicely, I was able to port most of my codes with minor changes however due to how emulation works, I need to render image at pixel level.
As for desktop java I use
int[] pixelsA = ((DataBufferInt) src.getRaster().getDataBuffer()).getData();
which allow me to get the reference to the pixel buffer and update it on the fly(minimize object creations)
Currently this is what my emulator for android does for every frame
@Override
public void onDraw(Canvas canvas)
{
buffer = Bitmap.createBitmap(pixelsA, 256, 192, Bitmap.Config.RGB_565);
canvas.drawBitmap(buffer, 0, 0, null);
}
pixelsA is an array int[], pixelsA contains all the colour informations, so every frame it will have to create a bitmap object by doing
buffer = Bitmap.createBitmap(pixelsA, 256, 192, Bitmap.Config.RGB_565);
which I believe is quite expensive and slow.
Is there any way to draw pixels efficiently with canvas?
A: You can use the drawBitmap method that avoids creating a Bitmap each time, or even as a last resort, draw the pixels one by one with drawPoint.
A: One quite low-level method, but working fine for me (with native code):
Create Bitmap object, as big as your visible screen.
Also create a View object and implement onDraw method.
Then in native code you'd load libjnigraphics.so native library, lookup functions AndroidBitmap_lockPixels and AndroidBitmap_unlockPixels.
These functions are defined in Android source in bitmap.h.
Then you'd call lock/unlock on a bitmap, receiving address to raw pixels. You must interpret RGB format of pixels accordingly to what it really is (16-bit 565 or 32-bit 8888).
After changing content of the bitmap, you want to present this on screen.
Call View.invalidate() on your View. In its onDraw, blit your bitmap into given Canvas.
This method is very low level and dependent on actual implementation of Android, however it's very fast, you may get 60fps no problem.
bitmap.h is part of Android NDK since platform version 8, so this IS official way to do this from Android 2.2.
A: Don't recreate the bitmap every single time. Try something like this:
Bitmap buffer = null;
@Override
public void onDraw(Canvas canvas)
{
if(buffer == null) buffer = Bitmap.createBitmap(256, 192, Bitmap.Config.RGB_565);
buffer.copyPixelsFromBuffer(pixelsA);
canvas.drawBitmap(buffer, 0, 0, null);
}
EDIT: as pointed out, you need to update the pixel buffer. And the bitmap must be mutable for that to happen.
A: if pixelsA is already an array of pixels (which is what I would infer from your statement about containing colors) then you can just render them directly without converting with:
canvas.drawBitmap(pixelsA, 0, 256, 0, 0, 256, 192, false, null);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Logs Files will reduce the website speed in cakephp? Sorry for this basic question
I logging($this->log()) lot of things from all controllers in my live site. My tmp/logs folder contain around 1 gb of log files, whether this will reduce the site speed/ or slows site speed? we are removing log files once in a week from live server
A: Yes it will affect performance
If you have large log files, before writing to the log it's necessary to scan to the end of the log file - although this is not normally noticable it can with large files degrade performance.
It's for this reasons that tools like logrotate exist; and why it's a good idea to get in the habit of deleting/archiving your log files from time to time - or regularly if they are building up quickly.
A: the impact of writing log is pretty negligible (although I don't know how much you are logging). Besides, try to limit logging to debugging purpose, when you are done, remove it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to organize Interfaces/classes/implementations in the project I found some questions about how to organise projects (namespace, one class per file etc), but on a more specific note, how do you organize "things" that are very tightly related ?
I usually end up with :
*
*an interface IMyStuff
*a base (sometimes abstract) class that provides basic skeletton for that interface : BaseMyStuff
*implementation classes MyStuffWithBellsAndWhistles, MyStuffWithChocolateFlavours
It seems to make sense that they should be in the same namespace, but it feels like my folders start to be a bit over-crowded if I put all these files together in the same folder (not actually a real problem, but it feels strange).
Would it be OK to define both the interface and the base class in the same file ?
Or would it be OK to group those things in sub-folders, but in the same namespace ? like this :
-MyNamespace
|-Interfaces
| -IMyStuff
| -IMyOtherStuff
|-BaseClasses
| -BaseMyStuff
| -BaseMyOtherStuff
|-Implementation
| -MyStuffWithAwesomeBehaviour
| -MyStuffWithGreatUsefulness
| -MyOtherStuffSoNeatYouWillCry
What are the "best practices" regarding this kind of organization ?
A: If the purpose of the interfaces is to abstract the implementation and allow for alternative implementations that are not known to the author of the interface, then I would recommend keeping them in an seperate project file. When constructing unit test projects or other consumers of the interface this will allow them to create a project reference that drags in only the interfaces and not the implementations. This means alternative implementations of concrete classes never need to have a reference to the original concreate representation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to write a TextView in a determined coordinates of the screen? (frame layout) I have a app that shows the camera view on the screen on a FrameLayout. The screen is in fixed LandSape mode.
I need to write a textView with dinamically determined coordinates of the screen. The coordinates are determined in percentages, for example:
write the textview on the coorinates x=80% of the screen & y=20% of the screen.
write the textview on the coorinates x=35% of the screen & y=55% of the screen.
how to do it? i allready have the percentages, i only need to know how to use them to write the textview on the desired position of the frameLayout
code examples are welcome
thanks
A: You might want to add an AbsoluteLayout overlay, calculate the absolute position on the screen using screen dimensions and set the position of the view accordingly.
Edit
Since the AbsoluteLayout is deprecated, you can use the following technique to position the text in a RelativeLayout:
text = (TextView) findViewById(R.id.text);
RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
position.leftMargin = 20;
position.topMargin = 40;
text.setLayoutParams(position);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cut,Copy and Paste in eclipse GEF Editors I am creating eclipse gef editor using BPMN2 EMF models. Now i am almost end to editor functionality. But i am not clear to implement Cut,Copy and Paste functionality. i searched lot in net but all the tutorials i have seen using clone method in Models. In default bpmn2 models doesn't implement clone interface. Please suggest me any idea to achieve cut,copy and paste in gef editor without cloning.
Thanks.
A: You could look at the gef logic example:
they use a CopyTemplateAction (standard GEF action) and a custom LogicPasteTemplateAction.
These actions leverage the GEF command framework to istantiate a new Command to create the new model part.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: A stored proc to copy table data including any default value or binding data via a SQL script running within SQL Server I would like to be able to copy a table and it's data and also still have any default value or binding (as it is labelled within SQL Server Management console) constraints copied over.
The script below is a testing script to demonstrate the idea. The last line I assume needs to be replaced with a call to a custom stored proc?
Note: The source table (aSourceTbl) schema varies and can change over time.
--TEST SETUP
--Delete the prev tables so test script can be replayed
IF OBJECT_ID('aSourceTbl', 'U') IS NOT NULL
DROP TABLE aSourceTbl;
IF OBJECT_ID('aSourceCopyTbl', 'U') IS NOT NULL
DROP TABLE aSourceCopyTbl;
--Simple table to demonstrate table copying does not carry over the table constraits
CREATE TABLE [dbo].[aSourceTbl](
[aValue] [int] NOT NULL,
[DELETED] [int] NOT NULL
) ON [PRIMARY]
--Add some dummy data
INSERT INTO aSourceTbl (aValue, DELETED) VALUES (1,2);
INSERT INTO aSourceTbl (aValue, DELETED) VALUES (3,4);
--Add constraints of default values of 0 in this case
ALTER TABLE [dbo].[aSourceTbl] ADD CONSTRAINT [DF_aSourceTbl_aValue] DEFAULT ((0)) FOR [aValue]
ALTER TABLE [dbo].[aSourceTbl] ADD CONSTRAINT [DF_aSourceTbl_DELETED] DEFAULT ((0)) FOR [DELETED]
--Actual Required SQL script from here down
--The line below works nicely but does not copy the 2 constraints from the lines above into the new table.
--TODO QUESTION: Replace line below with the same functionaility + the constraints are also copied into new table
Select * INTO aSourceCopyTbl FROM aSourceTbl
Could you please help me by suggesting a suitable stored proc that can replace the last line in above SQL snippet? Any help greatly appreciated :)
References:
*
*Similar SO Question however focuses on PK constraints. I am only interested in default value constraints in this case.
A: You can execute this code after the last row which will replicate the defauld constraints to the new table (replace the variables with your table names).
declare @table_name sysname, @new_table sysname, @cmd varchar(max)
select @table_name = 'SOURCE_TABLE', @cmd = '', @new_table = 'TEST_TABLE'
select @cmd = @cmd+'ALTER TABLE '+@new_table+' ADD CONSTRAINT [DF_' +@new_table+'_'+a.name+'] DEFAULT '+b.definition+' FOR['+a.name+'];
'
from sys.columns a
join sys.default_constraints b on a.object_id = b.parent_object_id and a.column_id = b.parent_column_id
where a.object_id = object_id(@table_name)
print @cmd
exec (@cmd)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get maximum value from output of SQL query I have two tables: task_runs and integer_values. I am running a query to get this output:
task_name start_time value
acc_clock 2010-05-27 4
icc_opy 2010-05-28 5
icc_dtaf 2010-05-29 3
acc_clock 2010-05-25 34
icc_ruty 2010-05-23 33
icc_ruty 2010-05-22 45
This is my output of a SQL query which is coming from two different tables. Note that in this output, task_name is occuring twice. But I want the output to have only one occurrence of task_name and its associated value should be the maximum start_time, like this:
task_name start_time value
icc_opy 2010-05-28 5
icc_dtaf 2010-05-29 3
acc_clock 2010-05-25 34
icc_ruty 2010-05-23 33
My query is:
select t.task_name, max(t.start_time), i.value
from task_runs t, integer_values i
where i.run_id = t.id
and t.username = 'amit'
and t.start_time > '2010-05-20'
order by t.task_name
group by t.task_name
Why doesn't it work?
A: SELECT task_name, MAX(start_time) FROM your_table GROUP BY task_name;
Group by will take duplicates and group them in this case on task_name. And MAX will take the highest value. SO: when more tasks exist with the same name, display it once and show only the one with the highest start_time.
A: I think you need to take a look at GROUP BY and MAX
A: SELECT * FROM yourTable y
JOIN
(select task_name, MAX(start_time) maxtime FROM yourTable GROUP BY task_name) highest
ON y.task_name = highest.task_name AND y.start_time = highest.start_time
A: ;WITH max_start AS
(
SELECT
task_name
,start_time
,value
,row_number() OVER (PARTITION BY taskname ORDER BY start_time DESC) as row
FROM your_table
)
SELECT
task_name
,start_time
,value
FROM max_start
WHERE row = 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get the processor number on android Hi all, I want to get the processor number on android. can I do that like as follow:
int processporNum = sysconf(_SC_NPROCESSORS_CONF);
but everytime the return value is 1 on some of my phones, so i not sure this methold is right .is there anyother api can get this info
A: I see you're using native code.
So read file /proc/cpuinfo and interpret is accordingly.
It looks something like this:
Processor : ARMv7 Processor rev 2 (v7l)
BogoMIPS : 162.83
Features : swp half thumb fastmult vfp edsp thumbee neon
CPU implementer : 0x51
CPU architecture: 7
CPU variant : 0x0
CPU part : 0x00f
CPU revision : 2
Hardware : htcleo
Revision : 0000
Serial : 0000000000000000
A: you can run
Runtime.getRuntime().availableProcessors()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Titanium popover not working i'm trying to use the "Popover " functionality in the titanium.
i went throught the kitchensink and built a code in my application but some how
i'm getting this error:
Result of expression 'Ti.UI.iPad' [undefined] is not an object.
i dont know what i'm doing wrong.
here is my code:
var RLWindow=Ti.UI.createWindow({backgroundColor:'#700'});
var LBBar=Titanium.UI.createView({height:60,left:0,right:0,top:105,backgroundImage:'Images/toolbar.jpeg'});
var ShowNotes=Ti.UI.createButton({color:'blue',font:{fontSize:20,fontWeight:"bold"},right:10,title:'Today Notes',height:40,width:120});
LBBar.add(ShowNotes);
RLWindow.add(LBBar);
ShowNotes.addEventListener('click',function(e){
var popover = Ti.UI.iPad.createPopover({
width:300,
height:250,
title:'Test Popover',
arrowDirection:Ti.UI.iPad.POPOVER_ARROW_DIRECTION_UP
});
popover.show({
view:button,
animated:true
});
});
please help me with this situation..
Thank you
A: Clear out your build/iphone folder. I notice sometimes when you add a new platform UI object the compiler doesn't include the required Ti library in the xcode project.
A: This only works on the iPad, not on the iPhone. I am assuming you are using that? For iPhone you should use a regular window.
That being said, what is button? Stating the name, I guess that is your problem, because you need a view in that. If I do this (below) it seems to be working perfectly for me:
var popover = Ti.UI.iPad.createPopover({
width:300,
height:250,
title:'Test Popover',
arrowDirection:Ti.UI.iPad.POPOVER_ARROW_DIRECTION_UP
});
var win = Ti.UI.createWindow({backgroundColor: '#FFF'});
win.open();
var v = Ti.UI.createView();
win.add(v);
popover.show({
view: v,
animated:true
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: UINavigationBar with customized background - how to make rightBarButton visible I've customized background of navigation bar in my RootViewController (just part of code)
[navBar insertSubview:customBack atIndex:0];
I push detailViewController and add activity indicator as a rightBarButtonItem
UIActivityIndicatorView *actInd = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
self.activityIndicator = actInd;
[actInd release];
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:self.activityIndicator];
[self.navigationItem setRightBarButtonItem:barButton];
[barButton release];
The problem is that the indicator is not visible but without customized background it works OK.
A: You can better change your navigationBar Background I think. Create a subclass of UINavigationBar and add:
- (void)drawRect:(CGRect)rect {
UIImage * image = [UIImage imageNamed:@"MyNavigationBarBackground.png"];
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextScaleCTM(ctx, 1.0, -1.0); // Otherwise the image is drawn upside-down
CGContextDrawTiledImage(ctx, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);
}
I do that and I never add a problem with any button :)
A: Zoleas has the right idea. If you don't or can't use a subclass, I think your problem is that you are adding your subview at index 0 so it is on top of the other views in the navigation bar, it is probably hiding your buttons.
A: set rightBarButtonItem with following way
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Exit" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
Try this and also check the position of background
A: The activity indicator is there its just not being activated. Try animating it like this:
[actInd startAnimating];
Or if you want to keep it visible set the hideWhenStopped property like this:
actInd.hidesWhenStopped = NO;
A: Did you try to change the origin from the UIActivityIndicatorView?
Or creating it inside an UIView and add this UIView to the UIBarButtonItem.
I think the problem can be the frame from the element.
A: By this way you can resolve the problem:
Create activity indicator and add in a view1
Now this view1 add or create navigation bar with the help of this view1. Now when view1 is visible automatically you will be able to see the loading indicator.
Just wild try on this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the Best Way to Send Parameters to a UIViewController? I ask this question because it appears that viewDidLoad gets called before the main block of the initializer does and the class variables I'm initializing in the initializer are turning up nil in viewDidLoad. For your reference, I'm doing this entire viewcontroller programmatically and I've created a custom initializer so I can take in various parameters to be used in my viewcontroller. My custom initializer calls UIViewControllers designated initializer of course.
Basically, I'm curious about what is the proper design pattern for sending in parameters to a UIViewController? I've read other threads about this and haven't really gotten a definitive answer. Should I just skip the initializer and set the properties manually (from outside the class)? That seems kind of bleh, I'd really like to send in some parameters and am curious how others go about doing this?
A: The reason viewDidLoad is called before initialization completes, is probably because you call the view method in the initializer. For example:
- (id)init
{
if ((self = [super init])) {
_thing = 123;
_other = self.view.frame.size.width / 2;
}
return self;
}
viewDidLoad is called when the view loads. And the view loads as soon as you call the view method (or access the view property, if you prefer). So you should avoid referencing the view in init.
To answer your question, I prefer to create an init method for my view controllers.
- (id)initWithThing:(MyThing *)thing thang:(MyThang *)thang
{
if ((self = [super init])) {
_thing = [thing retain];
_thang = [thang retain];
// ...
}
return self;
}
You can also use properties to set extra variables after initing. Personally I prefer to do this with optional properties only, though, and put required properties in the init method. That way I can't init the view controller with an invalid state.
A: Basically you should have properties defined for your input data but add a custom init-function.
If you create a custom init-Method you should be fine - remember that initWithNibName:bundle: is the main initializer of UIViewController so this is what you want to call from your custom init-Method. viewDidLoad will always be called after your init-Method at the first usage of customVC.view (either from your code or via Framework):
- (id)initWithDataObject:(MyDataObject*)obj
{
self = [super initWithNibName:nil bundle:nil];
if (self) {
self.dataObj = obj;
}
return self;
}
A: I encapsulate the state of my controllers in an additional state object. So the controller usually has ivars for the GUI elements and a reference to this state object.
State objects are handled by a StateManager object on my delegate. So instead having a controller referencing another controller and set variables directly, all changes go through this manager. A little more work but way less messy.
Any class is able to retrieve the state for any other controller and change it. This is the purpose of some controllers (eg: choosing a video from youtube happens on a dedicated controller). But usually is just one class getting a state to push the next controller with initWithState:. The pushed controller then applies the state to its GUI in viewDidLoad or changes this state object passed from the previous class.
The StateManager keeps a dictionary of all the state objects. I keep the state object graph light, eg: I store a reference to a image, but not the image itself. The real beef of the application is in Core Data, I only use all this to handle the GUI state. The StateManager listens for the application resign event and saves the state dictionary to disk using NSCoding. The state object ivars are always nil or some meaningful value, no dangling pointers.
I'm working on my 2nd iPhone app and this seems to be working, but I wonder too how other people does it. Any input is welcome.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to avoid create one thread per room (group of players) I have made a game (is still in Beta, need improvements, and other things), and I would like to know if exists a better approach of what I have done in my game servers. (Programmed on C#)
The process to play a game is something like this:
Client application (player) → connect to lobby server → check for an available room with the game he likes to play → the lobby answer the request and point the player to right game server (all using "raw" TCP/sockets).
Each game server automatically start the game when exists at least 4 players in the room (multiple rooms are possible) and a maximum of 12. Each room is launched in a different thread, I mean, I create one thread per room (4-12 players), so if I have 1.200 (many more can be expected by game server) then will be at least 100 threads (even more depending of how many players are really in each room).
The main thread (and is work) plus all the threads created will be consuming all resources in my server... so, I was wondering if anybody can suggest a better idea or approach?
Keep in mine that all the connections are asynchronous, except in the room, I mean, in the room the server must wait for the move of one player (like a Ludo game or a bet) to let the next player (in the room) do the same. In fact, the buttons to make a move are enabled only to the player that is turn to move on. For that reason the transmission in place is synchronous and when somebody move the rest receive their respective notifications.
A: If you can wait on multiple sockets in the same thread (that I don't know and it's probably OS-specific) and you can unambiguously associate incoming data with a particular socket (this you should be able to, I think), then you can service all rooms (or just a few) sequentially in the same thread and thus save on per-thread data structures in the OS and the per-thread stack. You will likely need to implement some kind of a state machine to achieve that and rearchitect your data structures.
A: Coming from a MUD development background, the usual process for this kind of thing is to work on a "heartbeat" model:
*
*You have a timer thread, which fires a heartbeat event/message at regular intervals.
*With each heartbeat, a subscribed reader-thread checks all the connected sockets to see if they have any data to read. If so, the commands (button presses, etc) can be put in a queue (along with an indicator of which user, room, etc) to be read by the main game processor.
*Game processor simply processes messages from the incoming queue, and produces responses (which can be put on an outgoing queue for delivery, if you fancy it).
This is how I've always done it when writing chat servers, talkers, and MUDs, and sounds like it could be a good fit for your requirements too.
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.