text stringlengths 8 267k | meta dict |
|---|---|
Q: NHibernate advanced search headache I really believe this is a simple problem, but one of those with a solution that's not obvious to an NHibernate newbie like me...
Here's the deal, I'm conducting my NHibernate-related queries from a data service layer that knows nothing about NHibernate (for separation of concerns). As such, I'm constructing my queries by using LINQ (Sytem.Linq).
I want to search on more than one word. For instance, if someone types in "training excel", then I will search a number of entities and related location entities based on both words.
Here's what my code looks like in my service layer right now:
// We are delimiting by spaces and commas.
string delimiterString = " ,";
char[] delimiter = delimiterString.ToCharArray();
IEnumerable<string> words = searchWords.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
// Loop through each search word in the collection and apply the "Where" clause to our IQueryable collection:
foreach (string word in words) {
matches = matches.Where(i => i.Subject.Contains(word)
|| i.Background.Contains(word)
|| i.Summary.Contains(word)
|| i.Organization.Contains(word)
|| i.Locations.Any(l => l.Organization.Contains(word))
|| i.Locations.Any(l => l.City.Contains(word))
);
}
Here's the issue... through viewing my application logs and running NHibernate Profiler, I see that the T-SQL query is correctly being constructed. The search works fine with just one search word passed in. However, if 2 or more words are detected, the last word detected is the only one searched on. For instance, if the search term was "training excel", then, as I step through my code above, both words are correctly added in the loop, but the final T-SQL output has "excel" in both logical where groups in the WHERE clause (i.e. WHERE course.Subject like ('%' + 'excel' + '%')...... AND course.Subject like ('%' + 'excel' + '%')......). There should have been "training" in the first group and "excel" in the second group.
It seems like NHibernate is using some sort of query caching for efficiency because the query signature is the same (since we're looping through all the words). Again, I have verified that both words are being used when stepping through my code.
Any ideas??
A: This must be the common pitfall "access to modified closure". Try
foreach (string word in words)
{
var wordLoopVariable = word;
matches = matches.Where(i => i.Subject.Contains(wordLoopVariable)
|| i.Background.Contains(wordLoopVariable)
|| i.Summary.Contains(wordLoopVariable)
|| i.Organization.Contains(wordLoopVariable)
|| i.Locations.Any(l => l.Organization.Contains(wordLoopVariable))
|| i.Locations.Any(l => l.City.Contains(wordLoopVariable))
);
And do some googling on closures.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to embed youtube video into a facebook iframe app? I wanted to make a facebook app with an image which has 2 buttons and under the image there would be a video from youtube. But since coding is new to me I need your help. I tried different codes but none of them worked. the video is not appearing at all.
And heres the final code I came up with:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com /2008/fbml">
<script type="text/javascript">
function framesetsize(w,h){
var obj = new Object;
obj.width=w;
obj.height=h;
FB.Canvas.setSize(obj);
}
</script>
</head>
<body onload="framesetsize(520,3300)"> <!--specify the height and width for resize-->
<div id="fb-root">
<div align="center"><img src="http://fb.joma-sport.hu/jomafiuk4.jpg" width="520" height="390" border="0" usemap="#Map" /></p>
<map name="Map" id="Map">
<area shape="rect" coords="133,74,246,335" href="2.htm" target="_self" alt="Total fit" />
<area shape="rect" coords="248,43,414,339" href="3.htm" target="_self" alt="Aluminio" />
</map></div>
</div>
<iframe title="YouTube video player" width="650" height="390" src="http://www.youtube.com/watch?v=wUaxZLJ0-28" frameborder="0" allowfullscreen></iframe>
</div
</div>
<!--this div is required by the Javascript SDK--><script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
swfobject.registerObject("FlashID");
</script>
</body>
</html>
<body>
</body>
</html>
Any help would be appreciated!!!!
12minutes later.....BAAAAAH got the answer..Thanks anyway.. :)
A: The solution:
On youtube click the Share button (which is under your video), than click the Embed button. After that you'll get the code which you write in your HTML. I also checked Use old embed code, and I used that code in my HTML. Sorry if this wasn't clear. My first language is not English..but I hope I could help/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you display all values in an object? This is a Mongoid object, but I think it applies for all objects. How do I split up @product into key, value pairs when @product looks like this:
#<Product _id: 4e7cd178e66de72d70000010, _type: nil,
created_at: 2011-09-23 18:35:36 UTC,
updated_at: 2011-09-23 18:35:36 UTC, brand: "crystalrock",
name: "Crazy Fool Specialty Tank", retailer: nil, model: nil,
sku: nil store: {"id"=>"36033", "name"=>"Ed Hardy"},
product_id: "684", sku_number: "D9WAFDCR", category_primary: "Tanks">
I would think it would be a object method, but I don't see one that works.
A: It looks like @product.attributes is a Mongoid method that works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Designing an event-driven head-tracking library in C++ I want to provide my team with a very simple C++ interface to OpenCV head tracking.
What architecture is best for this application?
Should I provide an "event-driven" API or should I make the client query this library whenever it wants a head position (yuck)?
Should I ask the client application to define callback functions? Can I do something similar to the [TUIO API in Processing][1], where you pass your class to a TUIO class and then the TUIO event dispatcher looks for your callback methods within that class (your class becomes a delegate)? What's the C++ way to do this?
What about just asking for a function pointer to a static method with a given signature?
Details
The specification would follow the lead of TUIO and Community Core Vision. Instead of blobs (fingertips on a touch-table) we're looking for heads with a Haar classifier. Each new head gets a persistent ID. Then we just dispatch three events: addHeadObject(id, x, y), removeHeadObject(id), updateHeadObject(id, x, y). Possibly with more parameters for communicating certainty, etc. The updateHeadObject event would happen at frame rate, up to 30 times per second. The update rate cannot be improved by increasing some polling rate, so that is why the frame event coming from the camera device must ultimately drive the API.
A: I will follow the delegation pattern used in the TUIO C++ interface. http://www.tuio.org/?cpp
MyHeadTrackerListener listener; // defines a listener
HeadTrackerClient client; // creates the client
client.addHeadTrackerListener(&listener); // registers the listener
client.connect(); // starts the client
As it says in the TUIO documentation:
Your application needs to implement the TuioListener interface, and
has to be added to the TuioClient in order to receive messages.
A TuioListener needs to implement the following methods:
addTuioObject(TuioObject *tobj) this is called when an object becomes
visible removeTuioObject(TuioObject *tobj) an object was removed from
the table updateTuioObject(TuioObject *tobj) an object was moved on
the table surface addTuioCursor(TuioCursor *tcur) this is called when
a new cursor is detected removeTuioCursor(TuioCursor *tcur) a cursor
was removed from the table updateTuioCursor(TuioCursor *tcur) a cursor
was moving on the table surface refresh(TuioTime bundleTime) this
method is called after each bundle, use it to repaint your screen for
example
My client will be required to implement some head tracking event callback methods. It seems simple according to this outline, but I didn't know if it was normal to do it this way in C++.
A: If the library is controlling the program flow, then callbacks are likely the easiest solution. Abstracting it as a coroutine would also transition well into a multi-threaded solution if you wanted. I offer this in terms of implementation and maintenance ease, not performance.
I have had success using boost::signal as the means to this end in the past, it is worth looking at.
Your public interface may be something equivalent, though perhaps a little more detailed. I would expect pure virtual interfaces for most of these classes, but for demonstration plain structs are a little easier to read.
struct Head {
int transient_id;
int x, y;
};
struct Frame {
std::vector<Head> heads;
};
struct HeadTracker {
boost::signal<void(const Frame &)> updates;
};
I am not certain you absolutely need to fire an event when a head enters or leaves relevance. The updates give x and y, so relevance changes are only the transient_id. If a client didn't know which transient_id it had, it could just request the details. Though it may be helpful to simplify processing.
I have some concerns about degrees of certainty with your identifiers, as they will theoretically (or maybe routinely) change. It isn't clear to me if you are tracking identity of specific people (transient_id #35523 is Jane Doe) or just whether that shape is a head.
If Jane stepped out of the door, then back in, there would be two different people per the system. This would simplify things and I would recommend modelling it this way behind the scenes anyway.
struct Head {
int transient_id;
int x, y;
float is_head; // [0.0, 1.0]
};
Identifying this round shape in the scene as a head is one problem which is somewhat binary. This should exist entirely independently of any belief in identity. If you only saw the back of someone's head the belief that the head belonged to any one person would evolve as time went on.
You could have a statistic for every person on each frame. That is a table of data, not a single value. Though you would probably only want to act upon a finite number of them at any given time.
struct Person {
int person_id;
std::string name;
};
struct Head {
int transient_id;
int x, y;
size_t getNumRanks();
std::pair<Person, float> getPersonWithCertainty(size_t rank);
};
struct HeadTracker {
boost::signal<void(const Frame &)> updates;
};
Putting the rankings in Head may be somewhat misleading (however convenient) depending on the system behavior. If you had history of past frames then it is probably accurate. If you only ever had one statistic at any given time, then it probably belongs in HeadTracker.
Computing the rankings seems like it would be pretty intense for a real-time system, but maybe it isn't. I'm not certain that is what you are talking about, but it's certainly fun to think about. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to force Google Maps Mobile to open in map view instead of list/text view? When I open a link with directions embedded (such as the one below) on a mobile phone, it defaults to text/list view instead of the map view, even when trying to use parameters in the URL to force it to map view.
http://maps.google.com/maps?saddr=(37,-122)&daddr=(37,-120)&hl=en&ll=36.971838,-121.003418&spn=3.651097,7.020264&sll=37,-122.25&sspn=0.456252,0.877533&geocode=FUCTNAIdgG26-A%3BFUCTNAIdAPLY-A&vpsrc=6&mra=ls&t=m&z=8&view=map
You can test this by either opening it on a mobile device, or forcing your browser's user agent to iphone/ipad. To do this with Chrome on a Mac, open the terminal and paste the following in:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome -user-agent="Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10"
Is there some way to force it to open into map view instead of list/text view?
I searched Stack Overflow and the Google API forums but was not able to find a solution (two other users asked similar questions, but they went unanswered and given I am new to the site it will not let me up vote their questions). Preferably there would be a way to do this via URL parameters, but I am open to other solutions as well.
A: This may not exactly answer your question, but after updating to iOS 6 I've had the same problem on existing iOS apps that referenced maps.google.com. I found the solution is to reference maps.apple.com (change google to apple in the URL). I tested this on iOS 6 Safari and found that the new URL works as expected and opens to the maps view in the new Apple maps whereas the old Google reference now opens to the list/text view as described in the OP.
I am guessing that when Apple ripped out the Google map library it caused the side-effect that the iOS version of Safari is now treated by Google as any other mobile platform.
Reference: Apple Safari Map Links
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Single row selection - UITableView Good Afternoon,
I'm trying to deploy my application in the selection of a single line in UITableView, but when I select another row, the previous line is not clear. I'm using images to represent the selection of the lines. I've tried to make each user's selection table rows stay with the image of deselection, but got no success.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *EditCellIdentifier = @"EditCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:EditCellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:EditCellIdentifier] autorelease];
UILabel *label = [[UILabel alloc] initWithFrame:kLabelRect];
label.tag = kCellLabelTag;
[cell.contentView addSubview:label];
[label release];
UIImageView *imageView = [[UIImageView alloc] initWithImage:unselectedImage];
imageView.frame = CGRectMake(5.0, 10.0, 23.0, 23.0);
[cell.contentView addSubview:imageView];
imageView.hidden = !inPseudoEditMode;
imageView.tag = kCellImageViewTag;
[imageView release];
}
[UIView beginAnimations:@"cell shift" context:nil];
UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:kCellImageViewTag];
NSNumber *selected = [selectedArray objectAtIndex:[indexPath row]];
imageView.image = ([selected boolValue]) ? selectedImage : unselectedImage;
imageView.hidden = !inPseudoEditMode;
[UIView commitAnimations];
UILabel *label = (UILabel *)[cell.contentView viewWithTag:kCellLabelTag];
label.text =[listOfItems objectAtIndex:[indexPath row]];
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
label.opaque = NO;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tv deselectRowAtIndexPath:indexPath animated:YES];
if (inPseudoEditMode) {
BOOL selected = [[selectedArray objectAtIndex:[indexPath row]] boolValue];
[selectedArray replaceObjectAtIndex:[indexPath row] withObject:[NSNumber numberWithBool:!selected]];
[tv reloadData];
}
}
A: I guess you want to allow only one row selected at a time.
Here is what I suggest in tableView: didSelectRowAtIndexPath::
Mark all row as not selected:
for (int i = 0; i < [selectedArray count]; i++) {
[selectedArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}
Then, mark the current row as selected:
[selectedArray replaceObjectAtIndex:[indexPath row] withObject:[NSNumber numberWithBool:YES]];
OR, do it all in the same for loop:
for (int i = 0; i < [selectedArray count]; i++) {
NSNumber rowSelected = [NSNumber numberWithBool:(indexPath.row == i)];
[selectedArray replaceObjectAtIndex:i withObject:rowSelected];
}
Hope this is what you want!
A: Shortest way which i use
for (int i = 0; i < [selectedArray count]; i++) {
[selectedArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:i==indexpath.row?YES:NO]];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: declaring protected variable in javascript How do i declare protected variable. Let me give an example here
// Constructor
function Car(){
// Private Variable
var model;
}
// Public variable
Car.prototype.price = "5 Lakhs";
// Subtype
function Indiancar(){
}
// Prototype chaining
Indiancar.prototype = new Car();
// Instantiating Superclass object
var c = new Car();
// Instantiating subclass object
var ic = new Indiancar();
in this I would like to have a variable that is accessible as ic.variabl that is also present in car class.
A: You would do something like this:
var Base = function()
{
var somePrivateVariable = 'Hello World';
this.GetVariable = function()
{
return somePrivateVariable;
};
this.SetVariable = function(newText)
{
somePrivateVariable = newText;
};
};
var Derived = function()
{
};
Derived.prototype = new Base();
var instance = new Derived();
alert(instance.GetVariable());
instance.SetVariable('SomethingElse');
alert(instance.GetVariable());
Assuming I understood your question correctly.
EDIT: Updating with true 'private' variable.
A: There is a way to define protected variables in JavaScript:
A constructor function in javascript may return any object (not necesserily this). One could create a constructor function, that returns a proxy object, that contains proxy methods to the "real" methods of the "real" instance object. This may sound complicated, but it is not; here is a code snippet:
var MyClass = function() {
var instanceObj = this;
var proxyObj = {
myPublicMethod: function() {
return instanceObj.myPublicMethod.apply(instanceObj, arguments);
}
}
return proxyObj;
};
MyClass.prototype = {
_myPrivateMethod: function() {
...
},
myPublicMethod: function() {
...
}
};
The nice thing is that the proxy creation can be automated, if we define a convention for naming the protected methods. I created a little library that does exactly this: http://idya.github.com/oolib/
A: As has been said, javascript doesn't have protected variables.
In the 10 years since this question was written, Typescript has become a thing, and people interested in OOP in javascript should check it out! It does support protected variables.
That said, I'd like to throw my hat into the ring and provide a method for emulating protected variables using plain javascript, since this is a top Google search result and the top-voted answer as of writing doesn't really fit the bill.
// Declare objects within an anonymous function to limit access.
var objectRefs = (function() {
// This is the object we want to inherit from.
function Base(param1, _protected) {
var _public = this;
var _protected = _protected || {};
var _private = {};
// Declare some variables
_public.shared = "Anyone can access this!";
_protected.inherited = "This is protected";
_private.secretVar = "Children cannot access this.";
// Let's try a few functions.
_public.foo = function() {
// We can access protected and private functions here. This would
// not be possible if we attached it to the prototype.
console.log(_protected.inherited);
console.log(_private.secretVar);
_private.secret();
};
_protected.bar = function() {
// One thing to watch out for: private functions called after
// construction do NOT have access to the object via 'this'. This is
// masked by the fact that I assigned it to the '_public' var.
// More reading: https://stackoverflow.com/q/20279484/3658757
console.log(_public.shared);
};
_private.secret = function() {
// The same warning in _protected.bar applies here too.
console.log(_public.shared);
};
}
// Inherits from Base
function Derived(param1, _protected) {
var _public = this;
var _protected = _protected || {};
var _private = {};
// Inherit (ready for the magic?)
Base.call(this, param1, _protected);
// Since we passed a reference to the "_protected" object as an argument
// to the Base object, it has been attaching all of its protected
// variables to it. We can now access those variables here:
// Outputs "This is protected"
console.log(_protected.inherited);
// We can also access protected functions:
_protected.bar();
// We can even override protected variables and functions.
_protected.inherited = "New value!";
// We cannot access private variables belonging to Base.
// This fails:
// console.log(_private.secretVar);
}
// We don't want to allow public access to the constructors, because this
// would let outside code pass in a '_protected' var. Instead, we create new
// objects that accept all params minus '_protected', and inherit from the
// target object.
return {
Base: function(param1) {
Base.call(this, param1);
},
Derived: function(param1) {
Derived.call(this, param1);
}
};
}());
// Assign the constructors to variables for clarity.
var Base = objectRefs.Base;
var Derived = objectRefs.Derived;
// This is how you construct the object.
var newDerived = new Derived("param1");
// Public functions are accessible.
newDerived.foo();
// Protected functions are not. These fail:
// newDerived.bar();
// newDerived.protected.bar();
So that was fun! This structure makes protected variables function the way you'd expect: inheriting objects can access them, but they're inaccessible from the outside.
For reference, here's what the above code looks like in Typescript:
class Base
{
// Declare some variables
public shared: string = "Anyone can access this!";
protected inherited: string = "This is protected";
private secretVar: string = "Children cannot access this.";
constructor(param1: string) {
// We're not using param1; it's only there as an example.
// If we didn't need any constructor code, we could leave this out.
// Note that Typescript has type checking (hence the name)
}
// Let's try a few functions.
public foo(): void {
console.log(this.inherited)
console.log(this.secretVar)
this.secret();
}
protected bar(): void {
console.log(this.shared);
}
private secret(): void {
console.log(this.shared);
}
}
class Derived extends Base {
constructor(param1: string) {
super(param1);
// Outputs "This is protected"
console.log(this.inherited);
// We can also access protected functions:
this.bar();
// We can even override protected variables and functions.
this.inherited = "New value!";
}
}
// This is how you construct the object.
var newDerived = new Derived("param1");
// Public functions are accessible.
newDerived.foo();
// Protected functions are not. This fails:
// newDerived.bar();
Structurally, this is much clearer. As you're coding, you'll be given an error if you try to access a protected variable from outside the object.
But be aware: if you need the compiled javascript to limit outside access to those variables, Typescript won't do that for you. Here's what the compiled output looks like:
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Base = (function () {
function Base(param1) {
this.shared = "Anyone can access this!";
this.inherited = "This is protected";
this.secretVar = "Children cannot access this.";
}
Base.prototype.foo = function () {
console.log(this.inherited);
console.log(this.secretVar);
this.secret();
};
Base.prototype.bar = function () {
console.log(this.shared);
};
Base.prototype.secret = function () {
console.log(this.shared);
};
return Base;
}());
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived(param1) {
var _this = _super.call(this, param1) || this;
console.log(_this.inherited);
_this.bar();
_this.inherited = "New value!";
return _this;
}
return Derived;
}(Base));
var newDerived = new Derived("param1");
newDerived.foo();
As you can see, not only are the protected variables public, but so are the private ones!
If you need encapsulation in the browser, then you'll have to stick with workarounds like I outlined in the first chunk of code. If you're using encapsulation to help you reason about the code, Typescript is the way to go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: web services and custom soap handlers I want to know if we can we publish web services just with the help of wsdd file? I have a custom made wsdd file and if i deploy it in tomcat then my web services will be published.
I want to know how it works without wsdl file ? then i want to know how to provide our own custom soap handlers instead of axis handlers .anyone who has worked on this.
A: Well with Axis (as well as CXF) you can either have your wsdd/wsdl file and from there the framework will generate the necessary mapped classes, needing only for you to implement the actual business logic (contract first), or you can create your business logic classes and your data model classes, annotate them, and from there the framework will autogenerate the wsdd and/or wsdl file (contract last):
http://www.developer.com/design/article.php/3745701/Enterprise-Java-Contract-First-vs-Contract-Last-Web-Services.htm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Aliasing singleton method in a module I have a module called Setup and want to alias a method.
This is how it looks, but how it doesn't work:
module Setup
def Setup::option_set?(option)
#...
end
alias :option_set? :get_information
end
I guess it has to do with the Setup::-prefix. What to do?
A: module Setup
class << self
def option_set?(option)
#...
end
alias :get_information :option_set?
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: LINQ to XML. Enumeration yielded no results I'm having trouble populating an object from an XML file. I've copied an example I've found almost exactly, with variable names changed, but I keep getting the "Enumeration yielded no results" exception.
Here is my code:
Dim element As XElement = XElement.Load(path)
Dim itemProps = From p In element...<Property> _
Where p.<LanguageCode>.Value = "en_us" _
Select p.<Title>.Value, p.<Description>.Value
Using breakpoints, I have confirmed that the 'element' variable is being properly populated using the XElement.Load(path) method.
Here is the XML file that is being accessed:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Items>
<Item ItemID="1">
<Property ItemPropertyID="1">
<Title>Title1</Title>
<Description>Description1</Description>
<LanguageCode>en-us</LanguageCode>
</Property>
</Item>
<Item ItemID="2">
<Property ItemPropertyID="2">
<Title>Title2</Title>
<Description>Description2</Description>
<LanguageCode>en-us</LanguageCode>
</Property>
</Item>
<Item ItemID="3">
<Property ItemPropertyID="3">
<Title>Title3</Title>
<Description>Description3</Description>
<LanguageCode>en-us</LanguageCode>
</Property>
</Item>
<Item ItemID="4">
<Property ItemPropertyID="4">
<Title>Title4</Title>
<Description>Description4</Description>
<LanguageCode>en-us</LanguageCode>
</Property>
</Item>
<Item ItemID="5">
<Property ItemPropertyID="5">
<Title>Title5</Title>
<Description>Description5</Description>
<LanguageCode>en-us</LanguageCode>
</Property>
</Item>
<Item ItemID="6">
<Property ItemPropertyID="6">
<Title>Title6</Title>
<Description>Description6</Description>
<LanguageCode>en-us</LanguageCode>
</Property>
</Item>
</Items>
Essentially, the XML query is supposed to return the title and the description for every Property which has an element called Language Code, which is equal to "en-us". I have a feeling that my problem lies in my XML code.
A: This language code:
en_us
should be:
en-us
A: Try taking one of the dots out of
Dim itemProps = From p In element...<Property>
Your going 3 levels down, when you only need to go down 2.
If that doesn't work try just one dot, because essentially the path your travelling is only 1 below the root of the document.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to determine if element is last or first child of parent in javascript/jquery? I have the following code, emulating a click on the left or right key down events. This is used as part of a gallery slideshow:
$(document).keydown(function (e) {
if(e.keyCode == 37) { // left
$(".thumb-selected").prev().trigger('click');
}
else if(e.keyCode == 39) { // right
$("thumb-selected").next().trigger('click');
}
});
Essentially it picks the next or previous sibling (depending on the key pressed) and call the click event that will in turn display the appropriate image in the gallery. These images are all stored in a unordered list.
Where I am stumped is that when the first or last image is selected and the left or right button is clicked (respectively), I want it to get the next picture at the opposite end of the list of images. For example, if the first image is selected and the left arrow is pressed; given that there is no previous image (or li element), it will get the last image in the list. This way the keys never lose functionality.
Is there a function in jquery that will either check if the present element is the first or last child of its parent, or return its index relative to its parent so I can compare its index to the size() (child count) of his parent element?
A: You can use the is()[docs] method to test:
if( $(".thumb-selected").is( ':first-child' ) ) {
// whatever
} else if( $(".thumb-selected").is( ':last-child' ) ) {
// whatever
}
A: You can do this in native JavaScript like so:
var thumbSelected = document.querySelector('.thumb-selected');
var parent = thumbSelected.parentNode;
if (thumbSelected == parent.firstElementChild) {
// thumbSelected is the first child
} else if (thumbSelected == parent.lastElementChild) {
// thumbSelected is the last child
}
A: You could use index() which returns the index of the element or you could use prev() and next() to check if there is one more element.
if(e.keyCode == 37) { // left
if($(".thumb-selected").prev().length > 0)){
$(".thumb-selected").prev().trigger('click');
}else{
//no more elements
}
}
else if(e.keyCode == 39) { // right
if($(".thumb-selected").next().length > 0)){
$(".thumb-selected").next().trigger('click');
}else{
//no more elements
}
}
EDIT - i updated the code because it makes more sense to use next() and prev() instead of nextAll() and prevAll()
A: var length = $('#images_container li').length;
if(e.keyCode == 37) { // left
if($('.thumb-selected').index() > 0)
$(".thumb-selected").prev().trigger('click');
else
$('.thumb-container').eq(length-1).trigger('click');
}
else if(e.keyCode == 39) { // right
if($('.thumb-selected').index() < length-1)
$("thumb-selected").next().trigger('click');
else
$('.thumb-container').eq(0).trigger('click');
}
.thumb-container is the parent element of the all the thumbs. At least what I got from your code.
HTML
<ul class="thumb-container">
<li>thumb</li>
<li>thumb</li>
.
.
.
</ul>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Adobe AIR application: Installation shortcut How do I get the Adobe AIR installer that I exported from Flash Builder 4.5 install shortcut to the application on the "all users" desktop on Windows?
A: You can't force it, the user must select it during installation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to run java code with Apache Ant Here is a part of my build.xml:
<target name="run">
<java jar="${jar.dir}/${Main.class}.jar"
fork="yes"
<assertions>
<enable />
</assertions>
</java>
</target>
or
<target name="run">
<java classname="${Main.class}" classpath="${classes.dir};${lib.dir}" fork="yes"/>
</target>
Here is an example java code:
public class Test {
public Test() {
System.out.print("Test2");
}
public static void main(String[] args) {
System.out.println("Test1");
new Test();
while(true) {}
}
}
If I run this code from command line I have "Test1" and then "Test2".
If I run this code using the Ant I have only "Test1".
How can I solve this problem?
A: You'll probably find that Ant buffers the output to System.out of your program by line before printing to stdout, and because your program never terminates (the while (true) {}), Ant is waiting for the program to finish before flushing the output of the line. Try changing the Test constructor to use println and you'll see the output.
A: This should solve the problem.
System.out.flush();
Add it before you get into an infinite loop. (EDIT:) and after you call new Test()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to allow access to PHP methods according to user's role? I have a basic User model that satisfies all the needs of a generic user. I now need to create several different roles for the user, each with about 10-20 different methods that are unusable by the other roles.
Assume that I have to load the generic User class to determine the user's role...
Since it's inefficient and heavy to package so many different role-based methods into the generic User model (when they can't be utilized by all roles), what is the best way to give user's access to their role-based methods ONLY when they need them?
Here are some ideas I'm tossing around:
*
*Have a separate class of services per role, and give them to the User class according to the user's role
*Simply lug around all the methods in the user class, and only allow access to each when the user has the correct role.
*Totally refactor and make the role based classes inherit from the User class.
Are any of these good ideas, or is there a better idea at all?
A: Why not just composition the role based classes into the User object?
$user = new User(/* pass role as an arg */);
// Internally:
// if ($user->getRole() instanceof AdminRole) or similar...
if ($user->isAdmin()) {
// AdminRole::doSomethingAdminish()
$user->getRole()->doSomethingAdminish();
}
A: Take a look at the factory pattern. Essentially, you pass it the data required to instantiate the object, and it returns the correct object in a ready to use state.
Perhaps something like
class UserFactory
{
public static function getUser($userId)
{
$user = new User($userId);
switch ($user->getType()) {
case 'admin' :
return new AdminUser($user);
case 'guest' :
return new GuestUser($user);
default :
//handle
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why would a website not load? I went to a web page and it would not load. The browsers, Chrome and Firefox both said “Waiting…” and never gave an error or page can’t load, just continually said “Waiting…” In fact, in Chrome it was like that for over thirty minutes and never did load. I could load other websites with no problem; I thought there was something wrong with the website on the server.
Unfortunately I did not think to try it in IE at that time.
My Firefox browser’s cache I had been cleaning frequently, almost daily (localhost developing, nothing major). So when I posted the original question; a very bright, unselfish and polite Stackoverflow member suggested I clean my cache (remove the cookies, etc..) I did. And the page loaded. Same with Chrome. After all that, I did try it in IE and it loaded.
The web page was a simple one page with one image 950x648 pixels.
Why would that happen? I want to rule out the server side, but I had never experienced that before. (At least I don’t think so…) Could it be my internet connection, my router? My computer? Some settings? I'm leaning towards my computer, but where do I start to diagnosis this, if it is.
Is this the right section of the site to ask this question? Is there another site I should consider to ask this question?
UPDATE
Given the excellent resources listed below, I am ruling out the website and server. I will focus on the browsers and watch for this anomaly to repeat. Any thoughts, or course of action, would be greatly appreciated. Thx.
A: Perhaps try this site:
http://www.downforeveryoneorjustme.com/
A: It loads perfectly for me, must be your browser/network setup. Try opening Terminal (or Command Prompt) and executing ping eastsidepropertysolutions.com. If you get a reply then the connection from your network to the website is fine, most likely indicating a browser issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does this toggle checkbox function work in jQuery 1.3.2 but not in 1.6.2? This code simply toggles checkboxes and adjusts text box css. By default, the text box is readonly, then when you click the checkbox it should adjust the readonly and highlight the text box.
The following code works fine in 1.3.2, but doesn't do anything in 1.6.2. Has something changed?
$(document).ready(function() {
$("#toggleAll").click(function() {
var $checkBoxes = $("input:checkbox.closeItem");
$checkBoxes.attr("checked", $(this).attr("checked"));
$("input:checkbox.closeItem").each(function() {
HandleCheckboxCheck($(this));
});
});
$("input:checkbox.closeItem").click(function() {
HandleCheckboxCheck($(this));
});
});
function HandleCheckboxCheck($check) {
var $trackingNumber = $check.parent().siblings("td.trackingNumber").children(0);
if ($check.attr("checked") == true) {
$check.attr("checked", true);
$trackingNumber.addClass("highlight");
$trackingNumber.removeAttr("readonly");
$trackingNumber.val("");
} else {
$check.attr("checked", false);
$trackingNumber.removeClass("highlight");
$trackingNumber.attr("readonly", "readonly");
$trackingNumber.val("Check to Enable");
}
}
A: .prop is the proper way to toggle checkboxes.
http://api.jquery.com/prop/
The behavior of .attr is covered in this section:
$(elem).attr("checked")(1.6) "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked")(1.6.1+) "checked" (String) Will change with checkbox state
$(elem).attr("checked")(pre-1.6) true (Boolean) Changed with checkbox state
A: In jQuery 1.6.2, testing .attr('checked') for a checkbox returns "checked" or undefined: http://jsfiddle.net/wkDgv/5/
In jQuery 1.3.2, it returns true or false: http://jsfiddle.net/wkDgv/4/
Your sample code asks if ($check.attr("checked") == true) -- which never occurs in jQuery 1.6.2. http://jsfiddle.net/wkDgv/6/
However, if you replaced that code with just if ($check.attr("checked")), you should get identical results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Comparator throws strange ClassCastException: pkg.MyClass cannot be cast to pkg.MyClass I am using a Comparator to sort a List<Entity> by it's property (of type Date) in viewscoped managed bean.
The problem is that I keep getting the ClassCastException as follows -
java.lang.ClassCastException: pkg.db.BaseArStatus cannot be cast to pkg.db.BaseArStatus.
Why is it not able to cast BaseArStatus to BaseArStatus? Is it because BaseArStatus is an Entity?
The problem is really strange to me because I am not getting the exception every time. Most of the it works fine (runs without any problem) when build and deploy the application but sometimes (even though I am doing the same thing - build and deploy) it fails at runtime with the ClassCastException.
Why is this happening only sometimes and not all the time? Is it because I am using it in managed bean?
This is how the managed bean looks like -
@ManagedBean
@ViewScoped
public class MyBean {
@PersistenceContext(unitName = "myPU")
private EntityManager em;
public void myMethod() {
List<BaseArStatus> basList = this.fetchAllBaseArStatus();
Collections.sort(basList, new Comparator<BaseArStatus>() {
@Override
public int compare(BaseArStatus o1, BaseArStatus o2) {
return o1.getMonthDate().compareTo(o2.getMonthDate());
}
});
//...
And the entity BaseArStatus -
@Entity
@Table(name = "base_ar_status")
@NamedQueries({
@NamedQuery(name = "BaseArStatus.findAll", query = "SELECT b FROM BaseArStatus b")})
public class BaseArStatus implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@NotNull
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Column(name = "month_date")
@Temporal(TemporalType.DATE)
private Date monthDate;
@Basic(optional = false)
@NotNull
@Column(name = "ar_count")
private double arCount;
@Size(max = 50)
@Column(name = "user_id")
private String userId;
@Column(name = "last_update_date")
@Temporal(TemporalType.TIMESTAMP)
private Date lastUpdateDate;
public BaseArStatus() { }
//...
A: Two different classloaders are loading two different copies of the class. When client code "familiar" with one copy of the class gets an object that's an instance of the other copy of the class, this is what you get.
The problem will only occur if the class has been loaded by both classloaders. This can make it seem intermittent; depending on events you often have no control over, one of the classloaders may or may not have loaded the class. In my experience, this is a problem most commonly seen in Java EE programming, which, of course, is what you're doing.
A: Definitely sounds like a comparison between classes loaded by different ClassLoaders. You can use the Class.getClassLoader() method to confirm on deny this for us. Catch the Exception and print whether or not classA.getClassLoader() == classB.getClassLoader().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Struts 2 Custom Exception Handling I am a newbie to Struts 2. I am using the Apache Struts 2 documentation for learning Struts 2.
I need a tutorial for custom exception handling in Struts 2; where should I look?
A: I recommend the guides; they cover most functionality, including exception handling.
The nutshell version is that the "exception" interceptor handles Struts 2 declarative exception handling. You can declare both global and exception-specific exception handlers. Each specifies the exception to handle and the result to be returned if the exception is caught:
<!-- Here the results are expected to be global results. -->
<global-exception-mappings>
<exception-mapping exception="java.sql.SQLException" result="SQLException"/>
<exception-mapping exception="java.lang.Exception" result="Exception"/>
</global-exception-mappings>
<!-- Here an action configuration adds an addition exception handler. -->
<action name="DataAccess" class="com.company.DataAccess">
<exception-mapping exception="com.company.SecurityException" result="login"/>
<result name="SQLException" type="chain">SQLExceptionAction</result>
<result>/DataAccess.jsp</result>
</action>
If you have further questions after that, you'll need to be more specific.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Manage timeouts for multiple UDP sockets I have to write a TFTP (Trivial File Transfer Protocol) server on Windows and Linux for a university course. I'm using C++ and I want to use one thread and select() to check for new incoming packets. TFTP requires that if a packet is not acknowledged for a certain amount of time, that the packet is re-sent. I'm wondering what the best way is to manage these multiple timeouts.
I was thinking about creating an std::list, which contains objects that associate a connection with the absolute time at which the timeout occurs. The list is ordered by increasing timeout times (all timeouts are the same when they are assigned, so a new timeout is always the greatest and can go to the end of the list - otherwise I would need a map instead of the list).
Since I need to reset the timeout for a connection, if a packet arrives in time, I want to create an std::map that associates a connection with an iterator pointing to its place in the list. When a connection's timeout is updated the element in the list can be found quickly, updated and moved to the end of the list (again assuming that a new timeout is the greatest).
Is this a good way to handle the problem or is there anything simpler?
A: If I understand it correctly, you have pairs of connection/timeout, and you want to be able to access those pairs by connection as well as by timeout.
By connection because you have to change the timeout when you receive a packet, and by timeout because you need to know what is the next connection to timeout.
If you have nothing against boost, take a look at multi_index.
If you want to roll your own, you may keep two sets of pointers, giving to the set different comparison functions:
class Connection {
...
public:
int GetTimeout() const;
int GetID() const;
};
class TimeIsLess {
public:
bool operator()(const Connection*c1, const Connection*c2) const {
return c1->GetTimeout() < c2->GetTimeout();
}
}
class IdIsLess {
public:
bool operator()(const Connection*c1, const Connection*c2) const {
return c1->GetId() < c2->GetId();
}
}
std::set<Connection*,TimeIsLess> connectionsByTime;
std::set<Connection*,IdIsLess> connectionsById;
To create a connection:
...
Connection * c = new Connection(id, timeout);
connectionsByTime.insert(c);
connectionsById.insert(c);
...
To get the next connection that will timeout, just get the first one:
auto nextToTimeout = connectionsByTime.begin();
if (nextToTimeout != connectionsByTime.end())
{
if ( (*nextToTimeout)->GetTimeout() < now )
{
// Close the connection
}
}
To remove a connection, you'de have to remove the pointer from one set, and remove AND delete the pointer from the other set.
I compiled none of it so don't nail me on the typos (:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: upload_max_filesize not reflected in phpinfo() In my php.ini file (there is only one on the system) I have
post_max_size = 8M
upload_max_filesize = 8M
upload_max_size = 8M
Originally they were set to 2M. I changed them to 8M restarted apache, even restarted instance. But when I do a phpinfo() on it, it still shows 2M.
I am pretty sure I have the right php.ini file because if I increase the max_execution_time it is reflected in the phpinfo() but anything I put in for upload_max_filesize and post_max_size is not reflected in phpinfo() even though I double check php.ini and the settings are there.
This is a AWS Linux instance.
php5.2.16
apache 2.2.17(EL)
Any thoughts from the guru’s out there?
A: Do you have entries in Apache's .htaccess file that are overwriting the options?
They would look something like:
php_flag post_max_size 2M
php_flag upload_max_filesize 2M
php_flag upload_max_size 2M
Here's Apache's .htaccess documentation: http://httpd.apache.org/docs/1.3/howto/htaccess.html
A: If you are running in a local server, such as wamp or xampp, make sure it's using the php.ini you think it is. These servers usually default to a php.ini that's not in your html docs folder.
A: Please check if your php.ini file don't have any errors. php.ini takes all default values after error line.
I was having same issue, I fixed after removing errors from php.ini.
Hope this help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Basic subversion server question on a development web server I've just set up a development web server, where people will be testing out some changes before making these changes on the production web server. Currently the web development team is used to using subversion to make their changes on the production server. I'd like to set up a SVN server on the development web server as well.
My question is this: How can I make it so subversion stores the repository in the Apache document root, so that files they check into the repository will go right into the docroot and be served by the web server.
As I have it set up now, it seems that when files are commited, they turn into virtual files in the svn repo directory (only visible with "svn ls file:///repo/file" rather than just "ls /var/www/file".
Thank you
A: That's not how subversion works. It doesn't normally store files in a format that's directly accessible. What you want to do is add a post-commit hook that will update a checked-out copy in the web directory. Google search for "subversion post-commit update" for more information.
A: You can control your source code using subversion, but the real issue is that you are changing your installation and then archiving it instead of the "normal" development routine; which is to make your changes and THEN install the changes.
The best method would be to keep the subversion server far away from the production web server. Your development box checks in changes to the subversion server. A single "special" build user checks out all the subversion stuff and makes a zip file (or something more appropriate) and that "zip file" is then copied to the production server and "installed".
This will give you more flexibility in deploying to your web server, and it will allow you to test changes on other non-critical web servers (if you ever decide to get so fancy) before you deploy to the production server. It will also prevent you from having mistakes that get checked in directly taking down the web server (as you can opt to not deploy a build to the web server while you check in subsequent "fixes" for the introduced mistakes).
Either way, you can use crontab or some other cron-like functionality to do a "nightly" package, etc. The key isn't to create more work that a person has to do, it's to create more work that automated programs can do simply so you have more security in the event of eventual upsets. Your role should be to decide if you want to install "this" package, and to run the command (or two) to install it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Prevent freezing during reconstruction of complex WPF UI? OK lets face it, during render and a layout pass a WPF UI will freeze....
Any escape from this?
Someone talked about XAML serialization and Desrialization but does it really work? All I see is a momentary lapse and frozen window for complex UIs which are deserialized.
Will I ever be able to achieve swift UI loading?
P.S. I am not talking about loading view data on background thread and stuff. It is anyways a norm now-a-days. But is there ANY (this should sound desperate) way to not produce a hanged Window for complex UIs? By complex I mean heavy styles, deeply hierarchical templates, non virtualized panels etc.
A: Given the fabula of your question you're expecting an answer from Rob Relyea at very least (not sure if he's still in). I wish we have a property PreventFreezing, set by someone rather carelessly to false. But we aren't. I think the only way to look at the problem is to look at it on case per case basis. Some frameworks i.e. Prism and alikes sipmly aren't designed to support smooth execution, and it's clearly stated in the description.
After 5+ years of dealing with WPF/SL I still have feeling that we're all working with a prototype, well designed one, but still a prototype. A lot of things are designed nicely, but designed to never meet performance deadlines.
I think, that 'Adding futures w/out caring too much about anything else' is a very natural stage in a lifecycle of any large probject. During this stage the number of futures grows expotentially, so the technical debt does. This is all good stuff as long as it gets followed by the technical debt repayment, which didn't seem to happen with WPF -i.e. performance review, syntax usability review and more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: small excel macro-enabled file takes 5 minutes to open on a fast computer, why? I have an unbelievably slow opening excel 2007 macro-enabled workbook that is only 950kb in file size. It’s got 2 worksheets, one is empty, and the other has about 1,000 records spanning 10 columns. The file also contains 3 short macros, one of them being a web data query. I’m trying to figure out why the file opens so slow (like 5mins). If it's the web data query macro code, I would like to know why.
A: Well the simplest way to determine if its the web query, would be to:
- cache the web query data
- turn off the web query
- have the code populate from the cached data
- restart the sheet and time it.
If it's noticeably faster then you can probably blame the web query.
A: Do you have a ton of formulas in it? If you do and have them on Auto-Calculate it can cause a myriad of issues with being slow.
Also VBA likes to generate a lot of garbage if you change code a lot. You might try creating a new sheet and copying and pasting everything into the new one and delete the original. It'll start fresh. You won't be able to see the garbage that VBA kept around but it's decently well documented.
There is a free add-on for it somewhere on the web, just Google "VBA Code Cleaner"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: A design pattern for large conditions in a conditional I'm rewriting a beast of a program that does everything and it's kitchen sink. It's a phone IVR system (press 1 to blah blah, press 2 to...) I've got all of it's functions divvied up into their own projects, however my one biggest pain point comes right when we first answer the phone and have the user enter a code that lets us know what system to dispatch the caller to.
The whole code system is a mess TBH, but it can't be changed, and I've refactored about 800 lines of VB6 down to something that resembles the following code:
string code = foo.GetAccessCodeFromCaller();
if (DatabaseCheck1(code)
{
parse = ParseCode(code);
dbValue = GetSomethingFromDB(parse);
if (OtherCheck1(dbValue)
{
// Launch the Pay Taxes project.
}
else if (OtherCheck2(dbValue)
{
// Launch the Uploaded File project
}
else
{
// Schedule Something or other project
}
}
else if (LookForSomethingElseInDB(code)
{
parse2 = AltParseMethod(code)
if (Conditional(parse2))
{
if (LargeChunkOfCodeConditional(code))
{
// Report a something or other project.
}
else
{
// Talk to Tech Support.
}
}
else
{
// Invalid Input
}
}
else
{
if (YetAnotherChunkOfCode(code))
{
// Order products project
}
else
{
// Invalid Input.
}
}
I need a good architecture to get this system done right, where right equates to being highly adaptable to getting more crap shoe horned in to it. The original system was done in VB4/5, and lasted through over 16 years of near monthly changes. I want something that'll keep this mess orderly and make it easy to add crap to for the next 16 years.
So far I've tried a few patterns (Visitor, and Command), but nothing seems to be a good fit the way I tried to implement it. Any suggestions here would be very appreciated.
EDIT:
To be a bit more clear my current architecture has a solution with the following projects: Dispatch, PayTaxes, UploadedFiles, ScheduleSomething, ReportSomething, TechSupportRedirect, OrderProducts ect... (along with HardwareAbstraction, SharedInterfaces, and DatabaseAccess projects). Dispatch uses the HardwareAbstraction project to answer the phone and ask for the callers code, then routes the call to one of the other 10 projects that perform wildly different tasks (and can then be rewritten in parallel by 10 different developers without toes getting stepped on).
I can figure out the architectures of the destination projects well enough, but the actual Dispatch project is tripping me up. Also if my whole solutions architecture is some sort of anti-pattern someone let me know before I get too far.
A: Maybe what you need is just a simple ExtractMethod to exclude large inner bodies of conditionals to separate methods.
A: I don't know anything about VB6, but how about mapping the codes to "delegates" (dunno if that concept exists in VB6). The idea is: the input-code is a "key" to a dictionary returning the method to invoke (or Empty/Null/Nothing if no such code found).
UPDATE:
If this is written in C#, couldn't you just put the codes into a
Dictionary<string, Action> OpCodes;
Then do something like:
if(OpCodes.ContainsKey(code))
OpCodes[code]();
UPDATE 2:
It seems you have "layers" of conditionals. I guess this would map to "Dictionaries of dictionaries". But thinking about the problem: User types a sequence of choices, which should wind up in a certain behaviour, sounds like: Define "delegates" for each system behavior, and map to codes:
Like:
OpCodes["123"] = new Action(TechSupport.StartConversation);
A: Thanks to everyone that chimed in here, due to the suggestions I got past a few mental blocks and found that the chain of responsibility pattern will nicely solve my problem.Here's the MSDN article on how to implement it.
A: If you rewrote it to create different classes to handle the different codes it would probably make your codebase more maintainable.
Something like
var codeHandler = CodeHandlerDecider.GetCodeHandlerFor(
foo.GetAccessCodeFromCaller());
codeHandler.HandleCode();
Then your CodeHandlerDecider would do something like this:
public static ICodeHandler GetCodeHandlerFor(string code)
{
if (DatabaseCheck1(code)
{
return new FirstCodeHandlerClass(code);
}
else if (LookForSomethingElseInDB(code)
{
return new SecondCodeHandlerClass(code);
}
else
{
return new ThirdCodeHandlerClass(code);
}
}
and then an example class would be
public class FirstCodeHandlerClass: ICodeHandler
{
public void HandleCode(string code)
{
parse = ParseCode(code);
dbValue = GetSomethingFromDB(parse);
if (OtherCheck1(dbValue)
{
// Launch the Pay Taxes project.
}
else if (OtherCheck2(dbValue)
{
// Launch the Uploaded File project
}
else
{
// Schedule Something or other project
}
}
}
and the interface would look like
public interface ICodeHandler
{
void HandleCode();
}
A: This sounds like a job for a Finite-State Machine! You could even get fancy and create an external DSL because state-machines are very ameniable to this. In fact I just found a project on codeplex that appears to use a phone system as their primary example.
A: There's two common patterns for this type of problem:
1) subclassing/inheritance to achieve polymorphic dispatch
2) table-driven programming
The basic idea is that you place the information that allows you to make a decision in a table, then write code that traverses the table. If you hold your head at a funny angle, polymorphic methods are just table-driven programming that is built directly into the language. Table-driven techniques offer you these benefits: more declarative, smaller code size, easy to extend/add new cases, clearer.
As others have noted, you could implement this pattern with a Dictionary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's the best place to find Git reference content online while kernel.org is down? I like reading man pages nicely formatted in a browser instead of in my terminal console.
Until recently, any time I had to look up details of a Git command, I'd just Google the command (like "git reset") then hit the kernel.org link to the nicely formatted man page ( link www.kernel.org/pub/software/scm/git/docs/v1.7.1/git-reset.html)
Kernel.org's been down for a long time, and it's not clear whether/when it's coming back.
Fortunately the Google caches are still around. But is there another good place to find the Git command references?
A: It has been mirrored here: http://schacon.github.com/git/git.html, also check out http://gitref.org/
A: git subcommand --help is the best reference.
(this brings up the same man page in your browser that you would see in kernel.org)
A: You can follow instruction here: http://help.github.com/install-git-html-help/
That will install local versions of the html git man pages.
A: You can also launch your browser to the local version of the docs that are installed by git:
$ git help git -w
A: There's git-scm.org and the official Git Reference.
Another worthy site is Scott Chacon's community book ProGit
A: You could use an app like Bwana to bring your local man pages into your browser: http://www.bruji.com/bwana/
A: Don't forget the way back machine (archive.org). It is much better way to browse than Google Cache while a site is down.
http://wayback.archive.org/web/*/http://kernel.org
A: There's now an official online location for the Git man pages again - they're at:
*
*http://git-scm.com/docs
Now if only there were redirects from the old locations on kernel.org, that would stop the links on hundreds of StackOverflow answers being broken :(
Update: such redirects were requested on the git mailing list and Scott Chacon's reply indicates this is intended...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to log ssh debug info? I need to write the output of ssh debug info into the file. This
ssh -v root@172.16.248.xx > result.txt
ssh -v root@172.16.248.xx 2>&1 > result.txt
doesn't work, the file result.txt is empty, but on the screen i see bunch of debug lines, like:
OpenSSH_5.3p1 Debian-3ubuntu7, OpenSSL 0.9.8k 25 Mar 2009
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to 172.16.248.xx [172.16.248.xx] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
etc
Is there a way to redirect these lines to the file?
A: You have to change the order of the redirections on the command line:
ssh -v root@172.16.248.xx >result.txt 2>&1
or just:
ssh -v root@172.16.248.xx 2>result.txt
A: -E log_file
Append debug logs to log_file instead of standard error.
A: Apparently the best way to save this "hidden" debug output to the file is by using logsave:
logsave result.txt ssh -v root@172.16.248.xx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
} |
Q: Apache keepalive ratio Many web servers are faster when using keepalive, but of course,
the client must use this feature AND the user must generate more than one request in a row to be useful.
My question : For my web site, I use Apache, I would like to know how many requests has been done by using the keepalive versus those not using the keepalive.
I looked at the access.log file, but I did not found any clues : Do you know how can I get the information ?
A: Eric -- the default log format doesn't contain this info, but there's a %X format string that will tell you the status of the connection.
http://httpd.apache.org/docs/current/mod/mod_log_config.html
which you can add to a custom log format (also described on that page). There's another flag, %D which may also help -- measures time to serve the response.
This doesn't exactly tell you what you're looking for - you'll then need to group requests (probably by IP address within a few seconds of each other) so you can see what happened in an individual page load (that is, the html and subsequent requests for other files and assets).
But I can save you some time if you just want to know if keep-alive helps.
If your web page is pure text and contains no links to CSS or Javascript or images then keep-alive won't help. But that would be very, very unusual.
And, if you have a set of users who are locked in a time capsule, stuck with early versions of Netscape from 1995, then their user agents don't do HTTP 1.1. If you have users who live in modern times, their browsers support HTTP 1.1, and therefore will do keep-alive.
But actually, adding the additional item to the log is probably a good thing to do to satisfy your curiosity. I have had many people give me the kind of bland generalization I have provided here, but when I actually measured, found something far different than expected. So go for it!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery + AJAX + double calls I am building an ajax based navigation and everything works fine, except one thing:
When i look in Firebug I can see that on each click the ajax site gets called and loaded twice.
This is the script:
$(document).ready(function () {
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the main and show the progress bar
$('#main').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
//AJAX Navigation Helper function
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
//AJAX Navigation Helper function
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the main retrieved from ajax and put it in the #main div
$('#main').html(html);
//display the body with fadeIn transition
$('#main').fadeIn('slow');
//reload site scripts
$.getScript("js/script.js");
}
});
}
So whenever I click on a list in my navigation, the page gets loaded just fine into #main, but it happens twice (as displayed in Firebug). Any1 maybe has an idea why? :)
I noticed that it doesnt happen when i access a certain page by url (than it only does one ajax call), so I guess the problem is somewhere in the click function.
p.s. i am using the jquery history plugin, but I dont think the problem is there, or?
A: I'm going to guess that getPage is called twice. Put a debugger statement at the beginning of the function (debugger;) and open firebug to see if it is. Here's one way to fix the problem if it is getting called twice:
//AJAX Navigation Helper function
function getPage() {
if(getPage.isLoaded != true) {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the main retrieved from ajax and put it in the #main div
$('#main').html(html);
//display the body with fadeIn transition
$('#main').fadeIn('slow');
//reload site scripts
$.getScript("js/script.js");
}
});
}
getPage.isLoaded = true;
}
A: I believe your click event is bubbling to the anchor.
try:
$('a[rel=ajax]').click(function (event) {
//cancel the anchor tag behaviour
event.preventDefault();
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the main and show the progress bar
$('#main').hide();
$('#loading').show();
//run the ajax
getPage();
});
Edit: simply returning false won't cancel a jquery bound event.
Edit: @wildrot is right
A: Just speculating, but … Does the stuff you load via AJAX by any chance contain the same script again?
A: Just add
$('a[rel=ajax]').die('click').click(function (event) { -> will load once..
Hope this helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Animating gradients with jQuery This will be my list question today.. Is it possible to animate radial gradients in jQuery(using .animate), if yes how?
Example
background: -webkit-gradient(
radial, 50% 50% ,0, 50% 50%, 70, from(rgb(25,25,25)), to(rgb(50,50,50))
);
A: You can't do this by default in jQuery, you can't even animate flat colors without the corresponding plugin.
Animating gradients is tough because of the syntax differences between browsers. I wrote a plugin for a very specific case that may be useful to you. It's for a linear gradient but you can tweak it for radial.
jQuery.fx.step.gradient = function(fx) {
if (fx.state == 0) { //On the start iteration, convert the colors to arrays for calculation.
fx.start = fx.elem.style.background.match(/\d+/g); //Parse original state for numbers. Tougher because radial gradients have more of them
fx.start[0] = parseInt(fx.start[0]);
fx.start[1] = parseInt(fx.start[1]);
fx.start[2] = parseInt(fx.start[2]);
fx.end = fx.end.match(/\d+/g);
fx.end[0] = parseInt(fx.end[0]);
fx.end[1] = parseInt(fx.end[1]);
fx.end[2] = parseInt(fx.end[2]);
}
fx.elem.style.background = "-webkit-linear-gradient(rgb(" + [
Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")," + "rgb(0,0,0))";
}
$(this).animate({"gradient": "rgb(0, 255, 0)"});
DEMO.
You probably want to create two functions, one for the inner color (jQuery.fx.step.innerColor) and one for the outer (jQuery.fx.step.outerColor) which would be called like this:
$(this).animate({"innerColor": "rgb(25,25,25)",
"outerColor": "rgb(50,50,50)"});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Open Source Alternatives to ClearCase maybe my question is not paraphrased properly, so let me try to explain it.
I'm trying to investigate open source alternatives to ClearCase. One of the strengths of it is that it allows the logical partitoning of content into separate centralized version object bases (or vobs), which we can control access to. That is, the repository provides a unified view from an administrative point of view, and then we can assign access control rules that limit who can see/modify what in the repo.
Unfortunately, it's expensive... and many of its features suck. Overly complicated config spec language, the need to create a label type before applying a label, etc, etc. So, I'm looking for alternatives.
Has anyone reading this had any experience configuring and using an open source distributed version control system in such a manner? In particular with respect to applying access control rules on subsets of content in a repository (sized in terabytes)?
Same questions with respect to centralized open source alternatives.
Any first-hand experiences and from-the-trenches anecdotes will be greatly appreciated.
A: DVCS generally require that each developer have a complete copy of the repository so they can be poorly suited for such a large data set.
You might be able to make it work if most of the data is rarely updated. You would pay a steep penalty for initial checkouts, but smaller commits and updates might be reasonable. This is one area where centralized VCS with partial checkouts can be superior to distributed systems.
If there are logical divisions to the content, you could divide in to separate smaller repositories. Git & Mercurial allow you to create sub repositories, which make can make it easier.
Unless you need to block read access to some content, I think that the access controls are a non issue. Unlike a centralized system, you don't have to have one central repository for moving changes between developers. There are numerous workflows. You could have one senior developer who maintains a stable branch, and have them pull in updates from developers. You can have multiple public branches, in separate locations, and use standard network access controls who can push to each branch. The possibilities are endless.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does my storyboard that is within a DataTemplate not begin? I have a custom drawn 'Path' control with some texblocks inside making up a DataTemplate in Silverlight 4. I used the Animation window in Expression Blend to create a simple animation that I can 'play' and see work OK within Blend.
I want this animation to fire off on the '_MouseEnter()' event (VB.NET) I want to issue a .Begin method on the animation. Seems straight forward enough.
However at runtime nothing happens. I place a breakpoint on the _MouseEnter event and surely enough it goes into the event upon the mouse entering the control, it runs the line of code to begin animation but nothing happens. No exception, no animation, nothing.
Can anyone tell me what I am missing here since I know the actual animation does work, it just is not running at runtime? XAML and event are below (removed some styling properties on Texblocks, etc. to make easier to read):
<DataTemplate x:Key="MyItemTemplate">
<Grid Width="50" Height="80" Opacity="0.9"
RenderTransformOrigin="0.5,0.5"
ToolTipService.ToolTip="{Binding ItemName}">
<Grid.Resources>
<Storyboard x:Name="MyItemTemplateAnimate">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[4].(GradientStop.Offset)"
Storyboard.TargetName="path">
<EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0.296"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="0.384"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="0.475"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.6" Value="0.529"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="0.587"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.8" Value="0.652"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.9" Value="0.582"/>
<EasingDoubleKeyFrame KeyTime="0:0:1" Value="0.523"/>
<EasingDoubleKeyFrame KeyTime="0:0:1.1" Value="0.5"/>
/DoubleAnimationUsingKeyFrames>
</Storyboard>
</Grid.Resources>
<Grid.RenderTransform>
<CompositeTransform Rotation="180"/>
</Grid.RenderTransform>
<Path x:Name="path" Data="M 0,0 L 50,0 50,50 25,80 0,50 0,0" Stroke="Wheat" StrokeThickness="2">
<Path.Fill>
<LinearGradientBrush EndPoint="-0.419,0.662" MappingMode="RelativeToBoundingBox" StartPoint="1.051,-0.137">
<GradientStop Color="#FF250A0A" Offset="1"/>
<GradientStop Color="#FF250A0A"/>
<GradientStop Color="#FF501616" Offset="0.725"/>
<GradientStop Color="#FF501616" Offset="0.275"/>
<GradientStop Color="#FF9F4C4C" Offset="0.5"/>
</LinearGradientBrush>
</Path.Fill>
</Path>
<TextBlock x:Name="TextBlock1"
</TextBlock>
<TextBlock x:Name="TextBlock2"
</TextBlock>
</Grid>
</DataTemplate>
The code that uses the DataTemplate:
<m:MapItemsControl x:Name="MyItems" ItemTemplate="{StaticResource MyItemTemplate}"/>
And here is the VB.NET event:
Private Sub MyItems_MouseEnter(sender As Object, e As System.Windows.Input.MouseEventArgs) Handles MyItems.MouseEnter
MyItemTemplateAnimate.Begin()
End Sub
A: Since your storyboard is in an ItemTemplate there is going to be one storyboard per item. So I'm not sure why you're not getting an exception, but I believe this is a name scope issue.
If your animation is on the individual items why not start it when the mouse goes over the item itself instead of the itemscontrol?
A: Is the storyboards TargetProperty correct, because there you are using GradientBrush but in your path you have LinearGradientBrush. Just a wild guess. :)
A: I got it figured out:
Begin StoryBoard Animation Within A DataTemplate In Silverlight:
http://allen-conway-dotnet.blogspot.com/2011/09/begin-storyboard-animation-within.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating nav menu with nested content_tag ULs and LIs I'm a relative newbie to Rails, but wondering how to create a looping nav menu using content_tag. This should seemingly work, but I've seen that one must use concat inside of a content_tag loop. I feel that I've tried every possible avenue and and googled heartily. Any assistance would be much appreciated.
FYI:
*
*I pass @page.root to the right_nav function in my view in order to display the full branch from whatever section I may be in.
*for_menu checks to see whether a given page is supposed to be displayed in the menu.
Thanks.
def right_nav(page)
content_tag(:ul, :class => 'nav') do
if !page.children.for_menu.empty?
sub_nav(page)
else
concat content_tag(:li, link_to(page.title, page.path, :class=> current_menu_item?(page) ? 'current' : nil))
end
end
end
def sub_nav(parent)
content_tag(:li, nav_link(parent)) do
content_tag(:ul) do
parent.children.for_menu.each do |subpage|
if !subpage.children.for_menu.empty?
sub_nav(subpage)
else
content_tag(:li, nav_link(subpage))
end
end
end
end
end
def nav_link(page)
link_to(page.title, page.path)
end
A: instead of using each, maybe try using collect in your loop; that way the results are passed back up the chain.
A: The inner content_tag :ul is not getting a proper return value from each since each returns the collection that it was called on.
ruby-1.9.2-p180 :001 > [1,2,3,4].each {|n| n + 1}
=> [1, 2, 3, 4]
For something like content_tag you can use inject which will concat together all the li/sub_nav items and return that to the content_tag properly
def sub_nav(parent)
content_tag(:li, nav_link(parent)) do
content_tag(:ul) do
parent.children.for_menu.inject('') do |result, subpage|
if !subpage.children.for_menu.empty?
result + sub_nav(subpage)
else
result + content_tag(:li, nav_link(subpage))
end
end
end
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to process zip file with Python a.zip---
-- b.txt
-- c.txt
-- d.txt
Methods to process the zip files with Python,
I could expand the zip file to a temporary directory, then process each txt file one bye one
Here, I am more interested to know whether or not python provides such a way so that
I don't have to manually expand the zip file and just simply treat the zip file as a specialized folder and process each txt accordingly.
A: Yes you can process each file by itself. Take a look at the tutorial here. For your needs you can do something like this example from that tutorial:
import zipfile
file = zipfile.ZipFile("zipfile.zip", "r")
for name in file.namelist():
data = file.read(name)
print name, len(data), repr(data[:10])
This will iterate over each file in the archive and print out its name, length and the first 10 bytes.
The comprehensive reference documentation is here.
A: The Python standard library helps you.
Doug Hellman writes very informative posts about selected modules: https://pymotw.com/3/zipfile/
To comment on Davids post: From Python 2.7 on the Zipfile object provides a context manager, so the recommended way would be:
import zipfile
with zipfile.ZipFile("zipfile.zip", "r") as f:
for name in f.namelist():
data = f.read(name)
print name, len(data), repr(data[:10])
The close method will be called automatically because of the with statement. This is especially important if you write to the file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: i have 4 dropdowns and how can i edit and save the data mvc2 i have 4 drop-downs, insert is working and how can i edit the data and save the data to db mvc2. I got an error while update - The ViewData item that has the key 'SelectedTimeZone' is of type 'System.String' but must be of type 'IEnumerable
My Controller
public ActionResult Edit(int id)
{
return View(EventModel.Edit(id));
}
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Edit(int id, EventInfo EventInfo)
{
if (ModelState.IsValid)
{
EventModel.Edit(EventInfo);
return RedirectToAction("Index");
}
return View(EventInfo);
}
Model
public SelectList TimeZones { get; set; }
public SelectList EventType { get; set; }
private string selectedTimeZone = "";
public string SelectedTimeZone
{
get { return selectedTimeZone; }
set { selectedTimeZone = value; }
}
Load Function
myEventInfo.TimeZones = new SelectList(EventModel.getTIMEZOMES, "Key", "Value");
myEventInfo.SelectedTimeZone = Datareader["TIMEZONE"].ToString();
public static IList<KeyValuePair<string, string>> getTIMEZOMES
{
get
{
Dbhelper DbHelper = new Dbhelper();
IList<KeyValuePair<String, String>> Timezone = new List<KeyValuePair<String, String>>();
DbCommand cmd = DbHelper.GetSqlStringCommond("SELECT * FROM TMP_TIMEZONES");
DbDataReader Datareader = DbHelper.ExecuteReader(cmd);
while (Datareader.Read())
{
Timezone.Add(new KeyValuePair<String, String>(Datareader["ABBR"].ToString(), Datareader["NAME"].ToString()));
}
return Timezone;
}
}
View page
<%= Html.DropDownListFor(model => model.SelectedTimeZone, Model.TimeZones, "Select Timezone", new { style = "width:200px", @class = "textfield165" })%>
<%= Html.ValidationMessageFor(model => model.SelectedTimeZone)%>
I got an error while update / The ViewData item that has the key 'SelectedTimeZone' is of type 'System.String' but must be of type 'IEnumerable
A: In your POST action you forgot to populate the TimeZones property in case of error. Don't forget that only the selected timezone is POSTed, but not the list of timezones, so if you ever intend to redisplay the same view (for example in case of error) make sure you rebind this list (the same way you bound it in the GET action that allowed you to display the form on the first place):
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Edit(int id, EventInfo EventInfo)
{
if (ModelState.IsValid)
{
EventModel.Edit(EventInfo);
return RedirectToAction("Index");
}
// Here you must populate the TimeZones property before returning the view
EventInfo.TimeZones = new SelectList(EventModel.getTIMEZOMES, "Key", "Value");
return View(EventInfo);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: NSTableView only displaying "Table View Cell" I have a NSTableView with the delegate and datasource pointing to my controller. I have tried implementing the
- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
Method, but no matter what I return, the table always shows "Table View Cell" in the data. Any ideas of what I could be doing wrong? Attached are two pics showing that I have the delegates set properly (it also shows the proper number of rows).
Note that I have also just tried returning @"Hello World" for everything, but I get the same result.
A: Newer version of XCode:
*
*Select the table view (make sure the scroll view or any other view is not selected).
*On the right hand side, select the "Attribute Inspector"
*Change the Content Mode to "Cell Based" instead of "View Based"
*Save your changes and re-run the project.
A: Most of the responses involve converting the table view component to a cell-based table view. If that’s what you want then that’s fine, you’re good to go. At the time the question was asked, cell-based tables were the norm and when Apple changed the window component to a view-based one it obviously caused a lot of confusion. Today, Apple’s docs recommend that you should use view-based rather than cell-based tables.
The problem described in the question arises if you use - tableView:objectValueForTableColumn:row: in your datasource. You cannot use this method with view-based tables, it is only for cell-based tables. Instead you need to use the NSTableViewDelegate method - tableView:viewForTableColumn:row:. You don't need to make the object conform to the NSTableViewDelegate protocol to use this method but it must be set as the delegate of the table.
In response to Cœur, quoting from the Apple On-line docs.
NSCell-Based Tables Are Still Supported
In OS X v10.6 and earlier, each table view cell was required to be a subclass of NSCell. This approach caused limitations when designing complex custom cells, often requiring you to write your own NSCell subclasses. Providing animation, such as progress views, was also extremely difficult. In this document these types of table views are referred to as NSCell-based table views. NSCell-based tables continue to be supported in OS X v10.7 and later, but they’re typically used only to support legacy code. In general, you should use NSView-based tables.
A: Just change the Content Mode to Cell Based for the table view in IB. IB will display Text Cell as the cell placeholders, which are populated at runtime by whatever you return from tableView:objectValueForTableColumn:row:
A: Finally figured it out. My cells for some reason seem to contain both a TableCellView AND a text field cell. I removed the Table Cell View's and now everything is working. I have no idea how I got in that state.
A: It looks like you might be missing the all-important -numberOfRowsInTableView: data source method. See Table View Programming Guide: (View-based table view) The Required Methods and Table View Programming Guide: (cell-based table view) Providing Data To a Table View Programmatically for details.
Basically, the very first NSTableViewDataSource method that's called is numberOfRowsInTableView:. Only after you return a non-zero quantity from within that method will the subsequent tableView:objectValueForTableColumn:row: or tableView:willDisplayCell:forTableColumn:row: methods be called.
A: You're misunderstanding how the result of -tableView:objectValueForTableColumn:row: is used by the frameworks.
To do more-or-less what you're trying to accomplish above, override the delegate method -tableView:willDisplayCell:forTableColumn:row: instead. Here is an example cribbed from one of my own apps:
- (void)tableView:(NSTableView *)tableView
willDisplayCell:(id)cell
forTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row;
{
NSString * displayName = [self.senders objectAtIndex:row];
[cell setTitle:displayName];
[cell setState:[self.selection containsObject:displayName]];
}
This is the "old school" way, using cell-based tables (which are still the default).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: C++ shallow/deep copy? I have this function
int getrelation(string name, RELATION& output){
bool found=0;
int index=0;
for(int i=0;i<a_attributes.size();i++){
if(name==a_attributes[i].str_name){
found=1;
index=i;
}
}
if(!found){
printf("relation not found");
return 1;
}
output=a_attributes[index];
return 0;
}
RELATION is a class
a_attributes is a vector of relations.
its supposed to return a reference to the relation object. After getrelation() is called, if i change the values of output, then the values of a_attributes[index] should also be changed because this is a shallow copy, right?
A: It really depends on your assignment operator, which isn't listed here.
The line
output=a_attributes[index];
will use the assignment operator to set output. If that assignment operator makes a deep copy, then a deep copy is what you get.
A: If you haven't overloaded the assignment operator, then no, you will not get a shallow copy. When you assign output=a_attributes[index];, you are making a copy of a_attributes[index]. Thus, any modifications to the returned value will not affect a_attributes.
If you want a shallow copy, then you would have to either overload the assignment operator, or pass a pointer by reference, by changing the argument to RELATION& *output, and passing in a pointer, then changing the last line to output=&a_attributes[index];.
There is also another problem with your code. You can't compare strings directly with == like you have in the line if(name==a_attributes[i].str_name), because it will only return true if the strings are stored in the same location. You need to use something like strcmp().
A: No, because what you here is a deep copy. The output parameter is a reference to some object of class RELATION. So if you change that object in getrelation function then the user will notice those changes, because you change a referenced object. However, on this line - output=a_attributes[index]; you essentially invoke a copy assignment operator of the object output, which does a deep copy of every field from object returned by a_attributes[index] to the object referenced by output, unless copy assignment operator is overloaded and does something different. This is basically because you cannot change a value of the reference - for example, it cannot be referencing one object and end up referencing another. To achieve what you want (if I get you right), you have to pass a pointer to pointer to the object (or a reference to a pointer), then you can change a pointer to the object by de-referencing it. Something like this:
int getrelation(string name, RELATION **output){
bool found=0;
int index=0;
for(int i=0;i<a_attributes.size();i++){
if(name==a_attributes[i].str_name){
found=1;
index=i;
}
}
if(!found){
printf("relation not found");
return 1;
}
*output= &a_attributes[index];
return 0;
}
Hope it helps!
A: No ... if you want to get a reference to the output object, then pass a reference-to-a-pointer of type RELATION to the function, not a reference-to-an-object of type RELATION.
For instance:
int getrelation(string name, RELATION*& output)
{
bool found=0;
int index=0;
for(int i=0;i<a_attributes.size();i++){
if(name==a_attributes[i].str_name){
found=1;
index=i;
}
}
if(!found){
printf("relation not found");
return 1;
}
output = &(a_attributes[index]); //take the address-of object
return 0;
}
You would then call your function like so:
RELATION* ptr_to_object = NULL;
string argument_name;
//...more code to initialize argument_name
if (getrelation(argument_name, ptr_to_object) == 1)
{
//...handle error condition
}
//now ptr_to_object points to your a_attribute[index] object
So at this point, you can now dereference ptr_to_object, and you will get the object at a_attribute[index]. You can then change the attributes of that object through dereferencing the pointer. The only warning is that you should not call delete on ptr_to_object since it does not "own" the object being pointed to, and the pointer being returned does not point to the beginning of a memory segment that was allocated with new. Furthermore if the container a_attribute disposes of the object (i.e., if it's a std::map or std::vector), then the pointer will be pointing to an invalid memory location. So you have to make sure the container out-lives the pointer you're using as a reference to the object.
A: Here is some more idiomatic C++ although returning the actual iterator could be a good idea as well.
struct rel_by_name : public std::binary_function<const std::string&, const RELATION&, bool> {
bool operator()(const std::string& s, const RELATION& rel) {
return s == rel.str_name;
}
};
RELATION& getrelation(const std::string& name) {
std::vector<RELATION>::iterator it = std::find_if(a_attributes.begin(), a_attributes.end(),
std::bind1st(rel_by_name(), name));
if(it == a_attributes.end()) {
//not found, report error by throwing or something
}
else { return *it; }
}
You might want to add a const overload returning a const Relation&.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Font size and actual text size proportion I know that the actual size occupied by a rendered text is font-dependent.
For a predetermined font, however, and knowing the font_size/actual_width proportion for a given font size and a particular text, is it possible to determine the width for another value of size?
I guess what I'm really asking is: is the relation between a font size in pixels and the actual rendered size of a text linear?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CKEditor image properties not saving I am using the latest version of CKEditor, 3.6.2, combined with FCK's filemanager - followed a tutorial that I found here - http://www.mixedwaves.com/2010/02/integrating-fckeditor-filemanager-in-ckeditor/
Everything seems to be working correctly, however, when I insert an image and, for example, align it to the right this "align" property is not saved through the editor and the image just sits above the text. Other properties not being saved are width and height. Alt is being saved.
Does anyone know how I can fix this?
Thanks in advance.
A: This was happening to me as well.
In my case it turned out to be an xss-filtering setting in CodeIngniter, which I use as a PHP framework. The way CKEditor posts the image attributes for some reason gets filtered out.
In case you use CodeIgniter as well, this was the fix for me
In /application/config/config.php
Change
$config['global_xss_filtering'] = true;
to
$config['global_xss_filtering'] = false;
.. and of course make sure you're not using xss_filtering on the form_validation rules in your controller.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Phone's Processes Flooding LogCat Output -- How To Eliminate those Messages? I know how to filter out messages in LogCat, so that's not what I am asking about.
The problem is that certain phones are "noisier" than others and flood the LogCat buffer to the point of triggering a bug that makes it discard newer messages.
This problem doesn't happen on the Nexus One, but it does happen with the Samsung Continuum i400, for example.
Is there a way to tell Android or LogCat to completely discard (i.e. not filter) messages from certain processes?
A: There's no way to prevent any application of posting anything to logcat, as far as I know. All you can do is clear the log before capturing, and then filter out things you don't want to see. For example:
adb logcat -c
adb logcat BadProcessName:S MyProcessName:V > log.txt
CTRL-C
I hope this helps.
A: "Clear Log" sometimes works.
And sometimes it doesn't.
When "Clear Log" doesn't help, there is no need to restart Eclipse. All you have to do is show the Devices view in the DDMS perspective and the LogCat message will magically start appearing again.
You can then close the Devices view (if you don't need it).
A: As @Emmanuel has mentioned, and as I mentioned in the comments, I don't believe there is a way to stop other applications from posting log messages. You can filter them, but you can't stop them completely.
The easiest solution that I have found when I run up against this problem is to simply hit the "Clear Log" button in Eclipse.
That should clear the buffer (at least until the noisy apps fill it up again). You can click the button at any time, so I find that it's most helpful to clear the log just before I perform the action that I want to debug.
I guess another option is to kill the process entirely. If the noisy application isn't critical to the app that you are trying to debug, you can just end the process.
A: The best thing to do in this case would be to should use the filter functionality to only show the logs from your application. You can filter by PID or by application name.
Click the green plus button to create a filter for your app.
A: You can restart the device to stop the processes from flooding the logcat
This is the solution used by me every time
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: SELECT statement issue I have a modal pop up that currently holds checkboxes in it for an admin to be able to add features to a product. I needed to change this to be able to get tied to the category of the product on the current page, but my sql statement isn't working.
The tables here are Feature, Category and Marketing. Feature connects to Category with the CategoryID(named CategoryID in Feature & in Category tables), and Feature connects to Marketing with the FeatureID(called MarketingData in the Marketing table)
The MarketingTypeID of 3 tells the Marketing table to look for a Feature and will jump over to the feature table. The select statement worked before I added the Category table stuff to it, so obviously I coded that part wrong. Can someone help me get the select statement working?
This works:
SELECT DISTINCT FeatureID, FeatureTitle
FROM Feature
WHERE FeatureID NOT IN
(SELECT m.MarketingData FROM Marketing
WHERE MarketingTypeID = 3 AND ProductID = @ProductID)
ORDER BY FeatureTitle
This doesn't:
SELECT DISTINCT f.FeatureID, f.FeatureTitle FROM Feature f
INNER JOIN Category c
ON c.CategoryID = f.CategoryID
WHERE f.CategoryID = @CategoryID
AND f.FeatureID NOT IN
(SELECT m.MarketingData FROM Marketing m
WHERE m.MarketingTypeID = 3 AND m.ProductID = @ProductID)
ORDER BY f.FeatureTitle
EX: FeatureID #23, Web Tutorials, has a CategoryID of 32....this Category is called Platforms and is located in the Category table. FeatureID #23 is NOT in the Marketing table, therefore is NOT associated to the Product that was chosen, which is ProductID #1. I need a checkbox that says Web Tutorials to show up in the modal. Like I said before, it was just fine before I added all the stuff about the Category that is associated to the product that was selected by the user.
UPDATE: I have no idea why I was trying to write that statement the way I had it. I realized that it was much easier than I had originally thought and changed the statement. This works now, thank you for all the help everyone! I changed the SELECT statement to:
"SELECT DISTINCT f.FeatureID, f.FeatureTitle
FROM Feature f
LEFT JOIN Category c ON c.CategoryID = f.CategoryID
WHERE f.CategoryID IN
(SELECT CategoryID FROM CategoryLink
WHERE ProductID = @ProductID)
AND f.FeatureID NOT IN
(SELECT m.MarketingData FROM Marketing m WHERE m.MarketingTypeID = 3
AND m.ProductID = @ProductID)
ORDER BY f.FeatureTitle"
A: If you compare this JOIN:
FROM Feature f INNER JOIN Category c ON c.CategoryID = f.CategoryID
with the database structure you'll see that you're trying to use a column (Feature.CategoryID) that does not exist in your database. In fact, with the existing design you're going to have to write a pretty involved query to get from Feature to Category.
It may be true, however that there is a more direct relationship between Categories and the Features they can have that is not yet represented in your database. If that's true, you'll need to add a table CategoryFeatureLink, then use that table along with Category and Feature in a three-way JOIN.
A: This is my second answer to this question, pursuing a different problem with the query.
Is the MarketingData field NULLable? If so, and if your sub-query returns and NULL values, your statement may not evaluate as you expect depending on certain database settings.
In theory, this won't make a difference between the two queries because they both contain the same sub-query, but if you happened to test with different @ProductID you may only have come across the problem with a particular product.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Doctrine 2: how to clone all values from one object onto another except ID? In $entity variable, there is an object of same type as $other_address, but with all field values filled in.
I want to set all fields in $other_address object to have exact same values as $entity object.
Is this doable in less then N number of lines, where N is number of fields I need to set?
I tried "clone" keyword, but it didnt work.
Here's the code.
$other_address = $em->getRepository('PennyHomeBundle:Address')
->findBy(array('user' => $this->get('security.context')->getToken()->getUser()->getId(), 'type' => $check_type));
$other_address = $other_address[0];
//I want to set all values in this object to have values from another object of same type
$other_address->setName($entity->getName());
$other_address->setAddress1($entity->getAddress1());
$other_address->setAddress2($entity->getAddress2());
$other_address->setSuburbTown($entity->getSuburbTown());
$other_address->setCityState($entity->getCityState());
$other_address->setPostZipCode($entity->getPostZipCode());
$other_address->setPhone($entity->getPhone());
$other_address->setType($check_type);
A: I'm not sure why cloning won't work.
This seems to work for me, at least in a basic test case:
$A = $em->find('Some\Entity',1);
$B = clone $A;
$B->setId(null);
If you've got relationships to worry about, you might want to safely implement __clone so it does what you want it to do with related entities.
A: Just Clone the entity, you don't even need to unset the id. Doctrine has tackled this for you
A: $A = $em->find('Some\Entity',1);
$B = clone $A;
$em->persist($B);
$em->flush();
if you merge it will update the entity, best you use persist() it will duplicate the entire row and add auto incremented primary key
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: LDAP vs database for storing application configuration data What is the best place to store Java application configuration data? (like property files, etc) The data may be modified during runtime though not very often. What are the advantages and disadvantages of both approaches?
A: You have to clarify a little. Are you storing per-user configuration data? Per-install? Both?
Databases (except the NoSQL variety) are a terrible idea for storing configuration. Configuration implies key-value pairs that can change meaning/format over the lifetime of the application. Unless its a document-based database, of course. You could store entire files in blob or giant varchar() fields but this only makes it more complicated.
LDAP is designed for this sort of thing, I suppose, and its 'fast', but it has a (in my opinion) terrible API.
Have you considered using HTTP or FTP, and pulling down the files from the web using... the web?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL Server performance erratic after migration I recently had a web application migrated to a different data center. That included moving the database from SQL 2000 to 2005, which shouldn't be a problem per se (I run other instances of the same app with SQL 2000 to 2008 R2).
The problem is, after the migration some operations, especially UPDATEs, became extremely slow (timing out after whatever limit I define in my app, and I tried up to 6 minutes).
I tried running the same query on Management Studio, but the results were inconsistent. Sometimes it just runs instantly, but sometimes it takes forever and I have to cancel the query. On my app, it always time out (Classic ASP app).
It's happening on more than one query, but most frequently on one that looks like this:
UPDATE mytable SET timestampcol = GETDATE() WHERE record_id = 12345 /* record_id is the PK */
What I tried already:
*
*First, I suspected of the table size (~2M rows). So I deleted old records, leaving only ~40,000 rows, but the problem persisted.
*Then I tried recreating my indexes, and it didn't work.
*I also tried running both sp_updatestats and sp_updatestats 'resample', but no luck.
So, I'm stuck. Does anyone has a clue of what might be happening, and how could I fix it?
UPDATE
Looking at sys.dm_tran_locks, I can see that two locks are in place while the query is running from my app:
request_mode request_type request_session_id
S LOCK 65
IX LOCK 67
I also realized the S lock appears before I try to run the query that gets stuck, on an SP call. I'm now revising the SP to try and understand why the lock persists after the SP finishes running.
UPDATE 2 - Answers to Aaron Bertrand questions (see comments)
*
*Does the procedure use transactions?
No, there are no transactions in the whole app
*Are there any code paths where the transaction might not be committed? N/A
*Who is calling this other stored procedure? The same script is calling it, a few lines before the problematic query
*Are you using some kind of transaction context in .NET? No, and it's not .NET, it's classic asp (old legacy code I have to maintain)
*Why isn't the app calling stored procedures? You means instead of running the problematic query directly from (ADO) connection.execute? Well, also tried it, same result.
*Why does calling the other stored procedure not affect you when you run the problematic query in SSMS? I have no idea! But the update is currently running just ok from SSMS, whether I call the sp before that or not.
Guys, thank you for all your help, but I'm about to give up on this. Things just worked before someone decided to move the server. The problem was just dropped on my hands, I'll try to pass it along to someone else.
A: sp_updatestats gives nothing if there are no suitable statistics already created (both tables and indexes). Review actual execution plans and look for missing statistics (explicit warnings and mismatches between actual and estimated rows says that statistics are probably wrong)
A: This turned out to be a lock on the table. I still don't understand why it was getting locked, but I solved it by adding the WITH(NOLOCK) hint to my stored procedure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use Botan Amalgamation files and VS2008
*
*Clean install of Windows XP SP3
*Install Python 2.7.2
*Extract Botan 1.10.1 to the desktop
*Run configure.py --cc=msvc --disable-shared --gen-amalgamation
*Copy botan_all.h and botan_all.cpp to my dev workstation
*Make a new project Win32 console project in VS2008
This gives me 102 errors ... anyone using this library?
#include "botan_all.h"
int main(int argc, char *argv[])
{
return 0;
}
A: The problem is your project is a windows application and includes windows.h, windows.h includes macros for min and max.
The solution is to define #define NOMINMAX
You can do through the project's property pages > C/C++ > Preprocessor > Preprocessor definitions
Also, add #define BOTAN_DLL in botan_all.h to avoid error at least in version 1.10.1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Autoloading Problem with Symfony2 I am trying to include MagentoBundle into my Symfony2 app. After installing and configuring the bundle according to the README I received the following error message:
Fatal error: Class 'Liip\MagentoBundle\SessionStorage\MagentoSessionStorage' not found in .../app/cache/dev/appDevDebugProjectContainer.php on line 1447
Yes, the bundle is added to the autoloader and to the appkernel. However I am not quite sure where to look next, since I am new to Symfony2 and seemingly installed everything accordingly.
Any help or ideas would be greatly appreciated :) .
A: be sure to have this in your deps file
[LiipMagentoBundle]
git=http://github.com/liip/LiipMagentoBundle.git
target=/bundles/Liip/MagentoBundle
Then, manually remove cache
rm -rf app/cache/*
set the right :
sudo setfacl -R -m u:www-data:rwx -m u:`whoami`:rwx app/cache app/logs
sudo setfacl -dR -m u:www-data:rwx -m u:`whoami`:rwx app/cache app/logs
and reinstall vendors
php bin/vendors install --reinstall
If it's still failing use a debuger and look what happend it the autoloader
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the answer to the bonus question in test_changing_hashes of Ruby Koans? In the Ruby Koans, the section about_hashes.rb includes the following code and comment:
def test_changing_hashes
hash = { :one => "uno", :two => "dos" }
hash[:one] = "eins"
expected = { :one => "eins", :two => "dos" }
assert_equal true, expected == hash
# Bonus Question: Why was "expected" broken out into a variable
# rather than used as a literal?
end
I can't figure out the answer to the bonus question in the comment - I tried actually doing the substitution they suggest, and the result is the same. All I can figure out is that it is for readability, but I don't see general programming advice like that called out elsewhere in this tutorial.
(I know this sounds like something that would already be answered somewhere, but I can't dig up anything authoritative.)
A: It's because you can't use something like this:
assert_equal { :one => "eins", :two => "dos" }, hash
Ruby thinks that { ... } is a block, so it should be "broken out into a variable", but you can always use assert_equal({ :one => "eins", :two => "dos" }, hash)
A: I thought it was more readable, but you can still do something like this:
assert_equal true, { :one => "eins", :two => "dos" } == hash
A: Another test you can use is the following:
assert_equal hash, {:one => "eins", :two => "dos"}
I’ve simply swapped the parameters to assert_equal.
In this case Ruby will not throw an exception.
But it still seems a bad solution to me. It’s much more readable using a separate variable and testing a boolean condition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
} |
Q: Save PHP code to file using fwrite I'm having a little problem with a script I'm working on, and this is what I'm running into:
First of all a bit about how the script works. It actually uses WordPress (it's a plugin) and it makes dynamic pages based on various settings they can change in the backend. I'm adding an Export to HTML feature where they can make a static version of that page after they have already created the page in the plugin.
In this exported page I need it to save a PHP function at the top of the file, and another one somewhere else in the page. This is what I'm trying to do:
$fbscript=file_get_contents('fbscript.txt');
$newcontent=str_replace('<!-- dont erase this line -->',$fbscript,$newcontent);
$fbscript2=file_get_contents('fbscript2.txt');
$newcontent=str_replace('<!-- dont erase this line 2 -->',$fbscript2,$newcontent);
The 2 dont erase this line things are somewhere in the dynamic pages where it needs to put the scripts. This is what is showing up somewhere in the exported page:
<br />
<b>Notice</b>: Undefined index: signed_request in <b>C:\xampp\htdocs\wp\wp-content\plugins\easyfanpagedesign\default.theme\htmlpost-31345.php</b> on line <b>82</b><br />
<br />
<b>Notice</b>: Undefined offset: 1 in <b>C:\xampp\htdocs\wp\wp-content\plugins\easyfanpagedesign\default.theme\htmlpost-31345.php</b> on line <b>3</b><br />
So I guess what I'm really trying to ask is how can I save a file using fwrite with a .php extension and have a php script inside the saved file. This is an example of the php script I'm trying to add to the page saved using fwrite (Facebook's PHP SDK):
<?php
function parsePageSignedRequesttt($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
return null;
}
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
?>
This is my entire export.php file which does everything:
<?php
$content=$_POST['efpd_page_content'];
$uistyle=$_POST['efpd_ui_style'];
$app_id=$_POST['efpd_appid'];
$the_fscripts=$_POST['efpd_fscripts'];
$the_hscripts=$_POST['efpd_hscripts'];
$bgstuff=$_POST['efpd_bgstuff'];
$jquery=$_POST['efpd_jquery'];
$jqueryui=$_POST['efpd_jqueryui'];
$cycle=$_POST['efpd_cycle'];
$copytext=$_POST['efpd_copytext'];
$affstr=$_POST['efpd_affstr'];
$the_style=$_POST['efpd_style'];
$the_gwf=$_POST['efpd_gwfstyle'];
$secret=$_POST['efpd_secret'];
if(empty($secret)){$secret=999999;}
$newcontent=file_get_contents($_POST['efpd_refurl']);
$fbscript=file_get_contents('fbscript.txt');
$newcontent=str_replace('<!-- dont erase this line -->',$fbscript,$newcontent);
$fbscript2=file_get_contents('fbscript2.txt');
$newcontent=str_replace('<!-- dont erase this line 2 -->',$fbscript2,$newcontent);
$newcontent=str_replace('THE_SECRET',$secret,$newcontent);
//die(var_dump($newcontent));
$int=rand(1,99999);
$savefile = "htmlpost-$int.php";
$handle = fopen($savefile, 'w') or die("can't open file");
fwrite($handle,$newcontent);
fclose($handle);
echo "<a href='$savefile'>Right Click > Save As to download the generated HTML page.</a>";
?>
A: Ok, so your problem is that you can not reference a php file in that way, because the server will parse it. Have a seperate script that sets the header and make this the target of your link.
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="filename.php"');
readfile('filename.php');
exit;
A: Okay, now that you've updated your question the solution is pretty clear:
You get those results when you do what your link says, right? You right-click on that link and do "Save as.." - but you don't really save the php code but just what the server outputs as the php code first gets executed by the server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Compiler error with pow() in a for loop I'm a writing a function to print out a ternary tree in C. Of course, my method is terribly inefficient, but that's beside the point, all I need to do is print out the tree without regard to space or time complexity.The compiler (gcc) is giving me an error on the line where the for loop is. I can't figure out what's wrong. I even set empty as a double, and I have included math.h, so I really do not see what the problem is. Please help!
This is the output from the compiler:
make traverse clean
gcc -c -Wall traversals.ctraversals.c: In function ‘printTree’:
traversals.c:112: error: syntax error before ‘)’ token
traversals.c:112: error: syntax error before ‘)’ token
make: * [traversals.o] Error 1
Regrettably, it's not being very specific about what the error actually is. I think there are 2 errors actually.
void printTree(node_t* node)
{
printf("%d %s %d\n", node->depth, node->string, node->counter); // Print the root node
int level;
double empty = 0;
// Starting from the second level and ending when all the children of a particular level are null
for(level = 2; empty != pow(3, level - 1)); level++)
{
empty = checkLevel(node, level); // Print out any children that match the requested depth level and return the number of empty children
}
}
A: You've got an extra )
for(level = 2; empty != pow(3, level - 1)); level++)
^ here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Doctrine querying and accessing with relations No problem, just a question about good code-writing. I'm still learning Symfony + ORM and have no orientation in these frameworks.
I have in my database table User (with login column) and Account (also with login column, which is different than the login in User).
One User (identified by ID for database and by login for logging in) have many Accounts (identified also by ID and login which acts as account-name). So relation in schema.yml is:
Account:
(...)
relations:
idUser:
class: User
local: id_user
foreign: id_user
foreignAlias: Accounts
Now I'm trying to access all the Account's logins related to one User's login in the following way (let's say I'm only displaying list of Account's logins of the current user for now):
/* $u = login-name of the current user */
$q = Doctrine::getTable('User')->
createQuery('u')->innerjoin('u.Accounts a WITH u.login=?', $u)->execute();
foreach($q[0]->Accounts as $v) {
echo $v->login . "<br />";
}
This code works very well. However what I wonder now is if isn't it ugly or not the best way to achieve this? Like I said, I have no much orienatation in Symfony and don't know which programming methods are recommended, and which aren't.
A: This does not look so bad to me, but I'd have written it like this:
/* $login = login-name of the current user */
/* Always use ModelTable::getInstance() instead of Doctrine::getTable :
your IDE will give you better auto-completion if the doc block of the
getInstance has a correct @return annotation.
You will have all the methods of ModelTable in your auto-completion */
$users = UserTable::getInstance()
->createQuery('u')
->innerjoin('u.Accounts a WITH u.login = ?', $login)
->execute(); //Try to align opening parenthesis when writing DQL, it is easier to read
foreach ($users[0]->Accounts as $v) // egyptian brackets are for java(script) programmers
{
echo $v->login . "<br />";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create record and assign to 1 of 3 sub-types, each sub-type with different properties I'm constructing a schema for a MySQL database. I have a table called 'entry' (the supertype). An entry can be either a 'photo', 'essay', or 'video' (subtype). Each subtype has different properties/columns.
My current design calls for an entries table, and a separate table for each of the three sub-types.
The sub types are associated with the a record in 'entries' via a foreign-key to the entries table's id attribut. My question is, how can I modify this design to restrict an entry to being associated with only one type of subtype. Currently, multiple subtypes can be associated with the same entries record.
A: I'm not entirely sure that this is the best way of doing it, but here's an option:
CREATE TABLE `entries` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`type` enum('photo','essay','video') NOT NULL DEFAULT 'photo',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
My thinking here is that you enforce only one entry in the entries table per name, hence the UNIQUE KEY, and the type enum essentially informs you which table to join on.
This might be totally inappropriate depending on how you want to use / select the data out of the table(s), mind you.
A: You cannot easily do this declaratively in SQL. What you want to do is put a CONSTRAINT on the primary key that's shared across all four tables that the key must exist in entries (that's OK, it's a PRIMARY KEY) and that it must not exist in either of the other two tables. That second part has no corresponding constraint type in SQL.
You're basically stuck with TRIGGERs. (You can do this in some other engines with a CHECK CONSTRAINT that contains a sub-query, but I don't think MySQL supports CHECK CONSTRAINTs at all and some engines will not look outside the current row when evaluating a CHECK CONSTRAINT).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is using a jQuery resizer faster that using PHP's TimThumb? Hello my question is if using a jQuery plugin to scale/resize images on the fly, will be faster than doing it through a PHP function or TimThumb.
This came into my mind because jQuery is a user-side and PHP is server side.
A: You can't compare them, both have pros and cons.
I would go for timthumb, since it has some advanced options on cropping + it stores a cached version of the resized image which would save you bandwidth in the future plus speed up your website loading time.
Also think about the small amount of people that have javascript disabled, timthumb will also provide them resized images while a jQuery plugin wouldn't.
GO for timthumb ;)
A: Both are interpreted languages so I guess the speed would be pretty close. It will really depend on your requirements. In the first case you will be using the client's resources whereas in the second the server resources. For example if you just want to generate some thumbnails on the fly without posting to the server you could do it with javascript. But if you will make a request to the server then probably it would be better to do it on the server.
A: Uhm … You wouldn't need any jQuery Plugin to resize images client-side. Browsers can do that on their own, you just need to tell them to do so either via CSS or via "width" and "height" attributes of the <img> tag.
As for performance: Depending on the user's machine, their connection speed and dozens of other factors, performance may significantly improve if you serve them pre-resized images.
Rule of thumb (mind the pun!): If you can cache your resized images, it's usually worth to resize them server-side. You have to do the nitty gritty computation only once, afterwards, the images are neatly sitting in the cache and waiting for the client to come fetch them.
No more resizing, neither server nor client side! Everyone's happy.
Now, can I have a cookie?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL does not pull records based on exact date I exported records and I want to know which record was exported on a particular day. It does not work. Here is the data if I query it.
* comapny Name * * date exported *
ABC Company, Inc 2011-08-01 15:44:52.857
XYZ Company, Inc 2011-08-01 15:44:52.857
I issue this command which does not retrieves the exact matches
select companyname, exporteddate from mytable exporteddate = '2011-08-01' <- does not work
select companyname, exporteddate from mytable exporteddate like '%2011-08-01%' <-- tried this variation too and many other, did not work
The interesting thing is >=, >, <= works. What really is the problem? The exported date is declared as datetime field.
select companyname, exporteddate from mytable exporteddate >= '2011-08-01' <- this works
I am using Windows XP, MS-SQL 2005 SP3 (not exactly but close).
A: = '2011-08-01' will only match datetimes of exactly midnight on that date (i.e. any rows you have that have values of 2011-08-01 00:00:00.00).
The best way of doing the query is where exporteddate >= '20110801' and exporteddate < '20110802'
This is sargable, avoids ambiguous datetime formats and is better than the BETWEEN alternative with an end condition on 20110801 23:59:59.997 as that relies on an implementation detail about the max precision of the datetime datatype that will break if you move over to the new SQL Server 2008 datetime2 datatype at some later stage.
A: Your problem is that you're using a DATETIME field to store a DATE. As you can see, the data is actually stored down to milliseconds.
To get this to work, you can:
*
*Search on a range of DATETIME values
WHERE exporteddate BETWEEN '2011-08-01 00:00:00.000' AND '2011-08-01 23:59:59.999'
*Convert your storage from DATETIME to DATE (the simplest solution if you don't really need to distinguish multiple loads on single date).
A: A datetime field with no time specified is interpreted as a date with a time of 00:00:00.
A: unless you specify, the time part will be exactly 00:00:00 so all those seconds in your timestamp will prevent exact match.
A: Date fields don't work like text fields.
Your first non-working select doesn't include time (which is in the data). You would need to trunc the date or convert it to a string using a format that only has year/month/day.
Same for the LIKE statement. Its not a text field.
Date's however can be checked for equality using >, <, etc as you see.
A: Like many other suggest, because you don't supply time the SQL will use 00:00:00 instead. To compare a DATE to a DATEIME you may convert your DATETIME to a DATE.
I don't know how to achive this in SQL server but in MySQL it would be : select companyname, exporteddate from mytable DATE(exporteddate) = '2011-08-01'
A: Try this, you are converting both dates to same format and comapring them.
select companyname, exporteddate from mytable CONVERT(VARCHAR,exporteddate ,103)=
CONVERT(VARCHAR,'2011-08-01',103);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Flex 4 Datagrid itemrender I'm using s:MXDataGridItemRenderer for my Datagrid. The click event for an image inside the ItemRenderer is not getting dispatched.I have pasted my code below.
ItemRenderer:
<s:MXDataGridItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
focusEnabled="true">
<fx:Script>
<![CDATA[
private function acceptBtn_clickHandler(event:MouseEvent):void
{
updateData(false, "Accepted", 1);
}
private function updateData(approved:Boolean, buttonName:String, score:int):void
{
data.approved=approved;
data.score=score;
data.decisionText=buttonName;
}
private function rejectBtn_clickHandler(event:MouseEvent):void
{
updateData(false, "Rejected", 1);
}
]]>
</fx:Script>
<mx:HBox id="imageBox"
horizontalAlign="center"
verticalAlign="middle"
width="100%"
height="100%"
enabled="true"
>
<mx:Image id="acceptBtn"
source="@Embed(source='../../../assets/icons/button-accept.png')"
click="acceptBtn_clickHandler(event)"
buttonMode="true"
toolTip="Accept"/>
<mx:Image id="rejectBtn"
source="@Embed(source='../../../assets/icons/button-reject.png')"
click="rejectBtn_clickHandler(event)"
buttonMode="true"
toolTip="Reject"/>
</mx:HBox>
Datagrid:
<mx:DataGrid id="testList"
dataProvider="{testListDP}"
width="100%"
height="100%"
editable="true">
<mx:columns>
<mx:DataGridColumn dataField="score"
headerText="Score"
editable="false"/>
<mx:DataGridColumn headerText="Decision"
itemRenderer="DecisionColumnItemRenderer"
editable="false"/>
</mx:columns>
</mx:DataGrid>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: error message color in symfony i want to change the color of errors that occour when a form is submitted by users, i set
.errorMessage{ color:red }
in main.css, but it dosn't work :(, is there any option for error color in widgets?
i google it but i can't find answer, my symfony version is 1.4.11, and another question is i want to have captcha in my forms, i write this code for that
$this->widgetSchema['captcha'] = new sfWidgetFormReCaptcha(array(
'public_key' => sfConfig::get('app_recaptcha_public_key')
));
$this->validatorSchema['captcha'] = new sfValidatorReCaptcha(array(
'private_key' => sfConfig::get('app_recaptcha_private_key')
));
but when i echo the form this error occour:
Captcha Input error: k: Format of site key was invalid
A: You need to theme it in template file
<?php foreach($form->getErrorSchema()->getErrors() as $name => $error): ?>
<div class="errorMessage <?php echo $name; ?>"><?php echo $error; ?></div>
<?php endforeach; ?>
You will get something like that:
Captcha Input error: k: Format of site key was invalid
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: importing modules in python i am having some trouble in understanding how to distribute a tornado application into multiple files.i need to have one file which creates the application instance another file which handles login/logout functionality ,another which handles profile page view and so on.but what i dont get is how to do this .
lets say for example i have two files:
-app.py(creating app instance)
-auth.py(login/logout functionality)
app.py
>import tornado
>import auth
> handlers = [
(r"/", MainHandler),
(r"/auth", auth.AuthHandler),
(r"/logout", auth.LogoutHandler),
]
this works fine but when i have app.py as this:
>import tornado
>import auth
>import profile
> handlers = [
(r"/", MainHandler),
(r"/auth", auth.AuthHandler),
(r"/logout", auth.LogoutHandler),
(r"/profile", profile.ViewHandler),
]
auth.py
>import tornado
>import app
>class AuthHandler(app.BaseHandler)
> > ...
>class LogoutHandler(app.BaseHandler)
> >...
and in profile.py i have this:
>import app
>import tornado
>class ViewProfile(app.BaseHandler)
---it shows error that in profile.py module app has no attribute BaseHandler
A: What happens if you drop the "import app" in both auth.py and profile.py? it seems you are creating circular imports.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: A save function in F# that does not want to run I have borrowed the following save function to save values of any type to a given file (cheers to John Harrop, writer of F# for scientists).
open System.IO
open System.Runtime.Serialization.Formatters.Binary
let save filename x =
use stream =
new FileStream(filename, FileMode.Create)
(new BinaryFormatter()).Serialize(stream, x);;
But F# is telling me that there is no body for the "use" part of the function. I seems to not like the final line but the intellisense is not giving me an error message when I hover.
Do I need to declare another namespace?
Can anyone advise? Very grateful for any help.
A: Works on my machine! :-) If you're typing this directly into FSI try putting it in a script file and using 'Send to Interactive'. If you're not, remove ;; on the last line.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to swipe between several jquery mobile pages? Here is the code extract which works well with 2 pages:
<script>
$(document).ready(function() {
window.now = 1;
$('#device1').live("swipeleft", function(){
window.now++
$.mobile.changePage("#device"+window.now, "slide", false, true);
});
$('#device2').live("swiperight", function(){
window.now--;
$.mobile.changePage("#device"+window.now, "slide", true, true);
});
});
</script>
...
<div data-role="page" id="device1">
...
</div><!-- /page -->
<div data-role="page" id="device2">
...
</div><!-- /page -->
How can I make it more universal to work with huge number of pages?
A: This code also works for the swipe.
<script>
$('div.ui-page').live("swipeleft", function () {
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.changePage(nextpage, "slide", false, true);
}
});
$('div.ui-page').live("swiperight", function () {
var prevpage = $(this).prev('div[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, {
transition: "slide",
reverse: true
}, true, true);
}
});
</script>
A: This seems to do what you want
<script>
$(document).ready(function() {
$('.ui-slider-handle').live('touchstart', function(){
// When user touches the slider handle, temporarily unbind the page turn handlers
doUnbind();
});
$('.ui-slider-handle').live('mousedown', function(){
// When user touches the slider handle, temporarily unbind the page turn handlers
doUnbind();
});
$('.ui-slider-handle').live('touchend', function(){
//When the user let's go of the handle, rebind the controls for page turn
// Put in a slight delay so that the rebind does not happen until after the swipe has been triggered
setTimeout( function() {doBind();}, 100 );
});
$('.ui-slider-handle').live('mouseup', function(){
//When the user let's go of the handle, rebind the controls for page turn
// Put in a slight delay so that the rebind does not happen until after the swipe has been triggered
setTimeout( function() {doBind();}, 100 );
});
// Set the initial window (assuming it will always be #1
window.now = 1;
//get an Array of all of the pages and count
windowMax = $('div[data-role="page"]').length;
doBind();
});
// Functions for binding swipe events to named handlers
function doBind() {
$('div[data-role="page"]').live("swipeleft", turnPage);
$('div[data-role="page"]').live("swiperight", turnPageBack);
}
function doUnbind() {
$('div[data-role="page"]').die("swipeleft", turnPage);
$('div[data-role="page"]').die("swiperight", turnPageBack);
}
// Named handlers for binding page turn controls
function turnPage(){
// Check to see if we are already at the highest numbers page
if (window.now < windowMax) {
window.now++
$.mobile.changePage("#device"+window.now, "slide", false, true);
}
}
function turnPageBack(){
// Check to see if we are already at the lowest numbered page
if (window.now != 1) {
window.now--;
$.mobile.changePage("#device"+window.now, "slide", true, true);
}
}
</script>
UPDATE: I tested this with the iPhone emulator and the Android emulator and it worked as expected in both.
UPDATE: Changed answer to address the user's comment about using a slider causing swipe left/right.
A: I'm using swipeview to handle a large number of pages. From the creator of iScroll.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Which database to use- Mysql or Oracle? If someone is to build a University Management System using PHP, which database would you suggest for that- Mysql or Oracle? Or let me put it this way.. is it okay if someone uses mysql as a database for the University Management System or it is better to use Oracle?
Thanks in Advance
EDIT
Sorry, I should have been more specific about the University management system. What the plan is, to store student, teacher, employees information. Enroll Students in courses(students will hook up online and do it by themselves). All students,teachers and employees will have own personalized page. Some other features are fee collection, library management, attendance tracking etc.
Thanks :)
A: In my opinion, MySQL is powerful enough for most things. If you're looking for data storage, then MySQL will do the job. If you're going to be doing a lot of clustering, replication, stored procedures, triggers, and integration with enterprise software such as PeopleSoft, then Oracle may be a better solution.
It's a rather hard question to answer with out knowing how the database will be utilized.
In my experience I have used MySQL clustered and replicated across time zones with high traffic social networks, and have had no problems.
A: If you write your PHP application using the PDO library for your database access, then your application will be able to work with either MySQL or Oracle (or several other DBs) without having to change the code.
However, if you have to make a choice over database now, then between these two it comes down to cost: MySQL is free; Oracle costs money. Quite a lot of money.
There's nothing wrong with MySQL as a database. It is capable of running high performance, high volume systems. There are advantages to using a commercial database like Oracle though (they wouldn't be able to justify the price otherwise).
(By the way, as an aside, it's worth knowing that the Oracle company also owns MySQL. So in fact both databases are produced by the same company)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: sql order by not working in classic asp loop I have a sql query that orders the rows by an id, however it doesn't seem to output the data in order when in classic asp:
sSQL = "SELECT * FROM a ORDER BY ID DESC"
Set RS = ConnStr.Execute(sSQL)
<% DO WHILE NOT RS.EOF %> <td>
<br><p class='h1'>
<%=RS("ID")%>-
<%=RS("Title")%></p>
<% RS.MoveNext
Loop %>
Database:
ID Title
1 car
2 tree
3 dog
wrong asp output:
ID
2
3
1
A: My fellow StackOverflowers, allow me to theorize on OPs context. It's a shot in the dark, with a little bit of experience in it. Consider this data structure:
declare @mytable table (ID varchar(5))
insert into @mytable (ID) values
(' 1'), ('2'), (' 3')
select * from @mytable
order by ID desc
Notice the spaces before 1 and 3. Result:
ID
2
3
1
Since the browser will not visually render the empty spaces, OP might not be seeing them, but they might be there in the HTML.
That's the only way I can think of where ORDER BY <field> DESC would "apparently fail".
A: figured it out. But not sure why it works. I had an open
< td >
tag that I never closed in the loop. Why would this cause the order to be off?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Rectangle With Only One Border I am creating a template for a button. How do I draw only the bottom border of it?
Thanks!
A: Since you want a dashed line, use a Line object and set it to the bottom of your control
<Line Stroke="Red" Height="2" Stretch="Fill" X2="1"
StrokeDashArray="1 2" VerticalAlignment="Bottom" />
If you don't need the Dashed line, I'd recommend a Border with the BorderThickness property set to 0,0,0,1
A: You probably want a Border, not a Rectangle in this case.
A: <Border BorderThickness="0,0,0,1">
<!-- Content -->
</Border>
You can set different thickness for any part of Border control.
A: You could try this make a rectangle of height 1 and vertically align it to bottom
<Rectangle Height="1" Stroke="Red" StrokeDashArray="1 2" VerticalAlignment="Bottom" />
A: If you only want to have a line at the bottom, you could just have a transparent Border which contains (at some point in the tree) a line.
A: You shouldn't use either:
*
*A Rectangle is a Shape (Geometry).
*A Border does not support a dashed line
Instead, I would create a custom Decorator (Border is a Decorator). You'll be able to customize it how you want and it contains a Child DependencyProperty, so you can wrap it around your content.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Displaying Parent/Children name with indent i have an object that have parent/children relationship.
below is shorter version of what i have but the below is the core props
public class Company
{
Name {get;set;}
List<Company> ChildCompany {get;set;}
}
displaying something like this:
-----ABC Corporation (in this chas ABC has child company so it will display right indent)
----------ABC Child
----------ABC One
----------ABC Two
-----BBC Corporation (in this case no child company)
-----CBS
-----CNN Corporation
----------ABC
----------BBC
----------NBC
my code:
Company company = new Company();
company = GetDataForCompany(); //DAL
if(!string.IsNullEmpty(company.Name))
{
//dispaly Name
PlaceHolder ph;
l = new Literal();
l.Text = "<ul>" + Environment.NewLine;
ph.Controls.Add(l);
l = new Literal();
l.Text = "<li">";
ph.Controls.Add(l);
hl = new HyperLink();
hl.Text = company.Name;
ph.Controls.Add(hl);
foreach (Company item in company)
{
l = new Literal();
l.Text = "<li">";
ph.Controls.Add(l);
hl = new HyperLink();
hl.Text = item.Name;
ph.Controls.Add(hl);
}
}
the above code does not seems to rendering exactly what i wanted as shown above.
A: First of all, literals aren't intended for such task, but you have for example HtmlGenericControl which fits better your goal. And same for place holders - these are for templating -.
HtmlGenericControl unorderedList = new HtmlGenericControl("ul");
HtmlGenericControl tempItem = null;
HtmlGenericControl tempAnchor = null;
foreach (Company item in company)
{
tempItem = new HtmlGenericControl("li");
unorderedList.Controls.Add(tempItem);
tempAnchor = new HtmlGenericControl("a");
tempAnchor.Controls.Add(new Literal { Text = item.Name });
tempItem.Controls.Add(tempAnchor);
}
If you need further features, you can use System.Web.HtmlControls namespace which has web controls for any of common (X)HTML forms' elements and more:
*
*http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols(v=VS.100).aspx
About literals, these are for localization or a good way of representing literal text in server controls, since literals have an identifier like any other control, easing text substitution and other tasks.
Another important point is indenting will be achieved by overriding server controls' methods like Render, RenderChildren and so on, which provides you access to the HtmlTextWriter, the text stream writer later putting its output to the HTTP response stream.
A: You aren't nesting the Child companies within another unordered list. You need to check for child companies and nest those list items in another list to get the HTML to look like you need it.
// Code to display name here....
if (company.ChildCompany != null && company.ChildCompany.Count > 0)
{
l = new Literal();
l.Text = "<ul>";
ph.Controls.Add(l);
foreach (Company item in company.ChildCompany)
{
// Code for children.
}
l = new Literal();
l.Text = "</ul>";
ph.Controls.Add(l);
}
The output should end up looking something like:
<ul>
<li>Company
<ul>
<li>Child Company #1</li>
<li>Child Company #2</li>
</ul>
</li>
</ul>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Fastest ways to get a directory Size and Size on disk I recently answered to a similar question but what I'd like to do now is to emulate using bash the Windows "Directory --> right click --> Properties" function (see fig.).
I was able to reproduce something like the Size: in bytes using this command:
echo $(find . -type f -printf "%s+") | sed 's/+$//g' | bc
which is quite fast but is it possible to get info faster (than find) or do the math faster (than bc)?
In addition I would use the du -sb command to emulate the Size on Disk: and probably another couple of find to count files and directory and emulate the Contains: line.
Are there better ways to emulate such results?
A: Assuming cygwin:
cd /cygdrive/c
printf "Size: %s", $( du --apparent-size -sh )
printf "Size on disk: %s", $( du -sh )
find . -printf "%y\n" | awk '
$1 == "d" {dirs++}
END {printf("Contains: %d files, %d folders\n", NR-dirs, dirs)}
'
A: I just wrote a quick and dirty utility based on nftw(1).
The utility is basically just the manpage sample, with some stats added.
Functional
I opted to
*
*stay within a single mountpoint
*not follow symlinks (for simplicity and because it is usually what you want)
*note that it will still count the size of the symlinks themselves :)
*it shows apparent size (the length of a file) as well as the size on disk (allocated blocks).
Tests, speed
I tested the binary (/tmp/test) on my box:
# clear page, dentry and attribute caches
echo 3> /proc/sys/vm/drop_caches
time /tmp/test /
output
Total size: 28433001733
In 878794 files and 87047 directories (73318 symlinks and 0 inaccessible directories)
Size on disk 59942192 * 512b = 30690402304
real 0m2.066s
user 0m0.140s
sys 0m1.910s
I haven't compared to your tooling, but it does seem rather quick. Perhaps you can take the source and build your own version for maximum speed?
To test whether sparse files were in fact correctly reported:
mkdir sparse
dd bs=1M seek=1024 count=0 of=sparse/file.raw
ls -l sparse/
./test sparse/
Output:
total 0
-rw-r--r-- 1 sehe sehe 1073741824 2011-09-23 22:59 file.raw
Total size: 1073741884
In 1 files and 1 directories (0 symlinks and 0 inaccessible directories)
Size on disk 0 * 512b = 0
Code
#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
static uintmax_t total = 0ul;
static uintmax_t files = 0ul;
static uintmax_t directories = 0ul;
static uintmax_t symlinks = 0ul;
static uintmax_t inaccessible = 0ul;
static uintmax_t blocks512 = 0ul;
static int
display_info(const char *fpath, const struct stat *sb,
int tflag, struct FTW *ftwbuf)
{
switch(tflag)
{
case FTW_D:
case FTW_DP: directories++; break;
case FTW_NS:
case FTW_SL:
case FTW_SLN: symlinks++; break;
case FTW_DNR: inaccessible++; break;
case FTW_F: files++; break;
}
total += sb->st_size;
blocks512 += sb->st_blocks;
return 0; /* To tell nftw() to continue */
}
int
main(int argc, char *argv[])
{
int flags = FTW_DEPTH | FTW_MOUNT | FTW_PHYS;
if (nftw((argc < 2) ? "." : argv[1], display_info, 20, flags) == -1)
{
perror("nftw");
exit(EXIT_FAILURE);
}
printf("Total size: %7jd\n", total);
printf("In %jd files and %jd directories (%jd symlinks and %jd inaccessible directories)\n", files, directories, symlinks, inaccessible);
printf("Size on disk %jd * 512b = %jd\n", blocks512, blocks512<<9);
exit(EXIT_SUCCESS);
}
Compile with...
gcc test.c -o test
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Database auto increment primary key with business login I have a database with USERS table and EVENTS table, both with auto increment integer primary key called id. when the client app start an event, a message sent to the server, and the server creates a new EVENT entry in the EVENTS table with the username of the user that started the event(and some more data).
now what is the best practice to refetch this event when needed?
for example if the next day the user wants to ask the server for this event should the server search the EVENT table by username(every user have only one event in the table)? If so isn't less efficient to search by string then by the event integer id?
or maybe when the server creates the event entry in the EVENTS table i need to send the user the entry id, so the next time the user ask for the event he can ask it with the id? but if i do it this way im using the auto increment id with the business login and im not sure this is good..
A: You want to use a foreign key. in events with the user id
To get the events done by a particular user, you just do
select events.*, users.* from users left join events where users.id = events.user_id
WHERE user.username = 'johnboy'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Lazy Initialization Errors from Refreshes How can I prevent LazyInitializationExceptions from being thrown when a page is requested multiple times? If I simply hold Ctrl-R on a page in my webapp, I consistently receive this message in my log files.
I have the following interceptor configured in my servlet.xml file:
<mvc:interceptors>
<bean
class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor" />
</mvc:interceptors>
Yet I constantly receive the following errors:
2011-09-23 15:14:28,854 [http-8080-23] ERROR org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/web-app].[springmvc] - Servlet.service() for servlet springmvc threw exception
org.hibernate.LazyInitializationException: illegal access to loading collection
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:366)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
at org.hibernate.collection.PersistentSet.iterator(PersistentSet.java:186)
Note: Turning logging on the Interceptor I clearly see that it's being invoked and opening / closing transactions:
2011-09-23 15:36:53,229 [http-8080-5] DEBUG org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor IP134.167.141.34 CV#ef955014-cc9d-42fc P#75004 - Opening single Hibernate Session in OpenSessionInViewInterceptor
2011-09-23 15:36:53,229 [http-8080-5] WARN eqip.core.springmvc.extensions.interceptors.AbstractAgencyDataInterceptor IP134.167.141.34 CV#ef955014-cc9d-42fc P#75004 - Pre handle: http://134.167.141.34:8080/web-app/main.xhtml Status: 200
2011-09-23 15:36:53,511 [http-8080-5] WARN org.hibernate.engine.StatefulPersistenceContext.ProxyWarnLog IP134.167.141.34 CV#ef955014-cc9d-42fc P#75004 - Narrowing proxy to class core.model.entities.Subclass - this operation breaks ==
2011-09-23 15:36:53,511 [http-8080-5] WARN org.hibernate.engine.StatefulPersistenceContext.ProxyWarnLog IP134.167.141.34 CV#ef955014-cc9d-42fc P#75004 - Narrowing proxy to class core.model.entities.Subclass - this operation breaks ==
2011-09-23 15:36:53,916 [http-8080-5] DEBUG org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor IP134.167.141.34 CV#ef955014-cc9d-42fc P#75004 - Flushing single Hibernate Session in OpenSessionInViewInterceptor
2011-09-23 15:36:53,916 [http-8080-5] DEBUG org.springframework.web.servlet.DispatcherServlet IP134.167.141.34 CV#ef955014-cc9d-42fc P#75004 - Rendering view [eqip.core.springmvc.extensions.velocity.VelocityToolsLayoutView: name 'pages/myEqip'; URL [pages/main.xhtml]] in DispatcherServlet with name 'springmvc'
2011-09-23 15:36:54,213 [http-8080-5] DEBUG eqip.core.springmvc.extensions.velocity.VelocityToolsLayoutView IP134.167.141.34 CV#ef955014-cc9d-42fc P#75004 - Rendering screen content template [pages/main.xhtml]
2011-09-23 15:36:54,384 [http-8080-5] DEBUG org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor IP134.167.141.34 CV#ef955014-cc9d-42fc P#75004 - Closing single Hibernate Session in OpenSessionInViewInterceptor
Using Spring 3.0.5, Hibernate 3.6.5, velocity 1.7
Final Fix: Was adding the following to our controller declarations:
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
This allowed us to keep use of our interceptors and ensure that we were getting new copies of our pre-loaded pieces on each request.
A: Are you sure that interceptor class is actually called? Get the sources, and do a debug on it to see if the execution actually gets to it. Make sure you've actually declared that interceptor as an interceptor in your spring mvc configuration:
<bean id="urlMapping"class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="openSessionInViewInterceptor"/>
</list>
</property>
<property name="mappings">
</bean>
Or you can just go with the simpler OpenSessionInVIewFilter, which only needs to be configured as a servlet filter that intercepts /* (or a generic enoug URL to encompass all the urls of your controllers that deal with hibernate entities).
A: It might be that you are saving some hibernate objects in the session, these objects might have uninitialized proxies.
Each time you press Ctrl+R, new request opens, and it is not possible to initialize proxy object from previous request durring the current request and as the result LazyInitializationException exception raises.
If this is not your case, then try to dig it in this direction.
A: Write a Class like :-
public class CustomHibernateSessionViewFilter extends OpenSessionInViewFilter {
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
Session session = super.getSession(sessionFactory);
session.setFlushMode(FlushMode.COMMIT);
return session;
}
protected void closeSession(Session session, SessionFactory factory) {
session.flush();
super.closeSession(session, factory);
}
}
Declare it in web.xml like this:-
<filter>
<filter-name>OSIVF Filter</filter-name>
<filter-class>your.path.to.CustomHibernateSessionViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OSIVF Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: FindByIdentity - performance differences The following code works fine from a variety of machines on our domain.
var context = new PrincipalContext(ContextType.Domain);
var principal = UserPrincipal.FindByIdentity(context, @"domain\username")
However, if I run this similar code on a machine that is not on a domain, it works but the FindByIdentity line takes 2+ seconds.
var context = new PrincipalContext(ContextType.Machine);
var principal = UserPrincipal.FindByIdentity(context, @"machinename\username")
Can this performance difference be addressed by supplying special parameters to the PrincipalContext constructor and/or the FindByIdentity method? Is there a setting in IIS or Windows that could be tweaked?
At the very least, can anybody tell me why it might be slower in the second scenario?
The code is running from an ASP.NET MVC 3 app hosted in IIS 7.5 (Integrated Pipeline) on Windows Server 2008 R2.
A: I had the same problem. Try the below block of code. I don't know why but it's much faster (ignore first time slow login after build in VS - subsequent logins are speedy). See similar SO question Why would using PrincipalSearcher be faster than FindByIdentity()?
var context = new PrincipalContext( ContextType.Machine );
var user = new UserPrincipal(context);
user.SamAccountName = username;
var searcher = new PrincipalSearcher(user);
user = searcher.FindOne() as UserPrincipal;
The underlying issue may have something to do with netBios calls. See ADLDS very slow (roundtrip to \Server*\MAILSLOT\NET\NETLOGON)
A: Even with JimSTAT's answer being quite old, it led me into the right direction solving my problem.
I would like to point out that disabling NetBIOS over TCP/IP on all my Hyper-V-Switch network interfaces eliminated every delay I had experienced beforehand. Every call to PrincipalContext(), UserPrincipal.FindByIdentity() and UserPrincipal.GetGroups() is down to 10 ms or lower, from well above 10,000 ms. It appears to me that every virtual network card was being queried which took a felt century to time out. Lucky me I found this post!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: How do you enumerate all accelerators in C++ AMP? In C++ AMP, how does one detect and enumerate all C++ AMP accelerators?
Don McCrady distributed an app here that enumerates non-emulated accelerators. Though I had a DX11 card (GTX 260), I didn't see any available accelerators. Daniel Moth shows here how to query an individual accelerator, but I couldn't find how do enumerate all (emulated and non) accelerators using a C++ AMP call.
A: Looks like it's pretty simple: concurrency::get_accelerators(); Daniel Moth comments:
in the VS 11 Developer Preview bits, you simply call concurrency::get_accelerators();. We are working to make that more discoverable for the Beta, whenever that is.
Here's my code:
#include <iostream>
#include "stdafx.h"
#include "amp.h"
using namespace std;
using namespace concurrency;
void inspect_accelerators()
{
auto accelerators = accelerator::get_all();
for_each(begin(accelerators), end(accelerators),[=](accelerator acc){
wcout << "New accelerator: " << acc.description << endl;
wcout << "is_debug = " << acc.is_debug << endl;
wcout << "is_emulated = " << acc.is_emulated <<endl;
wcout << "dedicated_memory = " << acc.dedicated_memory << endl;
wcout << "device_path = " << acc.device_path << endl;
wcout << "has_display = " << acc.has_display << endl;
wcout << "version = " << (acc.version >> 16) << '.' << (acc.version & 0xFFFF) << endl;
});
}
Update 1:
As of VS 11 Beta, this is now accelerator::get_all();
A: Thanks for reposting the answer from my blog here :-)
You made a side comment in your question:
"Though I had a DX11 card (GTX 260), I didn't see any available accelerators"
If Don's utility didn't find your card, then it is not a DX11 card, or there is a bug in his utility and we'd appreciate you reporting the repro to him. However, I verified on the vendor's site that GTX 260 is a DX10 card. So that would not be a good target for C++ AMP code, unfortunately...
Cheers
Daniel
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: using bitset with floating types Can you have bitset container of floating data types? Example:
bitset<sizeof(float)*sizeof(char)> second(5.5f);
cout << second.to_string() << endl;
It doesn't work correctly. what i'm trying to do is get the bit representation.
A: bitset only takes a unsigned long as its constructor argument. In your example the float is converted to unsigned long and then used as the argument.
To get what you desire use something along the lines of:
float f = 5.5f;
std::bitset<sizeof(float)*CHAR_BIT> foo(*reinterpret_cast<unsigned long*>(&f));
This reinterprets the "memory" the float is in as memory containing an unsigned long and thus "tricks" the constructor.
A: In order to build a bitset from a float in a well-defined manner, you should:
*
*ensure your types have compatible sizes;
*copy the representation of your float into a compatible integer;
*build a bitset from that integer.
Here is a minimal example:
#include <bitset>
#include <cstring>
float f = 1.618;
static_assert(sizeof(float) <= sizeof(long long unsigned int), "wrong sizes"); // 1.
long long unsigned int f_as_int = 0;
std::memcpy(&f_as_int, &f, sizeof(float)); // 2.
std::bitset<8*sizeof(float)> f_as_bitset{f_as_int}; // 3.
But, this won't work as expected on a big endian target whose long long unsigned int is larger than float, because the bitset constructor always pick the least significant bits of the argument, regardless of the endianness. And this sucks.
So, if we want to be complete, we need to address this. To do so, one can copy the float to an integer of the same size (2.), then cast (3.) it to a long long unsigned int, resulting to a endianness-agnostic representation. But yeah, an endianness-agnostic solution is tedious:
#include <bitset>
#include <cstring>
#include <cstdint>
#include <iostream>
namespace details
{
template<unsigned nbits> struct uint {};
template<> struct uint<8> { using type = uint8_t; };
template<> struct uint<16> { using type = uint16_t; };
template<> struct uint<32> { using type = uint32_t; };
template<> struct uint<64> { using type = uint64_t; };
}
template<class T>
using unsigned_integer_of_same_size = typename details::uint<sizeof(T)*8>::type;
int main()
{
float f = -1./0.;
static_assert(sizeof(float) <= sizeof(long long unsigned int), "wrong sizes"); // 1.
unsigned_integer_of_same_size<float> f_as_uint = 0;
std::memcpy(&f_as_uint, &f, sizeof(float)); // 2.
std::bitset<8*sizeof(float)> f_as_bitset{f_as_uint}; // 3. && 4.
std::cout << f_as_bitset << "\n";
}
(live demo)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Detect Arduino port in Python I am using an Arduino for sensing using Python 2.7 on Windows XP, but the non-static nature of the USB-to-serial port translation is giving me a headache. With a physical serial port there is no issue hard coding the port position, but the Arduino is moving around based on what is or is not plugged in at the time of object instantiation. Is there some way in Python for me to just get the port address during each object initialization and pass it to PyVISA or pySerial?
A: I also suggest a handshake but do it the other ay round.
Just READ for input from the all Serial ports before starting your program. As you turn up the Device you can make it send something like an ON signal. when your code detects the ON signal on that port then do a handshake.
A: In pySerial there is a quite hidden way to check for VID/PID on all serial ports (at least on Windows).
Just find the VID/PID of the Arduino in port properties adn put it into the python code.
Of course this won't work if you have multiple Arduino connected (same VID/PID)
import serial.tools.list_ports
for port in list(serial.tools.list_ports.comports()):
if port[2].startswith('USB VID:PID=1234:5678'):
#here you have the right port
A: I recommend a handshaking signal and scanning all the ports. For example, send "whoru" from your python script to the arduiono and have code on the arduiono that responds with "arduino" when it detects "whoru" on the serial port. This way, you scan the ports, send the handshake, and when you get the proper response you know which port the arduino is on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Cygwin's bash became extremely slow after errors I realize there are a few other questions about why Cygwin is apparently slow, but this case seems to be unique.
I had some issues where things were reporting lots of errors, and then after a reboot any process launched from bash is extremely slow. I honestly have no idea what could be causing this (I checked the process priority in taskmgr; it's still normal).
Details:
I was running a soak test of some socket code overnight and came back in the morning to find my screen flooded with errors (DialogBoxes - mostly attempted to access NULL pointers) as well as quite a few things sent to the command line. There was quite a bit of text I wasn't able to capture (the computer was mostly unresponsive; I had to reboot it manually). I do remember some of the text referenced "Win32 error 6" (which I assume means INVALID HANDLE).
After the reboot, most things are fine, but Cygwin/bash is still pretty unresponsive. I ran the following, as suggested in another question:
$ time for i in {1..10} ; do bash -c "echo Hello" ; done
...
real 1m12.244s
user 0m3.522s
sys 0m34.460s
Invoking another bash instance isn't necessary for the terrible speed:
$ time for i in {1..10}; do ls ; done
# nb there are about 6 entries in pwd
....
real 0m47.718s
user 0m2.568s
sys 0m23.411s
Although builtins do seem to go quickly enough:
$ time for i in {1..10} ; do echo Hello ; done
....
real 0m0.001s
user 0m0.000s
sys 0m0.000s
Update:
I just realized a Windows Update installed between then and now, too. I'm glad this isn't getting too complicated or anything. (Although, I believe other coworkers have installed the update and aren't seeing problems).
Update 2:
To answer a comment below, the files in /bin execute without any problems from CMD. Also, I completely removed and re-downloaded my cygwin installation directory and the problem is still occurring.
I'm [still] not entirely sure how to use Cygwin's strace, but I think the first column may be time delta. With that in mind, here's a few lines that look problematic (the 0xDEADBEEF is certainly not encouraging):
4100175 4101564 [main] bash 5664 _cygtls::remove: wait 0xFFFFFFFF
4278898 4279724 [main] bash 5612 child_copy: dll bss - hp 0x628 low 0x611DC000, high 0x612108D0, res 1
2210923 25635973 [proc_waiter] bash 5664 pinfo::maybe_set_exit_code_from_windows: pid 5400, exit value - old 0x8000000, windows 0xDEADBEEF, cygwin 0x8000000
3595425 16085618 [proc_waiter] bash 5612 pinfo::maybe_set_exit_code_from_windows: pid 5376, exit value - old 0x8000000, windows 0xDEADBEEF, cygwin 0x8000000
3057452 19149209 [proc_waiter] bash 5664 pinfo::maybe_set_exit_code_from_windows: pid 5612, exit value - old 0x8000000, windows 0xDEADBEEF, cygwin 0x8000000
2631997 38835042 [proc_waiter] bash 5716 pinfo::maybe_set_exit_code_from_windows: pid 5720, exit value - old 0x8000000, windows 0xDEADBEEF, cygwin 0x8000000
2610852 38836658 [main] bash 4624 _cygtls::remove: wait 0xFFFFFFFF
3708283 42556365 [proc_waiter] bash 5716 pinfo::maybe_set_exit_code_from_windows: pid 4624, exit value - old 0x8000000, windows 0xDEADBEEF, cygwin 0x8000000
3666884 42562053 [main] bash 5664 fhandler_base_overlapped::wait_overlapped: GetOverLappedResult failed, bytes 0
2742397 45305871 [proc_waiter] bash 5664 pinfo::maybe_set_exit_code_from_windows: pid 5716, exit value - old 0x8000000, windows 0xDEADBEEF, cygwin 0x8000000
45322195 45322997 [main] bash 3996 child_copy: dll bss - hp 0x62C low 0x611DC000, high 0x612108D0, res 1
4247577 49581019 [main] bash 3996 _cygtls::remove: wait 0xFFFFFFFF
4266690 49581325 [main] bash 5664 child_info::sync: pid 3996, WFMO returned 0, res 1
49622099 49623318 [main] bash 4840 child_copy: dll bss - hp 0x690 low 0x611DC000, high 0x612108D0, res 1
4225718 53860809 [main] bash 4840 _cygtls::remove: wait 0xFFFFFFFF
4248491 53861119 [main] bash 3996 child_info::sync: pid 4840, WFMO returned 0, res 1
2167422 2169463 [main] bash 1412 _cygtls::remove: wait 0xFFFFFFFF
10369 2205831 [main] bash 1412 pwdgrp::load: \etc\passwd curr_lines 4082
10313 2237148 [main] bash 1412 cygwin_gethostname: name A119894
14720 2251868 [main] bash 1412 stat64: entering
A: I had a similar problem, fixed by removing disconnected network shares.
http://cygwin.com/faq/faq-nochunks.html#faq.using.slow
http://cygwin.com/ml/cygwin/2010-06/msg00510.html (read all replies)
You can look into this as well:
http://cygwin.com/acronyms/#BLODA
gl
A: I have little experience with this, but I can at least give you my opinion on what it looks like.
I'm seeing lots of [proc_wiater] lines, each at over 5000 ... that's longer than your actual directory listing takes :/ Looks like the problem here is "ls is a program". I bet if you timed dir you'd not notice such a ridiculous time.
-Someone who knows nothing of strace.
A: It creates a dirty log file, use awk.
A: So I never actually solved this. Got a new computer instead.
Similar problem cropped up there eventually, and the problem was the NVIDIA driver software--not the actual drivers themselves.
So, the path was:
*
*Install NDIVIA Drivers
*Remove NVIDIA Software from AppWiz.cpl
*Use Hardware Manager to find the .inf files that were left around
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: pass value swt to swf I have a two swf, index and gallery. I am call gallery.swf in to index.swf.
loadMovie("image_gallery/gallery.swf",1);
I want to make pass value from gallery.swf.
How can I do this.
Thanks for answers.
A: You can send values in the URL, like this:
loadMovie("image_gallery/gallery.swf?variableName=value",1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing STL and/or MFC objects between modules I have a rather large code base that is highly modular (lots and lots of plugins), and very often need to pass strings and such between modules. For reference, the code:
*
*only compiles in MSVC/Visual Studio, and very clearly does not and will not support other compilers. Supporting them is not a concern.
*only runs on Windows, and very clearly does not and will not support other OSes. Same as above.
*all modules will be Windows PEs of some sort; assume the same bitness and that they're built for the same platform.
*there are a few spots where MFC is easier to use, a few where STL is. There's a very good chance both will be used within each module.
*The question is only regarding passing objects between modules.
Now, I'm under the impression that passing STL objects between modules can really break, if the library or compiler versio changes. Particularly when it comes to dtors and destroying objects outside of the module/version they were created in.
Is MFC any safer in that way? Can you pass a MFC object (a CString for example) from Base.dll to Plugin.dll safely? Do you have to pass a pointer, can you not safely delete it from the plugin?
Does it matter if MFC is statically linked or used from a DLL?
MSDN mentions in a few places that:
All memory allocations within a regular DLL should stay within the DLL; the DLL should not pass to or receive from the calling executable any of the following:
*
*pointers to MFC objects
*pointers to memory allocated by MFC
If you need to do any of the above, or if you need to pass MFC-derived objects between the calling executable and the DLL, then you must build an extension DLL.
However, the page extension DLLs mention they are intended primarily for implemented objects derived from MFC objects. I have no interest in doing that, just using them and passing between various modules.
Does passing shared_ptrs change anything (or a class with a virtual dtor)?
Is there a solution to this without resorting to C types?
A: An extension DLL will share the MFC DLL with the application and any other extension DLLs, so that objects may be passed freely between them. Microsoft may have intended for extension DLLs to implement extended classes, but that's not a requirement - you can use it any way you want.
The biggest danger with the standard library is that so much of it is based on templates. That's dangerous, because if the DLL and application are built with different versions of the templates you run against the One Definition Rule and undefined behavior bites you in the rear. This is not just initialization or destruction of the object, but any operation against the object whatsoever!
A: You can declare COM-like abstruct-method only interfaces and pass interface instead. For example write a factory method like WMCreateReader that create an object (whether it is MFC based or has STL members does not need to be exposed to the caller) and return its interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Eclipse Plugin - Text Editor - SingleLineRule I've been trying to develop my own text editor through a eclipse plugin.
I would like just highlight some words in a text editor.
I wrote the following lines:
IToken xmlComment = new Token(TEXT_START);
new SingleLineRule("@st","art", textStart);
with these lines I have managed to highlight the word @start. But if I write any upper case letter is not longer highlighted.
It's any way to create a SingleLineRule with a regular expresion???
Thanks in advance!
A: I'm gonna answer my own question:
To create rules for "words" we can use the org.eclipse.jface.text.rules.WordRule Object, its constructor has as arguments the following objects:
word detector It's a implementation of IWordDetector
defaultToken The token itself
ignoreCase Of course a boolean value to ignore case.
Then to add the words just call the addWord method
myWordRule.addWord(myWord, myToken);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Turn Off CKEditor's Auto Correct Settings Does anybody know of a way to turn off CKEditor's HTML tidying function? I know CKEditor has some pretty strict HTML rewriting rules in place, but I am wondering if there is a way to control those so pages being edited don't get messed up when the HTML does not follow CKEditor's concept of valid code?
Is there a plugin to help, maybe, that can help to add exceptions?
A: You can use the config.allowedContent in your config.js file like this:
config.allowedContent = true;
Check documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Set width of list items to fill unordered list So I have a horizontal unordered list with a set width. Inside, I have a dynamic number of list items. It could be 2 items, or 6 - it depends on several factors.
I'd like to be able to set the width of each list item so that they fill the entire width of the ul, no matter how many items are inside. So if there was 1 list item, it's width would be 100%; 2, and they would both be 50%, and so on.
Here's my HTML and CSS:
ul
{
width: 300px;
height: 50px;
background-color: #000000;
list-style: none;
margin: 0;
padding: 0;
}
li
{
float: left;
height: 50px;
background-color: #4265CE;
margin: 0;
padding: 0;
}
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
Here it is in jFiddle: http://jsfiddle.net/vDVvm/3/
Is there a way to do this with CSS, or will I have to use jQuery?
A: No way with pure CSS, I'm afraid.
Edit: Most proper jQuery solution i can think of: http://jsfiddle.net/vDVvm/8/
(function( $ ){
$.fn.autowidth = function() {
return this.each(function() {
$('li', this).css({'width' : (100 / $('li', this).length) + '%'})
});
};
})( jQuery );
$(document).ready(function(){
$('.fill-me').autowidth();
});
Keep in mind though, that whenever (100 % number_of_lis !== 0), you're gonna be running into some nasty problems with rounding errors.
A: A solution without JavaScript.
ul
{
width: 300px;
height: 50px;
background-color: #000000;
list-style: none;
margin: 0;
padding: 0;
display: table;
}
li
{
height: 50px;
background-color: #4265CE;
margin: 0;
padding: 0;
display: table-cell;
}
http://jsfiddle.net/vDVvm/5/
It may be not cross browser enough, however.
A: This is also possible just with css, but will only work in modern browsers.
ul {
/* ... */
display: table;
}
li {
/* ... */
display: table-cell;
}
A: Using jQuery, you can do something like this :
var li = $('#mylist li').size();
var liWidth = 100 / li;
$('#mylist li').width(liWidth + '%');
assuming your HTML looks like:
<ul id="mylist">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
A: Here's a working fiddle : http://jsfiddle.net/vDVvm/7/
A: Here is an improvement on vzwick's function:
(function( $ ){
$.fn.autowidth = function() {
return this.each(function() {
var w = $(this).width();
var liw = w / $(this).children('li').length;
$(this).children('li').each(function(){
var s = $(this).outerWidth(true)-$(this).width();
$(this).width(liw-s);
});
});
};
})( jQuery );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to create a fade transition between the images in an image map / swap. I have created a map of a part of Florida. It contains hotspots over different locations and when you hover over them, all other areas darken. What I have done is create one normal image of the map and separate images for each location with the surrounding areas darkened. When you hover over the area on the map it swaps with the other image. Im trying to achieve this effect: http://www.sandestin.com/Map.html
I want to create a fade between the images instead of just a normal quick swap. I have been working on this one part of the project for the past 2 days and for some reason cant seem to figure it out.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Outdoor Map PNG.gif</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--Fireworks CS5 Dreamweaver CS5 target. Created Wed Sep 21 18:18:30 GMT-0500 (Central Daylight Time) 2011-->
<script language="JavaScript1.2" type="text/javascript">
<!--
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
//-->
</script>
</head>
<body bgcolor="#ffffff" onload="MM_preloadImages('../../../../Map/Out Door Rallavers/PNG/Inlet Beach OD PNG.png','Outdoor%20Map%20PNG.gif','../../../../Map/Out Door Rallavers/PNG/BGS OD.png','../../../../Map/Out Door Rallavers/PNG/Santa Rosa OD PNG.png','../../../../Map/Out Door Rallavers/PNG/Sandestin OD PNG.png','../../../../Map/Out Door Rallavers/PNG/Miramar OD PNG.png','../../../../Map/Out Door Rallavers/PNG/Destin OD PNG.png','../../../../Map/Out Door Rallavers/PNG/Okaloosa OD PNG.png');">
<img name="OutdoorMapPNG" src="Outdoor%20Map%20PNG.gif" width="960" height="296" border="0" id="OutdoorMapPNG" usemap="#m_Outdoor20Map20PNG" alt="" /><map name="m_Outdoor20Map20PNG" id="m_Outdoor20Map20PNG">
<area shape="rect" coords="688,74,960,295" href="javascript:;" alt="" onmouseout="MM_swapImage('OutdoorMapPNG','','Outdoor%20Map%20PNG.gif',1);" onmouseover="MM_swapImage('OutdoorMapPNG','','../../../../Map/Out Door Rallavers/PNG/Inlet Beach OD PNG.png',1);" />
<area shape="rect" coords="596,51,693,177" href="javascript:;" alt="" onmouseout="MM_swapImage('OutdoorMapPNG','','Outdoor%20Map%20PNG.gif',1);" onmouseover="MM_swapImage('OutdoorMapPNG','','../../../../Map/Out Door Rallavers/PNG/BGS OD.png',1);" />
<area shape="rect" coords="487,0,596,143" href="javascript:;" alt="" onmouseout="MM_swapImage('OutdoorMapPNG','','Outdoor%20Map%20PNG.gif',1);" onmouseover="MM_swapImage('OutdoorMapPNG','','../../../../Map/Out Door Rallavers/PNG/Santa Rosa OD PNG.png',1);" />
<area shape="rect" coords="394,9,488,108" href="javascript:;" alt="" onmouseout="MM_swapImage('OutdoorMapPNG','','Outdoor%20Map%20PNG.gif',1);" onmouseover="MM_swapImage('OutdoorMapPNG','','../../../../Map/Out Door Rallavers/PNG/Sandestin OD PNG.png',1);" />
<area shape="rect" coords="321,43,395,88" href="javascript:;" alt="" onmouseout="MM_swapImage('OutdoorMapPNG','','Outdoor%20Map%20PNG.gif',1);" onmouseover="MM_swapImage('OutdoorMapPNG','','../../../../Map/Out Door Rallavers/PNG/Miramar OD PNG.png',1);" />
<area shape="rect" coords="174,17,321,77" href="file:///C:/Users/Phillip/Desktop/ECCI/web_map/google_map_version/index.html" alt="" onmouseout="MM_swapImage('OutdoorMapPNG','','Outdoor%20Map%20PNG.gif',1);" onmouseover="MM_swapImage('OutdoorMapPNG','','../../../../Map/Out Door Rallavers/PNG/Destin OD PNG.png',1);" />
<area shape="rect" coords="0,42,182,74" href="javascript:;" alt="" onmouseout="MM_swapImage('OutdoorMapPNG','','Outdoor%20Map%20PNG.gif',1);" onmouseover="MM_swapImage('OutdoorMapPNG','','../../../../Map/Out Door Rallavers/PNG/Okaloosa OD PNG.png',1);" />
<area shape="rect" coords="0,42,182,74" href="javascript:;" alt="" />
</map>
</body>
</html>
A: In the interest of science I set about to figure out how to do this without JavaScript. It was a little tricky but nothing major. Take a look. It uses CSS3 transitions (namely transition-property: opacity), which should work on all major browsers (I think even IE10).
I've commented the heck out of the code at the above link, but the gist, sans comments, is:
Markup:
<ul id="map">
<li id="foo"><a href="#">Hello</a></li>
<li id="bar"><a href="#">Goodbye</a></li>
<li id="mask"></li>
</ul>
CSS:
#foo { left: 35px; top: 35px; }
#foo:hover ~ #mask { background-position: -265px -265px }
#bar { left: 160px; top: 160px; }
#bar:hover ~ #mask { background-position: -140px -140px; }
#map, #mask {
width: 300px; height: 300px;
}
#map {
border: 1px solid black;
position: relative;
background: url(http://i.imgur.com/zucgV.png) no-repeat;
}
#map li {
position: absolute;
width: 100px; height: 100px;
z-index: 1;
}
#map a {
color: transparent;
display: block;
position: absolute;
width: 100px; height: 100px;
z-index: 100;
}
li#mask {
width: 300px; height: 300px;
background: url(http://i.imgur.com/S9Z7W.png) no-repeat;
-webkit-transition: opacity 0.2s ease-in-out, visibility 0s linear 0.2s;
-moz-transition: opacity 0.2s ease-in-out, visibility 0s linear 0.2s;
-o-transition: opacity 0.2s ease-in-out, visibility 0s linear 0.2s;
-ms-transition: opacity 0.2s ease-in-out, visibility 0s linear 0.2s;
transition: opacity 0.2s ease-in-out, visibility 0s linear 0.2s;
opacity: 0;
visibility: hidden;
}
#map li:hover { z-index: 10; }
#map :hover ~ #mask {
-webkit-transition-delay: 0s
-moz-transition-delay: 0s;
-o-transition-delay: 0s;
transition-delay: 0s;
opacity: .75;
visibility: visible;
}
One nice thing about this approach is that you only need one image for the map and one image to darken the "unlit" areas (if your "hotspots" are different sizes, though, you'll need to use different background images or use the background-size property). For each "hotspot" you just give the "darkening" image a different background-position. You could even do some more interesting transitions, like making the spotlight "fly" from one hotspot to another. Just a thought. I hope you use this as inspiration to turn your map into a lightweight, modern experience.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using readablity.js from a Windows Desktop App I need to obtain a stripped down version of a web page programmatically using readability.js and the webbrowser control.
http://arc90labs-readability.googlecode.com/svn/trunk/js/readability.js
Do I have to load the web page I want to strip into the webbrowser control and then inject the readability javascript function into the HEAD and somehow call it from there (using WebBrowser1.Document.parentWindow.execScript) or is there some easier way to go?
Just looking for a bump in the right direction.
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: View Array contents in Qt Creator debugger I am using Qt on Ubuntu. When I debug I only see the very first value of the array in Locals and Watchers. How can I view all the array contents?
struct node
{
int *keys;
void **pointers;
int num_keys;
struct node *parent;
int is_leaf;
struct node *nextLevelNode;
};
It shows only the first key value in the debugging window.
A:
It shows only the first key value,in the debugging window
I presume you're referring to the pointer keys, declared with int *keys;
The debugger doesn't know that this is an array: all it knows is that this is a pointer to an int. So it can't know how many values you want it to display.
What I've found, using the Qt Creator 2.1.0 debugger on Ubuntu, is that the following code allows me to see all 5 values:
int array1[5];
array1[0] = 2;
array1[1] = 4;
array1[2] = 6;
array1[3] = 8;
array1[4] = 10;
Whereas with this code, the debugger only shows the first value, exactly as you describe.
int* array2 = new int[5];
array2[0] = 20;
array2[1] = 21;
array2[2] = 22;
array2[3] = 23;
array2[4] = 24;
Aside: of course, the above code would be followed by this, to avoid leaking memory:
delete[] array2;
Later: This Qt Developer Network Forum Post says that you can tell the debugger to display a pointer as an array:
In Locals and Watchers, context menu of your pointer’s entry, select “Watch Expression”. This creates a new watched expression below.
There, double click on the entry in the “Names” column, and add “@10” to display 10 entries.
This sounds like it should get you going.
A: Just right-click on your variable, and choose Change Value Display Format and check Array of 100 items.
A: In Expression evaluator,
Try (int[10])(*myArray) instead of (int[10])myArray
Or, *myArray@10 instead of myArray@10
A: In Qt for mac what worked for me was:
*
*Add an expression evaluator for the desired variable (right click the variable on the debugger window then "Add expression evaluator for "var name here""
*The array variable appears initially as a single value. Just change "var" to "var[start...end] and the array values appear.
A: Two dimensional arrays sometimes cannot be displayed that way. There is a work-around. First, declare a two-dimensional array as a one-dimensional array like this:
int width = 3;
int height = 4;
int* array2D = new int [width*height];
int x,y;
for(x=width-1;x>-1;x--)
for(y=height-1;y>-1;y--)
array2D[x*height + y] = -1; // mark a breakpoint here!
// add to expression evaluator: (int[3][4]) *array2D
delete [] array2D;
Then add (int[3][4]) *array2D to the expression evaluator. Unfortunately you have to index the array your self, but you can write a special-purpose inline function or use another encapsulation method to make it slightly cleaner.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: include_once errors with youtube api / Zend Gdata I'm using Zend Framework ver 1.11.10, specifically the GDATA/YouTube functions.
My log is getting blasted with
include_once(Zend\Gdata\Media\Extension\VideoQuery.php) failed to open stream: No such file or directory C:\Zend\ZendServer\share\ZendFramework\library\Zend\Loader.php 148
include_once(): Failed opening "Zend\Gdata\Media\Extension\VideoQuery.php" for inclusion (include_path=".;C:\Zend\ZendServer\share\ZendFramework\library") C:\Zend\ZendServer\share\ZendFramework\library\Zend\Loader.php 148
include_once(Zend\Gdata\Media\VideoQuery.php) failed to open stream: No such file or directory C:\Zend\ZendServer\share\ZendFramework\library\Zend\Loader.php 148
include_once() Failed opening "Zend\Gdata\Media\VideoQuery.php" for inclusion (include_path=".;C:\Zend\ZendServer\share\ZendFramework\library") C:\Zend\ZendServer\share\ZendFramework\library\Zend\Loader.php 148
include_once(Zend\Gdata\YouTube\Extension\VideoQuery.php) failed to open stream: No such file or directory C:\Zend\ZendServer\share\ZendFramework\library\Zend\Loader.php 148
include_once() Failed opening "Zend\Gdata\YouTube\Extension\VideoQuery.php" for inclusion (include_path=".;C:\Zend\ZendServer\share\ZendFramework\library") C:\Zend\ZendServer\share\ZendFramework\library\Zend\Loader.php 148
Stepping through the code, I get to gdata\app.php in line 1046 where its looping through all the _registeredpackages, the first 3 being the ones listed above until it gets to the right class Zend_Gdata_YouTube.
So my question is how can I get the above messaged to not log? Seems there would be a fail-safe to verify the file exists before it tries to include it.
Note: I went back and reviewed my logs and these errors haven't always been there, even when using the Zend framework. I'm wondering if I caused this to happen somehow.
A: I've solved it by calling registerPackage('Zend_Gdata_YouTube'); on Zend_Gdata_YouTube instance.
$yt = new Zend_Gdata_YouTube();
$yt->registerPackage('Zend_Gdata_YouTube');
This simply unshift the correct package to _registeredpackages.
Now the following code doesn't produce errors by Zend_Loader:
$yt->newVideoQuery();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Explanation of combinators for the working man What is a combinator??
Is it "a function or definition with no free variables" (as defined on SO)?
Or how about this: according to John Hughes in his well-known paper on Arrows, "a combinator is a function which builds program fragments from program fragments", which is advantageous because "... the programmer using combinators constructs much of the desired program automatically, rather than writing every detail by hand". He goes on to say that map and filter are two common examples of such combinators.
Some combinators which match the first definition:
*
*S
*K
*Y
*others from To Mock a Mockingbird (I may be wrong -- I haven't read this book)
Some combinators which match the second definition:
*
*map
*filter
*fold/reduce (presumably)
*any of >>=, compose, fmap ?????
I'm not interested in the first definition -- those would not help me to write a real program (+1 if you convince me I'm wrong). Please help me understand the second definition. I think map, filter, and reduce are useful: they allow me to program at a higher level -- fewer mistakes, shorter and clearer code. Here are some of my specific questions about combinators:
*
*What are more examples of combinators such as map, filter?
*What combinators do programming languages often implement?
*How can combinators help me design a better API?
*How do I design effective combinators?
*What are combinators similar to in a non-functional language (say, Java), or what do these languages use in place of combinators?
Update
Thanks to @C. A. McCann, I now have a somewhat better understanding of combinators. But one question is still a sticking point for me:
What is the difference between a functional program written with, and one written without, heavy use of combinators?
I suspect the answer is that the combinator-heavy version is shorter, clearer, more general, but I would appreciate a more in-depth discussion, if possible.
I'm also looking for more examples and explanations of complex combinators (i.e. more complex than fold) in common programming languages.
A:
I'm not interested in the first definition -- those would not help me to write a real program (+1 if you convince me I'm wrong). Please help me understand the second definition. I think map, filter, and reduce are useful: they allow me to program at a higher level -- fewer mistakes, shorter and clearer code.
The two definitions are basically the same thing. The first is based on the formal definition and the examples you give are primitive combinators--the smallest building blocks possible. They can help you to write a real program insofar as, with them, you can build more sophisticated combinators. Think of combinators like S and K as the machine language of a hypothetical "combinatory computer". Actual computers don't work that way, of course, so in practice you'll usually have higher-level operations implemented behind the scenes in other ways, but the conceptual foundation is still a useful tool for understanding the meaning of those higher-level operations.
The second definition you give is more informal and about using more sophisticated combinators, in the form of higher-order functions that combine other functions in various ways. Note that if the basic building blocks are the primitive combinators above, everything built from them is a higher-order function and a combinator as well. In a language where other primitives exist, however, you have a distinction between things that are or are not functions, in which case a combinator is typically defined as a function that manipulates other functions in a general way, rather than operating on any non-function things directly.
What are more examples of combinators such as map, filter?
Far too many to list! Both of those transform a function that describes behavior on a single value into a function that describes behavior on an entire collection. You can also have functions that transform only other functions, such as composing them end-to-end, or splitting and recombining arguments. You can have combinators that turn single-step operations into recursive operations that produce or consume collections. Or all kinds of other things, really.
What combinators do programming languages often implement?
That's going to vary quite a bit. There're relatively few completely generic combinators--mostly the primitive ones mentioned above--so in most cases combinators will have some awareness of any data structures being used (even if those data structures are built out of other combinators anyway), in which case there are typically a handful of "fully generic" combinators and then whatever various specialized forms someone decided to provide. There are a ridiculous number of cases where (suitably generalized versions of) map, fold, and unfold are enough to do almost everything you might want.
How can combinators help me design a better API?
Exactly as you said, by thinking in terms of high-level operations, and the way those interact, instead of low-level details.
Think about the popularity of "for each"-style loops over collections, which let you abstract over the details of enumerating a collection. These are just map/fold operations in most cases, and by making that a combinator (rather than built-in syntax) you can do things such as take two existing loops and directly combine them in multiple ways--nest one inside the other, do one after the other, and so on--by just applying a combinator, rather than juggling a whole bunch of code around.
How do I design effective combinators?
First, think about what operations make sense on whatever data your program uses. Then think about how those operations can be meaningfully combined in generic ways, as well as how operations can be broken down into smaller pieces that are connected back together. The main thing is to work with transformations and operations, not direct actions. When you have a function that just does some complicated bit of functionality in an opaque way and only spits out some sort of pre-digested result, there's not much you can do with that. Leave the final results to the code that uses the combinators--you want things that take you from point A to point B, not things that expect to be the beginning or end of a process.
What are combinators similar to in a non-functional language (say, Java), or what do these languages use in place of combinators?
Ahahahaha. Funny you should ask, because objects are really higher-order thingies in the first place--they have some data, but they also carry around a bunch of operations, and quite a lot of what constitutes good OOP design boils down to "objects should usually act like combinators, not data structures".
So probably the best answer here is that instead of combinator-like things, they use classes with lots of getter and setter methods or public fields, and logic that mostly consists of doing some opaque, predefined action.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "95"
} |
Q: Why is it that when I have X(long) / (Y*Y*Y)(long) I get Error: Divide by Zero? In my example X is already long and Y is a long also. I am not casting at then.
I really just want to divide by a number that is cubed. (using native libraries)
These numbers are extremely large. If I convert them to floats and do it, its value is Infinite...
System.out.println(formatter.format("%20d", (X/(Y*Y*Y))));
Y is an extremely large number, it is not 0. X is a measurement of time in milliseconds.
I will post the exact code in a short while if this question doesn't get closed... I don't have access to it right this minute.
Context: I am dealing with a big notation calculation for O(n^3).
Error: "Exception in thread "main" java.lang.ArithmeticException: / by zero"
Answers:
Assuming you didn't really mean the quotes, the likely reason is that
Y * Y * Y is greater than 2 ^ 31. It's overflowing, with a lower part
of 0. I believe this would only happen if Y is a multiple of 2^11
(2048) - but I'm not certain*
-This is the case for me, Y is a multiple of 2048, hopefully this helps with trying to find a solution.
// Algorithm 3
for( int n = 524288; n <= 5000000; n *= 2 ){
int alg = 3;
long timing;
maxSum = maxSubSum3( a );
timing = getTimingInfo( n, alg );
System.out.println(fmt.format("%20s %20d %20d %20d %20d %20s%n", "Alg. 3", n, timing, timing, timing/(n*n), "time/(n*log(n))"));
}
A: Surely you don't mean to pass "(X/(Y*Y*Y))" as a string literal? that's a string containing your express, and not compilable Java code that expresses a computation that Java will perform. So that's problem #1: remove those quotes.
Second, the formatter has nothing to do with dividing numbers, so that is not relevant nor your problem.
Third, casting has nothing to do with this. Your problem is exactly what it says: you're dividing by zero. I assume you don't want to do that. So, Y must be 0.
Fourth, nothing here uses native libraries. It's all Java. Right, that's what you mean?
You may want to use BigInteger to perform math on very large values that overflow a long. But, that will not make division by zero somehow not be division by zero.
A: Assuming you didn't really mean the quotes, the likely reason is that Y * Y * Y is greater than 2 ^ 31. It's overflowing, with a lower part of 0.
I believe this would only happen if Y is a multiple of 2^11 (2048) - but I'm not certain.
It can be avoided by making sure that the computation of Y^3 is done using some datatype that can hold it. If it's less than 2 million, you can use a long instead. If not, you'll have to either use a double or a BigInteger. Given that your other value is in milliseconds, I'd guess that floating point would be fine. So you'd end up with:
System.out.println(formatter.format("%20d", (int)(X/((double)Y*Y*Y))));
You may want to use floating point for the output as well - I assumed not.
A: Perhaps you should try, either with long or float conversions:
( ( X / Y ) / Y ) / Y
If Y is a high enough power of 2 (2^22 or more), then Y^3 will be a higher than 2^64 power of 2. And long uses 64 bits in Java, isn't that correct?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Is `xargs` the way to go with this problem? I've got a text file with a listing of file locations I want to move, first to temporary directory, do some in the source directory then move the files back to the original location.
The listing file is of the format generated by, say, a find command, such as:
~/$ find . -name "*.[ch]" > ~/tmp/my_file_list.txt
Currently I'm using sed to manipulate the file on the screen, and cutting and pasting its output to issue the commands. I find this offensive, but it works:
~/$ sed -r 's_.+_cp & ~/tmp/_' ~/tmp/my_file_list.txt
(copy and paste outputs, then to put the files back)
~/$ sed -r 's_.+/(.+)_cp ~/tmp/\1 &_' ~/tmp/my_file_list.txt
(copy ... paste ... wince)
How could I do the above two lines simply without the copy and paste ... I'm thinking xargs might hold the solution I yearn.
[Edit]
To deal with spaces:
~/$ sed -r 's_.+_cp "&" ~/tmp/_' ~/tmp/my_file_list.txt
and
~/$ sed -r 's_.+/(.+)_cp "~/tmp/\1" "&"_' ~/tmp/my_file_list.txt
A: Simply pipe the output into bash:
~/$ sed -r 's_.+_cp & ~/tmp/_' ~/tmp/my_file_list.txt | bash
A: Although I see you've already gotten an answer that solves the copy-paste problem, I would actually suggest using rsync for this. The sequence would go as follows:
~/$ find . -name "*.[ch]" > ~/tmp/my_file_list.txt
To backup:
~/$ rsync --files-from=tmp/my_file_list.txt . tmp/
Do whatever with the original files, then to restore:
~/$ rsync --files-from=tmp/my_file_list.txt tmp/ .
This has the (negligible) advantage of not copying files that you haven't modified, thus saving a bit of disk activity. It has the less negligible advantage that if you have multiple files with the same name in different directories, they won't clash because rsync preserves the relative paths.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: System.ArgumentException: Parameter is not valid I have a page that sends html5 canvas data, encoded as a base64 bmp image (using this algorithm http://devpro.it/code/216.html) to a serverside process that converts it into a System.Drawing.Image object and does some operations on it.
In my local environment, this works just fine, but on my ec2 instance I get the following error:
System.ArgumentException: Parameter is not valid. at
System.Drawing.Image.FromStream(Stream stream, Boolean
useEmbeddedColorManagement, Boolean validateImageData) at
System.Drawing.Image.FromStream(Stream stream, Boolean
useEmbeddedColorManagement)
My code looks as follows:
System.Drawing.Image image = null;
string b64string = "...";
byte[] sf = Convert.FromBase64String(b64string );
using (MemoryStream s = new MemoryStream(sf, 0, sf.Length))
{
image = System.Drawing.Image.FromStream(s, false);
}
...
Here's a text file with a sample b64string that I'm using to test: https://docs.google.com/leaf?id=0BzVLGmig1YZ3MTM0ODBiNjItNzk4Yi00MzI5LWI5ZWMtMzU1OThlNWEyMTU5&hl=en_US
I've also tried the following and had the same results:
System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
image = converter.ConvertFrom(sf) as System.Drawing.Image;
Any insight would be greatly appreciated!
A: I still don't know the real cause of your problem, but i guess it is related with a image format which Image class doesn't recognize. After inspecting the binary data a little bit, I could be able to form your image. I hope this helps.
Bitmap GetBitmap(byte[] buf)
{
Int16 width = BitConverter.ToInt16(buf, 18);
Int16 height = BitConverter.ToInt16(buf, 22);
Bitmap bitmap = new Bitmap(width, height);
int imageSize = width * height * 4;
int headerSize = BitConverter.ToInt16(buf, 10);
System.Diagnostics.Debug.Assert(imageSize == buf.Length - headerSize);
int offset = headerSize;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
bitmap.SetPixel(x, height - y - 1, Color.FromArgb(buf[offset + 3], buf[offset], buf[offset + 1], buf[offset + 2]));
offset += 4;
}
}
return bitmap;
}
private void Form1_Load(object sender, EventArgs e)
{
using (FileStream f = File.OpenRead("base64.txt"))
{
byte[] buf = Convert.FromBase64String(new StreamReader(f).ReadToEnd());
Bitmap bmp = GetBitmap(buf);
this.ClientSize = new Size(bmp.Width, bmp.Height);
this.BackgroundImage = bmp;
}
}
A: The posted code seems correct. I have tested it and it works fine.
The exception "System.ArgumentException: Parameter is not valid." without any other hint (especially not the name of the parameter) is a wrapper for GDI+ (the underlying technology behind .NET Image class) standard InvalidParameter error, which does not tell use exactly what parameter is invalid.
So, following the FromStream code with .NET Reflector, we can see that the parameters used in GDI+ calls are essentially ... the input stream.
So my guess is the input stream you provide is sometimes invalid as an image? You should save the failing input streams (using File.SaveAllBytes(sf) for example) for further investigation.
A: This could happen if sf contained invalid image data. Verify the validity of the data you're passing into the stream, and see if that fixes your issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Deserialize unknown section into List or Dictionary I have the following XML file:
<Error>0</Error>
<Description>1</Description>
<Document>
<ObjectID>06098INF1761320</ObjectID>
<ced>109340336</ced>
<abstract>DAVID STEVENSON</abstract>
<ced_a />
<NAM_REC />
<ced_ap2 />
</Document>
So I deserialize it on C# (4.0) with this objects structure:
[XmlElement("Error")]
public string Error { get; set; }
[XmlElement("Description")]
public string Description { get; set; }
[XmlElement("Document")]
public List<EDocument> LstDocument { get; set; }
So here's my issue: the element "Document" has unknown sub-elements: ObjectID, ced, etc., is there a way that I can deserialize those unknows elements into a List, Array, Dictionary or something to iterate with (something like this, it DOESN'T have to be exactly like this, I'm just guessing):
object.LstDocument[0].ListDocument.name; //to get the name
object.LstDocument[0].ListDocument.value; //to get the value
Any help would be appreciated.
EDIT 1:
To add some extra clarification to my question:
The child nodes under "Document" element are unknown because they are variable, with this I mean that at a moment I could have "ObjectID" and "ced", in other moment they could be "ced","ABC", etc. I'm not sure which elements came there as child nodes, all I know is that they are elements (not attributes) and that they don't have any child-nodes inside them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ClearCase UCM: Is it possible to have a temporary view on any given baseline? Is it possible to open a view (snapshot or dynamic, maybe readonly) on any given baseline (recommended or older) in a stream (integration, development or child) for performing some tasks and then remove the view when done? How?
A: To open a view to a given baseline, you actually need a view associated to a stream with said baseline as a foundation baseline.
That means you need to rebase that stream first, which is:
*
*not always desirable (since you would need to merge said baseline with current content, and that doesn't always make sense)
*not always possible (you can only rebase a sub-stream with baselines coming from its immediate parent).
What is possible is to:
*
*get the stream on which your baseline has been put
*make a sub-stream from that stream, taking said baseline as the foundatio one
*create a snapshot or dynamic view on it
*do your work
*put a new baseline, and deliver it to its parent stream
*obsolete that sub-stream (and you can delete your view if you want)
Note: you could create a base ClearCase dynamic view (ie non-UCM) with a config spec you could then change as you want, but that wouldn't allow you to checkout and modify any file.
That would only be a convenient way to visualize any baseline of your choice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: NSFetchedResultsController with relationship not updating Let's say I have two entities, Employee and Department. A department has a to-many relationship with an employee, many employees can be in each department but each employee only belongs to one department. I want to display all of the employees in a table view sorted by data that is a property of the department they belong to using an NSFetchedResultsController. The problem is that I want my table to update when a department object receives changes just like it does if the regular properties of employee change, but the NSFetchedResultsController doesn't seem to track related objects. I've gotten passed this issue partially by doing the following:
for (Employee* employee in department.employees) {
[employee willChangeValueForKey:@"dept"];
}
/* Make Changes to department object */
for (Employee* employee in department.employees) {
[employee didChangeValueForKey:@"dept"];
}
This is obviously not ideal but it does cause the employee based FRC delegate method didChangeObject to get called. The real problem I have left now is in the sorting a FRC that is tracking employee objects:
NSEntityDescription *employee = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:self.managedObjectContext];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"department.someProperty" ascending:NO];
This works great and sorts the employees correctly the first time it's called, the problem is that when I make changes to some property of a department that should change the sorting of my employee table, nothing happens. Is there any nice way to have my employee FRC track changes in a relationship? Particularly I just need some way to have it update the sorting when the sort is based on a related property. I've looked through some similar questions but wasn't able to find a satisfactory solution.
A: Swift
Because the NSFetchedResultsController is designed for one entity at a time, you have to listen to the NSManagedObjectContextObjectsDidChangeNotification in order to be notified about all entity relationship changes.
Here is an example:
//UITableViewController
//...
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(managedObjectsDidChangeHandler(notification:)), name: .NSManagedObjectContextObjectsDidChange, object: mainManagedContext)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .NSManagedObjectContextObjectsDidChange, object: mainManagedContext)
}
@objc fileprivate func managedObjectsDidChangeHandler(notification: NSNotification) {
tableView.reloadData()
}
//...
A: The NSFetchedResultsController is only designed to watch one entity at a time. Your setup, while it makes sense, it a bit beyond what the NSFetchedResultsController is currently capable of watching on its own.
My recommendation would be to set up your own watcher. You can base it off the ZSContextWatcher I have set up on GitHub, or you can make it even more straightforward.
Basically, you want to watch for NSManagedObjectContextDidSaveNotification postings and then reload your table when one fire that contains your department entity.
I would also recommend filing a rdar with Apple and asking for the NSFetchedResultsController to be improved.
A: This is a known limitation of NSFetchedResultsController: it only monitors the changes of you entity's properties, not of its relationships' properties. But your use case is totally valid, and here is how to get over it.
Working Principle
After navigating a lot of possible solutions, now I just create two NSFetchedResultsController: the initial one (in your case, Employee), and another one to monitor the entities in the said relationship (Department). Then, when a Department instance is updated in the way it should update your Employee FRC, I just fake a change of the instances of affiliated Employee using the NSFetchedResultsControllerDelegate protocol. Note that the monitored Department property must be part of the NSSortDescriptors of its NSFetchedResultsController for this to work.
Example code
In your example if would work this way:
In your view controller:
var employeesFetchedResultsController:NSFetchedResultsController!
var departmentsFetchedResultsController:NSFetchedResultsController!
Also make sure you declare conformance to NSFetchedResultsControllerDelegate in the class declaration.
In viewDidLoad():
override func viewDidLoad() {
super.viewDidLoad()
// [...]
employeesFetchedResultsController = newEmployeesFetchedResultsController()
departmentsFetchedResultsController = newDepartmentsFetchedResultsController()
// [...]
}
In the departmentsFetchedResultsController creation:
func newDepartmentsFetchedResultsController() {
// [specify predicate, fetchRequest, etc. as usual ]
let monitoredPropertySortDescriptor:NSSortDescriptor = NSSortDescriptor(key: "monitored_property", ascending: true)
request.sortDescriptors = [monitoredPropertySortDescriptor]
// continue with performFetch, etc
}
In the NSFetchedResultsControllerDelegate methods:
That's where the magic operates:
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
if controller == departmentsFetchedResultsController {
switch(type){
case .insert, .delete, .update:
managedObjectContext.performAndWait {
let department = anObject as! Department
for employee in (department.employees ?? []) {
// we fake modifying each Employee so the FRC will refresh itself.
let employee = employee as! Employee // pure type casting
employee.department = department
}
}
break
default:
break
}
}
}
This fake update of the department of each impacted employee will trigger the proper update of employeesFetchedResultsController as expected.
A: SwiftUI
I haven't seen posts that directly addressed this issue in SwiftUI. After trying solutions outlined in many posts, and trying to avoid writing custom controllers, the single factor that made it work in SwiftUI—which was part of the previous post from harrouet (thank you!)—is:
Make use of a FetchRequest on Employee.
If you care about, say, the employee count per department, the fake relationship updates did not make a difference in SwiftUI. Neither did any willChangeValue or didChangeValue statements. Actually, willChangeValue caused crashes on my end.
Here's a setup that worked:
import CoreData
struct SomeView: View {
@FetchRequest var departments: FetchedResults<Department>
// The following is only used to capture department relationship changes
@FetchRequest var employees: FetchedResults<Employee>
var body: some View {
List {
ForEach(departments) { department in
DepartmentView(department: department,
// Required: pass some dependency on employees to trigger view updates
totalEmployeeCount: employees.count)
}
}
//.id(employees.count) does not trigger view updates
}
}
struct DepartmentView: View {
var department: Department
// Not used, but necessary for the department view to be refreshed upon employee updates
var totalEmployeeCount: Int
var body: some View {
// The department's employee count will be refreshed when, say,
// a new employee is created and added to the department
Text("\(department) has \(department.employees.count) employee(s)")
}
}
I don't know if this fixes all the potential issues with CoreData relationships not propagating to views, and it may present efficiency issues if the number of employees is very large, but it worked for me.
An alternative that also worked for establishing the right employee count without grabbing all employees—which may address the efficiency issue of the above code snippet—is to create a view dependency on a NSFetchRequestResultType.countResultType type of FetchRequest:
// Somewhere in a DataManager:
import CoreData
final class DataManager {
static let shared = DataManager()
let persistenceController: PersistenceController
let context: NSManagedObjectContext!
init(persistenceController: PersistenceController = .shared) {
self.persistenceController = persistenceController
self.context = persistenceController.container.viewContext
}
func employeeCount() -> Int {
var count: Int = 0
context.performAndWait {
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Employee")
fetchRequest.predicate = nil
fetchRequest.resultType = NSFetchRequestResultType.countResultType
do {
count = try context.count(for: fetchRequest)
} catch {
fatalError("error \(error)")
}
}
return count
}
}
And the main View becomes:
import CoreData
struct SomeView: View {
@FetchRequest var departments: FetchedResults<Department>
// No @FetchRequest for all employees
var dataManager = DataManager.shared
var body: some View {
List {
ForEach(departments) { department in
DepartmentView(department: department,
// Required: pass some dependency on employees to trigger view updates
totalEmployeeCount: dataManager.employeeCount())
}
}
//.id(dataManager.employeeCount()) does not trigger view updates
}
}
// DepartmentView stays the same.
Again, this may not resolve all possible relationship dependencies, but it gives hope that view updates can be prompted by considering various types of FetchRequest dependencies within the SwiftUI views.
A note that DataManager needs NOT be an ObservableObject being observed in the View for this to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Facebook API: list of most liked pages Using the Facebook API, is it possible to get a list of the most liked pages (non Facebook pages) that were liked in a certain time span?
A: A list of pages is not available via the Facebook Graph API. You could scrape their Page Browser, as it does not require anyone to be logged into Facebook. It also has an option for pages by country.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to loop and compare two arrays at the same time(PHP) I have two array. What I want to do is compare the key ['user_id'] of two arrays, if they are the same, pass the ['user_id'] and ['ref'] in hidden form. I tried to put them into two foreach, but system seems into a dead lock.
<?php foreach($_SESSION['printing_set'] as $data) { ?>
<?php foreach(getProvenaMailableUserlist() as $userlist){ ?>
<input type="hidden" name="reference[<?php echo $data['user_id'] ?>]" value="<? if($userlist['user_id'] == $data['user_id']){echo $userlist['ref'];} ?>" />
<?php } ?>
<?php } ?>
What is the right way to do that?
A: What you are doing is printing again and again the part of '<input type="hidden" name="...'. here is what you should do
<?php
echo '<input type="hidden" name="reference[' . $data['user_id'] . ']" value="'; //olny one time.
foreach($_SESSION['printing_set'] as $data) {
foreach(getProvenaMailableUserlist() as $userlist){
if($userlist['user_id'] == $data['user_id']){
echo $userlist['ref']; //only if condition is true
}
}
}
echo '" />'; //only one time
?>
A: You've got some funky formatting going on, so it's hard to tell where the error might be. Try it like this:
<?php
foreach($_SESSION['printing_set'] as $data) {
foreach(getProvenaMailableUserlist() as $userlist){
$value = "";
if($userlist['user_id'] == $data['user_id'])
$value = $userlist['ref'];
echo "<input type='hidden' name='reference$user_id' value='$value' /> \n";
}
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Page anchors fail Visual Studio 2010 HTML validation I have a few <a name="something"></a> entries in my html page to enable page anchors; Visual Studio 2010 (with either HTML 4.01 or HTML 5 target) underlines name attribute and shows warning "Element 'name' is obsolete or nonstandard".
Am I doing anything wrong? Is in-page anchoring deprecated?
A: Page anchors should now be done with ID attributes.
This is something that has been obsoleted in the draft for HTML 5:
Authors should not specify the name attribute on a elements. If the attribute is present, its value must not be the empty string and must neither be equal to the value of any of the IDs in the element's home subtree other than the element's own ID, if any, nor be equal to the value of any of the other name attributes on a elements in the element's home subtree. If this attribute is present and the element has an ID, then the attribute's value must be equal to the element's ID. In earlier versions of the language, this attribute was intended as a way to specify possible targets for fragment identifiers in URLs. The id attribute should be used instead.
The name attribute is actually valid HTML 4.01, so I am not sure what Visual Studio is doing there (possibly not applying the correct validation).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: jquery flexbox ? I'm using right now FlexBox plugin to make search box, everything work fine but how can i make the css work perfectly with the search box ( the css file that downloaded with flexbox )
I have the following html
<form action="result.php" method="post">
<div id="suggest"></div>
</form>
and the flexbox callback
$(function(){
// begin to write
$("#suggest").flexbox('back/search.php', {
width: 350,
method: 'post',
watermark: 'Enter value',
noResultsText: 'No Value',
maxVisibleRows: 8,
containerClass: 'ffb',
contentClass: 'content',
inputClass: 'ffb-input',
arrowClass: 'ffb-arrow'
});
});
A: Open the page in Chrome. Right click and click Inspect Element
You need to create a CSS Stylesheet for the code that you see during inspect element.
Alternatively, you could use this to view what's actually in the HTML DOM when you are viewing the page.
html:
<textarea id="whats_in_dom"></textarea>
jQuery
$('textarea').text($('/*container holding flexbox*/').html());
example: http://jsfiddle.net/DGDrx/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Time Cost Comparison: Haml render_to_string vs. string addition I'm working on something that will render a small bit of xml (10 lines) every second.
I like the ease of constructing Xml with Haml, but I was wondering if anyone knew any details about the server cost of using render_to_string with haml versus building a string with String addition.
A: Haml is meant to be used when
*
*you want to generate pretty XML,
*the structure of the XML is hand-edited.
If you are generating small XML documents for machine consumption use faster libraries like Nokogiri or Builder.
Please do not use string interpolation, most of the time you will end up creating malformed documents because the input data will be slightly different from the data you used to test your app. This is true whenever you handle user-generated data. String interpolation is also a nice way to introduce security bugs. Just don't do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How complete should MongoDB indexes be? For example, I have documents with only three fields: user, date, status. Since I select by user and sort by date, I have those two fields as an index. That is the proper thing to do. However, since each date only has one status, I am essentially indexing everything. Is it okay to not index all fields in a query? Where do you draw the line?
What makes this question more difficult is the complete opposite approach to indexes between read-heavy and write-heavy collections. If yours is somewhere in between, how do you determine the proper approach when it comes to indexes?
A:
Is it okay to not index all fields in a query?
Yes, but you'll want to avoid this for frequently used queries. Anything not indexed will imply a "table scan". This means accessing each possible document individually, which will be slow.
Where do you draw the line?
Also note, that if you sort by an un-indexed field, MongoDB will "yell at you" if you're trying to sort too much data. So you have to have some awareness of how much data is "outside of" the index.
If yours is somewhere in between, how do you determine the proper approach when it comes to indexes?
Monitoring, instrumenting, experimenting and experience.
There is no hard and fast rule here, it's all going to be about trade-offs. CPU vs. RAM vs. Disk IO vs. Responsiveness, etc.
A: The perfect situation is to store everything in a single index. By everything I mean all fields you query on, you sort by and you retrieve. This will ensure that you'll get maximum performance (if index fits in ram)
This situation is not always possible, so you'll have to make choices.
Here are 3 tips to reduce at maximum the index size:
Does each of your query have a lot of results or only a few ? => A few : you do not have to index all the fields you retrieve (only the query and sort fields because few results mean few disk access).
Does your query results are often the same (i.e your working set is small) ? => don't index the field you retrieve because results are cached by mongodb.
Do you have a query field more selective than another ? => index the more selective field only.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: .NET Compact Framework Reflection call to internal method in .NET framework class I am trying to load a .NET assembly from a .NET 2.0 CF application. I want to invoke an internal method with three params like so:
var obj = new System.Web.Security.SqlMembershipProvider();
MethodInfo mi = obj.GetType().GetMethod("GenerateSalt",
BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[] {}, null);
object resObj = mi.Invoke(obj, new object[] {});
When the GetMethod call is executed, a InvalidProgramException is thrown. I can make this call from a regular .NET 2.0 console app test harness, but in .NET 2.0 CF it throws.
What is going on?
A: You cannot reference the assembly (System.Web.dll) that contains SqlMembershipProvider from a Compact Framework project. As far as I can tell, this type is not available in the Compact Framework.
You are likely getting the exception because you are loading an assembly that contains IL that the Compact Framework Runtime cannot understand.
However, it is fairly simple to re-write what GenerateSalt does yourself, and the compact framework should have everything needed to make it work:
public string GenerateSalt()
{
byte[] data = new byte[0x10];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(data);
return System.Convert.ToBase64String(data);
}
No need to use the SqlMembershipProvider (or reflection) at all.
A: Try using new Type[0] rather than new Type[]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ File list with all file informations I'm planning to make a program that would work between a folder on my computer and my NAS.
It would list all the files in both folders, then determine which file is newer, and then upload it to the other device.
I know how to upload files via FTP, but I'm stuck at the start, because I don't know how to list my files. I have looked a little at using FindFirstFile() and FindNextFile() with WIN32_FIND_DATA. This way, I can get the last write data, but this doesn't let me list subdirectories.
Do you know any easy way listing all files in a folder and its subdirectory and saving the information of every file in a list?
A: The easy way is to use boost::recursive_directory_iterator.
#include <boost/foreach.hpp>
#include <iostream>
#include <vector>
#include <boost/filesystem.hpp>
#include <boost/date_time.hpp>
#include <algorithm>
#include <iterator>
#include <ctime>
using boost::filesystem::path;
using boost::filesystem::recursive_directory_iterator;
using boost::filesystem::directory_entry;
using boost::filesystem::filesystem_error;
using boost::filesystem::last_write_time;
using std::vector;
using std::cout;
using std::copy;
using std::ostream_iterator;
using std::time_t;
using boost::posix_time::from_time_t;
int main(int ac, const char **av)
{
vector<const char*> args(av+1, av+ac);
if(args.empty())
args.push_back(".");
vector<directory_entry> files;
BOOST_FOREACH(path p, args)
{
boost::system::error_code ec;
copy(recursive_directory_iterator(p, ec),
recursive_directory_iterator(),
back_inserter(files));
}
BOOST_FOREACH(const directory_entry& d, files)
{
if(exists(d.path()))
{
cout << from_time_t(last_write_time(d.path())) << " " << d.path() << "\n";
}
}
}
A: FindFirstFile() and FindNextFile() does let you list subdirectories. One of the members of WIN32_FIND_DATA is dwFileAttributes which will include FILE_ATTRIBUTE_DIRECTORY for a directory entry. Simply start another FindFirstFile() in that subdirector, rinse, repeat.
There is a sample on MSDN that shows how to use the FindFirstFile API, here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to load json data with jqgrid, although jsonstring works fine I have a jqgrid that I'd like to populate with my json, but I can't get it to work. I think my json is fine since the grid is working when supplying the json as a string (datatype:jsonstring). The thing is, I don't get any errors from jqgrid, which makes it hard to debug.
Here's my json (validated with jslint):
{ "total":"1", "page":"1", "records":"5", "rows": [ {"id" :"1", "cell" :["Modulex", "", "", "", ""]}, {"id" :"2", "cell" :["Lemoltech", "", "", "", ""]}, {"id" :"3", "cell" :["Isothermic", "", "", "", ""]}, {"id" :"4", "cell" :["Renova", "", "", "", ""]}, {"id" :"5", "cell" :["Natart Juvenile", "", "", "", ""]} ] }
And here's my config
$("#list").jqGrid({
url:'/tempajax/',
datatype: 'json',
colNames:['Nom','Adresse','Ville','Tel','Courriel'],
colModel :[
{name:'company_name', index:'company_name', width:55},
{name:'address', index:'address', width:90},
{name:'city', index:'city', width:90},
{name:'telephone', index:'telephone', width:80},
{name:'email', index:'email', width:80},
],
autowidth: true,
pager: '#pager',
rowNum:10,
viewrecords: true,
gridview: true,
height: '100%'
});
This is my first post here, so I hope to have supplied enough information for you guys to help, if not just ask.
Thanks a lot for your help!
A: Your JSON result doesn't match with what you're configuring your jqGrid to consume.
Your jqGrid is expecting a JSON result that has company_name, address, city, telephone, and email as fields, but your data is bringing back id and cell, and even then it's nested inside the top json result, which has total, page, records, and rows. Either way, it's not lined up with your jqGrid.
A: I fixed my problem, the json was fine afterall. The server was throwing a 404 code, even though the output was good. This prevented jqGrid from even parsing the json. I hope this will be helpfull to others as well!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to cascade deletions with Doctrine 1.2? I have been struggling with defining cascade behavior in Doctrine ORM.
According to the documentation, one is supposed to use onDelete: CASCADE for database-level cascade (which is what I am trying to achieve here).
A complete example may be seen on the Symfony tutorial.
However, all such cascade specifications are ignored in my schema.
Here is the relevant excerpt:
Advancement:
columns:
association_id:
type: integer(4)
notnull: true
task_id:
type: integer(4)
notnull: true
state:
type: enum
values: ['todo', 'current', 'done', 'cancelled']
notnull: true
relations:
Association:
class: Association
local: association_id
foreignType: one
onDelete: CASCADE
Task:
class: Task
local: task_id
foreignType: one
onDelete: CASCADE
Of course, the Task and Association tables are defined correctly. I won't post them here in the first place to avoid a too long question, but please ask if that seems necessary.
Here is the generated SQL (linebreaks mine):
CREATE TABLE advancement
(id INTEGER PRIMARY KEY AUTOINCREMENT,
association_id INTEGER NOT NULL,
task_id INTEGER NOT NULL,
state VARCHAR(255) NOT NULL);
Not a trace of a CASCADE (nor a REFERENCES, by the way…). Of course, cascading does not work, and I had to implement it manually by altering the default backend actions.
Does anyone know what I am doing wrong here?
A: I think doctrine will shut up about the fact that your RDBMS (is it MySQL?) does not support cascades if it doesn't. This is the case if you use MySQL with the MyISAM storage engine (which does not support REFERENCES either, by the way...). If I were you, I'd try to create a cascade directly with your RDBMS client, just to check whether it is possible or not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Will Postgres push down a WHERE clause into a VIEW with a Window Function (Aggregate)? The docs for Pg's Window function say:
The rows considered by a window function are those of the "virtual table" produced by the query's FROM clause as filtered by its WHERE, GROUP BY, and HAVING clauses if any. For example, a row removed because it does not meet the WHERE condition is not seen by any window function. A query can contain multiple window functions that slice up the data in different ways by means of different OVER clauses, but they all act on the same collection of rows defined by this virtual table.
However, I'm not seeing this. It seems to me like the Select Filter is very near to the left margin and the top (last thing done).
=# EXPLAIN SELECT * FROM chrome_nvd.view_options where fkey_style = 303451;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------
Subquery Scan view_options (cost=2098450.26..2142926.28 rows=14825 width=180)
Filter: (view_options.fkey_style = 303451)
-> Sort (cost=2098450.26..2105862.93 rows=2965068 width=189)
Sort Key: o.sequence
-> WindowAgg (cost=1446776.02..1506077.38 rows=2965068 width=189)
-> Sort (cost=1446776.02..1454188.69 rows=2965068 width=189)
Sort Key: h.name, k.name
-> WindowAgg (cost=802514.45..854403.14 rows=2965068 width=189)
-> Sort (cost=802514.45..809927.12 rows=2965068 width=189)
Sort Key: h.name
-> Hash Join (cost=18.52..210141.57 rows=2965068 width=189)
Hash Cond: (o.fkey_opt_header = h.id)
-> Hash Join (cost=3.72..169357.09 rows=2965068 width=166)
Hash Cond: (o.fkey_opt_kind = k.id)
-> Seq Scan on options o (cost=0.00..128583.68 rows=2965068 width=156)
-> Hash (cost=2.21..2.21 rows=121 width=18)
-> Seq Scan on opt_kind k (cost=0.00..2.21 rows=121 width=18)
-> Hash (cost=8.80..8.80 rows=480 width=31)
-> Seq Scan on opt_header h (cost=0.00..8.80 rows=480 width=31)
(19 rows)
These two WindowAgg's essentially change the plan to something that seems to never finish from the much faster
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------
Subquery Scan view_options (cost=329.47..330.42 rows=76 width=164) (actual time=20.263..20.403 rows=42 loops=1)
-> Sort (cost=329.47..329.66 rows=76 width=189) (actual time=20.258..20.300 rows=42 loops=1)
Sort Key: o.sequence
Sort Method: quicksort Memory: 35kB
-> Hash Join (cost=18.52..327.10 rows=76 width=189) (actual time=19.427..19.961 rows=42 loops=1)
Hash Cond: (o.fkey_opt_header = h.id)
-> Hash Join (cost=3.72..311.25 rows=76 width=166) (actual time=17.679..18.085 rows=42 loops=1)
Hash Cond: (o.fkey_opt_kind = k.id)
-> Index Scan using options_pkey on options o (cost=0.00..306.48 rows=76 width=156) (actual time=17.152..17.410 rows=42 loops=1)
Index Cond: (fkey_style = 303451)
-> Hash (cost=2.21..2.21 rows=121 width=18) (actual time=0.432..0.432 rows=121 loops=1)
-> Seq Scan on opt_kind k (cost=0.00..2.21 rows=121 width=18) (actual time=0.042..0.196 rows=121 loops=1)
-> Hash (cost=8.80..8.80 rows=480 width=31) (actual time=1.687..1.687 rows=480 loops=1)
-> Seq Scan on opt_header h (cost=0.00..8.80 rows=480 width=31) (actual time=0.030..0.748 rows=480 loops=1)
Total runtime: 20.893 ms
(15 rows)
What is going on, and how do I fix it? I'm using Postgresql 8.4.8. Here is what the actual view is doing:
SELECT o.fkey_style, h.name AS header, k.name AS kind
, o.code, o.name AS option_name, o.description
, count(*) OVER (PARTITION BY h.name) AS header_count
, count(*) OVER (PARTITION BY h.name, k.name) AS header_kind_count
FROM chrome_nvd.options o
JOIN chrome_nvd.opt_header h ON h.id = o.fkey_opt_header
JOIN chrome_nvd.opt_kind k ON k.id = o.fkey_opt_kind
ORDER BY o.sequence;
A: No, PostgreSQL will only push down a WHERE clause on a VIEW that does not have an Aggregate. (Window functions are consider Aggregates).
< x> I think that's just an implementation limitation
< EvanCarroll> x: I wonder what would have to be done to push the
WHERE clause down in this case.
< EvanCarroll> the planner would have to know that the WindowAgg doesn't itself add selectivity and therefore it is safe to push the WHERE down?
< x> EvanCarroll; a lot of very complicated work with the planner, I'd presume
And,
< a> EvanCarroll: nope. a filter condition on a view applies to the output of the view and only gets pushed down if the view does not involve aggregates
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: javax.servlet.ServletException: java.lang.VerifyError: createELResolver signature I am struggling with the following issue and help to resolve it would be greatly appreciated.
I am developing an application and have been running it in Tomcat 7.0.19 installed locally on my machine. Everything was working fine until today when I deployed it on the dev server which has Tomcat 7.0.14 installed on it. I get the following issue when I open my application on the Dev server.
javax.servlet.ServletException: java.lang.VerifyError: (class: org/apache/jasper/runtime/JspApplicationContextImpl, method: createELResolver signature: ()Ljavax/el/ELResolver;) Incompatible argument to function
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:342)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
with root cause
java.lang.VerifyError: (class: org/apache/jasper/runtime/JspApplicationContextImpl, method: createELResolver signature: ()Ljavax/el/ELResolver;) Incompatible argument to function
org.apache.jasper.runtime.JspFactoryImpl.getJspApplicationContext(JspFactoryImpl.java:220)
org.apache.jsp.WEB_002dINF.views.login_jsp._jspInit(login_jsp.java:28)
org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:49)
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:171)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:356)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
Please let me know.
A: Remove all Tomcat-specific libraries like el-api.jar from your webapp's /WEB-INF/lib folder. It will make your webapp incompatible with containers of a different make/version resulting in this kind of errors.
See also:
*
*How do I import the javax.servlet API in my Eclipse project?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to disable system keyboard handling in Java AWT Application? How can i disable such keys and their combinations as, for example, Alt ; Alt + F4 and others in my Java AWT application?
E.g. my KeyboardListener should handle that keys as 'usual' keys and combinations without closing window or entering window menu.
A: One way is to create a program in "kiosk mode", something that requires more than Java to achieve (such as JNA or JNI). If you google this or search this site for this, you'll find out more about it. If I were using your code, though, I'd be very frustrated and perhaps angry, unless this were being run on a dedicated kiosk terminal.
Edit: Another option is as per this thread: java-full-screen-program-swing-tab-alt-f4:
window.setExtendedState(Frame.MAXIMIZED_BOTH); //maximise window
window.setUndecorated(true); //remove decorations e.g. x in top right
window.setAlwaysOnTop(true);
Edit 2: and this brute-force method: Remove the possibility of using Alt-F4 and Alt-TAB in Java GUI
A: Found this solution:
*
*for Tab - use Frame.setFocusTraversalKeysEnabled(false);
*for Alt - add keyEvent.consume(); at the end of each key
event handling code block
Then, to find out if Alt or Ctrl key is pressed - use keyEvent.isAltDown() and keyEvent.isControlDown() methods of keyPressed or keyReleased events.
Thanks, @Hovercraft , for your quick response!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Tool like magic draw but for generate C# code It's there a plugin for visual studio or a specific program that allows to draw an UML model and generates the classes for C#?? and more, for example Creates a repository classes from classes entities of the entity framework generates
A: Visual Studio has had the Class Designer built in since Visual Studio 2005, though not all versions (the Express versions don't have it).
A: A former co-worker swore by http://www.sparxsystems.com.au/products/ea/index.html. The generated code definitely needed some tweaking though. Or something like http://staruml.sourceforge.net/en/index.php might have plugin's to generate needed c#...or perhaps t4.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: lazy loading not working when on new saved objects, (when getting them from the context that saved them) I have this class
public class Comment
{
public long Id { get; set; }
public string Body { get; set; }
public long OwnerId { get; set; }
public virtual Account Owner { get; set; }
public DateTime CreationDate { get; set; }
}
the problem is that the virtual property owner is that I get null object reference exception when doing:
comment.Owner.Name
when calling this right after the object was saved (from the same instance of DbContext)
with a new context will work
anybody knows anything about this?
A: That is because you created Comment with constructor. That means that Comment instance is not proxied and it cannot use lazy loading. You must use Create method on DbSet instead to get proxied instance of Comment:
var comment = context.Comments.Create();
// fill comment
context.Comments.Add(comment);
context.SaveChanges();
string name = comment.Owner.Name; // Now it should work because comment instance is proxied
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.