text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How to scan XElement and put all the element ( with value ) in Dictionary? My input is XElement object - and i need to convert this object to Dictionary
The XElement is look like this
<Root>
<child1>1</child1>
<child2>2</child2>
<child3>3</child3>
<child4>4</child4>
</Root>
And the output that i actually need to return is
Dictionary that look like this
[ Child1, 1 ]
[ Child2, 2 ]
[ Child3, 3 ]
[ Child4, 4 ]
How can i do it ?
thanks for any help.
A: You're looking for the ToDictionary() method:
root.Elements().ToDictionary(x => x.Name.LocalName, x => x.Value)
A: var doc = XDocument.Parse(xml);
Dictionary<string, int> result = doc.Root.Elements()
.ToDictionary(k => k.Name.LocalName, v => int.Parse(v.Value));
A: You're all missing the point.
The keys are meant to be "ChileX", as in the country. :)
var xml = XElement.Parse("<Root><child1>1</child1><child2>2</child2><child3>3</child3><child4>4</child4></Root>");
var d = xml.Descendants()
.ToDictionary(e => "Chile" + e.Value, e => v.Value);
A: You can try
XElement root = XElement.Load("your.xml");
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (XElement el in root.Elements())
dict.Add(el.Name.LocalName, el.Value);
or
For linq solution check @jon skeet answer : Linq to XML -Dictionary conversion
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: unable to get the changes made in index of phonegap android I'm unable to get the changes made in the index of PhoneGap Android.
Actually I have added everything into my eclipse android project with phonegap.
When i change that index.html page, I'm not getting the changes in emulator.
Those changes are not reflecting in the emulator. It is remaining with same page like Helloworld.
A: After making the changes to index.html, you need to select its enclosing project and choose Run As -> Android Application from the right click menu.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Heap sort analysis In the analysis of heap sort we know that one of the ways to perform heap sort is in two phases.
*
*Create a heap i.e., max or min priority queue.
*Remove the maximum/minimum from priority queue until all elements have been removed
Suppose there are N elements. For phase 1 the number of comparisons is 2N and for one removal the number of comparisons is 2lgN so for N removals it is 2NlgN comparisons. So total number of comparisons is 2N + 2NlgN.
This is my understanding. The book I am reading is Algorithms analysis by Wesis which says:
In the second phase, the ith deletemax uses at most 2(floor(log i)) comparisons, for a total of at most 2NlogN - O(N) comparsions (assuming N >= 2). Consequently in the worst case, there are at most 2NlogN - O(n) comparisons for heap sort.
My questions are
*
*How did the author conclude that in the second phase, the ith deletemax uses at most 2(floor(logi)) comparisons?
*How did the author come up with a total of 2NlogN - O(N)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How does the methods "shouldChangeTextInRange" and "stringByReplacingCharactersInRange" work? I would like to know the working of the following code.
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 10);
}
What does "stringByReplacingCharactersInRange" do? And how does the above method limit the number of characters that can be entered in the textField?
Thanks in advance!
A: textField:shouldChangeCharactersInRange:replacementString: is UITextFieldDelegate method that gets called any time text field's contents are about to change (entering, deleting, cutting or pasting text into the text field), asking the delegate if it wants to allow this change.
stringByReplacingCharactersInRange:withString: is an NSString instance method that does exactly what it says, replaces some text in current string with another string, creating a new string.
The code you have checks if the string that would be a result of this change is longer than 10 characters and if it is, delegate will return NO and text field contents will not change. If the resulting string would be 10 characters or less, delegate will return YES and text field's contents will change to the same string that you got in newString.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Component based architecture: Replacing an assembly at runtime Is it a good idea to replace an assembly at runtime?
What problems can I encounter?
Original question: StructureMap - Ability to replace an assembly at runtime
What is the difference in replacing an assembly at runtime within a web- and a non-web application?
A: The difference is that IIS creates a new shadow copy each time you update a DLL. Hence you get a new AppDomain automatically when you add the new DLL.
WinForms etc doesn't do that magic for you and that's why it won't work.
A: If the code that runs against that assembly runs in a separate AppDomain and that you shut down the appdomain before doing the operation, you should have no problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to save data filled in pdf using ABCpdf or EOPdf in asp.net? I have a Pdf with input fields and i want to save the data filled in these field and the output should be a pdf i have searched on net but still notable to find helpful code... or any other example. Please help me as soon as possible. thanks in advance
A: abcPDF is useful for this, you can get the data from the PDF using one of the examples in their help file. You can use the same tool to read out the form fields and then write them back into another copy of the document.
Alternatively you can probably use the Stamp() method they provide to lock the fields into the document and save it.
You can try abcPDF for free for 30 days.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it a SQL injection? I am finding my SQL Server database fields getting hacked as follows. Please note that Original Content is existing value of the field and it gets changed to following.
Original Content</title><script src=http://dfrgcc.com/ur.php></script></title><a style=position:absolute;left:-9999px;top:-9999px; href=http://file-dl.com/show.php?id=6 >crack</a>
I assume it's a SQL injection attack. If not, please guide. I have ensured following, however the DB gets hacked every few days.
1) All my data access is in dataset files i.e. app_code\DataLayer.xsd. I call my data methods as follows.
Dim memberDAL As new membersTableAdapter
Dim memberName As String = tbName.text
memberDAL.insertMember(memberName)
Does above code gets qualified as parametrized query. Is it safe data access as far as my problem is concerned. All data access is done in this manner. There are number of forms with lot of input fields, and the content DOES go in database. However what seems to be happening is not INSERT but a UPDATE. Even membership tables are being affected. e.g. in aspnet_users table a username called 'admin' changes to following.
admin</title><script src=http://dfrgcc.com/ur.php></script></title><a style=position:absolute;left:-9999px;top:-9999px; href=http://file-dl.com/show.php?id=1 >crack</a></title><script src=http://dfrgcc.com/ur.php></script>
2)I have used CAPTCHA to exclude bots, but this did not help.
I am on shared host, as per server admin I need to sanitize my code. Please advise.
A: It's not an SQL Injection, this is cross site scripting.
On an SQL Injection the attacker would try to inject SQL code into your query. For example if you have a query to retrieve - let's say - a student record:
SELECT * FROM students WHERE name = '$name' LIMIT 0,1
If I pass in the following as name and the developer hasn't done a good job sanitizing their input, something bad would happen: $name = "Robert'; DROP TABLE students; --" (See http://xkcd.com/327/) the resulting query would be
SELECT * FROM students WHERE name='Robert'; DROP TABLE students; --' LIMIT 0,1
I think I don't need to explain what this does :)
This XSS attack tries to inject HTML code (or in this case javascript code) into your page. If you don't filter out HTML tags or change the special characters to HTML entities (> to >) this code would be executed in the users browser.
A: If you're seeing arbitrary markup inserted into your data, it may be a SQL injection attack. It also may be that the data has just been appended to form input and hasn't actually exercised any SQLi techniques - you just haven't white-listed allowable values.
As a result of this data, you now have a persistent XSS risk but the data almost certainly didn't get there as a result of XSS.
Try taking a look at OWASP Top 10 for .NET developers part 1: Injection then OWASP Top 10 for .NET developers part 2: Cross-Site Scripting (XSS). This should cover you need from protecting against SQLi to then ensuring XSS can't be exploited.
A: This is an XSS attack. Your database has not been compromised, but it now contains links to externally hosted Javascript that is executed in the context of your domain. This means that they may be able to hijack users' sessions, or make requests on behalf of the user.
You should HTML encode the data that you output to the page - replacing the < with < (and the rest) will "contextually encode" the data, ensuring that what is supposed to be plain text (the "injected" HTML above) is output as text, and not interpreted by the browser as HTML (and Javascript).
To understand more, check the OWASP article.
A: Short answer is yes this is very likely to be an SQL Injection attack.
You will need to use a tool like Scawlr to find the actual attack vector:
https://h30406.www3.hp.com/campaigns/2008/wwcampaign/1-57C4K/index.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Engineyard rollback - does it rollback migrations as well? I am new to Enginyard. I have deployed the application using enginyard web interface but rollback from console using "ey rollback" command.
My question is is this command also rollback the migrations or not ?
A: Judging from the engineyard-serverside API, it doesn't rollback migrations. This makes sense given how unpredictable that can be. For reference, the actual code which does the migration is:
# task
def rollback
if c.all_releases.size > 1
rolled_back_release = c.latest_release
c.release_path = c.previous_release(rolled_back_release)
revision = File.read(File.join(c.release_path, 'REVISION')).strip
info "~> Rolling back to previous release: #{short_log_message(revision)}"
run_with_callbacks(:symlink)
sudo "rm -rf #{rolled_back_release}"
bundle
info "~> Restarting with previous release"
with_maintenance_page { run_with_callbacks(:restart) }
else
info "~> Already at oldest release, nothing to roll back to"
exit(1)
end
end
You can fairly easily parse that out to mean that it re-does the symlink for your project, removes the newest (failed) deployment, and restarts the webserver.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use of activity indicator in xml parsing I am new to IOS development. I am developing an app in which i have to do xml parsing. this is taking some time, so i want to display the Activity Indicator during this time. Could anyone let me know how to do it?
where to stast and stop the activity indicator;
Thanks for every help;
A: If you are talking about the little one in the top you use:
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES/NO];
A: you can start and stop in didReceiveResponse: and didFinishLoading: repectively
A: Step 1:Create the new view with activity indiactor(LoadingView)
Step 2:Call the showLoading method before you call the webservice
Step 3:Call removeLoading after completed the parsing xml
- (void)showLoading {
lview = [[LoadingView alloc] init];
[self.view insertSubview:lview.view aboveSubview:self.parentViewController.view];
}
-(void)removeLoading{
[lview.view removeFromSuperview];
[lview release];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: What is the difference between ANSI C 89 and C that supports by C++? I know there are some difference between ANSI C 89 and C that supports by C++.
for example in ANSI C 89, you should declare variables at first line of blocks.
or when you want to declare struct variables, you should use struct keyword (eg struct student std1;).
or // is not valid for commenting and you should use /**/ for commenting in ANSI C 89.
for example this C code is not valid in ANSI C 89:
struct student
{
char* name;
};
enum number
{
ODD,
EVEN
};
void test()
{
printf("Hello world!");
int a, b; // Not valid in ANSI C 89, variables should declare at first line of blocks.
student std1; // Not valid. It should be: struct student std1;
struct student std2; // Valid.
number n1 = ODD; // Not valid.
enum number n2 = EVEN; // Valid.
}
I want to develope an application using ANSI C 89 and my question is:
What is the difference between ANSI C 89 and C that supports by C++?
A: The C subset of C++98/03 is modeled on C89 (obviously, since C99 wasn't out at the time); that of C++11 is modeled on C99. Nonetheless, the languages are quite different and the C subset of C++ isn't the same as the language C.
You're essentially asking "what's the difference between C++ and C", which isn't really a suitable question.
(For example, sizeof('a') is different in C and in C++, so if you're using MSVC++, knowing the C standard on which C++ was modeled doesn't help you at all).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: cycle focus issue - I'm rewrite default template of ListBoxItems & ListBox. Here MainWindow.xaml
<Window x:Class="NestedBindingTry.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="Window_Loaded"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<Style TargetType="ListBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<StackPanel
IsItemsHost="True"
FocusManager.IsFocusScope="False"
/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<StackPanel FocusManager.IsFocusScope="True"
KeyboardNavigation.ControlTabNavigation="Cycle"
KeyboardNavigation.DirectionalNavigation="Cycle">
<StackPanel>
<CheckBox Content="SelectAll" />
</StackPanel>
<ListBox SelectionMode="Multiple" Name="M" ItemsSource="{Binding}" FocusManager.IsFocusScope="False">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="SelectionStates">
<VisualState x:Name="Unselected">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="CheckBox"
Storyboard.TargetProperty="IsChecked">
<DiscreteBooleanKeyFrame KeyTime="0"
Value="False" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Selected">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="CheckBox"
Storyboard.TargetProperty="IsChecked">
<DiscreteBooleanKeyFrame KeyTime="0"
Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="SelectedUnfocused">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="CheckBox"
Storyboard.TargetProperty="IsChecked">
<DiscreteBooleanKeyFrame KeyTime="0"
Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<CheckBox Focusable="False"
Name="CheckBox"
Content="{Binding}"
Checked="CheckBox_Checked"
Unchecked="CheckBox_Unchecked"
VerticalAlignment="Center"
Margin="0,0,3,0" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
</StackPanel>
</Grid>
</Window>
Here codeBehind MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace NestedBindingTry
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new List<string>() { "123", "546", "789"};
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBox bik = sender as CheckBox;
DependencyObject dob = bik as DependencyObject;
while (dob.GetType() != typeof(ListBox))
{
dob = VisualTreeHelper.GetParent(dob);
}
ListBox my = dob as ListBox;
if (!my.SelectedItems.Contains(bik.DataContext))
my.SelectedItems.Add(bik.DataContext);
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
CheckBox bik = sender as CheckBox;
DependencyObject dob = bik as DependencyObject;
while (dob.GetType() != typeof(ListBox))
{
dob = VisualTreeHelper.GetParent(dob);
}
ListBox my = dob as ListBox;
if (my.SelectedItems.Contains(bik.DataContext))
my.SelectedItems.Remove(bik.DataContext);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.M.SelectedItems.Add(((IList<string>)this.DataContext)[0]);
this.M.SelectedItems.Add(((IList<string>)this.DataContext)[2]);
}
}
}
Main idea I want to achive - is to create checkable ListBox. One feature I want to have - is Select All CheckBox. But here the problem. SelectAll CheckBox is not laying inside ListBox. So its under it.
I want that focus worked like SelectAll CheckBox lay inside ListBox. It means, that when I click Tab key, focus should go to the next CheckBox. In my case, if ListBox have more than 1 item, its just change focus between two CheckBoxes - between SelectAll CheckBox and first from ListBox item. But I want it goes down to the next ListBox item. I try to play with FocusManager's properties, but nothing happens.
Any suggestion...?
A: Use ItemsControl instead of ListBox.... the ListBox hails from Selector base class and this class somehow overrides simple Tab based focus for its items with Control + Up / Down Arrow in its ItemsPanel.
When I used ItemsControl it worked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to replace backslash followed by 't' or any other alphabet or character in escape chacter in file path to forward slash in java? I'm importing a CSV file to MySQL database. This can be done using java.mysql support for forward slash in file path. If user gives the path
String filepath=" c:\upload\date\csv\sample.csv";
we can do it by replacing '\' with '/' using following line of code.
String filepath2=filepath.replace("\\","/");
but when user enters path as follows
String filepath=" c:\test.csv";
the replace function unable to replace "\\" with "/"
as '\' in the filepath does not remain '\' as '\' is followed by 't' and it becomes as '\t' escape character.
this type of problem will come with each and every escape sequence.
I want to search for backslashes in the path and replace them with a forward slash, to give this:
c:/test.csv
How is that done?
How to solve this problem?
A: If you're getting the value via JFileChooser, then it will be more like this:
String value = "c:\\test.csv"; // This really only has a single backslash
But you shouldn't need to replace the backslashes with forward slashes. My guess is that you're including the value directly in the SQL you're generating: don't do that. Use a prepared statement with parameters instead, and you may well find the problem just goes away... and suddenly you won't be as vulnerable to SQL injection attacks either...
If you really, really need to convert backslashes to forward slashes, you can use:
String newValue = oldValue.replace("\\", "/");
... but you shouldn't have to do this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: BLToolkit.4 : DbManager could not be found I'm trying to create new application using BLToolkit but i can't compile the code, i get this error:
The type or namespace name 'DbManager' could not be found (are you
missing a using directive or an assembly reference?
This class is described here
I included this References:
*
*BLToolkit.4
*BLToolkit.SL.4
But i don't see it, what is wrong?
Person GetPerson(int personId)
{
using (DbManager db = new DbManager())
{
return db
.SetCommand(@"
SELECT
p.PersonId,
p.FirstName,
p.LastName,
p.MiddleName,
p.Gender
FROM Person p
WHERE p.PersonId = @PersonId",
db.Parameter("@PersonId", personId))
.ExecuteObject<Person>();
}
}
the same problem is with version 3
A: I just got it.
It is the classical newbie error, BLToolkit that comes in binary files, is compiled under Framework 3.5, and my project was 4.0
There are two ways to solve this problem:
*
*download source code project BLToolkit and include it to my project under FrameWork 4
*or change configuration of current project to use FrameWork 3.5
issue solved
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Find the matched record in mongodb? I have a record in my collection and I want to fetch the details of the person whose id is 1. But I am getting the details for 2times instead of 1.
db.mycollection.insert({"person" : [ { "id":1, "details" : { "name" : "Aswini", "Age" : 10 }}, { "id":2, "details" : { "name" : "Mahesh", "Age" : 11}}]})
Then running
> db.mycollection.findOne({"person.id":1},{"person.details":1,"_id":0})
the result is :
{
"person" :
[
{
"details" :
{
"name" : "Aswini",
"Age" : 10
}
},
{
"details" :
{
"name" : "Mahesh",
"Age" : 11
}
}
]
}
But I need as follows:
{
"person" : [
{
"details" : {
"name" : "Aswini",
"Age" : 10
}
}
]
}
Don't understand where am making mistake. Please need your help. Am using MongoDB, Java
A: This is the behavior of filtering multi level embedded document, normally the matching filter would return the whole document, not the subsets.
Usually positional operator $ used to match the sub documents in updates. But the feature is not yet implemented in return specifiers.
There is an outstanding issue already in mongo Support for positional ($) operator in fields to return specifier. (Please login to vote if you really needed the feature)
So you have to redesgin your schema to handle this, may be like this
db.test.insert({"person" : [ { "id":1, "details" : { "name" : "Aswini", "Age" : 10 }}]})
db.test.insert({"person" : [ { "id":2, "details" : { "name" : "Mahesh", "Age" : 11}}]})
db.test.find({"person.id":1},{'person.details':1})
A: person is an array. If you want to get first element of this array you should use $slice
db.mycollection.findOne({"person.id":1},{"person":{$slice:[0,1]},"_id":0})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there any way to change the default session table field name in NodeJS? I have been using expressJS and connect-mongo plugin to SAVE session data's in MongoDB as follows,
var conf = {
db: {
db: dbconfig.mongo_db_name,
host: dbconfig.mongo_host,
username: '',
password: '',
collection: 'sessionDataTable'
},
secret: '076ee61d63aa10a125ea872411e433b9',
};
app.configure(function(){
app.use(express.session({
secret: conf.secret,
maxAge: new Date(Date.now() + 3600000),
store: new MongoStore(conf.db)
}));
});
In connect-mongo, they had given options to change the table name only, If i want to add / change a field name in the "sessionDataTable", then how do i achieve it?. Please help me on this!!!
A: To add extra data to the session you have to use the session property of the req object provided by connect.
E.g.
app.get('/', function(req, res) {
req.session.name = 'Test Name';
});
This should then add that to the collection you have defined in MongoStore.
Is this what you mean?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to determine if a table row is visible or not? I want to know how to identify table row is visible or not. I want to resolve by using jQuery
A: You can use the :visible pseudo-selector, and the is method, which returns a boolean value:
if($("#tableRowId").is(":visible")) {
//It's visible
}
A: Is visible should help you :-
$('#table_row').is(':visible')
A: This should work:
var none=$("table tr").css("display")
if(none=="none"){
// Row is invisible
} else{
// Row is visible
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Problem in passing multiple strings to stringByEvaluatingJavaScriptFromString I'm stuck in a weird problem. I am currently working on mapkit on iPhone. I need to show two routes in my map, for which there is a source city and two different destination. For a route between two cities my code was fine. for that purpose in one place in my code i was doing like this….
- (void)loadWithStartPoint:(NSString *)startPoint endPoint:(NSString *)endPoint options:(UICGDirectionsOptions *)options {
[googleMapsAPI stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"loadDirections('%@', '%@', %@)", startPoint, endPoint, [options JSONRepresentation]]];
}
In the above code stringByEvaluatingJavaScriptFromString was passing javascript to my delegate method due to which route was drawn.
Now, i have to draw two different routes, for that purpose i have changed above code like this..
- (void)loadWithStartPoint:(NSString *)startPoint endPoint:(NSMutableArray *)endPoints options:(UICGDirectionsOptions *)options {
for (int idx = 0; idx < [endPoints count];idx ++)
{
NSString* msg = [NSString stringWithFormat:@"loadDirections('%@', '%@', %@)", startPoint, [endPoints objectAtIndex:idx], [options JSONRepresentation]];
mstr = [msg retain];
if (idx == 0)
{
[googleMapsAPI stringByEvaluatingJavaScriptFromString:msg];
}
else {
[NSThread detachNewThreadSelector:@selector(loadroute:) toTarget:self withObject:mstr];
}
}
}
i have the following to create and implement NSThread.
-(void)loadroute :(NSString *)message
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:@selector(loadComplete:) withObject:message waitUntilDone:YES];
[pool release];
}
-(void)loadComplete:(NSString *)message
{
[googleMapsAPI stringByEvaluatingJavaScriptFromString:message];
}
here, i have created another thread due to which i would be able to pass strings to stringByEvaluatingJavaScriptFromString separately.
But only the last string is passed to the delegate method.What i'm missing? please help me out. i'm stuck in this weird problem since last week. Any help would be appreciated. Thnx in advance.
A: As suggested by Ali u can go wid..performSelector:withObject:afterDelay:it will give u desired result..
u can write ur code like..
- (void)loadWithStartPoint:(NSString *)startPoint endPoint:(NSMutableArray *)endPoints options:(UICGDirectionsOptions *)options {
for (int idx = 0; idx < [endPoints count];idx ++)
{
NSString* msg = [NSString stringWithFormat:@"loadDirections('%@', '%@', %@)", startPoint, [endPoints objectAtIndex:idx], [options JSONRepresentation]];
mstr = [msg retain];
[self performSelector:@selector(loadComplete:) withObject:nil afterDelay:0.5];
}
}
-(void)loadComplete:(NSString *)message
{
[googleMapsAPI stringByEvaluatingJavaScriptFromString:message];
}
Hope this will help u out.
A: I guess this is due to multithreading not being very compliant with the UIWebView.
You should use NSOperationQueue or GCD to stack your calls of stringByEvaluatingJavaScriptFromString so that they are executed asychronously in the background, but still execute them in the main thread (use dispatch_get_main_queue() or performSelectorOnMainThread: etc).
If there is no real matter about multithreading, you may also simply call stringByEvaluatingJavaScriptFromString directly (why creating a thread? You can still call the method multiple times even if you want to pass strings separately, don't you?)
You may also try using performSelector:withObject:afterDelay: (with a delay of 0 or 0.01) so that the call will be executed during the next iteration of the runloop.
In general, if you don't really need to use them, avoid using threads (see "Concurrency Programming Guide" and the "Threading Programming Guide" for details info in Apple's doc). Prefer using asynchronous methods when they exists, then NSOperationQueues or GCD (and only if you don't have any other solution, you may use NSThreads). This is because higher APIs will manage tricky stuff for you and make problems less complex when dealing with multithreading.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to force django and php to work together? I have project in django on my server (wsgi, configured in apache)
I do not have access to config file, i have only django.wsgi file in my public_html folder.
And django works fine, but i wish in one of the public_html subdirectory place php script.
How to do it?
A: since python will use the wsgi protocol, maybe you could use another protocol to use php, for example cgi ;) (thank you Kevin)
A: If you haven't got access to config, the someone must have added:
AddHandler wsgi-script .wsgi
to the main Apache config or you added it to your .htaccess file for your Django application to work.
All that is required is the appropriate AddHandler directive for .php extension files and PHP code should be able to be placed in the same directories without interference presuming Apache as a whole has PHP support enabled.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom AWT Title Window I am new to AWT and I have been given a Photoshop mock up. I have to design a mock up Window based in AWT
Currently, I am stuck at Title Bar design.The Title Window looks like this.
http://i.imgur.com/wT5mm.png
Please let me know how can I accomplish this using AWT.
I am aware that I need to use setUndecorated(true) to get rid of default Title Window, but then I have no idea about how can I implement the one that is shown in the image.
I am just looking for a direction.
Thanks in Advance!!!
A: It is just a JPanel (if your working with Swing, see Panel in AWT) with a gradient background. I don't really know AWT but in Swing, do the following:
*
*set the JPanel layout to BorderLayout,
*add a JLabel as the centered component for the title (with the icon),
*add a JLabel with just the cross icon for the "close" button as the right component
*add the whole panel to the top of your window (using a BorderLayout for your window pane for instance)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to Read and Write a single sector in SD Card, using Android NDK How to Read and Write a single sector in SD Card, using Android NDK C/C++?
Is it possible, like this:
http://www.8051projects.net/mmc-sd-interface-fat16/reading-writing-sd-mmc-sector.php
I know it is not possible for Java.
A: This is a low-level operation not likely to be provided by the SDK, but I could be wrong I suppose. It most likely requires native code and root access. That is most likely what you will find after you investigate this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to hide -> move ->show -> an element in loop? $parent.animate({'left': '-='+parentLeft+'px'}, options.speed, options.easing, function(){
if(slideLoop){
$parent.css('left', '-'+getSlidePosition(currentSlide, 'left')+'px');
}
I need to animate $parent in sequence: hide -> move ->show ->
and I need to adapt to the above code.
Already it only moves...
A: you can use the
$('#parent').hide()
and
$('#parent').show()
methods before and after your move code
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Replace HTML-encoded symbol (™) in PHP string I'm trying to remove an encoded TM sign from a PHP string which is displayed as a a page title. The character displays as ™ in the title, which is obviously ugly. Unfortunately none of the inbuilt encoding functions seem to deal with translation of very many encoded characters, and TM isn't one of them. What I want to do is replace '™' with '(tm)'.
Before I dig into substrings I wanted to see if anyone knew of a cleverer way to do this. I don't know the position the symbol appears in the string (it varies depending on the page title).
Any thoughts much appreciated!
A: What about this:
<title><?php print str_replace("™", "™", $yourStr); ?></title>
Actually I don´t know is it the best way to do this, but at least it works.
A: As I understand it you want to replace the '™' with '(tm)' in a string in PHP. You can just use the str_replace() function for that.
It would look something like this
$titleString = "SOME TITLE - Trademark ™ My Company";
$titleStringReplaced = str_replace("™", "(tm)", $titleString);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: "undefined reference to `_head_libpython27_a'" So, I've been trying to install py-notify (now I've been running into the same problems with trying to install cython), but I've run into a problem that I wasn't able to fix with Google this time (the only results are for this question now...).
First, I was running into this problem: http://pastebin.com/0hs6ngsj
After following the procedure on this page to create the file libpython27.a (which seemed to be what is required), and putting it into C:\Python27\libs\, I now get this error instead:
C:\...>easy_install py-notify
Searching for py-notify
Reading http://pypi.python.org/simple/py-notify/
Reading http://home.gna.org/py-notify/
Reading http://download.gna.org/py-notify/
Best match: py-notify 0.3.1
Downloading http://pypi.python.org/packages/source/p/py-notify/py-notify-0.3.1.tar.gz#md5=58428761bc196bf9b1f1d930991ee3ca
Processing py-notify-0.3.1.tar.gz
Running py-notify-0.3.1\setup.py -q bdist_egg --dist-dir c:\users\nightkev\appdata\local\temp\easy_install-qfiohj\py-notify-0.3.1\egg-dist-tmp-zoe6ad
C:\Python27\libs\libpython27.a(dwtms01015.o):(.idata$7+0x0): undefined reference to `_head_libpython27_a'
C:\Python27\libs\libpython27.a(dwtms00254.o):(.idata$7+0x0): undefined reference to `_head_libpython27_a'
C:\Python27\libs\libpython27.a(dwtms00713.o):(.idata$7+0x0): undefined reference to `_head_libpython27_a'
C:\Python27\libs\libpython27.a(dwtms00221.o):(.idata$7+0x0): undefined reference to `_head_libpython27_a'
C:\Python27\libs\libpython27.a(dwtms00008.o):(.idata$7+0x0): undefined reference to `_head_libpython27_a'
C:\Python27\libs\libpython27.a(dwtms00338.o):(.idata$7+0x0): more undefined references to `_head_libpython27_a' follow
collect2: ld returned 1 exit status
dllwrap: gcc exited with status 1
error: Setup script exited with error: command 'dllwrap' failed with exit status 1
Python info:
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on win32
OS: Windows 7 Professional Edition x64
I'm unsure what other information I might need to provide.
A: I'm having the same problem. The best solution I could come up with was to scrap MinGW and install Visual Studio. For Python 2.7 you need Visual Studio C++ Express Edition 2008 (note that 2010 won't work!)
http://www.microsoft.com/visualstudio/en-us/products/2008-editions/express
If you come up with an answer that works with MinGW please let me know.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problem with generating pdf file I'm trying to generate pdf file from xhtml using Flying Saucer do you have any idea why this code always throwx exception?
import org.xhtmlrenderer.pdf.ITextRenderer
import com.lowagie.text.DocumentException
private void testconfiguration(String taskId) throws IOException, DocumentException {
String inputFile = "/home/marcin/firstdoc.xhtml";
String url = new File(inputFile).toURI().toURL().toString();
String outputFile = "/home/marcin/firstdoc.pdf";
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os); // this line generates Exception
os.close();
}
A: You probably have two incompatible versions of libraries in your classpath (i.e. the xhtmlrenderer library probably expects a version of the lowagie library that is not the one you're using).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Web-based Git that reads Markdown (i.e. README.md like Github) Is there any open source package that provides a web frontend to Git that reads Markdown (i.e. README.md like Github) ?
A: Gitorious understands Markdown syntax in most description fields and whatnot. I don't believe that it will render Markdown content in files, though.
Note that Gitorious provides both project hosting as well as an open source server you can install on your own systems. We're using Gitorious internally and it's quite slick.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where can I download animated gif that are designed for phone mobile applications? I googled about animated gif free download but every site I opened are not good for mobile application. They are all suited for web pages and emails. So where can I download animated gif for these types of mobile application action : upload , download , exit , customers.
A: I hope the sample canvas app can help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wait for a file using Jquery I have this situation where I have to check if a file exists on the server using JQuery. I can use Jquery Ajax to do this, but I need a listener which listens on the server for the presence of the file, and if it is there, then trigger some action.
To provide more sense here is an example,
client--> checks on server for file(time 0)--> not present
client--> checks on server for file(time 5)--> not present
client--> checks on server for file(time 10)--> file present--> return some message to client.
So How do I implement a listener which checks for some particular file on the server and notifies the user when it is available.
A: You can use ajax polling..means check the server at a particular interval of time .
You can use setInterval function in java script to call a particular function ..And write ajax request in that function .and if the file found , just clear the timer
Check the sample code
var timerForLoadingResult= setInterval(checkServerForFile,4000);//call the fnction in every 4 seconds.write ajax in that function.
function checkServerForFile() {
$.ajax({
type: "POST",
cache: false,
url: url,
success: function (result) {
if(check result) //if the file is on server
{
//do something
clearInterval(timerForLoadingResult) // clear timer
}
; }
});
}
A: The ability to run different functions depending on the HTTP Status Code returned by the server was added in jQuery 1.5. So if the server responds with a 200 execute the function needed if file exists and if it returns a 404 execute the function required if it does not.
$.ajax({
statusCode: {
404: function() {
// file not found
},
200: function() {
// file found
}
}
});
For more info see: jQuery.ajax in the jQuery docs.
Edit: From your comments I can see that you need to keep checking until the file exists. If so just wrap the request in a function and then call that function if the file is not found. Use setTimeOut though else you will be spamming the server with connection requests.
A: I would start a listener thread on request and pass in a state object that listener would update after detecting the file. Also on the UI thread i would check the status of the state object if it was updated by the listener thread and perform necessary actions.
UI thread is basically a jQuery ajax call on a timer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Changing view states hi guys my problem is when i create a button in state 1 and click on it according to code it should make a group in another state named as expand. However according to my code it is still making group in current state 1. any guidance will be appreciated.
mybutton.addEventListener(MouseEvent.CLICK, max);
public function max(event:MouseEvent):void
{
currentState = 'expand';
var s:String;
s = "abc";
var myGroup:Group = new Group();
myGroup.id = s;
addElement ( myGroup );
container_Class2(myGroup);
}
A: currentState is just a property of your class, there is no such things as "creating something in a state". If you add an element to your class it will exist whatever the state is.
You can create an element as a child of a container which appears only in a specific state:
<s:Group id="expandContainer" includeIn="expand" />
...
expandContainer.addElement(myGroup);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery IE exception 'nodes' is null or not an object On $(element).trigger('someevent') $('body').trigger("ReciveData"); it works just fine on Firefox, Chrome, Safari
then I come to IE its send me exception this the message:
'nodes' is null or not an object
My code:
try {
var tempId = data.substring(0, 4);
if (ServiceCallerObject.TemplateId == tempId) {
UtillsObject.WriteToLog('Service System Action Request Data On Template Id:' + ServiceCallerObject.TemplateId + ' Recived Message:' + data, 'debug');
ServiceCallerObject.MessageData = ServiceCallerObject._doSuccessOutputParser(ServiceCallerObject.TemplateId, data);
UtillsObject.WriteToLog('Service System Action Param Converted Into Objected', 'info');
$('body').trigger("ReciveData");
}
} catch (e) {
ServiceCallerObject.IsCallActive = false;
ServiceCallerObject.IsStillWaitForCall = false;
UtillsObject.WriteToLog('Service System Action Exeption: {MSG: ' + e.message + ' ,File:' + e.fileName + ' ,Line:' + e.lineNumber + ' ,Type:' + e.name + ' }', 'Debug');
UtillsObject.WriteToLog('Service System Action Request Error In Data On Template Id:' + ServiceCallerObject.TemplateId + ' Recived Message:' + data, 'error');
$('body').trigger("ReciveDataError");
}
How do I fix this in order to make my application working?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is Razor a Step Backwards? I need some convincing on the Razor View Engine.
From what I can tell, Microsoft have simply re-introduced inline code back into markup; weren't code-behind pages originally introduced to eradicate this?
I assume (and hope) that I am missing something :)
A: razor is best used with MVC. Yes it does reintroduce inline code. but it is about separation of code.
Your razor code should not have any logic in it. It really should be used to simply get your data onto a page (small amounts of logic e.g If Data= True THen Should this section, are ok tho)
but all business logic is still in your controller/codebehind
A: I think you should start looking into ASP.NET MVC first. There aren't (or shouldn't be) any code-behinds.
Then compare Web Forms View Engine with Razor View Engine. That should help you.
A: Razor is about making the page more readable by getting rid of bulky <% %> and allowing you to create your own render methods through delegates.
If anything by giving you neat shorthands for dealing with well prepared data it allows you views to look more like HTML, encouraging you NOT to put inline code to process data too much.
Everything that is done in a view should relate to rendering, whether its in Razor syntax or not.
As other answers point out have a look into the structure of an MVC application, all data processing should already be done by the time it comes to render a view.
A: Razor is not for writing your business logic in your view.
Razor is for iterating over model and converting it to html. Your business logic is in controller besides even in WebForms view engine you did the same looping only with a more verbose syntax. Razor has cleaner syntax. It doesn't bring anything else with it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: SQL - Insert Statement conflicting with Foreign Key I've got two tables, Enrolment and Attendance. The Primary Keys of Enrolment are UnitCode and StudentID. The Primary Keys of Assignment are UnitCode, StudentID (both of which are Foreign Keys to the same columns in Enrolment) and AssNo.
I've got a stored procedure named Insert Student Attendance:
ALTER PROCEDURE dbo.InsertStudentAttendance
@unitCode varchar(4),
@studentID integer,
@date datetime
AS
INSERT INTO Attendance
(UnitCode, StudentID, AttDate, AttStatus)
VALUES(@unitCode, @studentID, @date, 1)
RETURN
Calling the procedure like so:
InsertStudentAttendance 'SIT101', 1, '2011-06-04'
Results in the error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Attendance_308E3499". The conflict occurred in database "db_test", table "dbo.Enrolment".
However, this only occurs when I use the stored procedure, not when I manually input the values into the exact same command. In Enrolment, there is a StudentID 1 enrolled in the UnitCode 'SIT101'. Any ideas what's going wrong?
Thanks in advance.
A: In your stored procedure declaration you have @unitCode varchar(4), but it appears the value you are trying to insert is SIT101.
This will get silently truncated to SIT1 which does not exist - hence the FK violation.
Increase the length of the parameter type to match that of the column.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: UIPrintInfo symbol not found error in iOS < 4.2 I want to run printer functionality in my iPhone app, which runs perfect in iOS 4.2 but when I'll try to run that app in iOS < 4.2, it gives me error
dyld: Symbol not found: _OBJC_CLASS_$_UIPrintInfo
What could be the cause and how to resolve this issue?
Thanks!
A: You can't, UIPrintInfo is only available in iOS 4.2 and higher.
What you need to do is check whether UIPrintInfo is available and if it is only then add the button that will allow the user to print:
if (NSClassFromString(@"UIPrintInfo")) {
// Add print button
}
Also weaklinkg the UIKit:
Go to your project and select the "Build Phases" tab, here you will find a list of the "link Binary With libraries".
There should be required behind the UIKit.framework and changed it to optional.
A: you can write this
if (NSClassFromString(@"UIPrintInfo")) { // Add print button }
in your code as well as set one flag in your
project settings -> build -> Other Linker Flags = -weak_framework and
UIKit.
Then you will not get any error at the time of compilation.
Plz take care that Other Linker Flags box should display first flag as -weak_framework and next is UIKit.
Hope this will help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how do i match a space with two shell variables inside awk in just one match function I have a command:
ls -l | nawk -v d1=Sep -v d2=26 '{if(match($0,d1)) print $0}'
-rw-rw-r-- 1 nobody nobody 12 Sep 26 11:36 file1
-rw-rw-r-- 1 nobody nobody 14 Sep 26 11:37 file2
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:46 file3
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:44 file4
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:50 file5
-rw-rw-r-- 1 nobody nobody 0 Sep 26 11:00 file6
-rw-rw-r-- 1 nobody nobody 0 Sep 25 11:00 file7
-rw-rw-r-- 1 nobody nobody 0 Sep 26 14:22 ksh
-rwxrwxr-x 1 nobody nobody 208 Sep 26 16:31 test.sh*
-rwxrwxr-x 1 nobody nobody 62 Sep 26 15:15 test2.sh*
But when i use the below:
ls -l | nawk -v d1=Sep -v d2=26 '{if(match($0,d1 d2)) print $0}'
Its not giving me any output!!
As you can see there is a space between Sep and 26 and i am using the same space in regex to match the string "Sep 26".
could nybody pls help?
I am expecting output to be:
-rw-rw-r-- 1 nobody nobody 12 Sep 26 11:36 file1
-rw-rw-r-- 1 nobody nobody 14 Sep 26 11:37 file2
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:46 file3
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:44 file4
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:50 file5
-rw-rw-r-- 1 nobody nobody 0 Sep 26 11:00 file6
-rw-rw-r-- 1 nobody nobody 0 Sep 26 14:22 ksh
-rwxrwxr-x 1 nobody nobody 208 Sep 26 16:31 test.sh*
-rwxrwxr-x 1 nobody nobody 62 Sep 26 15:15 test2.sh*
A: Assuming user and group names don't contain spaces, here's the Awk way of doing this:
ls -l | nawk -v d1=Sep -v d2=26 '{if(match($6, d1) && match($7, d2)) print $0}'
# NOTE ----^^ ----^^
A: kent$ echo "-rw-rw-r-- 1 nobody nobody 12 Sep 26 11:36 file1
-rw-rw-r-- 1 nobody nobody 14 Sep 26 11:37 file2
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:46 file3
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:44 file4
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:50 file5
-rw-rw-r-- 1 nobody nobody 0 Sep 26 11:00 file6
-rw-rw-r-- 1 nobody nobody 0 Sep 25 11:00 file7
-rw-rw-r-- 1 nobody nobody 0 Sep 26 14:22 ksh
-rwxrwxr-x 1 nobody nobody 208 Sep 26 16:31 test.sh*
-rwxrwxr-x 1 nobody nobody 62 Sep 26 15:15 test2.sh*
"|awk -v d1=Sep -v d2=26 'BEGIN{x=d1" "d2}{ if(match($0,x))print $0;}'
-rw-rw-r-- 1 nobody nobody 12 Sep 26 11:36 file1
-rw-rw-r-- 1 nobody nobody 14 Sep 26 11:37 file2
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:46 file3
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:44 file4
-rw-rw-r-- 1 nobody nobody 0 Sep 26 10:50 file5
-rw-rw-r-- 1 nobody nobody 0 Sep 26 11:00 file6
-rw-rw-r-- 1 nobody nobody 0 Sep 26 14:22 ksh
-rwxrwxr-x 1 nobody nobody 208 Sep 26 16:31 test.sh*
-rwxrwxr-x 1 nobody nobody 62 Sep 26 15:15 test2.sh*
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: c++ Binary Search on dates sorted -> i need a range (cca) I have a binary search on a file. The file is filled with log messages where each line begins with a date (dates or sorted based on event occurs)
example:
*
*2011-09-18 09.38.20.123
*2011-09-18 09.38.20.245
*2011-09-18 09.38.20.393
*2011-09-18 09.38.20.400
*2011-09-18 09.38.20.785
If i need to find this date for example: 2011-09-18 09.38.20.390 my binary search will not find an exact match - but i don't need exact match, i need to find the closest date to it (there is my position).
The current code will jump between 2011-09-18 09.38.20.245 and 2011-09-18 09.38.20.393.
I need some help how to modify the below code so that i get the closest number. In the above situation i would like to have: 2011-09-18 09.38.20.245 (better more than less)
BinarySearch::BinarySearch(QString strFileName,QDateTime dtFrom_target,QDateTime dtTo_target)
{
QFile file(strFileName);
qint64 nFileSize = file.size();
int nNewFromPos;
int nNewToPos;
nNewFromPos = Search(file, dtFrom_target, nFileSize);
nNewToPos = Search(file, dtFrom_target, nFileSize);
if(nNewFromPos!=-1 && nNewToPos!=-1){
// now parse the new range
}
else{
// dates out of bound
}
}
int BinarySearch::Search(QFile &file, QDateTime dtKey, int nMax)
{
file.open(QIODevice::ReadOnly);
char lineBuffer[1024];
qint64 lineLength;
QDateTime dtMid;
int mid;
int min;
if(!min) min = 0;
while (min <= nMax)
{
mid=(min+nMax)/2; // compute mid point.
file.seek(mid); // seek to middle of file (position based on bytes)
qint64 lineLength=file.readLine(lineBuffer,sizeof(lineBuffer)); // read until \n or error
if (lineLength != -1) //something is read
{
// validate string begin (pos = 0) starts with date
lineLength = file.readLine(lineBuffer, 24); //read exactly enough chars for the date from the beginning of the log file
if(lineLength == 23)
{
dtMid = QDateTime::fromString(QString(lineBuffer),"yyyy-MM-dd HH.mm.ss.zzz"); //2011-09-15 09.38.20.192
if(dtMid.isValid())
{
if(dtKey > dtMid){
min = mid + 1;
}
else if(dtKey < dtMid){
max = mid - 1; // repeat search in bottom half.
}
else{
return mid; // found it. return position
}
}
}
}
}
return -1; // failed to find key
}
A: Try to implement an algorithm equivalent to std::equal_range which returns a pair of result of std::lower_bound and std::upper_bound
*
*Find the position of the first element in the sorted range which does not compare less than the value (lower bound)
*Find the position of the first element in the sorted range which compares greater than the value (upper bound)
--
template<typename OutIter>
void ReadLogsInRange(
std::istream& logStream, Log::Date from, Log::Date to, OutIter out)
{
Log l = LowerBound(logStream, from);
*out++ = l;
while(logStream >> l && l.date < to)
*out++ = l;
}
Full example: http://ideone.com/CvIYm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Replacing multiple strings I have an XML file with texts in a certain language and I need to traverse it and translate certain expressions. I was thinkging about creating an array containing the expressions and an array containing the replacements:
var searchFor = ['Foo', 'Bar'];
var replaceWith = ['Bar', 'Foo'];
Is there some way I can traverse the XML effectively replacing all items in the first array with the next?
xml.each(function(){
$(this).text($(this).text().multiReplace(searchFor, replaceWith));
});
What I'm looking for is a javascript function that is equivalent to the PHP function str_replace that can take in an array for the first and second parameters:
http://php.net/manual/en/function.str-replace.php
'FooBar'.multiReplace(searchFor,replaceWith); // should return 'BarFoo'
PS: Alternative solutions are also welcome.
A: For a very simple implementation, since you have jQuery you can use $.each inside you callback :
var txt = $(this).text();
$.each(searchFor, function(i,v){
txt.replace(v, replaceWith[i]);
});
$(this).text(txt);
If you want to swap values, you have to insert tokens that you are sure do not exist in your string.
For instance, '##i##'. (Search for the regexp '##\d+##' in your string. If it exists, then add enclosing '#' and search again until you find a token that you know do not exist in the string.)
var txt = $(this).text();
var tokens = [];
$.each(searchFor, function(i,v){
var token = "##" + i + "##";
tokens.push(token);
txt.replace(v, token);
});
$.each(tokens, function(i,v){
txt.replace(v, searchFor[i]);
});
$(this).text(txt);
A: I have found a solution that seems to work fine. I have extended the String object with the multiReplace function that takes a map of translations as a parameter and returns a new string with the replaced expressions.
String.prototype.multiReplace = function(translations){
var regexStr = '';
var result = '';
for(var key in translations){
regexStr += key + '|';
}
regexStr = '(' + regexStr.substring(0,regexStr.length-1) + ')';
var rx = new RegExp(regexStr,'g');
result = this.replace(rx, function(match){
return translations[match.toLowerCase()];
});
return result;
}
var translations = {
'Foo':'Bar',
'Bar':'Foo'
};
text = 'FooBarFooFooBarBarFooBarFooFoo';
text = text.multiReplace(translations);
// text = "BarFooBarBarFooFooBarFooBarBar"
A: I have this function like ~5 years already. I don't know where i got this.
function str_replace (search, replace, subject) {
var result = "";
var oldi = 0;
for (i = subject.indexOf (search); i > -1; i = subject.indexOf (search, i)) {
result += subject.substring (oldi, i);
result += replace;
i += search.length;
oldi = i;
}
return result + subject.substring (oldi, subject.length);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP, MySQL table query syntax error? I hope someone can help see what's wrong here:
I have a form with two field EMAIL and PASSWORD that opens a php page where I intend to run a simple query on a table.
I get an error message that makes no sense:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@gmail.com' at line 1.
The email address I entered in this case did end with '@gmail.com'
Here's the code:
<?php
$dbhost = 'somewhere.net';
$dbuser = 'someUser';
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn));
$email = mysql_real_escape_string($_POST['email']);
$query = "SELECT * FROM employee WHERE email = $email";
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));
while ($row = mysql_fetch_array($result)) {
extract($row);
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>
Any advice would be appreciated.
A: You are missing quotes around string fields:
$query = "SELECT * FROM employee WHERE email = '$email'";
Additionally,
extract(mysql_fetch_assoc($result));
will fetch the first row from the database, so your while loop will start from the second row.
A: You have to put the value in quotes inside SQL string.
$email = mysql_real_escape_string($_POST['email']);
$query = "SELECT * FROM employee WHERE email = '$email'";
(mind the extra '' around $email)
A: Your query translates to:
SELECT * FROM emloyee WHERE email = foo@bar.com
This doesn't work, you have to put strings in quotes. Change your code to the following and it will work:
$query = "SELECT * FROM employee WHERE email = '$email'";
A: Just single quote the variable '$email' because it varchar type value and field .
As wrote, Darhazer :)
A: Full fixed code:
<?php
$dbhost = 'somewhere.net';
$dbuser = 'someUser';
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn));
$email = mysql_real_escape_string($_POST['email']);
$query = "SELECT * FROM employee WHERE email = '$email'";
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));
while ($row = mysql_fetch_array($result)) {
extract($row);
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to convert a date given as "20110912T220000"(NSString) to NSDate I am getting start and end dates for my calendar event(while parsing a .ics file) in "20110912T220000" format. How can I convert this to a NSDate to add to add as event(EKEvent)'s startDate property.
If anyone knows please help me soon.
A: You should use NSDateFormatter for this.
See Data Formatting Guide (the Date & Time Programming Guide may also be interesting)
This is also detailed in this Technical Note in Apple's Q&As. Note that for such situations, you should use the special "en_US_POSIX" locale as explained in this technical note.
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
[df setDateFormat:@"yyyyMMdd'T'HHmmss"];
NSDate* parsedDate = [df dateFromString:...];
A: NSString *dateString = @"20110912T220000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
formatter.locale = locale;
formatter.dateFormat = @"yyyyMMdd'T'HHmmss";
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date: %@", date);
NSLog() output: date: 2011-09-13 02:00:00 +0000
Note, NSLog outputs the data in you local timezone.
Note the single quotes around the 'T' in the date format.
Here is a link to UTS: date/time format characters
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Reflection, generics, eventhandlers and delegates problem I’m struggling with reflection, generics, eventhandlers and delegates. I have a Type which is derived from AsyncCompletedEventArgs. I would like to create a generic EventHandler instance with this Type and also a delegate. Afterwards I want to add this eventhandler to an event.
Can anyone help my creating the eventhandler and delegate by using reflection? All help is appreciated.
// The type is derived from AsyncCompletedEventArgs
Type[] typeArgs = { soapServiceInfo.GetEntitiesCompletedEventArgsType };
var eventHandlerType = typeof(EventHandler<>);
var constructed = eventHandlerType.MakeGenericType(typeArgs);
// getEntitiesCompleted = (sender, arguments) => { }
// soapServiceInfo.GetEntitiesCompletedEventInfo.AddEventHandler(client, getEntitiesCompleted);
A: You can only create a lambda expression for types known at compile time.
You're trying to create a lambda expression at runtime; to do that, you need to compile an expression tree.
A: Look at Delegate.CreateDelegate()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Make an image follow the frame size I'm using Java Swing to make a GUI.
I need to present to the user some information printed on images (which are generated at run time as BufferedImage objects).
What I am doing: I put a JPanel on my JFrame, and when the system calls the paint(Graphics g) method I draw the image on g -> (g.drawImage(buffImg,0,0,null)).
The thing I do not like is: When I resize the frame, the image remains the same, I only expand the field of view. I'd like instead to make the image "stretch" with the frame when I resize it.
Is there an efficient way of doing it? (I thought I could create a new resized image, the size of the frame, each time I refresh the graphics, but I'm updating the image several times per second, so it would be a really heavy task..)
A: Change:
g.drawImage(BuffImg,0,0,null):
To:
g.drawImage(BuffImg,0,0,getWidth(),getHeight(),this):
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Set DataFormatString for MVC3 DateTime I have some issue with displaying date correctly, using the MVC3 DateTime object.
In the controller, I set Date = DateTime.Now.
In ViewModel:
[Required(ErrorMessage = "Please enter a date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.mm.yyyy}")]
public DateTime Date { get; set; }
In View:
@Html.LabelFor(m => Model.Date, "Date")
@Html.ValidationMessageFor(m => Model.Date)
@Html.TextBoxFor(m => Model.DatoForIntervju, new { @class = "datepicker" })
Output:
<input class="datepicker" (...) value="26.09.2011 13:26:16" />
However, I want the value to be 26.09.11.
Why doesn't it work?
A: Your viewModel correct (only thing is you need to use "yy" if you want to show short year in C#), but I don't understand what do you do with this code
@Html.LabelFor(m => Model.Date, "Date")
@Html.ValidationMessageFor(m => Model.Date)
@Html.TextBoxFor(m => Model.DatoForIntervju, new { @class = "datepicker" })
I show you how I add datepicker, in this example date shows and return from view in correct format:
@Html.EditorFor(m => m.Date)
@Html.ValidationMessageFor(m => m.Date)
<script type="text/javascript">
$(document).ready(function () {
$('#Date').datepicker({ firstDay: 1, dateFormat: 'dd.mm.yy', clickInput: true });
});
</script>
A: change
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.mm.yyyy}")]
to
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yy}")]
Then, instead of textboxfor, use
@Html.EditorFor(m => m.Date)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How can I save a custom type as binary data in .NET? I'm creating something that has save files. For the most part, it's just saving objects with 4 values.
*
*x
*y
*id
*layer
I've been saving this as XML for a while, the problem is, the files are starting to get HUGE because I'm saving hundreds to thousands of these objects and XML is kind of bulky for something like this. I tried switching to Json but it was too big as well (I will admit though, better).
My Question
I know a lot of programs save directly using bytes to conserve space. I want to do this. Say I have 300 objects with the properties X, Y, Id, and Layer, how could I save this to file x as bytes and load it later?
I've tried reading bytes when I used to make my own servers. I usually ended up getting frustrated and giving up. I'm hoping this isn't too similar (my gut says otherwise).
EDIT
Oh sorry guys, I forgot to mention, I'm using VB.NET so all .NET answers are acceptable! :)
Also, all of these values are integers.
A: I would use protobuf-net (I would; I'm biased...). It is an open-source .NET serializer, that uses attributes (well, that is optional in v2) to guide it. For example, using C# syntax (purely for my convenience - the engine doesn't care what language you use):
[ProtoContract]
public class Whatever {
[ProtoMember(1)]
public int X {get;set;}
[ProtoMember(2)]
public int Y {get;set;}
[ProtoMember(3)]
public long Id {get;set;}
[ProtoMember(4)]
public string Layer {get;set;}
}
You can then serialize, for example:
List<Whatever> data = ...
Serializer.Serialize(file, data);
and deserialize:
var data = Serializer.Deserialize<List<Whatever>>(file);
job done; fast binary output. You probably can get a little tighter by hand-coding all reading/writing manually without any markers etc, but the above will be a lot less maintenane. It'll also be easy to load into any other platform that has a "protocol buffers" implementation available (which is: most of them).
A: Alternative:
why not xml and zip (or some other compression)
Advantage:
* its still "human" readable
* text files have normaly a good compression factor
Also what programming languae you are using?
in C/C++ or you create a struct with the data
reinterpret cast the struct to byte * and write sizeof bytes to the file... simple as that
(assuming the struct is fixed size (id and layer are also fixed sized variables like int)
A: Why don´t you use a database like MySql or SQL ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: In Notepad++, using regular expressions to delete something on each line starting with a certain character? On each line, I have a list of pdfs followed by junk.
Like:
yes.pdf xxxxxx
no.pdf aewrnnta
hello.pdf aewraewr
I would like to make it so I get
yes
no
hello
on three separate lines
How can I do this with regex?
A: Try -
\.pdf.* in find box
and
'' in replace box
Make sure you have the RegEx radio button checked.
A: Find:
^([^.]*)\..*
Replace with:
\1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jsoncpp problems I am using Jsoncpp to parse json-formats for c++.
I do not understand how it works though; there is a lack of documentation and examples to get me started, and I was wondering if anyone could give me some quick pointers. The only examples I've found deals with files...
*
*I'm using a HTTP stack to get a json-message in a buffer. For example, a buffer contains the message {"state":"Running"}. How do I use the Json::reader to parse this? Again the only example I've found deals with reading from files
*How do you write values to a Json-message? For example I want to write "monkey : no" and "running : yes" to a Json-message which I can then use in my GET request.
Thanks
UPDATE:
on 1), for example, how to parse a buffer containing a json-message like this:
char* buff;
uint32_t buff_size;
A: Maybe this is good sample for first part of your question:
Json::Value values;
Json::Reader reader;
reader.parse(input, values);
Json::Value s = values.get("state","default value");
A: There is anything but lack of documentation. Yes, it's mainly reference documentation, but it's quite good and well cross-linked.
*
*Just read the documentation
*Just use this class or possibly use the other class
A: Sample code for your reference, below:
file.json
{
"B":"b_val2",
"A":{
"AA":"aa_val1",
"AAA" : "aaa_val2",
"AAAA" : "aaaa_val3"
},
"C":"c_val3",
"D":"d_val4"
}
jsoncpp usage scenario as below, for above sample json file.
#include <iostream>
#include "json/json.h"
#include <fstream>
using namespace std;
int main(){
Json::Value root;
Json::Reader reader;
const Json::Value defValue; //used for default reference
std::ifstream ifile("file.json");
bool isJsonOK = ( ifile != NULL && reader.parse(ifile, root) );
if(isJsonOK){
const Json::Value s = root.get("A",defValue);
if(s.isObject()){
Json::Value s2 = s.get("AAA","");
cout << "s2 : " << s2.asString() << endl;
}else{
cout << "value for key \"A\" is not object type !" << endl;
}
}
else
cout << "json not OK !!" << endl;
return 1;
}
Output::
s2 : aaa_val2
Additionally, I have used the "amalgamate.py" for generating and using the jsoncpp for the sample source above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to attach a DataPoint with a Theory? @DataPoints public static final Integer[] input1={1,2};
@Theory
@Test
public void test1(int input1){
}
@DataPoints public static final Integer[] input2={3,4};
@Theory
@Test
public void test2(int input2 ){
}
I want that test1 runs with data set input1 - {1,2} and test2 runs with input2 - {3,4}. But currently each test runs with both the data sets {1,2,3,4}. How to bind specific @DataPoints to specific @Theorys
A: In reference to Gábor Lipták's answer, named datapoints can be defined as a static fields (reference) which give us more concise code:
@RunWith(Theories.class)
public class TheoriesAndDataPointsTest {
@DataPoints("a values")
public static int[] aValues = {1, 2};
@DataPoints("b values")
public static int[] bValues = {3, 4};
@Theory
public void theoryForA(@FromDataPoints("a values") int a) {
System.out.printf("TheoryForA called with a = %d\n", a);
}
@Theory
public void theoryForB(@FromDataPoints("b values") int a) {
System.out.printf("TheoryForB called with b = %d\n", a);
}
}
A: With JUnit 4.12 (not sure when it was introduced) it is possible to name the DataPoints and assign them to parameters (i learned it from http://farenda.com/junit/junit-theories-with-datapoints/):
@RunWith(Theories.class)
public class TheoriesAndDataPointsTest {
@DataPoints("a values")
public static int[] aValues() {
return new int[]{1, 2};
}
@DataPoints("b values")
public static int[] bValues() {
return new int[]{3, 4};
}
@Theory
public void theoryForA(@FromDataPoints("a values") int a) {
System.out.printf("TheoryForA called with a = %d\n", a);
}
@Theory
public void theoryForB(@FromDataPoints("b values") int a) {
System.out.printf("TheoryForB called with b = %d\n", a);
}
}
Output:
TheoryForA called with a = 1
TheoryForA called with a = 2
TheoryForB called with b = 3
TheoryForB called with b = 4
A: DataPoints apply to the class. If you have a @Theory method which takes an int, and you have a DataPoint which is an array of ints, then it will be called with the int.
@RunWith(Theories.class)
public class TheoryTest {
@DataPoint public static int input1 = 45;
@DataPoint public static int input2 = 46;
@DataPoints public static String[] inputs = new String[] { "foobar", "barbar" };
@Theory public void testString1(String input) {
System.out.println("testString1 input=" + input);
}
@Theory public void testString2(String input) {
System.out.println("testString2 input=" + input);
}
@Theory public void test1(int input) {
System.out.println("test1 input=" + input);
}
@Theory public void test2(int input) {
System.out.println("test2 input=" + input);
}
}
This calls test1 with 45 & 46, and test2 with 45 & 46. It calls testString1 with "foobar" and "barbar" and testString2 with "foobar" and "barbar".
If you really want to use different data sets for different theories, you can wrap the data in a private class:
@RunWith(Theories.class)
public class TheoryTest {
public static class I1 { int i; public I1(int i) { this.i = i;} }
public static class I2 { int i; public I2(int i) { this.i = i;} }
@DataPoint public static I1 input1 = new I1(45);
@DataPoint public static I2 input2 = new I2(46);
@Theory
public void test1(I1 input) {
System.out.println("test1 input=" + input.i);
}
@Theory
public void test2(I2 input) {
System.out.println("test2 input=" + input.i);
}
}
This calls test1 with 45 and test2 with 46. This works, but in my opinion, it obscures the code, and it may be a better solution to just split the Test class into two classes.
A: Some of the references I have seen talking about using tests for specific values and theories for verifying behavior. As an example, if you have a class that has methods to add and subtract from an attribute, a test would verify correctness of the result (e.g., 1+3 returns 4) whereas a theory might verify that, for the datapoint values (x1, y1), (x2, y2), x+y-y always equals x, x-y+y always equals x, x*y/y always equals x, etc. This way, the results of theories are not coupled as tightly with the data. With theories, you also can filter out cases such as y == 0; they don't count as failure. Bottom line: you can use both. A good paper is: http://web.archive.org/web/20110608210825/http://shareandenjoy.saff.net/tdd-specifications.pdf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Strange limitation in ArrayBufferView constructor The TypedArray specification states that an ArrayBufferView may be created this way:
TypedArray(ArrayBuffer buffer,
optional unsigned long byteOffset, optional unsigned long length)
However, the second parameter, byteOffset, has a limitation:
The given byteOffset must be a multiple of the element size of the
specific type, otherwise an exception is raised.
This means we cannot work with odd offsets for two-byte views, such as:
var view1 = new Uint8Array([0, 1, 2, 3]),
view2 = new Uint16Array(view1.buffer, 1, 1);
So, even though [1,2] could be correctly converted into Uint16, I can't access those elements that way.
The byteOffset limitation seems to significantly decrease ArrayBufferView's flexibility.
Does anybody know why this limitation was imposed?
A: This restriction was imposed in order to maintain maximum performance for the typed array views such as Uint16Array and Float32Array. These types are designed to operate on data in the machine's natural alignment. Supporting unaligned loads would either slow down the fast case unacceptably, or lead to performance "cliffs" where programs would mostly run fast, except when they slowed down by a large factor.
DataView is designed to support unaligned loads and stores of single elements of data, specifically to handle the case of networking or disk I/O, where file formats may not have any alignment restrictions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Applying CssStyle to Infragistics WebDataGrid column, when loading dynamically I'm trying to right-align a column in my WDG. I've been through the Infragistics tutorials, so I know that I need to added a new CSS style as such...
tbody > tr > td.ColumnRight
{
text-align: right;
}
Then on my column apply CssStyle="ColumnRight"
However, my WDG is on a usercontrol which is dynamically loaded.
When the page comes up the right-align has not taken hold.
It does not work until you refresh the page (F5) - but this is undesirable, really need the style in place upon first-load.
Its obviously a problem with the dynamic loading, but any ideas how to fix it?
Any help much appreciated!
A: For looking into this, I would look at the css that is applied to the cells by using an element inspector like provided by the developer tools for IE or fire bug on Firefox. This should help you to know if your css is being loaded and something else is taking precedence.
Also, when you dynamically load the UserControl is it on a full post back or an AJAX call back such as inside of an update panel? If in an AJAX call and you change the call to be a full post back, does it change the behavior?
Is the behavior consistent across multiple web browsers or does it only occur in one browser?
For more specific suggestions, I would need more details on how you are dynamically loading the UserControl and where the CSS is. Is it in another file, a style on the page/user control?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make a news Scroller for our Web Site I Have a problem that, I want design a Scroller which contains a dynamic data from Database which is updatable by an administrator of the web site and I want to redirect on diffrent Pages when I Selected one of them,and all the values in the scroller is going to upwards from Bottom. I don't know how to implement that?
PLease suggest me for right answer.
Thanks in advance.
A: Try this:
http://flowplayer.org/tools/demos/scrollable/vertical.html
combined with using Server Side code to generate the data for the scroller.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Page Administration & Open Graph I'm an Admin for this page
http://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fwww.westberks.gov.uk%2Findex.aspx%3Farticleid%3D23789
and I've also specified that my App can administer it too. I've Liked this page so I thought I should be able to access the admin screen for the page but I can't seem to. Any ideas on how I access the admin screen for this page in FB, so I can manually publish updates?
Additionally, when I try to update page programmatically I get the message
(OAuthException) (#200) The user hasn't authorized the application to perform this action
but the page has my App listed here
http://graph.facebook.com/10150303466842688
A: This was definitely a bug rather than a programming or setup issue. The bug has been marked fixed by Facebook as of 1/18/2012 and everything now works as it is supposed to! Bug report:
http://developers.facebook.com/bugs/308356579205492?browse=search_4f0f1475c470b2076799347
Until this recent fix, there was a problem where OpenGraph pages did NOT allow the admins of those pages to retrieve page access tokens for them. Which means they were locked out of posting "as the page" and apparently also locked out of the Admin area for their own pages as well.
I know that this is fixed for me now with this bugfix, and hopefully it will also be fixed for everyone else.
A: You will need to ask for manage_pages, read_stream and publish_stream. Once your admin accepts those permissions, the app can call me/accounts on the Graph (play here https://developers.facebook.com/tools/explorer). In there will be a list of all the pages they admin. In each listing will be a unique access token. This is called the page access token. Using that token you should be able to read and write to the me/feed for that page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting window coordinates of the insertion point - Cocoa What is the best way to get window coordinates of the current caret position in a text edit control in Cocoa?
Here is how I do that in other platforms
*
*Windows - EM_POSFROMCHAR
*GTK - Using gtk_text_view_get_iter_location and gtk_text_view_buffer_to_window_coords.
I am wondering how the same can be done using Cocoa. I am on MacOSX 10.6.8 and I am doing this using C++.
A: Assuming textView is a variable that points to the text view and window is a variable that points to the window:
// -firstRectForCharacterRange:actualRange returns a frame rectangle
// containing the insertion point or, in case there's a selection,
// the first line of that selection. The origin of the frame rectangle is
// in screen coordinates
NSRange range = [textView selectedRange];
NSRect screenRect = [textView firstRectForCharacterRange:range actualRange:NULL];
// -convertRectFromScreen: converts from screen coordinates
// to window coordinates
NSRect windowRect = [window convertRectFromScreen:screenRect];
// The origin is the lower left corner of the frame rectangle
// containing the insertion point
NSPoint insertionPoint = windowRect.origin;
A: The following method is in the documentation
- (void)drawInsertionPointInRect:(NSRect)aRect color:(NSColor *)aColor turnedOn:(BOOL)flag
it says
The focus must be locked on the receiver when this method is invoked. You should not need to invoke this method directly.
If you override this method (and call the super implementation) in an NSTextView subclass it would allow you to know the position of the insertion point, at least when it's required by Cocoa.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Using applicationComplete and initialize together in flex? <?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="init();" initialize="initializeHandler(event)">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
import sandacreative.sqlite.events.StatementSuccessEvent;
import sandacreative.sqlite.SQLiteManager;
private var database:SQLiteManager = SQLiteManager.getInstance();
protected function initializeHandler(event:FlexEvent):void
{ trace("inside initializehandler");
database.start("Users.db", "Users", "CREATE TABLE Users(UserId VARCHAR(150) PRIMARY KEY, UserName VARCHAR(150))");
database.addEventListener(SQLiteManager.COMMAND_EXEC_SUCCESSFULLY, onSelectResult);
database.addEventListener(SQLiteManager.COMMAND_EXEC_FAILED, function():void {
trace("fail!");
});
readEntries();
}
private function insertEntry():void
{
var sql:String = "INSERT INTO Users VALUES('"+nameField.text+"');";
database.executeCustomCommand(sql);
}
// SQLite Ends Here*/
import flash.media.Camera;
import sandacreative.WebCam;
import sandacreative.Base64;
import mx.core.UIComponent;
import mx.graphics.codec.JPEGEncoder;
private var webCam:WebCam;
private function init():void {
webCam = new WebCam(160, 120);
var ref:UIComponent = new UIComponent();
preview.removeAllChildren();
preview.addChild(ref);
ref.addChild(webCam);
}
</fx:Script>
<mx:Panel width="180" height="160" id="preview" title="Snapshotr" x="158" y="343"/>
<mx:Button label="Save" id="submit" x="280" y="521" width="100" enabled="true" click="insertEntry();"/>
init() initiates a cam and that works properly .. while initiliseHandler() creates a sqlite table. But the table is not created and when i try to save it shows the error
Error: Error #3104: A SQLConnection must be open to perform this operation.
at Error$/throwError()
at flash.data::SQLStatement/checkAllowed()
at flash.data::SQLStatement/checkReady()
at flash.data::SQLStatement/execute()
at sandacreative.sqlite::SQLiteManager/executeCustomCommand()[C:\Documents and Settings\sujith\My Documents\Visitrac1\src\sandacreative\sqlite\SQLiteManager.as:238]
at sandacreative::Main/insertEntry()[C:\Documents and Settings\sujith\My Documents\Visitrac1\src\sandacreative\Main.mxml:34]
at sandacreative::Main/__submit_click()[C:\Documents and Settings\sujith\My Documents\Visitrac1\src\sandacreative\Main.mxml:153]
SQLiteManager.as
package sandacreative.sqlite
{
import sandacreative.sqlite.events.StatementSuccessEvent;
import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.errors.SQLError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.filesystem.File;
public class SQLiteManager extends EventDispatcher implements ISQLiteManager
{
/**
* Database file name and extension
*/
public var dbFullFileName:String;
/**
* Database Name
*/
public var tableName:String;
/**
* SQL command to create the database
*/
public var createDbStatement:String;
// datsbase apis instances
protected var connection:SQLConnection;
protected var statement:SQLStatement;
protected var sqlFile:File;
// repeated sql command
protected var repeateFailCallBack:Function;
protected var repeateCallBack:Function;
protected var repeateSqlCommand:String = "";
// events strings
public static var COMMAND_EXEC_SUCCESSFULLY:String = "commandExecSuccesfully";
public static var DATABASE_CONNECTED_SUCCESSFULLY:String = "databaseConnectedSuccessfully";
public static var COMMAND_EXEC_FAILED:String = "commandExecFailed";
public static var DATABASE_READY:String = "databaseReady";
// Singleton instance.
protected static var instance:SQLiteManager;
/**
* Enforce singleton design pattern.
*
* @param enforcer
*
*/
public function SQLiteManager(enforcer:AccessRestriction)
{
if (enforcer == null)
throw new Error("Error enforcer input param is undefined" );
}
/**
* Opens a database connection.
*
* @param dbFullFileName the database file name for instance: Users.sql
* @param tableName holds the database name, for instance: Users
* @param createTableStatement holds the create database statment for instance: CREATE TABLE Users(userId VARCHAR(150) PRIMARY KEY, UserName VARCHAR(150))
*
*/
public function start(dbFullFileName:String, tableName:String, createTableStatement:String):void
{
this.dbFullFileName = dbFullFileName;
this.tableName = tableName;
this.createDbStatement = createTableStatement;
connection = new SQLConnection();
sqlFile = File.applicationStorageDirectory.resolvePath(dbFullFileName);
try
{
connection.open(sqlFile);
this.dispatchEvent(new Event(DATABASE_CONNECTED_SUCCESSFULLY));
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
fail();
}
}
/**
* Close connection
*
*/
public function close():void
{
connection.close();
}
/**
* Test the table to ensure it exists. Sends a fail call back function to create the table if
* it doesn't exists.
*
*/
public function testTableExists():void
{
var sql:String = "SELECT * FROM "+tableName+" LIMIT 1;";
executeCustomCommand(sql, this.onDatabaseReady, this.createTable );
}
/**
* Method to create the database table.
*
*/
private function createTable():void
{
statement = new SQLStatement();
statement.sqlConnection = connection;
statement.text = createDbStatement;
statement.execute();
statement.addEventListener(SQLEvent.RESULT, onDatabaseReady);
}
/**
* Common sql command: select all entries in database
*
* @param callback
* @param failCallback
*
*/
public function executeSelectAllCommand(callback:Function=null, failCallback:Function=null):void
{
var sql:String = "SELECT * FROM "+tableName+";";
executeCustomCommand(sql, callback, failCallback);
}
/**
* Common sql command: delete all entries in database
*
* @param callback
*
*/
public function executeDeleteAllCommand(callback:Function=null):void
{
var sql:String = "DELETE * FROM "+tableName+";";
executeCustomCommand(sql, callback);
}
/**
* Method to execute a SQL command
*
* @param sql SQL command string
* @param callback success call back function to impliment if necessery
* @param failCallBack fail call back function to impliment if necessery
*
*/
public function executeCustomCommand(sql:String, callBack:Function=null, failCallBack:Function=null):void
{
statement = new SQLStatement();
statement.sqlConnection = connection;
statement.text = sql;
if (callBack!=null)
{
statement.addEventListener(SQLEvent.RESULT, callBack);
}
else
{
statement.addEventListener(SQLEvent.RESULT, onStatementSuccess);
}
statement.addEventListener(SQLErrorEvent.ERROR, function():void {
fail();
});
try
{
statement.execute();
}
catch (error:SQLError)
{
this.handleErrors(error, sql, callBack, failCallBack);
}
}
/**
* Utility method to clean bad characters that can break SQL commands
*
* @param str
* @return
*
*/
public static function removeBadCharacters(str:String):String
{
var retVal:String = str.split("'").join("’’");
return retVal;
}
// ------------------------------HANDLERS----------------------------
/**
* Method to handle SQL command that create the dataabase.
* If the method was created due to a fail SQL command method checks if need to repeate any SQL command.
*
* @param event
*
*/
private function onDatabaseReady(event:Event=null):void
{
var evt:Event = new Event(DATABASE_READY);
this.dispatchEvent(evt);
if (repeateSqlCommand != "")
{
this.executeCustomCommand(repeateSqlCommand, repeateCallBack, repeateFailCallBack);
repeateSqlCommand = "";
repeateFailCallBack = null;
repeateCallBack = null;
}
}
/**
* Handle successful calls
* @param event
*
*/
private function onStatementSuccess(event:SQLEvent):void
{
var results:Object = statement.getResult();
var evt:StatementSuccessEvent = new StatementSuccessEvent(COMMAND_EXEC_SUCCESSFULLY, results);
this.dispatchEvent(evt);
}
/**
* Error handler
*
* @param error
* @param sql
* @param callBack
* @param failCallBack
*
*/
private function handleErrors(error:SQLError, sql:String, callBack:Function, failCallBack:Function):void
{
trace("Error message:", error.message);
trace("Details:", error.details);
if (error.details == "no such table: '"+tableName+"'")
{
repeateSqlCommand = sql;
repeateFailCallBack = failCallBack;
repeateCallBack = callBack;
createTable();
}
else
{
if (failCallBack != null)
{
failCallBack();
}
else
{
fail();
}
}
}
/**
* Handler for fail calls
*
* @param event
*
*/
private function fail(event:Event=null):void
{
var evt:Event = new Event(COMMAND_EXEC_FAILED);
this.dispatchEvent(evt);
close();
}
/**
* Method function to retrieve instance of the class
*
* @return The same instance of the class
*
*/
public static function getInstance():SQLiteManager
{
if( instance == null )
instance = new SQLiteManager(new AccessRestriction());
return instance;
}
}
}
class AccessRestriction {} // can this happen ?
ISQLiteManager.as
package sandacreative.sqlite
{
/**
* Describes the contract for Objects that serve as a central point to access SQLite database.
*
* @author Elad Elrom
*
*/
public interface ISQLiteManager
{
function start(dbFullFileName:String, tableName:String, createTableStatement:String):void
function close():void
}
}
StatementSucessEvent.as
package sandacreative.sqlite.events
{
import flash.events.Event;
public class StatementSuccessEvent extends Event
{
/**
* Holds the event string name
*/
public static var COMMAND_EXEC_SUCCESSFULLY:String = "command_exec_succesfully";
/**
* Holds results object
*/
public var results:Object;
/**
* Default constructor
*
* @param type event name
* @param videoList video list collection
*
*/
public function StatementSuccessEvent(type:String, results:Object)
{
super(type);
this.results = results;
}
}
}
I took this code from Elad Elrom
Is that because i used both applicationComplete and Initilize together ? Please help
A: The error is kind of obvious. Your database hasn't been created/connected yet before your button is pressed. Also, the createTable function is never called because you never keep state on your connection property.
Before any statement is executed, you should always check that the DB is connected. For all you know, the connection failed.
And thirdly (and probably most important), you are doing a synchronous execution because you used connection.open. For this to work, you need to do connection.begin() before executing any statements and finish with connection.commit(). I think the better way for you to go here is to use connection.openAsync instead to create an asynchronous execution which is easier to manage and probably what you wanted to do. Only use synchronous if the order of the statements are important (like in a transaction or if one statement is dependent on another).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Is there a performance benefit to creating a multiple index on a primary key + foreign key? If I have a table that has a primary key and a foreign key, and searches are frequently done with queries that include both (...WHERE primary=n AND foreign=x), is there any performance benefit to making a multiple index in MySQL using the two keys?
I understand that they are both indexes already, but I am uncertain if the foreign key is still seen as an index when included in another table. For example, would MySQL go to the primary key, and then compare all values of the foreign key until the right one is found, or does it already know where it is because the foreign key is also an index?
Update: I am using InnoDB tables.
A: For equality comparisons, you cannot get an improvement over the primary key index (because at that point, there is at most just one row that can match).
The access path would be:
*
*look at the primary key index for primary = n
*get the single matching row from the table
*check any other conditions using the row in the table
A composite index might make some sense if you have a range scan on the primary key and want to narrow that down by the other column.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: help with facebook and twitter share buttons im trying to create something similar to this, which is going to show up on each post that I put on my wordpress site. ideally I want it so i can try it out on normal HTML then transfer it to wordpress if possible.
can some one advice me on what the best way of doing this would be.
A: wordpress has plugins to achive this.
http://wordpress.org/extend/plugins/fblikebutton/
http://wordpress.org/extend/plugins/wp-twitter-retweet-button/screenshots/
These are developer's api page from facebook and twitter you can refer them too,
http://developers.facebook.com/docs/reference/plugins/like/
https://dev.twitter.com/docs/tweet-button
A: there's a share-this plugin u can download this lets you set custom settings for social websites.
http://help.sharethis.com/integration/wordpress
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: YouTube PHP API - Getting status of previously uploaded video? Just started digging into the YouTube PHP API and got the browser-based Zend upload script working. However, I can't find any documentation on how to retrieve the status of the video after it's been uploaded. The main reason I would need this is for error handling - I need to be able to know whether the video was approved by YouTube, since someone could technically upload an image or a file too large. I need to know that the vid was approved so that I know what message to display the end user when they return to the site (ie 'Your video is live' or 'Video upload failed').
The YouTube PHP browser-based upload returns a URL parameter status of 200 even if the format or size is incorrect, which is of course not helpful. Any ideas on how else to get this info from the YT object?
All in all, when a user returns to the site, I want to be able to create a YT object based on their specific video ID, and want to be able to confirm that it was not rejected. I'm using ClientLogin to initiate the YouTube obj:
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'myuser@gmail.com',
$password = 'mypassword',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
Any thoughts?
A: Whew, finally found the answer to this after searching around and piecing together code for the last few days. After you create the $yt object, use the following to check the status:
$yt->setMajorProtocolVersion(2);
$youtubeEntry = $yt->getVideoEntry('YOUR_YOUTUBE_VID_ID', null, true);
if ($youtubeEntry->getControl()){
$control = $youtubeEntry->getControl();
$state = $control->getState()->getName();
}
Echoing out $state displays the string 'failed' if the video was not approved for whatever reason. Otherwise it's empty, which means it was approved and is good to go (Guessing the other state names would be: processing, rejected, failed, restricted, as Mient-jan Stelling suggested above).
Crazy how tough this answer was to put together for first-time YouTube API'ers. Solved! (Pats self on back)
A: Do you have a CallToken if so its pretty easy.
For this example i use Zend_Gdata_Youtube with Zend AuthSub.
WHen uploading your video you had a CallToken, With this call token you can access the status of the video.
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'myuser@gmail.com',
$password = 'mypassword',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$youtube = new Zend_Gdata_YouTube( $httpClient, '', NULL, YOUTUBE_DEVELOPER_KEY );
$youtubeEntry = $youtube->getFullVideoEntry( 'ID_OF_YOUTUBE_MOVIE' );
// its the 11 digit id all youtube video's have
in $youtubeEntry all your data about the video is present
$state = $youtubeEntry->getVideoState();
if state is null then your video is available else make of state a string like this.
(string) $state->getName();
There are about 4 important state names. ( processing, rejected, failed, restricted)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to save dynamically changed HTML? I have around 8 div items arranged in UL LI list. Each has unique ID, and specific content.These items are sortable, I am using jquery UI for this. Once user drag and drop component position of list item changes. But after refreshing the page I am getting same HTML page. I want to retain new positions of items at server. What is the effective way to do this? I can create clone of HTML and retain it during the session but i want changes to be saved at server. The change of position of the element is specific to user.. This is something like element positions are changed by the user and he want to save the settings.. thank for the help in advance
A: Don't bother inspecting the resulting HTML. Rather, just communicate the new ordering of the items back to the server via AJAX. This could be as simple as a sequence of numbers. Store those and use them next time to create the list in the desired order.
A: you could store the position in a cookie, and rearange after refresh based on that cookie
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ruby Gem for comments with mongoid I am in need to integrate comments to my existing mongoid documents. is there any rubygem available to achieve it?
A: usually you'd use acts_as_commentable
https://github.com/jackdempsey/acts_as_commentable
but it only works with ActiveRecord.
Use this one for Mongoid:
https://github.com/mgolovnia/mongoid_commentable
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java - AWS - too many files open I'm using the java AWS SDK in order to download a big amount of files from one S3 bucket, edit the files, and copy them back to a different S3 bucket.
I think it's supposed to work fine, but there is one line that keeps throwing me exceptions:
when I use
myClient.getObject(myGetObjectRequest, myFile)
I get an AmazonClientException saying there are too many files open.
Now, each time I download a file, edit it and copy it back to the bucket, I delete the temporary files I create.
I'm assuming it's taking a few milliseconds to delete the file, and maybe that's why I'm getting these errors.
Or is it maybe because of the open files on Amazon's side?
Anyway, I made my application sleep for 3 seconds each time it encounters this exception, that way it would have time to close the files, but that just takes too much time. Even if I'll take it down to 1 second.
Has anybody encountered this problem?
What should I do?
Thanks
A: Do you actually call "myFile.close()" at some point?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I combine MinimumSize with AutoScrollMinSize in c# .net dockable forms? I want my dockable Winforms to have a minimum size when floating. They also show scrollbars if they are minimized to less than a set AutoScrollMinSize property. If I add a MinimumSize property to get a desired behaviour the scrollbars stop working.
How can I both use the AutoScrollMinSize and the MinimumSize properties on my forms?
Thanks!
A: Set AutoScrollMinSize to some value smaller than MinimumSize so the form will still display scroll bars even if the form is at its minimum size.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Multithreading problem using System.out.print vs println I have the following thread which simply prints a dot every 200ms:
public class Progress {
private static boolean threadCanRun = true;
private static Thread progressThread = new Thread(new Runnable()
{
public void run() {
while (threadCanRun) {
System.out.print('.');
System.out.flush();
try {
progressThread.sleep(200);
} catch (InterruptedException ex) {}
}
}
});
public static void stop()
{
threadCanRun = false;
progressThread.interrupt();
}
public static void start()
{
if (!progressThread.isAlive())
{
progressThread.start();
} else
{
threadCanRun = true;
}
}
}
I start the thread with this code (for now):
System.out.println("Working.");
Progress.start();
try {
Thread.sleep(10000); //To be replaced with code that does work.
} catch (InterruptedException ex) {}
Progress.stop();
What's really strange is this:
If I use System.out.println('.'); , the code works exactly as expected. (Apart from the fact that I don't want a new line each time).
With System.out.print('.');, the code waits for ten seconds, and then shows the output.
System.out.println:
Print dot, wait 200ms, print dot, wait 200ms etc...
System.out.print:
Wait 5000ms, Print all dots
What is happening, and what can I do to go around this behaviour?
EDIT:
I have also tried this:
private static synchronized void printDot()
{
System.err.print('.');
}
and printDot() instead of System.out.print('.');
It still doesn't work.
EDIT2:
Interesting. This code works as expected:
System.out.print('.');
System.out.flush(); //Makes no difference with or without
System.out.println();
This doesn't:
System.err.print('.');
System.err.flush();
System.out.print('.');
System.out.flush();
Solution: The issue was netbeans related. It worked fine when I run it as a jar file from java -jar.
This is one of the most frustrating errors I have seen in my life. When I try to run this code with breakpoints in debug mode, everything works correctly.
A: The stdout is line buffered.
Use stderr, or flush the PrintStream after each print.
A: (This is weird code -- there are much cleaner ways to write and manage threads. But, that's not the issue.)
Your IDE must be buffering by line. Try running it directly on the command line. (And hope that the shell isn't buffering either, but shouldn't.)
A: The println method automatically flushes the output buffer, the print method not. If you want to see the output immediately, a call to System.out.flush might help.
A: I think this is because the println() method is synchronized
A: (This is not an answer; the asker, David, requested that I follow up on a secondary point about rewriting the threading. I am only able to post code this way.)
public class Progress {
private ProgressRunnable progressRunnable = new ProgressRunnable();
public void start() {
new Thread(progressRunnable).start();
}
public void stop() {
progressRunnable.stop();
}
private class ProgressRunnable implements Runnable {
private final AtomicBoolean running = new AtomicBoolean(true);
@Override
public void run() {
while (running.get()) {
System.out.print('.');
System.out.flush();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
}
private void stop() {
running.set(false);
}
}
public static void main(String[] args) {
Progress progress = new Progress();
progress.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
progress.stop();
}
}
A: I tested your code, with System.out.print() and System.out.flush(). The code works for me, except for the code:
while (!threadCanRun)
{
Thread.yield();
}
in Progress class. Doing that, the thread is pausing allowing other thread to execute, as you can see in the thread api page. Removing this part, the code works.
But I don't understand why do you need the yield method. If you call Progress.stop(), this will cause to invoke the yield method. After the thread will stop with interrupt, (after waiting a huge amount of time on my pc).
If you want to allow other threads executing and the current thread pausing, consider the join() method.
If you want to stop the current thread, maybe you can consider to remove the
while(!threadCanRun) loop, or place Thread.currentThread().join() before Thread.interrupt() in the stop() method to wait for the completion of other threads, or simply call the p.stop() method .
Take a look to these posts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Eclipse plugin sample could not be run On my Mac computer, I follow the tutorial on this page to get the Taipan example run, but still failed so many times.
Switch to the Plug-in Development perspective and open the models folder within the org.eclipse.gmf.examples.taipan project. Explore each of the models found hereand their element properties. You'll notice that there are full and RCP versions of the generated Taipan examples to explore.
When I try to run as "Eclipse application", it launches a new eclipse app but the dialog box Examples does not have the 'Taipan Diagram' as it says:
create an empty project and a new 'TaiPan Diagram' found in the Examples folder of the New dialog
What are the possible causes? Someone helps me to solve it out?
A: I'm assuming that your plugin is working fine and doesnt show compilation errors?
Then the most likely reason is that you havent chosen your plugin to be active in your launch dialog.
I answered a similar question with this:
My guess is that you have just created the plugin, but aren't running it in your current Eclipse instance. That can be verified by opening the view "Plugin registry". That will show a list of all plugins, see if the plugin you have created is in that list.
If you click on the run button in Eclipse you will open a run configuration dialog. In one of the tabs, you get to choose what plugins should be available. Make sure your plug-in is selected. This will start up a new Eclipse instance that will run your plugin.
To make your plugin be a part of your ordinary Eclipse installation, you will need to export it to a jar and copy that jar to the dropins catalog.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery: Detect Mouse Click and Open Target in New Tab I'm currently designing a simple forum application. It's mostly powered by jQuery/AJAX and loads everything on the same page; however, I know that sometimes users want to open several topics at once to look at them in new tabs when browsing a forum.
My solution to this was to detect when the middle mouse button is clicked and the left mouse button is clicked, and doing different actions then. I want to load the target with AJAX in the window when the left-mouse button is clicked, otherwise load it in a new tab.
My only problem is I don't know of a way to open a target location in a new tab with jQuery. Obviously opening new tabs at will isn't allowed, but is there a way to assign this type of behavior to a user-generated action?
Thanks!
A: You need to also consider that ctrl-click and cmd-click are used to open new tabs (in windows/linux and mac respectively. Therefore, this would be a more complete solution:
jQuery.isClickEventRequestingNewTab = function(clickEvent) {
return clickEvent.metaKey || clickEvent.ctrlKey || clickEvent.which === 2;
};
A: Please take look on sample code. It may help
<script type='text/javascript'>
jQuery(function($){
$('a').mousedown(function(event) {
switch (event.which) {
case 1:
//alert('Left mouse button pressed');
$(this).attr('target','_self');
break;
case 2:
//alert('Middle mouse button pressed');
$(this).attr('target','_blank');
break;
case 3:
//alert('Right mouse button pressed');
$(this).attr('target','_blank');
break;
default:
//alert('You have a strange mouse');
$(this).attr('target','_self"');
}
});
});
</script>
A: <a href="some url" target="_newtab">content of the anchor</a>
In javascript you can use
$('#element').mousedown(function(event) {
if(event.which == 3) { // right click
window.open('page.html','_newtab');
}
})
A: $('#element').mousedown(function(event) {
if(event.which == 3) { // right click
window.open("newlocation.html","");
}
});
See it live http://jsfiddle.net/8CHTm/1/
A: The default action of the middle mouse button is to open in a new tab.
You could set the hyperlinks target attribute to _blank to open a new tab.
<a href="#link" target="_blank">Link</a>
You can also refer to this question How to distinguish between left and right mouse click with jQuery
A: Please try "_newTab" instead of "_blank"
window.open( URL , "_newtab");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Error - Open clipboard failed I am using Visio professional 2003. It was working fine. But now when I copy and paste any shapes it showing the error "Open clipboard failed". After that I am not able to change any properties or name.
When I try to close the window it is showing warning as "You cant quit visio program because a program is handling an event from visio. If VBA at break point, reset VBA, then quit"
Can anyone tell me what the problem is?
A: this has been a problem with Visio for 7 years and the last 3 versions of the product(Visio 2003 to Visio 2010).
The issue happens if you are running some other clipboard manager, like ditto or similar. The only thing you can do is use task manager to kill visio, then disable any clipboard manager you are using and restart visio.
A: It is working fine after i restarted the system.
A: I'd like to ring in that I had this issue when a Citrix session remoting to server 1 which was remoting to server 2 went into "triple lock": The screen saver in all three servers had kicked in. Ditto went crazy as did every app that I used the clipboard in.
Once I unlocked the sessions (which were lagging like crazy) everything went back to normal.
A: On my side the issue was coming from Citrix. Thx for pointing that out Vincent.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: use defineProperty from a module Let's say in my module I have something like this :
Object.defineProperty(Array.prototype,
'sayHello', {get: function(){ return "hello I'm an array" });
Now I would like to make this change visible to any scripts that import the module. Is this possible ?
I tried to modify the EXPORTED_SYMBOLS accordingly but I got no results so far.
Is there another way to achieve the same thing ? (i.e. load modules that add not enumerable properties to selected objects - like Array in the example above)
EDIT:
Following the comment below by Alnitak about value: and get: ...
I'm able now to define and use a property like this:
Object.defineProperty(Array.prototype, 'firstId' , {value: function(){return this[0].id}});
var a = [{id:'x'},{id:'y'}]
a.firstId()
that returns as expected
x
Now: is it possible to put the defineProperty invocation in a module, load a module from a script and expects that the Arrays of this script will act as the one above ?
EDIT2 :
I'm writing an application with xulrunner and I'm using Components.utils.import() to laod the module - I thought (probably wrongly) that the question could be put more generally ...
A: The get: type within a property descriptor can be used to supply a read-only value that's calculated at runtime:
Object.defineProperty(Array.prototype, 'sayHello', {
get: function() {
return "hello I'm an array";
}
});
Use value: if the property is just a read-only constant value:
Object.defineProperty(Array.prototype, 'sayHello', {
value: "hello I'm an array"
});
The usage of both of those is just:
var hello = myArray.sayHello;
You should also use the value: type to add a function as a non-enumerable property of a prototype, e.g.:
Object.defineProperty(Array.prototype, 'sayHello', {
value: function(o) {
return "hello I'm an array";
}
});
usage:
var hello = myArray.sayHello();
Likewise,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Connection Pool Size for Fixed Thread Program I have a fixed thread java program. It is implemented with Spring Integration and ActiveMQ.
Fixed thread here means that program has multiple threads but the count of them in runtime don't change.
Now I need to set connection pool size for it, So I should know:
*
*How many threads it have
*Which of them may connect to DB simultaneously.
For 1. I use visualVM tool.
*
*Can I use visualVM for 2. ? How?
*Has anyone another solution for this problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Alternative key combination for jumping to the end of a line to enter a semicolon Due to automatic code completion, I regularly find myself in between parentheses, having to get to the end of a line to add the inevitable semicolon.
Then I have to get my right hand up, move it to the right, hit End, and come back to the main part of the keyboard again to enter the semicolon.
I perceive this as disturbing to my flow of typing, especially when writing on a notebook, as then those moves of my hand are very inefficient.
Is there already a key combination for reaching the end of a line, or adding a semicolon, within the main keyboard area? Or is it possible to configure PhpStorm in those regards?
(I'm using PhpStorm, but I added the IntelliJ IDEA tag to this question as I guess they would be similar regarding those basic features.)
A: More efficiently: invoke Edit | Complete Current Statement (Ctrl+Shift+Enter) to automatically insert semicolon at end of line and start new line.
A: You need to try touchcursor. I just love it.
A: You can assign any keyboard shortcut to the Move Caret to Line End action in Settings | Keymap.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Creating webpage to retrieve SSRS I created a report using SSRS in sql server 2008 r2,and now i want to create a front end webpage to retrieve the reports depending on the users choice..eg: Giving the user the reports from start to end date..
A: Assuming that you are trying to show it in ASP.NET, you need to use the ReportViewer Control.
http://msdn.microsoft.com/en-us/library/aa179197%28v=SQL.80%29.aspx
A: Provide a custom UI to take in the parameter values parameter and then load the report in an inline frame by passing the parameters using the rc: commands and disable the toolbars if wanted
refer the following : Using URL Access Parameters
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Regarding Spring and Apache CXF Integration Inside the applicationcontext.xml file we have like this
<bean id="vincent" class="com.bayer.vincent.service.vincent"/>
<jaxws:endpoint
id="vincentSOAP"
implementor="#vincent"
implementorClass="com.bayer.vincent.service.vincent"
address="/vincent/soap"
bindingUri="http://schemas.xmlsoap.org/wsdl/soap/" />
what does this mean by this defination ??
My question is how the vincent class is being getting called ??
A: As far I understand there created proxy class which forwards all calls to your real class.
See also Configuring an Endpoint where described all jaxws:endpoint attributes.
A: CXF has provided a custom spring namespace to help easily configure a webservice endpoint here.
If the implementor starts with a #, CXF makes the assumption that the endpoint is a Spring Bean, the way it is in your case.
The endpoint will have to be a normal JAX-WS endpoint, i.e annotated with @Webservice annotation, eg:
@WebService(serviceName="MemberService", endpointInterface="org.bk.memberservice.endpoint.MemberEndpoint", targetNamespace="http://bk.org/memberservice/")
Now any call to your uri-/vincent/soap, will be redirected by the CXF front controller(which you can register in the web.xml file):
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
which maintains an internal registry of payload uri's to handlers(in this case the Spring bean) and dispatches the request appropriately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apple Development Certificate To test the iPhone application in the physical device are needed to obtain the Apple Development Provisioning Profile in iPod and Development Certificate in the MAC.
My question is if the Development Certificate in the MAC can be installed in many MAC or you can install only a single MAC.
What about the certificate for the iPod goes the same?
A: First of all, the developer certificate - as the name says - is bound to a developer, not a device. When you've dann all the steps in the provisioning portal to obtain your certificate (One hint: You have to use Safari to upload the Certificate Signing Request. That took me quite some time to figure that out) and have imported your profile to Xcode you can easily export your certificate into a password protected zip-file and move it to another mac.
==> So you can have one developer profile on multiple machines and you can also have multiple developer profiles on one machine
For the devices you don't really have a certificate. You need to add the devices to your developer account (This can easily be done from within Xcode) and than you have to create a provisioning profile for your apps. When you create that profile you can select which devices you want to include in that profile.
A: You can have the developer certificate in any MAC , but for each developer certificate you can only get 99 devices provisioned ... So that developer ceertificate will only let you test and debug only on those 99 devices.. hope this helps...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Coderush Intellassist vs Intellisense I'm using coderush with vs 2008. coding in VB.net.
I don't see any evidence of Intellassist, all i see is the usual VS intellisense.
Is this normal? Preferred? Do most people leave the defaults or do most/some turn off vs's intellisense?
Does intellassist somehow agument intellisence?
thanks
jonathan
A: I see CodeRush Intellassist as an extension of Visual Studio Intellisense and not its replacement or anything else. Intellassist completes the text at the editor caret position with an in-scope identifier and may include other suggestions, such as physical file path completion or enumeration elements completion (which is not actual for Visual Basic).
To use Intellassist, just write code as you normally would. When Intellassist senses one or more suggestions matching the code you've entered so far, the best suggestion will be displayed to the right of the editor caret.
Once Intellassist is active, you have several options:
*
*Press Enter to accept the highlighted suggestion. If you have the case-sensitive option turned off, Intellassist will ensure the entire suggestion is properly cased to match the declaration.
*Press Shift+Enter to accept a portion of the suggestion. Shift+Enter accepts from the caret to the character preceding the next uppercase letter in the suggestion. For example, if "AllowMultipleSelections" was the suggestion, and "al" had been typed in, pressing Shift+Enter successive times would cause the selection to shift as follows:
*Shift+Enter is useful when you need to create a new variable name that is similar to a portion of an existing suggestion, or when you want to quickly access a different but similarly-named suggestion (differing only in the latter portions of the text). You can press Shift+Enter to move the selection right, and then start typing to get other suggestions.
*If more than one entry is suggested you can cycle forward and backward through the suggestions by pressing the Tab and Shift+Tab.
*Press the Delete key to cancel the suggestion.
*Do nothing for a few moments and Intellassist will hide the suggestion.
*If the text you've entered is a code template that you want to expand, just press Space or ; to expand the template normally.
*Continue typing (narrowing down the suggestion list or ultimately ignoring all suggestions).
Intellassist is highly configurable. You can specify whether case-insensitive suggestions should be made, and also change a host of other options.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Pie chart with percentage in color filling Sample Image url : http://173.201.63.11/CEOontheGO/chartsample
Is there any jquery component to draw the pie chart shown in the attached image? My requirement is if the pie chart has 6 segments, each segment color i have to fill based on the percentage. if 100% is the input then that segment have to fill fully. if 50% is the input then half of the section of that segment have to fill the color.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Hibernate: Inconsistent primary key generation due to one-to-one relation I have two one-to-one relations here between a class called "MailAccount" and the classes "IncomingServer" and "OutgoingServer".
(It's a Java application running on Tomcat and Ubuntu server edition).
The mapping looks like this:
MailAccount.hbm.xml
<hibernate-mapping package="com.mail.account">
<class name="MailAccount" table="MAILACCOUNTS" dynamic-update="true">
<id name="id" column="MAIL_ACCOUNT_ID">
<generator class="native" />
</id>
<one-to-one name="incomingServer" cascade="all-delete-orphan">
</one-to-one>
<one-to-one name="outgoingServer" cascade="all-delete-orphan">
</one-to-one>
</class>
</hibernate-mapping>
IncomingMailServer.hbm.xml
<hibernate-mapping>
<class name="com.IncomingMailServer" table="MAILSERVER_INCOMING" abstract="true">
<id name="id" type="long" access="field">
<column name="MAIL_SERVER_ID" />
<generator class="native" />
</id>
<discriminator column="SERVER_TYPE" type="string"/>
<many-to-one name="mailAccount" column="MAIL_ACCOUNT_ID" not-null="true" unique="true" />
<subclass name="com.ImapServer" extends="com.IncomingMailServer" discriminator-value="IMAP_SERVER" />
<subclass name="com.Pop3Server" extends="com.IncomingMailServer" discriminator-value="POP3_SERVER" />
</class>
</hibernate-mapping>
OutgoingMailServer.hbm.xml
<hibernate-mapping>
<class name="com.OutgoingMailServer" table="MAILSERVER_OUTGOING" abstract="true">
<id name="id" type="long" access="field">
<column name="MAIL_SERVER_ID" />
<generator class="native" />
</id>
<discriminator column="SERVER_TYPE" type="string"/>
<many-to-one name="mailAccount" column="MAIL_ACCOUNT_ID" not-null="true" unique="true" />
<subclass name="com.SmtpServer" extends="com.OutgoingMailServer" discriminator-value="SMTP_SERVER" />
</class>
</hibernate-mapping>
The class hierarchy looks like this:
public class MailAccount{
IncomingMailServer incomingServer;
OutgoingMailServer outgoingServer;
}
public class MailServer{
HostAddress hostAddress;
Port port;
}
public class IncomingMailServer extends MailServer{
// ...
}
public class OutgoingMailServer extends MailServer{
// ...
}
public class ImapServer extends IncomingMailServer{
// ...
}
public class Pop3Server extends IncomingMailServer{
// ...
}
public class SmtpServer extends OutgoingMailServer{
// ...
}
Now, here comes the problem:
Although most of the time my application runs well, there seems to be one situation in which email servers get deleted, but the corresponding account doesn't and that's when this call is made:
session.delete(mailAccountInstance);
In a one-to-one relation in Hibernate, the primary keys between mail account and its servers must be equal, if not, the relation completely gets out of sync:
Example:
Imagine, the tables are filled with data like this:
Table "MailAccount" (Current auto_increment value: 2)
MAIL_ACCOUNT_ID NAME
0 Account1
1 Account2
Table "IncomingMailServer" (Current auto_increment value: 2)
MAIL_SERVER_ID MAIL_ACCOUNT_ID
0 0
1 1
Now, image the account with ID=1 gets deleted and new accounts get added. The following then SOMETIMES happens:
Table "MailAccount" (Current auto_increment value: 3)
MAIL_ACCOUNT_ID NAME
0 Account1
1 Account2
2 Account3
Table "IncomingMailServer" (Current auto_increment value: 2)
MAIL_SERVER_ID MAIL_ACCOUNT_ID
0 0
1 2
This completely messes up my database consistency.
How can I avoid this?
A: If you want a shared primary key, you can use the native id generator only once. You create the mail account first, which will generate its own id, but when you create the Incoming- or OutgoingMailServer, these need to take their id from the mailAccount property.
So you need the "foreign" generator:
<class name="OutgoingMailServer">
<id name="id" column="MAIL_SERVER_ID">
<generator class="foreign">
<param name="property">mailAccount</param>
</generator>
</id>
<one-to-one name="mailAccount" not-null="true" constrained="true"/>
<class>
You don't need a MAIL_ACCOUNT_ID column, since it will always be identical to the MAIL_SERVER_ID anyway.
Quite basic follow the reference about bidirectional one-to-one association on a primary key.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is it possible to link to the same page from wordpress page menu? I have a big one page wordpress site and a menu created from wordpress admin pages panel. I added everywhere in my main page such links like <A NAME="gohere"> and similar. Now I need to add href's to the page menu name's like <a href="#gohere"> Actually I do not know is it possible to do this from the wordpress admin page's menu or maybe anybody know where these pages are stored so that I could add the links manually in the file's. Thanks!
Tried plugin "Page Links to" and added something like <A NAME="gohere"> as a link in where, but unfortunately plugin do not understand this,
Regards,
A: You shouldn't use the name attribute of the a element. Instead, assign ID values to the elements of your page, for instance:
<a href="#foo">Link to foo</a>
<div id="foo">
<!-- Your foo content goes here -->
</div>
For your question: You can manually add links to your WordPress menu, entering custom values as the href attribute. To add a link, enter #foo in the URL field of the custom link in the menu admin section.
A: Are you using the WordPress's built in menu manager? (Appearance -> Menus)
If so, then yes it should be fairly simple.
First you need to mark the areas within the page you want to link to - setting an ID to the element is enough. So if you want the browser to scroll to the top of the latest posts when a link is clicked, for example, you need to add an ID to the tag that contains the latest posts. Then give it a unique name (this is important). So something like id="latest_posts_area" should do it. Be warned though, you may need to edit the template files to do this, so ensure you have taken a backup of your theme just in case you make any mistakes.
So, if you have:
<div class="latest_posts">
You would edit it to be:
<div class="latest_posts" id="latest_posts_area">
Then, in the admin menu, when adding/editing a link, you simply set the URl as #latest_posts_area - then on every page that link is visible, clicking it will scroll the users browser to the to the top of the tag you added the ID to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing arrays between activities or take data from database I have one question about android basic concepts.
I have an Activity that pass two arrays of Integers to another Activity via an Intent. One array is an array of IDs (Integers) and the other is an array of Names (String). I have all this information also in an SQLite Database.
So my question is:
What is better, passing all the info using the intent or passing only the ID's array and take the Names directly from the database when the OnCreate of the second activity is invoke?.
Thanks.
A: In general, it's preferable to retrieve large amount of data from DB than pass it to intent since parceling into intent requires memory. So if you want to send, for example, an array of complex objects which contain bitmaps, the OutOfMemoryException can be thrown, which won't be thrown in case you retrieve those objects from DB or another persistent storage directly.
But in your case it seems that the difference won't be noticed, as you pass only strings. So you can go with passing your data via intent and save resources for opening/closing DB.
This isn't the postulate however, so any comments would be appreciated.
A: The best approach is to send as little info through intents as possible. This will keep your code for storing / restoring data in the proper places, as well as reduce the transition time between activities.
Since you've already got that information stored in the DB, and already presumably have the methods to store and retrieve that information, why add more work for yourself writing code to bundle it all up for an intent? Just send the identifying info and let the rest of your framework do the work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cache problem after sending a html-form in some part of my webpage i allow my users to change their profile picture. This is made simple by a form with the element <input type="file" name="avatar" id="avatar" />. After they upload the photo a php script is called were all the image checking and processing is made. When everything is ok, the previous user image is deleted and changed by the new one (with the same name) and then the user is redirected to their profile page.
The problem is, when the user change his picture, the firts time he goes to his profile page (when is redirected by the upload script) the picture is not the new one, is a cached copy of the old one, after a few f5 (reloads) the new image is showed.
A while ago a have a similar problem with an rss parser i made in php, if i call the url feed sometimes instead of a new version of the feed, i got a cached version. I solved this problem just by generating a ramdom number every time i needed the feed and then adding it to the url like; www.page.com/thefeed.rss?var=#ramdom_number
But, i really dont want to implement this "solution" because is unprofessional and my users will see the url with that parameter.
This is a resume of the upload operation:
profile.php?i=mycv : In this page is all the user data included the actual profile picture and the form to upload a picture, the form makes a post call to image_handler.php
image_handler.php : Is a php script who process the image sended by profile.php?i=mycv and is everything is ok, the user is redirected to profile.php?i=mycv.
Thanks for any help!
A: Try this code in profile.php
<?php
$act = $_GET["a"];
if($a == "return"){
header("location:profile.php?i=mycv");
}
?>
And then change url in image_handler.php that it sends user to profile.php?a=return page instead of profile.php?i=mycv
If that does not work you can add like this: <img src="http://someplace.com/someimage.png?<?php print time(); ?>"> then user cannot see the number part.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: accessing first n variadic function arguments I have the following code :
template<size_t sz,typename T=float> class Vec{
T v[sz];
Vec(const T& val,const T&... nv){
//how do i assign `sz` number of first arguments into `this->v` array
}
}
I want to create constructor, that receive generic number of constructor argument, and assign the first sz number of arguments into member variable of v
what I want to do, is to be able doing like this: Vec<3> var(1.0,2.0,3.0);
A: This is possible, but complicated. Here is some code that does it. It may be possible to eliminate the holder type, but I leave that as an exercise for the reader. This has been tested with g++ 4.6.
#include <iostream>
#include <typeinfo>
template<size_t ... Indices> struct indices_holder
{};
template<size_t index_to_add,typename Indices=indices_holder<> >
struct make_indices_impl;
template<size_t index_to_add,size_t...existing_indices>
struct make_indices_impl<index_to_add,indices_holder<existing_indices...> >
{
typedef typename make_indices_impl<
index_to_add-1,
indices_holder<index_to_add-1,existing_indices...> >::type type;
};
template<size_t... existing_indices>
struct make_indices_impl<0,indices_holder<existing_indices...> >
{
typedef indices_holder<existing_indices...> type;
};
template<size_t max_index>
typename make_indices_impl<max_index>::type make_indices()
{
return typename make_indices_impl<max_index>::type();
}
template<unsigned index,typename ... U>
struct select_nth_type;
template<unsigned index,typename T,typename ... U>
struct select_nth_type<index,T,U...>
{
typedef typename select_nth_type<index-1,U...>::type type;
static type&& forward(T&&,U&&... u)
{
return select_nth_type<index-1,U...>::forward(static_cast<U&&>(u)...);
}
};
template<typename T,typename ... U>
struct select_nth_type<0,T,U...>
{
typedef T type;
static type&& forward(T&&t,U&&...)
{
return static_cast<T&&>(t);
}
};
template<unsigned index,typename ... U>
typename select_nth_type<index,U...>::type&& forward_nth(U&&... u)
{
return static_cast<typename select_nth_type<index,U...>::type&&>(
select_nth_type<index,U...>::forward(
static_cast<U&&>(u)...));
}
template<size_t sz,typename T=float> struct Vec{
struct holder
{
T data[sz];
};
holder v;
template<typename ... U>
struct assign_helper
{
template<size_t... Indices>
static holder create_array(indices_holder<Indices...>,Vec* self,U&&... u)
{
holder res={{static_cast<T>(forward_nth<Indices>(u...))...}};
return res;
}
};
template<typename ... U>
Vec(U&&... u):
v(assign_helper<U...>::create_array(make_indices<sz>(),this,static_cast<U&&>(u)...))
{}
};
int main()
{
Vec<3> v(1.2,2.3,3.4,4.5,5.6,7.8);
std::cout<<"v[0]="<<v.v.data[0]<<std::endl;
std::cout<<"v[1]="<<v.v.data[1]<<std::endl;
std::cout<<"v[2]="<<v.v.data[2]<<std::endl;
}
A: I believe this satisfies all the requirements:
template <size_t sz,typename T,typename... Args> struct Assign;
template <typename T,typename First,typename...Rest>
struct Assign<1,T,First,Rest...> {
static void assign(T *v,const First &first,const Rest&... args)
{
*v = first;
}
};
template <size_t sz,typename T,typename First,typename... Rest>
struct Assign<sz,T,First,Rest...> {
static void assign(T *v,const First &first,const Rest&... rest)
{
*v = first;
Assign<sz-1,T,Rest...>::assign(v+1,rest...);
}
};
template<size_t sz,typename T=float>
struct Vec{
T v[sz];
template <typename... Args>
Vec(const T& val,const Args&... nv){
Assign<sz,T,T,Args...>::assign(v,val,nv...);
}
};
A: This is another technique which is much simpler if it is ok not to have at least sz parameters:
template<size_t sz,typename T=float>
struct Vec {
T v[sz];
template <typename... Args>
Vec(const T& val,const Args&... nv)
{
T data[] = {val,static_cast<const T &>(nv)...};
int i=0;
for (; i<sz && i<(sizeof data)/sizeof(T); ++i) {
v[i] = data[i];
}
for (; i<sz; ++i) {
v[i] = T();
}
}
};
A: First declare this utility function:
template <typename T> inline void push(T* p) {}
template <typename T, typename First, typename... Args>
inline void push(T* p, First&& first, Args&&... args)
{
*p = first;
push(++p, std::forward<Args>(args)...);
}
Then, in your class:
template<size_t sz,typename T=float>
class Vec
{
T v[sz];
template <typename... Args>
Vec(T first, Args&&... args) // << we have changed const T& to T&&
{
//how do i assign `sz` number of first arguments into `this->v` array
// like this:
push(&v[0], first, std::forward<Args>(args)...);
}
}
A: sz is a template argument, you can directly use it in your code.
A: Can you make use of something like this?
template <typename... Args> class Vec {
std :: tuple <Args...> m_args;
Vec (const Foo & a, const Bar & b, Args&&... args)
: m_args (args...)
{
// ... something with a, b
}
};
There are a few rules to constrain you:
*
*you can only have one template... Args-style packed argument list per template class
*methods which use it must have the templated arguments on the right-hand-side
A: The following could work:
template <typename T, std::size_t N>
struct Foo
{
T arr[N];
template <typename ...Args> Foo(Args &&... args) : arr{std::forward<Args>(args)...} { }
};
Usage:
Foo<int, 3> a(1,2,3);
This allows you to construct the array elements from anything that's convertible to T. You can obtain the number of parameters (which can be anything not exceeding N) with sizeof...(Args).
A: You need to unpack the argument pack while keeping a count and do the necessary runtime operation in a functor. This should get you started:
template<unsigned, typename...>
struct unroll;
template<unsigned size, typename Head, typename... Tail>
struct unroll<size, Head, Tail...> {
void operator()(Head&& h, Tail&&... tail) {
// do your stuff, pass necessary arguments through the ctor of the
// struct
unroll<size - 1, Tail...>()(std::forward<Tail>(tail)...);
}
};
template<typename Head, typename... Tail>
struct unroll<1, Head, Tail...> {
void operator()(Head&& h, Tail&&... tail) {
// do your stuff the last time and do not recurse further
}
};
int main()
{
unroll<3, int, double, int>()(1, 3.0, 2);
return 0;
}
A: The following almost works (and for the last N arguments instead of the first, but hey). Perhaps someone can help with the compile error in the comments below:
#include <iostream>
void foo (int a, int b) {
std :: cout << "3 args: " << a << " " << b << "\n";
}
void foo (int a, int b, int c) {
std :: cout << "3 args: " << a << " " << b << " " << c << "\n";
}
template <int n, typename... Args>
struct CallFooWithout;
template <typename... Args>
struct CallFooWithout <0, Args...> {
static void call (Args... args)
{
foo (args...);
}
};
template <int N, typename T, typename... Args>
struct CallFooWithout <N, T, Args...> {
static void call (T, Args... args)
{
CallFooWithout <N-1, Args...> :: call (args...);
// ambiguous class template instantiation for 'struct CallFooWithout<0, int, int, int>'
// candidates are: struct CallFooWithout<0, Args ...>
// struct CallFooWithout<N, T, Args ...>
}
};
template <int n, typename... Args>
void call_foo_with_last (Args... args)
{
CallFooWithout <sizeof...(Args)-n, Args...> :: call (args...);
}
int main ()
{
call_foo_with_last <2> (101, 102, 103, 104, 105);
call_foo_with_last <3> (101, 102, 103, 104, 105);
}
I don't see why it's ambiguous because 0 is more specialised than N so that should satisfy the partial order ?!?!?
By contrast, the below is fine.
template <int N, typename... T>
struct Factorial
{
enum { value = N * Factorial<N - 1,T...>::value };
};
template <typename... T>
struct Factorial<0, T...>
{
enum { value = 1 };
};
void foo()
{
int x = Factorial<4,int>::value;
}
What's the difference?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Help with type of layout what type of layout should i be used for a layout like this?
Should i be used linear layout or relative? Could you explain why you chose the layout you did. A sample would be helpful as well.
Thanks
A: If your layout is as simple as the above shown, I would use LinearLayout - mostly because I find working with relative layouts a bit annoying and harder to find bugs in.
A sample would be:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent" android:id="@+id/linearLayout1"
android:orientation="vertical" android:layout_weight="1"
android:background="@android:color/darker_gray">
<!-- Put widgets here -->
</LinearLayout>
<LinearLayout android:layout_height="100dp"
android:layout_width="fill_parent" android:id="@+id/linearLayout2"
android:orientation="vertical" android:background="@android:color/background_light">
<!-- Put widgets here -->
</LinearLayout>
</LinearLayout>
A: <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout android:layout_width="match_parent"
android:background="#ff00" android:id="@+id/relativeLayout1"
android:layout_height="100dp" android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"></RelativeLayout>
<RelativeLayout android:layout_width="match_parent"
android:background="#f0f0" android:id="@+id/relativeLayout2"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_above="@+id/relativeLayout1"
android:layout_centerHorizontal="true"></RelativeLayout>
</RelativeLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Splitting data into a per-year basis using SQL with pivots I'm having some trouble figuring out how construct a series of SQL statements to split some data I have into a per-year basis. There are n items which have a recorded quantity for a set of days across so many years. Here's is a a small sample layout for the main data I have.
|========|==============|===========|
| Name | Date | Quantity |
|========|==============|===========|
1 | AAAAA | 10-DEC-2008 | 5 |
2 | AAAAA | 11-DEC-2008 | 2 |
3 | AAAAA | 12-DEC-2008 | 0 |
4 | AAAAA | 09-DEC-2009 | 3 |
5 | AAAAA | 10-DEC-2009 | 2 |
6 | AAAAA | 11-DEC-2009 | 3 |
7 | BBBBB | 10-DEC-2008 | 5 |
8 | BBBBB | 11-DEC-2008 | 2 |
9 | BBBBB | 12-DEC-2008 | 0 |
10 | BBBBB | 09-DEC-2009 | 3 |
11 | BBBBB | 10-DEC-2009 | 1 |
12 | BBBBB | 11-DEC-2009 | 0 |
|========|==============|===========|
I need to convert this into a table which takes the form.
|========|==============|===============|===============|
| Name | Date | Quantity 2008 | Quantity 2009 |
|========|==============|===============|===============|
1 | AAAAA | 09-DEC | | 3 |
2 | AAAAA | 10-DEC | 5 | 2 |
3 | AAAAA | 11-DEC | 2 | 3 |
4 | AAAAA | 12-DEC | 0 | |
5 | BBBBB | 09-DEC | | 3 |
6 | BBBBB | 10-DEC | 5 | 1 |
7 | BBBBB | 11-DEC | 2 | 0 |
8 | BBBBB | 12-DEC | 0 | |
|========|==============|===============|===============|
It should be assumed that there are thousands of named items in the database and the start days of recording on each year will be different, E.G., 6th Dec 2010 and 5th Dec 2009.
Hope someone can help.
A: In case you are using Oracle 11g, you can pivot the table as:
select *
from (
select name,
to_char(theDate, 'DD-MON') as dayMonth,
extract(year from thedate) as year,
quantity
from yourTable
)
pivot (sum(quantity) as quantity for (year) in (2008 as y2008, 2009 as y2009))
order by name, dayMonth;
that returns the following
NAME DAYMONTH Y2008_QUANTITY Y2009_QUANTITY
----- --------------- ---------------------- ----------------------
AAAAA 09-DEC 3
AAAAA 10-DEC 5 2
AAAAA 11-DEC 2 3
AAAAA 12-DEC 0
BBBBB 09-DEC 3
BBBBB 10-DEC 5 1
BBBBB 11-DEC 2 0
BBBBB 12-DEC 0
8 rows selected
A: Something like this should do the job:
SELECT
Name, FormattedDate, SUM(Quantity_2008), SUM(Quantity_2009)
FROM
(
SELECT
Name,
ConvertDateToDayMonthRepresentation(YourDate) as FormattedDate,
DECODE(EXTRACT(YEAR FROM YourDate), 2008, Quantity, 0) as Quantity_2008,
DECODE(EXTRACT(YEAR FROM YourDate), 2009, Quantity, 0) as Quantity_2009
FROM
YourTable
)
GROUP BY Name, FormattedDate;
Please note:
*
*You need to add code for each year you want to have - your Query can't have dynamic columns.
*ConvertDateToDayMonthRepresentation is a user defined function that should convert a date into the string representation of day and month without the year. It is trivial to create using EXTRACT.
A: Prior to Oracle11, you can use this standard pivot trick:
SQL> create table mytable (name,mydate,quantity)
2 as
3 select 'AAAAA', date '2008-12-10', 5 from dual union all
4 select 'AAAAA', date '2008-12-11', 2 from dual union all
5 select 'AAAAA', date '2008-12-12', 0 from dual union all
6 select 'AAAAA', date '2009-12-09', 3 from dual union all
7 select 'AAAAA', date '2009-12-10', 2 from dual union all
8 select 'AAAAA', date '2009-12-11', 3 from dual union all
9 select 'BBBBB', date '2008-12-10', 5 from dual union all
10 select 'BBBBB', date '2008-12-11', 2 from dual union all
11 select 'BBBBB', date '2008-12-12', 0 from dual union all
12 select 'BBBBB', date '2009-12-09', 3 from dual union all
13 select 'BBBBB', date '2009-12-10', 1 from dual union all
14 select 'BBBBB', date '2009-12-11', 0 from dual
15 /
Table created.
SQL> select name
2 , to_char(mydate,'dd-MON')
3 , sum(case extract(year from mydate) when 2008 then quantity end) quantity_2008
4 , sum(case extract(year from mydate) when 2009 then quantity end) quantity_2009
5 from mytable
6 group by name
7 , to_char(mydate,'dd-MON')
8 order by name
9 , to_char(mydate,'dd-MON')
10 /
NAME TO_CHA QUANTITY_2008 QUANTITY_2009
----- ------ ------------- -------------
AAAAA 09-DEC 3
AAAAA 10-DEC 5 2
AAAAA 11-DEC 2 3
AAAAA 12-DEC 0
BBBBB 09-DEC 3
BBBBB 10-DEC 5 1
BBBBB 11-DEC 2 0
BBBBB 12-DEC 0
8 rows selected.
Regards,
Rob.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: [Cocos2d]How to Create bitmap from GlSurfaceView How can I take screen shot of Glsurfaceview in Cocos2d. I tried with following code using GLsurfaceView
GlsurfaceView glv=CCDirector.sharedDirector().getOpenGLView();
glv.setDrawingCacheEnabled(true);
Bitmap bitmap=glv.getDrawingCache();
but it return transparent image.
A: I got answer from this anddev forum question I attached code along with this hope somebody will find this helpful
Please Put this code inside renderer class onDraw Method inside starting.
public static Bitmap SavePixels(int x, int y, int w, int h, GL10 gl)
{
int b[]=new int[w*h];
int bt[]=new int[w*h];
IntBuffer ib=IntBuffer.wrap(b);
ib.position(0);
gl.glReadPixels(x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, ib);
/* remember, that OpenGL bitmap is incompatible with
Android bitmap and so, some correction need.
*/
for(int i=0; i<h; i++)
{
for(int j=0; j<w; j++)
{
int pix=b[i*w+j];
int pb=(pix>>16)&0xff;
int pr=(pix<<16)&0x00ff0000;
int pix1=(pix&0xff00ff00) | pr | pb;
bt[(h-i-1)*w+j]=pix1;
}
}
Bitmap sb=Bitmap.createBitmap(bt, w, h, true);
return sb;
}
public static void SavePNG(int x, int y, int w, int h, String name, GL10 gl)
{
Bitmap bmp=SavePixels(x,y,w,h,gl);
try
{
FileOutputStream fos=new FileOutputStream("/sdcard/my_app/"+name);
bmp.compress(CompressFormat.PNG, 100, fos);
try
{
fos.flush();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
A: Here is solution:
if (MainImageProcessingActivity.capture) {
int width = MainImageProcessingActivity.w;
int height = MainImageProcessingActivity.h;
int screenshotSize = width * height;
ByteBuffer bb = ByteBuffer.allocateDirect(screenshotSize * 4);
bb.order(ByteOrder.nativeOrder());
gl.glReadPixels(0, 0, width, height, GL10.GL_RGBA,
GL10.GL_UNSIGNED_BYTE, bb);
int pixelsBuffer[] = new int[screenshotSize];
bb.asIntBuffer().get(pixelsBuffer);
bb = null;
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.RGB_565);
bitmap.setPixels(pixelsBuffer, screenshotSize - width, -width, 0,
0, width, height);
pixelsBuffer = null;
short sBuffer[] = new short[screenshotSize];
ShortBuffer sb = ShortBuffer.wrap(sBuffer);
bitmap.copyPixelsToBuffer(sb);
// Making created bitmap (from OpenGL points) compatible with
// Android bitmap
for (int i = 0; i < screenshotSize; ++i) {
short v = sBuffer[i];
sBuffer[i] = (short) (((v & 0x1f) << 11) | (v & 0x7e0) | ((v & 0xf800) >> 11));
}
sb.rewind();
bitmap.copyPixelsFromBuffer(sb);
MainImageProcessingActivity.captureBmp = bitmap.copy(Bitmap.Config.ARGB_8888,false);
MainImageProcessingActivity.capture=false;
}
put the code under onDrawFrame(GL10 gl) method, IT WORKS!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: adding reference to facebook sdk in android I am making an android app in which i am using facebook login.
I am unable to add the facebook sdk as library to my project.
can anyone tell what could be the problem.
thanks
A: You got facebook sdk from https://github.com/facebook/facebook-android-sdk Link.
Import this project in your eclips.
then go to package explorer of your eclipse and right click your original project --> property --> android . at this place below built target there is library option add your facebook project from here.
It may help you.
A: Did you solve your problem? If not here is what I did. In Eclipse right click in your app folder select Build Path -> Link Source and finally find the facebook-sdk folder click Finish and you are done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Sign extension with unsigned long long We found some strange values being produced, a small test case is below.
This prints "FFFFFFFFF9A64C2A" . Meaning the unsigned long long seems to have been sign extended.
But why ?
All the types below are unsigned, so what's doing the sign extension ? The expected output
would be "F9A64C2A".
#include <stdio.h>
int main(int argc,char *argv[])
{
unsigned char a[] = {42,76,166,249};
unsigned long long ts;
ts = a[0] | a[1] << 8U | a[2] << 16U | a[3] << 24U;
printf("%llX\n",ts);
return 0;
}
A: In the expression a[3] << 24U, the a[1] has type unsigned char. Now, the "integer promotion" converts it to int because:
The following may be used in an expression wherever an int or unsigned int may
be used:
[...]
If an int can represent all values of the original type, the value is converted to
an int;
otherwise, it is converted to an unsigned int.
((draft) ISO/IEC 9899:1999, 6.3.1.1 2)
Please note also that the shift operators (other than most other operators) do not do the "usual arithmetic conversions" converting both operands to a common type. But
The type of the result is that of the promoted left operand.
(6.5.7 3)
On a 32 bit platform, 249 << 24 = 4177526784 interpreted as an int has its sign bit set.
Just changing to
ts = a[0] | a[1] << 8 | a[2] << 16 | (unsigned)a[3] << 24;
fixes the issue (The suffix Ufor the constants has no impact).
A:
ts = ((unsigned long long)a[0]) |
((unsigned long long)a[1] << 8U) |
((unsigned long long)a[2] << 16U) |
((unsigned long long)a[3] << 24U);
Casting prevents converting intermediate results to default int type.
A: Some of the shifted a[i], when automatically converted from unsigned char to int, produce sign-extended values.
This is in accord with section 6.3.1 Arithmetic operands, subsection 6.3.1.1 Boolean, characters, and integers, of C draft standard N1570, which reads, in part, "2. The following may be used in an expression wherever an int or unsigned int may be used: ... — An object or expression with an integer type (other than int or unsigned int)
whose integer conversion rank is less than or equal to the rank of int and unsigned int. ... If an int can represent all values of the original type ..., the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. ... 3. The integer promotions preserve value including sign."
See eg www.open-std.org/JTC1/SC22/WG14/www/docs/n1570.pdf
You could use code like the following, which works ok:
int i;
for (i=3, ts=0; i>=0; --i) ts = (ts<<8) | a[i];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Android Error : Can't create handler inside thread that has not called Looper.prepare() I am Creating one thread inside my Click event. I want to call my webservice repeatedly on particular time thats why i am using Timer event inside my click event but it throws exception that java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() .
if i can not call timer in click event then please give me some hint to do so
here is my code
holder.linear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mo.equals(BUDDYNAMECOPY.get(BUDDYNAMECOPY.indexOf(mo)))) {
INDEX = BUDDYNAMECOPY.indexOf(mo);
B_Id = BUDDYLIST.get(INDEX).getBuddyUID();
tim.schedule(new TimerTask() {
@Override
public void run() {
CurrentLocation location =new CurrentLocation(getApplicationContext());
lat=location.getCurrentLatitude();
lon=location.getCurrentLongitude();
String url=UrlConstant.BASEURL + UrlConstant.GET_LATLONG
+ JsonDataProcessor.uid + "&buddy_uid="
+ B_Id;
JsonDataProcessor caller=new JsonDataProcessor(url,BuddyList.this,UrlConstant.BUDDYLOCATION);
}
},0,30000);
}
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Assertion fails after using memcpy() I have the following code, where the assertion fails. Can anyone explain me why?
double *E = (double *) malloc(sizeof(double) * voxelSpaceSize);
double *E_new = (double *) malloc(sizeof(double) * voxelSpaceSize);
// ...some manipulations inside E and E_new, the memory locations do not change though
...
memcpy(E, E_new, sizeof(double) * voxelSpaceSize);
for (int i=0; i<voxelSpaceSize; i++) {
assert(E[i] == E_new[i]);
}
A: By definition, the special floating-point value NaN is not equal to itself: NaN == NaN returns false. So now I'm betting the value at the unequal index is NaN. You may want to print out the value at the index where the value's not equal to itself, rather than using assert.
A: Assuming you want to copy from E to E_new, your arguments to memcpy are in the wrong order -- the second argument is the source pointer, the first is the destination.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get a confirm popup in asp.net Inside the grid I have a delete button inside a grid and have a code behind to perform the delete.
<asp:TemplateField HeaderText="Edit Controls" ItemStyle-Width="15%">
<ItemTemplate>
<asp:LinkButton ID="Lnk_Delete" ToolTip="Delete Message"
CommandArgument='<%#Eval("MsgID") %>' CommandName="Delete" runat="server">
<img id="Img1" src="Styles/Images/Delete.jpg" runat="server" /></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
protected void Grid_Messagetable_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
Everything works fine how to get a confirm pop up before the delete is performed.
A: You could use the OnClientClick property as shown in the following article:
<asp:LinkButton
ID="Lnk_Delete"
runat="server"
ToolTip="Delete Message"
CommandArgument='<%#Eval("MsgID") %>'
CommandName="Delete"
OnClientClick="return confirm('Are you sure you want to delete this record?');">
<img id="Img1" src="Styles/Images/Delete.jpg" runat="server" />
</asp:LinkButton>
A: Try adding
OnClientClick="return confirm('Do you want Delete?');"
A: onClientClick="return confirm('Are you sure you want to delete?')";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make the JFileChooser to return the file or directory path containing the forward slash in stead of backward slash in java? I have implemented JFileChooser of Java swing successfully. As the implemented JFileChooser gives file or directory path with backward slash as a file separator on windows os.
My question is how to make this JFileChooser to return the file or directory path containing the forward slash in stead of backward slash as path separator in java independent of windows os or any other os?
Please guide me Friends!
Thank You!
A: Normally, you don't have to care about forward/backward slashes. The JFileChooser will return the path so that it is suitable for the machine it is running on.
A: The File class actually abstracts you of this task. The JFileChooser return a File object, then you can call its getCanonicalPath method (for instance) which has a different format depending on the OS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Facebook Application SSL Change - AJAX Flash/Server Data Security We are in the process of migrating (yup a bit late huh) of our apps to handle SSL fully (rather than just the monetization portions).
We've looked at a few other application developer integrations and it looks like the Flash-server data requests are under normal HTTP requests (well, in AMF).
Any ideas if both JS AMF requiring HTTPS transport?
A: Looks like the JS AMF is still in pre-alpha state per the project's home page. I'm not sure it is being developed for anymore, as the last update was in Jul 09. A very long time ago. I would suggest using the latest Facebook Javascript SDK and go from there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to represent Listeners in UML sequence diagram In sequence diagrams, how would you represent an event triggered listener?
It is not just a regular method call, so displaying like that would not seem correct.
I try to make a sequence diagram of a system including a JMS listener. I could start the lifeline with the send() call of the system to the JMS queue (displaying the system calling send() as a business actor), or I could start the lifeline at the onMessage() call. (displaying JMS Queue as a business actor)
Or should I just ignore the whole JMS Queue in the diagram?
For what it's worth: I'm using Astah Community to create the diagrams.
A: It is usually not important if you either use an "event" or an explicit "method call".
What is your audience and how do you model the JMS listern? I would assume the JMS Listener is just another actor, and if your audience is on the "requirements" level I would simply use an event (a message in a sequence diagram usually can be of various "types" like event, message, or method call).
A: A found message is a message where the receiving event occurrence is known, but there is no (known) sending event occurrence. We interpret this to be because the origin of the message is outside the scope of the description. This may for example be noise or other activity that we do not want to describe in detail. The semantics is simply the trace (receiveEvent)
A lost message is a message where the sending event occurrence is known, but there is no receiving event occurrence. We interpret this to be because the message never reached its destination. The semantics is simply the trace (sendEvent).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: JQGrid + ASP.NET MVC 3 Redirect to record details on doubleclick I have implemented a simple jqGrid in my ASP.NET MVC 3 application. It shows the data correctly, so that's fine. But now I want my application to show the details of a row if I doubleclick on a row.
I have a Detail action method that actually gets called with the correct ID, the details are retrieved from database and the Details view is returned, so that seems to be OK, but in my application nothing happens.
I have the following script for the grid:
jQuery(document).ready(function ()
{
jQuery("#list").jqGrid({
url: '/Incident/ListData/',
datatype: 'json',
mtype: 'GET',
colNames: ['TicketNumber', 'Title', 'CreatedOn'],
colModel: [
{ name: 'TicketNumber', index: 'TicketNumber', width: 75, align: 'left' },
{ name: 'Title', index: 'Title', width: 250, align: 'left' },
{ name: 'CreatedOn', index: 'CreatedOn', width: 90, align: 'left'}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 50, 100],
sortname: 'CreatedOn',
sortorder: "desc",
viewrecords: true,
width: 650,
imgpath: '/Content/themes/base/images',
caption: 'Incidents',
ondblClickRow: function (id) { $.get('/Incident/Detail/' + id); }
});
});
I've tried using $.ajax instead of $.get, but in both cases the details method gets called and nothing happens.
This is the Details action method
public ViewResult Detail(Guid id)
{
var query = from inc in _repository.Incidents
where inc.Id == id
select
new IncidentModel(inc)
{
CreatedOn = inc.CreatedOn,
Description = inc.Description,
ModifiedOn = inc.ModifiedOn,
TicketNumber = inc.TicketNumber,
Title = inc.Title,
Status = inc.Status
};
var incident = query.FirstOrDefault();
return View(incident);
}
A: $.get sends an AJAX request and gives you the server's reply.
It doesn't actually do anything with the server's reply; it's up to you to do something useful.
It sounds like you don't want AJAX at all; instead, you want to navigate to that page:
location = '/Incident/Detail/' + id
A: As Slaks said, you're not doing anything with the content. Should your double click event actually be redirecting the browser to that action?
(Just a side note, why double click? Nearly everything else net based uses a single click to browse).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Difference between String.getBytes() and Bytes.toBytes(String data) I'm writing a Hadoop/HBase job. I needed to transform a Java String into a byte array. Is there any differences between Java's String.getBytes() and Hadoop's Bytes.toBytes()?
A: Reading the Javadoc, it appear that String.getBytes() returns a byte[] using the default encoding and Bytes.toBytes() returns a byte[] using UTF-8
This could be the same thing, but it might not be.
Its always useful to read the Javadoc if you want to know something. ;)
A: According to its documentation Bytes.toBytes() converts the parameter to a byte[] using UTF-8.
String.getBytes() (without arguments) will convert the String to byte[] using the platform default encoding. That encoding can vary depending on the OS and user settings. Use of that method should generally be avoided.
You could use String.getBytes(String) (or the Charset variant) to specify the encoding to be used.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: android monkey runner scripts i am tryig to execute a sample python program through monkey runner command prompt and it is throwing an error
Can't open specified script file
Usage: monkeyrunner [options] SCRIPT_FILE
-s MonkeyServer IP Address.
-p MonkeyServer TCP Port.
-v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO,
WARNING, SEVERE, OFF)
Exception in thread "main" java.lang.NullPointerException
so any one can guide me how to resolve this one
A: scriptfile should be a full path file name
try below
monkeyrunner c:\test_script\first.py
A: try using something like
...\tools>monkeyrunner -v ALL first.py
where first.py was my sample python script which I copied into tools folder of android SDK (the place where monkeyrunner.bat is located)
A: Under all unix/linux families OS the sha bang syntax can be used.
Edit the first line of your script with the results of the following command:
which monkeyrunner
for example, if monkeyrunner (usually provided with android sdk) has been installed under /usr/local/bin/sdk write:
#!/usr/local/bin/sdk/tools/monkeyrunner
or even use "env"
#!/usr/bin/env monkeyrunner
then set you script file as executable
chmod +x <script>
You can now launch your script from the shell.
A: It looks not make sense to switch working directory to Android SDK folder but just for obtain some relative references path for itself. It means you have to specify the full path for your script file and the PNG image files you want to save or compare to.
A better way is modify few lines in the "monkeyrunner.bat" under your SDK folder as below. This will use your current path as working directory, so, no necessary to use full path file name.
rem don't modify the caller's environment
setlocal
rem Set up prog to be the path of this script, including following symlinks,
rem and set up progdir to be the fully-qualified pathname of its directory.
set prog=%~f0
rem Change current directory and drive to where the script is, to avoid
rem issues with directories containing whitespaces.
rem cd /d %~dp0
rem Check we have a valid Java.exe in the path.
set java_exe=
call %~sdp0\lib\find_java.bat
if not defined java_exe goto :EOF
set jarfile=monkeyrunner.jar
set frameworkdir=
set libdir=
if exist %frameworkdir%%jarfile% goto JarFileOk
set frameworkdir=%~sdp0\lib\
if exist %frameworkdir%%jarfile% goto JarFileOk
set frameworkdir=%~sdp0\..\framework\
:JarFileOk
set jarpath=%frameworkdir%%jarfile%
if not defined ANDROID_SWT goto QueryArch
set swt_path=%ANDROID_SWT%
goto SwtDone
:QueryArch
for /f %%a in ('%java_exe% -jar %frameworkdir%archquery.jar') do set swt_path=%frameworkdir%%%a
:SwtDone
if exist %swt_path% goto SetPath
echo SWT folder '%swt_path%' does not exist.
echo Please set ANDROID_SWT to point to the folder containing swt.jar for your platform.
exit /B
:SetPath
call %java_exe% -Xmx512m -Djava.ext.dirs=%frameworkdir%;%swt_path% -Dcom.android.monkeyrunner.bindir=%frameworkdir%\..\..\platform-tools\ -jar %jarpath% %*
A: I met the same things as you did, I resolved by using "monkeyrunner" command under tools, and your script file should be a full path name. It looks like the directory “tools” is the main directory of MonnkeyRunner. I am depressed that I can't run my script files by pydev IDE directly.
A: monkeyrunner.bat cygpath -w $(pwd)/monkey.py
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to insert more than 10^6 elements in a array I want to operate on 10^9 elements. For this they should be stored somewhere but in c, it seems that an array can only store 10^6 elements. So is there any way to operate on such a large number of elements in c?
The error thrown is error: size of array ‘arr’ is too large".
A:
For this they should be stored somewhere but in c it seems that an
array only takes 10^6 elements.
Not at all. I think you're allocating the array in a wrong way. Just writing
int myarray[big_number];
won't work, as it will try to allocate memory on the stack, which is very limited (several MB in size, often, so 10^6 is a good rule of thumb). A better way is to dynamically allocate:
int* myarray;
int main() {
// Allocate the memory
myarray = malloc(big_number * sizeof(int));
if (!myarray) {
printf("Not enough space\n");
return -1;
}
// ...
// Free the allocated memory
free(myarray);
return 0;
}
This will allocate the memory (or, more precise, big_number * 4 bytes on a 32-bit machine) on the heap. Note: This might fail, too, but is mainly limited by the amount of free RAM which is much closer to or even above 10^9 (1 GB).
A: An array uses a contiguous memory space. Therefore, if your memory is fragmented, you won't be able to use such array. Use a different data structure, like a linked list.
About linked lists:
*
*Wikipedia definition - http://en.wikipedia.org/wiki/Linked_list
*Implementation in C - http://www.macs.hw.ac.uk/~rjp/Coursewww/Cwww/linklist.html
On a side note, I tried on my computer, and while I can't create an int[1000000], a malloc(1000000*sizeof(int)) works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Reading large excel tables (guessing size) I'm using pywin32 to read and write to excel. Now the only method I know is accessing Range.Value however, I usually don't know the size of the full excel table in advance.
So at the moment I read line by line until I find a completely empty line. This can be quite slow.
Of course I will try tricks like reading blocks of data - then I'd have to find an optimal block size.
Do you know another method (maybe some internal excel function) or other approaches which are faster?
A: You can use xlrd to open a workbook and read the size of particular worksheet. It's quite fast.
Hints: book = xlrd.open_workbook("myfile.xls") then you get Sheet object by sheet = book.sheet_by_index(sheetx) or sheet = book.sheet_by_name(sheet_name) and you have sheet.nrows property with number of rows in given sheet.
Here is the API documentation.
A: How about getting the whole range with the Worksheet.UsedRange property ?
A: In VBA, we often use the End statement like this:
Worksheets("sheet1").Cells(Rows.Count, "A").End(xlUp).Row
That may help you find the last used cell of a column (yet, I don't know how to extend this method to pywin)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: directing OpenSSL not to free a BIO object upon setting a new BIO In this sample code:
BIO *bio1 = BIO_new(BIO_s_mem());
BIO *bio2 = BIO_new(BIO_s_mem());
SSL_set_bio(ssl, bio1, bio1);
SSL_set_bio(ssl, bio2, bio2);
the last call to SSL_set_bio automatically calls BIO_free(bio1).
Is there anyway to tell OpenSSL not to do so?
I know that upon creating a memory bio with BIO_new(BIO_s_mem()) I can tell OpenSSL not to free it's memory buffer with BIO_set_close(bio, BIO_NOCLOSE). Is there anything similar for my case?
A: There's no way to prevent SSL_set_bio from freeing the current BIO in the public API. You can see in the source code that it simply checks whether each bio is not null and then frees it.
The main idea is that after you call SSL_set_bio, OpenSSL owns the BIO and is responsible for it.
void SSL_set_bio(SSL *s,BIO *rbio,BIO *wbio)
{
/* If the output buffering BIO is still in place, remove it
*/
if (s->bbio != NULL)
{
if (s->wbio == s->bbio)
{
s->wbio=s->wbio->next_bio;
s->bbio->next_bio=NULL;
}
}
if ((s->rbio != NULL) && (s->rbio != rbio))
BIO_free_all(s->rbio);
if ((s->wbio != NULL) && (s->wbio != wbio) && (s->rbio != s->wbio))
BIO_free_all(s->wbio);
s->rbio=rbio;
s->wbio=wbio;
}
If I had a legitimate reason to keep the bio buffer around in production code, I would write my own bio and use that. It's not as hard as it sounds. Just copy <openssl source>/crypto/bio/bss_mem.c, rename the functions and mem_method table, and then replace the behavior of mem_free(). Then instead of BIO_s_mem, pass BIO_custom_mem_bio or whatever you name the accessor function for your bio.
If I needed it for debugging purposes and not production code, I'd probably just grovel into the internals of the ssl_st struct (SSL *) and make all the bios NULL before calling SSL_set_bio. But I wouldn't do that in production code because future SSL versions may break that code.
A: You can use BIO_up_ref() to increase the reference count.
BIO_free() would decrease the count, but not free it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Admin Products Routing Hi hoping to get some answers here. I have thought this over and over, it is killing me. Want to get answers now, everything i have been finding is more complex then my litle system at the moment. Question is below information.
First my routes file:
get 'admin' => 'admin#index'
namespace "admin" do
resources :products
end
My Admin Products Controller is as follows:
class Admin::ProductsController < ApplicationController
# GET /products
# GET /products.json
def index
@products = Product.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @products }
end
end
# GET /products/1
# GET /products/1.json
def show
@product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @product }
end
end
# GET /products/new
# GET /products/new.json
def new
@product = Product.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @product }
end
end
# GET /products/1/edit
def edit
@product = Product.find(params[:id])
end
# POST /products
# POST /products.json
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render json: @product, status: :created, location: @product }
else
format.html { render action: "new" }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
# PUT /products/1
# PUT /products/1.json
def update
@product = Product.find(params[:id])
respond_to do |format|
if @product.update_attributes(params[:product])
format.html { redirect_to @product, notice: 'Product was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
@product = Product.find(params[:id])
@product.destroy
respond_to do |format|
format.html { redirect_to products_url }
format.json { head :ok }
end
end
end
My Admin Products View files are standard, here is the _form, new, index files:
New:
<%= render 'form' %>
<%= link_to 'Back', admin_products_path %>
_form:
<%= form_for [:admin, @product] do |f| %>
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% @product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description, rows: 6 %>
</div>
<div class="field">
<%= f.label :image_url %><br />
<%= f.text_field :image_url %>
</div>
<div class="field">
<%= f.label :price %><br />
<%= f.text_field :price %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Index:
<h1>Admin Listing products</h1>
<table>
<% @products.each do |product| %>
<tr class="<%= cycle('list_line_odd', 'list_line_even') %>">
<td>
<%= image_tag(product.image_url, class: 'list_image') %>
</td>
<td class="list_description">
<dl>
<dt><%= product.title %></dt>
<dd><%= truncate(strip_tags(product.description),
length: 80) %></dd>
</dl>
</td>
<td class="list_actions">
<%= link_to 'Edit', edit_admin_product_path(product) %><br/>
<%= link_to 'Destroy', admin_product_path(product),
confirm: 'Are you sure?',
method: :delete %>
</td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New product', new_admin_product_path %>
Ok I hope that is all the information that is needed to help me.
This is the question: if i go to localhost:3000/admin/products/new
I get to the form to create a new product. However if i complete the form it takes me to the following localhost:3000/product/:id. I want it to redirect_to admin/products.
I keep telling myself that it has to be the redirect_to in the "create" procedure on the admin products controller, but tried everything and it is not working..... Please help it is kill me lol
A: JUst redirect to your index action instead of showing the product. This also applies to your update action if at all you also want the user to be redirected to the index page if they update a product. Just change redirect_to @product to redirect_to :action => 'index'.
A: That did not work, however here is a step by step guide.
http://icebergist.com/posts/restful-admin-namespaced-controller-using-scaffolding
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to replace a double quote with string ' \" ' in XSLT? I have an XML in which the double quotes should be replaced with the string \".
eg:<root><statement1><![CDATA[<u>teset "message"here</u>]]></statement1></root>
so the output should be <root><statement1><![CDATA[<u>teset \"message\"here</u>]]></statement1></root>
Can anybody explain how to accomplish this?
A: I. XSLT 1.0 solution:
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"
cdata-section-elements="statement1"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pPattern">"</xsl:param>
<xsl:param name="pReplacement">\"</xsl:param>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="statement1/text()" name="replace">
<xsl:param name="pText" select="."/>
<xsl:param name="pPat" select="$pPattern"/>
<xsl:param name="pRep" select="$pReplacement"/>
<xsl:choose>
<xsl:when test="not(contains($pText, $pPat))">
<xsl:copy-of select="$pText"/>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="substring-before($pText, $pPat)"/>
<xsl:copy-of select="$pRep"/>
<xsl:call-template name="replace">
<xsl:with-param name="pText" select=
"substring-after($pText, $pPat)"/>
<xsl:with-param name="pPat" select="$pPat"/>
<xsl:with-param name="pRep" select="$pRep"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<root>
<statement1><![CDATA[<u>teset "message"here</u>]]></statement1>
</root>
produces the wanted, correct result:
<root>
<statement1><![CDATA[<u>teset \"message\"here</u>]]></statement1>
</root>
II. XSLT 2.0 solution:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output omit-xml-declaration="yes" indent="yes"
cdata-section-elements="statement1"/>
<xsl:param name="pPat">"</xsl:param>
<xsl:param name="pRep">\\"</xsl:param>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="statement1/text()">
<xsl:sequence select="replace(.,$pPat, $pRep)"/>
</xsl:template>
</xsl:stylesheet>
when applied on the same XML document (as above), the same correct result is produced:
<root>
<statement1><![CDATA[<u>teset \"message\"here</u>]]></statement1>
</root>
A: <?xml version='1.0' ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version='1.0'>
<xsl:output method="xml"/>
<xsl:template match="/">
<xsl:for-each select="//p">
<xsl:value-of select="translate(text(), '&x22;','#')"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
It worked for me ....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Garbage collection in Flash Media Server I have memory leak in my project and I wonder how garbage collector working in Flash Media Server.
I have 2 questions:
*
*Will FMS release objects from memory that have cycle references. For example when object A is has ref to Object B and vise versa.
*Why FMS still consumes memory after application unloaded by idle timeout. For example there were no users connected then fms unloaded app after 20 minutes. Memory usage left at the same level (for a long period of time).
In general I miss some best practices of writing FMS code.
FMS 3.5.1 on WinXP
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Atomikos + Infinispan + Jetty errors I'm using Spring with hibernate, atomikos and infinispan on jetty. After annotating any entity as @Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL) following error appears
13:24:02.590 [main] WARN atomikos - atomikos connection pool 'atomikosDataSource': error creating proxy of connection an AtomikosXAPooledConnection with a SessionHandleState with 0 context(s)
com.atomikos.datasource.pool.CreateConnectionException: an AtomikosXAPooledConnection with a SessionHandleState with 0 context(s): connection is erroneous
at com.atomikos.jdbc.AtomikosXAPooledConnection.testUnderlyingConnection(AtomikosXAPooledConnection.java:114)
at com.atomikos.datasource.pool.AbstractXPooledConnection.createConnectionProxy(AbstractXPooledConnection.java:68)
at com.atomikos.datasource.pool.ConnectionPool.borrowConnection(ConnectionPool.java:161)
at com.atomikos.jdbc.AbstractDataSourceBean.getConnection(AbstractDataSourceBean.java:321)
at com.atomikos.jdbc.AbstractDataSourceBean.getConnection(AbstractDataSourceBean.java:373)
at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:82)
at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:51)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:168)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:375)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872)
at org.springframework.orm.hibernate3.SessionFactoryBuilderSupport.newSessionFactory(SessionFactoryBuilderSupport.java:607)
at org.springframework.orm.hibernate3.SessionFactoryBuilderSupport.doBuildSessionFactory(SessionFactoryBuilderSupport.java:467)
at org.springframework.orm.hibernate3.SessionFactoryBeanDelegate.afterPropertiesSet(SessionFactoryBeanDelegate.java:110)
at org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean.afterPropertiesSet(AnnotationSessionFactoryBean.java:121)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1479)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:476)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:377)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:278)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:549)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:136)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at runjettyrun.Bootstrap.main(Bootstrap.java:82)
It seems that problems lies between atomikos and infinispan. My configuration is based on documentations examples. However in https://docs.jboss.org/author/display/ISPN/Implementing+standalone+JPA+JTA+Hibernate+application+outside+J2EE+server+using+Infinispan+2nd+level+cache they say to add 2 properties to config but what hibernate.jndi.class I can set under jetty?
A: I don't think you need this any more since Infinispan 2LC acts as a synchronization rather than an XA resource by default (at least in latest Hibernate 4.0.1 which uses Infinispan 5.1), so I'd revert back any changes you applied from that wiki.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Memory error in Android after capturing images In my Android application I'm trying to capture three images and upload this three images. I'm capturing two images one by one no problem but when I capture third images the application crashes with error:
09-26 16:17:31.398: ERROR/AndroidRuntime(24115): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
09-26 16:17:31.398: ERROR/AndroidRuntime(24115): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
09-26 16:17:31.398: ERROR/AndroidRuntime(24115): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:459)
09-26 16:17:31.398: ERROR/AndroidRuntime(24115): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:271)
09-26 16:17:31.398: ERROR/AndroidRuntime(24115): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:296)
How can I solve the error like this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Adding element to XML using linq to XML i have this piece of code which i use to add some elements:
string xmlTarget = string.Format(@"<target name='{0}' type='{1}' layout='${{2}}' />",
new object[] { target.Name, target.Type, target.Layout });
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var xmlDoc = XElement.Load(configuration.FilePath);
var nlog = xmlDoc.Elements("nlog");
if (nlog.Count() == 0)
{
return false;
}
xmlDoc.Elements("nlog").First().Elements("targets").First().Add(xmlTarget);
xmlDoc.Save(configuration.FilePath,SaveOptions.DisableFormatting);
configuration.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("nlog");
return true;
it supposed to add a target to the xml , problem is it replace "<" with "<" and ">" with ">" which mess up my xml file.
how do i fix this ?
Note please dont pay attention to nlog, i`m concerned about the linqtoxml problem.
A: You're currently adding a string. That will be added as content. If you want to add an element, you should parse it as such first:
XElement element = XElement.Parse(xmlTarget);
Or preferrably, construct it instead:
XElement element = new XElement("target",
new XAttribute("type", target.Name),
new XAttribute("type", target.Type),
// It's not clear what your format string was trying to achieve here
new XAttribute("layout", target.Layout));
Basically, if you find yourself using string manipulation to create XML and then parse it, you're doing it wrong. Use the API itself to construct XML-based objects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Classic forms control cannot resize in WPF environment I've added a regular forms control but I cannot resize it. Instead I have to resize host.
MSDN sample: Hosting a Windows Forms Control in WPF
System.Windows.Forms.Integration.WindowsFormsHost host =
new System.Windows.Forms.Integration.WindowsFormsHost();
MaskedTextBox mtbDate = new MaskedTextBox("00/00/0000");
host.Child = mtbDate;
this.grid1.Children.Add(host);
mtbDate.Width = 200; //Not work!
host.Width = 200; //Workaraound...
How can I resize the control, not the host?
A: This page gives a lot of information about hosting WinForms controls in WPF: http://msdn.microsoft.com/en-us/library/ms744952.aspx
The short story is that you are not supposed to resize the textbox- that will be ignored/overridden. Instead, resize the WindowsFormsHost (either in WPF or via WPF dynamic layout)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to double the content of a file I've an ASCII file contains a two dimensional array of size 360X720, with all 1's & 0's.
I want to double the size of that array horizontally like 720X720. By repeating the same content. How can I do that from notepad or notepad++? Suggest me if there is any macro in the notepad++.
A: Rectangular selection FTW
*
*rectangularly select your array (holding alt key)
*copy
*move caret at the end of first line
*paste
A: Mmmm not sure you can.
In gvim (download):
you'd do:
ggC-q$GyP
*
*gg (go to first line)
*C-q -- start visual block select mode (assumes behave mswin; if you have behave xterm (default except on windows) use C-v instead)
*$ extend block selection to end of line
*G extend block selection to last line (if you have empty trailing lines, move cursor back up or do }k$ instead)
*y - yank selection into default register
*P - paste (put) yanked selection before cursor in blockwise mode
All done
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to parameterize styles? I'm new in WPF. I'm trying to do same styles. The idea is to have a button style customizable. So, for example, i would like to change the background color of the button. or the image of the button.
Here is the code of the style
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
x:Class="WPFControlsApp.App"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!-- Resources scoped at the Application level should be defined here. -->
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Simple Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
<ControlTemplate x:Key="CustomButtonStyle" TargetType="{x:Type Button}">
<ControlTemplate.Resources>
<Storyboard x:Key="CuandoEstoyArribaDelBoton">
<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="Glow">
<EasingColorKeyFrame KeyTime="0" Value="White"/>
<EasingColorKeyFrame KeyTime="0:0:0.7" Value="#FF562020"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</ControlTemplate.Resources>
<Grid>
<Rectangle x:Name="Background" Fill="#FF5A98EB" RadiusY="15" RadiusX="15" Stroke="#FF114FA1" StrokeThickness="2"/>
<Rectangle x:Name="Glow" Fill="White" RadiusY="15" RadiusX="15" Stroke="{x:Null}" StrokeThickness="0" Margin="0,0,0,49" Opacity="0.215"/>
<Rectangle x:Name="Glass" RadiusY="15" RadiusX="15" Stroke="#FF114FA1" StrokeThickness="2" Opacity="0.475">
<Rectangle.Fill>
<RadialGradientBrush RadiusY="0.62" RadiusX="0.62" GradientOrigin="0.506,1.063">
<GradientStop Color="#00000000" Offset="0"/>
<GradientStop Color="#FF00084B" Offset="1"/>
</RadialGradientBrush>
</Rectangle.Fill>
</Rectangle>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content="{Binding MINOMBREBOTON, FallbackValue=MiBoton}"/>
<Image HorizontalAlignment="Left" Margin="7,24,0,25" Width="100" Source="{Binding BtnImageSource}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True"/>
<Trigger Property="IsDefaulted" Value="True"/>
<Trigger Property="IsMouseOver" Value="True">
<Trigger.ExitActions>
<StopStoryboard BeginStoryboardName="CuandoEstoyArribaDelBoton_BeginStoryboard"/>
</Trigger.ExitActions>
<Trigger.EnterActions>
<BeginStoryboard x:Name="CuandoEstoyArribaDelBoton_BeginStoryboard" Storyboard="{StaticResource CuandoEstoyArribaDelBoton}"/>
</Trigger.EnterActions>
</Trigger>
<Trigger Property="IsPressed" Value="True"/>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</ResourceDictionary>
</Application.Resources>
</Application>
here is the problem i don´t know how to solve
<Image HorizontalAlignment="Left" Margin="7,24,0,25" Width="100" Source="{Binding BtnImageSource}"/>
I have a binding named BtnImageSource. But i don´t know how to set it in button definition.
<Button Content="Salir" Height="102" HorizontalAlignment="Right" Margin="0,0,25,26" Name="btn_salir" VerticalAlignment="Bottom" Width="280" ClipToBounds="False" Click="btn_salir_Click" Style="{StaticResource CustomButtonStyle}" />
Do you know how can i have 3 o 4 buttons each one with the same style but different images?
This is a test for a new app. The idea is to use styles with parameters or find another alternative.
Thanks in advance. I hope be clear.
A: Yes thats possible.... DynamicResource should help. Set the color properties to some DynamicResource (with a resource key). This Key may not exist at the time of declaration. Then when you need a specific color, then create a Brush of that color and declare it same Key and merge with the relevant resource.
E.g. you have this style resource that uses a dynamic color brush DynamicColorBrush to set to a button's background...
<App.Resources ...>
<Style TargetType="{x:Type Button}">
<Setter Background="{DynamicResource DynamicColorBrush}" />
</Style>
....
Note that App.Resources does not have DynamicColorBrush defined. Now suppose you define buttons in two different views
<UserControl ... x:Class="UserControl1">
<UserControl.Resources>
<SolidColorBrush x:Key="DynamicColorBrush" Color="Red"/>
</UserControl.Resources>
<Grid><Button Content="Red Button"/></Grid>
</UserControl>
and
<UserControl ... x:Class="UserControl2">
<UserControl.Resources>
<SolidColorBrush x:Key="DynamicColorBrush" Color="Green"/>
</UserControl.Resources>
<Grid><Button Content="Green Button"/></Grid>
</UserControl>
This should work.
The whole concept of flexi themes where runtime base color change is allowed is done using the dynamic resource concept.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.