text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Java: inheritance, instance variables and this I understood that this is a reference to the currently executing object. If that is the case can you explain the behaviour of the following code?
public class Inherit {
public static class ClassA
{
private String privateInstanceVar = "Private";
public void classAMethod()
{
System.out.println("In class: " + this.getClass().getName());
System.out.println("Can access: " + this.privateInstanceVar);
}
}
public static class ClassB extends ClassA
{
}
public static void main(String[] args)
{
ClassB b = new ClassB();
b.classAMethod();
//Outputs:
//In class: Inherit$ClassB
//Can access: Private
//System.out.println(b.privateInstanceVar); // Fails to compile
}
}
The first line of classAMethod reports that this is a reference to ClassB. However, on the next line I use this to access the private instance variable privateInstanceVar of ClassA, which I shouldn't have access to. (The commented out last line of main shows that this is indeed the case.)
So, my questions are:
*
*If this really is a reference to ClassB, how can I access the private instance variable on ClassA from a method that belongs to ClassB?
*Is classAMethod actually a member of ClassA and ClassB at the point of execution?
*If the answer to 2. is yes, what are the rules for determining in which context any given line in the method will execute?
*If the answer to 2. is no, then what alternative explanation is there for the behaviour of the code?
*Is there some bigger picture or subtlety here that I'm failing to appreciate?
A:
If this really is a reference to ClassB, how can I access the private
instance variable on ClassA from a method that belongs to ClassB?
Because you inherit the method from classA, and that method accesses the private variable.
Is classAMethod actually a member of ClassA and ClassB at the point of
execution?
Yes
If the answer to 2. is yes, what are the rules for determining in
which context any given line in the method will execute?
Compile-time context: the method or field that is visible from the code you are writing will be chosen. Example:
public static class ClassA{
private String foo = "bar";
public String getFoo(){return foo;}
}
public static class ClassB extends ClassA{
private String foo = "phleem";
}
new ClassB().getFoo() will return "bar", not "phleem", because ClassA does not know about ClassB.
A: I'm not sure what the source of your confusion is. It works exactly as one would expect:
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html
A: *
*Yes, this refers to the ClassB instance, which is also a ClassA instance. The method classAMethod is defined in ClassA, and thus has access to all the ClassA's private members.
*Yes, classAMethod is a method of ClassA, inherited by ClassB
*A line executes in the context of the class in which this line is defined.
*Not applicable
A: 1) Because ClassB inherit from ClassA, so all public, protected method of ClassA are visible to ClassB instance.
2) Yes.
3) unless you override the classAMethod in ClassB, ClassB will just execute the CLassA.classAMethod()
5) This is the normal way inheritance works in Java.
A: ClassB has access to classAMethod() but it does not have access to privateInstanceVar. So if you try to override classAMethod() or even define some other method which would attempt to access privateInstanceVar you would get an error. The variable would have to be declared protected in order to do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to rescale widgets in a layout? I have a widget (lets call it a main widget), which should display another two widgets. I am using QGridLayout to position these two widgets in the main widget. (This is just simplified. I really got 5 widgets in the main window)
Initially, these two widgets are of the same size, but they can rescale. For example, the 2nd widget should be displayed 2, 3 or 4 times bigger as the 1st widget, but both should be displayed.
Something like this :
I tried using addWidget, with stretching the 2nd widget over rows and columns, but that didn't work as expected (the widget's sizes remained the same)
So, how would you suggest me to achieve as requested?
If QGridLayout is not the right class, what should I use?
EDIT:
Some types:
...
struct info
{
int item;
int row;
int column;
int rowSpan;
int columnSpan;
}
typedef std::vector< info > LayoutDefinition;
...
The class WindowsContainer contains this :
vector< QWidget* > containers;
Here is the method that updates the layout:
void WindowsContainer::SetNewLayout( const LayoutDefinition & newLayoutDef )
{
// hide all containers
for ( std::vector< QWidget* >::iterator it = containers.begin(); containers.end() != it; ++ it )
{
(*it)->hide();
}
// remove all items in the layout, and release the layout
QLayout * currentLayout( layout() );
if ( 0 != currentLayout )
{
// remove all items in the layout
// (this code is taken from the reference page for the QLayout::takeAt() function)
QLayoutItem *child;
while ( ( child = currentLayout->takeAt( 0 ) ) != 0 )
{
delete child;
}
}
delete( currentLayout );
// form the new layout
QGridLayout *newLayout = new QGridLayout( this );
newLayout->setSpacing( 0 );
newLayout->setContentsMargins( 0, 0, 0, 0 );
for ( LayoutDefinition::const_iterator it = newLayoutDef.begin(); newLayoutDef.end() != it; ++ it )
{
QWidget * w( containers.at( it->item ) );
newLayout->addWidget( w,
it->row,
it->column,
it->rowSpan,
it->columnSpan
);
w->show();
}
// update the layout of this object
setLayout( newLayout );
}
It all works, until I try to set rowSpan and columnSpan. Both images still occupy the same area size.
I also tried with spacers, and that didn't work (not sure if I did it correctly).
A: Yes, this can be accomplished with layouts, spacers and size policies. Here is a screen shot from QtCreator that reproduces the effect you are looking for:
The "TopWidget" will occupy as little space as necessary as dictated by the widgets it contains and the "BottomWidget" will expand to occupy all remaining space when the application window is resized.
The "BottomWidget" has both horizontal and vertical size policies set to "expanding".
A: I figured out how to do it : it is enough to set the stretch factors.
In the above example :
for ( LayoutDefinition::const_iterator it = newLayoutDef.begin(); newLayoutDef.end() != it; ++ it )
{
QWidget * w( containers.at( it->item ) );
newLayout->addWidget( w, it->row, it->column );
w->show();
}
newLayout->setRowStretch( 0, 1 );
newLayout->setRowStretch( 1, 2 );
This will cause the 2nd row to be two times bigger then the 1st row.
A: It's impossible. Layout is a thingy that is supposed to automatically manage layout and size of widgets. Write your own layout.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: pygtk popup executes out of order I have pygtk menu, in which a function is called on menuitem click, in this function i am showing a popup to user saying wait while checking internet connectivity and then calling a function which checks internet connectivity,
My problem is the my programs is first calling the internet connectivity check function and then after completion of function call it shows me popup,
I tried putting,
while gtk.events_pending():
gtk.main_iteration_do(False)
It shows blur popup which hangs till my function call is completed and then gets clear.
my code looks something like,
dialog = gtk.MessageDialog(
parent = None,
flags = gtk.DIALOG_DESTROY_WITH_PARENT,
type = gtk.MESSAGE_INFO,
buttons = gtk.BUTTONS_NONE,
message_format = None)
dialog.set_markup("Please wait while checking internet connectivity")
dialog.set_title('Checking internet')
dialog.set_position(gtk.WIN_POS_CENTER)
dialog.connect('response', self.show_hide, dialog )
dialog.show()
gobject.timeout_add(5, self.show_hide, dialog)
try :
netStatus = check_network()
except Exception, excp:
print excp
Can somebody tell me whats wrong??
Thanks in advance...
A: The main loop calls your handler for the menu item and waits for it to return before it does anything else, including dismissing the menu so your dialog can get the focus.
The easiest workaround might be to use timeout_add to call your connection check when the main loop gets around to it, i.e. after showing the dialog.
A: You need to refactor check_network() to make it non-blocking.
Instead of making a blocking call on some socket, use gobject.io_add_watch() to register a callback that will be be notified as soon as data is ready for the socket. In this callback, you can update or destroy the popup.
On Linux GTK will most likely use the select system call behind the scene, which can wait on any number of file descriptor events with a timeout, including sockets and FIFOs (in case you are spawning a subprocess).
This concept is called "event-based programming". You have only a single thread of execution. Almost every GUI framework works this way. The idea is that you never do anything that might take longer than a few milliseconds. It's a great concept, because it avoids all the hairy problems that arise with synchronization of truly concurrent threads.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What other options do I have to streamline WordPress memory utilization? So I've run into a wall trying to crack why this WordPress install hogs so much memory. I upgraded my server from 512 to 1 gb ram on a MediaTemple DV 4.0 account, and this single install is using 60% on average, which jumps to 118% if anyone fiddles with the Dashboard. Users on the front end experience no performance issues whatsoever, and the site isn't crashing, but because so much memory is being consumed, I often have to reboot the server just to FTP or SSH in. And now, oftentimes each page in the Dashboard will hang for a solid minute or two. This happens intermittently, but once it starts, every page in the Dashboard will hang consistently, and rebooting the server doesn't correct it (it just goes back to normal mysteriously). Also, I have other WP installs on the server, but none of them are experiencing any problems in or outside the Dashboard. They are also using CloudFlare and AmazonS3 as I describe below. I know there's no straight answer for this, but I'm curious if anyone has any advice to offer what to try next, given what I've already tried:
Here's what's installed:
*
*W3 Total Cache + PHP APC (The site is using database caching, page caching, and object caching with APC).
*Image assets are being hosted on Amazon S3/Cloudfront via W3 Total Cache. I have something like 50,000 images stored on S3, although only a tiny fraction (around 1-2k) are actively used in the site.
*The site is behind CloudFlare and is using the CloudFlare plugin that corrects IPs for comments.
*I'm not doing anything particularly spectacular in the theme (http://www.rokkyuu.com). The only especially advanced thing the site does is that for certain images coming out of WP, if there exists no resized version of the image in the Media Library, WP resizes the image on the fly and then pushes that image to Amazon S3 so that when W3 Total Cache replaces the path, the front end ends up using the S3 asset. This was to avoid having WP crop 8 zillion custom sizes for every image that gets uploaded. However, this doesn't happen in the Dashboard.
*These are the plugins I have installed:
*
*Akismet
*BWP Google XML Sitemaps
*CloudFlare
*Coauthors Plus
*Facebook Page Publish
*Livejournal Crossposter
*Redirection
*SABRE
*Simple Local Avatars
*Theme My Login
*Twitter Tools
*Tweet Blender
*User Switching
*W3 Total Cache
*WordPress SEO
*WordPress Firewall 2
*WP-DB Manager
*WP Custom Admin Bar
*WP Hide Dashboard
*WPTouch Pro
What I've tried to do to debug:
*
*I installed APC caching (but then again, W3 Total Cache doesn't cache the Dashboard)
*I altered my MySQL config to match Matt Mullenweg's mysql recommendations. http://www.codinghorror.com/blog/files/matt-mullenweg-wordpress-mysql-recommendations.txt
*I installed xdebug and webgrind and analyzed the cachegrind output, but I'm not quite sure what counts as a red flag. Very few PHP functions I wrote are even listed among the items called out for having high total inclusive costs, and where the total inclusive cost is highest (php::call_user_func_array), the functions being called via call_user_func_array are evenly spread across core functions and my own. A sample cachegrind for the homepage I pulled was 15 MB. The cachegrind for the Post Edit screen in the Dashboard, on the other hand, is 186 MB, and the top offender seems to be the custom manage_posts_columns. However, I removed all manage_post_columns customizations and the Dashboard still hangs, regularly unusable.
Where do I even begin to troubleshoot further?
A: Start with a clean, fresh WP install, and then slowly add in the various things you are doing. If you watch the memory usage as you add things in, you will find the piece that is causing problems.
A: I think I found the culprit:
The CloudFlare WP plugin and the Dashboard = nuclear meltdown.
I'm not sure why, but after examining the memory profile of Dashboard pages in webgrind, I found that the curl requests for the CloudFlare API caused huge spikes in memory. Once I disabled CloudFlare from the MediaTemple DNS and disabled the plugin, the Dashboard started operating normally.
Not sure though if it's okay to have CloudFlare enabled w/o the WP plugin, but for my purposes I'd rather have a functioning Dashboard...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Returning validation errors as JSON with Play! framework I want to build an application where forms are submitted via Ajax without a complete page reload. To display server-side validation errors the server should return validation errors as JSON and an appropriate HTTP status (400).
How can I accomplish this with the Play! framework?
A: In Play Framework 2.x and Scala you can use this example:
import play.api.libs.json._
case class LoginData(email : String, password: String)
implicit object FormErrorWrites extends Writes[FormError] {
override def writes(o: FormError): JsValue = Json.obj(
"key" -> Json.toJson(o.key),
"message" -> Json.toJson(o.message)
)
}
val authForm = Form[LoginData](mapping(
"auth.email" -> email.verifying(Constraints.nonEmpty),
"auth.password" -> nonEmptyText
)(LoginData.apply)(LoginData.unapply))
def registerUser = Action { implicit request =>
authForm.bindFromRequest.fold(
form => UnprocessableEntity(Json.toJson(form.errors)),
auth => Ok(Json.toJson(List(auth.email, auth.password)))
)
}
I see that question is labeled with java tag, but I suppose this maybe useful for Scala developers.
A: Are you looking for something more complex than this:
public static void yourControllerMethod() {
... // your validation logic
if (validation.hasErrors()) {
response.status = 400;
renderJSON(validation.errors);
}
}
A: To perform server side validation of your request, Play framework provides a builtin validation module which uses Hibernate Validator under the hood.
Assuming you have a POJO class corresponding to the incoming request,
import play.data.validation.Constraints;
public class UserRequest{
@Constraints.Required
private String userName;
@Constraints.Required
private String email;
}
The request validation can be performed from controller as follows.
public class UserController extends Controller{
Form<UserRequest> requestData = Form.form(UserRequest.class).bindFromRequest();
if(requestData.hasErrors()){
return badRequest(requestData.errorsAsJson());
} else{
//... successful validation
}
}
The following response will be produced if the request fails the validation.
{
"userName": [
"This field is required"
],
"email": [
"This field is required"
]
}
In addition to this, you can apply multiple Constraints to the class fields. Some of them are,
*
*@Constraints.Min()
*@Constraints.Max()
*@Constraints.Email
A: Look at the samples-and-tests folder and the validation application. One of the examples (Sample7), does exactly what you are after, using a custom tag called jQueryValidate (which you can see in the sample).
If you try the sample, you will see that it is quite a neat solution, and in my opinion, this validation method should be part of the Core Playframework.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Can I get Entity Framework to work only part of a table? I need to connect to an existing database table and allow users to update a few columns. The thing is, this database table is part of our 3rd party software and contains over 150 columns, and I only need to access about 5 of them.
Is there a way, without using views, to get Entity Framework to select and update only a few columns?
I suppose I could pull down the entire record, but I also have a 2nd table I need to connect to and I had wanted to break that table out into multiple entities, because our software vendor, in their infinite wisdom, decided to put multiple unrelated bits of information into a single table.
A: The options mentioned so far will work, but there is an easier solution which requires neither new DB schema nor changing your model.
To select only a few columns, just project:
var smallResultSet = from b in Context.BigHonkinTable
where b.Id == someId
select new
{
This = b.This,
That = b.That
};
Check the generated SQL.
To update, use a stub:
var stub = new BigHonkinEntitiy { Id = someId };
Context.AttachTo("BigHonkinTable", stub);
// important: Mutate stub *after* attaching
stub.This = "Something else";
Context.SaveChanges();
A: The view would be the best decision here. Although it is possible to create the class and then delete 147 properties and be left with the ones you actually require. Be aware that you will need to keep the primary key in all classes!
In addition inserts might not work due to the fact that some of the columns that are left out might not allow nulls which would result in an sql exception.
A: You could do your updates thru a stored procedure mapped into EF. The SP can act on just those columns that you want; you could also use an SP for the select if you would like to cut down on the number of columns pulled down to your app.
A: The Entity Framework has a feature called Table Splitting. I found the steps here: Table Splitting in Entity Framework
You can split into two entities in your EF model so that one entity would only have the 5 columns you need. I have tried this before to help me avoid retrieving all of the data from a table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Saving images as pdf sharepoint I have some images in a asset library of sharepoint server 2010.
i want to convert and save them as PDF files.
Is there any service available within sharepoint server 2010 for this just like word automation service is used for ms office documents conversion.
A: I was working with a ConversionJob just now, the MSDN page has a full list of supported formats
TL;DR: no.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What guarantees are given by SMB and EXT3 regarding order of file writes? From my (Linux-)application, I am watching a hotfolder for specific sets of files. For example, I am waiting for this set:
*
*example-1.xml
*example-2.xml
*example-3.xml
The hotfolder is shared over the network via SMB. Now, to be sure that all files are written before I move them away, I will wait for one last empty file:
*
*example.done
My client will ensure that this file will be the last file that is written.
My assumptions are:
*
*files will be sent over the network and stored on disk in the order they were written.
*once the example.done file is available, all previous files will be complete.
Are these assumptions correct?
Searching for "file system guarantees" only results in explanations of in-file ordering or reliability in system crashes:
Guarantees of order of the operations on file
Does Linux guarantee the contents of a file is flushed to disc after close()?
What reliability guarantees are provided by NTFS?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to preempt a ProgressDialog? App I'm building is carrying out a task, ProgressDialog is on the screen circling 'round and 'round.
How can I provide the user the ability to break out of that Dialog at any given time, immediately disappear the Dialog and stop the task from being carried out mid run?
A: Try this ,if it is an AsynkTask:
dialog = ProgressDialog.show(
Activity.this,
"",
"Loading the results...Please wait.",
true,
true,
new DialogInterface.OnCancelListener(){
@Override
public void onCancel(DialogInterface dialog) {
*YourTask*.this.cancel(true);
}
}
);
A: I can't figure out what to put into the YourTask placeholder that nibha has posted. (I've tried nibha's snip in the same spot in the class where Lalit Poptani's shorter snip succesfully just disappears the dialog message only.) Anyway, the following is the class (with declarations and other stuff removed for simplicity in conveying the question). It paints something onto the screen. I just want the routine to immediately stop at the same time the message dialog disappears. (Thanks again for any help):
public class WhateverActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWhatView = new WhateverView(this);
setContentView(mWhatView);
whatever = new Whatever();
whatever.addListener(mWhatView);
whatever.execute(this);
mDialog = ProgressDialog.show(
WhateverActivity.this,
"",
"Loading the results...Please wait.",
true,
true,
new DialogInterface.OnCancelListener(){
@Override
public void onCancel(DialogInterface dialog) {
*YourTask*.this.cancel(true);
}
}
);
}
private class WhateverView extends View implements WhateverListener {
@Override
public void whateverDone() {
}
@Override
public void whateverPart(ArrayList<Float> list) {
synchronized (this) {
Iterator<Float> iter = list.iterator();
...
}
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
...
}
@Override
protected void onDraw(Canvas canvas) {
synchronized (this) {
if (mBitmap != null) {
canvas.drawBitmap(mBitmap, 0, 0, null);
}
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Navigation bar not displaying well in IE6,7,8 but works on 9 and all other browsers [www.tdeltd.net][1]
[1]: http://tdeltd.net is my site. The navigation bar is broken in all versions of IE except 9. All other browsers display the site properly. After two days of searching I am posting here as I cant find the solution. I get two errors on w3c validation but they are not relevant to the header and nav tags that the breakage is taking place within. I see some javascript related to IE versions in the head that point to files that do not exist. I am not sure where to get these. This design came from a template. CSS validated without errors so I am not sure where to put focus to try to fix ie6, 7 and 8 problems.
CSS for the header:
/* Header */
header {
height:262px;
position:relative;
}
/*===== header =====*/
header nav {
height:50px;
background:url(../images/nav-tail.gif) repeat-x left top;
position:absolute;
right:49px;
top:201px;
width:988px;
}
header nav ul li {
float:left;
}
header nav ul li a {
font-size:1.273em;
line-height:1.2em;
font-weight:bold;
color:#fff;
text-decoration:none;
display:block;
padding:17px 20px 14px 20px;
}
header nav ul li a:hover,
header nav ul li.current a {
background-color:#df5b03;
border-bottom:13px solid #0065a4;
}
HTML is easily seen on the web by "get source" in ones browser. My challenge is that I only have a mac at my disposal and have to rely on others for feedback on breakage. Can anyone help guide me to a problem area or any potential ideas as to why this looks perfect on anything except previous version of IE? Many thank you's in advance!
Daryl
Thanks again for everyones help. Adding the html5shiv to the head section was a definite fix. Stack Overflow is great! Very glad I signed up and posted. My problem was solved within one hour. Took me longer to test and confirm than it did to get rock solid answers. Thanks again!
A: Older versions of IE do not support custom tags, such as the <nav> you have used. Use <div class="nav"> instead for browser compatibility.
A: What you need is something like the html5shim, that will enable HTML5 tags in IE (older than version 8). Requires JS, though...
A: Ie versions less than 9 do not natively support html 5 elements like "nav." However, the fix is easy. By some weird quirk, if you create the element via JS (you don't even have to insert it into the DOM), IE will now know it exists and be able to style it.
So in your <head>, do this for each html5 element type you are using:
<!--[if lt IE 9]>
<script>
document.createElement('nav');
//ditto for other html5 elements
</script>
<![endif]-->
A: HTML 5 elements are not available below IE 9.
The following code will fix that:
http://html5doctor.com/how-to-get-html5-working-in-ie-and-firefox-2/
<!--[if lt ie 9]>
<script>
document.createElement('nav')
<script>
<style>
nav{display:block}
</style>
<[endif]-->
Remember, it's important to style the tags after you create them in IE.
Your best bet is to use htmlshim, which is hosted on google code and likely cahched on the person's browser already:
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
Best performance is to put that in the head after the CSS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Including demo database in installation pack I have a C# program which is using Sql Server 2008 R2 to store data.
I have a problem with deploying the application, because I want to include a demo database in the installation pack, so that its easier for users to test.
Is there a way to do this?
A: This is not simple. Your installer will have to install SQL Server, possibly a silent install. But the machine may already have it installed. In which case they will not want you to uninstall it but instead use that install.
An easier approach might be to require that the Sql Server 2008 R2 is already installed, ask for it's connection properties and create your schema in that instance during the install.
A: Can you consider installing/using the SQL Server Compact Edition, just for the demo database? Presumably the demo data will be small and it would be straightforward to add the CE edition to your regular setup.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: UISearchBar, UITableViewController and UINavigationController, Got a SIGSEGV while executing native code I have a simple test application with a NavigationController that extends UINavigationController
[MonoTouch.Foundation.Register("NavigationController")]
public class NavigationController : UINavigationController
{
public NavigationController (IntPtr handle) : base (handle)
{
}
[Export ("initWithCoder:")]
public NavigationController (NSCoder coder) : base (coder)
{
}
public NavigationController (UIViewController rootViewController) : base(rootViewController)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
View.BackgroundColor = UIColor.Green;
}
}
I have also a CustomersTableViewController that extends UITableViewController (here Source is not influential). In ViewDidLoad method I create a UISearchBar and I add it to TableHeaderView.
public class CustomersTableViewController : UITableViewController
{
UISearchBar _searchBar;
public CustomersTableViewController(UITableViewStyle style) : base(style)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
_searchBar = CreateSearchBar ();
_searchBar.SearchButtonClicked += OnSearchBarSearchButtonClicked;
TableView.TableHeaderView = _searchBar;
}
void OnSearchBarSearchButtonClicked (object sender, EventArgs e)
{
}
static UISearchBar CreateSearchBar ()
{
UISearchBar search = new UISearchBar ();
search.Placeholder = "Search Customers";
search.SizeToFit ();
search.AutocorrectionType = UITextAutocorrectionType.No;
search.AutocapitalizationType = UITextAutocapitalizationType.None;
return search;
}
}
In Main.cs, I run the following snippet of code. If I create the navigationController by code or through xib, it is the same.
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
// This method is invoked when the application has loaded its UI and its ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// If you have defined a view, add it here:
//window.AddSubview (navigationController.View);
NavigationController navigationController = new NavigationController(new CustomersTableViewController(UITableViewStyle.Plain));
window.AddSubview (navigationController.View);
window.MakeKeyAndVisible ();
return true;
}
}
The graphic interface is displayed correctly, but when I click on the searchBar the application crashes with the following error.
Stacktrace:
at (wrapper managed-to-native) MonoTouch.UIKit.UIApplication.UIApplicationMain (int,string[],intptr,intptr) <IL 0x0009f, 0xffffffff>
at MonoTouch.UIKit.UIApplication.Main (string[],string,string) [0x00042] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:29
at MonoTouch.UIKit.UIApplication.Main (string[]) [0x00000] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:34
at TestSearchBar.Application.Main (string[]) [0x00000] in /Users/lorenzo/Projects/TestSearchBar/TestSearchBar/Main.cs:13
at (wrapper runtime-invoke) <Module>.runtime_invoke_void_object (object,intptr,intptr,intptr) <IL 0x00050, 0xffffffff>
Native stacktrace:
0 TestSearchBar 0x000d1e9c mono_handle_native_sigsegv + 343
1 TestSearchBar 0x000100e0 mono_sigsegv_signal_handler + 322
2 libSystem.B.dylib 0x9373205b _sigtramp + 43
3 ??? 0xffffffff 0x0 + 4294967295
4 UIKit 0x01d73227 -[UITextField canBecomeFirstResponder] + 204
5 UIKit 0x01da7226 -[UIResponder becomeFirstResponder] + 171
6 UIKit 0x01f6f961 -[UITextInteractionAssistant setFirstResponderIfNecessary] + 208
7 UIKit 0x01f725e2 -[UITextInteractionAssistant oneFingerTap:] + 1676
8 UIKit 0x01f694f2 -[UIGestureRecognizer _updateGestureWithEvent:] + 730
9 UIKit 0x01f654fe -[UIGestureRecognizer _delayedUpdateGesture] + 47
10 UIKit 0x01f6bafc _UIGestureRecognizerUpdateObserver + 584
11 UIKit 0x01f6bce1 _UIGestureRecognizerUpdateGesturesFromSendEvent + 51
12 UIKit 0x01cff32a -[UIWindow _sendGesturesForEvent:] + 1292
13 UIKit 0x01cfaca3 -[UIWindow sendEvent:] + 105
14 UIKit 0x01cddc37 -[UIApplication sendEvent:] + 447
15 UIKit 0x01ce2f2e _UIApplicationHandleEvent + 7576
16 GraphicsServices 0x04053992 PurpleEventCallback + 1550
17 CoreFoundation 0x00ea6944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
18 CoreFoundation 0x00e06cf7 __CFRunLoopDoSource1 + 215
19 CoreFoundation 0x00e03f83 __CFRunLoopRun + 979
20 CoreFoundation 0x00e03840 CFRunLoopRunSpecific + 208
21 CoreFoundation 0x00e03761 CFRunLoopRunInMode + 97
22 GraphicsServices 0x040521c4 GSEventRunModal + 217
23 GraphicsServices 0x04052289 GSEventRun + 115
24 UIKit 0x01ce6c93 UIApplicationMain + 1160
25 ??? 0x077f6764 0x0 + 125790052
26 ??? 0x077f6630 0x0 + 125789744
27 ??? 0x077f5f60 0x0 + 125788000
28 ??? 0x077f5eac 0x0 + 125787820
29 ??? 0x077f5f37 0x0 + 125787959
30 TestSearchBar 0x0000fe9b mono_jit_runtime_invoke + 1332
31 TestSearchBar 0x001ee961 mono_runtime_invoke + 137
32 TestSearchBar 0x001f1048 mono_runtime_exec_main + 669
33 TestSearchBar 0x001f0432 mono_runtime_run_main + 843
34 TestSearchBar 0x000a3f9e mono_jit_exec + 200
35 TestSearchBar 0x002a3d21 main + 3733
36 TestSearchBar 0x00003179 _start + 208
37 TestSearchBar 0x000030a8 start + 40
=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================
Any suggestions? Is this a MT bug? Do I have missed something? Thank you in advance.
EDIT:
I'm running MT 4.2.2 with Mono 2.10.4. The crash still persists also with Mono 2.10.5.
A: Change your:
NavigationController navigationController = new NavigationController(new CustomersTableViewController(UITableViewStyle.Plain));
from a local variable (which the GC can collect as soon as it's not used anymore) into a field (which will keep the reference alive as long as the type's instance exists). E.g.
private NavigationController navigationController;
...
navigationController = new NavigationController(new CustomersTableViewController(UITableViewStyle.Plain));
Note that:
window.AddSubview (navigationController.View);
will only keep a reference to the View, not to it's parent (common mistake).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How would I get text from an input 'type=text' element using jquery? Provided I cannot edit the HTML code at all how would I do this?
<input type="text" id="Identifier"
class="inputControlFlexWidth" value="" tabindex="9" size="25"
name="texthole">
I'm guessing this has to be a timed event such as
setInterval(ObserveInputValue(), 100);
Because the input can happen at any time.
I then want to use this text to update a URL.
Thanks.
Edit:
<input id="ServiceRequestEditForm.CustomObject6 Name.hidden" type="hidden" value=""
tabindex="-1" name="ServiceRequestEditForm.CustomObject6 Name.hidden">
A: One way is
$('#Identifier').blur(function(){
$(this).val();
});
Explanation: When the input loses focus, grab the value of the field.
Example: http://jsfiddle.net/4DtUh/
EDIT
As per the comments...
@Interstellar_Coder is right about spaces inside the id.
So, instead of using the id as the "hook", you could use the name attribute:
$('input[name="ServiceRequestEditForm.CustomObject6 Name.hidden"]')
Example 2: http://jsfiddle.net/4DtUh/10/
A: You can add an event listener for the change event, then do whatever you need to in there.
$('#Identifier').change(function(){
//do whatever you need to
});
A: No, nothing so complex. You can just use .val() to get the value. In your code you would do:
$('#Identifier').val()
Take a look at the documentation for val()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Drupal live and staging image path I have 2 version of my drupal site that are the live and staging. My live site is http://www.mysite.com/ and the staging is http://mystaging.com/site/www.mysite.com/.
In live site, the path of images is displaying but on my staging the images are not displaying. It’s because of the 2 subdirectory (site/www.mysite.com/) on my staging.
I would like to ask about solutions how I can display all images in my staging without editing the database or some .tpl.php file just to add “site/www.mysite.com/”. Is it possible to fix via .htaccess?
I hope someone can help me or enlighten me.
Thank you.
A: You can change the $base_url variable in sites/default/files/settings.php for your local copy, that should let you set an absolute base path for your site
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to set enable=false to a item template inside a grid in asp.net I want to set enable = false according to the role
I have an if statement to check for the role
page load() {
if(role == "something")
{
// I want to set imgbtn.enabled = false;
}
}
How to do that.
<Columns><asp:TemplateField HeaderText="Edit Controls" ItemStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="imgbtn" ImageUrl="Styles/Images/Edit.jpg" runat="server" OnClick="imgbtn_GroupEditClick" ToolTip="Edit Group" />
<asp:ImageButton ID="img_Send" ImageUrl="Styles/Images/Message.jpg" Enabled="True"
runat="server" PostBackUrl='<%# Eval("GroupName", "SendMessage.aspx?GroupName={0}") %>'
ToolTip="Create Message"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="GroupID" ItemStyle-Width="0%" HeaderText="GroupID" />
<asp:BoundField DataField="GroupName" ItemStyle-Width="20%" HeaderText="GroupName" />
</columns>
I am doing databinding for the grid
A: You can handle the RowDataBound Grid's event
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Or you can use e.Row.Cells[0].FindControl("ur control id");
foreach (object c in e.Row.Cells[0].Controls)
{
ImageButton btn = c as ImageButton;
if (c != null && role == "something")
{
//Do your logic here
}
}
}
A: Handle the RowDataBound event on the GridView like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
var btn = e.Row.FindControl("imgbtn") as Button;
btn.Enabled = role == "something";
}
A: If you have one or more controls on the page you wish to enable or disable based on a role, you could create a public property in your page/control like so:
public bool BelongsToRoleA { get; set; }
Set its value based on the role
If(role==”something”)
{
BelongsToRoleA = true;
}else
{
BelongsToRoleA = false;
}
And then reference it in your markup like so:
<asp:ImageButton ID="imgbtn" Enabled='<%# BelongsToRoleA %>' ...
A: Maybe you can use a databinding expression and do it in the ASPX markup:
<asp:ImageButton ID="imgbtn" Enabled='<%# role == "something" %>' ... />
A: You can also do like this:-
set on your .aspx.cs page
public string role { set; get; }
and in design part replace your code with this
<Columns>
<asp:TemplateField HeaderText="Edit Controls" ItemStyle-Width="15%">
<ItemTemplate>
<%if (role == "Something")
{ %>
<asp:ImageButton ID="imgbtn" ImageUrl="Styles/Images/Edit.jpg" runat="server" OnClick="imgbtn_GroupEditClick"
ToolTip="Edit Group" Enabled="false" />
<%}
else
{ %>
<asp:ImageButton ID="ImageButton1" ImageUrl="Styles/Images/Edit.jpg" runat="server" OnClick="imgbtn_GroupEditClick"
ToolTip="Edit Group" Enabled="true" />
<%} %>
<asp:ImageButton ID="img_Send" ImageUrl="Styles/Images/Message.jpg" Enabled="True"
runat="server" PostBackUrl='<%# Eval("GroupName", "SendMessage.aspx?GroupName={0}") %>'
ToolTip="Create Message"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="GroupID" ItemStyle-Width="0%" HeaderText="GroupID" />
<asp:BoundField DataField="GroupName" ItemStyle-Width="20%" HeaderText="GroupName" />
</Columns>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iOS camera, torch intensity control is there a way to control the iPhone 4 torch intensity.
I did a lot of looking around and the documentation says there are only 3 states : off, on, auto. Any kind of workaround is welcome.
A: No, there is not a way to do this as of iOS 5.0.1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fill continental areas in geographical maps created with R I try to get into creating geographical maps using the maps-package in R. I'm not sure if this is the "package of choice".
I tried to draw a map of the world with a bluish background, white continental areas and red country borders. But it seems, that it is not possible to fill areas without drawing country borders in black. What is my mistake?
library(maps)
# Show the World map without country border,
# with black continent boundaries on a bluish background
map("world", interior=F, boundary=T, bg="#ddeeff", col="black")
# Fill continental areas in white
map("world", col="white", interior=F, fill=TRUE, add=T)
# Add country borders in red
map("world", interior=T, boundary=F, col="red", add=T)
Using ?map gives me:
fill - logical flag that says whether to draw lines or fill areas. If FALSE, the lines bounding each region will be drawn (but only once, for interior lines). If TRUE, each region will be filled using colors from the col = argument, and bounding lines will not be drawn.
My R-Version is:
platform x86_64-apple-darwin9.8.0
arch x86_64
os darwin9.8.0
system x86_64, darwin9.8.0
status
major 2
minor 13.0
year 2011
month 04
day 13
svn rev 55427
language R
version.string R version 2.13.0 (2011-04-13)
A: Using base graphics:
(There is a certain amount of overplotting of red on top of black boundaries - I couldn't find a way of getting rid of this altogether.)
library(maps)
map("world", interior=TRUE, fill=TRUE, boundary=FALSE, col="white", bg="lightblue")
map("world", interior=TRUE, boundary=TRUE, col="red", add=TRUE)
Using ggplot:
(With ggplot you have full control over all the colours and there is no overplotting. But it takes a bit longer to render...)
library(ggplot2)
library(maps)
mapWorld <- borders("world", colour="red", fill="white")
ggplot() +
mapWorld +
geom_path() +
opts(
plot.background=theme_rect(fill="lightblue"),
panel.background=theme_rect(fill="lightblue")
)
A: It is possible to change the color of the borders in a single 'map' command:
map("world", fill=TRUE, col="white", bg="lightblue", border="red")
The "border='red'" option is not documented explicitely in '?map', because it is in fact an option directly for "polygon()" which is called from inside map(). It's part of the "..." in the map() call.
A: Using base graphics:
In order to avoid the overplotting, you can set the lty argument to 0 in the first call to fill the countries without drawing the black boundaries.
library(maps)
map("world", interior=TRUE, fill=TRUE, boundary=FALSE, col="white", lty=0, bg="lightblue")
map("world", interior=TRUE, boundary=TRUE, col="red", add=TRUE)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: OOP : Naming a class In my application I have a Market with a bunch of Levels. Each level has Goods and Supply Chain Operations. Now, I'm stuck figuring out how to name a family of classes that populate Levels with these entities. I know that a name is important in a sesnse that a proper one makes code self-commented. Since stuff like Builder, Creator, Factory, Provider is more of a wiring classes, I'm out of ideas. Right now I use Market_Level_Goods_Filler, but it feels odd. Any suggestions? Thanks
A: Personally I like to use the Command/Query pattern as a way of dividing and managing these types of classes.
In this context your class would be a command. Either way I'd be naming my classes to describe what they actually do.
What does your class do?
Perhaps PopulateLevelsForMarket or PopulateMarketLevels? (PopulateLevelsForMarketCommand if using the Command/Query paradigm).
If you're finding it hard to name your class because it does a variety of different things you'll want to start thinking about breaking up the class so that the focus is one a single set of operations.
Think SRP at the class level.
A: Your description makes me think that Market and Level make up a Gang of Four Composite pattern. Is that correct?
I would say that a LevelBuilder or LevelLoader would be appropriate. I don't understand your "more of a wiring classes" [sic] objection. Populate sounds like a creation verb to me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to perform server-side validation before submit Form contains input element. Entered value is validated using server callback from blur
event andler.
If wrong value is entered and submit button is pressed, form is submitted with wrong value:
Validate method is not completed but form submit action method is executed.
How to force Validate() method to be completed before form submit method is executed ?
jquery, jqueryUI, ASP .NET MVC2 are used.
<form id="Form" class='form-fields' method='post' action='/Report/Render'>
<input id='test' name='test' value='test' />
<input id='_submit' type='submit' value='Show report' />
</form>
$('#test').bind({
blur: function (e) {
if (!Validate(e.target)) {
cancel(e);
}
}
});
Update
As required in BobTodd comment here is validate method:
function Validate(elem) {
var i,
res;
$.ajax('Grid/Validate' );
{
data: $("#Form").serializeArray(),
//async: false,
type: 'POST',
error: function (jqXHR, textStatus, errorThrown) {
elem.skipBlur = true;
errorMessage(decodeErrorMessage(jqXHR.responseText === undefined ? '' : jqXHR.responseText,
textStatus, errorThrown));
elem.focus();
elem.select();
elem.skipBlur = false;
elem.ischanged = true;
res = false;
},
success: function (data) {
elem.ischanged = false;
for (i = 0; i < data.length; i += 1) {
$('#' + data[i].name).val(data[i].value);
}
res = true;
}
});
return false; // res;
}
Update2
All answers suggest to prevent submit method to run if validation is not preformed. This provides very bad user experience: validate takes some time. User shoudl press two times in submit button for form to submit. How to allow form to submit using single click ? Maksing Validate() sync method alllws this but i'm not sure is using sync call reasonable solution for this.
A: You will have to rerun the Validate method on form submit and cancel it there.
Look at the jQuery Validate plugin, it supports remove validation methods that work super easy w/ mvc.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
http://docs.jquery.com/Plugins/Validation/Methods/remote#options
A: Just disable the submit button until validation is complete.
A: Wouldnt you be best served binding that jquery to the submit event of the form instead otherwise its just when the user leaves the textbox...
$('.form-fields').bind({
submit: function (e) {
if (!Validate(e.target)) {
cancel(e);
}
}
});
A: When you validate a field, add a valid class to the element if it's valid. Then, when submitting the form, simply check if all of the fields have that class :
$('#Form').submit(funciton(e){
$(this).find('input').length == $(this).find('input.valid').length || e.preventDefault();
});
$('#Form input').bind({
blur: function (e) {
if(Validate(e.target))
$(e.target).addClass('valid');
else
$(e.target).removeClass('valid');
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Check the possibility of allocating a certain amount of memory on the x64 platform I have an application that uses a lot of memory, but it is a normal situation. I need to inform user if there is not enough memory to perform an operation.
I know that x86 process can allocate less then 2 GB user memory. But x64 process can allocate much more user memory depending on physical memory.
Earlier the application supported x86 platform only and I used the following code:
private bool CheckMemoryInternal(long bytesCountToCheck) {
// Get physical memory of the current workstation
long memSize = long.MaxValue;
NativeMethods.MEMORYSTATUSEX memory = new NativeMethods.MEMORYSTATUSEX();
memory.dwLength = (uint)System.Runtime.InteropServices.Marshal.SizeOf(memory);
if (UnsafeNativeMethods.GlobalMemoryStatusEx(ref memory))
memSize = (long)memory.ullTotalPhys;
// Don't know the reason, but this value is measured in kilobytes, and MSDN wrote that it is measured in bytes
long maxWorkingSet = (long)Process.GetCurrentProcess().MaxWorkingSet * 1024;
// Obtain the maximal amount of memory for our app
// If the current amount of physical memory is less than maxWorkingSet, we can use it, but it should not be less than 512 MB for our application.
long maxMemorySize = Math.Min(Math.Max(512 * OneMegaByte, memSize), maxWorkingSet);
return bytesCountToCheck + Process.GetCurrentProcess().PrivateMemorySize64 < maxMemorySize;
}
I know one more way to do that:
private bool CheckMemoryInternal(long megaBytes) {
try {
byte[][] chunks = new byte[megaBytes][];
for (int i = 0; i < chunks.Length; i++)
chunks[i] = new byte[1024 * 1024];
return true;
}
catch (OutOfMemoryException) {
return false;
}
}
But I don't like this way.
Now I migrated the application to the x64 platform. And at first the code sample didn't work correctly. The maximal size of the allowed memory used for allocating remained the same as in the x86 application (MaxWorkingSet(32 bit) == MaxWorkingSet(64 bit)).
I tried to allocate a lot of memory on a x64 machine and I succeeded. I was able to allocate 4Gb memory on a x64 machine with 4Gb physical memory, and after that I've got the OutOfMemory exception.
How can I check the possibility of allocating a certain amount of memory on the x64 platform?
A: That's not at all how Windows works. It is a virtual memory operating system. You get OOM when you can no longer allocate any more virtual memory. Physical memory (RAM) has nothing to do with it.
When your code runs in 32-mode, it has 2 gigabytes of addressable virtual memory. OOM happens when you try to allocate a chunk of memory and there isn't a hole left that's big enough to fit the request. Large allocations fail earlier. Never assume you can allocate everything, once a program has allocated more than a gigabyte, the odds that it will fail start to increase rapidly.
A problem that's solved on 64-bit operating system. Addressable virtual memory size is somewhere between 192 gigabytes and 2 terabytes, depends on the Windows version. The constraint is now how much of that huge address space is mappable. The maximum size of the paging file. Which is a moving target, the paging file is shared by other processes. When you get close to the limit you have much bigger problems, like garbage collections that take forever. You just don't bother anymore telling the user how close to OOM she gets, she already knows from your program not being responsive anymore.
Windows Internals is a good book to learn more about the way Windows works.
A: See MemoryFailPoint for a way to verify allocations without having the unpredictability of trying to intercept an OutOfMemoryException. Note that this works for x86 as well as for x64.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: String format compare in objective c hello all i have one NSString in this format +1-123-123-1234 (phone number US base style) , my question is How can we compare that my string is formted in +1-123-123-1234 format .
on the basic of String compare formatted i have to done another task ..so any one have any idea regarding same please help me .
A: You can use a NSRegularExpression to test if your string is of a certain format.
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"^\\+\\d-\\d{3}-\\d{3}-\\d{4}$"
options:NSRegularExpressionCaseInsensitive
error:nil];
int num = [regex numberOfMatchesInString:phoneNumberHere
options:0
range:NSMakeRange(0, [phoneNUmberHere length])];
if (num == 1) {
// match!
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: XAML Stop List Box Text Style Changing on Defocus I have an issue with a .NET 4 XAML program which contains a ListBox.
When a the list box looses focus the text turns to grey rather than the set white colour. The background did do this but I resolved that with
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#376807" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#487918" />
</Style.Resources>
I have tried several methods of resolving this including
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="#FFFFFF" />
</Trigger>
<Trigger Property="IsSelected" Value="False">
<Setter Property="Foreground" Value="#444444" />
</Trigger>
</Style.Triggers>
But not have been successful...
A: OK I have edited my code. Just check if this satisfies your need, if not then please revert.
The following has been tried with some dummy data in the listbox and it works. I hope this is what you were looking for, if not, then please clarify some more.
<DataTemplate x:Key="SelectedTemplate">
<TextBlock Text="{Binding}" Background="Green" Foreground="White" />
</DataTemplate>
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
<Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<ListBox x:Name="dummyList" ItemContainerStyle="{StaticResource ContainerStyle}" HorizontalContentAlignment="Stretch" >
<ListBoxItem Content="A" />
<ListBoxItem Content="B" />
<ListBoxItem Content="C" />
</ListBox>
<Button Height="31" Width="61" Content="Click"/>
<ListBox Name="listBox2" Height="100" Width="120" HorizontalContentAlignment="Stretch">
<ListBoxItem Content="XX" />
<ListBoxItem Content="YY" />
</ListBox>
</StackPanel>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Entity Framework Code First DbContext Checks the ConnectionString During Compile? It seems that the Code First DbContext really uses the given ConnectionString during compile? I don't even know how that is possible but to me it seems to be so. If I turn OFF my local SQL Server, I get the error stating "Failed to get the MetadataWorkspace for the DbContext type...". Turning the SQL Server ON, everything compiles fine.
Here's part of my context (I'm using an existing database and yes, I know, not actually code first)
public class MyContext : DbContext
{
public MyContext() : base("MY_DYNAMIC_CONNECTIONSTRING")
{
Database.SetInitializer<MyContext>(null);
}
...
If this is really the case, there's a huge problem. How can I prevent it from doing that? What if I'm using separate build machines where the ConnectionString doesn't work? Or am I doing something wrong? Any advice?
A: WCF RIA Services instantiates a DbContext at design time and build time, not only at runtime:
Quote from http://jeffhandley.com/archive/2011/06/30/RIAServicesCodeFirst.aspx:
In order to generate code into your Silverlight project, RIA Services
has to inspect your DbContext at build time in order to get the entity
types that are available.
Quote from http://varunpuranik.wordpress.com/2011/06/29/wcf-ria-services-support-for-ef-4-1-and-ef-code-first/#comment-102
The difference between EF CodeFirst stand alone and with RIA Services
is that we initialize a new DbContext at design time as well.
If the connection string is not valid or the connection can't be established you apparently get the exception you mentioned.
A: Here is the way that I use to track down the root cause of the "Failed to get the MetadataWorkspace for the DbContext type '{type}'" error:
http://joshmouch.wordpress.com/2011/11/09/failed-to-get-the-metadataworkspace-for-the-dbcontext-type-type/
I know it doesn't specifically answer your question, but it could help others who search Google for this error message.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Immutable in java In Effective Java, Bloch recommends to make all the fields final in making an object immutable .
Is it necessary to do so ? Won't just not giving accessor methods make it immutable.
For example
class A {
private int x;
A (int x) {
this.x = x;
}
}
The above class is immutable even if I don't declare x as final right ? Am I missing something ?
A: In addition to @Bozho's point, declaring a field as final means that it can be safely accessed without any synchronization.
By contrast, if the field is not final there is a small risk that another thread will see an anomalous value for the field if it accesses it without proper synchronization. This can happen even if nothing changes the field's value after object construction!
A: It is not "completely" immutable, because you can change the values. Next thing will be someone else on the team assigning a new value to the field. final indicates the intention of immutability.
A: The class 'Effectively Immutable', as Java Concurrency In Practice defines the term.
This means that, as long as references to instances are 'safely published', they are immutable. Safely publishing the reference involves using synchronisation such that the Java Memory Model (JMM) can guarantee that callers will see the value of the field fully written. For example, if the field is not final, and an instance is constructed and passed to another thread, the other thread may see the field in an undefined state (such as null if it's an object reference, or only half of a 64-bit long field).
If the instance is only used in a single thread, then the distinction doesn't matter. This is because the JMM uses 'within-thread as-if-serial' semantics. Thus the assignment of a field within a constructor will always happen before the field can be read.
If the field was final, the JMM would guarantee that callers would see the correct value, no matter how the reference was published. So final has a benefit if you want to pass the instance to other threads without using forms of synchronisation.
A: You could also do that, but the compiler will help you when you declare it final. As soon as you try to assign a new value to a member variable the compiler will throw an error.
A: In it's current form, yes, this class is immutable. Ignoring reflection of course.
However as @Bozho says it only takes someone adding a method to change that.
Making x final provides extra safety and makes your intent clear.
A: You can always set a private field with setAccessible. This is how Spring, Hibernate and other such frameworks operate. If it is also possible to subclass A, this raises the question about whether all instances of A are immutable or not.
The main benefit from making immutability explicit is that it makes the intention of the coder clear. There can not be a setter for final so someone reading the code does not have to look for it. I usually also state the intention of immutability in the class comment.
(I assume you know the benefits of immutability in general, because you asked just about the mechanisms.)
A: Apart from the possibility to add code that changes the value of non-final field, the JVM treats final and non-final fields differently. The Java memory model has a section on the subject (quite non-casual reading).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: UIVideoEditorController know the start and end point I am trying to use the UIVideoEditorController to be a UI so user can choose the place to split the video into 2 pieces. The problem with the UIVideoEditorController is that I cannot know where user chooses the start position and end positions. Does anybody know how I can get these information from UIVideoEditorController? Or does it have any third party library that replicate the user interface of UIVideoEditorController?
A: No by using UIVideoEditorController you cannot get start position and end positions whatever the user had selected. And still now there is no third party library.
A: You can alternatively do this task with image picker controller
after knowing the start and end point split the video or whatever you want
-(void) imagePickerController: (UIImagePickerController *) picker
didFinishPickingMediaWithInfo: (NSDictionary *) info
{
NSNumber *start = [info objectForKey:@"_UIImagePickerControllerVideoEditingStart"];
NSNumber *end = [info objectForKey:@"_UIImagePickerControllerVideoEditingEnd"];
}
Set allows editing yes
and this will give the start and end point of user selected part for iOS 5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: generate a patterned numpy matrix Is it possible to generate a numpy matrix with a circular pattern of "1"s in a rest matrix of "0"s? So basically a
generate(ysize, xsize, ycenter, xcenter, radius)
Should look something like
[000000000]
[000000000]
[000001000]
[000011100]
[000111110]
[000011100]
[000001000]
[000000000]
(ok this looks stupid but on a 1000x1000 scale it would make sense)
Is there such a possibility in numpy?
A: def generate(ysize, xsize, ycenter, xcenter, radius):
x = np.arange(xsize)[None,:]
y = np.arange(ysize)[:,None]
return ((xcenter - x) ** 2 + (ycenter - y) ** 2 <= radius ** 2) * 1
generate(10,8,4,3,2)
array([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]])
A: A little more concisely than @eumiro's answer, but essentially the same.
import numpy
def generate(ysize, xsize, ycenter, xcenter, radius):
x, y = numpy.mgrid[0:ysize,0:xsize]
return ((x - ycenter)**2 + (y - xcenter)**2 <= radius**2) * 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How I can Save WebView Contents to show even when no network available? I am creating a app and using WebView for open URL. I see some apps offer "Save Page"(A web page) option to user.
I want to know how to Save a page from my WebView so that I can show it to user when it request.
A: Maybe using a cache is the best way... for that you should check http://developer.android.com/reference/android/webkit/WebSettings.html
"Manages settings state for a WebView. When a WebView is first
created, it obtains a set of default settings. These default settings
will be returned from any getter call. A WebSettings object obtained
from WebView.getSettings() is tied to the life of the WebView. If a
WebView has been destroyed, any method call on WebSettings will throw
an IllegalStateException."
Especifically:
public static final int **LOAD_CACHE_ONLY**
Since: API Level 1
Don't use the network, load from cache only. Use with setCacheMode(int).
Constant Value: 3 (0x00000003)
Or
public static final int **LOAD_CACHE_ELSE_NETWORK**
Since: API Level 1
Use cache if content is there, even if expired (eg, history nav) If it is not in the cache, load from network. Use with setCacheMode(int).
Constant Value: 1 (0x00000001)
Update1:
hmm "crappy code of all life" for example:
public static InputStream fetch(String url) throws MalformedURLException,
IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
private static String convertStreamToString(InputStream is)
throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
return writer.toString();
}
So, you can fetch a url with InputStream fetch(String url) an then convert that stream to String with private static String convertStreamToString(InputStream is) and save that stream to a file, later you can load that content to a webview..... to read later
Update2:
Or you can do some Java Serialization stuff... cant remember if this work on android xD
Discover the secrets of the Java Serialization API http://java.sun.com/developer/technicalArticles/Programming/serialization/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to do Spring.NET DI injection in action filters (ASP.NET MVC 3) Tried to search but no specific answers (I am very new in this)...
With Spring.NET supporting ASP.NET MVC 3, how can I do dependency injection inside action filters? Studied around but I have no clue at all! :/
On Spring.NET documentary, it appears to mention that this has all been taken care of, all that's needed to do is to just register the action filter into spring's context and spring will take care of all the necessary injection process.
http://www.springframework.net/doc-latest/reference/html/web-mvc3.html
However, I just can't get it to work. Studying around blogs and etc, there are mentions of using filter providers, or directly using ContextRegistry.GetContext(), but this doesn't appear to adhere to AOP..
Using Spring.Net to inject dependencies into ASP.NET MVC ActionFilters
Spring.Net & Attribute Injection
So what's the proper way to do this? I thought this is already covered by spring.net, but it appears that it isn't.
I referenced to Spring.Web.Mvc3 v4.0.30319, and I am running on ASP.NET MVC 3.
EDIT:
I tried this:
SpringMvcDependencyResolver dr =
new SpringMvcDependencyResolver(ContextRegistry.GetContext());
and then getting the service via dr.GetService<ITestService>(); This seems to make it work somewhat, but instead of getting the correct actual service implementation (on my Filters.xml, I wrote the property ref to TestService), it returns the Stub version of the service. Did I do it wrong? Or do I have to sift through and pick the right one or something via GetServices()?
EDIT2:
@Andreas: Sorry for the late reply. But, my Global.asax DOES have it in.
public class MvcApplication : Spring.Web.Mvc.SpringMvcApplication
To test, I have this in my spring config:
<object type="Spring.Mvc3QuickStart.Filters.TestFilter, Spring.Mvc3QuickStart" singleton="false" >
<property name="Message" value="This is the ActionFilter message" />
</object>
In my filter:
public class TestFilter : ActionFilterAttribute
{
public string Message { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewBag.ActionMessage = Message;
base.OnActionExecuting(filterContext);
}
}
In my controller I have this:
ViewData["Message"] = Message;
So purely for this test project, the Filter should have the message injected. But the output isn't as expected.
A: The 1.3.2 release of Spring.Net.Mvc3 seams to be a bit buggy. In SpringMvcDependencyResolver the method public IEnumerable<object> GetServices(Type serviceType) will always fail. It should be return services.Values.Cast<object>(); instead of return services.Cast<object>();. The simplest fix is to override BuildDependencyResolver of SpringMvcApplication and register your own fixed SpringMvcDependencyResolver.
I created a complete solution hosted here:
https://gist.github.com/1262927
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JSON object parsing into a TRY, CATCH block I would like to check for a condition which if true should goto the next statement. The problem I am facing is that I've put the code in a try, catch block. Every time I check for its value I need to initialize it, but once initialized if found untrue, as normal execution the try block exits and passes the handle to the catch block
public class HandleJSON{
UserHelper userAdapter;
private static final String TAG = "&&----HTTPClient-----**";
public static String SendHttpPost (String URL, JSONObject jsonobj) {
String regName = "";
try{
Log.v("Json object request is ", jsonobj.toString());
DefaultHttpClient httpClientInstance = GetHttpClient.getHttpClientInstance();
HttpPost httpPostRequest = new HttpPost(URL);
Log.v(TAG,"The url is "+URL);
StringEntity se;
se = new StringEntity(jsonobj.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpClientInstance.execute(httpPostRequest);
Log.i(TAG, "HTTPRESPONSE RECIEVED" +(System.currentTimeMillis()-t) + "ms");
String resultString = convertStreamToString(response.getEntity().getContent());
Log.v(TAG , "The response is " +resultString);
JSONObject jsonObj = new JSONObject(resultString);
JSONObject sessionJson = jsonObj.getJSONObject("session");
Log.i(TAG,"is it coming here");
Log.i(TAG,""+sessionJson.getJSONObject(resultString).toString());
String sessionId = sessionJson.getString("sessionid");
String name = sessionJson.getString("name");
JSONObject messageJson = jsonObj.getJSONObject("message");
Log.i(TAG, "message is true log statement");
String type_JSON = messageJson.getString("sessionid");
String content_JSON = messageJson.getString("name");
Log.i(TAG,""+messageJson.getJSONObject(resultString).toString()+type_JSON+content_JSON);
Log.v(TAG,"The session ID is "+sessionId);
Log.v(TAG,"The name is "+name);
regName = name+"-"+sessionId+"-"+URL;
} catch (Exception e){
Log.i(TAG, "message is true log statement");
e.printStackTrace();
}
Log.v(TAG,"before the return statement "+regName.toString().split("-"));
return regName;
}
I'll put in a bit of explanation here I will get a JSON object that I will parse it. There are two types of JSON response that I will get
message: if username & password is not correct
session: if username & password is correct
I want to check if session is true, then pass the control to initialize the session statement and split it apart.
Hope I was clear.
Thanks in advance
A: you can use
jsonObj.has("session")
to see if the resultant message is valid. The above statement will return true if resultant json has "session" key in it. you can do the same if you want to check for message.
HTH.
A: Well I figured this out by putting my session code in the Catch statement. If the condition is true it will continue execution. If the condition is false it will go the catch block and execute the statements there instead of just using printstacktrace()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: objective-c: Webservice, How to get two elements after parsing through NSXMLParser? I am using the below code which gives me the string of one element after parsing, while I want to get another element's text on the base of first element's result.
e.g. I am getting bool value from ResponseType and now on the base of that value I want to get another element's ("TotalAmt") value. and if ResponseType is 0 anohter field appears in code which is DeclineReason and then I want to get DeclineReason's value.
<AuthorizeResult>
<ResultCode>Success</ResultCode>
<RequestTime>2011-09-30T01:42:54.1834586-04:00</RequestTime>
<ResultObj>
<RequestId>55258</RequestId>
<ResponseType>1</ResponseType>
<UserType>Permanent</UserType>
<RequestDate>2011-09-30T05:42:54.481</RequestDate>
<TransactionId>0081315926057572</TransactionId>
<TransactionCode>001440</TransactionCode>
<TotalAmt>1</TotalAmt>
<UserId>47</UserId>
</ResultObj>
</AuthorizeResult>
I code this but its not workin g and get only the value of "ResponseType"
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *) attributeDict {
if ([elementName isEqualToString:@"ResponseType"])
{
if (!soapResults)
{
soapResults = [[NSMutableString alloc] init];
elementFound = YES;
}
}
}
//---when the text in an element is found---
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string {
if (elementFound)
{
[soapResults appendString: string];
}
}
//---when the end of element is found---
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:@"ResponseType"])
{ //---displays the country---
NSLog(@"%@", soapResults);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response Type!" message:soapResults delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
[soapResults setString:@""];
elementFound = FALSE;
}
}
A: I call [xmlParser parse] two times.
qelementName = @"ResponseType";
[soapResults setString:@""];
[xmlParser parse];
ResponseType =[[NSString alloc] initWithFormat:@"%@", soapResults];
qelementName = @"TotalAmt";
[soapResults setString:@""];
[xmlParser parse];
TotalAmt = [[NSString alloc] initWithFormat:@"%@", soapResults];
and it works.
A: How about
if ([elementName isEqualToString:@"ResultObj"] || [elementName isEqualToString:@"Reason"])
in both didStartElement and didEndElement?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Linq projection of flattened table into parent and child object graph I have a enumerable list that contains a flattened parent-child relationship:
ParentGuid1, ParentName1, ChildGuid1, ChildName1
ParentGuid1, ParentName1, ChildGuid2, ChildName2
ParentGuid2, ParentName2, ChildGuid3, ChildName3
ParentGuid2, ParentName2, ChildGuid4, ChildName4
I have defined a Child class and a Parent class that includes a List<Child> property called Children.
Can I use linq to create on object graph with one instance of the Parent class per unique ParentGuid, referencing a List populated by the children associated with that parent.
Something along the lines of this (note, this code doesn't compile):
myFlattenedHierarchy.Select(p => new Parent
{Guid = p.ParentGuid,
Name = p.ParentName,
Children = myFlattenedHierarchy.Where(c => c.ParentGuid == p.ParentGuid).Select(c => new Child{Guid = c.ChildGuid, Name = c.ChildName})
});
A: myFlattenedHierarchy.Select(p => new Parent
{Guid = p.ParentGuid,
Name = p.ParentName,
Children = myFlattenedHierarchy.Where(c => c.ParentGuid == p.ParentGuid).Select(c => new Child{Guid = c.ChildGuid, Name = c.ChildName})
});
You should be able to do that, but the Children can not be a List, it has to be IEnumerable.
A: Here's the pre-Linq way to do it with a simple loop.
Dictionary<Guid, Parent> parents = new Dictionary<Guid, Parent>();
foreach(RowType row in myFlattenedHierarchy) //just enumerate once
{
if (!parents.ContainsKey(row.ParentGuid)
{
Parent newParent = new Parent(row);
parents[row.ParentGuid] = newParent;
}
Child newChild = new Child(row);
Parent theParent = parents[row.ParentGuid];
theParent.Children.Add(newChild);
}
List<Parent> result = parents.Values.ToList();
Or you could use GroupBy to get a similar result.
from row in myFlattenedHierarchy
group row by row.ParentGuid into g
select new Parent()
{
Guid = g.Key,
Name = g.First().ParentName,
Children =
(
from childRow in g
select new Child()
{
Guid = childrow.ChildGuid,
Name = childrow.ChildName
}
).ToList()
}
It's a toss-up which is more maintainable. Either way, don't re-enumerate myFlattenedHierarchy inside the loop/query.
A: I believe you can use GroupBy() (full disclosure: not compiled):
myFlattenedHierarchy.GroupBy(row => row.ParentGuid)
.Select(group => new Parent
{
Guid = group.Key.ParentGuid,
Name = group.Key.ParentName,
Children = myFlattenedHierarchy.Where(c => c.ParentGuid == group.Key.ParentGuid)
.Select(c => new Child{ Guid = c.ChildGuid, Name = c.ChildName })
.ToList()
});
A: You need to tackle with recursivity and infinite recursivity if you have a loop from within your flat collection. Linq can't be used for the complete problem but can help returning child of a specific node.
A: This should work, very similar to David B's second example but I couldn't get his to work without a bit of fixing (grouping by multiple column) so I've added it here for the record.
from row in myFlattenedHierarchy
group row by new { row.ParentGuid, row.ParentName } into g
select new Parent()
{
Guid = g.Key.ParentGuid,
Name = g.Key.ParentName,
Children =
(
from childRow in g
select new Child()
{
Guid = childRow.ChildGuid,
Name = childRow.ChildName
}
).ToList()
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Android How to get First Activity's Handler data into third activity?
I have three activities A,B,and C.
I go from Activity A -> Activity B -> Activity C
Now currently Activity C is displaying and Activity A is bottom on Activity Stack
then I provide some inputs to Activity C through which the another thread send some data to Handler of Activity A.
Now I want to receive that data on my Activity C.
Can any possible solution ?
Should I use intent and if yes then can u give me appropriate guidance ?
Thanks in Advance.
A: If data is for decision purpose only then you can use static or SharedPreference and use handler to notify that the data has come or changed.
A: Pass data through intents as extras. USe .putExtra and just pass from B to C.
A: It sounds like you are trying to pass massages from one to activity to the other. You can use a singleton class to do that. Here is a skeleton you can use
// Singleton Class for message passing
public class Messenger {
private static Messenger instance = new Messenger();
public static Messenger get() {
return instance;
}
private String theMessage_;
// Default Constructor
private Messenger() {
}
// Setter to set the message you want to pass
public void setMessageToBePassed(String myMessage){
theMessage_ = myMessage;
}
// Getter to get the message that is passed to you
public String getMessage(){
return theMessage_;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery mobile - How to dynamically create content on pre-existing pages using XML First time posting here so take it easy with me, lol. I'm currently trying to load content into my "pages" that I have already written the html out for. My jquery script is reading the data in from my xml file content.xml. My first page loads fine, but the pages I'm trying to insert data into it have nothing in them. I've deliberately created each page as a shell to avoid data-url issues.
Here's snippets of my code (lots of repetition so no point in putting it all in):
Jquery:
$(function () {
$.ajax({
type: "GET",
url: "content.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(xml) {
$(xml).find('Phonetic').each(function () {
var a = 1;
$test = $("s" +a).append('<div><div class=<div class="S3">' +
$(this).find("S3").text() +
'</div>"S1">' +
$(this).find("S1").text() +
'</div><div class="S2">' +
$(this).find("S2").text() +
'</div><div class="S4">' +
$(this).find("S4").text() +
'</div></div>');
$test.page();
a++;
});
}
Here's the html:
<div data-role="page" id="c1">
<div data-role="header"><h1>Test</h1></div>
<div data-role="content" id="s1"></div>
<div data-role="footer"><h1>Test release v1.0 - Android tablet test</h1></div>
</div>
Any help would be great!
A: I had the same problem and following solution worked for me:
*
*Store your pages into a global array
*change your anchors to look like this: <a href='javascript:change_page(1)' /> where 1 is replaced by the index of your page.
*then define .change_page() method and call jquery.mobile.changePage(arr[index]); to navigate to your dynamically added page.
Regards.
A: i have just one page, the key is to have pagebeforechange in your document ready or ondeviceready function.
$(document).bind("pagebeforecreate",function( e, data ){
if ( typeof data.toPage === 'string' ){
var p = $.mobile.path.parseUrl( data.toPage );
if( u.hash.search( new RegExp( /^MyPageName/ ) ) !== -1 ) {
$.mobile.showPageLoading();
MyCodeToExecForThisPage( p, data.options );
e.preventDefault(); // tell jquery i will create a page not him
}
}
});
so thats your way in, you now need a function to process the page and show the html, here is what i do:
function SetPagesTemplate( ){
$page = $("#AllPage"); // this is the name of my page in the index file
$header = $page.children( "#AllHead" ); // my header so i can custom change
$content = $page.children( ":jqmData(role=content)" ); // the content area of page
$header.html( 'custom graphic or text' );
$content.html(''); // clear everything up
$footer = $page.children( "#allFoot" ); // hook into my footer bar
$footer.html( 'custom footer nav and links' );
}
below is code to show when navigating to a page that nees a value for example #person?personid=22 my page is person and i will be taking the id [ personid ] and getting the correct info, i will then populate my ALLPAGES page with the content and make jquery think i am actually on #person.
// take note here that i take in urlObj [ this was p ] and options
function LoadPerson( urlObj, options ) {
try{
// lets get the number sent by stripping everything out
var id = urlObj.hash.replace( /.*personid=/,"" ),
extra = "";
SetPagesTemplate( ); // the code that sets the page so i dont have to repeat myself.
$.ajax({
url: "http:\/\/" + domain + "/Ajax/MobilePersonProfile",
type: "POST",
dataType: "json",
data: { id: id },
crossDomain: true,
success: function ( data ) {
//loop through data create rows
if( data.length === 0 ){ ThrowCustomAlert( 'Sorry, unable to load profile.', 'no profile available', true ); }
else {
// now deal with your data on this example your processed data would be called template
// all this page stuff was set up earlier so lets fill it
$content.append("<section><nav id='profilescroll'>" + extra + template + "</nav></section>" );
$page.page(); // make our page into a page
options.dataUrl = urlObj.href;
template = null;
data = null;
// above cleanup, on mobile device to keep memory leaks low
// now we navigate to our created page THIS
$.mobile.changePage( $page, options );
StartScroller( "profilescroll" );
HideLoading(); // lets hide the page loading
}
},
error: function ( jqXHR, textStatus, errorThrown ) { CustomError(errorThrown,'',"Profile",true); }
});
}
catch( ee ){ CustomError( ee.message, ee.description, "profile", true ); }
}
thats all you need, its all i ever use, i dont think i have seen examples like this i have had to basically turn my entire app into this way of working to reduce the memory usage on iphone 2 when using as a phonegap app, and it is very very very quick with full ajax navigation.
points to note is that you only need hashtag navigation, in your pagebeforecreate set up a new if for every page you want. w
well hope it helps
as requested here is the html for my page:
<div data-role="page" id="AllPage" class="body" style="overflow:hidden;">
<header class="bar" id="AllHead"></header>
<div data-role="content" class="content" id="home"></div><!-- /content -->
<footer class="bar" id="allFoot"></footer>
</div><!-- /page -->
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What's more difficult to reverse engineering: Application or jar containing Applet? What's more difficult to reverse engineering: Application or jar containing Applet?
I know it's easy to reach the source code of a java application but is that possible for a
jar containing applet like this one in this html?
<HTML>
<HEAD>
</HEAD>
<BODY>
<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
<applet code = 'poster'
archive = 'poster.jar',
width = 100%,
height = 700/>
</P>
<HR WIDTH="100%">
</BODY>
</HTML>
A: There is no difference, you can download poster.jar, by pointing your browser to the URL of the web page, without the final file name and adding poster.jar to it.
Alternatively, you can use firebug, go in the Net view, find poster.jar, right click on it and choose "Copy Location", then paste it in a new tab.
Once downloaded you can examine it.
A: In the end, an applet referencing a jar file will download that jar, furthermore, the jar in the applet will be public, so it will be possible to download it by pointing at its URL.
If you want to difficult reverse-engineering of your java packages, you can always use bytecode obfuscation. There are several tools out there (i.e. ProGuard).
A: The relative "difficulty" doesn't depend on what is the underlying application (in the case of Java, of course) but whether some sort of code obfuscation technique was applied.
A:
I know it's easy to reach the source code of a java application
No it isn't, unless you post it on the Internet.
If you are referring to JAR files, all JAR files can be decompiled, although you can make it harder via obfuscation. Application or applet makes no difference to that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Google API 2 legged Oauth : "Token invalid - Invalid AuthSub token." I've based my code on http://gdatatips.blogspot.com/2008/11/2-legged-oauth-in-php.html.
Here's my code, I want to work with the Google Doc (Document List) API :
$endpoint = 'https://www.google.com/accounts/OAuthGetRequestToken';
$consumer = new OAuthConsumer(GOOGLE_API_DOCLIST_CONSUMER_KEY, GOOGLE_API_DOCLIST_CONSUMER_SECRET, NULL);
$arrParams = array(
'scope' => 'https://docs.google.com/feeds/'
,'xoauth_requestor_id' => GOOGLE_API_DOCLIST_USER_EMAIL
);
$req = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $endpoint, $arrParams);
$req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, null);
$curl = new Auth_Curl();
$content = $curl->request($req->to_url());
$docAPI = new GoogleAPI_DocumentList(new Auth_Curl(), $req->to_header());
var_dump($req->to_header());
echo '<br />-- Getting Collections list';
$url = 'https://docs.google.com/feeds/default/private/full/-/folder' . '?xoauth_requestor_id=' . GOOGLE_API_DOCLIST_USER_EMAIL;
$raw = $docAPI->getCollectionList($url);
var_dump($raw);
die();
I constantly get:
Token invalid - Invalid AuthSub token.
What am I doing wrong ?
Edit:
Here's some "hints":
*
*They seem to mix the API endpoint and the base feed. I've put the OAuthGetRequestToken for the endpoint. It seem to generate a valid response.
*I've kept it, but I'm not sure that the xoauth_requestor_id is required.
*The documentation tells us to use space to separate the parameters in the Authorization header. the library use comma.
A: Here's the corrected code:
$endpoint = 'https://docs.google.com/feeds/default/private/full/-/folder';
$consumer = new OAuthConsumer(GOOGLE_API_DOCLIST_CONSUMER_KEY, GOOGLE_API_DOCLIST_CONSUMER_SECRET, NULL);
$arrParams = array(
'xoauth_requestor_id' => GOOGLE_API_DOCLIST_USER_EMAIL
);
$req = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $endpoint, $arrParams);
$req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, null);
$docAPI = new GoogleAPI_DocumentList(new Auth_Curl(), $req->to_header());
var_dump($req->to_header());
echo '<br />-- Getting Collections list';
$url = 'https://docs.google.com/feeds/default/private/full/-/folder' . '?xoauth_requestor_id=' . GOOGLE_API_DOCLIST_USER_EMAIL;
$raw = $docAPI->getCollectionList($url);
var_dump($raw);
die();
*
*The API and EndPoint were not mixed. On OAuth v1.0, you don't ask the server to generate a token to be used in the authorization header, the authorization header is generated 100% locally. ( I think the URL is used at some point to render the authorization header )
*As you don't generate an access_token, you don't need to define a scope.
*Make sure you have a business account
*
*Only business account allow you to activate 2 legged Authentication.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: newb Qu, themerolling jQuery UI - how to get border thickness and background fade I'm using jQuery UI which seems great but I'm trying to customise it with it's themeroller app. http://jqueryui.com/themeroller/ I'm using a dialog to popup a modal window
I can see that I can control the color of borders but I can't see how I'm meant to change the thickness of them. For example in the content section (the above link and look right) you can change color but not thickness.
Also when the modal window appears I'd like the background to fade to the overlayed color rather than just flick to it. Is there somewhere I can control this?
cheers :)
A: Themeroller can't do that for you. You will have to add this yourself to your CSS file. For example, if you want the thickness of the dialog border to be 3px, add
.ui-dialog { border-width: 3px }
If you want to modify all widgets' border thickness, then do
.ui-widget-content { border-width: 3px }
To make dialog fade in instead of just appearing, you will have to modify your JavaScript code that creates a dialog. Since 'show' and 'hide' only affect the dialog itself (not the overlay) you will have to fade overlay manually:
$('<div/>').dialog({
show: 'fade',
hide: 'fade',
modal: true,
open: function( e, ui ) {
$('.ui-widget-overlay').hide().fadeIn()
}
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Programatically intercept and/or manipulate check-in comments in TFS / Visual Studio 2010 is there a way to intercept a check-in comment during check-in operation on Team Foundation Server Version Control in order to enrich it with additional information?
Another option would be to intercept it and ensure that it's formatted correctly and contain some mandatory information.
We have some policy regarding formatting comments and I would like to add some prevention / user assistance functionality at that point.
The worst case would be a shortcut to fill out the comment field in Visual Studio from some predefined template.
Thanks in advance.
A: What you need here is a custom check-in policy. Power Tools has some policies out of the box, however they do not cover your needs. The closest one requires users to provide a meaningful comment for their check-ins, which is not what you are looking for.
Still there is a way to implement policy on your own. Here is the blog post on MSDN written by Jim Lamb. He explains how one can implement custom check-in policy, package it and deploy on TFS 2010.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: if the user checks remember me on the asp login control, when will the user have to login again? just trying to get a better understanding of the concepts involved with this so i can make better decisions on implementing the login based on the requirements i've been given.
in the case where the user checks the remember me box,
how long does the asp login control's "remember me" remember for?
A: The default is set to 50 years.
From the MSDN page:
When the RememberMeSet property is true, the authentication cookie sent to the user's computer is set to expire in 50 years, making it a persistent cookie that will be used when the user next visits the Web site. Because the authentication cookie will be present on the user's computer, the user will be considered already authenticated and will not have to log in to the Web site again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to correctly merge 2 branches I have a master-branch called trunk and a branch of it called prototype has been created.
Since the branch happened, commits have been done in both trunk and prototype (sometimes even the same files).
What's the best way to update the prototype so that it contains all new commits from the trunk without losing the prototype-commits?
I just tried to rightclick on my projectfolder -> Team -> Merge, selected the trunk as From: and my prototype as To:. I also checked both Merge from HEAD revision.
But after this some new files of prototype were missing.
A: First of all, the merge must be done on the working copy of the prototype branch.
A merge consists in applying a diff between two versions of some branch to another branch. The From and the To must thus both point to the trunk. You want to apply, on the prototype branch, the changes made on trunk, from revision X to revision Y.
This is very well explained in the SVN book.
A: You should first update your branch to get the changes since you have branched
(this is easier if you do this frequently). How to achive this is answered here. In short: you do not specify the different subtrees of the repositories but a range of revisions, so the addresses of from and to are most times the same.
After the branch is working correctly with all new files from the trunk you should commit the branch and then merge the changes back to the trunk with the same mechanism. When the branch is closed after the integration into the trunk you should use "reintegrate a branch", but this will make the branch read only.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hierarchy for developing several unrelated util packages I developed a Java library and the package is called com.rachum.amir.util.permutation. I also have a github repo called Permutations, and an Eclipse project. Now I want to add some more stuff to my library, e.g., I want to develop a com.rachum.amir.util.range package. My question is how to arrange the repositories/directory structure. Should I create a new Eclipse util project (or actually rename the current Permutation one), and create new projects within 'util`'s directories, or should I create a different, unrelated projects with just shared package names? Is it accustomed to create different git repositories for each sub-package or just one big one, or both?
Edit: Another conundrum is how to name the big package. util seems to be too general.
A: In general, you should have one repository for each element that will be released.
So, if your permutation package will be released independently from range, then have range be it's own repository. On the flip-side, if they will always be released together, then you should probably have a single util repository and have them both in there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Calculate Dates I have a monthly report that i run manually currently. So, the report runs from the previous month of 27th to the current month of 26th.
For Example i'm manually using the following:
declare @StartDate datetime = '08/27/2011 00:00:00'
declare @EndDate datetime = '09/26/2011 23:59:59'
for the next month Its going to be:
declare @StartDate datetime = '09/27/2011 00:00:00'
declare @EndDate datetime = '10/26/2011 23:59:59'
I wanted to get the above results automatically. Please help.
Thanks.
A: Use
declare @EndDate datetime = DATEADD(month,1,@StartDate)
Then update your query to use
where [TheDate] >= @StartDate and [TheDate] < @EndDate
By using a less than operator, you won't need to worry about the time portion.
A: This should work:
declare @DayOfMonth tinyint set @DayOfMonth = 27
declare @Month tinyint set @Month = DATEPART(month, getDate())
declare @Year int set @Year = DATEPART(year, getDate())
declare @calcDate datetime
declare @startDate datetime
declare @endDate datetime
select @calcDate =
DATEADD(day, @DayOfMonth - 1,
DATEADD(month, @Month - 1,
DATEADD(Year, @Year-1900, 0)))
select @startDate = DATEADD(month, -1, @calcDate)
select @endDate = DATEADD(SECOND, -1, @calcDate)
select @startDate
select @endDate
A: 27th of last month:
DATEADD(month,DATEDIFF(month,'20110201',CURRENT_TIMESTAMP),'20110127')
26th of this month:
DATEADD(month,DATEDIFF(month,'20110101',CURRENT_TIMESTAMP),'20110126')
Rather than trying to set the time portion to the last possible moment on the 26th, it would be far better to use a less than < comparison, rather than <= or between. Then, you just need the 27th of this month:
DATEADD(month,DATEDIFF(month,'20110101',CURRENT_TIMESTAMP),'20110127')
If you want something based on a particular "base date" (rather than "this month"), then substitute that date value where I'm using CURRENT_TIMESTAMP. You always leave the date literals (e.g. '20110101') as they are.
All of the above calculations work in the same way - the inner DATEDIFF computes the number of month transitions that have occurred since some arbitrary date; we then add that same number of month transitions to a second date - not quite as arbitrary - that exhibits the final "offset" that we want to achieve (e.g. in the first one, the "arbitrary date" is 1st Feb 2011. The second date is 27th Jan 2011 - the 27th of the month before).
A: Declare @ReportStartDay int = 27;
declare @CurrentDay int;
declare @dateDiff int = 0;
set @CurrentDay = DAY(DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())))
set @dateDiff = (@CurrentDay - @ReportStartDay) *-1;
Declare @ReportStartDate datetime = DATEADD(mm, -1, DATEADD(dd, @datediff, DATEDIFF(dd, 0, GETDATE())))
Declare @ReportEndDate datetime = DATEADD(dd, @dateDiff - 1, DATEDIFF(dd, 0, GETDATE()))
select @ReportStartDate as 'Start Date', @ReportEndDate as 'End Date'
I have a feeling there is a better way to do this though...
A: Create the dates like this:
declare @StartDate datetime
declare @EndDate datetime
set @EndDate = convert(datetime, cast(year(getdate()) as varchar) + '/' + cast(month(getdate()) as varchar) + '/' + '27', 101)
set @StartDate = dateadd(m, -1, @EndDate)
And then use them like this:
select ....
from ...
where MyDate >= @StartDate and MyDate < @EndDate
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I save different-2 instance of an Activity in Android? I want to know can I save two or more instance of an Activity and can use those instances as per my requirements.
For example I have two Activities say A & B.
I go from Activity A to B by checking some condition.
if condition meets first instance of Activity B should be started else another one.
For example- In Activity B I have a form which has some EditTexts,some CheckBOxes & form has two Buttons Save & Cancel.
If user presses Save Button so it goes to Activity A & send all form's data which user filled to Activity A. Activity A displays all data filled by user.
But when user again goes to Activity B so he should see all the fields which user previously saved.
After again coming to Activity B user modifies data or fills other fields and instead of saving he presses Cancel Button goes to Activity A without sending any data.
so Activity A shows only previously saved data not modified or extra ones.
But when I again goes to B so I should only see data which user saved first time.
I think I can do this by using SharedPrefernces.
But I want to know can I save two or more instances of Activity B so on condition basis I can use required one.
A: You can't really save an instance of the Activity in the method you mention. You are correct in your assumption that SharedPreferences is one way you can accomplish your task.
In your example, I would have Activity B always pull its form data from the SharedPreferences. Also, when you hit the Save Button, it would cause the form data to be persisted to the SharedPreferences. Finally, in Activity A, you would show the data from the SharedPreferences whenever it was available.
If you want to know if Activity B was exited via Save or Cancel in Activity A, you should start Activity B with startActivityForResult. Then, in Activity B, call setResult in the onClick handler for your Save or Cancel button. Finally, Activity A will get this result in onActivityResult.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML scraping with hpricot using Ruby 1.8.7 vs 1.9.2 Relevant snippet from test.html:
<div id="seat_31F_vacant" class="seatVacant" onclick="UpdateHost(this);Common.DoPostBack('lbtPostBack','31F');" onmouseover="Seat_onMouseOver(this)" onmouseout="Seat_onMouseOut(this)">F</div>
Now consider this ruby code:
doc = Hpricot(test.html)
doc.search("//div[@class='seats']").each do |seat|
@vacant_seat += seat.to_s.scan(/id="seat_(.*)_vacant/)
end
@log.info @vacant_seat.to_s
When logging @vacant_seat.to_s this is what I end up with:
[["31F"], ["31E"], ["31D"], ["31C"]] (Using 1.9.2)
31F31E31D31C (Using 1.8.7)
that means if I do @vacant_seat[0].to_s I'll get:
["31F"] (1.9.2) and 31F (1.8.7)
I want to end up with 31F (as I do with 1.8.7)
Any thougts? Is there a generic way to do this that will work in both Ruby versions? I need to extract the string (eg. 31F) which is located between the underscore characters (_) in the ID attributes. If there is a better way to do this I would appreciate to hear about it.
A: Ruby 1.9.2 changed to_s for Arrays. It used to concatenate all of the elements and print them like 31F31E31D31C.
Now it adds fancy formatting to make it look like an array, so you see the brackets on the arrays, and quotes to the string elements inside of them, so you get [["31F"], ["31E"], ["31D"], ["31C"]].
It looks like @vacant_seat is an array of arrays, so that's why @vacant_seat[0].to_s gives you ["31F"].
If you just need the array that has the elements, then it's the same array in both, just being printed differently.
Now, you can use join to call what was to_s in 1.8.7. @vacant_seat.join #=> 31F31E31D31C or @vacant_seat[0].join #=> 31F, will give you what you're looking for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sign JAX-WS SOAP request I would like to write a JAX-WS web service that signs my SOAP messages using the http://www.w3.org/TR/xmldsig-core/ recommendation.
With what I found on the internet I wrote a JAX-WS handler (SOAPHandler<SOAPMessageContext>) that manages to change a copy of the SOAP request:
@Override
public boolean handleMessage(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
SOAPMessage message = smc.getMessage();
if (outboundProperty) {
try {
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
Source source = soapPart.getContent();
Node root = null;
Document doc22 = null;
if (source instanceof DOMSource) {
root = ((DOMSource) source).getNode();
} else if (source instanceof SAXSource) {
InputSource inSource = ((SAXSource) source).getInputSource();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = null;
db = dbf.newDocumentBuilder();
doc22 = db.parse(inSource);
root = (Node) doc22.getDocumentElement();
}
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null),
Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
null, null);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null),
fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
Collections.singletonList(ref));
// Load the KeyStore and get the signing key and certificate.
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("client_keystore.jks"), "changeit".toCharArray());
KeyStore.PrivateKeyEntry keyEntry =
(KeyStore.PrivateKeyEntry) ks.getEntry("client", new KeyStore.PasswordProtection("changeit".toCharArray()));
X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif2 = fac.getKeyInfoFactory();
List x509Content = new ArrayList();
x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif2.newX509Data(x509Content);
KeyInfo ki = kif2.newKeyInfo(Collections.singletonList(xd));
Element header = getFirstChildElement(root/*.getDocumentElement()*/);
DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), header /*doc.getDocumentElement()*/);
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);
//TODO: change this to update the SOAP message, not write it to disks
OutputStream os = new FileOutputStream("out.xml");
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(root), new StreamResult(os));
} catch (Exception ex) {
System.out.println(ex);
}
}
return true;
}
But I can't figure out how to update the SOAP request?
A: I develop a SOAPHandler for Xml Digital Signature of Soap Request.
public class SOAPSecurityHandler implements
LogicalHandler<LogicalMessageContext> {
static final String KEYSTORE_FILE = "keystore_name.jks";
static final String KEYSTORE_INSTANCE = "JKS";
static final String KEYSTORE_PWD = "123456";
static final String KEYSTORE_ALIAS = "keystore";
public Set<QName> getHeaders() {
return Collections.emptySet();
}
@Override
public boolean handleMessage(LogicalMessageContext smc) {
Boolean outboundProperty = (Boolean) smc
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
try {
if (outboundProperty) {
Source source = smc.getMessage().getPayload();
Node root = null;
root = ((DOMSource) source).getNode();
XMLSignatureFactory fac = XMLSignatureFactory
.getInstance("DOM");
Reference ref = fac.newReference("", fac.newDigestMethod(
DigestMethod.SHA1, null), Collections.singletonList(fac
.newTransform(Transform.ENVELOPED,
(TransformParameterSpec) null)), null, null);
SignedInfo si = fac.newSignedInfo(fac
.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null), fac
.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
Collections.singletonList(ref));
// Load the KeyStore and get the signing key and certificate.
KeyStore ks = KeyStore.getInstance(KEYSTORE_INSTANCE);
ks.load(new FileInputStream(KEYSTORE_FILE),
KEYSTORE_PWD.toCharArray());
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks
.getEntry(
KEYSTORE_ALIAS,
new KeyStore.PasswordProtection(KEYSTORE_PWD
.toCharArray()));
X509Certificate cert = (X509Certificate) keyEntry
.getCertificate();
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif2 = fac.getKeyInfoFactory();
List x509Content = new ArrayList();
x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif2.newX509Data(x509Content);
KeyInfo ki = kif2.newKeyInfo(Collections.singletonList(xd));
Element header = DOMUtils.getFirstChildElement(root);
DOMSignContext dsc = new DOMSignContext(
keyEntry.getPrivateKey(), header);
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
public boolean handleFault(SOAPMessageContext smc) {
// addDigitalSignature(smc);
return true;
}
// nothing to clean up
public void close(MessageContext messageContext) {
}
@Override
public boolean handleFault(LogicalMessageContext arg0) {
// TODO Auto-generated method stub
return false;
}
}
I think the problem in code of @AndrewBourgeois is the way of get Source.
Regards,
A: The simplest way is to use functionality integrated in application server. For example :Securing JAX-WS Web services using message-level security with WebSphere App Server
How to configure signing on WAS you can find here.
And here is WebLogic documentation about Configuring Message-Level Security.
A: You can try soapPart.saveChanges();
A: After the code line:
signature.sign(dsc);
insert this statement:
soapMsg.saveChanges();
It will save your changes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: PHP PDO extension not available is command line I've moved from WAMP to EasyPHP and now there are problems using PDO.
PDO works fine when I view the site in the browser, but doesn't work in cmd or when I run the test file via Netbeans.
I get:
"PDOException: could not find driver"
In phpinfo() for Configure Command I have
cscript /nologo configure.js " --enable-snapshot-build" " --disable-isapi" " --enable-debug-pack" " --disable-isapi" " --without-mssql" " --without-pdo-mssql" " --without-pi3web" " --with-pdo-oci=D:\php-sdk\oracle\instantclient10\sdk, shared" " --with-oci8=D:\php-sdk\oracle\instantclient10\sdk, shared" " --with-oci8-11g=D:\php-sdk\oracle\instantclient11\sdk, shared" " --enable-object-out-dir=../obj/" " --enable-com-dotnet" " --with-mcrypt=static" " --disable-static-analyze"
In php.ini I have already uncommented these lines:
extension=php_pdo_mysql.dll
extension=php_mysql.dll
Any ideas on how I can get this working?
A: When running php from the command line, you can use the -c or --php-ini argument to point to the php.ini file to use. This will allow you to use one php.ini file for both. You can also alias php to php -c/path/to/php.ini if you are running the script yourself.
A: All web server install should you be in linux or windows usually use 2 different php.ini. One for the CLI (Command line client) and one for APACHE or wathever the server is in easyphp.
I can't help you more than that since i'm on linux and don't use EasyPHP, but look in that direction, maybe a system wide search can help you out?
A: I found the solution to the problem. As Mathieu Dumoulin pointed out, PHP has loads a different .ini for CLI. So what I did was create a php-cli.ini file under php folder and the problem was solved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Python: variables by references (hack) Is there any way (hack) to push Python function (def) to return results by reference even for immutable types?
A proposal application (swap as subroutine):
def swap(a, b):
.....a,b = b,a
Note:
def swap(a, b):
.....return b,a
works as function which is not the answer of the question!
For example there is a function random.shuffle(a) that works in-place.
My idea is to call a function written in Fortran/C++ and call them via Python. It does work but has disadvantages too.
note:
Both "lambda" and "def" (as function) have the following problem: a, b = swap(a, b) which requires care about order of variables. In my proposal (if it was possible) the subroutine is used as: swap(a, b) so there is no requirement to care about order of variable.
A: All names in Python are references. And no, there are no "out" references (e.g. in a C++ sense) available. You need to pass a mutable object and then you can mutate it in the function. But then again, returning new value(s) should be the preferred way.
A: No, such things don't exist, because you get the given object as a reference, but if you re-assign it, it won't be changed back.
You either have to work with a mutable container (list, dict, object with attributes) in this case.
A: In python there is no way to pass a "write pointer". You can pass an object and a name (so the callee can use for example setattr) or you can pass a list and an index. There is no such a thing as a context free "address of a modifiable cell"... there are only names or indexes that however also need a context (which namespace, which array).
In the general case if you really need to pass a write pointer a solution in Python is to pass a "setter" function that can be used by the callee to set the value.
For example:
def foo(setter):
setter(42)
def bar():
x = [1,2,3,4]
def setFirst(value):
x[0] = value
foo(setFirst)
print x[0] # --> 42
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Linter reporting missing tags for OG proto - tags there - xml namespaces there - possibly bad admin The linter is reporting missing properties for the title, url, and type even though they're there.
See this linted url for an example
We're also getting behavior like this thread, where the like buttons loses it's count after a refresh, which is probably due to the bad admin field. It will be removed on the next deploy.
But I don't know why it's saying the url, title, and type are missing.
A: This is an artifact of how the object debugger works. The admin field error was an exception in the parser, so it didn't get to look at your other tags. When you fix that one error it will be able to see the rest of your data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error when trying to select all items in listbox on button click event Error :
Unable to cast object of type 'System.String' to type 'System.Windows.Forms.ListBox'.
private void button3_Click(object sender, EventArgs e)
{
foreach (ListBox item in SelectTables_Listbox.Items)
{
item.SelectedItem = true;
}
MessageBox.Show(" All tables Selected ");
}
A: The items in SelectedTables.Items are not ListBoxes. In your case, each item is a string. The easiest method for selecting all elements would be something like this:
for(int i = 0; i < SelectTables.Items.Count; i++)
{
SelectTables.SetSelected(i, true);
}
A: Aren't you trying to cast list box items into a ListBox ???
foreach (ListBox item in SelectTables.Items)
I am not sure what the type should be, but not ListBox
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Handling OnError events in a class library I am writing a class library that wraps different objects
(mostly device drivers for USB hardware components)
Some classes of these device drivers expose an event of kind "OnError": in short if a runtime error or other error occured in the device driver then the event is fired. Something like:
AddHandler oDevice.DriverRunTimeErrorEvent,
AddressOf HandleDriverRunTimeErrorEvent
Private Sub HandleDriverRunTimeErrorEvent(
ByVal sender As Object,
ByVal eventData As DriverRunTimeErrorEventArgs)
'handle the error
End Sub
Positive of this solution is that if an error occurs, the program is not stopped, but I will never know what is happened if I do not use the event.
Now, wrapping the device driver in my class library I have to think what I have to pass to the client that will use my class library and if I should do.
*
*I could forward the device driver solution and generate a new event in the class library. Then the client should handle the forwarded event.
*But I could also throw an exception with all error information
*I could simply ignore the error and just log it in a protocol file.
The solution 1. seems to be more robust to me and I would use it, but it is not "near" to the .NET world.
The solution 2. throws an error asynchronously with the program flow: in the client application I would not have any try-catch block that could trap it. In other words the class could throw an error without the client having called any method of the class.
Of course I could trap all the errors at application level, but anyway this introduces some fuzziness in the logic that I would prefer to avoid.
How would you handle these OnError events?
A: Option 3 you should always do, independently of your choice of approach to present the errors to users - of course if it's reasonably achievable, i.e. if you have write access to storage big enough to hold the logs.
Choosing between 1 and 2 depends on the general approach you pick to deliver error information to your users. In the .NET world throwing exceptions is preferred, at least in standard situations, and by standard I mean if your interface is synchronous. If your users are calling a method of your class and wait for you to return a value (or simply finish execution) - then you should throw an exception if something wrong 'enough'
You may need to steer away from throwing exceptions in some cases, one being if the interface you provide to clients is asynchronous. If they call your method and you return immediately, leaving a worker thread in the background - then throwing exceptions is simply not an option and you need to add a similar event-based approach to let your clients subscribe for error information - if they need it! That's something that you need to decide (unless you post more details about the nature of your project) - if you can get away with just logging errors to a file then why bother raising events?
There is another reason why you may need to implement error notifications not based on exceptions. You may still have a synchronous model - clients call you and wait for your operation to complete - and then you can (and you should) use events to notify the caller that the operation could not come to a successful conclusion. But you may have distinction between something going 'wrong enough' and 'mildly wrong'. Consider the following scenario:
The client calls a method, you start an asynchronous operation, but at some point start waiting for it to complete, e.g. with Thread.Join or WaitHandle.WaitOne. When the worker thread eventually finishes you return the result to the user. You may subscribe to an error event from the underlying framework - but you may identify this error as non fatal, so instead of throwing an exception you may decide to continue waiting for the background thread to finish, but notify the user about the error anyway (again - only if you need to, quite often you can get away by simply logging). You can do this either by means of events, or by a return value (or ref/out parameter). The latter is the more mainstream approach - you just return a list of non-fatal errors, that in most cases will be empty, and if the client cares - he'll go over the list.
That's it pretty much, it depends mainly on your class library's interface - is it synchronous or not, if you share more details on that you can get more specific answers.
A: Error events are application logic. I don't see why you'd want to handle these events in a library.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Additional, non-Paperclip attribute ignores when updating model via accepts_nested_attributes_for I have a model, "Update" which has_many "Assets". An Asset has has_attached_file of :asset, using Paperclip.
I can successfully create multiple assets through my update form (using fields_for), but when editing an Update, I can't update an additional, non Paperclip attribute called "sort_order" on the asset. The new values are posted, but the object doesn't seem to be updated.
models/asset.rb
...
belongs_to :update
...
models/update.rb
has_many :assets, :dependent => :destroy
...
accepts_nested_attributes_for :assets, :allow_destroy => true
I am not using attr_accessible on either model.
views/updates/_form.html.erb
<ul class="existing-images">
<%= f.fields_for :assets do |a| %>
<% unless a.object.new_record? %>
<li>
<%= link_to image_tag(a.object.asset.url(:small)), a.object.asset.url(:original) %>
<%= a.check_box :_destroy %>
<%= a.label :_destroy %>
<%= a.text_field :sort_order %>
<%= a.label :sort_order %>
</li>
<% end %>
<% end %>
</ul>
In the a.text_field :sort_order field above, the default sort_order for the asset appears, but cannot be updated.
New values entered into this field are being sent as per the log:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"2IUei4WR7fRpsM0TKD3Yk8u5FlYv2FDszzjJc3y4eG8=", "update"=>{"year"=>"2011", "week"=>"39", "title"=>"A new piece of work", "content"=>"", "assets_attributes"=>{"3"=>{"_destroy"=>"0", "sort_order"=>"1", "id"=>"1"}, "4"=>{"_destroy"=>"0", **"sort_order"=>"20"**, "id"=>"2"}}, "video_url"=>"", "quote"=>"", "allow_reactions"=>"1", "is_published"=>"1", "allow_public_feed"=>"0"}, "id"=>"1"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Update Load (0.2ms) SELECT "updates".* FROM "updates" WHERE "updates"."id" = ? LIMIT 1 [["id", "1"]]
Asset Load (0.4ms) SELECT "assets".* FROM "assets" WHERE "assets"."update_id" = 1 AND "assets"."id" IN (1, 2) ORDER BY assets.sort_order
(0.1ms) SELECT 1 FROM "updates" WHERE ("updates"."update_type_id" = 1 AND "updates"."id" != 1 AND "updates"."year" = 2011 AND "updates"."week" = 39 AND "updates"."user_id" = 1) LIMIT 1
Update Load (0.1ms) SELECT "updates".* FROM "updates" WHERE "updates"."id" = 1 LIMIT 1
[paperclip] Saving attachments.
("sort_order"=>"20" is the new value) yet the value isn't being saved.
This is also despite the _destroy checkbox working as expected.
Hope that's enough information; if anyone can help I'd be so grateful!!
A: I think you must use attr_accessible in your assets model:
attr_accessible :sort_order
That should solve your problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to display open transactions in MySQL I did some queries without a commit. Then the application was stopped.
How can I display these open transactions and commit or cancel them?
A:
How can I display these open transactions and commit or cancel them?
There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).
You display threads using
SHOW FULL PROCESSLIST
See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html
It will not help you, because you cannot commit a transaction from a broken connection.
What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html
4.5.1.6.3. Disabling mysql Auto-Reconnect
If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.
This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:
Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html
How to diagnose and fix this
To check for auto-reconnection:
If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call mysql_thread_id() to get the original connection identifier before calling mysql_ping(), then call mysql_thread_id() again to see whether the identifier has changed.
Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.
A: Although there won't be any remaining transaction in the case, as @Johan said, you can see the current transaction list in InnoDB with the query below if you want.
SELECT * FROM information_schema.innodb_trx\G
From the document:
The INNODB_TRX table contains information about every transaction (excluding read-only transactions) currently executing inside InnoDB, including whether the transaction is waiting for a lock, when the transaction started, and the SQL statement the transaction is executing, if any.
A: You can use show innodb status (or show engine innodb status for newer versions of mysql) to get a list of all the actions currently pending inside the InnoDB engine. Buried in the wall of output will be the transactions, and what internal process ID they're running under.
You won't be able to force a commit or rollback of those transactions, but you CAN kill the MySQL process running them, which does essentially boil down to a rollback. It kills the processes' connection and causes MySQL to clean up the mess its left.
Here's what you'd want to look for:
------------
TRANSACTIONS
------------
Trx id counter 0 140151
Purge done for trx's n:o < 0 134992 undo n:o < 0 0
History list length 10
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 17004, OS thread id 140621902116624
MySQL thread id 10594, query id 10269885 localhost marc
show innodb status
In this case, there's just one connection to the InnoDB engine right now (my login, running the show query). If that line were an actual connection/stuck transaction you'd want to terminate, you'd then do a kill 10594.
A: By using this query you can see all open transactions.
List All:
SHOW FULL PROCESSLIST
if you want to kill a hang transaction copy transaction id and kill transaction by using this command:
KILL <id> // e.g KILL 16543
A: With this query below, you can check how many transactions are running currently:
mysql> SELECT count(*) FROM information_schema.innodb_trx;
+----------+
| count(*) |
+----------+
| 3 |
+----------+
1 row in set (0.00 sec)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "112"
}
|
Q: How to handle plugin settings over TCP I have an application which consists of two parts. A server and a client. The two communicate via TCP sockets.
The server supports plugins which in turn can store settings of various complexity (anything from integers and strings to complex objects).
I would like to build support for editing a plugins settings in the client UI, however this has proven to be hard since I don't really know what kind of data the plugin is storing.
Does anyone have any good ideas on how to do something like this?
-- update
To give an example,
The server has a plugin which monitors different RSS feeds, and acts upon updates. The plugin stores its settings as a list complex objects
class RssItem
{
string Url { get; set; }
int PollInterval { get; set; }
}
However, the server does not know about this. It just stores the serialized object.
Now I'm interested in ways to have the client application show a form where a user can edit this list of RssItem. Any solution I can think of involves heavy reflection on a serialized object.
An application I know does something like this is the Deluge torrent client. It's written in Python and manages server side plugins, but through some Twisted Deferred objects hux flux magic the plugins can have a custom settings page in the client UI.
A: With smart configuration objects you can create dynamic forms on client side. For example use ExtJS on client and server will send you the JSON with form structure.
This is not a solution but this is what you have to consider.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Load custom configuration file in WCF relative to Working Directory I have a WCF service library that reads a xml file that's located in the WCF publish location. The project is not client profile.
When I debug in the WCF test client it works fine with:
XDocument xDoc = XDocument.Load(@".\PaymentAvailability.xml");
But when consuming the service from a website it says it cannot find PaymentAvailability.xml ... it looks like its trying to get the location of the xml file from the consuming app.
I've tried the answers posted here but no luck How to get working path of a wcf application?
System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath returns null
With AspNetCompatability HttpContext.Current.Server.MapPath("."); also doesn't return anything
A: This is a really bad practice, you should place the configuration for your library in the .config file for the application that is using your library, using custom section handlers (which the Configuration Section Designer does very well for you) if you want strongly typed XML configuration.
The reasoning being that it's your application that you are configuring; if your library really operated so independently of your application, then you should reconsider whether or not the library should not be it's own application.
One option that you have to mitigate this to create a custom config section handler and then use the configSource attribute. While you won't be able to use one single file (the attribute does not allow for absolute paths), you can copy the one file into the bin directory of each application.
Note that you'll have to explicitly get the config section, but you have to do that anyway now to load your file, but at least you'll be more in line with the configuration manager.
A: In general
System.Reflection.Assembly.GetExecutingAssembly().Location
gives you the phyisical path of the executing assembly.
On the msdn page you can see the difference between GetExecutingAssembly, GetEntryAssembly and GetCallingAssembly.
That said, it may not be a good idea anyways (see casperOne's answer).
A: This works, but from the other answers, I'm going to see if this is indeed a bad practice and can be done a better way.
ServiceHostBase hostBase = OperationContext.Current.Host;
VirtualPathExtension virtualPathExtension = hostBase.Extensions.
Find<VirtualPathExtension>();
XDocument xDoc;
if (virtualPathExtension != null)
{
/// It’s hosted.
xDoc = XDocument.Load(Path.Combine(
HostingEnvironment.ApplicationPhysicalPath, AvailabilityFileName));
}
else
{
/// It’s not hosted.
xDoc = XDocument.Load(AvailabilityFileName);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: is there any function in c++ to check whether a file given in a specific path is a script(.sh) file or not there is .sh file in one of the directories
for eg: path = /opt/WD/CD/SCD/temp.sh
is there any function is c++ to check whether file in that location(path) is a script(.sh) file or not
bool ValidCommand(const string & path)
{
bool return = true;
{
if (!access(path.c_str(),X_OK))
{
return = true;
}
else
return = false;
}
path = /opt/WD/CD/SCD/temp.sh
access is not working for me:(
A: Have a look at
*
*stat -- to check the executable bit
*libmagic -- to detect file type from (a.o.) the hash-bang line
A: Maybe stat does what you need, otherwise you can look at the source for file and see how it does it.
A: You can use stat. If it failed (returned -1), the file doesn't exist.
A: Just how precise do you want it. It's fairly straightforward to read
the directory and look for filenames ending in .sh.
(boost::filesystem has everything you need for that.) But of course,
I could name my C++ headers file.sh if I wanted (and was a bit
perverse). A considerably more accurate test would involve reading the
start of the file: if the first two bytes are "#!", it's probably a
script of some sort, and if the first line matches
"#!\\s*(?:/usr)?/bin/sh/[a-z]*sh", then you're almost sure it's a shell
script. Drop the [a-z]*, and it's a Bourne or a Posix shell script.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to configure an Element-collection to map an existing DB table in JPA orm.xml configuration? I have migrated an app from a full-Hibernate featured one to a JPA/Hibernate based-one and I have a problem with my JPA mapping.
We have managed to use orm.xml to map our entities. Everything was working fine until I have had to deal with an Element-collection.
Actually, I have an entity called User which has an embedded map (Map collection called preferences). So we have something like that :
public class User {
private Long id;
private Map<String, String> preferences;
}
In our full-hibernate version, a PREFERENCE(ID, name, value) table gets generated. But when we tried to migrate it to JPA, we used the following mapping :
<element-collection name="preferences" target-class="java.lang.String" fetch="LAZY">
<map-key-class class="java.lang.String" />
<map-key-column name="[name]" />
<column name="[value]" />
<collection-table name="PREFERENCE">
<join-column name="ID" />
</collection-table>
</element-collection>
and a new User_Preferences table gets generated. Even though I have specified a name='PREFERENCES' attribute in the xml configuration, I can't get the element-collection to point to the existing table PREFERENCES.
Have you ever experienced this situation ?
Any help would really be appreciated.
Thanks a lot guyz,
A: Looks like a bug. I cannot point anything wrong with your mappings and I tried it with EclipseLink 2.3.0 and such a mapping created table named PREFERENCE. Also tried with Hibernate 3.5.6, and name of table is USER_PREFERENCES as you said.
Looks like they simply discard name for collection-table. But same with annotations works fine:
@ElementCollection(targetClass = java.lang.String.class)
@MapKeyClass(java.lang.String.class)
@MapKeyColumn(name="name")
@CollectionTable(name = "PREFERENCE", joinColumns = @JoinColumn(name="ID"))
@Column(name="value")
A: Have you tried this structure:
Set<Preference> preferences;
then transform your set to a map computationaly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to DIE all LIVE'S in a dialog when close? I have a dialog $('.dialog'), then a fill with an html of the form when I open it:
$('.dialog').html(getForm());
Then I have a function named close(); When I click close I do:
$('.dialog').html('');
$('.dialog').hide();
BUT, if in the form I put dynamic elements (new DOM), with .live('event',function(){})...
when I open the dialog again I get the live action attached two times, if I close the dialog and open again I get the live action attached three times, etc. (Please UNDERSTAND that I need to use .live() and not .bind())
THE FORM:
<form id="formid">
<input type="text" class="please_only_onetime"/>
<script type="text/javascript">
$(document).ready( function() {
$('.please_only_onetime').live('focusin', function(){ alert( 'one time' );});
});
</script>
</form>
Finally, if I put the following before the .live(), the code works well:
$('.please_only_onetime').die();
BUT, What I want is to generalize this in close() function like:
$('.dialog').find('*').die() // but this seems not to be working!
A: If you're using ".live()", you don't have to re-attach the event handlers. That's the whole point. Just attach them at the start, and then they'll keep working no matter how many times you load and unload the form.
A: $('.dialog').delegate('.please_only_onetime', 'focusin', function () {
//this is all you need to do... no rebinding, no "die"'ing ...
});
Or for simplicity you can keep using live. I think you should make the switch to delegate() though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NHibernate mapping many-to-many lists not loading the objects right I am attempting a many-to-many list in one of my objects.
I have three classes which I am attempting to save and load via NHibernate: Intersection, Vehicle and Zone. Intersection and Vehicle are both derived from Device.
The Intersection class contains a list of Zones, which each zone may only belong to 1 Intersection, but each Intersection may contain multiple Zones. I have this mapped correctly and it is saving the many-to-one association of Zones to the Intersections just fine.
The Vehicle class contains a List of Zones. The Vehicle may belong to multiple Zones. Also, the Zones contain a List of Vehicles. Each Zone may contain multiple Vehicles. Thus the many-to-many relationship between the two.
All the objects appear to be saved to the database correctly. I can go through my tables and all the fields for each Intersection, Vehicle, and Zone are propagated correctly; however, they are not loading the fields when I load the object using NHibernate.
I am hoping someone may be able to shed some light as to what may be going wrong here.
Here is my mapping of Device which includes the Intersection and Vehicle class mappings:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class xmlns="urn:nhibernate-mapping-2.2" name="EMTRAC.Devices.Device, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="`Device`" lazy="false">
<id name="PK" type="System.Int64, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="PK" />
<generator class="identity" />
</id>
<many-to-one class="EMTRAC.Connections.Connection, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="LocalConnection" lazy="false" cascade="all">
<column name="LocalConnection_id" />
</many-to-one>
<many-to-one class="EMTRAC.Connections.Connection, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Connection" lazy="false" cascade="all">
<column name="Connection_id" />
</many-to-one>
<many-to-one class="EMTRAC.Packets.Packet, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Configuration" lazy="false" cascade="all">
<column name="Configuration_id" />
</many-to-one>
<joined-subclass name="EMTRAC.Intersections.Intersection, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" lazy="false">
<key>
<column name="Device_id" />
</key>
<component name="Zones" access="property">
<bag name="_list" cascade="all-delete-orphan" access="field" lazy="false" fetch="join">
<key>
<column name="Zone_PK" />
</key>
<many-to-many class="EMTRAC.Zones.Zone, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</bag>
</component>
<many-to-one class="EMTRAC.Intersections.Streets, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Streets" lazy="false" cascade="all">
<column name="Streets_id" />
</many-to-one>
<many-to-one class="EMTRAC.Positions.Position, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Position" lazy="false" cascade="all">
<column name="Position" />
</many-to-one>
</joined-subclass>
<joined-subclass name="EMTRAC.Vehicles.Vehicle, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<key>
<column name="Device_id" />
</key>
<component name="Zones" access="property">
<bag name="_list" cascade="all-delete-orphan" access="field" lazy="false" table="VehicleZones" inverse="false">
<key>
<column name="Vehicle_PK" />
</key>
<many-to-many class="EMTRAC.Zones.Zone, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</bag>
</component>
<property name="Active" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Active" />
</property>
<property name="Status" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Status" />
</property>
<property name="Velocity" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Velocity" />
</property>
<property name="Heading" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Heading" />
</property>
<property name="Agency" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Agency" />
</property>
<property name="Unit" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Unit" />
</property>
<property name="Priority" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Priority" />
</property>
<many-to-one class="EMTRAC.Positions.Position, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Position" lazy="false" cascade="all">
<column name="Position_id" />
</many-to-one>
<many-to-one class="EMTRAC.VehicleClasses.VehicleClass, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="VehClass" lazy="false" cascade="all">
<column name="VehClass_id" />
</many-to-one>
</joined-subclass>
</class>
</hibernate-mapping>
And here is my mapping of the Zone class:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class xmlns="urn:nhibernate-mapping-2.2" name="EMTRAC.Zones.Zone, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="`Zone`" lazy="false">
<id name="ID" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="PK" />
<generator class="identity" />
</id>
<property name="Active" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Active" />
</property>
<property name="Dir" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Dir" />
</property>
<property name="IntID" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="IntID" />
</property>
<property name="Width" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Width" />
</property>
<property name="Distance" type="System.Double, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Distance" />
</property>
<many-to-one class="EMTRAC.Headings.Heading, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Heading" cascade="all-delete-orphan">
<column name="Heading_id" />
</many-to-one>
<many-to-one class="EMTRAC.Positions.Position, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Start" cascade="all-delete-orphan">
<column name="Start_id" />
</many-to-one>
<many-to-one class="EMTRAC.Positions.Position, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Finish" cascade="all-delete-orphan">
<column name="Finish_id" />
</many-to-one>
<component name="Vehicles" access="property">
<bag name="_list" cascade="all-delete-orphan" access="field" lazy="false" table="ZoneVehicles" fetch="join" inverse="true">
<key>
<column name="Zone_PK" />
</key>
<many-to-many class="EMTRAC.Vehicles.Vehicle, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</bag>
</component>
</class>
</hibernate-mapping>
And finally here are my Vehicle and Zone classes:
public class Vehicle : Device
{
#region Fields
protected bool active;
protected int id;
protected Position position = new Position();
protected int status;
protected VehicleClass vehClass;
protected int velocity;
protected int heading;
protected string agency;
protected string unit;
protected int priority;
private ZoneCollection zones = new ZoneCollection();
#endregion
#region Properties
[Browsable(false)]
public virtual long PK { get; set; }
[Browsable(false)]
public virtual bool Active
{
get { return active; }
set { active = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("Vehicle Identification Number")]
public virtual int ID
{
get { return id; }
set { id = value; }
}
[Browsable(false)]
public virtual Position Position
{
get { return position; }
set { position = value; }
}
[Browsable(false)]
public virtual int Status
{
get { return status; }
set { status = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("This is the type of vehicle.")]
public virtual VehicleClass VehClass
{
get { return vehClass; }
set { vehClass = value; }
}
[Browsable(false)]
public virtual int Velocity
{
get { return velocity; }
set { velocity = value; }
}
[Browsable(false)]
public virtual int Heading
{
get { return heading; }
set { heading = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("This is the name of the city agency that owns the vehicle.")]
public virtual string Agency
{
get { return agency; }
set { agency = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("This is the ID number assigned to the vehicle by the city or agency and is also used for identification purposes. This field accepts both alpha and numeric entries.")]
public virtual string Unit
{
get { return unit; }
set { unit = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("This is the priority level that the vehicle has over other vehicles with priority control capabilities (1 being the highest, 5 being the lowest). This is not the same as the priority control levels assigned to emergency vehicles (priority 1 for EVP) and mass-transit vehicles (priority 2 for TSP).")]
public virtual int Priority
{
get { return priority; }
set { priority = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("Zones associated with the Vehicle.")]
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.Editor(typeof(VehicleCollectionModalEditor), typeof(System.Drawing.Design.UITypeEditor))]
public virtual ZoneCollection Zones
{
get { return zones; }
set { zones = value; }
}
[Browsable(false)]
public virtual string IPLocal
{
get
{
if (LocalConnection.GetType() == typeof(Connections.ConnectionSerial))
{
return (
((Connections.ConnectionSerial)LocalConnection).SerialConn.PortName + " :: " +
((Connections.ConnectionSerial)LocalConnection).SerialConn.BaudRate.ToString()
);
}
else if (LocalConnection.GetType() == typeof(Connections.ConnectionTCP))
{
return (
((IPEndPoint)((Connections.ConnectionTCP)LocalConnection).Client.Client.RemoteEndPoint).Address.ToString() + " :: " +
((IPEndPoint)((Connections.ConnectionTCP)LocalConnection).Client.Client.RemoteEndPoint).Port.ToString()
);
}
else
{
return string.Empty;
}
}
}
[Browsable(false)]
public virtual string IPNetwork
{
get
{
if (Connection.GetType() == typeof(Connections.ConnectionSerial))
{
return (
((Connections.ConnectionSerial)Connection).SerialConn.PortName + " :: " +
((Connections.ConnectionSerial)Connection).SerialConn.BaudRate.ToString()
);
}
else if (Connection.GetType() == typeof(Connections.ConnectionTCP))
{
return (
((IPEndPoint)((Connections.ConnectionTCP)Connection).Client.Client.RemoteEndPoint).Address.ToString() + " :: " +
((IPEndPoint)((Connections.ConnectionTCP)Connection).Client.Client.RemoteEndPoint).Port.ToString()
);
}
else
{
return string.Empty;
}
}
}
#endregion
}
public class Zone
{
#region Private Fields
private bool active;
private string dir;
private Heading heading = new Heading();
private int id;
private int intID;
private Position start = new Position();
private Position finish = new Position();
private int width;
private Position[] corners = new Position[4];
private Streets streets = new Streets();
private VehicleCollection vehicles = new VehicleCollection();
private double distance;
#endregion
#region Constructors
public Zone()
{
if (Program.main != null)
{
IntID = Program.main.intID;
Intersection intersection = Program.data.Intersections.list.Find(
delegate(Intersection tInt)
{
return tInt.ID == IntID;
}
);
if (intersection != null)
{
Streets.Crossing = intersection.Streets.Crossing;
Streets.Route = intersection.Streets.Route;
}
}
}
#endregion
#region Properties
[Browsable(false)]
public virtual long PK { get; set; }
[Browsable(false)]
public virtual bool Active
{
get { return active; }
set { active = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("The direction for the Zone.")]
public virtual string Dir
{
get { return dir; }
set { dir = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("This is the amount of heading variance (clockwise and counter-clockwise) in actual degrees.")]
public virtual Heading Heading
{
get { return heading; }
set { heading = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("The Zone Identification Number.")]
public virtual int ID
{
get { return id; }
set { id = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("The Identification Number associated with the Priority Detector of the Zone.")]
public virtual int IntID
{
get { return intID; }
set { intID = value; }
}
[CategoryAttribute("Position"),
DescriptionAttribute("The location of the Zone's Start.")]
public virtual Position Start
{
get { return start; }
set { start = value; }
}
[CategoryAttribute("Position"),
DescriptionAttribute("The location of the Zone's Finish.")]
public virtual Position Finish
{
get { return finish; }
set { finish = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("The width of the Zone.")]
public virtual int Width
{
get { return width; }
set { width = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("The distance of the Zone.")]
public virtual double Distance
{
get { return distance; }
set { distance = value; }
}
[Browsable(false)]
public virtual Position[] Corners
{
get { return corners; }
set { corners = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("The streets associated with the Zone."),
DisplayName("Zone Streets")]
public virtual Streets Streets
{
get { return streets; }
set { streets = value; }
}
[CategoryAttribute("Configuration"),
DescriptionAttribute("Vehicles associated with the Zone.")]
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.Editor(typeof(VehicleCollectionModalEditor), typeof(System.Drawing.Design.UITypeEditor))]
public virtual VehicleCollection Vehicles
{
get { return vehicles; }
set { vehicles = value; }
}
#endregion
}
I'm sure it is probably something really small I am missing. Any ideas?
A: 1) your many-to-many tables a missing a foreign key definition. The foreign key will be generated by NH, but it must be the same for both sides, so it doesn't work.
eg.
<many-to-many class="EMTRAC.Zones.Zone, EMTRAC_v3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<column name="Zone_PK"/>
</many-to-many>
2) The bags are mapped using fetch="join" which isn't a good idea.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sencha Touch tabPanel using dynamic JSON data In my application the first page shows a tabPanel at the bottom. But number of tabs, their labels and icons are dynamic content coming from a json request. I am wondering how to do it. Here is what i tried.
TMDemo = new Ext.Application({
name: 'TMDemo',
launch: function(){
this.views.mainTabBar = new this.views.MainTabBar();
}
});
TMDemo.views.MainTabBar = Ext.extend(Ext.TabPanel,{
fullscreen: true,
tabBar:{
dock:'bottom',
layout:{
pack:'center'
}
},
addItems: function(){
this.add(addItemsBasedOnJsonData());
this.doLayout(); // important
},
listeners: {
beforerender:function(){
Ext.util.JSONP.request({
url: 'app/data/tabbar.json',
callbackKey: 'callback',
callback: function(result) {
console.log("Inside callback");
TMDemo.tabBarData = result;
}
});
}
render: function(){
console.log("Inside render");
this.addItems();
}
}
});
Here the tabbar data is coming from tabbar.json (dummy data actual will be some URL). I am adding items to this tabpanel through addItemsBasedOnJsonData() function which will create the tab items and returns the array.
But the problem is render event always fire first then the JSON request callback, so no jsondata available to create tabs dynamically.
Please guide me to a right direction. Whether this approach is right. Can i have any example to look for.
Tarun
A: Have you tried this:
callback: function(result) {
console.log("Inside callback");
TMDemo.tabBarData = result;
TMDemo.views.mainTabBar.add(TMDemo.views.mainTabBar.addItemsBasedOnJsonData());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ADO.NET Entity Data Model extension not working I want to develop a Visual Studio extension to add extra properties on entity types. As suggested in the answer to a related question I had asked before, I have installed the ADO.NET Entity Data Model Designer Extension Starter Kit as the first step.
However I can't get it working even if I simply build and install the starter kit project as-is: the extension gets installed and I can see it in the VS extensions manager, but I can't see the extra properties in the entity models I add to my projects.
Things I have tried so far:
*
*Enabling support for VS Ultimate in the extensions.vsixmanifest
properties page (as this is the VS edition I am using).
*In the "Content" pane in the extensions.vsixmanifest properties page,
removing the existing entry (of type "MEF content" and path pointing
to the generated DLL) and adding another one of the same type, but
referencing the project itself instead of the generated DLL.
*Running a standalone VS to test the extension / forcing a new
instance of VS to be open by running the extension project itself
(the extension being previously installed in both cases).
*Adding extra flags to the constructor of the
EntityDesignerExtendedProperty attribute of the
MyNewPropertyFactory class (to include the storage model besides of
the conceptual model).
*Generating a test model from scratch / from an existing database.
Nothing of this works, it is as if the extension was not installed at all. What else can I try out?
(As a side note, if I try to debug the extension the breakpoints I have placed appear as disabled, with a tooltip stating that "no symbols have been loaded", I don't know if this may be related to my problem).
My working environment:
*
*Windows 7 Ultimate 64 bits
*Visual Studio 2010 Ultimate SP1
*Visual Studio 2010 SDK SP1
*Entity Framework 4.1
Thank you!
A: Turns out that it was my fault... I violated the number one rule for diagnosing problems: change only one thing at a time. Arrrrgh... :-(
So the correct configuration starting from the initial state of the starter kit project seems to be: add VS Ultimate support but do not change the "Content" pane (leave the reference to the DLL as the content path).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using Session Scope in Spring Beans I'm using JSF 2 for the view and Spring for the business logic. I'm trying to set a session scope to one of my spring beans using annotations(@Scope("session")), but I'm getting this exception:
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handleFiles': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private creazione.util.FTPOperations creazione.components.HandleOldFiles.operations;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'ftpOperations': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton;
nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread?
If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
I know about RequestContextListener. It's in my web.xml. I've also added RequestContextFilter:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
Nothing seems to work. What am I doing wrong?
Thank you!
A: If you are using annotation based configuration, just change in your main config xml this tag:
<context:component-scan base-package="my.package"/>
to
<context:component-scan base-package="my.package" scoped-proxy="targetClass" />
Also it is possible to mark class for working with proxy via annotations:
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
This work for me.
More details here: 4.12 Classpath scanning, managed components and writing configurations using Java
Also if you're create bean via context xml configuration, here is another example for this case:
<bean id="somebean" class="com.package.beans" scope="session">
<aop:scoped-proxy/>
</bean>
A: Try to define the beans that have to be injected as session with aop:scoped-proxy.
<bean id="ftpOperations" class="..." scope="session">
<aop:scoped-proxy/>
</bean>
Add also the relevant namespace, if it's not present already:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
...
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: $.get not get HTML
A: If js is off, you cannot call $.get or another js function, respectively method doesn't return noscript
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the best way yo keep version on database? I need to develop a web application.
A web shop that sell different product in different package in different region ...
The admin need to modify thoses packages while end users wont be able to see his modifications. end user will be able to see those modifications only when the admin will publish the change.
my question is how can i design the database(or the webapp) so the admin will be able to see a different version (working version) of the application, while the end user will see another version (release version) ?
i was thinking of adding a field 'version_id' on each table.
Any idea? advice? link?
A: I'd store the pre-publish versions in a separate table and then update the "live" table when the admin publishes it.
This way you can keep the number of rows down in the table that's often read (the live table) which will cut down on the overhead - if it's a web shop the live table will be being read whenever someone visits that page.
If you're using MySQL you could also optimise the two tables so that the live version is using MyISAM which is (loosely speaking) better for heavy read operations and have the admin pre-publish table as an InnoDB table; InnoDB is (again loosely speaking) better performing on heavy write operations. That pre-publish table will only be accessed by very few (or even one) users at a time (the admin/s) but it may be updated frequently before publish as they realise they've misspelt something and change it.
If you want to incorporate a full version history you definitely want a separate table as you're going to end up with many more pre-publish versions in the table than live ones.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery .css, how to translate it into Javascript I have the following jQuery code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setTimeout(function() {
$('.green.bar .inner').css('width', '20%')
},1000);
});
</script>
And the html is:
<div class="green bar">
<div class="inner" style="width:10%"></div>
</div>
How can I do what the jQuery code does using just JavaScript?
Thanks a lot
A: If you mean without using jQuery:
// If you only want to operate on the first match
setTimeout(function(){
document.querySelector('.green.bar .inner').style.width = '20%';
});
Or:
// If you want to operate on all matches
setTimeout(function(){
var elements = document.querySelectorAll('.green.bar .inner');
for(e in elements){
elements[e].style.width = '20%';
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it better to use the mapred or the mapreduce package to create a Hadoop Job? To create MapReduce jobs you can either use the old org.apache.hadoop.mapred package or the newer org.apache.hadoop.mapreduce package for Mappers and Reducers, Jobs ... The first one had been marked as deprecated but this got reverted meanwhile. Now I wonder whether it is better to use the old mapred package or the new mapreduce package to create a job and why. Or is it just dependent on whether you need stuff like the MultipleTextOutputFormat which is only available in the old mapred package?
A: Functionality wise there is not much difference between the old (o.a.h.mapred) and the new (o.a.h.mapreduce) API. The only significant difference is that records are pushed to the mapper/reducer in the old API. While the new API supports both pull/push mechanism. You can get more information about the pull mechanism here.
Also, the old API has been un-deprecated since 0.21. You can find more information about the new API here.
As you mentioned some of the classes (like MultipleTextOutputFormat) have not been migrated to the new API, due to this and the above mentioned reason it's better to stick to the old API (although a translation is usually quite simple).
A: Old API (mapred)
*
*Exists in Package org.apache.hadoop.mapred
*Provide A map/reduce job configuration.
*Reduces values for a given key, based on the Iterator
*Package Summary
New API (mapreduce)
*Exists in Package org.apache.hadoop.mapreduce
*Job configuration is done by separate class, Called JobConf which is extension of Configuration
Class
*Reduces values for a given key, based on the Iterable
*Package Summary
A: Both the old and new APIs are good. The new API is cleaner though. Use the new API wherever you can, and use the old one wherever you need specific classes that are not present in the new API (like MultipleTextOutputFormat)
But do take care not to use a mix of the old and new APIs in the same Mapreduce job. That leads to weird problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
}
|
Q: What are the common pitfalls when using Perl's eval? What are the common pitfalls associated with Perl's eval, which might make you choose to use a module such as Try::Tiny?
A: In addition to the answers above, I would add...
*
*eval is affected by the global $SIG{__DIE__} handler causing action at a distance.
*It is easy for a novice to confuse eval BLOCK and eval STRING, since they appear to do the same thing, but one is a security hole.
Try::Tiny has its own pitfalls, the biggest being that while it looks like a block it is actually a subroutine call. That means this:
eval {
...blah blah...
return $foo;
};
and this:
try {
...blah blah...
return $foo;
};
do not do the same thing. These are laid out in the CAVEATS section of the Try::Tiny docs. That said, I'd recommend it over eval.
A: Perl's eval comes in two flavors, string eval and block eval. String eval invokes the compiler to execute source code. Block eval surrounds already compiled code in a wrapper that will catch the die exception. (string eval catches the die exception also, as well as any compilation errors).
Try::Tiny only applies to the block form of eval, but the following applies to both forms.
Every time you call eval it will change the value of $@. It will either be '' if the eval succeeded or the error caught by the eval.
This means that any time you call an eval, you will clear any previous error messages. Try::Tiny localizes the $@ variable for you, so that a successful eval will not clear the message of a previous failed eval.
The other pitfall comes from using $@ as the check to determine if the eval succeeded. A common pattern is:
eval {...};
if ($@) {
# deal with error here
}
This relies on two assumptions, first that any error message $@ could contain is a true value (usually true), and that there is no code between the eval block and the if statement.
Visually of course the latter is true, but if the eval block created an object, and that object went out of scope after the eval failed, then the object's DESTROY method will be called before the if statement. If DESTROY happens to call eval without localizing $@ and it succeeds, then by the time your if statement is run, the $@ variable will be cleared.
The solution to these problems is:
my $return = do {
local $@;
my $ret;
eval {$ret = this_could_fail(); 1} or die "eval failed: $@";
$ret
};
breaking that apart line by line, the local $@ creates a new $@ for the do block which prevents clobbering previous values. my $ret will be the return value of the evaluated code. In the eval block, $ret is assigned to, and then the block returns 1. That way, no matter what, if the eval succeeds it will return true, and if it fails it will return false. It is up to you what to do in the case of failure. The code above just dies, but you could easily use the return value of the eval block to decide to run other code.
Since the above incantation is a bit tedious, it becomes error prone. Using a module like Try::Tiny insulates you from those potential errors, at the cost of a few more function calls per eval. It is important to know how to use eval properly, because Try::Tiny is not going to help you if you have to use a string eval.
A: The issues are explained in the Try::Tiny documentation. Briefly, they are:
*
*Clobbering $@
*Localizing $@ silently masks errors
*$@ might not be a true value
A: Using eval on X11 function might still failed to keep alive.
The code is like
eval {
@win_arrays = GetWindowsFromPid($pid);
};
The script will be exited from
X Error of failed request: ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Lost Session When Moving From Http to Https I am having an issue where moving from http://mysite.com to https://secure.mysite.com causes the user to lose their session information. What would be the best way to deal with this? Thanks
A: I think you can use the SQL Server to keep your Session.
This will be helpful
Configure SQL Server to Store ASP.NET Session State
A: The session is being lost because the url is changing from mysite.com to secure.mysite.com Is it possible to keep the url the same and just use the secure https protocol?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding jQuery to Magento What is the recommended way to add jQuery (or any script) BEFORE the rest of the scripts that come with Magento using local.xml?
I've tried to use (in local.xml):
<reference name="head">
<action method="addItem">
<type>skin_js</type>
<script>js/jquery-1.6.4.js</script>
</action>
</reference>
but this ends up adding jQuery to the end of the scripts that are added by Magento in page.xml in the base package. I've even tried removing all the scripts using:
<action method="removeItem">
...
</action>
to remove all of the scripts that were added in page.xml and then re-adding them in local.xml in the order I need them to be in (jQuery first), but somehow, they are ending up in the same order (with jQuery last).
I've stepped through the Magento code and verified that the scripts are getting removed and then re-added to $this->_data['items'] in Mage_Page_Block_Html_Head, but at some point, when they get added to the page, they are added with jQuery last.
I'm guessing there has to be a more elegant way to do this, but I've yet to find it in my Googling. Everything I've found recommends modifying page.xml directly, which I've read elsewhere is not a good idea.
A: My preferred (and the most flexible way) to do this is through XML using local.xml, two separate Javascript files, and a new file we will create. The first Javascript file is jQuery itself--completely unmodified. The second file I call no-conflict.js and it contains only one line:
jQuery.noConflict();
Now we add both of these files, along with a new block, to the head section of our local.xml:
<reference name="head">
<block type="page/html_head" name="topScripts" template="page/html/top_scripts.phtml" before="head">
<action method="addItem">
<type>skin_js</type>
<name>js/jquery-1.7.2.min.js</name>
</action>
<action method="addItem">
<type>skin_js</type>
<name>js/no-conflict.js</name>
</action>
</block>
</reference>
no-conflict.js is necessary to allow jQuery to work alongside Prototype, the Javascript framework included in Magento by default. Keeping jQuery and a no-conflict file separated allows you to upgrade or downgrade jQuery as needed without the need to edit the jQuery file itself to include the noConflict() method.
In our XML we created a new block (topScripts) with the template file set to top_scripts.phtml.
Navigate to /app/design/frontend/PACKAGE_NAME/TEMPLATE_NAME/template/page/html/ and create this new file. It will contain one line:
<?php echo $this->getCssJsHtml(); ?>
Now edit /app/design/frontend/PACKAGE_NAME/TEMPLATE_NAME/template/page/html/head.phtml.
Find the line <?php echo $this->getCssJsHtml() ?> in your head.phtml and add this line directly above it:
<?php echo $this->getChildHtml('topScripts') ?>
You have now correctly added jQuery before any other Magento Javascript.
A: Best is to use the content delivery network which will be better in performance/speed for your website.
I mostly just open up template/page/html/head.phtml and right before
<?php echo $this->getCssJsHtml() ?>
<?php echo $this->getChildHtml() ?>
I add:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
Also make sure you run the jQuery.noConflict() method and always use the full jQuery name instead of the $ (dollar sign) to avoid conflicts with prototype ;)
A: You can add it in your block files with $this->getLayout()->getBlock('head')->addJs('path/to/jquery.js'); in the _prepareLayout() method
One caveat, Magento uses Prototype, so you'll need to make sure you set jQuery to another variable other than simply $. Adding this to the page made it work for me:
var $j=jQuery.noConflict();
Then you just use $j where you would normally use $
A: As an alternative way, and instead of manually editing Magento files each time, you can simply add jQuery using this extension: http://www.intersales.de/shop/magento-magejquery.html
What it does for you is download the jQuery version you specify and install all needed files automatically while also adding the references to your template. In the backend you can specify the desired version and also activate the no-conflict setting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to remove a key from a minor-mode keymap in Emacs? I have globally assigned C-c/ to ace-jump-mode but reftex-mode (a minor mode for citations used with AucTeX) overrides this key with some function I never use.
I tried local-unset-key but it only unbinds keys from the current major mode's map.
How do I remove C-c/ from reftex-mode-map without making changes to reftex.el?
A: You can use following command:
(define-key reftex-mode-map "\C-c/" nil)
to unmap this function from C-c /... But reftex-mode should be loaded, so reftex-mode-map will available for modification
A: You can change an existing key map using define-key. By passing nil as the function to call, the key will become unbound. I guess that you should be able to do something like:
(define-key reftex-mode-map "\C-c/" nil)
Of course, you should do this in some kind of hook, for example:
(defun my-reftex-hook ()
(define-key reftex-mode-map "\C-c/" nil))
(add-hook 'reftex-mode-hook 'my-reftex-hook)
A: This is how I do it. It could be improved, though.
(defun get-key-combo (key)
"Just return the key combo entered by the user"
(interactive "kKey combo: ")
key)
(defun keymap-unset-key (key keymap)
"Remove binding of KEY in a keymap
KEY is a string or vector representing a sequence of keystrokes."
(interactive
(list (call-interactively #'get-key-combo)
(completing-read "Which map: " minor-mode-map-alist nil t)))
(let ((map (rest (assoc (intern keymap) minor-mode-map-alist))))
(when map
(define-key map key nil)
(message "%s unbound for %s" key keymap))))
;;
;; Then use it interativly
;; Or like this:
(keymap-unset-key '[C-M-left] "paredit-mode")
..
..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
}
|
Q: How to set long text in a textview with a continuation mark at the end of the textview I have a textview with fixed height. I want to set a long text, but text comes at the last line getting cut by half, I want to avoid it and want to show a continuation symbol. I am giving an image here, I wan to achieve it like in the image.
A: Use the ellipsize attribute of TextView. By setting :
<TextView
....
android:ellipsize="end">
</TextView>
if the text is longer than your TextView you will have dots(...) at the end of the TextView.
A: Two line of string only possible to do like this. set ellipsize = end in text view properties.
A: you should use \n and special symbols from google code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When to use Runtime.maxMemory() and totalMemory() What is the exact difference between Runtime.maxMemory() and Runtime.totalMemory()? The javadoc is quite vague about this (for me).
What are typical use cases for these two methods, that is, When would it be inappropriate to use the respective other one?
A: The totalMemory() returns how much memory is currently used, while the maxMemory() tells how much the JVM can allocate in total.
Note: that from this follows: totalMemory() <= maxMemory(), and you can also get 'how much memory is left' by maxMemory() - totalMemory()
One use case for this is to diagnose how much memory your program uses, and you'll use totalMemory() for it.
Note: both are referring only to heap memory, and not stack memory.
A: The total memory is the memory that is currently allocated to the JVM. It varies over time. The max memory is the maximum memory that the JVM could ever reach. It's the upper limit of the total memory.
A: MaxMemory() is the value set by Xmx parameter
A: totalMemory() which represent current heap size of JVM which is combination of used memory currently occupied by objects and free memory available for new objects.As per javadoc value returned by totalMemory() may vary over time depending upon environment.
JVM totalMemory also equals to initial heap size of JVM
maximum heap space is not going to change over JVM life cycle.Jvm always trying to expand the size of totalMemory() according to no of new object created But not beyond maxMemory() size unles we will get java.lang.OutOfMemoryError.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: @font-face works locally but not on live website I have a website in production which uses @font-face to render fonts, and this works fine in a local environment but fails when uploaded to the live website.
The CSS file which links to the font files is in the root directory, and uses the following code:
@font-face {
font-family: 'ColaborateLightRegular';
src: url('css/fonts/ColabLig-webfont.eot');
src: url('css/fonts/ColabLig-webfont.eot?#iefix') format('embedded-opentype'),
url('css/fonts/ColabLig-webfont.woff') format('woff'),
url('css/fonts/ColabLig-webfont.ttf') format('truetype'),
url('css/fonts/ColabLig-webfont.svg#webfontR2xcGGVv') format('svg');
font-weight: normal;
font-style: normal;
}
The font is in the /css/fonts/ directory. I have tried adding the following to an .htaccess file to try fix the issue but still to no avail:
<FilesMatch "\.(ttf|otf|woff)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
I'm out of ideas really! I just find it very strange how I have no problems across browsers when viewing with XAMPP, but when I try and view it on my server (which is Apache) it wont work on any browser.
A: Check your CHMOD settings on the folders and make sure the server's not sending you a 403 back
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can you change a std::list while iterating through it? In the following functions, it it entirely possible for the IObserver's Process() function to try to remove itself from the notify list, using the this pointer's DeleteObserver().
This causes hell with the iterators (not surprisingly!), is there a way round this? Or should I be taking a closer look at my design?
void cButtonManager::DeleteObserver(IObserver *observer)
{
list<IObserver*>::iterator iter;
for (iter = m_ObserverList.begin(); iter != m_ObserverList.end(); ++iter)
{
if (*iter == observer)
{
// Found the specified observer in the list, delete it
m_ObserverList.erase(iter);
return;
}
}
}
void cButtonManager::NotifyObservers(void)
{
list<IObserver*>::iterator iter;
for (iter = m_ObserverList.begin(); iter != m_ObserverList.end(); ++iter)
{
(*iter)->Process(this);
}
}
For example, imagine that the list is a collection of people that subscribe to a magazine and the Process() function is the delivery of a new magazine issue; if the magazines latest issue is awful the subscriber may wish to un-subscribe as a direct result of that issue.
A: Edit:
Some people in comments corrected me, so I will change this answer. But don't upvote, as it's the commenters' solution, not mine.
(*iter++)->Process();
A: I don't see why you are not using list::remove here. That seems like a perfect match to me.
For the problem in NotifyObserver I would not let Process do the removing itself but rather let it signal that it wants itself to be removed from the list of observer. Plainly: return a bool from Process to signal and then call list::erase on it. Assign the return value of erase to the current iter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MVC RedirectToAction() any way to pass object to the target action? The populated catList is always Count=0 when the code jumps to CreateProduct() so I take it it does not get delivered.
Considering RouteValueDictionary does not do this ? Any other way?
public ActionResult GetCats(int CatID)
{
List<Category> catList = new List<Category>();
if (CatID >= 0 )
{
catList = context.Categories.Where(x => x.PCATID == CatID).ToList();
}
return RedirectToAction("CreateProduct", "Admin", new { catList });
}
public ActionResult CreateProduct(List<Category> catList) { }
A: You are actually trying to use controllers to do data access.
Move the "GetCats" data retrieval into your business layer (Service object, Repository, whatever suits you).
Then, CreateProduct will need to be there twice (2 signatures). One with no parameters in which you are going to call "GetCats" from your business layer and send it to the view.
The other implementation is going to be the flagged with the HttpPostAttribute and will contain in parameters all the necessary information to create a cat.
That's all. Simple and easy.
A: You could place any items that you need in TempData then call RedirectToAction.
A: RedirectToAction simply returns a "302" code to the browser with the URL to redirect to. When this happens your browser performs a GET with that URL.
Your RouteValues need to be simple. You can't really pass complex object or collections using a route value.
A: if you don't care about the browser url changing you could just
return CreateProduct(catList)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Detect DTMF Tones C# I have wav file in which using the naudio lib i have been able to get raw data out of the wav files.
Does any one know how to loop though the data in chuncks detecting DTMF tones?
A: The NuGet package DtmfDetection.NAudio provides extension methods and wrappers to detect DTMF tones in live (captured) audio and pre-recorded audio files.
On the GitHub site of the project you can find a sample program.
A: Well, on the top of the google is this:
http://sourceforge.net/projects/dtmf-cs/
But, if you want to use heavy artillery, you can always FFT your samples and check what two freqs are seen the most.
BTW, do some searching before you post anything, and you'll come up with:
Detect a specific frequency/tone from raw wave-data
or even
Is it possible to detect DTMF tones using C#
A: I've gone with http://www.tapiex.com/ToneDecoder.Net.htm
Its cheeap and does a good job at detection. All the others i found dont seem to do the job or have no documentation
A: DTMF stands for dual-tone multi frequence signaling. So you have to detect the two frequencies used to send a signal.
You have to transform your timebased audio material into the frequency domain typically by using a FFT algorithm.
Here i found a very old VB5 program with source online which does exactly what you want i think: http://www.qsl.net/kb5ryo/dtmf.htm
EDIT: Ok, maybe its better to take a look at the suggested C# lib.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can only one procedure within a PL/SQL package be run with AUTHID CURRENT_USER? I have a PL/SQL package that does not specify an AUTHID (effectively making it AUTHID DEFINER). However, there is precisely one procedure within this package that needs to run as AUTHID CURRENT_USER. Is this possible, or must I create a separate, top-level procedure?
A: Pretty sure a new package would be needed since the AUTHID can only be specified at the PACKAGE level (to the best of my knowledge anyway)
A: Though this linked question is slightly off-topic, the answer supplied by JulesLt explains that you can't specify AUTHID in a package at a level below the package level:
Executing an Oracle Stored Proc as Another User
A: Oracle does not allow the authid clause on a subprogram in a package or type. You will get the following error:
Error: PLS-00157: AUTHID only allowed on schema-level programs
A: A possible solution might be following:
*
*You create a package with AUTHID CURRENT_USER option;
*You grant select, insert, etc. to the objects that reside in the DEFINER schema that you want to use;
*You use fully qualified names of the DEFINER objects.
Here is an example:
CREATE PACKAGE pkg1 AUTHID CURRENT_USER
IS
procedure insert_current_user;
procedure insert_definer;
END pkg1;
/
CREATE OR REPLACE PACKAGE BODY pkg1
IS
procedure insert_current_user
is
begin
insert into table1 values(1);
end insert_current_user;
procedure insert_definer
is
begin
insert into DEFINER.table1 values(1);
end insert_definer;
END pkg1;
/
DEFINER is the owner of the table.
As an improvement, you can create a synonym for the DEFINER.table1 table and then use the synonyms in the package.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Storing password in database using hash with salt; not sure where/how to store salt I have a ASP.NET (MVC 3) web site where user will be able to login to perform certain actions. I need to store their password in backend SQL Server 2008 database. I will be using form authentication ( not windows authentication). I am just wondering what is the best way of storing the password in database. Reading some links like this, I am inclining towards using Hash with Salt but I am unclear on how to store the salt value? Should salt value be encrypted? Any one have other ideas, best practices, potential problem or key considerations before concluding with this approach?
A: Typically the salt is stored as part of the hash, sometimes as the first two bytes. It can be stored as a separate field if necessary, especially when the salt is longer. The salt does not need to be encrypted. You just store the salt+hash in a reasonably-secure (admin access only) location.
Don't ever store the actual password. You only need the salt and hash. When the user gives a password, you encrypt it using the stored salt for the user they claim to be, and if the result matches the stored hash, the password is correct.
A good article on the subject: http://www.obviex.com/samples/hash.aspx
A: A typical approach is to store the salt and the hash together, separated by some special character. This value is created by the authentication mechanism and can be passed to the authentication mechanism to verify, so that the application itself does not have to know that the value contains both a salt and a hash.
The salt is not stored encrypted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to know from a Site B, if the user is connected on the site A? I have got a website and now i have to add a forum. The forum will be on a sub-domain of the site, but may be on an other server.
The user must sign-in only from the website, to be connected on the forum. If the user try to see the forum without sign-in on the website, , he'll be redirect to the the sign-in page form the website, if he is yet connected from the website, he'll can see the site.
My question is how to kwow on the forum ,if there is a session open by the user on the website??? how do they both communicate ? (cookies stuff?, webservice?, and how?)
A: Cookies can be saved on the entire domain, thus allowing subdomains to read them.
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1);
.example.com should be replaced with your domain.
http://php.net/manual/en/function.setcookie.php
A: Single Sign-On?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to make a query with or condition in mongoid How can I make a query with or condition in Mongoid.
A: Here is the solution for "OR" query in mongoid.
if you want query like below
select * from user where id = 10 or name = 'hitesh';
in rails with mongoid then you have to write query like this
User.any_of({id: 10},{name: 'hitesh'}).first
A: This also works:
User.or({id: 10},{name: 'hitesh'})
A: @Simone Carletti is right but you also can use "mongo-style" notation:
# Ruby 1.9+
Person.where(last_name: {"$in" => ["Penn", "Teller"]})
#Ruby 1.9-
Person.where(:las_name => {"$in" => ["Penn", "Teller"]})
or simply
Person.where(:last_name.in => ["Penn", "Teller"])
upd
Conditions for two fields?
Person.where(:last_name.in => ["Penn", "Teller"], :first_name.in => ["Pedro", "Julio"])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: swfLoader vs mx Image I have an application that I'm migrating from flex 3 to flex 4.5. In this application, there is some mx Image components that load a simple swf file (image). Spark image doesn't load swf files, so I was wondering, should I keep the mx Image, or should I change it to SWFLoader? Is there any advantages to using one or the other?
A: Reading Adobe documentation about Image control:
Adobe Flex supports several image formats, including GIF, JPEG, and
PNG. You can import these images into your applications by using the
Spark Image control or BitmapImage. To load SWF files, you use the
SWFLoader control.
The Image control is part of both MX and Spark component sets. While
you can use the MX Image control in your application, Adobe recommends
that you use the Spark Image control instead.
As it states and recommends, it's better to use the spark architecture, instead the mx one (whenever it's possible. It's not a good idead to mix spark and mx components, but Adobe has not migrated every single component to spark yet). I'll go for <s:SWFLoader /> (which is already a new nomenclature for <mx:SWFLoader />.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sorting nsarray by index I simply want to sort an NSArray by the index number i.e. The order in which the values are entered into the array.
My problem is that I use this array in a uipicker, and therefore when reusing labels, end up with my values in the wrong order
My values consist of fractions. 1/4,3/8,1/2,3/4,1,1-1/14,1-3/8 etc
I want these fractions to display in the order they are entered
Must be simple, but I am having no luck
When I use sorted array localisedstandardcompare all the values get out of sequence
Any help will be appreciated
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// Only calls the following code if component "0" has changed.
if (component == 0)
{
// Sets the global integer "component0Row" to the currently selected row of component "0"
component0Row = row;
// Loads the new values for the selector into a new array in order to reload the data.
NSDictionary *newDict = [[NSDictionary alloc]initWithDictionary:[pickerData objectForKey:[selectorKeysLetters objectAtIndex:component0Row]]];
NSArray *sortArray = [[NSArray alloc]initWithArray:[newDict allKeys]];
NSMutableArray *newValues = [[NSMutableArray alloc]initWithArray:[sortArray sortedArrayUsingSelector:@selector(compare:)]];
self.selectorKeysNumbers = newValues;
component1Row = 0;
[self.myPicker selectRow:0 inComponent:1 animated:NO];
A: Your array is already sorted by the index number
A: Assuming that the array values are NSStrings the sort order will be by string value, not numeric value. In order to sort these fractions (rational numbers) you would have to write you own compare function.
But see @hypercrypt, the array should already be in the order entries were made.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When can a cond var be used to synchronize its own destruction/unmapping? According to POSIX,
It shall be safe to destroy an initialized condition variable upon which no threads are currently blocked.
Further, the signal and broadcast operations are specified to unblock one/all threads blocked on the condition variable.
Thus, it seems to me the following forms of self-synchronized destruction should be valid, i.e. calling pthread_cond_destroy:
*
*Immediately after a successful signal, in either the waiting or the signaling thread, when exactly one thread is blocked on the cond var.
*Immediately after a successful broadcast, in either any waiting thread or the broadcasting thread.
Of course this assumes no further waiters will arrive and no further signals shall be performed afterwards, which the application is responsible for guaranteeing if using pthread_cond_destroy.
Am I correct that destruction is valid in these situations? And are there other self-synchronized destruction scenarios to be aware of with condition variables?
Finally, for process-shared cond vars where unmapping the shared mapping without destruction might make sense, is it reasonable to expect unmapping to be valid in the same contexts destruction would be valid, or must further synchronization be performed if multiple threads in the same process (address space) are using the same mapping and want to unmap it in one of the above contexts?
A: No, I don't think that most of your assumptions are correct. Returning from pthread_cond_signal or pthread_cond_broadcast does not indicate that any of the threads are yet "unblocked" from the condition variable, i.e that the threads that are to be unblocked don't need access to that variable anymore. The standard only says "shall unblock" and not "on successful return from this call they will be unblocked". The later would be very restrictive for implementations, so there is probably a good reason that this is formulated as it is.
So I think from the scenarios you describe only one is valid, namely the case were the solely blocked thread or process destroys the condition after being woken up.
A: While I agree with your interpretation (and that of the Open POSIX test suite) of this language, usage will be implementation dependent. As such, here is a quick rundown of some of the major implementations:
Safe
*
*nptl - pthread_cond_destroy() will return EBUSY if there are threads still blocked on the condition. Destruction responsibility will pass to the threads that are signaled by not unblocked.
*pthread-win32 MSVC - pthread_cond_destroy() will return EBUSY if there are threads still blocked on the condition. Threads that are signaled but not unblocked will be executed before pthread_cond_destroy() returns control to the application.
Safe but blocking
*
*Darwin libc-391 - pthread_cond_destroy() will return EBUSY if there are threads still blocked on the condition. No provisions are made for blocked but signaled threads.
*dietlibc 0.27 - pthread_cond_destroy() will return EBUSY if there are threads still blocked on the condition. No provisions are made for blocked but signaled threads.
Possibly not safe
*
*Android - Depends on system implementation of __futex_wake_ex to be synchronous. Thus pthread_cond_broadcast() must block until all threads have woken (but not released their mutex).
*various win32 implementations - Many rely on the PulseEvent() function to implement pthread_cond_broadcast(). This has a known race condition
Oddballs
*
*OSKit 0.9 - Safe but returns EINVAL if pthread_cond_destroy() is called on a condition variable that is still referenced
Edit
The major issue, if I read your comments correctly is whether the pthread_cond_wait() can access the condition variable before it returns but after it is unblocked. And the answer is yes. The routine assumes that its arguments will remain valid.
This means that after broadcasting, your thread cannot assume that the condition variable is unused by other threads.
When you call pthread_cond_broadcast(), you do not acquire the associated mutex lock. While the threads waiting on your condition variable will execute sequentially, each acquiring the associated mutex in series. Because your waiters may block each other, your broadcasting thread may continue executing while waiters are still in pthread_cond_wait() blocked on the mutex (but not waiting for the condition).
Edit 2
[...]is it reasonable to expect unmapping to be valid in the same contexts destruction would be valid?
I don't think that this is a reasonable expectation based on the reasoning in Edit 1. Additional synchronization would definitely be required if you are precluded from using pthread_cond_destroy()
A: Comment (not answer):
Is that what you have in mind?
Global:
// protected by m:
pthread_mutex_t m;
pthread_cond_t c;
bool about_to_pthread_cond_wait = false;
bool condition_waited_on = false;
Thread A :
pthread_mutex_lock (&m);
{ // locked region
about_to_pthread_cond_wait = true;
while (condition_waited_on) {
// pthread_cond_wait (&m, &c) is decomposed here:
__pthread_mutex_cond_wait_then_unlock (&m, &c);
// unlocked region
pthread_mutex_lock (&m);
}
}
pthread_mutex_unlock (&m);
Thread B:
for (bool break_loop = false; !break_loop;) {
pthread_mutex_lock (&m);
{ // locked region
condition_waited_on = true;
if (about_to_pthread_cond_wait) {
pthread_cond_signal (&c);
pthread_cond_destroy (&c);
break_loop = true;
}
}
pthread_mutex_unlock (&m);
pthread_yield ();
}
EDIT:
I assume pthread_cond_wait (&m, &c); does:
__pthread_mutex_cond_wait_then_unlock (&m, &c);
pthread_mutex_lock (&m);
__pthread_mutex_cond_wait_then_unlock will being monitoring the signals to the CV, then unlock the mutex, then go to sleep.
If the CV has an internal mutex that __pthread_mutex_cond_wait_then_unlock and pthread_cond_signal must lock internaly, then I assume __pthread_mutex_cond_wait_then_unlock does:
pthread_mutex_lock (&c.int_mutex);
{ // locked region for c.int_state
__register_wakeup_cond (&c.int_state);
pthread_mutex_unlock (&m);
}
pthread_mutex_unlock (&c.int_mutex);
// will not touch c.int_state any more
__sleep_until_registered_wakeups ();
and pthread_cond_signal does:
pthread_mutex_lock (&c.int_mutex);
{ // locked region for CV internal state
__wakeup_registered (&c.int_state);
}
pthread_mutex_unlock (&c.int_mutex);
Then pthread_cond_destroy will only be called after __pthread_mutex_cond_wait_then_unlock has finished using c.int_state.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Update a Dictionary value using Linq I will call AnalyseLinqUpdate()
I think code itself clear..
I have to find behavior for each dictionary value and replace the value with the behavior I get from the method 'GiveBehavior'
void AnalyseLinqUpdate()
{
Dictionary<string, string> rawCollection = new Dictionary<string, string>();
rawCollection.Add("PT-1", "PTC-1");
rawCollection.Add("PT-2", "PTC-1");
rawCollection.Add("PT-3", "PTC-2");
rawCollection.Add("PT-4", "PTC-2");
rawCollection.Add("PT-5", "PTC-3");
rawCollection.Add("PT-6", "PTC-3");
//update here
// call GiveBehavior("PTC-1");
//returns a string that needs to be updated in place of "PTC-1"
}
string GiveBehavior(string ptc)
{
StringComparison ignoreCase = StringComparison.OrdinalIgnoreCase;
ptc = ptc.Trim();
if (ptc.Equals("PTC-1", ignoreCase))
{
return "PTB-1";
}
else if (ptc.Equals("PTC-1", ignoreCase))
{
return "PTB-2";
}
else
{
return "PTB-3";
}
}
Currently I have done like:
List<string> keys = rawCollection.Keys.ToList();
foreach (string key in keys)
{
string behavior = GiveBehavior(rawCollection[key]);
rawCollection[key] = behavior;
}
This is how I update the dictionary..
Is there anyway tat can be done via LINQ...
A: You could try the following:
List<string> keys = rawCollection.Keys.ToList();
keys.ForEach(key => { rawCollection[key] = GiveBehavior(rawCollection[key]); });
A: That should do it
rawCollection = rawCollection.ToDictionary(item => item.Key, item => GiveBehavior(item.Key));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Rendering issues with Sencha Touch list on orientation change This is for a mobile web site rather than an app. Accessing the mobile site from my iPhone 4 using mobile safari. The site comes up in portrait mode and works fine (can get to all list items although there are only a panel full at this point) and my disclosure icons are all visible.
The issues include:
*
*if changing to landscape my list items will display with the portrait width initially and it's not possible to scroll to see all items since the vertical space is now less.
*if I navigate to a detail page on the list and then use my home button to return the list will render the full width of the landscape mode panel correctly but still cannot scroll to items off the panel.
*return to portrait mode and the list redisplays all items but the width of each item is now landscape wide and the disclosure icons are off screen and not accessible. If I navigate to another page via a bBar command button and return things render correctly again.
Here is the list config code (pretty straightforward):
var listConfig = {
itemTpl: '<div class="rName">{menuitem}</div>',
scroll: 'vertical',
monitorOrientation: true,
selModel: {
mode: 'SINGLE',
allowDeselect: true
},
onItemDisclosure: {
scope: 'test',
handler: function(record, btn, index) {
mainpanel.hide();
showDetail(record);
}
},
store: nhsw.stores.topmenu
};
var topmenuList = new Ext.List(Ext.apply(listConfig, {
layout: 'fit',
hideOnMaskTap: false
}));
A: Added layout: 'fit' to containing panel and all is good now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to update location only when button is pressed How can I make my application update location only when a button is pressed?
I have a button named "REFRESH". Everytime this button is pressed, I want to show my user their location. For example, 51 Bourke Street, Victoria.
However, I do not want to update my location regularly. I want to update its location only when the button is pressed, to save battery power.
What do you think? Am I doing it correctly?
I have these classes:
*
*VoteViewController.h and VoteViewController.m
*CoreLocationController.h and CoreLocationController.m
This is what I have:
VoteViewController.h class
@interface VoteViewController : UIViewController <CoreLocationControllerDelegate>
{
CoreLocationController *coreController;
}
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
- (void)geoReverseAddress:(MKPlacemark *)placeMark;
- (IBAction)refreshButtonPressed;
VoteViewController.m class
- (void)viewDidLoad
{
[super viewDidLoad];
coreController = [[CoreLocationController alloc] init];
coreController.delegate = self;
}
- (IBAction)refreshButtonPressed
{
NSLog(@"Refresh Button pressed");
label.text = [NSString stringWithString:@""];
[coreController.locationManager startUpdatingLocation];
}
- (void)locationUpdate:(CLLocation *)location
{
comments.text = [location description];
[coreController.locationManager stopUpdatingLocation];
}
- (void)locationError:(NSError *)error
{
comments.text = [error description];
[coreController.locationManager stopUpdatingLocation];
}
- (void)geoReverseAddress:(MKPlacemark *)placeMark
{
label.text = [NSString stringWithFormat:@"%@ %@, %@", [placeMark subThoroughfare],
[placeMark thoroughfare], [placeMark locality]];
}
CoreLocationController.h class
@protocol CoreLocationControllerDelegate <NSObject>
@required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
- (void)geoReverseAddress:(MKPlacemark *)placeMark;
@end
@interface CoreLocationController : NSObject <CLLocationManagerDelegate, MKReverseGeocoderDelegate>
{
CLLocationManager *locationManager;
id delegate;
MKReverseGeocoder *reverse;
}
@property(nonatomic, retain) CLLocationManager *locationManager;
@property(nonatomic, retain) id delegate;
@end
CoreLocationController.m class
-(id) init
{
self = [super init];
if (self != nil)
{
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
self.locationManager.distanceFilter = kCLHeadingFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"Update location");
[self.delegate locationUpdate:newLocation];
reverse = [[MKReverseGeocoder alloc] initWithCoordinate:[newLocation coordinate]];
reverse.delegate = self;
[reverse start];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
[self.delegate locationError:error];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
[self.delegate locationError:error];
[reverse cancel];
[reverse release];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
[self.delegate geoReverseAddress:placemark];
[reverse cancel];
[reverse release];
}
A: When you first fire up CLLocationManager, you're very likely to get one stale location from the last time it ran. Once that's out of the way, you're going to start getting very inaccurate locations while the device uses WiFi sniffing and cell triangulation, while the GPS looks for a fix.
So in your didUpdateToLocation method, you probably want to throw away the first hit, and then test the .horizontalAccuracy value of your newLocation object for a low enough value to trust.
Apart from that, I don't see anything bad about what you've sent here. I'm not sure I'd go to the trouble of wrapping the location fetching work in its own class, I'd probably just do that out in my viewController. But that's a style choice. If you're reusing this functionality elsewhere, what you've got here is obviously the way to go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: jQuery select for element variable I haven't been able to find an answer to this:
My HTML (simplified) looks similar to this (there are several different controls on the page: text fields, comboboxes, etc.):
...
<input name="name" onfocus="showHint(this, 'Please enter your name')" onblur="hideHint()" ...>
...
An in the javascript function showHint I do something like:
function showFormEntryHint(control, text)
{
localOffset = 30;
$('#entry_hint').html(text);
var position = $(control).offset();
position.left += $(this).offset() + localOffset;
position.top -= 5;
$('#entry_hint').position(position);
$('#entry_hint').fadeIn();
}
The idea is to position the #entry_hint div next to the field that invoked the function. Unfortunately, selector $(control) does not seem to work - and .offset() on it always returns {left: 0, top: 0}.
Any idea how I can get this to work? Many thanks!
A: You're using jQuery anyway; why stick to DOM0-style event handlers?
Do it like this:
<!-- simplified -->
<input id='someInput' />
<script type='text/javascript'>
jQuery(function($) {
// this is where we attach the event handlers
$('input#someInput')
.focus(function() {
showFormEntryHint(this, 'Please enter your name.');
})
.blur(function() {
hideHint();
});
});
</script>
Barring that however, you can also look for ready-made plugins to do the brunt work for you if you don't need much custom logic.
A: well just get rid of the control and you can use $(this) like you do for position.left. not sure what you are trying to accomplish with $(control).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MSXML loadXML won't load elements with namespace prefixes... Why? Hiho,
i guess, it's a pretty stupid question, but i had to switch to C/C++ recently and haven't done this in years.
And right now I'm stuck on the following:
Given XML Element as a simple String:
<myns:factor>1000</myns:factor>
I have to parse the string, add the resulting Element to a surrounding MSXML2 DOM object within the same Namespace.
Right now i try it this way:
HRESULT hr;
MSXML2::IXMLDOMDocument2Ptr l_xmlFrame;
MSXML2::IXMLDOMElementPtr l_xmlFrameDoc;
hr = l_xmlFrame.CreateInstance(__uuidof(MSXML2::DOMDocument));
if( !FAILED(hr) ) {
l_xmlFrame->async = VARIANT_FALSE;
l_xmlFrame->validateOnParse = VARIANT_TRUE;
// p_strUnit holds the xml as a String
l_xmlFrame->loadXML(p_strUnit);
}
The loadXML(...) call just fails , but:
if i remove the namespace declarations and the element looks like this:
<factor>1000</factor>
the call works perfectly!
I really don't understand, why the loadXML function wont parse the string, when the Namespace declarations are set.
Any help appreciated!!!!! :)
Thanks!
A: The Problem
The string
<myns:factor>1000</myns:factor>
is not well-formed XML (with regard to namespaces). That's why XML parsers generally won't load it.
It's not well-formed because it uses the namespace prefix "myns", which has not been declared.
The Solution
If you changed the XML to something like this, it would parse fine:
<myns:factor xmlns:myns="mynamespaceURI">1000</myns:factor>
The namespace declaration (xmlns:myns="mynamespaceURI") can go on the element where the namespace prefix is used, or any ancestor thereof.
If you can't change the input XML, I would then ask the supplier of the XML, "Why are you giving me broken XML?"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is returning a type pointer the same as 'newing a type'? in c# Instead of...
Video v = new Video();
I want to do
Video v = GetVideo();
public Video GetVideo()
{
return new Video();
}
Are these two calls totally equal?
A: Yes, they are. I have used this approach several times to return me an object prepopulated by some default testing values.
A:
Is returning a type pointer the same as 'newing a type'?
It depends on the method returning the object reference.
Your given snippets, for example, are functionally equivalent because GetVideo() does nothing except return a new Video().
A: At least you can treat them as equal, they will probably be inlined to the same IL code if they reside in the same assembly.
A: They're the same in this case because the method also creates a new Video. However, consider this instead:
private Video video;
public Video GetVideo()
{
if (video == null)
{
video = new Video();
}
return video;
}
Now a new Video object will be created only the first call - subsequent calls will return a reference to the existing object.
(That's only a simple example, of course - it could sometimes create a new one, sometimes not, sometimes return null etc.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get the array of RGB values for each pixel of the client area of a window Is there a way to receive the colour values for each pixel in the client area of a window, with gdi?
A: As noted in comment by @JerryCoffin. Here's a simple example
hDC = GetDC(hwnd);
hBitmap = CreateCompatibleBitmap(hDC, width, height);
hMemDC = CreateCompatibleDC(hDC);
hOld = SelectObject(hMemDC, hBitmap);
BitBlt(hMemDC, 0, 0, width, height, hDC, x, y, SRCCOPY);
// Clean up
DeleteDC(hMemDC);
ReleaseDC(hwnd, hDC);
You should have a bitmap object selected into memory DC for which you can use GetPixel GDI function and then you can also extract the color values using GetRValue() , GetGValue() , and GetBValue() macros.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C Graphics Library Error I have the following code :
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
int dx,dy,p,end;
float x1,x2,y1,y2,x,y;
initgraph(&gd,&gm,"");
printf("\nEnter the value of x1: ");
scanf("%f",&x1);
printf("\nEnter the value of y1: ");
scanf("%f",&y1);
printf("\nEnter the value of x2: ");
scanf("%f",&x2);
printf("\nEnter the value of y2: ");
scanf("%f",&y2);
dx=abs(x1-x2);
dy=abs(y2-y1);
p=2*dy-dx;
if(x1>x2)
{
x=x2;
y=y2;
end=x1;
}
else
{
x=x1;
y=y1;
end=x2;
}
putpixel(x,y,10);
while(x<end)
{
x=x+1;
if(p<0)
{
p=p+2*dy;
}
else
{
y=y+1;
p=p+2*(dy-dx);
}
putpixel(x,y,10);
}
getch();
closegraph();
}
The code is mainly for creating a line. But when I run this program I get error message in my console(I'm using Ubuntu 10.04 version) as :
test.c:2: fatal error: conio.h: No such file or directory
compilation terminated.
test.c:2: fatal error: graphics.h: No such file or directory
compilation terminated.
Is that mean I have to add some lib to C path?
Thanks in advance.
A: conio.h and graphics.h are ancient, non-standard interfaces that came from Borland environments I suppose.
A: Those two headers are Windows-only. For getch() you can emulate it (see here) and for graphics.h you can install libgraph.
A: For Ubuntu users the mistake is when we dont have that library. So we include a corresponding library. Type the following command in terminal:
sudo apt-get install libncurses5-dev libncursesw5-dev
A: change
dx=abs(x1-x2);
by this:
dx=abs(x2-x1);
A: try to use OPENGL and delete the line including conio.h,graphics.h,getch(),closegraph(). Those are used by Turbo C DOS compiler and are obsolete.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jquery Cycle - how to use circle for pager? Am having a problem getting my pager to look right with jquery cycle.
The following code
$(document).ready(function() {
$('#slider_container')
.after('<div id="pager">')
.cycle({
fx: 'scrollRight',
speedIn: 400,
speedOut: 200,
timeout: 10000,
pause: 1,
delay: -4000,
easeIn: 'easeInCirc',
sync: false,
pager: '#pager',
pagerAnchorBuilder: function(idx, el) {
return '<li><a href="#"><img src="images/grey_dot.png" width="10" height="10" /></a></li>';
}
});
});
Has got me the images to show up as the navigation instead of the numbers but the problem is that I would like to be able to have a different coloured circle for the active slide.
I tried leaving the img bit out of the pageAnchorBuilder and using backgrounf:(url) in the CSS and a different one on .activeSlide but to no avail.
Would appreciate anyone's help, thanks.
A: I know you said you have already tried to style them via css and it didnt work? But in theorie it should work. I think you should try again.
Sample:
#pager a{
display:block;
background:url(pagerBg.png) no-repeat;
}
#pager a.activeSlide{
background:url(activePagerBg.png) no-repeat;
}
This works on my localhost. Ideally you can use the page anchor builder to hide the numbers:
pagerAnchorBuilder: function(idx, el) {
return '<a href="#"></a>';
}
I hope this helps!
EDIT:
First of all. Here is a demo on how it should work: http://jsfiddle.net/Lywtt/1/
Now, you should try following:
-remove the anchor builder completly
Once you remove the anchorbuilder you do see simple links with the number of slides, right? Like "123"
-Next thing we want to do is to style this links, so add the following in your css:
#pager{
width:200px;
margin-top:5px;
border:1px solid blue;
text-align:center;
}
#pager a{
display:inline-block;
width:20px;
margin-left:5px;
background:green;
}
#pager a.activeSlide{
background:yellow;
}
Obviously, most of the styles above are just for demo purpose and can be removed once everything works as you wish.
This must work in theory, however if it still doesnt work, than relink your updated site (without the anchor builder and with the new styles) and we can check it again.
Edit 2:
Good to hear it works! Now using images instead of the green and yellow (for active slides) blocks, is quite easy. Lets start with a demo again: http://jsfiddle.net/Lywtt/2/
What we need to do is following:
Simply replace the css with something like this:
#pager a{
display:inline-block;
width: 20px; /* width of the image */
height: 20px; /* height of the image */
margin-right:5px; /* space between the images */
background:url(pagerBg.png) no-repeat;
}
#pager a:last-child{
margin-right:0; /* we need no space after the last pager link */
}
#pager a.activeSlide{
background:url(activePagerBg.png) no-repeat;
}
As you can see, we simply replace background:green; and background:yellow; with the corresponding images. Of course you will have to adjust the links of the images to match your site structure.
You should now see the numbers with the images as background instead of green and yellow backgrounds.
As a final step, we want to remove this numbers. To do so, we have to insert a simple anchorBuilder in our script again:
pagerAnchorBuilder: function(idx, el) {
return '<a href="#" title="Slides"></a>';
}
You see we insert a simple anchorBuilder to display empty links (no numbers).
Now you should be able to see the images only without numbers.
If i didnt make a typo or another mistake, everything should work fine now. If not, dont hesitate to say so!
Regards!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I make my wcf services available for particular user? I'm using CustomMembershipProvider to validate the user for my WCF service. User will get a prompt for his credentials once he access the service.
Note: I thought I could get the username and identify the user. But how to pass variable from CustomMembershipProvider to my wcf service file?
Custom Membership Provider Code
Here is the code that I'm validating!
public override bool ValidateUser(string username, string password)
{
int authenticatedId = SecurityManager.Authenticate(username, password);
if (authenticatedId != -1)
{
return true;
}
return false;
}
Here is my Basic Authentication Host Factory
This will call my CustomMembershipProvider to replace the default web service factory.
public class BasicAuthenticationHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
var serviceHost = new WebServiceHost2(serviceType, true, baseAddresses);
serviceHost.Interceptors.Add(RequestInterceptorFactory.Create("DataWebService", new CustomMembershipProvider()));
return serviceHost;
}
}
Any help will be appreciated.
A: Once you've executed MembershipProvider.ValidateUser, a valid SecurityServiceContext should be created and added to the incoming request.
internal ServiceSecurityContext Create(Credentials credentials)
{
var authorizationPolicies = new List<iauthorizationpolicy>();
authorizationPolicies.Add(authorizationPolicyFactory.Create(credentials));
return new ServiceSecurityContext(authorizationPolicies.AsReadOnly());
}
Then you should have access to the username via ServiceSecurityContext.Current.PrimaryIdentity.Name
I think you're working from the article Basic Authentication on a WCF REST Service. The author appears to be very responsive to questions - you might want to hit him up for some pointers! Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Case condition broken need assistance to fix New to SQL, so please accept my apologies. A query was created that when
If HBL_CLNT_CAT._HS_EB_CODE1 = 'BF' then value = TBM_BILLGRP._HS_EB_DET1
If HBL_CLNT_CAT._HS_EB_CODE2 = 'BF' then value = TBM_BILLGRP._HS_EB_DET2
However of the _HS_EB_DET# exceeds 100 characters add a '*'.
With assistance a query was developed, however it broken the condition rules in that the 'then statement/action would fail because it was greater number than the condition statement (select _hs_eb_code1 from hbl_cat where hs_eb_code = 'bf' that returns only 1 record).
select
case when len(format) > 100
then left(format, 100) + '*'
else format
end as format
from
( select
case when exists ( select _hs_eb_code1
from hbl_cat
where hs_eb_code = 'bf'
)
then tbm_bllgrp._hs_eb_det1
end
) as format
from tbm_bllgrp
A: Formatting the code would have helped you find the error. Try this:
select
case when len(format) > 100
then left(format, 100) + '*'
else format
end as format
from
( select
case when exists ( select _hs_eb_code1
from hbl_cat
where hs_eb_code = 'bf'
)
then tbm_bllgrp._hs_eb_det1
end as format
from tbm_bllgrp
) as tmp
A: The above query is broken in several places. A working statement could look like this:
SELECT CASE
WHEN len(x.myval) > 100 THEN
left(x.myval,100) + '*'
ELSE
x.myval
END AS format
FROM (
SELECT CASE
WHEN h.HS_EB_CODE1 = 'BF' THEN
t._HS_EB_DET1
WHEN h._HS_EB_CODE2 = 'BF' THEN
t._HS_EB_DET2
ELSE
'unknown option'
END AS myval
FROM HBL_CLNT_CAT AS h
JOIN TBM_BILLGRP AS t ON ??? -- how are the two tables connected?
WHERE ??? -- some condition or do you want all rows in the table?
) AS x
But you need to tell us first, how TBM_BILLGRP and HBL_CLNT_CAT can be joined, and how you select your rows.
BTW, upper case is pointless in SQL-Server. Identifiers are case-insensitive as long as they are not enclosed in double quotes " " or brackets [ ].
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get an ACCESS_TOKEN from the new Add to Timeline Auth dialog I currently have the following situation. On my website, the user can access his settings page. This page features a tab called 'Facebook'. On this page, I have the following code that lets the user allow my website to post to his timeline when completing a certain action:
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#appId={APP_ID_HERE}&xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-add-to-timeline" data-show-faces="false" data-mode="button"></div>
When the user clicks the button, it is forwarded to the Add to Timeline dialog. When the user clicks Allow, the user gets redirected back to his settings page on my website.
The question is; how do I get an access token out of this? I need a user access token to post to his timeline, according to this line from the tutorial:
https://graph.facebook.com/me/YOUR_NAMESPACE:cook?recipe=OBJECT_URL&access_token=ACCESS_TOKEN
A: Just tell user to get log in
<fb:login></fb:login>
and after that, use this code everywhere you want
FB.api(
'/me/NAMESPACE:cook','post', {recipe:'http://samples.ogp.me/214706465259448'},
function(response) {
//posted
});
Where cooking is an object
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: 500 error when querying yahoo placefinder with a particular character? I am using the Yahoo Placefinder service to find some latitude/longitude positions for a list of addresses I have in a csv file.
I am using the following code:
String reqURL = "http://where.yahooapis.com/geocode?location=" + HttpUtility.UrlEncode(location) + "&appid=KGe6P34c";
XmlDocument xml = new XmlDocument();
xml.Load(reqURL);
XPathNavigator nav = xml.CreateNavigator();
// process xml here...
I just found a very stubborn error, that I thought (incorrectly) for several days was due to Yahoo forbidding further requests from me.
It is for this URL:
http://where.yahooapis.com/geocode?location=31+Front+Street%2c+Sedgefield%2c+Stockton%06on-Tees%2c+England%2c+TS21+3AT&appid=KGe6P34c
My browser complains about a parsing error for that url. My c# program says it has a 500 error.
The location string here comes from this address:
Agape Business Consortium Ltd.,michael.cutbill@agapesolutions.co.uk,Michael A Cutbill,Director,,,9 Jenner Drive,Victoria Gardens,,Stockton-on-Tee,,TS19 8RE,,England,85111,Hospitals,www.agapesolutions.co.uk
I think the error comes from the first hyphen in Stockton-on-Tee , but I can't explain why this is. If I replace this hypen with a 'normal' hyphen, the query goes through successfully.
Is this error due to a fault my end (the HttpUtility.UrlEncode function being incorrect?) or a fault Yahoo's end?
Even though I can see what is causing this problem, I don't understand why. Could someone explain?
EDIT:
Further investigation on my part indicates that the character this hypen is being encoded to, "%06", is the ascii control character "Acknowledge", "ACK". I have no idea why this character would turn up here. It seems that differrent places render Stockton-on-Tee in different ways - it appears normal opened in a text editor, but by the time it appears in Visual Studio, before being encoded, it is Stocktonon-Tees. Note that, when I copied the previous into this text box in firefox, the hypen rendered as a weird, square box character, but on this subsequent edit the SO software appears to have santized the character.
I include below the function & holder class I am using to parse the csv file - as you can see, I am doing nothing strange that might introduce unexpected characters. The dangerous character appears in the "Town" field.
public List<PaidBusiness> parseCSV(string path)
{
List<PaidBusiness> parsedBusiness = new List<PaidBusiness>();
List<string> parsedBusinessNames = new List<string>();
try
{
using (StreamReader readFile = new StreamReader(path))
{
string line;
string[] row;
bool first = true;
while ((line = readFile.ReadLine()) != null)
{
if (first)
first = false;
else
{
row = line.Split(',');
PaidBusiness business = new PaidBusiness(row);
if (!business.bad) // no problems with the formatting of the business (no missing fields, etc)
{
if (!parsedBusinessNames.Contains(business.CompanyName))
{
parsedBusinessNames.Add(business.CompanyName);
parsedBusiness.Add(business);
}
}
}
}
}
}
catch (Exception e)
{ }
return parsedBusiness;
}
public class PaidBusiness
{
public String CompanyName, EmailAddress, ContactFullName, Address, Address2, Address3, Town, County, Postcode, Region, Country, BusinessCategory, WebAddress;
public String latitude, longitude;
public bool bad;
public static int noCategoryCount = 0;
public static int badCount = 0;
public PaidBusiness(String[] parts)
{
bad = false;
for (int i = 0; i < parts.Length; i++)
{
parts[i] = parts[i].Replace("pithawala", ",");
parts[i] = parts[i].Replace("''", "'");
}
CompanyName = parts[0].Trim();
EmailAddress = parts[1].Trim();
ContactFullName = parts[2].Trim();
Address = parts[6].Trim();
Address2 = parts[7].Trim();
Address3 = parts[8].Trim();
Town = parts[9].Trim();
County = parts[10].Trim();
Postcode = parts[11].Trim();
Region = parts[12].Trim();
Country = parts[13].Trim();
BusinessCategory = parts[15].Trim();
WebAddress = parts[16].Trim();
// data testing
if (CompanyName == "")
bad = true;
if (EmailAddress == "")
bad = true;
if (Postcode == "")
bad = true;
if (Country == "")
bad = true;
if (BusinessCategory == "")
bad = true;
if (Address.ToLower().StartsWith("po box"))
bad = true;
// its ok if there is no contact name.
if (ContactFullName == "")
ContactFullName = CompanyName;
//problem if there is no business category.
if (BusinessCategory == "")
noCategoryCount++;
if (bad)
badCount++;
}
}
A: Welcome to real world data. It's likely that the problem is in the CSV file. To verify, read the line and inspect each character:
foreach (char c in line)
{
Console.WriteLine("{0}, {1}", c, (int)c);
}
A "normal" hyphen will give you a value of 45.
The other problem could be that you're reading the file using the wrong encoding. It could be that the file is encoded as UTF8 and you're reading it with the default encoding. You might try specifying UTF8 when you open the file:
using (StreamReader readFile = new StreamReader(path, Encoding.UTF8))
Do that, and then output each character on the line again (as above), and see what character you get for the hyphen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: "Symbol 'map' could not be resolved" in namespace Hello!
I am currently developing an game engine. Even though I only just started, I have already run into a problem.
I have this code:
#ifndef INSTANS_H_
#define INSTANS_H_
#include <map>
#include "Core/Version.h"
#include "Core/Window.h"
#include "Core/Component.h"
#include "Core/Game.h"
namespace Instans
{
class Window;
class Component;
class Engine
{
public:
Engine();
~Engine();
void AddComponent(char* name, Component* component, int priority = 10);
void RemoveComponent(char* name);
void SetFramerateLimit(int limit);
int GetFramerate();
int GetFramerateLimit();
void Run(char* title, int width, int height);
void Load();
void Update();
void Render();
void Release();
protected:
private:
Window* _window;
// Game, managers etc.
std::map<int, char*, Component*> _components;
};
};
#endif
Even though I have included , Eclipse gives me the following error:
Symbol 'map' could not be resolved Instans.h
What could be the cause?
A: The correctly qualified name is ::std::map, since you're already in some other namespace.
A: The third parameter to map is a comparison function type, not a third contained data type. Chances are that's what's causing your problem.
I can't quite tell what you're trying to do but if you're trying to map an int/string composite key to a Component you could use:
std::map<std::pair<int, std::string>, Component*>
A: The third template parameter to map should be a comparison function. I'm guessing you are trying to map from int -> (char *, Component ). You'll need to wrap the char and Component* into a struct or a pair...
typedef std::pair<char*, Component*> CharAndComponentPair;
typedef std::map<int, CharAndComponentPair> ComponentMap;
ComponentMap _components;
A: If this is an Eclipse issue rather than a compile issue then the problem is that there are a bunch of include directories that are missing from the indexers perspective.
Adding the following worked for me, but may depend on your particular setup where they actually exist:
/usr/include/c++/4.6.1
/usr/include/
/usr/include/c++
/usr/include/c++/4.6
/usr/include/x86_64-linux-gnu
/usr/include/asm-generic
/usr/include/c++/4.6.1/x86_64-linux-gnu/
They can be set in Project>Properties>C++ Include Paths
A: If you installed the CDT plugin for eclipse, everything should work out of the box.
I tried to declare a vector but when it came to instantiating it, it gave the same unresolved symbol error. Checking CDT forums, i found that sometimes just turning errors to warnings worked. So i just ignored the compile errors and ran the project. It worked.
#include <vector> // this was fine. no complaints from eclipse
int main() {
std::vector V; /// vector was underlined red. Just ignore and run.
V.push_back(1);
return 0;
}
A: #include <map>
using namespace std;
map<string, SDL_Texture* > m_textureMap;
http://www.cplusplus.com/reference/map/map/map/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: c# Trackbar increase/decrease I am really new to C# and do have a few problems with the trackbar.
I am trying to increase/decreasing the volume by adjusting the trackbar up and down.
I do have two commands that I can send with a protocol through serial cable, lets that it is "UP" for increased and "DOWN" for decreased volume. after writing "UP", you also write how many times (nn 0-254) you want to increase the volume. e.g. "UP10" will increase the volume by 10.
This is really easy if you have two buttons.
void VolumeDownClick(object sender, EventArgs e)
{
try
{ //writing to serial port
serialPort.WriteLine("UP10");
}
catch
{
}
}
But how would I achieve the same result with a trackbar?
I have tried to play around with trackbar.Value, but without result.
A: As a quick guess, but without platform info
If you can get the devices current volume info, then that would be useful to then marry the value in the track bar and the actual volume., and store it in a local value (lastvolume perhaps)
In the valueChanged event, retrieve the new value. Then compare it to the last volume, if its > then send an UP(currentvalue-lastvalue) else if its less DOWN(lastvalue-currentvalue) and store the new value in last value.
You should end up with a working volume control.
A: Assuming you have the old volume stored in a variable named oldVolume. You can use the Trackbar's ValueChanged event to determine the newVolume and calculate the difference. You can then simply write that to your serial port.
A: Use a variable to keep track of what the current value is. This will be used to increase or decrease the volume.
All you have to determine the value increased or decreased, you can do this by checking what the previous value was, and then sending your UPValue or DOWNValue based on that result.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Macintosh: Converting RAW files to dng using a shell script A while back I built a simple droplet app that took raw files and moved them from a desktop to a server location and did a DB update. I've now received a request from the photo dept. to have it also convert raw files to dng format.
The app is built in XCode but just runs an AppleScript. I've used shell scripts for updating databases and cURL and getting meta data. I don't want to and really can't pop open an app (like PS CS5) to do the conversion, is there a shell script out there that'll take care of this for me?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django admin inline model for User I have model as
class Employer(models.Model):
create_user = models.ForeignKey(User,unique=False,null=True, related_name='%(class)s_user_create')
update_user = models.ForeignKey(User,unique=False,null=True, related_name='%(class)s_user_update')
and I would like to list all Employer objects while I was at details of user in Django admin panel.
I have written something like
admin.py
class EmployerInline(admin.TabularInline):
model = Employer
class UserAdmin(admin.ModelAdmin):
inlines = [
EmployerInline
]
admin.site.register(UserAdmin)
but it gives me error as 'MediaDefiningClass' object is not iterable
How can I list employers that are created by a spesific user while I was looking for user's details ?
Thanks
A: The particular error you mention doesn't seem to have anything to do with what's going on in your code, so I'm not sure about that particularly. However, you have other errors here, so potentially fixing those will resolve that error as well.
First, you need to specify fk_name on your EmployerInline. Django resolves the foreign key automatically in most circumstances, but since you have two foreign keys to the same model, you have to give Django some help.
class EmployerInline(admin.TabularInline):
model = Employer
fk_name = 'create_user'
Second, you may have just omitted it, but you must unregister User before registering it. You also need to specify the model when registering:
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: GORM Mapping Manifesto :: To Long or not to Long Fairly basic problem but it's roots run deep in the framework (and there is little definitive information on the subject), so I am putting it out here so as to save others the pain (and to verify that I am correct or not in my thinking).
What is the problem?
Grails automatically injects an id field of type Long into your domains (see Beckwith's comment). When using a legacy DB Grails maps Longs to bigints by default, an inefficient storage type that anyone dealing with large million+ record tables would avoid.
Upon discovering this a few months ago I set to work on getting a "proper" column type in place for my domain ids. Not having a Java background, blindly I thought, Long-bad, Integer-good and set hibernate mapping dialect for Integer types to what I would do by hand in mysql
registerColumnType(Types.INTEGER, 'mediumint unsigned')
and then defined "Integer id" in all of my domains (not necessary according to Bert's comment in link above). Everything worked swimmingly, wonderful, on to other things.
Fast forward to Grails 2.0 (as I could not resist all of the goodies ;-)) and Spock. For the life of me I could not figure out why, despite 2.0 new in-memory GORM and support for dynamic finders, that Domain.findByFoo(fooVal) would always return null (yes, I @Mock(Domain) and populate with test data). In fact, both within the test itself and @TestFor target, the only GORM methods that worked were save() and get(); everything else returned null.
I whipped up a quick test app, domain + controller + spoc spec and discovered the source of the problem: If you use a property type other than Long for your ids (including referenced FKs), your @Mock domain(s) will be rendered useless.
So, am I correct or not in saying that one must use Long ids in order to take full advantage of the framework? @Mock + @TestFor + Spock is an incredible combo! Guidance appreciated before I head down refactor-to-Long road...
A: I cannot imagine any realistic scenario where the difference between Integer and Long would make any noticeable difference to performance (which seems to have been the original motivation for making this change).
If using Long works, but Integer causes problems, then use Long and move onto more important tasks. I would only worry about this if you can prove that using Integer makes any significant difference.
Update
You're right, I did completely miss the point about the database type that Grails automatically uses for Long. As you seem to already know, you can control the database type in the mapping closure of your domain class, e.g.
class Person {
Long id
static mapping = {
// See here for alternatives to integer, and how they map to DB types
// http://docs.jboss.org/hibernate/stable/core/manual/en-US/html/mapping.html#mapping-types-basictypes
id type:'integer'
}
}
You also brought up in the comments
dealing with Long at code level where one must specify def foo(Long id) {...} and params.id.toLong() as opposed to Integer
You can simply define an action as
def myAction = {Person p ->
}
or
def myAction = {
Person p = new Person(params)
}
And Grails will take care of type-converting the id request parameter to Person.id, regardless of whether it's a Long, Integer, BigDecimal, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: SsrsMsbuildTasks - Report image added using AddResource tasks renders as broken link in the report I'm using the following to add images during report deployment. The images are uploaded, and are valid (you can display them in the browser), but they are rendered as broken links in the reports.
<Target Name="AddResources" DependsOnTargets="ValidateDeploymentSettings;GetServerUrl">
<AddResource ReportServerURL="$(TargetServerUrl)" Folder="$(TargetReportFolder)"
Files="%(ResourceFiles.Fullpath)" />
</Target>
Are there other parameters needed by AddResource task to make images work? Could this be a permission issue?
Any help appreciate.
Best,
/jhd
John Dhom
note: also posted to project forum here... http://ssrsmsbuildtasks.codeplex.com/discussions/274252
A: AddResource will add the mimetype if you pass the pass the files using '@', as in...
<AddResource ReportServerURL="$(TargetServerUrl)" Folder="$(TargetReportFolder)" Files="@(ResourceFiles)" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598532",
"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.