text
stringlengths 8
267k
| meta
dict |
---|---|
Q: How to add a css class to a z3c.form button I want to add the css class allowMultiSubmit to a zrc.form button to avoid multi-submit alert. The button is defined like this:
from z3c.form import form
from plone.app.z3cform.layout import wrap_form
class MyForm(form.Form):
...
@button.buttonAndHandler(_(u"Search"))
def handleSearch(self, action):
...
MyWrappedFormView = wrap_form(MyForm)
The result that I want to achieve is this:
<input id="form-buttons-search"
class="submit-widget button-field allowMultiSubmit"
type="submit"
value="Search"
name="form.buttons.search">
There must be an easy way but I can't figure out how.
A: You can override the updateActions method of your z3c.form class and use the addClass method to add a css class to your button:
from z3c.form import form
from plone.app.z3cform.layout import wrap_form
class MyForm(form.Form):
...
@button.buttonAndHandler(_(u"Search"))
def handleSearch(self, action):
...
def updateActions(self):
super(MyForm, self).updateActions()
self.actions['submit'].addClass("allowMultiSubmit")
MyWrappedFormView = wrap_form(MyForm)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Google authentication without user I've a device running Android and display web site that show photos from PicasaWeb.
In order to show the photos the app must auth to google accounts.
Until now I use 'remember me' feature but that's not stable enough.
Is there a way to auth to google account using stored user name and password?
Is there completely other way like using client key or something to pull PicasaWeb album info?
Thank you,
Ido
A: There is a new Google API Java client JAR that works on Android and integrates with the account system. Here is a sample Picasa Android app that uses it. Here is more information on using the JAR in general on Android. Perhaps this will help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create 'groups' that users can join, what would be a good approach? I want to build "groups" that users can join,
The flow of steps and things needed is in my head but the code to build this lacks some bit since I'm still learning rails. I would like to ask some advice on your ideas best practice of what would be needed to accomplish below:
*
*You can create a group with a name 'test'
*You automatically join the group test, other users can join to
*If want to see a list of the users joined my group 'test'
Im thinking of creating a model sessions like
groups|name|
But then how could I store the multiple users that are in this session?
Should I make an array of the user_id's for example and make an extra column like
groups|name|user_ids ?
What would be best practice and what rails (3) methods could I use to get a very rough version of the above functionality up and running ?
A: From what I understand this is a many to many relationship. So you would have 3 models :
class User < AR
has_many :memberships
has_many :groups, :through => :memberships
end
class Membership < AR
belongs_to :user
belongs_to :group
end
class Group < AR
has_many :memberships
has_many :users, :through => :memberships
end
and to know what users belong to a group :
@group = Group.find_by_name("test")
@users_group = @group.users
Update
to ensure the user creating the group also belongs to it :
# in group_controller.rb
def create
@group = Group.new(params[:group])
@group.users << current_user
if @group.save
# ... etc
end
end
of course the current_user should exist/be logged in with the usual before_filter (if I remember correctly its authenticate! with devise)
A: Sorry i'm creating a new thread, but I am unable to comment as of my new status right now.
@charlysisto your answer for this question involves a User, Membership, and Group class. I understand the need of User and Group, but I am confused to why we would need a Membership class. If anything doesn't it make more sense to have a Groups class with Group?
class User < AR
belongs_to :group
belongs_to :groups, :through => :group
end
class Groups < AR
has_many :groups
has_many :users, :through => :group
end
class Group < AR
has_many :users
belongs_to :groups
end
What do you think?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can we use jquery $.post() for using muliple urls in it var js={"studentId":$(this).val()};
$.post(url+"admin/course/getformadmissionfees",js,function(data){
$("#student").val(data.admissionFee);
$("#studentform").val(data.formFee);
My question can i include different url 1
url+"admin/course/getformadmissionfees"
and url 2
url+"admin/course/getformadmissionfees"
url+"admin/course/getformadmission"
in one $.post
A: No. It is only one HTTP call. You can however roll this up into reusable bites.
A: No you can't, because each $.post handles only one request.
You can, however, design your server-side script to accept more parameters, eg:
admin/course/getformadmission/getformadmissionfees
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cascade Grouping sql rows into Xml nodes I have the following rows:
ID|Customer | Part Number | Part Number Price | Hardware ID | Hardware Value
------------------------------------------------------------------------------
1 | John | 15 | 10 | 1 | 1000
2 | John | 16 | 15 | 2 | 500
The output i'm trying to get in SQL Server is the following:
<Order>
<Customer>John</Customer>
<PartNumbers>
<PartNumber>15</PartNumber><PartNumberPrice>10</PartNumberPrice>
<PartNumber>16</PartNumber><PartNumberPrice>15</PartNumberPrice>
</PartNumbers>
<Hardware>
<HardwareId>1</HardwareId><HardwareValue>1000</HardwareValue>
<HardwareId>1</HardwareId><HardwareValue>500</HardwareValue>
</Hardware>
</Orders>
Any idea how to solve this one?
Thanks!
A: This may look a little funny with the self joins but that is only because your tables are not properly normalized. You might want to consider column names without spaces as well.
SELECT Customer as Customer,
(SELECT DISTINCT o.[Part Number] partNumber,o.[Part Number Price] PartNumberPrice
FROM yTable o
where t.id = o.id
FOR XML AUTO, TYPE),
(SELECT DISTINCT x.[Hardware ID] hardwareid,x.[Hardware Value] hardwarevalue
FROM yTable x
where t.id = x.id
FOR XML AUTO, TYPE)
FROM yTable t
FOR XML AUTO, TYPE
A: declare @T table
(
ID int,
Customer varchar(10),
[Part Number] int,
[Part Number Price] int,
[Hardware ID] int,
[Hardware Value] int
)
insert into @T values
(1, 'John', 15, 10, 1, 1000),
(2, 'John', 16, 15, 2, 500)
select T1.Customer as Customer,
(select T2.[Part Number] as PartNumber,
T2.[Part Number Price] as PartNumberPrice
from @T as T2
where T1.Customer = T2.Customer
for xml path(''), root('PartNumbers'), type),
(select T2.[Hardware ID] as HardwareId,
T2.[Hardware Value] as HardwareValue
from @T as T2
where T1.Customer = T2.Customer
for xml path(''), root('Hardware'), type)
from @T as T1
group by T1.Customer
for xml path(''), root('Order')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iPhone:Store & Retrieve NSMutableArray object appDelegate.categoryData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, @"name",image ,@"image", nil];
[appDelegate.categories addObject:appDelegate.categoryData];
NSLog(@"Category Data:--->%@",appDelegate.categories);
I am successfully added object mutabledictionary into mutuablearray but I want to store that array and retrieve when application is launched so please give me idea to develop this functionality.
Thanks in advance.
A: //you can save array in NSUserDefaults like below
if ([[NSUserDefaults standardUserDefaults] valueForKey:@"detail"]==nil)
{
NSMutableDictionary *dic_detail = [NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, @"name",image ,@"image", nil];
NSMutableArray *ary_detail = [[NSMutableArray alloc] init];
[ary_detail addObject:dic_detail];
[[NSUserDefaults standardUserDefaults] setObject:ary_detail forKey:@"detail"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
//if you want read that array you can read like below in your app
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"detail"]];
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"applicationDidEnterBackground = %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"detail"]);
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
NSLog(@"applicationWillEnterForeground = %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"detail"]);
}
in my log its printing like this
applicationDidEnterBackground = (
{
image = img1;
name = cat1;
}
applicationWillEnterForeground = (
{
image = img1;
name = cat1;
}
A: Perhaps something like this:
NSMutableArray * array = [NSMutableArray array];
appDelegate.categoryData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, @"name",
image ,@"image",
array, @"array", nil];
A: Something like:
On Application launch:
[[NSUserDefaults standardUserDefaults] registerDefaults:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSArray new], @"StoredArray", nil]];
In your class that "owns" control of the array:
- (void)setArray:(NSMutableArray *)array {
[[NSUserDefaults standardUserDefaults] setObject:array forKey:@"StoredArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSArray*)array {
return [[[NSUserDefaults standardUserDefaults] arrayForKey:@"StoredArray"] mutableCopy];
}
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cursor not incrementing updating row with start value I'm very new to SQL Server. I'm using a cursor to populate a table with ids; I just discovered cursors today. The code is running but it is populating each row with the start value.
SET NOCOUNT ON
DECLARE @Irow int
declare @cheese int;
set @cheese = (select (max(balanceid) + 1) from balancetbl)
DECLARE aurum CURSOR FOR
SELECT @Irow
FROM aurumaugupload
OPEN aurum
FETCH aurum INTO @Irow
WHILE @@Fetch_Status = 0
BEGIN
update aurumaugupload set balanceid = @cheese
set @cheese = @cheese + 1;
FETCH aurum INTO @Irow
END
CLOSE aurum
DEALLOCATE aurum
RETURN
I think it's a really basic error but I can't see it due to my inexperience.
UPDATE: thanks guys for your prompts answers. I got it working after nonnb's help. Here's the final code:
SET NOCOUNT ON
DECLARE @acc int
declare @start int;
set @start = (select (max(balanceid) + 1) from balancetbl)
DECLARE aurum CURSOR FOR
SELECT accountid
FROM aurumaugupload
OPEN aurum
FETCH aurum INTO @acc
WHILE @@Fetch_Status = 0
BEGIN
update aurumaugupload set balanceid = @start where accountid = @acc
set @start = @start + 1;
FETCH aurum INTO @acc
END
CLOSE aurum
DEALLOCATE aurum
RETURN
A: Your update statement doesn't have a where clause, so you are updating every row each time.
A: There are at least 2 bugs here:
Bug 1
DECLARE aurum CURSOR FOR
SELECT @Irow
FROM aurumaugupload
will select the same (unitialised) constant for every row of aurumaugupload
You need something like
SELECT Irow
FROM aurumaugupload
Bug 2 - You are updating all rows within the cursor. You need a where
update aurumaugupload set balanceid = @cheese
where IRow = @IRow;
set @cheese = @cheese + 1
A: Try this solution (if the sorting/update order doesn't matter):
SET NOCOUNT ON
DECLARE @Irow int
DECLARE @cheese int;
SET @cheese = (SELECT (MAX(balanceid) ) FROM balancetbl)
UPDATE aurumaugupload
set @cheese = balanceid = @cheese+1;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's difference between escape_string and real_escape_string? I'm working on dreamviewer. When i'm trying to write basic syntax it usually autocompletes.
As you see it offers 2 variants for "escape": real_escape_string and escape_string. I wonder, Is there any difference between them?
A: escape_string is an alias to real_escape_string, so they're identical.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Send Request For Web Service And Important Delegate Methods For XML Parsing I want to send request to service and in reply i am getting xml data.
So, please tell me how can i send request to the web-server with check of internet connection and also let me know the important delegate methods for xml parsing.
A: First You Also Need To get The Reachability.h and Reachability.m File
*You Can get Reachability File From here :-- *
http://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
Also Need To import .h file in your file in which you want to check internet connection
Define below variables in your .h file
NSMutableData *urlData;
NSMutableString *currentElementValue;
Also Define the Property of NSMutableString
Below is the code for urlConnection
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert Title"
message:@"Internet connection not currently available."
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:@"Ok", nil];
[alert show];
[alert release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
return;
}
NSString *post = [NSString stringWithFormat:@""];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"Your Information Which You Want To Pass"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
urlData=[[NSMutableData alloc] init];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
For XML Parsing Below Important Methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[urlData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[urlData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
xmlParser = [[NSXMLParser alloc] initWithData:urlData];
[xmlParser setDelegate:self];
[xmlParser parse];
[urlData release];
}
#pragma mark -
#pragma mark XML Parsing Delegate Methods
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSCharacterSet *charsToTrim = [NSCharacterSet whitespaceAndNewlineCharacterSet];
string = [string stringByTrimmingCharactersInSet:charsToTrim];
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];
//NSLog(@"Current Element Value :- '%@'",currentElementValue);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
[currentElementValue release];
currentElementValue = nil;
}
You Can also abort the parsing by Below Line
[xmlParser abortParsing];
A: this question have already asked you should try atleast first by yourself well,
here u go for the complete solution:
to check internet connection
hope will help u!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need Removable comments in this textarea Hi I need to add some content which would be clear on click in the given below textarea.
Not able to find the answer, please help me
<tr><td><?php echo tep_draw_textarea_field('comments', 'soft', '60', '5'); ?></td></tr>
A: If I understand you properly, you want to display some text in your textarea, which will disappear when user moves focus to that textarea.
If you're using html5 it will be a simple task - just add a placeholder attribute to your textarea. I do not know what kind of php sript/framework are you using, but it should look like this:
<textarea placeholder="Click me to type something"></textarea>
If not, you should use javascript to achieve this result. There are lots of available solutions, for example:
jQuery Placeholder
EDIT: I checked how the tep_draw_textarea_field function works, for html5 code you should use:
<?php echo tep_draw_textarea_field('comments', 'soft', '60', '5', '', 'placeholder="Click me"'); ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it a convention to prefix private classes with underscores? I have seen code in which functions/constants are prefixed with underscores.
My understanding is that this indicates that they are not to be used directly.
Can I do this with classes ?
class _Foo(object):
pass
class __Bar(object):
pass
A: Yes; the single underscore usage is endorsed by PEP8 for internal-use classes.
I don't believe the double underscore usage will have any real effect most of the time, since it's used to active name mangling for class attributes, and generally a class isn't an attribute of another class (granted, it can be, in which case Python will happily mangle the name for you.)
A: You can use a single underscore as the first character in any variable, but it is carries the implied meaning, "Do not use outside of the class/module unless you really know what you're doing" (eg. intended protected/internal) and it will not import if you use from <module> import *.
Using a double underscore is something you should never do outside of a class as it could mess with name mangling otherwise (and by "could", I mean, "caused me a big headache this past week because I did not realize that it does").
A: Yes, and this is not only a convention. When you import * from this module, names starting with underscore will not be imported.
A: Better only use one _. This indicates that a name is private within a module.
It is not imported with the catch-all from <module> import *, and it has some other features such as "preferred destruction".
From here:
If __all__ is not defined, the set of public names includes all names
found in the module’s namespace which do not begin with an underscore
character ('_').
From here:
Starting with version 1.5, Python guarantees that globals whose name begins with a
single underscore are deleted from their module before other globals are deleted.
Double-underscore starting class members are name-mangled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: PHP & mySQL - ë written as ë
Possible Duplicate:
PHP messing with HTML Charset Encoding
We've come across special characters being transformed.
What is causing this? How can we fix it?
For example:
ë becomes ë
Thank you.
A: Thats a utf-8 character and you can parse it through utf8_encode() and utf8_decode() in PHP
A: Charset can be set at numerous places.
*
*table charset
*field charset
*PHP-MySQL connection charset
*Apache default charset
*and in HTML metainfo
Make sure you use UTF-8 everywhere, and don't forget to setup the connection properly before the first query:
mysql_query("SET NAMES 'utf8'");
A: Make sure you are setting your charset in HTML document and with PHP header's function.
Also, you could try to make the first query in MySQL to be SET NAMES=UTF8 (SET NAMES utf8 in MySQL?)
A: If this is the output of a PHP script, I guess you may consider mb_internal_encoding() function.
Or you can fix that by HTML encoding meta tag. Like <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> inside <head>...</head>.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Binding a single value within a for comprehension The Learn You a Haskell tutorial has an example of using a let binder in a list comprehension:
calcBmis xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2, bmi >= 25.0]
The function takes a list of height/weight pairs, and returns a list of the corresponding body-mass indices that exceed some limit, eg:
ghci> calcBmis [(70, 1.85), (50, 2.00), (130, 1.62)]
[49.53513183965858]
What's interesting to me here is that the value bmi that is bound within the comprehension can be used both in a guard and in the resulting expression. The only way I know how to do something similar in Scala is to write:
def calcBmis(xs : Seq[(Double,Double)]) =
for((w,h) <- xs ; bmi <- Some(w / (h*h)) if bmi >= 25.0) yield bmi
Having to wrap my value in a Some here feels wrong. Anyone knows of a better way?
A: Yes, there is such syntax.
def calcBmis(xs : Seq[(Double,Double)]) =
for((w,h) <- xs ; bmi = w / (h*h); if bmi >= 25.0) yield bmi
One-liner alternative (but not comprehension):
calcBmis.map(wh => wh._1/(wh._2*wh._2)).filter(_>=25.0)
A: I've just copied om-nom-nom's answer to show how you can lay it out using curly braces without the semicolons; it's a bit clearer this way
def calcBmis(xs : Seq[(Double,Double)]) = for { (w,h) <- xs
bmi = w / (h*h)
if bmi >= 25.0 } yield bmi
and instead of using tuples, I'd use a case expression (again, requires curly braces)
xs map {case (w, h) => w / (h * h)} filter {_ >= 25.0}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Android Market says app incompatible with SG2 Are there any known issues about Samsungs SG2 (2.3.4) concerning the compatibility of Apps. Many potential users of our app with a SG2 report that the Android Webstore thinks the app is not compatible and that the app is not visible on the Android Market App. Whereas the same users are able to install and use the app without any problems if they download the app from Android Pit.
Edit: I have not set a maximum SDK Version. Min SDK-version is 7. According to the developer console there are already some users with SGS2.
Edit2: Here are some parts of the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.app.full" android:installLocation="auto"
android:versionName="1.1" android:versionCode="1">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:name="myAppPlaceholderName">
<!-- Activities left out -->
<receiver android:name="my.app.OnebyOneWidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/one_by_one_widget_info" />
</receiver>
<supports-screens android:anyDensity="true"
android:largeScreens="true" android:smallScreens="true"
android:normalScreens="true" android:xlargeScreens="false" android:resizeable="true" />
</application>
</manifest>
I am also using the deprecated copy protection of androidmarket.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Spinner Error : android.view.WindowManager$BadTokenException: Unable to add window I want to set the spinner value using String[] or ArrayList.
I have done spinner in other activity working fine.In this activity inside the Tab acivityGroup another Tab activity.
My problem is setting values into spinner. Spinner is displaying correctly Thay means when load the activity, that is working fine but when I click On spinner its give error:
Error is :
09-30 16:11:37.693: ERROR/AndroidRuntime(699): FATAL EXCEPTION: main
09-30 16:11:37.693: ERROR/AndroidRuntime(699): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@407f4de8 is not valid; is your activity running?
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.view.ViewRoot.setView(ViewRoot.java:527)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.view.Window$LocalWindowManager.addView(Window.java:424)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.app.Dialog.show(Dialog.java:241)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.app.AlertDialog$Builder.show(AlertDialog.java:802)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.widget.Spinner.performClick(Spinner.java:260)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.view.View$PerformClick.run(View.java:9080)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.os.Handler.handleCallback(Handler.java:587)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.os.Handler.dispatchMessage(Handler.java:92)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.os.Looper.loop(Looper.java:123)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at android.app.ActivityThread.main(ActivityThread.java:3683)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at java.lang.reflect.Method.invokeNative(Native Method)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at java.lang.reflect.Method.invoke(Method.java:507)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-30 16:11:37.693: ERROR/AndroidRuntime(699): at dalvik.system.NativeStart.main(Native Method)
This is my code :
View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.line_discount, null);
this.setContentView(viewToLoad);
ArrayList<String> productList = new ArrayList<String>();
int size = products.size()+1;
String[] proList = new String[size];
proList[0] = "---Select----";
for(int i = 1; i< size ;i++){
productList.add(products.get(i-1).getDescription());
proList[i] = products.get(i-1).getDescription();
}
sp = (Spinner)findViewById(R.id.spProList);
ArrayAdapter<String> adapter = new ArrayAdapter<String> (LineDiscountActivity.this, android.R.layout.simple_spinner_item, proList);
sp.setAdapter(adapter);
This is my image:
Problem in TabActivity.Because I have run this part Within the TabActivityGroup. Its was working.When I run this inside the Tab Activity within TabActivityGroup, then its a problem.
I have TabActivtyGroup &Within that normal TabActivity.
How can I do in this situation?
A: It's obvious from the error message that the problem is with context used for creating the spinner. Try this
viewToLoad = LayoutInflater.from(this).inflate(R.layout.line_discount, null);
Or:
viewToLoad = getLayoutInflater().inflate(R.layout.line_discount, null);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, proList);
sp.setAdapter(adapter);
A: I think you have context problem.Try to get context using below method
you can create a new activity and set its theme to dialog theme so that when you start your activity it will display as dialog.
For more information about dialog see below post
Click here
EDIT2
I found a solution for badTokenExcaption
In your activity's onCreate() method replace the line setContentView(R.layout.XXXXX) by
View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.XXXXX, null);
this.setContentView(viewToLoad);
and replace the spinner code by following lines
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.medicine_types, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spDosageType.setAdapter(adapter);
A: When you create your ArrayAdapter you should pass the Context of your ActivityGroup not the Context of your current Activity.
Here is an example of how I get it:
public class MyActivityGroup extends ActivityGroup{
pulbic static MyActivityGroup sGroup;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sGroup=this;
//...
}
}
// Tab Implementation
//.....
ArrayAdapter<String> adapter = new ArrayAdapter<String> (
MyActivityGroup.sGroup, android.R.layout.simple_spinner_item, proList);
A: I tried with code.Its working fine:
View viewToLoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewToLoad = LayoutInflater.from(getDialogContext(this)).inflate(R.layout.header_discount, null);
this.setContentView(viewToLoad);
ArrayAdapter<String> adapter = new ArrayAdapter<String> (viewToLoad.getContext(), android.R.layout.simple_spinner_item, proList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
headerDisProdCode.setAdapter(adapter);
headerDisProdCode.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,int arg2, long arg3) {
seletcedProductName = parent.getSelectedItem().toString();
seletcedProductCode = (products.get((int) headerDisProdCode.getSelectedItemId())).getProductCode();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
ArrayAdapter context I gave like : viewToLoad.getContext() viewToLoad is the inflate
A: I had this problem as well, but with Fragments, when adding a fragment to a view, and the answer for me was to pass in getApplicationContext(), but I had to do it through a separate method after instantiating the fragment, since it was requiring the use of a Bundle.
I also had to do the following when inflating the view, using the context passed in above:
View v = inflater.from(context).inflate(R.layout.layout_name, ViewGroup container, T/F);
rather than just:
View v = inflater.from(context).inflate(R.layout.layout_name, ViewGroup container, T/F);
Hope this helps somebody struggling with Fragments.
A: viewToLoad = getLayoutInflater().inflate(R.layout.line_discount, null);
(viewToLoad.getContext(), android.R.layout.simple_spinner_item, proList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
This did the job for me
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What kind of project type for TableViewSuite App I am moving from theory to some practice. I've downloaded from Apple site a couple of sample codes. The first app is TableViewSuite from
https://developer.apple.com/library/ios/#samplecode/TableViewSuite/Introduction/Intro.html
Looks nice and attractive. The most thing I like is mastering .nib file programmatically. I tried to repeat this app, but oh Dear, what kind of project to choose?
*
*Navigation-Based Application
*View-Based Application
or
*
*Window-Based Application?
First I tried Window-Based Application cos it promises
This template provides a starting point for any application. It provides just an application delegate and a window.
Sounds good. Just window and delegate, but when I started to write code I've faced such dilemma. In Apple's code, the first thing I have to implement for exposing nib file with table view is
- (void)applicationDidFinishLaunching:(UIApplication *)application {
/*
Create and configure the navigation and view controllers.
*/
RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStylePlain];
// Retrieve the array of known time zone names, then sort the array and pass it to the root view controller.
NSArray *timeZones = [NSTimeZone knownTimeZoneNames];
rootViewController.timeZoneNames = [timeZones sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
self.navigationController = aNavigationController;
[aNavigationController release];
[rootViewController release];
// Configure and display the window.
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}
This method is clear for me. I mean it's clear for me what it does. In my app this method is implemented in quite different way.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
It returns BOOL instead of returning void and doesn't get (UIApplication *)application parameter and I can't initialize RootViewController with style.
So, what kind of project should I choose? Please help me with your advice. Thanx in advance.
A: As far as what type of project to use, I think choosing a Window based application is a good starting point. As you said it's a window and a delegate and those are pretty much the essentials.
This method:
*
*(void)applicationDidFinishLaunching:(UIApplication *)application
is actually used in older versions of iOS. You should be using:
*
*(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
This method basically does the same thing except it takes two parameters instead of 1. The first is the UIApplication (just like the first method). The 2nd parameter is a dictionary the tells you why the application was launched (opened from springboard, opened as a result of acting on a push notification, etc).
As for the return value, you probably want to return NO when just starting out. If your app is going to handle URL resources then you will probably want to re-implement it so that it looks inside the options dictionary to see if the app is launching because the user is trying to open a file or resource that your application claims to support (in which case you would return YES).
There should be no reason the code you posted above cannot be used. You just need to add a return value. There shouldn't be anything stopping you from initializing your UINavigationController or your RootViewController (which I assume is a subclass of UITableView).
A: Hey nathan both these method does the same.
And if you are missing application instance then you can create it using [UIApplication sharedApplication] as this is a singleton and will return the same instance every time.
If you are new to iPhone then go for View Based first then go for Navigation based app and then finally for window based application.
And about the two method above - (void)applicationDidFinishLaunching:(UIApplication *)application method is used in earlier versions of iOS to initialize the application and prepare it to run. In iOS 3.0 and later, you should use the - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions instead.
These are the lines straight from apple's docs you can check here
The difference between these two method is that when your applicaion is launched due to local/push notification the the method - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions is called and a dictionary is passed as launch option. So use this one instead of other.
And about the above downloaded code it is a navigation based application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SharePoint 2007 Calculator Does anyone know how to create a simple calculator using CEWPs or Form Web Parts on SharePoint 2007? Basically all I need is two fields for input and a submit button which uses the 2 input fields in a function and then gives the answer.
Sounds simple but everything I've tried (using html and javascript) produces an error in SharePoint, even if it works in a normal html page!!
Thanks in advance,
Karl
<HTML>
<HEAD>
<TITLE>Saves Calculator</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function CalculateSaves(Atext, Btext, form)
{
var A = parseFloat(Atext);
var B = parseFloat(Btext);
form.Answer.value = ((((A * B)/60)/60)/7.33)/19;
}
function ClearForm(form)
{
form.input_A.value = "";
form.input_B.value = "";
form.Answer.value = "";
}
</SCRIPT>
</HEAD>
<BODY>
<P><FONT SIZE="+2">Saves Calculator</FONT></P>
<FORM NAME="Calculator" METHOD="post">
<P>Time in Seconds: <INPUT TYPE=TEXT VALUE="30" NAME="input_A" SIZE=10> Activities: <INPUT TYPE=TEXT NAME="input_B" SIZE=10></P>
<P><INPUT TYPE="button" VALUE="Calculate Saves" name="AddButton" onClick="CalculateSaves(this.form.input_A.value, this.form.input_B.value, this.form)"> <INPUT TYPE="button" VALUE="Reset" name="ClearButton" onClick="ClearForm(this.form)"></P>
<P>Saves = <INPUT TYPE=TEXT NAME="Answer" SIZE=12></P>
</FORM>
</BODY>
</HTML>
A: I had the same problem.
*
*Move the html and javascript to a notepad file, save as .html
*Upload to document library
*Add a Page Viewer webpart to your page, and link it to the html file saved within the library
This should now work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: quotes in sql query how can you add quotes in a sql query if the field names includes "-" or other charactors or if the field has a reserved name like "type" or others
SELECT `enclosure.id`, `enclosure.time`, `enclosure.note`
FROM tbl.enclosure LEFT JOIN tbl.book ON book.enc_id=enclosure.id
WHERE `book.book_id`='277' ORDER BY enclosure.time DESC, enc_id_ DESC
error
#1054 - Unknown column 'enclosure.id' in 'field list'
A: I'm not sure if I got you correct, but I think you should replace
`book.bookid`
with
`book`.`bookid`
.
A: you have something wrong in query..it must be like below ( you did not set alias for table )
SELECT `enclosure`.id`, `enclosure`.time`, `enclosure`.note`
FROM tbl_enclosure enclosure
LEFT JOIN tbl_book book ON `book`.`enc_id`=`enclosure`.`id`
WHERE `book`.book_id`='277'
ORDER BY `enclosure`.`time` DESC, `enclosure`.`enc_id` DESC
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How is fork() working when children fork? I have executed a block of code. And it is as shown below:
#include<stdio.h>
main() {
int i=0;
fork();
printf("The value of i is:%d\n",++i);
fork();
printf("The value of j is:%d\n",++i);
fork();
wait();
}
And I got following output:
The value of i is:1
The value of j is:2
The value of i is:1
The value of j is:2
The value of j is:2
pckoders@ubuntu:~$ The value of j is:2
Can anyone explain to me what role fork() and wait() functions play here?
A: The program generates a tree of processes. At every fork, this tree branches in two. If you grab a piece of paper, it's not very hard to draw this tree; the only thing that's hard is getting the i values right due to your use of prefix ++. If you let each of the process sleep for a few seconds at the end, you can also observe the tree using the pstree program.
Each one of the processes then runs the wait system call, which waits for any one of its child processes (child nodes in the process tree) to finish.
A: fork() call is a literally fork. After it's finished you are having 2 exact processes with exact stack and all descriptors are referring to same objects. You can distinguish them by a return value. For child process fork() returns 0, for parent - child's process id.
so
main() {
int i=0;
fork();
// at this point you are having 2 processes. stdout and stdin are basically just dupplicates.
// (P)
// / \
// (P) (C)
// prints1 prints 1
printf("The value of i is:%d\n",++i); // so 2 processes with print 1
fork();
// now you are having 4 processes( both parent and children forked)
// (P)
// / \
// / \
// (P) (C)
// / \ / \
// (PP) (PC) (CP) (CC)
// prints 2 prints 2 prints 2 prints 2
printf("The value of j is:%d\n",++i);
fork();
// now 4 processes are forking. now you have 8 processes
// (P)
// / \
// / \
// / \
// (P) (C)
// / \ / \
// / \ / \
// (PP) (PC) (CP) (CC)
// / \ / \ / \ / \
// (PPP) (PPC) (PCP) (PCC) (CPP) (CPC) (CCP) (CCC)
wait();
}
A: After the first fork() there were two processes (the current and it's exact copy, the child), which both printed 1.
Each of these two processes duplicated itself with the second fork() call, and there were 4 processes, each of them printed 2.
Their output comes in random order, as it always does with parallel execution.
A: The Forking processes creates Children in a tree-like manner.Consider each fork to be the different layers of a Binary Tree.When you dont issue a fork() u have a process tree of only a root node.When u issue a single fork() then u have a binary tree with two levels now , the first level will the contain the parent process , the second level will contain two processes - the parent and the child process.
When u want to find out the number of processes u have at hand just proceed building the binary/process tree and see how many nodes are there at the last level, the last level is nothing but the current state of the process/tree.Wait function makes your parent wait for the child process to finish executing.In applications where u do not want a zombie process you need to issue a wait or else these zombie processes will keep hogging the system... link.
Remember that wait is also useful when you always want the parent to finish after the child . Forking doesnt always give the same output , the order is jumbled , thus to get the same output always , use wait(). To wait on a particular child process , use wait(pid) where the pid is the pid of a specific child and that pid can be obtained by getpid inside the child process's space.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: A block changes its ID when moved between regions? Under Drupal 6 I have a custom block, which I have named and placed into a custom, right-hand sidebar region. This block's ID (which I have discovered from block.tpl.php, from the $block_id helper variable) is 7.
I am overriding the output of this block as it displays a View and I need to change the markup; I have a preprocess function in template.php called myTheme_preprocess_block() which searches for the block's unique ID thus:
myTheme_preprocess_block(&$vars) {
$this_block_id = $vars['id']; /* region-independent ID (for reliability) */
$vars['template_files'] = array();
switch ($this_block_id) {
case 7:
$vars['template_files'][] = 'block-my-override-template';
break;
default:
/* take no action */
}
}
Now, I've moved this block from the right-hand sidebar region (which is a custom region and not the default one which comes with Garland) to a footer region, which also has a custom name. And suddenly, my overriding template file, block-my-override-template.tpl.php, is no longer referenced.
I do a little digging and output the unique block ID from within block.tpl.php, and magically this block has changed its ID from 7 to 13! With a straight face, no less! Returning this block to the right-hand sidebar region also returns the block to ID 7 (and all my code starts working again).
My question is this: How can we uniquely identify a block if its "unique" ID changes when it moves from one region to another?
A: If you are using a View, why don't you instead override the block display of the View instead of mucking around with the actual block?
You could alternatively simply declare your custom block in a module? That should make it easier for you to manage theming aspects of the block.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Silverlight Deep Zoom Server Control? The Silverlight Deep Zoom was one of those cool things that I heard about when it was introduced a few years ago, but I never got around to actually trying it out. But now is the time, and I was so surprised to learn how complicated it apparently is to get the thing working, that I’m worried that I’m missing something here.
As far as I understand, using Silverlight Deep Zoom requires you to
*
*Write an Silverlight app to embed on your site, which is not exactly trivial with no prior Silverlight experience, as you have to implement the various actions (zoom, pan) yourself and include button icons.
*Create the Deep Zoom pyramid files “manually”.
I found plenty of examples on how to do both, but it’s a far cry from sticking a control on your page, set the original image source and height and width, which honestly was all I figured it would require.
So: Before I go ahead and implement my own,
*
*Do you know any component (free or commercial) that wraps the above in a nice way?
*Do you know any alternatives to Silverlight Deep Zoom? JavaScript? HTML5?
*I got this feeling that the technology is considered somewhat outdated today?
A: Quite a few points, will try to cover them all:
*
*Silverlight Deep Zoom requires a Silverlight app...
Yes (hence Silverlight in the name :))
Is that difficult... not really. It is just files copied to the right place on a server.
This example is hosted under a simple WordPress blog and took 10 mins to build
*
*You have to implement the buttons etc...
No You can use the free DeepZoom Composer output out-of-the-box. You only create your own pyramids for more advanced on-the-fly generation.
*
*You need to create a pyramid of files manually...
No (use the DeepZoom composer)
So in answer to your last points:
*
*Do you know any component (free or commercial) that wraps the above
in a nice way?
No need. It is not as difficult as you imagine.
*
*Do you know any alternatives to Silverlight Deep Zoom? JavaScript?
HTML5?
None yet although I am sure something will be invented
*
*I got this feeling that the technology is considered somewhat
outdated today?
Not in my books, but I don't know where you get your information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using window.open within a modalDialog - address bar always visible? (This problem has been observed in IE9)
I am experiencing some problems relating to the display of an address bar when opening a new window from within a modalDialog.
The following sample page illustrates this.
test.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function windowOpen()
{
var sOptions = "width=300,height=300,location=0,menubar=0,toolbar=0,status=0";
window.open("test.html", "", sOptions);
}
function modal()
{
var sOptions = "dialogHeight:300px;dialogWidth:300px;";
window.showModalDialog("test.html", "", sOptions);
}
</script>
</head>
<body>
<a href="javascript:void(0);" onclick="modal()">window.showModalDialog</a><br /><br />
<a href="javascript:void(0);" onclick="windowOpen()">window.open</a>
</body>
</html>
Clicking on the 'window.open' link on the page works as expected and the address bar is hidden. If you click the link again in the resulting new window, it still performs as expected.
If however, you open the page in a modalDialog at any point (using the window.showModalDialog link) and then click on 'window.open' the address bar is visible.
Is there any way of avoiding this behaviour?
Any help would be appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Calculating JMP instruction's address I am trying to hook a function by replacing its beginning with a JMP instruction which should lead to my function. But the problem is that I don't know how to calculate the JMP offset to target the address of my function. Well, I know how to do it if you jump forward in memory (Destination addr - Current addr), but I haven't got any ideas how to determine it when you jump back in memory.
Could somebody help?
A: Just use negative offset to jump backwards.
And remember to account for the size of the JMP instruction. The offset is relative to the end of the JMP instruction and not the beginning. If the current address is where you are about to write the JMP then you need an offet of 5+dest-current since the size of the JMP instruction plus the offset if 5 bytes.
A: This is basic math that you should be able to figure out. :)
If a JMP forward is Destination - Origin, then a JMP backward would be Origin - Destination
Think about it in plain numbers: If you want to JMP forward from 100 to 110, your JMP would be 110 - 100 = 10. If you want to JMP the same amount backward, it would be 100 - 110 = -10.
A: relative jumps are signed, that is, they have positive and negative displacement using the sign bit. absolute jumps are absolute so it doesn't matter. see volumes 2A & 2B of the intel instruction guide.
A: Be sneaky
Make a dummy call to a location above your function
call location1
.location1
call location2
.location2
pop ax
ret
.yourfunction
You now have the address of location2 in ax
add 3 to ax and you have the memory address of your function
A: hello i suggest you use the 'call' statement. The 'call' statement will take care of putting the return pointer on the stack.
the formula to calculate the jump you need to do is: ToAddress - FromAddress - 5
-5 this is because it is the space that the 'call' + offset instruction occupies in memory
pointers in memory are written inversely. if you want to point to memory 0x857830, in memory this value is written 307885
instructions opcode
jmp = 0xE9
call = 0xE8
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: correct MIN, MAX and CASE statements I like to extract MIN and MAX values from the same column. As I am using Group By so I have to use min and max. If I just use the whole column, it gives me error that you have to use aggregate function with Group By
How can I do it
ValueA = MAX(ValueB) + MIN(ValueB)
what will be the correct syntax?
Anyone?
and second question is
How can I use 2 case statement in a situation like this
select
ValueA = Case ValueC
when ValueB then ValueC
else ''
End
Case ValueD
when ValueE is blank then ValueD is also blank
END
From TableA
using 2 case statement like above gives me 2 columns instead, I want 1 column
plus in second case statement I just wrote algorithm of what i want
How can I fix this code?
A: Do you mean this?:
SELECT
MAX(ValueB) + MIN(ValueB) AS ValueA
FROM
tableX
GROUP BY
columnX
A: add column name in select clause by which u want grouping. I think it works and not give error
select max(valueB)+min(ValueB)as valueB,columnX from tbl group by columnX
A: Question 1:
Depends on that group by clause. Please paste the actual code you are using.
If you want each ValueB for each columnX then add it to your group by i.e.
group by columnX, ValueB
Or if you just want each ValueB once. Then
SELECT DISTINCT ValueB from tableX
Question 2:
Quite confusing description. Give example input and output data.
My best guess is you are asking for, if B = C AND E = '' AND D = '' Return C ELSE ''
i.e.
SELECT CASE WHEN B = C AND E = '' AND D = '' THEN C ELSE '' END as A
FROM tableA
A: Do you mean this for the CASE?
SELECT ValueA,
CASE
when ValueB = ValueA THEN ValueC
else ''
End as ValueC,
CASE
when ValueE IS NULL THEN ''
END AS ValueD
It is difficult to understand exactly what you need. Could you please add the data you have (several rows) and what output you expect to get?
Most people do not like images of the data, but that is better than nothing. :-) Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Can't generate subreport in JasperReports from Java code I have some problem with generating a subreport in JasperReports.
I have 2 reports which I made in iReport.
Main report:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="raporcik" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<parameter name="autor" class="java.lang.String"/>
<parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
<defaultValueExpression><![CDATA["C:\\Documents and Settings\\user\\workspace\\Jasper\\report\\"]]></defaultValueExpression>
</parameter>
<field name="name" class="java.lang.String"/>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="79" splitType="Stretch">
<staticText>
<reportElement x="242" y="31" width="115" height="28"/>
<textElement>
<font size="18"/>
</textElement>
<text><![CDATA[Something]]></text>
</staticText>
<textField>
<reportElement x="439" y="59" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$P{autor}]]></textFieldExpression>
</textField>
</band>
</title>
<pageHeader>
<band height="35" splitType="Stretch"/>
</pageHeader>
<detail>
<band height="28" splitType="Stretch"/>
<band height="50">
<subreport>
<reportElement x="46" y="0" width="200" height="50"/>
<connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
<subreportExpression class="java.lang.String"><![CDATA[$P{SUBREPORT_DIR} + "info.jasper"]]></subreportExpression>
</subreport>
</band>
</detail>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
Second Report(subreport):
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="info" language="groovy" pageWidth="555" pageHeight="802" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<field name="name" class="java.lang.String"/>
<background>
<band splitType="Stretch"/>
</background>
<detail>
<band height="52" splitType="Stretch">
<textField>
<reportElement x="37" y="12" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{name}]]></textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>
And Java Code:
Code in Main method:
JasperDesign jsp = JRXmlLoader.load("C:/Documents and Settings/user/workspace/Jasper/report/raporcik.jrxml");
JasperCompileManager.compileReportToFile("C:/Documents and Settings/user/workspace/Jasper/report/info.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(jsp);
Map<String, Object> parametros = new HashMap<String, Object>();
parametros.put("autor", "Jasper W.");
parametros.put("SUBREPORT_DIR","C:/Documents and Settings/user/workspace/Jasper/report/");
List lista = new ArrayList();
lista.add(new Name("something1"));
lista.add(new Name("something2"));
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, new JRBeanCollectionDataSource(lista));
JRExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File("C:/Documents and Settings/user/workspace/Jasper/report/hello.pdf"));
exporter.exportReport();
And Name Class:
public class Name {
String name;
public Name(){
}
public Name(String _name){
this.name = _name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I don't know what I am doing wrong, but I can't generate subreport. It is always empty. I have the same problem when subreport contains only static text.
A: I tried for a few days to get sub-reports to work, and even though I followed the doc exactly, it didn't work.
IMHO "sub-reports" don't actually work.
A: Your subreport is empty probably because you have no datasource or query in your subreports's or main report's JRXML. You can find more information in this answer. It has exactly what you need to use your subreport with only static fields.
So your problem is not exactly with subreports, but with the way the Jasper Reports environment generates reports.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ajax.BeginForm says action doesn’t exists, however it does I am working with AJAX Helper method in one my applications, things were all good and right but suddenly am facing this strange problem i.e. in view
<% using (Ajax.BeginForm("Feedback", "User", new AjaxOptions { InsertionMode = InsertionMode.InsertBefore, HttpMethod = "POST", OnFailure = "searchFailed", OnSuccess = "feedbackRecorded", LoadingElementId = "ajax-loader-fb", UpdateTargetId = "newsletter", }, new { @id = "feedback" })) { %>
The first parameter to Ajax.BeginForm that is the {action name} is now being marked in red color(I am using Resharper) and says that ‘cannot resolve action ‘ActionName’’, however the Action is present in my controller.
Another strange thing is that on running the app and submitting the form it ends up invoking the Javscript’s "OnSuccess” method as if it has succeeded but in actually nothing happened and it didn’t even get to first line call of the specified controllers action. (This is happening to both AJAX forms in the view)
Does anyone have any ideas about the possible reasons forit to behave this way suddenly?
Thankyou!
I just created a new 'SharedController' controller with the same action in it and now it is recognizing but its is not recognizing in the UserController?
public class SharedController : Controller
{
public ActionResult Feedback()
{
throw new NotImplementedException();
}
}
A: Maven, about ReSharper - it's complaining right, because you use this method overload
public static MvcForm BeginForm(
this AjaxHelper ajaxHelper,
string actionName,
Object routeValues,
AjaxOptions ajaxOptions,
Object htmlAttributes)
where second parameter is routeValues, so ReSharper looks for action 'Feeeback' in current controller.
Obviously, you wanted another overload, with this invocation
<% using (Ajax.BeginForm("Feedback", "User", null, new AjaxOptions { InsertionMode = InsertionMode.InsertBefore, HttpMethod = "POST", OnFailure = "searchFailed", OnSuccess = "feedbackRecorded", LoadingElementId = "ajax-loader-fb", UpdateTargetId = "newsletter", }, new { @id = "feedback" })) { %>
Pay attention to third null argument.
A: The second parameter of Ajax.BeginForm is the controller name.
Try changing the code to:
<% using (Ajax.BeginForm("Feedback", "Shared", ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: According to language change currency of zencart Am working on a zen cart project, I have used Google language converter to change the language of site,
now the project demand is if
"customer is in spanish google shopping and he click on my site product it take him to the product page displayed in euros and spanish without them doing anything".
Now I have some specific question to ask
How can we set the currency according to language, b'cz zen cart didn't provide this?
Is it possible to achieve the same requirement?
Thanks
and if yes Please suggest me the way to do it.
A: As you are not using inbuilt multi-language facility so It's very difficult to get solution.
This can be possible in two different ways.
*
*First of all maintain relation between language and currency. create/add special div where you show price in html <div class="randomPrice">$10.00</div>. By adding special div you will get all instance of price in loaded html. Now on change of language by Google language update all special div with updated currency.
*Use default multi-language facility and maintain relation between language and currency. when user change language update currency session accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to detect if a text-field needs to wrap in JavaScript/dojo? I have a textfield in a grid in which I wish to turn off text wrapping, but display a tooltip with the full text if wrapping is required. So, how could I detect if a field needs to wrap?
I tried to query the field's length, but it was either in em or in px based on if the user resized it. How could I get the wrapping status?
A: An option to detect if the text wraps - create (with jQuery, for instance) an invisible span with the same font settings and white-space: nowrap, set it's text to the field's content and check if the span's width is bigger than the field's width (in pixels, obtained via width())
Working fiddle: http://jsfiddle.net/TR98y/1/
A: Perhaps you can check the height (via scrollHeight) of the text container. It should increase when things start wrapping.
The only other alternative I can think of is setting overflow-x:hidden and then dettecting the overflow somehow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Regarding profile url shorten I am wondering to know about this is it possible or not. If yes then please help me.
I want to change this URL:
http://domain.com/profile/admin
to
http://domain.com/admin
Where admin is username of profile user.
Why I am thinking it is impossible like the URL is already rewritten in .htaccess or somewhere.
A: You provide a little to less context to give a definitive answer but it must certainly be possible. It all depends on how you have setup your code and webserver now and in what degree you are allowed to modify any of them.
A: You can use below snippet in your .htaccess file -
<IfModule mod_rewrite.c>
RewriteEngine on
RedirectMatch 302 ^/$ /admin
RewriteRule ^/profile (.*) $1 [R=301,L]
</IfModule>
This snippet won't work if the URL- http://domain.com/profile/admin is auto-generated in between the application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to show Google Map in a different shape I'm trying to find (without luck so far) any examples of Google Maps that are shown in a shape that is not the standard rectangle.
I know that ultimately the map IS a rectangle, but specifically I'd like examples of how I could show graphics on top of that rectangle to give the illusion that the map borders are a different shape.
To explain further what I mean, imagine a page with a black background with a standard Google Map (rectangle) in the top left. Now imagine placing a DIV over the bottom half of the map, where this DIV contains half a black circle and a transparent background. The purpose would be to give the illusion that the map has a curved bottom edge.
I'd then want to do something similar with the remaining 3 sides so that the map no longer appears like it's in a rectangle.
To explain further still, I'm going to be given a web page template which will have a shape - not a rectangle - into which I'm expected to put a Google Map...
Importantly, I'd still need to be able to 'grab' the map with the mouse and move it about within its 'new shape'.
Any advice would be appreciated - thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reading XML from Javascript, is it reasonably possible? I'm developing a very smooth site that will display products for a company. I'm using jQuery to display the products. Problem is, I don't want to hard-code all of the products in. I want to store all of the products (product, description, price, etc.) in XML. I'm not worried about security because clients wont actually be buying anything directly from site.
With this in mind, what is the best way to load and read the XML file using Javascript/jQuery. I've read some stuff online but it all looks pretty dodgy, especially when it comes to browser support. Is this realistically possible? Should I do this another way? How can I best achieve this?
EDIT
JSON also seems like a decent alternative as well. I just need explanations on how to do it.
Thanks!
A: Storing data as JSON is a cleaner bet and it works a lot more seamlessly with JavaScript.
JQuery's ajax functions have a built in JSON data type that automatically parses if for you.
I would look into JSON at json.org and then start looking at some of the JQuery docs. It's not too complicated.
Really it's just JavaScript objects in string format. You deal with them, after parsing, as normal objects.
A: I agree that it should be easier to use JSON if you are using JavaScript directly.
If you want to use XML, you might be interested in using XQuery or XSLT (which natively support XML, and almost seamlessly (X)HTML) as the scripting language.
A: You might want to look into XML2JSON if you can afford the conversion to take place client-side.
A server-side alternative can be found here since you might want/need to implement a same-domain proxy (also, Caching would be pretty nice, I guess?).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Oracle.OLEDB not visible in 32 bit SSMS 2008 This is my first post on here.
I'm having trouble creating a linked server in SSMS because Oracle is not listed as a provider.
However, in BIDS the Oracle provider is visible. I can connect to my database just fine.
It appears that BIDS is 64 bit and SSMS is 32 bit so I downloaded 32 bit Oracle ODAC but the provider is still not visible.
I'm at my wits end here so any help would be greatly appreciated.
Thanks.
A: Make sure you have a full oracle client installed on the server, with Oracle ODAC 11.2.0.3 you may have to select "Oracle Provider for OLE DB" when installing (i.e. not ticked by default I think.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: asp.net ajax beginrequest I'm creating an asp.net application and I need to get the name of the control who initiated an asynchronous post pack from a beginRequestHandler.
Here is my code:
<script type="text/javascript">
function pageLoad(sender, args) {
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginAjaxRequest);
}
function beginAjaxRequest(sender, args) {
// do work here
}
</script>
A: To get the postbackelement
function BeginRequestHandler(sender, args)
{
var elem = args.get_postBackElement();
alert(args.get_postBackElement().id);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use OpenCV/or any ported library classes in Objective-C First, I apology for this newbie question. I'm new in Objective C and OpenCV
the normal method declaration in Objective-C is like that
Function functionName = [[Function alloc] init];
but when I use OpenCV class it says (for example CvMat) receiver type is not an Objective C class.
or am I suppose to write the code in C++ syntax ?
A: You write the code in C++ syntax. Objective-C is actually a superset of C++ which means that any C++ program is also a valid Objective-C program (well in most cases anyway). Objective-C just adds a whole lot of functionality to what already exists in C++.
When I was developing an openCV app for iOS, here were the main stumbling blocks:
*
*Compiling OpenCV as a static library. It's the only way to use OpenCV in iOS, and is not an easy task if you've never done anything similar before. There are a couple of great blog posts about how to do it, such as this one.
*Armv6 and armv7 - make sure you have static libraries compiled for both (or a universal binary), as iOS runs on both.
*When you're coding, just code as you would for c++. Here's a chunk of example code you can refer to.
// NOTE you SHOULD cvReleaseImage() for the return value when end of the code.
- (IplImage *)CreateIplImageFromUIImage:(UIImage *)image {
// Getting CGImage from UIImage
CGImageRef imageRef = image.CGImage;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Creating temporal IplImage for drawing
IplImage *iplimage = cvCreateImage(
cvSize(image.size.width,image.size.height), IPL_DEPTH_8U, 4
);
// Creating CGContext for temporal IplImage
CGContextRef contextRef = CGBitmapContextCreate(
iplimage->imageData, iplimage->width, iplimage->height,
iplimage->depth, iplimage->widthStep,
colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault
);
// Drawing CGImage to CGContext
CGContextDrawImage(
contextRef,
CGRectMake(0, 0, image.size.width, image.size.height),
imageRef
);
CGContextRelease(contextRef);
CGColorSpaceRelease(colorSpace);
// Creating result IplImage
IplImage *ret = cvCreateImage(cvGetSize(iplimage), IPL_DEPTH_8U, 3);
cvCvtColor(iplimage, ret, CV_RGBA2BGR);
cvReleaseImage(&iplimage);
return ret;
}
A: Yes. You should use special factory functions.
For example CvMat can be created by CvMat* cvCreateMat(int rows, int cols, int type);
For more info use documentation
A: Take a look at this article that shows how to use OpenCV on the iPhone. It provides an OpenCV framework that can be dropped into your own projects and supports video capture too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get date part (dispose of time part) from java.util.Date? I want to compare the date part of two java.util.Date objects. How can I achieve this? I am not looking to comparing the date, month and year separately.
Thanks in advance!
A: The commons-lang DateUtils provide a nice solution for this problem:
watch this
With this you can compare two Date instances in a single line, loosing sight of every part of the Date you want.
Date date1 = new Date(2011, 8, 30, 13, 42, 15);
Date date2 = new Date(2011, 8, 30, 15, 23, 46);
int compareTo = DateUtils.truncatedCompareTo(date1, date2,
Calendar.DAY_OF_MONTH);
In this example the value of compareTo is 0.
A: A Date is just an instant in time. It only really "means" anything in terms of a date when you apply a calendar and time zone to it. As such, you should really be looking at Calendar, if you want to stick within the standard Java API - you can create a Calendar object with the right Date and time zone, then set the time components to 0.
However, it would be nicer to use Joda Time to start with, and its LocalDate type, which more accurately reflects what you're interested in.
A: Use Calendar.set() with Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND to set all those fields to 0.
The answers to this duplicate question will be useful: Resetting the time part of a timestamp in Java
A: Find below a solution which employs Joda Time and supports time zones.
So, you will obtain date and time (into currentDate and currentTime) in the currently configured timezone in the JVM.
Please notice that Joda Time does not support leap seconds. So, you can be some 26 or 27 seconds off the true value. This probably will only be solved in the next 50 years, when the accumulated error will be closer to 1 min and people will start to care about it.
See also: https://en.wikipedia.org/wiki/Leap_second
/**
* This class splits the current date/time (now!) and an informed date/time into their components:
* <lu>
* <li>schedulable: if the informed date/time is in the present (now!) or in future.</li>
* <li>informedDate: the date (only) part of the informed date/time</li>
* <li>informedTime: the time (only) part of the informed date/time</li>
* <li>currentDate: the date (only) part of the current date/time (now!)</li>
* <li>currentTime: the time (only) part of the current date/time (now!)</li>
* </lu>
*/
public class ScheduleDateTime {
public final boolean schedulable;
public final long millis;
public final java.util.Date informedDate;
public final java.util.Date informedTime;
public final java.util.Date currentDate;
public final java.util.Date currentTime;
public ScheduleDateTime(long millis) {
final long now = System.currentTimeMillis();
this.schedulable = (millis > -1L) && (millis >= now);
final TimeZoneUtils tz = new TimeZoneUtils();
final java.util.Date dmillis = new java.util.Date( (millis > -1L) ? millis : now );
final java.time.ZonedDateTime zdtmillis = java.time.ZonedDateTime.ofInstant(dmillis.toInstant(), java.time.ZoneId.systemDefault());
final java.util.Date zdmillis = java.util.Date.from(tz.tzdate(zdtmillis));
final java.util.Date ztmillis = new java.util.Date(tz.tztime(zdtmillis));
final java.util.Date dnow = new java.util.Date(now);
final java.time.ZonedDateTime zdtnow = java.time.ZonedDateTime.ofInstant(dnow.toInstant(), java.time.ZoneId.systemDefault());
final java.util.Date zdnow = java.util.Date.from(tz.tzdate(zdtnow));
final java.util.Date ztnow = new java.util.Date(tz.tztime(zdtnow));
this.millis = millis;
this.informedDate = zdmillis;
this.informedTime = ztmillis;
this.currentDate = zdnow;
this.currentTime = ztnow;
}
}
public class TimeZoneUtils {
public java.time.Instant tzdate() {
final java.time.ZonedDateTime zdtime = java.time.ZonedDateTime.now();
return tzdate(zdtime);
}
public java.time.Instant tzdate(java.time.ZonedDateTime zdtime) {
final java.time.ZonedDateTime zddate = zdtime.truncatedTo(java.time.temporal.ChronoUnit.DAYS);
final java.time.Instant instant = zddate.toInstant();
return instant;
}
public long tztime() {
final java.time.ZonedDateTime zdtime = java.time.ZonedDateTime.now();
return tztime(zdtime);
}
public long tztime(java.time.ZonedDateTime zdtime) {
final java.time.ZonedDateTime zddate = zdtime.truncatedTo(java.time.temporal.ChronoUnit.DAYS);
final long millis = zddate.until(zdtime, java.time.temporal.ChronoUnit.MILLIS);
return millis;
}
}
A: tl;dr
LocalDate ld =
myUtilDate.toInstant()
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate() ;
Avoid legacy date-time classes
You are using troublesome old legacy date-time classes. Avoid them.
Instead use java.time classes. These supplant the old classes as well as the Joda-Time library.
Convert
Convert your java.util.Date to an Instant.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myUtilDate.toInstant();
Time Zone
Apply a time zone. Time zone is crucial. For any given moment the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while also being “yesterday” in Montréal Québec.
Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
Local… types
The LocalDate class represents a date-only value without time-of-day and without time zone. Likewise, the LocalTime represents a time-of-day without a date and without a time zone. You can think of these as two components which along with a ZoneId make up a ZonedDateTime. You can extract these from a ZonedDateTime.
LocalDate ld = zdt.toLocalDate();
LocalTime lt = zdt.toLocalTime();
Strings
If your goal is merely generating Strings for presentation to the user, no need for the Local… types. Instead, use DateTimeFormatter to generate strings representing only the date-portion or the time-portion. That class is smart enough to automatically localize while generating the String.
Specify a Locale to determine (a) the human language used for translating name of day, name of month, and such, and (b) the cultural norms for deciding issues such as abbreviation, capitalization, punctuation, and such.
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter fDate = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( locale );
String outputDate = zdt.format( fDate );
DateTimeFormatter fTime = DateTimeFormatter.ofLocalizedTime( FormatStyle.MEDIUM ).withLocale( locale );
String outputTime = zdt.format( fTime );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to change a single querystring parameter, possibly via a control action? In the last three days I've struggled trying to find a way to accomplish what I though was supposed to be a simple thing. Doing this on my own or searching for a solution in the web, didn't help. Maybe because I'm not even sure what to look for, when I do my researches.
I'll try to explain as much as I can here: maybe someone will be able to help me.
I won't say how I'm doing it, because I've tried to do it in many ways and none of them worked for different reasons: I prefer to see a fresh advice from you.
In most of the pages of web application, I have two links (but they could be more) like that:
*
*Option A
*Option B
This is partial view, retured by a controller action.
User can select or both (all) values, but they can't never select none of them: meaning that at least one must be always selected.
These links must che accessible in almost all pages and they are not supposed to redirect to a different page, but only to store this information somewhere, to be reused when action needs to filter returned contents: a place always accessible, regarding the current controller, action or user (including non authenticated users) (session? cookie?).
This information is used to filter displayed contents in the whole web application.
So, the problem is not how to create the business logi of that, but how (and where) to store this information:
*
*without messing with the querystring (means: keeps the querystring as empty/clean as possible)
*without redirecting to other pages (user must get the current page, just with different contents)
*allow this information to persists between all views, until user click again to change the option(s)
My aim is to have this information stored in a model that will contains all options and their selection status (on/off), so the appropriates PartialView will know how to display them.
Also, I could send this model to the "thing" that will handle option changes.
Thanks.
UPDATE
Following Paul's advice, I've took the Session way:
private List<OptionSelectionModel> _userOptionPreferences;
protected List<OptionSelectionModel> UserOptionPreferences
{
get
{
if (Session["UserOptionPreferences"] == null)
{
_userOptionPreferences= Lib.Options.GetOptionSelectionModelList();
}
else
{
_userOptionPreferences= Session["UserOptionPreferences"].ToString().Deserialize<List<OptionSelectionModel>>();
}
if (_userOptionPreferences.Where(g => g.Selected).Count() == 0)
{
foreach (var userOptionPreferencesin _userOptionPreferences)
{
userOptionPreferences.Selected = true;
}
}
UserOptionPreferences= _userOptionPreferences;
return _userOptionPreferences;
}
private set
{
_userOptionPreferences= value;
Session["UserOptionPreferences"] = _userOptionPreferences.SerializeObject();
}
}
Following this, I've overridden (not sure is the right conjugation of "to override" :) OnActionExecuting():
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
GetOptionSelections();
base.OnActionExecuting(filterContext);
}
GetOptionSelections()...
private void GetOptionSelections()
{
if (String.IsNullOrEmpty(Request["optionCode"])) return;
var newOptionCode = Request["optionCode "];
foreach (var userOptionPreferencesin UserOptionPreferences)
{
if (userOptionPreferences.OptionCode == newOptionCode )
userOptionPreferences.Selected = !userOptionPreferences.Selected;
}
}
This code I think can be better, but right now I just want to make it work and it doesn't.
Maybe there are also other issues there (quite sure, actually), but I believe the main issue is that OnActionExecuting is called by each action in a controller that inherit from BaseController, therefore it keeps toggling userOptionPreferences.Selected on/off, but I don't know how to make GetOptionSelections() being called only once in each View: something like the old Page_Load, but for MVC.
Last update AKA solution
Ok, using the session way, I've managed to store this information.
The other issue wasn't really on topic with this question and I've managed to solve it creating a new action that take cares of handling the option's change, then redirects to the caller URL (using the usual returnUrl parameter, but as action parameter).
This way, the option change is done only once per call.
The only thing I don't really like is that I can't simply work with the UserOptionPreferences property, as it doesn't change the session value, but only the value in memory, so I have to set the property with the new object's status each time: not a big deal, but not nice either.
A: This is a place to use session.
The session will keep your setting between requests while keeping it out of the url querystring. It seems that you have probably tried this already, but try it again and if you have problems ask again. I think it will be the best way for you to solve this problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Shortcut to make all split screens have the same width? When I open gvim -S (with a session) my split screens' widths are screwed up and I have to manually adjust them.
Is there a shortcut to make all split screens the same width ?
Thanks
A: This should normally work:
C-w= see window-resize
There are exceptions with windows that maintain a minimum/maximum width. This is frequently the case with 'sidebar' style plugins (taglist, nerdtree); In which case it is probably only what you wanted when they don't resize.
A: From the vim help pages:
CTRL-W = Make all windows (almost) equally high and wide, but use
'winheight' and 'winwidth' for the current window.
Windows with 'winfixheight' set keep their height and windows
with 'winfixwidth' set keep their width.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "50"
} |
Q: .Net Chart control with logarithmic scale on the X-axis For a project we are using the Telerik RadChart control to display a graph on a website. At the moment the X-axis follows a normal scale but we would like to change that to a logarithmic scale. As far as we can tell the control does not allow that.
Does anyone know of an alternative that would support this?
TIA,
David
Example of what we would like to achieve.
A: "Unfortunately the current version of RadChart does not support logarithmic X-Axis. We have already logged such a request in our public issue tracking system, you can find it here, however, taking a decision for implementing a certain feature depends on multiple conditions including complexity, existing features impact, demand rate, etc. It is not yet in our immediate plans, still, I would encourage you to use the above link to vote and track the issue."
Regards,
Nikolay
the Telerik team
Taken from here, as it was posted this month.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make User Interface of add contact detail same like in iPhone Contact List? I am making an app, in which I am making custom contact list for this application, now I made add button to add contact in my custom contact list.
Now I want to add all the detail (name, mobile, email, photo etc..) of contact, same like iPhone new contact detail has, and with same userInterface that apple use in add contact...
I think its custom group table view but still I can not get how they use it, and I want to do like exactly same...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL Server: alter table, how to add SPARSE definition I would like alter my table and add SPARSE option to all fields that contain a lot of NULL values. What is the right syntax for this ALTER TABLE command?
A: The other answers work, but you can also get away with:
ALTER TABLE #foo ALTER COLUMN bar ADD SPARSE;
This way you don't have to look up the column's type or nullability.
A: CREATE TABLE #Foo
(
X INT NULL,
Y INT NULL
)
ALTER TABLE #Foo ALTER COLUMN Y INT SPARSE NULL
ALTER TABLE #Foo ALTER COLUMN X INT SPARSE NULL
A: ALTER TABLE Xtable
ADD myCol int sparse null
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Backup sqltabledata and structure into an output file Hi currently i am developing an windows form application to backup table data and table structure to an output file and i am using 3rd party dll to back up it and i have 3 radiobuttons in which user selects
1. To backup only table data
2. To back up only table structure.
3. To backup both table data and structure.
With that 3rd party dll i managed to do 2nd and 3rd points . To achive first one i am doing 3rd bit first and finally in my output file there will be both tabledata and table structure and if i want only table data i am trying to delete lines till schem bit and leave the data part and for that iam using following code :
StringBuilder newText = new StringBuilder();
using (StreamReader tsr = new StreamReader(filePath))
{
do
{
string textLine = tsr.ReadLine() + "\r\n";
{
if (textLine.StartsWith("INSERT INTO"))
{
newText.Append(textLine + Environment.NewLine);
}
}
}
while (tsr.Peek() != -1);
tsr.Close();
}
System.IO.TextWriter w = new System.IO.StreamWriter(filePath);
w.Write(newText.ToString());
w.Flush();
w.Close();
If i am doing above coding i am missing GO between INSERT INTO statements as i want GO between each insert into statement . Please help and let me know is there anything worng with my approach
A: Possible approach: just don't write the program, use SQL Server features.
https://serverfault.com/questions/147638/dump-microsoft-sql-server-database-to-an-sql-script
http://www.kodyaz.com/articles/how-to-script-data-in-sql-server-2011.aspx
http://blog.sqlauthority.com/2007/11/16/sql-server-2005-generate-script-with-data-from-database-database-publishing-wizard/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facebook Graph API, mark inbox as read? Okay I think the title pretty much sums it up but I'll explain my situation anyway. I have written a desktop app using the Facebook C# SDK and Graph API which notifys me when I have new notifications and new (unread) messages in my inbox and it seems to work but the facebook graph api even when I use Facebooks Graph API explorer to get /me/inbox (this is specific to my facebook account) has an inbox thread that is marked as unread but does not show up on facebooks website or any of the Facebook apps i use (android/iPhone) so I can see in the api explorer everything about the thread and theres a message under the "message" field but doesn't have anything in "comments". Anyway my problem is when I use this new app i've written this keep showing up and as it doesnt show in messages on facebooks website or the facebook mobile apps, I cannot mark it as read. So is there a way to do this manually using the graph API even just so I can do it with the api explorer because I dont want it forever showing in my app, I know that i can mark notifications as read this way but I cannot work out how to mark this inbox thread as read. I could always hardcode the thread id into my app and tell it to ignore it but this is an extremely unelegant solution especially considering I am not the only person who will use this app. Even a way to delete the thread completely by graph API, is this possible?
EDIT: I have tried POST https://graph.facebook.com/(thread_id) with fields "unread": 0 but that did not work
A: No, there is no permissions in the current APIs that Facebook has available other than Read-Only access to a user's Inbox.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to smoothen jquery slider? i have this jquery slider code here -
jsfiddle or jquery demo
now all i want to do is that i want to make the slider work more smoother
please help!
P.S. by smoother i mean that i drag the slider to a little distance from my mouse and it automatically gets dragged to a little more...its an animation affect kind of something.....and i tried those options on the demo page but they just make the slider disappear and not function.
A: What is your view on the word 'smoother'? jQuery slider has numerous options that can influence the behavior of it (http://jqueryui.com/demos/slider/), so try to expiriment with that.
A: slide: function(event, ui) {
if (scrollContent.width() > scrollPane.width()) {
scrollContent.animate({
"margin-left": Math.round(ui.value / 100 * (scrollPane.width() - scrollContent.width()))
}, 20);
} else {
scrollContent.animate({
"margin-left": 0
}, 20);
}
}
http://jsfiddle.net/v9V7W/3/
A: I've actually made one which we currently use at work. You can use CSS3 property of transform3d to make a smooth slide. Transform3d is hardware accelerated, unlike margin-left or left, so it's a lot smoother.
You can check it out here - http://dezignhero.github.io/swiper/
It's designed primarily for webkit devices but also works on desktop too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Processes locking on multicore machine I recently started running my java program on my new multicore machine. I am suddenly seeing a problem which never occurred on my old single core Pentium. I suspect that the issue has to do with some sort of contention between my program and the various browsers I am running at the same time. When the processes get into this state, no amount of killing of processes seems to help (there's always some residual firefox or chrome process), so I end up restarting the machine. My program does a lot of opening and reading of URLs essentially using the following lines:
URL url = new URL( urlString );
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
........
while ((inputLine = in.readLine()) != null ) {...}
Every so often the URL my program tries to hit does not exist. In these cases, the call to create the BufferedReader eventually times out. I am going to modify the program to use a shorter time out, but I suspect that this in itself is not going to fix the problem.
Any suggestions would be appreciated.
A: I think the system change is a red herring. When you working with raw URL connection on the jdk there might be an issue. There is no in built retry mechanism and you will have to write all the code yourself. Try the HTTP client library from Apache. That should more or less solve any problem you face with URLConnection - http://hc.apache.org/httpclient-3.x/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to export text into pdf in Java, Android?
Possible Duplicate:
How to create pdf files on android
I need to create app for exporting text into pdf file. But I don't know how to do it, because I never used it ever. Help me please, give me an example for this task or link for tutorial.
A: Some libraries in java to acheive this
http://pdfbox.apache.org/
http://itextpdf.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Drop TAble if exist and then create table i am creating java application using ms access database.
i have to create table "student" if not exit and if exist then drop table first then make table student.
i have writing code for it. for this i have made function boolean makeTable(Connection con,String tablename) and function boolean dropTable (Connection con,String tablename)
First time
if exist table then maketable() return false but then call function dropTable() it return false also(table not deleted)
second time
call dropTable() then return true (table deleted successfully) but then call createTable() return false (table not created).
why this happens i don't know.
please help this.
if there is statement (Drop Table IF EXIST STUDENT)
or other way to doing this
thanks in advance.
--PARAG HUMANE
A: Use Connection.getMetaData().getTables() method. It return tables description.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Expose Action as Action I'm creating a framework that contains a wrapper around a library (specifically SharpBrake) that performs all interaction with SharpBrake via reflection so there's no hard dependency on the library to 3rd parties of my framework.
If 3rd parties of my framework wants to use SharpBrake, they can just stuff the SharpBrake.dll into the bin folder, but if they don't, they can just forget about it. If my framework had explicit references to SharpBrake types, users of my framework would get exceptions during runtime of SharpBrake.dll missing, which I don't want.
So, my wrapper first loads SharpBrake.dll from disk, finds the AirbrakeClient type, and stores a delegate pointing to the AirbrakeClient.Send(AirbrakeNotice) method in a private field. My problem, however, is that since the Send() method takes an AirbrakeNotice object and I can't reference the AirbrakeNotice object directly, I need to somehow convert the Send() method to an Action<object>.
I have a strong feeling this isn't possible, but I want to explore all options before settling on exposing Delegate and using DynamicInvoke(), which I assume is far from optimal, performance-wise. What I would love to do is the following:
Type clientType = exportedTypes.FirstOrDefault(type => type.Name == "AirbrakeClient");
Type noticeType = exportedTypes.FirstOrDefault(type => type.Name == "AirbrakeNotice");
MethodInfo sendMethod = clientType.GetMethod("Send", new[] { noticeType });
object client = Activator.CreateInstance(clientType);
Type actionType = Expression.GetActionType(noticeType);
Delegate sendMethodDelegate = Delegate.CreateDelegate(actionType, client, sendMethod);
// This fails with an InvalidCastException:
Action<object> sendAction = (Action<object>)sendMethodDelegate;
However, this fails with the following exception:
System.InvalidCastException: Unable to cast object of type 'System.Action`1[SharpBrake.Serialization.AirbrakeNotice]' to type 'System.Action`1[System.Object]'.
Obviously, because sendMethodDelegate is an Action<AirbrakeNotice> and not an Action<object>. Since I can't mention AirbrakeNotice in my code, I'm forced to do this:
Action<object> sendAction = x => sendMethodDelegate.DynamicInvoke(x);
or just exposing the Delegate sendMethodDelegate directly. Is this possible? I know that there's chance of getting into situations where the object can be of a different type than AirbrakeNotice which would be bad, but seeing how much you can mess up with reflection anyway, I'm hoping there's a loophole somewhere.
A: If you're happy to use expression trees, it's reasonably simple:
ConstantExpression target = Expression.Constant(client, clientType);
ParameterExpression parameter = Expression.Parameter(typeof(object), "x");
Expression converted = Expression.Convert(parameter, noticeType);
Expression call = Expression.Call(target, sendMethod, converted);
Action<object> action = Expression.Lambda<Action<object>>(call, parameter)
.Compile();
I think that's what you want...
A: If you don't need below C# 4 support you can get much greater performance using the dynamic vs DynamicInvoke.
Action<dynamic> sendAction = x => sendMethodDelegate(x);
Actually I guess you wouldn't even need the above if you can use dynamic, because it would increase performance and simplify everything if you just did:
Type clientType = exportedTypes.FirstOrDefault(type => type.Name == "AirbrakeClient");
dynamic client = Activator.CreateInstance(clientType);
...
client.Send(anAirbrakeNotice);
But if you need to support .net 3.5 jon skeets answer with expression trees is definitely the way to go.
A: From my comment on the OP:
I'd avoid extended use of reflections if you are concerned about performance. If you can come up with an interface for the class(es) you are using, then I'd create one. Then write a wrapper that implements the interface by calling into the SharpBreak code, and stuff it in a separate DLL. Then dynamically load just your wrapper assembly and concrete wrapper type(s), and call into that interface. Then you don't have to do reflections at a method level.
I'm not sure all the classes you'd need, but here's a simple example of how you can hook into that library with loose coupling based on interfaces.
In your program's assembly:
public IExtensions
{
void SendToAirbrake(Exception exception);
}
public static AirbreakExtensions
{
private static IExtensions _impl;
static()
{
impl = new NullExtensions();
// Todo: Load if available here
}
public static void SendToAirbrake(this Exception exception)
{
_impl.SendToAirbrake(exception);
}
}
internal class NullExtensions : IExtensions // no-op fake
{
void SendToAirbrake(Exception exception)
{
}
}
In a load-if-available (via reflections) assembly
public ExtensionsAdapter : IExtensions
{
void SendToAirbrake(Exception exception)
{
SharpBrake.Extensions.SendToAirbrake(exception);
}
}
The advantage of this approach is that you only use reflections once (on load), and never touch it again. It is also simple to modify to use dependency injection, or mock objects (for testing).
Edit:
For other types it will take a bit more work.
You might need to use the Abstract Factory pattern to instantiate an AirbrakeNoticeBuilder, since you need to deal directly with the interface, and can't put constructors in interfaces.
public interface IAirbrakeNoticeBuilderFactory
{
IAirbrakeNoticeBuilder Create();
IAirbrakeNoticeBuilder Create(AirbrakeConfiguration configuration);
}
If you're dealing with custom Airbreak structures, you'll have even more work.
E.g. for the AirbrakeNoticeBuilder you will have to create duplicate POCO types for any related classes that you use.
public interface IAirbrakeNoticeBuilder
{
AirbrakeNotice Notice(Exception exception);
}
Since you're returning AirbrakeNotice, you might have to pull in nearly every POCO under the Serialization folder, depending on how much you use, and how much you pass back to the framework.
If you decide to copy the POCO code, including the whole object tree, you could look into using AutoMapper to convert to and from your POCO copies.
Alternately, if you don't use the values in the classes you're getting back, and just pass them back to the SharpBreak code, you could come up with some sort of opaque reference scheme that will use a dictionary of your opaque reference type to the actual POCO type. Then you don't have to copy the whole POCO object tree into your code, and you don't need to take as much runtime overhead to map the object trees back and forth:
public class AirbrakeNotice
{
// Note there is no implementation
}
internal class AirbreakNoticeMap
{
static AirbreakNoticeMap()
{
Map = new Dictionary<AirbreakNotice, SharpBreak.AirbreakNotice>();
}
public static Dictionary<AirbreakNotice, SharpBreak.AirbreakNotice> Map { get; }
}
public interface IAirbrakeClient
{
void Send(AirbrakeNotice notice);
// ...
}
internal class AirbrakeClientWrapper : IAirbrakeClient
{
private AirbrakeClient _airbrakeClient;
public void Send(AirbrakeNotice notice)
{
SharpBreak.AirbrakeNotice actualNotice = AirbreakNoticeMap.Map[notice];
_airbrakeClient.Send(actualNotice);
}
// ...
}
internal class AirbrakeNoticeBuilderWrapper : IAirbrakeNoticeBuilder
{
AirbrakeNoticeBuilder _airbrakeNoticeBuilder;
public AirbrakeNotice Notice(Exception exception)
{
SharpBreak.AirbrakeNotice actualNotice =
_airbrakeNoticeBuilder.Notice(exception);
AirbrakeNotice result = new AirbrakeNotice();
AirbreakNoticeMap.Map[result] = actualNotice;
return result;
}
// ...
}
Keep in mind that you only need to wrap the classes and parts of the public interface that you're going to use. The object will still behave the same internally, even if you don't wrap its entire public interface. This might mean you have to do less work, so think hard and try to wrap only what you need now, and what you know you're going to need in the future. Keep YAGNI in mind.
A: The programming style I have come to really like for problems like this is to write as much strongly-typed code as possible, and then hand off the logic from the dynamically-typed code to the strongly-typed code. So I would write your code like this:
//your code which gets types
Type clientType = exportedTypes.FirstOrDefault(type => type.Name == "AirbrakeClient");
Type noticeType = exportedTypes.FirstOrDefault(type => type.Name == "AirbrakeNotice");
//construct my helper object
var makeDelegateHelperType=typeof(MakeDelegateHelper<,>).MakeGenericType(clientType, noticeType);
var makeDelegateHelper=(MakeDelegateHelper)Activator.CreateInstance(makeDelegateHelperType);
//now I am in strongly-typed world again
var sendAction=makeDelegateHelper.MakeSendAction();
And this is the definition of the helper object, which is able to get away with fewer reflectiony calls.
public abstract class MakeDelegateHelper {
public abstract Action<object> MakeSendAction();
}
public class MakeDelegateHelper<TClient,TNotice> : MakeDelegateHelper where TClient : new() {
public override Action<object> MakeSendAction() {
var sendMethod = typeof(TClient).GetMethod("Send", new[] { typeof(TNotice) });
var client=new TClient();
var action=(Action<TNotice>)Delegate.CreateDelegate(typeof(Action<TNotice>), client, sendMethod);
return o => action((TNotice)o);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to Stop a Service in Android when the application is not running. I have Started my service in one of my main activity class.The problem is that when my application is not running I want to Stop my service.How can i implement this.Is there any option to stop it without stopping it using any button click or other click events of the control.
Also is there any way to indicate the service is running or not while my application is running
A: Using intent you can stop the service.
Intent intentStartervice = new Intent(context, MyService.class);
stopService(intentStartService);
or
just pass the Context.
context.stopService(new Intent(context, MyService.class));
A: Simply by firing an Intent like this:
Intent intent = new Intent(this, Your_service.class);
Just add this block of code where you have stop your service:
stopService(intent);
Update:
add this method to each and every activity of your application
public boolean onKeyDown(int key, KeyEvent event)
{
switch(key.getAction())
{
case KeyEvent.KEYCODE_HOME :
Intent intent = new Intent(this, Your_service.class);
stopService(intent);
break;
}
return true;
}
A: You can start service in onCreate of your launcher activity and stop service in onStop of the same activity.
You can refer to this for complete service tutorial:
http://marakana.com/forums/android/examples/60.html
And yes,better you use the same intent variable to start and stop activity.At last,Don't forget to add your service to manifest.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: HTML Element: get notified when the scrollbar appears I have a div like this:
<div id='test' style='overflow:auto'>
...
</div>
In javascript (no jquery) How do I know when - as a consequence of the user resizing the browser - the div is showing a horizontal bar or not ?
Note: I don't want only to figure if it is showing horizontal bar or not, I want to be notified when that happens.
A: If you want to hook the resize of window
window.onresize = function(){
var test = document.getElementById("test");
if(test.offsetHeight != test.scrollHeight)
// raise event or call ur method
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Accessing Mutual fund quotes I have been looking for a while at how to retrieve financial quotes in c#, in this case, Canadian mutual funds.
It seems there are 2 main sources of information for this, Yahoo and Google! Also there seems to be 2 preferred methods, API and HTML scrapping. My preference would be for an API method, but I am open to any suggestion.
I have found the Yahoo api to be very nice to use, however although it works for stocks like "MSFT" it fails to retrieve the data for mutual funds like "RBCCANADIANI.TO". For some reason this symbol only works on the web site itself.
Google's API seems to requires to have a portfolio set up and login in order to retrieve quotes, I would prefer to avoid logins and use a completly opened api if possible.
HTML scraping introduce a totally new set of complications, asking the user to locate on an html page where the price is and such. Note that Google's html (http://www.google.com/finance?q=MUTF_CA:RBF556) returns the right page, but a look at the html source shows that the price is not in an easily identifiable tag (id not set!).
Has anybody tried similar things, I have the feeling I am missing something here :)
Many thanks
A: I am having success with the following YQL query:
select LastTradePriceOnly from yahoo.finance.quotes where symbol in ("F0CAN05NGC.TO")
This is for Royal Global Precious Metals fund.
Mutual funds have a LastTradePriceOnly field but no Bid field like stocks have. I got the symbol from the Symbol Lookup on the Yahoo finance page.
A: If you are looking for pricing data I would suggest a service like IQFeed. I have used them as a client for some time and they do have mutual fund data (although I don't use it). If you don't want to pay for it you will probably have to scrape it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Logging only debug level messages to file in symfony 1.4 Most of my app logging is done at debug level because in sf 1.4 it's not used by symfony itself, and that makes it easy to see just the messages I'm interested in using something like:
tail -f log/frontend_dev.php | grep "\[debug\]"
This is great in the dev environment while I'm sat there watching it scroll past, but I now want to log only these debug messages in the production environment.
If I set the log level for the production log to debug, then obviously I'll get everything down to and including the debug level, which is far too much data.
Is it possible to write a logger that will just record [debug] messages and nothing else?
A: Of course it is possible - you can extend sfFileLogger and override log($message, $priority) function (which sfFileLogger inherits from sfLogger class).
...
public function log($message, $priority = self::DEBUG)
{
if ($this->getLogLevel() != $priority)
{
return false;
}
return $this->doLog($message, $priority);
}
...
Now you have to configure logging in your app to use your new logger class, configuration is located in app/<your app>/config/factories.yml:
prod:
logger:
class: sfAggregateLogger
param:
level: DEBUG
loggers:
sf_file_debug:
class: myDebugOnlyLoggerClass
param:
level: DEBUG
file: %SF_LOG_DIR%/%SF_APP%_%SF_ENVIRONMENT%.log
This logger will save only messages logged with the same priority (and only the same, not the same or higher) as configured in factories.yml.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery to read and compare a word as you type I need to implement a sort of word sensing feature . What I require is to have a plugin which will read and compare a word, as I type , with a predefined word , and on successfull matches , it will display a checkbox .
As in the image , once I type test and give a space , it will take the entire word Test and compare it with a predefined word say "Testimony" . Now, as I have given a space after Test , it won't match with the reference word and it will wait for the next word. Again , as a user presses spacebar , it will take the new word and start comparing .
A: If you need a more customizable option than jQuery's autocomplete, you can bind a keypress event to the textbox you are typing in, check the keycode of the key that the user is pressing, and act accordingly. Something along the lines of this:
$('#textarea').bind('keypress', function(e) {
var key = (e.keyCode ? e.keyCode : e.charCode);
if( key == '32') {
alert("spacebar was pressed");
var input = $("#textArea").val();
// Put your comparison logic here
}
});
I remember there being some funkiness with how IE handles codes, but the above works at least with FF and Chrome.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Talend: Write data to PostgreSQL database error I am trying to write data from a .csv file to my postgreSQL database. The connection is fine, but when I run my job i get the following error:
Exception in component tPostgresqlOutput_1
org.postgresql.util.PSQLException: ERROR: zero-length delimited identifier at or near """"
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:1592)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1327)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:192)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:451)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:336)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:328)
at talend_test.exporttoexcel_0_1.exportToExcel.tFileInputDelimited_1Process(exportToExcel.java:568)
at talend_test.exporttoexcel_0_1.exportToExcel.runJobInTOS(exportToExcel.java:1015)
at talend_test.exporttoexcel_0_1.exportToExcel.main(exportToExcel.java:886)
My job is very simple:
tFileInputDelimiter -> PostgreSQL_Output
I think that the error means that the double quotes should be single quotes ("" -> ''), but how can i edit this in Talend?
Or is it another reason?
Can anyone help me on this one?
Thanks!
A: If you are using the customer.csv file from the repository then you have to change the properties of customer file by clicking through metadata->file delimited->customer in the repository pane.
You should be able to right click the customer file and then choose Edit file delimited. In the third screen, if the file extension is .csv then in Escape char settings you have to select CSV options. Typical escape sequences (as used by Excel and other programs) have escape char as "\"" and text enclosure is also "\"".
You should also check that encoding is set to UTF-8 in the file settings. You can then refresh your preview to view a sample of your file in a table format. If this matches your expectations of the data you should then be able to save the metadata entry and update this to your jobs.
If your file is not in the repository, then click on the component with your file and do all of the above CSV configuration steps in the basic settings of the component.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can we post image on twitter using twitter API in Android? I had successfully integrate twitter API and I am able to post text from my device but I want to know two things
*
*Is is possible to post Image on twitter using API in Android ?
*In twitter we used OAuth.OAUTH_TOKEN and OAuth.OAUTH_TOKEN_SECRET tokens.I passing token values on second argument in below code is it ok ? or I have to leave it blank ?
String token = prefs.getString(OAuth.OAUTH_TOKEN, OAuth_token_key);
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, OAuth_token_secret);
I searched to know whether is it possible to post image on twitter using twitter API in Android but I have not found any link that I know whether it is possible or not.
I got one similar post image issue for iPhone and there is a answer also. I don't know about iPhone so I can't know weather it is right answer or not.Here is a link of similar question of post image for iPhone
Please help me out from this issue.
A:
Is is possible to post Image on twitter using API in Android ?
Yes you can upload Images to Twitter after successful Authentication Using Twitter Media Uplload.
In twitter we used OAuth.OAUTH_TOKEN and OAuth.OAUTH_TOKEN_SECRET
tokens.I passing token values on second argument in below code is it
ok ? or I have to leave it blank ?
You should add both Token and Token Secret Key it will be useful for setTokenWithSecret methos of Tiwtter in which you have to send both Token and Token Secret..
A: Yes You can post the Image on the Twitter.
AIK, there are two methods to upload the photo to the Twitter.
With First you have to implemente the Twitter API and use this Link to upload the Photot to the Twitter.
Sorry for the Example. as i dont get any example for how to use this.
With Second you can do this with the help of the twitPic4j API.
Just add the API for twitPic4j and write below code to upload the photo.
Code:
File picture = new File(APP_FILE_PATH + "/"+filename+".jpg");
// Create TwitPic object and allocate TwitPicResponse object
TwitPic tpRequest = new TwitPic(TWITTER_NAME, TWITTER_PASSWORD);
TwitPicResponse tpResponse = null;
// Make request and handle exceptions
try {
tpResponse = tpRequest.uploadAndPost(picture, customMessageEditText.getText()+" http://www.twsbi.com/");
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Please enter valid username and password.", Toast.LENGTH_SHORT).show();
}
catch (TwitPicException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Invalid username and password.", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Please enter valid Username and Password.", Toast.LENGTH_SHORT).show();
}
// If we got a response back, print out response variables
if(tpResponse != null) {
tpResponse.dumpVars();
System.out.println(tpResponse.getStatus());
if(tpResponse.getStatus().equals("ok")){
Toast.makeText(getApplicationContext(), "Photo posted on Twitter.",Toast.LENGTH_SHORT).show();
//picture.delete();
}
}
Above code works in for my case.
Hope you got the sollution with the second one and i dont know how to use the first one.
Enjoy. :)
Updated
If still it not works for you and try some project listed below:
Example 1
Example 2
Example 3
Example 4
Hope that will help you.
Happy Coding.
==================================
FOR erdomester and Updated answer
==================================
Please check my first link given with Example1 and its api: Twitter4J
So, if any library that stop giving functionality to upload image on twitter, you can use other library for same. Please check and read regrading Twitter4j.
Check Twitter4J API to upload file to Twitter: Twitter4j Image Upload
For instance help you can also check below code to upload image file on Twitter.
Code to upload Image:
/**
* To upload a picture with some piece of text.
*
*
* @param file The file which we want to share with our tweet
* @param message Message to display with picture
* @param twitter Instance of authorized Twitter class
* @throws Exception exception if any
*/
public void uploadPic(File file, String message,Twitter twitter) throws Exception {
try{
StatusUpdate status = new StatusUpdate(message);
status.setMedia(file);
twitter.updateStatus(status);}
catch(TwitterException e){
Log.d("TAG", "Pic Upload error" + e.getErrorMessage());
throw e;
}
}
I hope this will help you more for your query.
Thanks to eredomester to notify me that tweetpic is no more working for Twitter. But please dont do downvote to answer untill you have not fully search on the given reply. Given library Twitter4J in Example1 gives clear idea about uploading image to twitter and you can easily implement it.
For more help and code you can also check: Twitter Upload media
Note: To use this please make sure you have latest jar file. I have used twitter4j-core-2.2.5.jar or more for this.
Please comment me instead of downvoting this answer, if you facing any issue in this.
A: Yes you can post image on twitter using Twitter api like twitter4j but I will suggest you to do using HttpPost class and DefaultHttpClient class because its good in practice and you dont need to add any external twitter api to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Error after deploying the application in appspot I get the following error in the browser when trying to access my Java application in appspot.
Error: NOT_FOUND
However it works fine when I run from Eclipse or ant. I have checked the logs in GAE admin console but couldn't find any error messages.
I have also tried by removing all the *.class files before building.
The application is deployed using the appcfg script provided in appengine-java-sdk-1.5.3. Is there any specific reason for this behaviour?
Here is the debug messages from GAE log console:
2011-10-02 22:11:39.306 / 302 14950ms 10348cpu_ms 315api_cpu_ms 0kb Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1
115.119.214.18 - - [02/Oct/2011:22:11:39 -0700] "GET / HTTP/1.1" 302 191 - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1" "xxxxxxxx-test.appspot.com" ms=14950 cpu_ms=10348 api_cpu_ms=315 cpm_usd=0.287514 loading_request=1 throttle_code=1 instance=00c61b117c46324075b13d0c2ce04f5678c813
I 2011-10-02 22:11:26.447
javax.servlet.ServletContext log: Initializing Spring root WebApplicationContext
W 2011-10-02 22:11:26.728
[s~xxxxxxxx-test/8.353561328003056299].<stderr>: log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
W 2011-10-02 22:11:26.728
[s~xxxxxxxx-test/8.353561328003056299].<stderr>: log4j:WARN Please initialize the log4j system properly.
I 2011-10-02 22:11:37.075
javax.servlet.ServletContext log: Initializing Spring FrameworkServlet 'dispatcher'
I 2011-10-02 22:11:39.306
This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application.
web.xml:
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/servlet-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/ExampleApp/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Contents of index.jsp (welcome-file)
<% response.sendRedirect("/ExampleApp/user/login"); %>
Here is the build.xml:
<project>
<property name="sdk.dir" location="../appengine-java-sdk-1.5.3" />
<import file="${sdk.dir}/config/user/ant-macros.xml" />
<path id="project.classpath">
<pathelement path="war/WEB-INF/classes" />
<fileset dir="war/WEB-INF/lib">
<include name="**/*.jar" />
</fileset>
<fileset dir="${sdk.dir}/lib">
<include name="shared/**/*.jar" />
</fileset>
</path>
<!--
<target name="copyjars" description="Copies the App Engine JARs to the WAR.">
<copy todir="war/WEB-INF/lib" flatten="true">
<fileset dir="${sdk.dir}/lib/user">
<include name="**/*.jar" />
</fileset>
</copy>
</target>
-->
<target name="compile" description="Compiles Java source and copies other source files to the WAR.">
<mkdir dir="war/WEB-INF/classes" />
<copy todir="war/WEB-INF/classes">
<fileset dir="src">
<exclude name="**/*.java" />
</fileset>
</copy>
<javac srcdir="src" destdir="war/WEB-INF/classes" classpathref="project.classpath" debug="on" />
</target>
<target name="datanucleusenhance" depends="compile" description="Performs JDO enhancement on compiled data classes.">
<enhance_war war="war" />
</target>
<target name="runserver" depends="datanucleusenhance" description="Starts the development server.">
<dev_appserver war="war" />
</target>
<target name="update" depends="datanucleusenhance" description="Uploads the application to App Engine.">
<appcfg action="update" war="war" />
</target>
<target name="update_indexes" depends="datanucleusenhance" description="Uploads just the datastore index configuration to App Engine.">
<appcfg action="update_indexes" war="war" />
</target>
<target name="rollback" depends="datanucleusenhance" description="Rolls back an interrupted application update.">
<appcfg action="rollback" war="war" />
</target>
<target name="request_logs" description="Downloads log data from App Engine for the application.">
<appcfg action="request_logs" war="war">
<options>
<arg value="--num_days=5"/>
</options>
<args>
<arg value="logs.txt"/>
</args>
</appcfg>
</target>
</project>
A: After several days of tests and experiments, I got the solution for the problem in appspot.com. There was an issue with the JSP configuration in which the prefix had an additional slash.
Old Configuration:
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
New configuration:
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix" value="/WEB-INF/views" />
<property name="suffix" value=".jsp" />
</bean>
In the controller the return path was "/Login/LoginPage.jsp". ( did the change in xml file since there were too much controller methods which returned the jsp file location).
I couldn't trace the issue until log4j was enabled to record the debug issues. The key in identifying the issue was the following line in the logs:
2011-10-10 21:38:14.644
[s~exampleapp-test/8.353868453989422042].<stdout>: 16:08:14,644 DEBUG [org.springframework.web.servlet.view.JstlView] - Forwarding to resource [/WEB-INF/views//Login/LoginPage.jsp] in InternalResourceView '/Login/LoginPage'
Thanks @Dave for your patience and guidance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Live Scrolling Stock Ticker Looking for a scrolling stock ticker, as seen here: http://www.bloomberg.com/ - preferably run in combination with jQuery liScroller.
How would I go about this? RSS? Any costs involved?
Recommendations welcome.
A: If your going to use a plugin like liScroller to do the ticker for you than that should not be that much of an hassle.
What you have to do before that is to get the content you want the ticker to scroll throw onto the page before you execute the plugin functions.
I'm not sure what information you want to get, but its likely you can get in on an RSS feed.
You can use jquery to parse the rss feed, sins rss is just an xml file. Here are the documentation http://api.jquery.com/jQuery.parseXML/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rendering a page in PHP: How? This may be a inappropriate question for SO, but I thought lets see :)
I'm writing a website in php. Every pageload may have 10-20 DB requests.
Using the result of the DB queries I need to generate a page.
The page would contain a topic (should be image or text) followed by comments. There could be mutiple topics like this.
Currently, I'm creating a string using the DB result and sending it to the browser.
When browser receives the string (as an ajax response), it parses using split functions and creates the HTML dynamically.
I'm basically a C++ programmer; relatively new to web development. So, I do not have fair understanding of the JS objects. How long of a string can JS variable hold? Is it ok to use split and generate HTML at the client.
I'm not generating the complete HTML at the server side to avoid any overhead because of string concatenation. I believe sending less no. of characters to the client (like I'm doing) is better as compared to sending complete HTML code.
Is something (or everything) wrong in my understanding :)
Any help is appreciated.
EDIT:
Well, I'll be highly grateful if I could get opinions in yes/no. What would you recommend. Sending HTML to the client or a string that will be used at the client to generate HTML?
A: Unless you have a specific reason for doing so, I think you should look into generating the HTML with PHP and sending it directly to the browser. PHP was built specifically for this purpose.
A: I think you be best off to look at jQuery and more specific to the AJAX method of that library. Also, take a look at JSON and you should be all good to go.
A: Have you considered using a templating engine like Smarty?
It's pretty simple to use, take a look at the crash course, you might like it! http://www.smarty.net/crash_course
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: web.config in subdirectories doesn't work with web.config presence in root directory I have 3 Wordpress installation on my webserver, one in the root folder, 2 in sub directories (iis):
/
/wp_one
/wp_two
All of them have a web.config. If I remove the web.config from the root directory, URLs in children wp works pretty well. If I add it again, links point to the right place but when you click, I`m redirected to the correspondent page on root. For example:
www.site.com/wp_one/contact redirects to www.site/contact.
web.config content (they have the same content):
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="wp" stopProcessing="true">
<match url=".*"/>
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
</conditions>
<action type="Rewrite" url="index.php"/>
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
A: When you have multiple config files they are merged into a single one during runtime. This said when you have a web.config in your root the child ones are merged inside and since your paths are not relative they become invalid.
In order to fix this you will have to make your paths relative based on the topmost web.config.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wordpress image name same as page Friends, i'm stuccoed with images in wordpress - please, help me understand where search for solution.
If you create webpage - www.wordpress.local/page1/01-0001 and you upload an image 01-0001 on that page, you can see, that when you'll visit www.wordpress.local/page1/01-0001, you'll see the page with image, not the page, that you created with text and images.
Any ideas how to solve it ?
PS Not renaming images :)
A: When you use the WordPress-uploader, the images are stored in /wp-content/uploads/, and WordPress takes care of using filenames that aren't already in use.
If you upload an image, e.g. via FTP, that has the same name as a WordPress-page, the server has to decide what it should serve; either the WordPress-page or the image. One URL = one file served.
In your case, the server decides for the image. You could of course change this configuration; but in all cases, one of the two files won't be accessible.
If you want to make both files accessible, you either need to rename the image or the WordPress-page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inner div should be displayed in front of outer div I have the following code and would like the inner div with the class: escaping-container to be displayed in front of the outer div with the class container.
The inner div has bigger height setting than the outer div. So a part of it is cut off.
Also the part that is being cut of by outer div must be displayed.
<style type="text/css">
div.container{
width: 100px;
height:100px;
overflow-x:scroll;
overflow-y:hidden;
position:relative;
z-index:1;
}
div.escaping-container{
width:50px;
height:150px;
position:relative;
z-index:10;
background-color:red;
}
</style>
<div class ="container">
<div class="escaping-container"></div>
</div>
I tried to get this done by setting the z-index, but it doesn't work. Any help will be appreciated.
A: Im afraid your question is a contradiction. If you want the inner div to be visible, you must remove the overflow-x and overflow-y css statements.
A: if the overflow settings are necessary
try this http://jsfiddle.net/sandeep/59nGZ/
css:
div.container{
width: 100px;
height:100px;
overflow-x:scroll;
overflow-y:hidden;
border:1px solid red;
}
div.escaping-container{
width:50px;
height:150px;
position:absolute;
background-color:red;
}
A: You won't be able to position the inner <div> outside the parent with overflow set to scroll, hidden or auto. To be able to do so you either need to change your markup, or remove the overflow-properties from your CSS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Passing and Parse PayPal IPN Custom field I have setup a PayPal IPN file. When the user is at the site and press submit details about the transaction is uploaded to the db. The relevant id is sent via PayPal as the custom field. When payment complete IPN used to update DB as transaction completed based on id.
All is fine.
However, this is the tricky bit. I also need to update another table - a discount/coupon code db. The update is based on the code entered and also the number of times the code can still be used. Basically if it was 50 times, after used once the db would be updated with 49. So I need to pass the code and the remaining uses allowed so can say update table where code = XXXX (update new value of 49 etc).
I can work out how to pass all these values in the custom field, but cannot work out how to parse them out again? Read about separating them with : etc, but need some advice from someone who has done before.
This is how IPN details currently comes back:
$custom = $_POST['custom'];
Thank you.
A: This expands on JustAnil's solution.
HTML:
<input type="hidden" name="custom" value="some-id=1&some-type=2&some-thing=xyz"/>
and your IPN script would look something like this:
<?php
parse_str($_POST['custom'],$_CUSTOMPOST);
echo $_CUSTOMPOST['some-id'];
echo $_CUSTOMPOST['some-type'];
echo $_CUSTOMPOST['some-price'];
?>
You may want to double check that parse_str performs urldecode on resulting array elements.
A: Here is an example using JSON:
<?php
$arr = array($member_id, $coupon);
$data = json_encode($arr);
?>
<input type="hidden" name="custom" value="<?= $data ?>"/>
Then on the other side:
$custom = json_decode($_POST['custom'], true);
$member_id = $custom[0];
$coupon = $custom[1];
You can also parse associative arrays too:
<?php
$arr = array('id' => $member_id, 'coupon' => $coupon);
$data = json_encode($arr);
?>
<input type="hidden" name="custom" value="<?= $data ?>"/>
Then on the other side:
$custom = json_decode($_POST['custom'], true);
$member_id = $custom['id'];
$coupon = $custom['coupon'];
There's a nice symmetry when using JSON to parse the data.
A: I did just this recently,
Send your paypal custom field to data as your would, inside that custom field, use a separator to split your data.
In the below example, the values are split using a "|", you can use any character you want available in your charset.
$member_id = 1;
$some_other_id = 2;
<input type="hidden" name="custom" value="<?php echo $member_id.'|'.$some_other_id ?>"/>
This will output:
<input type="hidden" name="custom" value="1|2"/>
When you get the information from paypal (the IPN response) process it like so:
$ids = explode('|', $_POST['custom']); // Split up our string by '|'
// Now $ids is an array containing your 2 values in the order you put them.
$member_id = $ids[0]; // Our member id was the first value in the hidden custom field
$some_other_ud = $ids[1]; // some_other_id was the second value in our string.
So basically, we send a string with a custom delimiter that we choose to paypal, paypal will return it to us in the IPN response. We then need to split it up (using the explode() function) and then do what you would like with it.
When you get your value from the database your select it using normal methods, then just decrement it by 1 using:
$val_from_db--; // Thats it!, Takes the current number, and minus 1 from it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: how to change stylesheet when an image is clicked JS newbie here
I want to have a kind of profile preview page where people can select a color (could be clicking on an image or could be a radio button) and that changes the background colors in certain divs in the preview page.
IE someone clicks on the button for red then the gradients in the background of the title bar, info boxes etc will turn to reds.
Whats the best way to do this?
A: I think you'd be best off if you define specific stylesheets for each 'color' (read: style) you want to be available to the user. If the user clicks on something to make his color choice, you can change the stylesheet that is loaded. You probably will need a default.css or a main.css file that contains all positioning and default coloring stuff and for each color you have a separate css file like red.css that will load the colors for each element in your dom you want to be changed.
In simple Javascript this could look something like:
<link rel="stylesheet" href="style1.css" id="stylesheet">
<script type="text/javascript">
function changeStyle() {
document.getElementById('stylesheet').href = 'style2.css';
}
</script>
Of course, you can also include a library like jQuery to do this for you. Another option (non JS) is to do a POST when the user picks a color and change the stylesheet server side. But that will make the page refresh.
A: Use jQuery:
$(document).ready(function(){
$('#my-button').click(function(){
$('.title-bar').css({'background' : 'red'});
});
});
Edit:
I just hacked together a better (as in "programmatic") solution: http://jsfiddle.net/eNLs6/
$(document).ready(function(){
$('.colorchanger').click(function(){
$('#preview-div').css({'background' : $(this).val()});
});
});
A: I would add a class to the body and then use that in the stylesheet to create different themes.
JS:
$('#red').click(function() {
document.body.className = 'red';
});
CSS:
body.red .title{background:url('red-gradient.png');}
body.red .color{color: red}
/* etc... */
You can of course put each theme in a separate CSS file, to make things easier to organize. But for performance reasons, I suggest you load all CSS at once and just swap classes onclick, instead of a dynamic stylesheet loader .
A: I think the best way to achieve that is to have different div classes for each color (theme in general) and change the css class of the div when button or image clicked :
$('#myRedButton').click(function(){$('#myDiv').attr('class','red')});
$('#myBlueButton').click(function(){$('#myDiv').attr('class','blue')});
And you will have a html looking like
<div id="myDiv">....the div that will have it's color changed </div>
<img src="..." id="myRedButton"/>
<img src="..." id="myBlueButton"/>
A: Create a base stylesheet (base.css) for general stuff and then secondary ones for each colour, eg red.css, blue.css
When a users clicks the red image, it loads the red.css stylesheet.
$('#red').click(function() {
//load red.css
}
See this question on how to change a secondary stylesheet with jQuery for more details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it safe to use PHP exec() to handle system-related tasks on a server? I'm developing an application in PHP and Javascript and I need to set up disk quotas for a given user (as I'm using an FTP daemon (ProFTPd in this case) to allow for users to have their own document manager) so elFinder (which is the document manager I'm currently thinking on using) can run 'freely' (instead of having to create my own PHP function to control how much space is actually being used).
The idea is to run a single command to adjust the disk quota on the server side, but... is it safe to let PHP run system commands (even if I'm not going to accept parameters or allow any kind of user interaction with the system)?
A: Usualy is not safe. It doesn't matter if you let users send commands or any other kind of interactivity. Even if your script runs alone, exploits can be invented to make use of it in one form or another and maybe alter it's actions.
But, this applies only if you want to have insane security rules on your server. In real world, the chance is minimal that you can compromise your server security.
I still have some suggestions for you :
*
*make sure your script does not accept any input from outside, it does not read a database or a file. Everything must be enclosed inside the script.
*Try to put the script somewhere outside the documentRoot so it won't be accesible by users.
*Put some special permissions on the script so that it's actions are limited to the user it runs as. Even if someone breaks it somehow, the OS will not let him do something else than running just that particular command in a particular environment.
This of course may be completed with more rules, but this is just what comes in mind now. Hope it helps
A: It is unsafe if you let the user enter info; POST or GET values without filtering.
If you have to use a GET value the user enters, you should use escapeshellarg() or escapeshellcmd().
*
*http://www.php.net/manual/en/function.escapeshellarg.php
*http://php.net/manual/en/function.escapeshellcmd.php
A: As long as you are not getting any user input and for the command the be run, it is just as safe to use exec() as it is to do it from the command line. If you are going to use user input in the commands, use escapeshellarg() or escapeshellcmd() and it should still be safe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Netty HTTP Authetication for Client Look at the test code I have written below.
Using pure java I set an Authenticator and make a URI call to get some xml data and convert it to an object.
I wrote the code below to test performance of hotpotato (netty) vs. pure java (no pipelining).
The trouble is, I can't figure out how to Authenticate my request with hotpotato or netty, code for either is acceptable, I just want to test the performance diff (i.e. see how many requests will be performed in 5 seconds).
public static void main(String[] args) throws Exception {
Authenticator.setDefault(new MyAuthenticator("DummyUser", "DummyPassword"));
int timeToTestFor = 5000; //5 seconds;
int count = 0;
System.out.println("Start time");
long starttime = System.currentTimeMillis();
do {
URL url = new URL(
"http://example.com/rest/GetData.ashx?what=pizza&where=new%20york&visitorId=12345&sessionId=123456");
SearchResultsDocument doc = SearchResultsDocument.Factory.parse(url);
count++;
} while (System.currentTimeMillis() - starttime < timeToTestFor);
System.out.println("DONE Total count=" + count);
System.out.println("Netty/Hotpotatoe Start time");
count = 0;
starttime = System.currentTimeMillis();
do {
// Create & initialise the client
HttpClient client = new DefaultHttpClient();
client.init();
// Setup the request
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_0,
HttpMethod.GET, "/rest/GetData.ashx?what=pizza&where=new%20york&visitorId=12345&sessionId=123456");
// Execute the request, turning the result into a String
HttpRequestFuture future = client.execute("example.com", 80, request,
new BodyAsStringProcessor());
future.awaitUninterruptibly();
// Print some details about the request
System.out.println("A >> " + future);
// If response was >= 200 and <= 299, print the body
if (future.isSuccessfulResponse()) {
System.out.println("B >> "+future.getProcessedResult());
}
// Cleanup
client.terminate();
count++;
} while (System.currentTimeMillis() - starttime < timeToTestFor);
System.out.println("DONE Total count=" + count);
}
A: Here is working example of using basic authentication with Netty only. Tested with Jetty as a server requiring basic authentication.
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.base64.Base64;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpClientCodec;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.util.CharsetUtil;
public class BasicAuthTest {
private static final int PORT = 80;
private static final String USERNAME = "";
private static final String PASSWORD = "";
private static final String URI = "";
private static final String HOST = "";
public static void main(String[] args) {
ClientBootstrap client = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
client.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("codec", new HttpClientCodec());
pipeline.addLast("aggregator", new HttpChunkAggregator(5242880));
pipeline.addLast("authHandler", new ClientMessageHandler());
return pipeline;
}
});
DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, URI);
request.addHeader(HttpHeaders.Names.HOST, HOST);
String authString = USERNAME + ":" + PASSWORD;
ChannelBuffer authChannelBuffer = ChannelBuffers.copiedBuffer(authString, CharsetUtil.UTF_8);
ChannelBuffer encodedAuthChannelBuffer = Base64.encode(authChannelBuffer);
request.addHeader(HttpHeaders.Names.AUTHORIZATION, encodedAuthChannelBuffer.toString(CharsetUtil.UTF_8));
client.connect(new InetSocketAddress(HOST, PORT)).awaitUninterruptibly().getChannel()
.write(request).awaitUninterruptibly();
}
public static class ClientMessageHandler extends SimpleChannelHandler {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
e.getCause().printStackTrace();
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
HttpResponse httpResponse = (HttpResponse) e.getMessage();
String json = httpResponse.getContent().toString(CharsetUtil.UTF_8);
System.out.println(json);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL SERVER - Create Table by matching rows and columns and put Y or N I currently have a table with all the data, using this data i want to create another table which could be used for auditing purpose (similar layout like pivot table)
Example Below:
Raw Data
Name Places Visited
----------------------------
Will London
John Toronto
Dave New York
Will London
What I want (similar to Pivot Table but I can use letters):
Name/Places Visted London Toronto New York
Will Y N Y
John N Y N
Dave N N Y
Any help to produce this will be much appreciated!
I hope i've explained myself well but let me know if you would like to clarify anything.
Many Thanks!!
A: Solution for SQL Server 2005/2008:
DECLARE @Temp TABLE
(
Name NVARCHAR(100) NOT NULL
,Place NVARCHAR(100) NOT NULL
);
INSERT @Temp
SELECT 'Will','London'
UNION ALL
SELECT 'John','Toronto'
UNION ALL
SELECT 'Dave','New York'
UNION ALL
SELECT 'Will','London';
SELECT
pvt.Name [Name/Places Visted]
,CASE WHEN [London] IS NOT NULL THEN 'Y' ELSE 'N' END [London]
,CASE WHEN [Toronto] IS NOT NULL THEN 'Y' ELSE 'N' END [Toronto]
,CASE WHEN [New York] IS NOT NULL THEN 'Y' ELSE 'N' END [New York]
FROM @Temp src
PIVOT( MAX(src.Place) FOR src.Place IN([London], [Toronto], [New York]) ) pvt
ORDER BY pvt.Name DESC;
Results:
Name/Places Visted London Toronto New York
------------------- ------ ------- --------
Will Y N N
John N Y N
Dave N N Y
Note: Columns resulting from PIVOT operation are static. This means that if you add records with Place='PARIS' you should modify the query like this: PIVOT( MAX(src.Place) FOR src.Place IN([London], [Toronto], [New York], [Paris]). So, you could use PIVOT operator if you have a limited number of cities.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When can multiple ServiceHost instances share the same port? Our application server exposes 5 WCF services over the net.tcp transport, all on the same port. We've been hosting these during development using WcfSvcHost and I've never had to think about how these manage to use the same port.
We're moving them to a Windows Service now, and now I'm instantiating the ServiceHost instances myself. One of the services uses Streamed TransferMode over Tcp.
When starting these services using a configuration file with WcfSvcHost, they work fine. But in our service it complains about the port being in use.
Should it be possible for the streamed service to use the same port?
A: I solved the problem eventually, after alot of trial and error with programmatic configuration of the bindings.
It seems that something in the binding stack generated when you create a NetTcpBinding allows multiple NetTcpBindings to share a port. The problem was that I needed to make a custom binding.
The Solution ended up being to create a custom binding based on a NetTcpBinding. For example:
var lBinding = new NetTcpBinding()
{
SendTimeout = TimeSpan.FromMinutes(5),
ReceiveTimeout = TimeSpan.FromMinutes(5),
MaxConnections = 100,
ReliableSession = new OptionalReliableSession
{
Enabled = true,
Ordered = true,
InactivityTimeout = TimeSpan.FromMinutes(30)
},
Security = new NetTcpSecurity
{
Mode = SecurityMode.TransportWithMessageCredential,
Message = new MessageSecurityOverTcp { ClientCredentialType = MessageCredentialType.UserName }
},
MaxReceivedMessageSize = 524288
};
var lCustomBinding = new CustomBinding(lBinding);
// Edit the custom binding elements here
var lEndpoint = new ServiceEndpoint(lContract, lCustomBinding, new EndpointAddress(pServiceHost.BaseAddresses.First()));
A: I found another solution to for this issue by using a the RoutingService class. Each contract must still be hosted in it's own ServiceHost, but there can be a RoutingService sitting on top of all of them - and presenting them over an unified "endpoint". I've also written a codeproject article about it. The example code is also available on Bitbucket.
A: See here about Net.TCP Port Sharing, which is what you're looking for.
You've got to enable the service for that too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to expect that the '=' method runs for the 'session'? I am using Ruby on Rails 3.1.0 and the rspec-rails 2gem. I would like to test if some session data has been set to nil.
In my controller I have:
def create
...
session[:user] = nil
...
end
In the related spec file I would like to make something like the following:
it "should be set to nil" do
# Here I would like to expect if the 'session[:user]' is set to 'nil'
# NOT using this approach:
#
# session[:user].should be_nil
#
# That is, I would be sure that the 'session[:user] = nil' runs the same way
# I may do with method "expectation". For example:
#
# mock_model(User).should_receive(:find).and_return(nil)
#
# Maybe a solution can be similar to this (note: of course, the following
# doesn't work):
#
# session[:user].should_receive(:"=").and_return(nil)
post :create, { ... }, { ... }
...
end
Is it possible? If so, how?
P.S.: I would like to use that approach in order to check some particular internal behavior.
UPDATE ... and how can I test the following?
session[:user][:nested_key] = nil
A: The method your are looking for is []=:
session.should_receive(:[]=).with(:user, nil)
This feels really invasive to me, however. Not that I'd never do it, but I'd question why you don't want to just test the outcome?
session[:user] = 37
post :create # ...
session[:user].should be_nil
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Touch events not get triggered on SVG document Touch events do not get triggered on SVG document when a USE element has been used to draw a shape(via, xlink:href). The USE element references another element and indicates that the graphical content of the element is drawn here. However, touch events get triggered on the document in the absence of USE element.
Can anyone help me if am doing anything wrong?
This example shows the working touch events: http://jsfiddle.net/qGWQj
This examples doesn't work: http://jsfiddle.net/5gAPn/1
The problem happens on the iPad using iOS 4.3.5.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can't find layout ID for < 1% of users? I have an app which gets several thousand users a day. I'm getting a handful of reports through marketplace that my entry activity can't load its layout xml resource. I don't see how this could be possible?:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.me.app/com.me.app.MyActivity}: **android.content.res.Resources$NotFoundException: Resource ID #0x7f030065**
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f030065
at android.content.res.Resources.getValue(Resources.java:896)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:1873)
at android.content.res.Resources.getLayout(Resources.java:735)
at android.view.LayoutInflater.inflate(LayoutInflater.java:318)
at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
at android.app.Activity.setContentView(Activity.java:1657)
at com.me.app.MyBaseActivity.setContentView(MyBaseActivity.java:50)
at com.me.app.MyActivity.onCreate(MyActivity.java:116)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
... 11 more
The exception points to this line:
setContentView(R.layout.my_layout);
Any ideas what I could be doing wrong here? Again, for 99% of users, no problem.
Thank you
A: I agree with the comments on the question that troubleshooting resource ID 0x7f030065 is the key to understanding these error reports.
I'm assuming that resource is NOT the my_layout file. Despite my_layout being pointed to as the line of the problem, it most likely is not the root issue. Something inside the my_layout file is referring to resource 0x7f030065. The layout inflater often does not report these errors very clearly.
If there isn't a version of 0x7f030065 in a default folder (ex: drawable instead of drawable-landscape), then perhaps the 1% is running in a configuration that can't find it is falling back to the non-existent default. This could be possible even if your app is locked in landscape orientation for instance - occasionally a portrait draw could still happen - even if it's not visible to the end user.
Is it always the same resource id? That's a good thing to pay attention to.
In my experience, other issues like running out of memory can cause these sorts of inflate time exceptions. If resource 0x7f030065 refers to a custom layout class, then anything that happens in the constructor of that class could possibly result in a Resources$NotFoundException
A: I have experienced something similar.
I was having an activity that I wanted to show only in landscape - so in AndroidManifest.xml I had android:screenOrientation="landscape".
Than a folder layout-land and there my layout file.
From time to time, randomly, I was getting a Resources$NotFoundException when the activity was trying to load the main layout.
I solved it by renaming folder layout-land to layout.
But I think we hit some kind of bug in android.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: how to prevent multiple inserts when submitting an ajax form On this problem some more people have stumbled and for non-ajax scenario there is already a solution :
How to prevent multiple inserts when submitting a form in PHP?
(answered Jan 25 '10 at 17:02)
I'd like to know how could be implemented efficiently on both the server and client side a similar solution for the following problem :
*
*there is a wall listing containing multiple items on which the users can click an ajax-enabled "i like" button (no page reload)
*the user can have multiple browser windows opened on which can click "i like" buttons
Expected :
Only the first click on the "I like" button for any of the wall items is taken at the server side into account and the following requests for the wall item are not handled anymore.
A: Keep track of the liked items of each user on the serverside (for example an extra database table). When a new like is going to be inserted, check if there is already an existing record in this table. If there is, the user has already liked this item and you dont't have to count it anymore.
A: I think the best way is to use a session variable that store the current state, ie when someone clicks you "i like", on the server side, you check the state of the SESSION var.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android How to call OnFling when Swiping anywhere in the Activity not only in the ViewFlipper In my viewFlipper some TextViews are loaded dynamically. The size may differ which means that under the viewFlipper there could be some space left (see the green part in the screenshot)
screenshot
I want the onFling method to be called not only when swiping on the grey part (which is the viewflipper) but also when swiping on the green part
my layout looks like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/root">
<ViewFlipper android:id="@+id/viewFlipper"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ViewFlipper>
</RelativeLayout>
In my onCreate i do this:
this.viewFlipper = (ViewFlipper) this.findViewById(R.id.viewFlipper);
this.gestureDetector = new GestureDetector(new MyGestureDetector());
RelativeLayout root = (RelativeLayout) this.findViewById(R.id.root);
root.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
Log.d("root", "true");
return false;
} else {
Log.d("root", "false");
return false;
}
}
});
So far I tried to return false even if I get true, so that the event does not get consumed and gets passed down to the viewFlipper even if the swipe has been made outside the viewflipper.
Note that the viewFlipper does not need any explicit onTouchListener. It works with or without one ( I dont really understand why..)
Does anyone know what to do?
A: Try adding android:clickable="true" to your RelativeLayout and you should be able to do it.
If that doesn't work you might need to implement these two methods also (if you haven't allready):
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//TouchEvent dispatcher.
if (gestureDetector != null) {
if (gestureDetector.onTouchEvent(ev))
//If the gestureDetector handles the event, a swipe has been executed and no more needs to be done.
return true;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Unable to upload themes to my WordPress installation I am unable to upload themes to my WordPress installation via WordPress admin. I am getting the following error:
The uploaded file could not be moved to /home/debiprasad/webapps/wordpress/wp-content/uploads/2011/09
The permission of wp-contents directory and all sub directories are: 0755. Some people may suggest to make it 0777. This may work, but I don't think this is the correct solution. Because, all the folders should be have permission 0755 and this is secure. 0755 is the default and it works in other installations.
I want to know what's the reason of this error and what is the perfect and secure solution?
A: Assuming you use Apache, is your uploads folder owned by www-data? (or whatever user apache/php run as?)
If you have access to change ownership, 0755 should work as long as the upload folder (and subdirectories within) are owned by the same "user" that the web server runs as - so in most cases, that'll be www-data.
If this doesn't work, what method do you use to install themes? ftp, ftps or ssh2?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tracking down null-reference error in Windows Service Application - whats going on here? I'm making a data-adapter service, and i need to take a backup of the affected tables before messing with the data. I'm using calling the external process "mysqldump.exe" and everything works fine from a command-line - but the service throws a null-reference error when initiating a backup.
As you can see in the code, I've tried very hard to pinpoint where the error happens (the exception is caught and written to the Windows Application Log in my controller layer), but none of my own Exceptions gets thrown, so I end up none-the-wiser.
here we go:
public static string Backup(string host, string database, string dbUser, string dbPwd, string[] tables, string OutputFile, out bool succes, string fileRoot)
{
Process myProcess = new Process();
int debug = 0;
try
{
myProcess.StartInfo.FileName = fileRoot + "Backup\\mysqldump.exe";
debug++;
myProcess.StartInfo.UseShellExecute = false;
debug++;
myProcess.StartInfo.CreateNoWindow = true;
debug++;
myProcess.StartInfo.RedirectStandardOutput = true;
debug++;
myProcess.StartInfo.RedirectStandardError = true;
debug++;
succes = false;
}
catch
{
throw new Exception("BackupMetoden blev afbrud ved en fejl under instantieringen af mysqldump.exe\r\n\r\nDebug niveau: " + debug);
}
//Rediger Arguments
debug = 0;
string output = "";
try
{
string args = "-h " + host + " " + database + " --tables #TABELLER#" + "--user=" + dbUser + " --password=" + dbPwd + " --result-file " + OutputFile;
debug++;
string tabeller = "";
debug++;
foreach (string t in tables)
{ tabeller += t + " "; }
debug++;
args = args.Replace("#TABELLER#", tabeller);
debug++;
myProcess.StartInfo.Arguments = args;
debug++;
output = "Ingen backup udført - der er sket en fejl";
}
catch(Exception ex)
{
throw new Exception("BackupMetoden blev afbrud ved en fejl under samling af kommando-syntaks\r\n" + ex.Message + "\r\nDebug niveau: " + debug);
}
try
{
myProcess.Start();
output = myProcess.StandardError.ReadToEnd();
succes = true;
}
catch(Exception ex)
{
succes = false;
throw new Exception("Der opstod en fejl under backup: " + output + "\r\n" + ex.Message + "\r\n\r\n" + ex.StackTrace);
}
return output;
}
I know for sure that the error is thrown within the code above, because the Exception is wrapped in a message by the calling method:
try
{
resultat = VDB_MysqlBackupRestore.Backup(indstillinger.Host(kilde), indstillinger.DB(kilde), indstillinger.User(kilde), indstillinger.Pass(kilde), tables, outputFile, out succes, rodmappe);
return resultat;
}
catch (Exception backupfejl)
{
throw new Exception("Der opstod fejl under uførelsen af backup i controller-laget: " + backupfejl.Message);
}
...And the wrapping message shows up in the application-log like this:
Der opstod fejl under uførelsen af backup i controller-laget: Object reference not set to an instance of an object.
I'm building it in Visual Studio 2010 on a Windows 7 32bit. It's been tested both locally and on a Windows 2008 Web server with the same result. I'm using the .net 4 framework
A: you are catching the exceptions in a very wrong way, inside the catch block if you really want to create a new exception and throw it, don't create a new base Exception but an ApplicationException or other derived class from Exception and make sure you pass to such constructor call the actual exception of the catch block, like ex; you should pass the ex object not only the ex.Message or you are going to hide the real exception and all its properties like callstack, inner exception and so on....
A: Probably the object indstillinger is null, or some of its internal things and when you try to use it, it throws an NullReferenceException.
Try to run this in a Console application and step through the code and you'll spot the error.
Or even better, have a look at the Topshelf project and implement your Windows service using that. It's a much more pleasant way to develop Windows Services.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Browser's repainting is very slow when using jquery addClass and removeClass I have a page where I need to dynamically add or css classes. I have the following Jquery code in my page,
myElementsList.addClass('AClass').removeClass('BClass')
These css classes will change the color and background color of my elements. The problem is that this takes 2 or 3 seconds to repaint the browser.
If i use css classes which does not eXist(or does not repaint the browser) then it will eecute very quickly.
myElementsList.addClass('NotEXistClassA').removeClass('NotEXistClassB')
Any suggestion will be welcome?
Edit:
The way I solve this issue by changing the first 20 rows first and changing the remaining using a timer. I am also reseting this timer every time if the events raised again before the timer elapased.
Any other suggestion is welcome.
A: The problem here is that you are trying to get the browser to do two things at once, which both require it to repaint the same things.
But in fact you can achieve what you want to do (change the colour of the rows) by only doing one of the two actions.
The basic change you need to make is not to have a style for "not-selected" and another style for "selected", but instead to have one for "default" and one for "selected".
Then you can have the "default" style to set the standard colour, and simply add the "selected" style to override it; you don't need to remove the default style, as the selected one will override it.
Here's a simple bit of CSS to get you started:
.grid tr {
background: #FFFFFF; /*default white background*/
}
.grid tr.selected {
background: #222222;
}
...and the script would just do addClass('selected') when you select it, and removeClass('selected') when you deselect it.
There really is no need for a not-selected class at all.
That simple change will remove a full half of the work that your program is doing when you toggle the selection, and in fact it will quite possibly speed it up by more an 50% due to it not having to do multiple re-paints on the same elements.
That will certainly get you going a bit faster. It isn't the whole story as to why your page is slow, but it will certainly help a lot.
A: First remove class then assign new class
myElementsList.removeClass('BClass').addClass('AClass');
I think this may help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Entity Framework One-To-Many Insert - Foreign Key violation I'm using Entity Framework for the first time and I'm trying to create a object with a collection (and I want all the objects in the collection to be created in database as well) but I'm having some foreign keys violations.
My sample tables:
table APPOINTMENTS: ID, VAR1, DATE_APPOINTMENT
table GUESTS: ID, APPOINTMENT_ID, USER_ID, VAR2, VAR3
My test code:
DomainService aux = new DomainService();
APPOINTMENTS appointment = new APPOINTMENTS();
appointment.VAR1 = "BLA";
appointment.DATE_APPOINTMENT = new DateTime();
//The user with id = 1 is already created in the database
appointment.GUESTS.Add(new GUESTS { USER_ID = 1, VAR2 = 1, VAR3 = "F" });
aux.InsertAppointment(appointment);
At DomainService I have:
public void InsertAppointment(APPOINTMENTS appointment)
{
using (var context = this.ObjectContext)
{
context.AddToAPPOINTMENTS(appointment);
context.SaveChanges();
}
}
But I'm getting this error:
{"ORA-02291: integrity constraint (FK_GUESTS_APPOINTMENTS) violated - parent key not found"}
What am I doing wrong?
UPDATE:
To create the ID's in the database, I am using a sequence for each table and a trigger before insert to get the next value.
When I create a single object, e.g. a appointment without guests, it inserts in the database and it generates the id.
A: The solution to this problem:
"The ID fields that are generated from sequences won't be handled
correctly. After saving the entities the ID's will be returned as 0.
I'll fix this by manually hacking the SSDL (open your .edmx file in a
text editor) with StoreGeneratedPattern="Identity" attributes on the
ID fields (lines 6 and 16). Note that designer may rip that change out
upon future modification.
While I suppose it's not absolutely necessary it might also be prudent
to modify some type metadata such as changing "number"s to "int"s in
your SSDL and "Decimal"s to "Int32"s in your CSDL where applicable.
Frequently these don't auto-generate with the desired values
especially with XE."
@http://www.chrisumbel.com/article/oracle_entity_framework_ef
A: As for me, the problem was solved simply by opening diagram .edmx and changing property StoreGeneratedPattern from None to Identity for each Primary Key in each table. After saving everything was fine.
I'm using VS 2012, Entity Framework 5 (6 is not supported yet), Oracle 11.2, last ODP.NET 12, .Net 4.5
A: In case of EF code first approach, if this error come
(ORA-02291: integrity constraint (FK_GUESTS_APPOINTMENTS) violated -
parent key not found)
In my case there are 2 tables which have Identity columns. So I just added
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
property to my model class just above the the column which is identity column in database and it solved my problem :)
Hope this help :)
A: I cant see where you are setting your Primary Key (the ID property of the appointment class). Are you using a key generator on the database side? If not this should be the problem.
A: You're inserting a record with a foreign key value that is not found in the parent table that constraint refers back to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Using a library written in C++ from a pure C project on Linux? Found this statement over at PSE: (quoting Bob)
One of my favorite tricks on Windows and Mac OS doesn't work on Linux.
That trick is to write a DLL/dylib using C++ internals, export a C
API, and then be able to call into it from C programs. Linux shared
objects (the local equivalent of a DLL) can't really do that easily,
because the C++ standard library .so isn't in the default search path.
If you don't do a bunch of weird stuff to your C program, it will fail
as soon as it dynamically loads your .so at runtime: your .so will try
to dynamically load the standard library .so, it won't find it, and
then your program will exit.
I find that a bit odd. How accurate is this, factoring in possible differences between the major desktop/server distros of Linux?
This is purely out of curiosity, as I do Windows only (C++) programming at the moment.
As for Windows, I had to do a bit of lookup and I'll put it here for reference:
A C++ executable will normally link to MSVCR*.DLL for the C std library and MSVCP*.DLL for the stuff of the STL that resides in this DLL. Both of these either reside in the system32 directory, or, for the manifested stuff they'll reside in a subdir of Windows SideBySide cache (winsxs folder).
A: I am doing this thing all the time, and it works fine. I am pretty sure that that guy had a totally unrelated problem and blamed the library search paths for it.
I have never seen any linux distro where the libstdc++.so is not in the /usr/lib[64]/ path.
Which also makes me wonder how C++ programs generally work for that guy, since to my knowledge the search path for .so files is language agnostic.
Maybe he always uses a special version and compiles all his programs with -rpath linker options? But even then, just adding that option to his C programs would work too.
it will fail as soon as it dynamically loads your .so at runtime: your
.so will try to dynamically load the standard library .so, it won't
find it, and then your program will exit.
This makes me wonder if he solely refers to using dlopen() on your own .so. But also then it works just fine, unless you did not link the .so to your libstdc++.so (which would then be your own fault; it would be the same problem had you dependencies on any other library, regardless what language it was written in).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to correctly set icon size of a button in extjs? I'm using extjs4 and What i'm trying to do seems to be simple but i can't find a working solution for it.
I have a 64*64px icon and i want my button to show it as the background image but extjs only shows the image partially.Googled on the net for a solution but nobody suggested a working solution for it.I just want my background image fit to my button.
here is my js code:
{
xtype : 'button',
text : null,
iconCls : 'startbutton',
//icon:'./assets/icons/startbtn.png',
//style:{height:'60px'},
width : 64,
height : 64
}
here is my css code:
.x-btn-icon .startbutton {
background-image: url(start.png) !important;
}
i tried some css combinations and still no success.
A: I had an important issue with the accepted answer.
The button text (left button in picture, below) appeared in the wrong position (behind the icon) - the position it was configured to be using the default scales.
In order to use an other-than-default icon size and place the text in the correct position, my solution was fairly simple, without overriding core styles.
I just replaced the text property with the html property.
Then, I placed the desired button text within a 'span' and added a class to this span in order to position it correctly with CSS.
This is the code (tested on IE , Firefox , Chrome):
Button definition
xtype:'button',
iconCls:'contactIcon80',
iconAlign:'top',
width:120,
height:100,
html:'<span class="bigBtn">Damn you hayate</span>'
Button iconCls
.contactIcon80 {
background-image: url(../images/calendar80.png) !important;
width:80px!important;
height:80px!important;
margin-right: auto !important;
margin-left: auto !important;
}
Span class
.bigBtn {
position: absolute;
bottom: 4px !important;
left: 0% !important;
text-align: center !important;
width: 120px !important;
}
Of course this is for icon top text bottom.
You can customize it for other layouts
A: Although this won't directly help if you're image is 64px high/wide, the following config 'scale' option can be used to adjust the size of a button:
•'small' - Results in the button element being 16px high.
•'medium' - Results in the button element being 24px high.
•'large' - Results in the button element being 32px high
A: The iconCls refers strictly to the icon of the button, if you want the picture to cover the whole button you should add the background to a css class added to the button.
{
xtype: 'button',
width: 64,
height: 64,
text: 'some text',
cls: 'startbutton'
}
and the css
.startbutton {
background-image: url(start.png) !important;
}
A: I'm using ExtJS 3.4.0 and i don't know if this is any easier in 4.x but i hope so!
I have solved the issue creating new button styles besides small/medium/large, then on the button specifing:
{ text: 'Read Data',
scale: 'extra',
iconAlign: 'left',
iconCls:'read_icon'}
CSS code must be specified for each side you're gonna use the icon, in my case i've just defined for left side, but you have to clone for each side top/bottom/right/left.
You can find all the original code inside ext-all.css, here's what i'm using for a 64x64 icon
.x-btn-text-icon .x-btn-icon-extra-left .x-btn-text{
background-position: 0 center;
background-repeat: no-repeat;
padding-left:66px;
height:64px;
}
You can re-use the code for all the 'extra'-sized buttons in your project and you can add as many you want
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: MySQL: Return row if joined table contains least one match
(Main table id equal to jid. Join based on that.)
The 1st item has got 2 row in the join table. /That's great./
But 3rd item has got no row in join table.
The question: How can i ignore those items that has got no joined rows? IN ONE QUERY.
I tried the following:
SELECT *
FROM mainTable AS mainT
LEFT JOIN joinTable AS joinT ON mainT.id=joinT.jid
WHERE COUNT(joinT.id) > 0
A: Replace LEFT JOIN with INNER JOIN, and remove the WHERE clause.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: javascript window.location and IE session variables are lost I am loosing session variables when using Internet Explorer (IE 9) when using the javascript
window.location function.
I have noticed that the page before and the page after displays the same session ID; but the
session variables are lost when the redirect occurs even if the session ids are the same.
I have also noticed that this does not happen each and every time in IE, only some times(Random).
With Chrome I experience no problems.
The live application is here: http://apps.facebook.com/zabeachwatch/
(When you view the Video it should time-out and redirect you back after some time has elapsed.
If you land up on a registration page, this means that the session variables have been lost. This should not happen when accessing the page via facebook)
Is there perhaps some other way to redirect on a timer event?
Below is a snippet that causes the redirect.(window.location...)
<%
String cat = request.getParameter("cat");
String back_url = "CameraList.jsp?cat=" + cat;
back_url = response.encodeURL(back_url);
%>
<script type="text/javascript" language="javascript">
<!--
var winW = 630, winH = 460;
function delayer(){
var s = "<%=back_url%>";
window.location.href = s;
return true;
}
<body id="images" style="background: rgb(197,204,211)
url(images/stripes.png);" onload="setTimeout('delayer()', 30000);
A: I have found that the "window.location.href" does not work as expected with INTERNET EXPLORER
8 and 9.
An alternative approach that works for me is to use the meta tag "refresh" together with some other
logic to get the same result. In my case it was a simple timeout function.
<meta http-equiv="refresh" content="60"/>
Good Luck
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't read CLOB into string... sometimes I have an array of CLOB datatypes. In my sample data, there are two items in the array. The array is embedded in a FOR loop that will loop until all of the data is read from the array (in this case, twice). I have a function that reads the CLOB data into a string, then returns the string, literally just:
function getCLOB($clob)
{
$str = $clob->read($clob->size());
return $str;
}
My problem is that it reads in the first thing I send it fine and I can get that to display back in the FOR loop. However, when I send the second one, the string is empty. I put in some echos to see what was happening with the data and the $clob variable has data once it's in the function, but the $str variable is empty after the first line of the function. Does anyone have any ideas on why it works once but not the second time?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Data Service Reflection Provider in ASP.NET MVC I have a existing model with classes that reads the model from a number of files from disk. I use this in a current ASP.NET MVC project and to read the correct files from disk the classes handling the read needs a version URL parameter and a Request.PhysicalApplicationPath parameter. This is easy when I'm in a ASP.NET MVC controller and have the Request object and the incoming parameters form the URL.
When I then however want to use a Data Service class to expose my model I first need to be able to send the same URL parameter and the Request object to the classes for reading the model. I don't get how I should be able to access the URL parameters and the Request object when I'm in my svc file or how I should be able to get these to the "context" object with the get property that I have to read my model?
Update:
I would like to have something like the below where "23456" would then be the version number that I can forward to my classes that reads the model from disk and the rest is queries I pass on to the DataService to do it's magic.
http://MySite/23456/MyService/Category(1)/Products?$top=2&$orderby=name
So basically - is it possible to both use MVC for routing and parameter control etc and then pass the rest of the query to DataService to get the full flexibility of asking URL based questions?
A: I think you are asking how to provide some context-specific data that is available in your controller to an underlying service (a data service in this case).
Typically, the easier and most straightforward way to do that is to make it the responsibility of the controller to pull out context-specific data and forward it along to the service as standard method parameters.
Is there something about your current situation that prevents you from grabbing the Version and Url data in the controller and passing them down to the service tier?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Grabbing a specific element of an array in Objective-C I'm splitting a string by ';', but want to specifically grab the first and second element.
I know with PHP it's just simply $array[0], just can't find anything for this for Objective-C
NSArray *tempArray = [returnString componentsSeparatedByString:@";"];
So here I have assigned my array, how can I go about getting the first and second element?
A: Starting with XCode 4.5 (and Clang 3.3), you may use Objective-C Literals:
NSString *tmpString1 = tempArray[1];
A: NSString *tmpString = [tempArray objectAtIndex:0];
NSLog(@"String at index 0 = %@", tmpString);
NSString *tmpString1 = [tempArray objectAtIndex:1];
NSLog(@"String at index 1 = %@", tmpString1);
You may also wish to do an IF statement to check tmpArray actually contains objects in before attempting to grab its value...
e.g.
if ([tempArray count] >= 2) {
// do the above...
}
A: Its just simply [array objectAtIndex:0] in Objective-C ;-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How to access gallery folder on an android device I want to retrieve a video or image from the gallery folder. In my honeycomb tablet I don't have a sdcard. Can anybody tell me how to retrieve the image or video in android?
Thanks
A: Use the MediaStore content provider to find indexed media on the device. The Gallery application, for example, uses MediaStore -- there is no "gallery folder".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rotate an jpg on the iPhone I have an app that takes the photos via the camera or select it from the library and save it as jpg in the documents folder. But before saving it, I would like to rotate is by 90degrees.
Hope anyone can help me out here.
Thanks
A: For iOS 4 and later:
UIImage imageWithCGImage:scale:orientation:
For iOS 3 and previous:
How to Rotate a UIImage 90 degrees?
static inline double radians (double degrees) {return degrees * M_PI/180;}
UIImage* rotate(UIImage* src, UIImageOrientation orientation)
{
UIGraphicsBeginImageContext(src.size);
CGContextRef context = UIGraphicsGetCurrentContext();
if (orientation == UIImageOrientationRight) {
CGContextRotateCTM (context, radians(90));
} else if (orientation == UIImageOrientationLeft) {
CGContextRotateCTM (context, radians(-90));
} else if (orientation == UIImageOrientationDown) {
// NOTHING
} else if (orientation == UIImageOrientationUp) {
CGContextRotateCTM (context, radians(90));
}
[src drawAtPoint:CGPointMake(0, 0)];
return UIGraphicsGetImageFromCurrentImageContext();
}
A: You can do it like
static inline double radians (double degrees) {return degrees * M_PI/180;}
UIImage* rotate(UIImage* src, UIImageOrientation orientation)
{
UIGraphicsBeginImageContext(src.size);
CGContextRef context = UIGraphicsGetCurrentContext();
if (orientation == UIImageOrientationRight) {
CGContextRotateCTM (context, radians(90));
} else if (orientation == UIImageOrientationLeft) {
CGContextRotateCTM (context, radians(-90));
} else if (orientation == UIImageOrientationDown) {
// NOTHING
} else if (orientation == UIImageOrientationUp) {
CGContextRotateCTM (context, radians(90));
}
[src drawAtPoint:CGPointMake(0, 0)];
return UIGraphicsGetImageFromCurrentImageContext();
}
Taken from here
A: img.transform = CGAffineTransformMakeRotation(3.14159265/2);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Daemon process cannot survive suspend I am writing daemon application for Debian Sid. It works perfectly most of the times, but dies silently after i put my laptop to suspend (or hibernate). So i have a couple of questions:
*
*What should I Google for solutions?
*Maybe, you have any ideas what is going on?
A: Try strace-ing the daemon to see what is the reason it dies silently. Generally, suspend/hibernate alone should have no effect on user processes.
A: Daemon's loop was on blocking read call, and suspend (hibernate) interrupts it. So, should check errnos more accurately.
Fixed by adding:
if ( errno == EINTR ) continue;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Sharepoint Client OM: Create a document in a library from an existing document template I am currently finding my feet with the Sharepoint 2010 client object model. I have a C#.net winforms application from which i need to access sharepoint.
I would like to programatically create a new document in a document library based on one of the document templates configured for that library. (Basically replicate the New Document drop down button functionality).
Desired functionality:
*
*Show a form with the available content types. (i can do this, i load the list.ContentTypes for my library) Then i allow the user to select one of these content types.
*Use the content type to create a document based on the Document Template that is configured for that content type. So there now exists a new document in the library with the content as sourced from the template doc.
*Open the new document.
When i get to point 2 I'm stuck - I expect there to be some sort of Create New Doc From Content Type/Template functionality, but i can't find it.
Can anyone set me on the correct path to working this out?
Cheers!
Jamie
A: SharePoint has a specific pattern for creating and adding item to SPList - you can't create item which doesn't belong to list. Note that lists and document libraries are both instances of SPList in object model.
So you need to get reference on your SPList - use SPWeb.Lists collection http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.lists.aspx. TryGetList method is the best IMO.
After that call one of the Add method to create item in list http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splist_methods.aspx.
You can change content type of newest created item by using this approach http://social.msdn.microsoft.com/forums/en-US/sharepointdevelopment/thread/c99b4599-0864-48bb-9977-2dd2066fbbb8. Call Update on item to apply content type.
Then set needed fields values for item.
Then call Update on item to save it to database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Serializing with ProtoBuf.NET without tagging members I've read somewhere a comment by the author of ProtoBuf.NET that:
There are options to automatically infer the numbers, but that is brittle and not recommended. Only use this if you know you never need to add more members (it orders them alphabetically, so adding a new AardvarkCount will break everything).
This is exactly that sort of situation I am interested in :)
I have something that is akin to a map-reduce scenario where I want to serialize results generated on remote machines using protocol buffers (e.g. the "map" side of map-reduce) and later read them and combine those results for further processing (e.g. the "reduce" side).
I don't want to start an attribute decoration marathon over every possible class I have that might get serialized during this process, and I do find the protocol buffers to be very alluring as I can create result with Mono and consume them effortlessly on MS.NET and vice-versa...
The apparent downsides of not pre-tagging the members doesn't bother me as exactly the same software revision does generation/consumptionn, so I don't need do worry about new members popping up in the code and messing my whole scheme...
So in short, my question is:
*
*How do I do it (Serialize with ProtoBuf.NET without tagging/building Meta classes on my own)?
*Is there any hole in my scheme that I've glaringly missed?
A: If you can live with a single attribute, then the trick is:
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
public class WithImplicitFields
{
public int X { get; set; }
public string Y { get; set; }
}
there are 2 options here; AllPublic works like XmlSerializer - public properties and fields are serialized (using the alphabetic order to choose tag numbers); AllFields works a bit like BinaryFormatter - the fields are serialized (again, alphabetic).
I can't remember if this is yet available on the v2 API; I know it is on my list of things to ensure work! But if you want it in v2 without any attributes, I'm sure I can add an Add(ImplicitFields) overload.
As long as the 2 ends are never out of step, this is fine. If you store the data, or don't version the two ends "in step", then there could be problems. See also the intellisense comments on the enum (which pretty much repeats the warning that you are already aware of).
A: I had the same problem and that how I've resolved it with TypeModel. It's based on properties ordered by their name (however it doesn't check on property setter/getter existence or serialize-ability of a given type):
[TestFixture]
public class InferredProtoPoc
{
[Test]
public void UsageTest()
{
var model = TypeModel.Create();
// Dynamically create the model for MyPoco
AddProperties(model, typeof(MyPoco));
// Display the Generated Schema of MyPoco
Console.WriteLine(model.GetSchema(typeof(MyPoco)));
var instance = new MyPoco
{
IntegerProperty = 42,
StringProperty = "Foobar",
Containers = new List<EmbeddedPoco>
{
new EmbeddedPoco { Id = 12, Name = "MyFirstOne" },
new EmbeddedPoco { Id = 13, Name = "EmbeddedAgain" }
}
};
var ms = new MemoryStream();
model.Serialize(ms, instance);
ms.Seek(0, SeekOrigin.Begin);
var res = (MyPoco) model.Deserialize(ms, null, typeof(MyPoco));
Assert.IsNotNull(res);
Assert.AreEqual(42, res.IntegerProperty);
Assert.AreEqual("Foobar", res.StringProperty);
var list = res.Containers;
Assert.IsNotNull(list);
Assert.AreEqual(2, list.Count);
Assert.IsTrue(list.Any(x => x.Id == 12));
Assert.IsTrue(list.Where(x => x.Id == 12).Any(x => x.Name == "MyFirstOne"));
Assert.IsTrue(list.Any(x => x.Id == 13));
Assert.IsTrue(list.Where(x => x.Id == 13).Any(x => x.Name == "EmbeddedAgain"));
}
private static void AddProperties(RuntimeTypeModel model, Type type)
{
var metaType = model.Add(type, true);
foreach (var property in type.GetProperties().OrderBy(x => x.Name))
{
metaType.Add(property.Name);
var propertyType = property.PropertyType;
if (!IsBuiltinType(propertyType) &&
!model.IsDefined(propertyType) &&
propertyType.GetProperties().Length > 0)
{
AddProperties(model, propertyType);
}
}
}
private static bool IsBuiltinType(Type type)
{
return type.IsValueType || type == typeof (string);
}
}
public class MyPoco
{
public int IntegerProperty { get; set; }
public string StringProperty { get; set; }
public List<EmbeddedPoco> Containers { get; set; }
}
public class EmbeddedPoco
{
public int Id { get; set; }
public String Name { get; set; }
}
And that's what you get from running it.
message EmbeddedPoco {
optional int32 Id = 1;
optional string Name = 2;
}
message MyPoco {
repeated EmbeddedPoco Containers = 1;
optional int32 IntegerProperty = 2;
optional string StringProperty = 3;
}
For performance, you could opt to compile the TypeModel, and/or store the generated proto for future uses. Beware however that hidden dependency on Protocol Buffer could be dangerous in the long run if the poco (Plain old container object) evolves.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Strange array behavior in Java This is a simple array declaration and initialization.
int arr[] = new int[10];
for(int i = 0; i<arr.length; i++){
arr[i] = i;
}
This
System.out.println(arr[000001]);
to
System.out.println(arr[000007]);
prints out the correct values but anything above 8
System.out.println(arr[000008]);
produces a java.lang.RuntimeException: Uncompilable source code
Why does this happen?
A: It's because the 0's in front of your index make Java think you're using the octal numbering system.
A: It has nothing to do with arrays.
Integer literals that start with a 0 are expected to be octal numerals.
Therefore, if you have any diggit bigger than 7 (i.e. 8 or 9) in there, then it won't compile.
Also: you only get an Exception because your IDE allows you to execute code that doesn't compile. That's a very bad idea, you should look at the compiler error it produces instead (it will probably have much more information than the message you posted).
A: It happens because 000001 , 000007, 000008 is octal notation. Integer literals starting with 0 is treated as octal. However there is no such thing as 000008 in a base 8 numeral system (octal).
(Though, I would have expected that to fail during compile time, not runtime)
A: This has nothing to do with arrays; integers starting with the digit 0 are octal (base 8). The legal octal digits are 0-7, so that 08 (or 00000008) are invalid octal integer literals. The correct octal for 8 is 010.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: JQuery/AJAX: How to pass variables to some JS-API? I have a problem with passing JS-defined Variables from an AJAX response to a JS-API, namely Googles jsapi. What I want to do is display a chart using this API and then use AJAX from time to time to reload the values from a database.
So far, everything works just fine. But as I return these variables by AJAX - how can I get JS to parse the result?
The code:
<div id="t">
xyz
</div>
<script>
window.setInterval(function()
{
$.post('mod/script.php', function(data) { $('#t').html(data) } );
}, 5000);
</script>
Where script.php would return values like
echo "data.addRows($datasets);";
echo "data.setValue($i, 0, '$date $time');";
Problem is, that I dont know, which values are returned by the script. This depends on what is currently stored in the database.
How to do this right? I have some ideas, but I wonder what is the most convenient way here...
A: If I get you right, you want to execute certain JS callbacks in the context of the current document, is that right?
The proper way would be JSONP.
A really really really quirky "alternative" would be to do this in your script.php:
echo "(function(){";
echo "data.addRows($datasets);";
echo "data.setValue($i, 0, '$date $time');";
echo "})()";
and have this callback:
$.post('mod/script.php', function(callback){ eval(callback); });
Also, see this fiddle: http://jsfiddle.net/EsytA/1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding a delay before keyup() fires in jQuery I have read through some of the suggested questions but I am not sure exactly how to implement them:
*
*(jquery/js) - get text from field on keyup, but with delay for further typing
*How to delay the .keyup() handler until the user stops typing?
*How to trigger an onkeyup event that's delayed until a user pauses their typing?
I have 8 textboxes, 7 are used for numeric input and the 8th is a total.
i.e. 7.5 + 7.5 + 7.5 + 7.5 + 7.5 + 0.0 + 0.0 = 37.5
I have the jQuery working so that it monitors each textboxes keyup() and adds all of the values and calculates the total.
I decided that I want to format the users input in the 7 textboxes so that it comes out like #.# if they enter "1" or ".1" i.e. "1.0" or "0.1".
The problem is that I need to add a delay before the input is formatted and I am unsure as to how I do it with javascript and/or jquery.
<script type="text/javascript">
$(function () {
var content = $('input[id*="txtMondayHours"]').val();
$('input[id*="txtMondayHours"]').keyup(function () {
if ($('input[id*="txtMondayHours"]').val() != content) {
content = $('input[id*="txtMondayHours"]').val();
$('input[id*="txtMondayHours"]').val((new Number($('input[id*="txtMondayHours"]').val())).toFixed(2));
var hoursMon = new Number(content);
var hoursTue = new Number($('input[id*="txtTuesdayHours"]').val());
var hoursWed = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
}
});
var content2 = $('input[id*="txtTuesdayHours"]').val();
$('input[id*="txtTuesdayHours"]').keyup(function () {
if ($('input[id*="txtTuesdayHours"]').val() != content2) {
content2 = $('input[id*="txtTuesdayHours"]').val();
var hoursMon = new Number(content2);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
}
});
var content3 = $('input[id*="txtWednesdayHours"]').val();
$('input[id*="txtWednesdayHours"]').keyup(function () {
if ($('input[id*="txtWednesdayHours"]').val() != content3) {
content3 = $('input[id*="txtWednesdayHours"]').val();
var hoursMon = new Number(content3);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtTuesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
}
});
var content4 = $('input[id*="txtThursdayHours"]').val();
$('input[id*="txtThursdayHours"]').keyup(function () {
if ($('input[id*="txtThursdayHours"]').val() != content4) {
content4 = $('input[id*="txtThursdayHours"]').val();
var hoursMon = new Number(content4);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtTuesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
}
});
var content5 = $('input[id*="txtFridayHours"]').val();
$('input[id*="txtFridayHours"]').keyup(function () {
if ($('input[id*="txtFridayHours"]').val() != content5) {
content5 = $('input[id*="txtFridayHours"]').val();
var hoursMon = new Number(content5);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtTuesdayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
}
});
var content6 = $('input[id*="txtSaturdayHours"]').val();
$('input[id*="txtSaturdayHours"]').keyup(function () {
if ($('input[id*="txtSaturdayHours"]').val() != content6) {
content6 = $('input[id*="txtSaturdayHours"]').val();
var hoursMon = new Number(content6);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtTuesdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
}
});
var content7 = $('input[id*="txtSundayHours"]').val();
$('input[id*="txtSundayHours"]').keyup(function () {
if ($('input[id*="txtSundayHours"]').val() != content7) {
content7 = $('input[id*="txtSundayHours"]').val();
var hoursMon = new Number(content7);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtTuesdayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
}
});
});
</script>
Ideally, I would like to fire this line:
$('input[id*="txtMondayHours"]').val((new Number($('input[id*="txtMondayHours"]').val())).toFixed(2));
After a specified time e.g. 100ms
Updated working code:
<script type="text/javascript">
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$(function () {
var content = $('input[id*="txtMondayHours"]').val();
$('input[id*="txtMondayHours"]').keyup(function () {
if ($('input[id*="txtMondayHours"]').val() != content) {
content = $('input[id*="txtMondayHours"]').val();
var hoursMon = new Number(content);
var hoursTue = new Number($('input[id*="txtTuesdayHours"]').val());
var hoursWed = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
delay(function () {
$('input[id*="txtMondayHours"]').val((new Number($('input[id*="txtMondayHours"]').val())).toFixed(2));
}, 750);
}
});
var content2 = $('input[id*="txtTuesdayHours"]').val();
$('input[id*="txtTuesdayHours"]').keyup(function () {
if ($('input[id*="txtTuesdayHours"]').val() != content2) {
content2 = $('input[id*="txtTuesdayHours"]').val();
var hoursMon = new Number(content2);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
delay(function () {
$('input[id*="txtTuesdayHours"]').val((new Number($('input[id*="txtTuesdayHours"]').val())).toFixed(2));
}, 750);
}
});
var content3 = $('input[id*="txtWednesdayHours"]').val();
$('input[id*="txtWednesdayHours"]').keyup(function () {
if ($('input[id*="txtWednesdayHours"]').val() != content3) {
content3 = $('input[id*="txtWednesdayHours"]').val();
var hoursMon = new Number(content3);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtTuesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
delay(function () {
$('input[id*="txtWednesdayHours"]').val((new Number($('input[id*="txtWednesdayHours"]').val())).toFixed(2));
}, 750);
}
});
var content4 = $('input[id*="txtThursdayHours"]').val();
$('input[id*="txtThursdayHours"]').keyup(function () {
if ($('input[id*="txtThursdayHours"]').val() != content4) {
content4 = $('input[id*="txtThursdayHours"]').val();
var hoursMon = new Number(content4);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtTuesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
delay(function () {
$('input[id*="txtThursdayHours"]').val((new Number($('input[id*="txtThursdayHours"]').val())).toFixed(2));
}, 750);
}
});
var content5 = $('input[id*="txtFridayHours"]').val();
$('input[id*="txtFridayHours"]').keyup(function () {
if ($('input[id*="txtFridayHours"]').val() != content5) {
content5 = $('input[id*="txtFridayHours"]').val();
var hoursMon = new Number(content5);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtTuesdayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
delay(function () {
$('input[id*="txtFridayHours"]').val((new Number($('input[id*="txtFridayHours"]').val())).toFixed(2));
}, 750);
}
});
var content6 = $('input[id*="txtSaturdayHours"]').val();
$('input[id*="txtSaturdayHours"]').keyup(function () {
if ($('input[id*="txtSaturdayHours"]').val() != content6) {
content6 = $('input[id*="txtSaturdayHours"]').val();
var hoursMon = new Number(content6);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtTuesdayHours"]').val());
var hoursSun = new Number($('input[id*="txtSundayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
delay(function () {
$('input[id*="txtSaturdayHours"]').val((new Number($('input[id*="txtSaturdayHours"]').val())).toFixed(2));
}, 750);
}
});
var content7 = $('input[id*="txtSundayHours"]').val();
$('input[id*="txtSundayHours"]').keyup(function () {
if ($('input[id*="txtSundayHours"]').val() != content7) {
content7 = $('input[id*="txtSundayHours"]').val();
var hoursMon = new Number(content7);
var hoursTue = new Number($('input[id*="txtMondayHours"]').val());
var hoursWed = new Number($('input[id*="txtWednesdayHours"]').val());
var hoursThu = new Number($('input[id*="txtThursdayHours"]').val());
var hoursFri = new Number($('input[id*="txtFridayHours"]').val());
var hoursSat = new Number($('input[id*="txtSaturdayHours"]').val());
var hoursSun = new Number($('input[id*="txtTuesdayHours"]').val());
$('input[id*="txtTotalWorkingHours"]').val(parseFloat(hoursMon.toFixed(2)) + parseFloat(hoursTue.toFixed(2)) + parseFloat(hoursWed.toFixed(2)) + parseFloat(hoursThu.toFixed(2)) + parseFloat(hoursFri.toFixed(2)) + parseFloat(hoursSat.toFixed(2)) + parseFloat(hoursSun.toFixed(2)));
delay(function () {
$('input[id*="txtSundayHours"]').val((new Number($('input[id*="txtSundayHours"]').val())).toFixed(2));
}, 750);
}
});
});
</script>
A: You could use the underscore.js library's debounce function.
A: Put your code in a timeout. Then on subsequent 1keyup events, clear the timeout and reset it.
That is what this one is doing How to delay the .keyup() handler until the user stops typing?
A: Use Ben Alman's jQuery throttle / debounce: http://benalman.com/projects/jquery-throttle-debounce-plugin/.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: VB6 software consuming WCF web services. Endpoints in App.config. Err VB6 has no App.config We have an EPOS system that is built in VB6. A client is using Microsoft Dynamics AX as a CRM system. A 3rd party has created the AX implementation for our client and they've exposed a set of WCF web services that we need to consume to synchronise data between the EPOS and the AX CRM. Knowing VB6 would have issues calling WCF services, I created the following components to handle the communication between the EPOS and the AX CRM.
VB6 EPOS which calls -->
1) VB6 DLL wrapper which calls... -->
2) .NET(3.5) COM Callable Proxy DLL wrapper which calls... -->
3) .NET(3.5) Web Service Handler (Where the web servicesw actually get called) -->
Microsoft Dynamics AX CRM.
I built a test console app in Vb.NET to simulate calls from VB6 to help with debugging, so that test console app calls component 2.
Whilst doing this I was getting the following exception:-
"(could not find default endpoint element that references contract 'X' in the servicemodel client configuration section. this might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.)"
I googled around and found that I had to copy the bindings and endpoints section from Component 3's app.config to a new app.config for my Test Console app. I don't know WCF and haven't got the time at the moment, to really learn it to the point where I understand why this fixed this error.
Now though, I'm trying to call the services from the VB6 EPOS and this error is popping up again. So I added an app.config to Component 2, thinking that as Component 2 is the first .NET(3.5) component in the chain, that is where the endpoint declaration should go, but No. The error is still popping up.
Does anyone have any ideas? Any programming heroes out there that can shed some light on this for a simpleton please??? Please don't ask why we don't re-write the EPOS. We will. just not yet. Theres over 3 million lines of spaghetti code in there and I've only been working on it for 8 months!!!
As an aside, Doesn't this scenario break one of the golden rules of OOP, i.e. encapsulation. Why should my VB6 EPOS need to know what endpoints Component 3 uses to access the WCF service???
A: Great question here...
Your problem is essentially coming from all the required configuration data needed to work with a WCF Service.
When dealing with .NET Windows or Web Applications the configuration data on both the client and server sides of WCF Services reside in the application configuration file. For a windows application this file will be app.config, whereas it will be a web.config for a web application.
In your case, you would like to put the proxy logic in some form of a COM-visible .dll.
This is going to cause you some grief...in the .NET platform, the .config file for top-level host application (web or windows) is the place where all configuration data is read. Even if your application leverages dozens of .NET assemblies (each with custom configuration needs), the runtime is going to expect those configuration elements to all reside in the top-most application configuration file.
To resolve your issue, you are going to need to communicate to a service that VB6 does have access to (think ASMX web services) and have that service forward your call along to the appropriate WCF service.
The other alternative is to pass configuration variables directly from your VB6 application to your Com-visible assembly so you can use the extensibility model of WCF to create proxies (overriding the default behavior to read configuration data from a file) with your passed-in configuration.
I would say that the latter scenario could go both ways as far as being a violation of SOA/OOP..depending on the situation it may/may not be appropriate for the VB6 application to know about/store configuration details for communicating with the (eventual) WCF endpoint
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: android layout according to language selected I would like to know if there is any good idea how to switch layouts according to application language selected - e.g. switch between left-to-right layout and right-to-left layout. Have different images or written text and ofcourse the position.
I thought doing it using a private member in the application that indicates the current language selected. According to this parameter I can choose the related XML and text etc.
Actualy I might create some LayoutFactory class, although I don't really think it is required.
But will have to create the realted layout XMLs.
Is there any option to put subdirectories under he layout?
Or should I name the files like en_.xml and he_.xml etc?
A: For values and drawable you can add folders like values-fr for French or values-ja for Japanese. The -fr indicates that if your phone is set to French localization the app will use any folder that has the -fr added to its name. I'm guessing this goes for the layout folder aswell.
You can read about Localization here .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python Convert Unicode-Hex utf-8 strings to Unicode strings Have s = u'Gaga\xe2\x80\x99s' but need to convert to t = u'Gaga\u2019s'
How can this be best achieved?
A: s = u'Gaga\xe2\x80\x99s'
t = u'Gaga\u2019s'
x = s.encode('raw-unicode-escape').decode('utf-8')
assert x==t
print(x)
yields
Gaga’s
A: Where ever you decoded the original string, it was likely decoded with latin-1 or a close relative. Since latin-1 is the first 256 codepoints of Unicode, this works:
>>> s = u'Gaga\xe2\x80\x99s'
>>> s.encode('latin-1').decode('utf8')
u'Gaga\u2019s'
A: import codecs
s = u"Gaga\xe2\x80\x99s"
s_as_str = codecs.charmap_encode(s)[0]
t = unicode(s_as_str, "utf-8")
print t
prints
u'Gaga\u2019s'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Toast fails to show when within a AsyncTask I have a simple application which sends an image (Base64 encoded) to a server, the server gets this data fine because the PHP script sends me an email with the Base64 Data attached. However, after the task gets completed the toast never shows. How do I take the Toast get shown after the data gets posted?
I think the issue is within the context.
http://pastie.org/2616524
UPDATE
I have updated the link, because i have since moved the upload logic into a different .java file.
A: Your sample look OK. If Activity, to which mContext variable belongs is currently active, it should show. Not in other case.
try this modification:
new UploadImage(ImageUploadActivity.this).execute(sentImage);
http://developer.android.com/guide/topics/ui/notifiers/toasts.html
Android toast.makeText context error
EDIT: WRONG TYPE DECLARATION OF AsyncTask
your AsyncTask declaration looks like class UploadImage extends AsyncTask<String, Void, String>
This means:
*
* is type of params to doInBackground(String... arg)
* is type of progress
* is type of result from doInBackground to onPostExecute
So change your onPostExecute declaration to this:
protected void onPostExecute(String result)
or change return type of doInBackground to <Bitmap> and change class declaration to: class UploadImage extends AsyncTask<String, Void, Bitmap>
http://developer.android.com/reference/android/os/AsyncTask.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rails 3.1 Mongoid has_secure_password I'm attempting to get has_secure_password to play nice with mongoid. I'm following Railscasts #270, however when I to signin with a username/password, I get the error:
undefined method `find_by_email' for User:Class
I see a similar post (http://stackoverflow.com/questions/6920875/mongoid-and-has-secure-password) however, having done as it suggested I still get the same error.
Here is my model:
class User
include Mongoid::Document
include ActiveModel::SecurePassword
validates_presence_of :password, :on => :create
attr_accessible :email, :password, :password_confirmation
field :email, :type => String
field :password_digest, :type => String
has_secure_password
end
Controller:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to root_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render "new"
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, :notice => "Logged out!"
end
end
Thanks.
A: Option 1: In your controller, you should use
user = User.where(:email => params[:email]).first
Option 2: In your model, you should define
def self.find_by_email(email)
where(:email => email).first
end
A: Mongoid doesn't support the find_by_attribute methods.
You should better use where instead:
User.where(:email => email).all
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Get this element Attribute and use it on other element So... What I want is the following:
When I .click an element with an id starting with 'menu' it will get its attr value='value' into a variable and use it on the next function.
Here's the source:
index.html
<div id='menuBar' >
<img id='menu01' src='/si/img/menu.apresentacao.jpg' value='apresentacao' >
<img id='menu02' src='/si/img/menu.servicos.jpg' value='servicos' >
</div>
jquery.js
$(document).ready(function() {
$('img[id^='menu']').click( function(){
var menuValue = $(this).attr('value');
$('div#contentBox').fadeOut(300, function() {
$('div#contentBox').replaceWith('<div id="contentBox">' + menuValue + '</div>');
});
});
});
variables.js
var servicos = "<p id='title'>Serviços</p><br><p id='text'>text text</p><br>";
Thanks in advance*
A: The only problem with your code is that your selector is malformed and therefor doesn't work:
$('img[id^='menu']').click( function(){
^ ^ ^ ^
| | | |
| | | \__ Closing single quote
| | |
| | \__ Opening single quote
| |
| |
| \__ Closing single quote
|
\__ Opening single quote
====> does not compute!
What it should be, is this (note the double quotes around "menu:):
$('img[id^="menu"]').click( function(){
^ ^
| |
\ /
\ /
\/
\_Double quotes, yay!
… and it works just fine: http://jsfiddle.net/HnsTu/
A: Instead of using var servicos use an object with the value of your image as a key.
var menuValueContent = {'servicos': '<p>....</p>', 'apre': '...'};
and in your click handler you can use menuValueContent[menuValue] to get the new content.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Play one instance of AVAudioPlayer in the background I have several instances of AVAudioPlayer in my app (in separate classes). I have added multi-tasking capabilities to one instance but all audio now plays in the background. I added the 'App plays audio' key to my plist and:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
to my class. How can I target this code to only 1 instance of AVAudioPlayer?
A: The only way around this I could find was the pause the specific AVAudioPlayer instance in:
applicationWillResignActive
I moved the creation of the instance to the appdelegate and then accessed it via:
appDelegate = [[UIApplication sharedApplication] delegate]
in my class. There is probably a better way to do this but this was the quickest and simplest I could find.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to return html instead of strings in php dom parser <?php
$convert = function($src) {
return '<div>'.$src.'</div>';
};
$doc = new DOMDocument;
$doc->loadhtml(getHTML());
foo($doc, $convert);
echo "after: ", $doc->savehtml(), "\n\n";
function foo(DOMDocument $doc, $fn) {
$xpath = new DOMXPath($doc);
$imgs = array();
foreach( $xpath->query('/html/body//img') as $n ) {
$imgs[] = $n;
}
foreach($imgs as $n) {
$txt = $fn($n->getAttribute('src'));
$div = $doc->createElement('div', $txt);
$n->parentNode->replaceChild($div, $n);
}
}
function getHTML() {
return '<html><head><title>...</title></head><body>
<p>lorem ipsum <img src="a.jpg" alt="img#1"/></p>
<p>dolor sit amet<img src="b.jpg" alt="img#2"/></p>
<div><div><div><img src="c.jpg" alt="img#3" /></div></div></div>
</body></html>';
}
In the above code in the third line doesn't appear as html in the output, it show as the string. How to return a html tag in this program.
A: Use echo() not return() when printing the HTML
A: This should do it:
<?php
$doc = new DOMDocument;
$doc->loadhtml(getHTML());
replaceImageTags($doc);
echo "after: ", $doc->savehtml(), "\n\n";
function replaceImageTags(DOMDocument $doc)
{
$xpath = new DOMXPath($doc);
$imgs = array();
foreach($xpath->query('/html/body//img') as $n ) {
$imgs[] = $n;
}
foreach($imgs as $n)
{
$div = $doc->createElement('div', $n->getAttribute('src'));
$n->parentNode->replaceChild($div, $n);
}
}
function getHTML() {
return '<html><head><title>...</title></head><body>
<p>lorem ipsum <img src="a.jpg" alt="img#1"/></p>
<p>dolor sit amet<img src="b.jpg" alt="img#2"/></p>
<div><div><div><img src="c.jpg" alt="img#3" /></div></div></div>
</body></html>';
}
Outputs:
after: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><head><title>...</title></head><body>
<p>lorem ipsum <div>a.jpg</div></p>
<p>dolor sit amet<div>b.jpg</div></p>
<div><div><div><div>c.jpg</div></div></div></div>
</body></html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Open Office server mode macro I'm trying to run xls files on an open office server on Windows.
I start the oo in server mode with the following bat:
start soffice.exe -headless -nofirststartwizard
-accept="socket,host=localhost,port=8100;urp;StarOffice.Service"
The server is used by a Java application.
The problem is that the macros of the given xls file don't execute.
Does anyone have experience with this?
A: Taking some links from https://stackoverflow.com/a/6238845/450812
This possibly has to do with having to explicitly set permissions for
macros, for instance:
Can't execute macro from command line (View topic) • OpenOffice.org Community Forum
See also:
*
*Custom OpenOffice.org Basic Macros and Libraries - OpenOffice.org Wiki
*OpenOffice.org Forum :: Enable OpenOffice Macro through Command Line.
*OpenOffice.org Forum :: simple command line question
*OpenOffice.org Forum :: HowTo Run Macros from Document from Shell
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: rounded border around img This is what I want to achieve.
I want to make it as flexible as possible, so i split the png into left top corner, left, right top corner etc..
Here is what I have tried:
<div class="top">
<div class="lt">
<div class="lr">
<img src='somepicture.jpg' />
</div>
</div>
</div>
.win{width:182px;}
.win .lt{background:url('../img/5.png') no-repeat left top;}
.win .lr{background:url('../img/7.png') no-repeat right top;}
.win .top{background:url('../img/6.png') top;}
.win .l{background:url('../img/2.png') no-repeat left;}
.win .top,.win .lt, .win .lr{height:10px;padding:0;margin 0;overflow:hidden;}
.win .l doesn't fit to the height of the image.
Maybe my whole approach is wrong. What's the best practice for such a problem?
/* EDIT */
it looks this solution doesnt work for me:
as u can sse the border is missing from the corners. if i make it 4+ px thick then its ok but i need it 1px thin. why it is a problem?
the html
<div class="win" >
<img class="rounded" src='red.jpg' />
</div>
and the css
.win{width:188px;float:left;margin:0 30px 25px 0;}
.win .rounded {
overflow: hidden;
behavior: url(PIE.htc);
border:1px solid #000;
-moz-border-radius: 7px; /* Firefox */
-webkit-border-radius: 7px; /* Safari and Chrome */
border-radius: 7px; /* Opera 10.5+, future browsers, and now also Internet Explorer 6+ using IE-CSS3 */
}
A: You should consider using border-radius, which gives you rounded corners in all modern browsers:
.something{
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius:4px;
}
More info here: https://developer.mozilla.org/en/CSS/border-radius
You can use this tool to determine the size: http://border-radius.com/
NB: if you need support for IE<9, you can use http://css3pie.com/
A: Border radius really would be the nice way forward as it's simple and IE<9 just have to make do with a slightly less visually appealing site. Still, if you want to go with the corner image option see this:
http://jsfiddle.net/chricholson/JS5AG/
HTML:
<div>
<img />
<span class="tl"></span>
<span class="tr"></span>
<span class="bl"></span>
<span class="br"></span>
</div>
CSS:
div {
height: 100px;
width: 100px;
background: red;
position: relative;
}
span {
position: absolute;
background: blue;
height: 20px;
width: 20px;
display: block;
}
span.tl {
top: 0; left: 0;
}
span.tr {
top: 0; right: 0;
}
span.bl {
bottom: 0; left: 0;
}
span.br {
bottom: 0; right: 0;
}
A: There is a hack is for using border-radius in IE8 (and older) and its very fussy,
First download this .htc solution: Curved Corner and upload it to your site. Then wherever you need a border radius, apply this CSS:
.rounded-corners {
behavior: url(/css/border-radius.htc);
border-radius: 20px;
}
Use it as a last resort.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7609790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.