text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How does GitHub change the URL without reloading a page? Go to any GitHub page and click on any of the directories/files and observe how the URL changes but only part of the page is updated. There's no whole page reloading.
How do I do something similar using jQuery?
Does this work on most browsers (I'm using Chrome)?
A: Github use PJAX (Ref). You may see about jquery-pjax here. Note that this feature is not covered support by all browser, there are some browser that cannot be use this benefits.
A: They use the history API, or specifically, history.pushState().
You can use this, jQuery is not required, but there are plugins such as history.js.
This works on most browsers, namely Chrome, Safari and Firefox. IE10 and above supports this. In older IEs, you can fall back onto using the hash (window.location.hash).
GitHub also blogged about this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: Loadin new images with jQuery How can i load a new image in place of another using jQuery?
I hope to do this possibly by clicking a button for previous or next. See below for an example. Important: i dont know how many pictures on server (1 or 100). So, i cant load them all on web page load. and cant do array in javascript code on same reason
showing /img/1.jpg (click on button 'next')
showing /img/2.jpg (click on button 'next')
showing /img/3.jpg (click on button 'prev')
showing /img/2.jpg (click on button 'prev')
showing /img/1.jpg (click on button 'prev')
A: You can just create an image tag each time you need a new image, and append it to the document and it will be loaded in asynchronously. e.g.:
var $img = $("<img/>");
$img[0].src = "foo.jpg";
$("#someDiv").append($img);
so you can do something like:
$("#next").click(function() {
$("#theImage").attr("src", "parse the number out of the filename, increment, put back");
});
A: var info = {
images : ["/img/1.jpg","/img/2.jpg","/img/3.jpg"],
current : 0
}
$("#imgID").live("click", function(){
if(info.current++ > info.images.length) {
info.current = 0;
}
$(this).attr("src",info.images[info.current]);
});
<img id="imgID" src="/img/1.jpg" />
I know there are no buttons, but click the images and this should scroll through them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Capybara switch_to.alert (dialog box) intermittent failure I'm trying to interact with a dialog box in FF using RSPEC / Capybara.
Found a elegant solution in: How to test a confirm dialog with Cucumber?
page.driver.browser.switch_to.alert.accept
However we're getting intermittent failures when the switch doesn't happen.
Anyone encountered this? Anyway to ensure the switch is always successful?
Thanks!
A: As the answer states, the Browser becomes unresponsive when the modal Alert/Confirm/Prompt dialog boxes open. Nowadays, even though browsers have learnt to show non-modal windows, Capybara still can't evaluate any code in the page context.
As the linked answer states, just stub the window.confirm method. That is the best stable way.
You can write the following two steps in Capybara:
When /I ensure the confirm box returns OK/ do
page.evaluate_script('window.confirm = function() { return true; }')
end
When /I ensure the confirm box returns Cancel/ do
page.evaluate_script('window.confirm = function() { return false; }')
end
Then you can proceed to rewrite your Capybara steps, so that first you make sure you stub the confirm box, and then you click on the link that triggers the confirm box:
When I ensure the confirm box returns OK
And I click on Remove
Then ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: detect printscreen simply put I want my program which runs in the background to check whether the print screen button has been pressed (which mostly triggers a function within another program to generate a screenshot of the current window. eg a game screen).
I have seen lots of possible answers, but most seem overkill for just detecting the print screen button.
I want to have a program in the background check so that it can move the screenshot that has just been made/saved to a certain location. after the button had been pressed.
I hope this question is clear, if not I'll try to explain more clearly.
ps
On a side note, would it be better to try and detect the printscreen button or to simply check the specified folder every 1 or 5 minutes whether a new image has been put in that folder and then move it if true.
EDIT
I decided to use the FileSystemWatch, however it seems to be to fast if i use the on create event as sometimes the file is still being made and it can't move the file yet.
Would the best action be to use a timer to delay ?
A: You could just watch the folder location for updates using a FileSystemWatcher. There are many examples around the place.
A: Global keyboard capture in C# application
You should be able to use a global key hook to handle the print screen key press.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Zend subform view script render I would rather not deal with decorators as my form design is not exactly straight forward, but i would like to keep the functionality of validating the forms.
So i have it set up where sub forms are working correctly, but when i try to style it manually in my viewscript i get the name without the parent. I've seen other posts that are similar, but i haven't found a solution.
Example:
This is in my view script
<?php echo $this->form->username->renderViewHelper();?>
I then get
<input type="text" value="" id="username" name="username">
When rendered. It should be
<input type="text" value="" id="form1-username" name="form1[username]">
How do i get that form1 portion?
Thanks!
Edit
Ok, so i found one way.
By using belongTo, it works:
$form1->addElements(array(
new Zend_Form_Element_Text('username', array(
'belongsTo' => 'form1',
'required' => true,
'label' => 'Username:',
'filters' => array('StringTrim', 'StringToLower'),
'validators' => array(
'Alnum',
array('Regex',
false,
array('/^[a-z][a-z0-9]{2,}$/'))
)
))
));
Is there a better way to do this or is this the only way?
Edit2
public function prepareSubForm($spec){
if (is_string($spec)) {
$subForm = $this->{$spec};
} elseif ($spec instanceof Zend_Form_SubForm) {
$subForm = $spec;
} else {
throw new Exception('Invalid argument passed to ' .
__FUNCTION__ . '()');
}
$this->setSubFormDecorators($subForm)
->addSubmitButton($subForm)
->addSubFormActions($subForm);
return $subForm;
}
public function setSubFormDecorators(Zend_Form_SubForm $subForm){
$subForm->setDecorators(array(
'FormElements', \\<--- I tried to change this to PrepareElements before.
array('HtmlTag', array('tag' => 'dl',
'class' => 'zend_form')),
'Form',
));
return $this;
}
A: I believe you can get your desired output just by using:
<?php echo $this->form->username; ?>
I get the expected output when calling this without renderViewHelper. This is also without any special code for decorators or preparing sub forms. All I had to do was add belongsTo to the form element.
UPDATED:
If you set this to be your default decorator, you can eliminate the dd/dt tags from rendering, instead it will use a div. Then you may be closer to getting the custom output you want. You can change the tag in HtmlTag from div to whatever tag you would like to wrap your elements in. This is what I use mostly:
array(
'ViewHelper',
'Errors',
array('Description', array('tag' => 'p', 'class' => 'description')),
array('HtmlTag', array('tag' => 'div', 'class' => 'form-div')),
array('Label', array('class' => 'form-label', 'requiredSuffix' => '*'))
);
This is the default for Zend Framework:
array(
'ViewHelper',
'Errors',
array('Description', array('tag' => 'p', 'class' => 'description')),
array('HtmlTag', array('tag' => 'dd', 'id' => array('callback' => $getId)))
array('Label', array('tag' => 'dt'))
);
Note that file, and submit/button elements use different decorators.
Also see this answer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Determining whether a feed is Atom or RSS I'm trying to determine whether a given feed is Atom based or RSS based.
Here's my code:
public boolean isRSS(String URL) throws ParserConfigurationException, SAXException, IOException{
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder
.parse(URL);
return doc.getDocumentElement().getNodeName().equalsIgnoreCase() == "rss";
}
Is there a better way to do it? would it be better if I used a SAX Parser instead?
A: The root element is the easiest way to determine the type of a feed.
*
*RSS feeds have the root element rss (see specification)
*Atom feeds have the root element feed (see specification)
For different Parsers there are different ways to get the root element. None is inferior to the other. There has been written enough about StAX vs. SAX vs. DOM etc, which can be used as basis for a specific decision.
There is nothing wrong with your first two lines of code:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(URL);
In your return statement you make a mistake on Java String comparison.
When you use the comparison operator == with Strings, it compares references not values (i.e. you check if both are exactly the same object). You should use the equals() method here. Just to be sure I would recommend to use equalsIgnoreCase():
return doc.getDocumentElement().getNodeName().equalsIgnoreCase("rss");
Hint: If you check for "rss" instead of "feed" (like for Atom) in your isRss() method you don't have to use the ternary operator.
A: Sniffing content is one method. But note that atom uses namespaces, and you are creating a non namespace aware parser.
public boolean isAtom(String URL) throws ParserConfigurationException, SAXException, IOException{
DocumentBuilderFactory f = DocumentBuilderFActory.newInstance();
f.setNamespaceAware(true);
DocumentBuilder builder = f.newInstance().newDocumentBuilder();
Document doc = builder.parse(URL);
Element e = doc.getDocumentElement();
return e.getLocalName().equals("feed") &&
e.getNamespaceURI().equals("http://www.w3.org/2005/Atom");
}
Note also that you cannot compare using equalsIgnorCase(), since XML element names are case sensitive.
Another method is to react on the Content-Type header, if it is available in a HTTP GET request. Content-Type for ATOM would be application/atom+xml and for RSS application/rss+xml. I would suspect though, that not all RSS feed can be trusted to correctky set this header.
A third option is to look at the URL suffix, e.g. .atom and .rss.
The last two methods are easily configurable if you are using Spring or JAX-RS
A: You could use a StAX parser to avoid parsing the entire XML document into memory:
public boolean isAtom(String url) throws ParserConfigurationException, SAXException, IOException{
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(new URL(url).openConnection());
xsr.nextTag(); // Advance to root element
return xsr.getLocalName().equals("feed") &&
xsr.getNamespaceURI().equals("http://www.w3.org/2005/Atom");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: CALayer delegate callbacks in a UITableViewCell - Workflow I'm using several CALayers to draw my content in a UITableViewCell subclass. The actual drawing is supposed to happen by calling the CALayer delegate method drawLayer:inContext:. However the delegate methods never gets called.
Here is my structure:
*
*CustomCell: UITalbeViewCell
*
*creates CustomCellContentView: UIView
*
*creates CABackgroundLayer: CALayer
*creates CATextLayer: CALayer
*creates CALayerDelegate: NSObject
Each customCell has a customContentView, which holds all the CALayers for drawing.
Each customCell creates a caLayerDelegate for the CALayers to call. The caLayerDelegate reports back to the customCell.
CustomCell:
#define CALAYER_TEXTLAYER_NAME @"CATextLayer"
#define CALAYER_BGLAYER_NAME @"CABackgroundLayer"
...
- (id) customContentViewForCurrentCell
{
CGRect contentViewFrame = CGRectMake(-CC_LEFTRIGHT_PADDING, 0., self.contentView.bounds.size.width, self.contentView.bounds.size.height);
CustomCellContentView *cellContentView = [[[CustomCellContentView alloc] initWithFrame: contentViewFrame] autorelease];
CALayerDelegate *layerDelegate = [[CALayerDelegate alloc] initWithView: self];
cellContentView.layerDelegate = layerDelegate;
[cellContentView setupSubLayers];
[layerDelegate release];
return cellContentView;
}
#pragma mark - Initialisation
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (!self)
return nil;
self.customContentView = (CustomCellContentView *)[self customContentViewForCurrentCell];
self.customContentView.opaque = TRUE;
self.backgroundColor = [UIColor clearColor];
self.selectionStyle = UITableViewCellSelectionStyleNone;
[self.contentView addSubview: self.customContentView];
return self;
}
#pragma mark - Cell Update
- (void) refreshLayout
{
[self setNeedsDisplay];
[self.customContentView setNeedsDisplay];
}
...
#pragma mark - CALayer Delegate Methods
-(void) drawLayer: (CALayer*) layer inContext: (CGContextRef) context
{
}
-(void) drawCABackgroundLayer: (CALayer*) layer inContext: (CGContextRef) context
{
UIGraphicsPushContext(context);
CGRect contentRect = [layer bounds];
UIImage *bgImage = [[ImageCacheController sharedImageCache] imageFromCache: GENERIC_BGIMAGE_FILENAME];
[bgImage drawInRect: CGRectMake(contentRect.origin.x, contentRect.origin.y, contentRect.size.width, contentRect.size.height)];
UIGraphicsPopContext();
}
-(void) drawCATextLayer: (CALayer*) layer inContext: (CGContextRef) context
{
UIGraphicsPushContext(context);
CGContextSetShadowWithColor(context, CGSizeMake(0.f, 2.0f), 0.0f, [UIColor mainLabelShadowColor].CGColor);
[[UIColor mainLabelColor] set];
UIFont *mainFont = [UIFont fontWithName: FONT_INFOS size: CC_MAINLABEL_FONTSIZE_MAX];
[@"ArthurDent" drawAtPoint: [self mainViewPosition]
forWidth: CC_MAINLABEL_WIDTH
withFont: mainFont
minFontSize: CC_MAINLABEL_FONTSIZE_MAX
actualFontSize: NULL
lineBreakMode: UILineBreakModeTailTruncation
baselineAdjustment: UIBaselineAdjustmentAlignBaselines];
UIGraphicsPopContext();
}
CustomCellContentView:
@interface CustomCellContentView : UIView
{
CALayerDelegate *layerDelegate;
CALayer *backgroundLayer;
CALayer *textLayer;
}
@property (nonatomic, retain) CALayerDelegate *layerDelegate;
@property (nonatomic, retain) CALayer *backgroundLayer;
@property (nonatomic, retain) CALayer *textLayer;
- (void) setupSubLayers;
@end
@implementation CustomCellContentView
@synthesize textLayer, backgroundLayer, layerDelegate;
#pragma mark - Initialisation
- (id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame: frame];
if(!self)
return nil;
return self;
}
- (void) setupSubLayers
{
self.textLayer = [CALayer layer];
self.textLayer.name = CALAYER_TEXTLAYER_NAME;
self.textLayer.shadowColor = [UIColor mainLabelShadowColor].CGColor;
self.textLayer.shadowOffset = CGSizeMake(0.0f, 2.0f);
self.textLayer.shadowOpacity = 1.f;
self.textLayer.shadowRadius = 0.f;
self.textLayer.needsDisplayOnBoundsChange = TRUE;
self.textLayer.delegate = self.layerDelegate;
self.backgroundLayer = [CALayer layer];
self.backgroundLayer.name = CALAYER_BGLAYER_NAME;
self.backgroundLayer.needsDisplayOnBoundsChange = TRUE;
self.backgroundLayer.delegate = self.layerDelegate;
[self.layer addSublayer: self.textLayer];
[self.layer addSublayer: self.backgroundLayer];
[self.textLayer setNeedsDisplay];
[self.backgroundLayer setNeedsDisplay];
}
#pragma mark - SetNeedsDisplay Overwritten
- (void) setNeedsDisplay
{
[super setNeedsDisplay];
[self.layer setNeedsDisplay];
[self.textLayer setNeedsDisplay];
[self.backgroundLayer setNeedsDisplay];
}
...
CALayerDelegate:
@implementation CALayerDelegate
#pragma mark - Initialisation
-(id) initWithView: (UIView *) view
{
self = [super init];
if (!self)
return nil;
_view = view;
return self;
}
#pragma mark - CALayer Delegate Methods
-(void) drawLayer: (CALayer*) layer inContext: (CGContextRef) context
{
NSString* methodName = [NSString stringWithFormat: @"draw%@:inContext:", [layer name]];
SEL selector = NSSelectorFromString(methodName);
if (![_view respondsToSelector: selector])
selector = @selector(drawLayer:inContext:);
[_view performSelector: selector
withObject: layer
withObject: (id)context];
}
@end
I've read for UIViewController it is better to create sub-CALayers in awakeFromNib: and not in initWithFrame:, because there is some form of layer - backing happening after the initWithFrame:, which will discard the creation of the sublayers. So, you should only add sublayers after the view is loaded?
I use seperate CALayerDelegate - objects, so the CustomCell and its view are only responsible for the customContentView.layer.
Anyone knows, what I'm doing wrong?
Thanks in advance!!
A: From the documentation for CALayer describing the 'delegate' property: 'In iOS, if the layer is associated with a UIView object, this property must be set to the view that owns the layer'.
If I read that correctly then you need to set CustomCellContentView as the layer delegate. Move the functionality from CALayerDelegate directly into your custom view class and see if that works. That would be the standard way to do it anyway, rather than creating a separate class just to act as a delegate.
A: Check that your frame is not CGRectZero.
I had a similar issue to what you describe. If the frame is CGRectZero this will prevent the drawLayer:inContext from being called.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you get the type of widget used by a Django form field? I've got a form factory that dynamically builds a form based on data coming back from the MailChimp API. I'm building a test case for each of the types of widgets that the form may use (select, radio, and checkbox). Right now I'm searching for a substring within the str() representation of the field, however, I assume there is a way to directly determine the type?
GroupsForm = groups_form_factory()
form = GroupsForm()
for field in form:
self.assertIn('type="checkbox"', str(field),
"Form field should be represented by a checkbox.")
# this works, but, isn't there a way to check the field's widget type?
A: to get the the type of the widget in your code use type(field.field.widget)
BoundField is defined in django.forms.
A: >>> from myapp.forms import RestaurantReviewForm
>>> f = RestaurantReviewForm()
>>> from django.forms.widgets import TextInput
>>> for field in f: print type(field.field.widget), isinstance(field.field.widget, TextInput)
...
<class 'django.forms.widgets.TextInput'> True
<class 'django.forms.widgets.TextInput'> True
<class 'django.forms.widgets.TextInput'> True
<class 'django.forms.widgets.TextInput'> True
<class 'django.forms.widgets.TextInput'> True
<class 'django.forms.widgets.CheckboxInput'> False
<class 'django.forms.widgets.Select'> False
<class 'django.forms.widgets.Textarea'> False
<class 'captcha.fields.CaptchaTextInput'> False
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Help with CSS navigation, text positioning and spacing All,
http://rich2233.comoj.com/
Three things I want to do:
*
*I need the navigation bar to sit below the header. This is probably
a simple fix, but for the life of me, I can't figure it out.
*I need the text in the navigation to be centered vertically.
*How do I put some space between the left and right columns?
Thanks for your help! Below is the css code:
body,html {
margin:0;
padding:0;
color:#101010;
font-family: ‘Palatino Linotype’, ‘Book Antiqua’, Palatino, serif;
}
p {
margin-top: 30px;
font-size: 16px;
line-height: 1.3em;
padding-bottom: 10px;
text-align: center;
color: #ffffff;
}
p a{
text-decoration: none;
color: #4e6f8c;
}
#wrapper {
width:960px;
margin:0 auto;
padding: 0px;
background:#fff;
}
#header {
padding:5px 10px;
background:#fff;
height:137px;
}
#nav {
padding:5px 10px;
background:#fff;
width: 960px;
height: 40px;
font-size: 15px;
color: #7c7c7c;
text-align: center;
}
#nav ul {
margin:0;
padding:0;
list-style:none;
position: absolute;
bottom: 5px;
}
#nav li {
display:inline;
margin:0;
padding:0;
width:160px;
height: 45px;
float: left;
background-color: #f6f6f6;
-moz-border-radius: 25px 10px / 10px 25px;
border-radius: 25px 10px / 10px 25px;
}
#nav li:hover {
background-color: #df220f;
}
#nav li:hover a{
color: #ffffff;
text-decoration: none;
}
#nav a {
color: #fff;
text-decoration: none;
}
#nav a:link {
color: #7c7c7c;
text-decoration: none;
}
#nav a:visited{
color: #ffffff;
text-decoration: none;
}
#nav a:hover {
color: #ffffff;
text-decoration: none;
}
#nav a:focus {
color: #ffffff;
text-decoration: none;
}
#nav a:active {
color: #ffffff;
text-decoration: none;
}
#leftcontent {
float:left;
width:710px;
height: 300px;
background:#df220f;
-moz-border-radius: 1em 4em 1em 4em;
border-radius: 1em 4em 1em 4em;
background-image:url('./images/main_placeholder.png');
background-repeat:no-repeat;
background-position:center;
}
h2 {
margin:10px 0 0 20px;
color: #24389b;
font-size: 19px;
padding-bottom: 8px;
}
#rightcontent {
float:left;
width:250px;
background:#df220f;
height: 1%;
-moz-border-radius: 1em 4em 1em 4em;
border-radius: 1em 4em 1em 4em;
height: 300px;
background-image:url('./images/side_logo.png');
background-repeat:no-repeat;
background-position:bottom center;
}
#footer {
clear:both;
padding:5px 10px;
background:#fff;
}
#footer p {
margin:0;
}
* html #footer {
height:1px;
}
_______ HTML EDIT:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<link rel = "stylesheet" type = "text/css"
href = "./style.css" media = "all" />
</head>
<body>
<div id="wrapper">
<div id="header"><img src="./images/logo.png" alt="Ultrabond Logo" /></div>
<div id="nav">
<ul>
<li><a href="Research">Home</a></li>
<li><a href="Research">Service<br />Details</a></li>
<li><a href="Research">Service<br />Request</a></li>
<li><a href="Research">Crack<br />Repair</a></li>
<li><a href="Research">FAQs</a></li>
<li><a href="Research">Contact</a></li>
</ul>
</div>
<div id="leftcontent">
</div>
<div id="rightcontent">
<p>Average cost of a windshield<br />replacement: $240</p><p>Average <i>repair</i> cost: $60</p><p>Just another reason why<br />windshield <i>repair</i> makes sense</p>
</div>
<div id="footer">
</div>
</div>
</body>
</html>
A: First of all your link doesn't work
1) Don't set position: absolute for nav ul
2) Use line-height rule (more detailed here)
3) Use margin or padding. Add margin-left: <whatever you want>px to #rightcontent
A: For #nav li, you don't need to do display:inline and float: left. I would just use float: left, and then you can adjust spacing using margin.
No need to use position: absolute on #nav ul, but if you are going to use that here is a tip that helps me all the time. If you use position:absolute in a container that you haven't specifically set to position:relative, then the absolute positioning is set to the entire page. However, if you have position:relative set on the container div, then you can absolutely position the child element anywhere within that div.
Like this:
#nav
{
width: 500px;
height: 100px;
position: relative;
}
#nav ul
{
position: absolute;
top: 20px;
right: 200px;
}
this places the #nav ul 20px down from the top and 200px from the right within the #nav div. If the #nav div didn't have position: relative on it.. then the #nav ul would be placed at 20px from the top of the page and 200px from the right of the page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Combine three tables into one when viewing I have three tables as seen in this image and I want to present it as seen in the last table. I can't figure out how to solve it - right now I'm using three nestled calls to display it.
First I loop through Customer to display all of them. Inside this loop I have a loop that goes through OrderCustom and inside that I check if there is a CustomerOrderCustom with the right Customer_id and OrderCustom_id.
Not only am I using a lot of queries but the view shows OrderCustom items that now Customer are using, in this case Zip Code. I'm using MySQL 5.
A: This is an entity-attribute-value database design. It is not relational in design and you will not be able to manipulate it with relational operations (such as JOINs) except for the most trivial examples.
If you are determined to store this non-relational data in a relational database you'll be dependent on either your own code or some EAV-based object serialization and deserialization library for whatever programming language you're using. SQL will be of little use to you.
If you are really required to use a model like this for this project (that is, you cannot adopt a relational model) then, if it is not too late in the development process, I would suggest abandoning SQL and reading up on XML, XPath, and XSLT which are probably a better fit for storing and recovering data in which each entry can have a different structure.
Bonus Article: "Why Entity-Attribute-Value is bad"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Seeker For Media Player I would assume that someone would have found an easy solution to this but I haven't found a straight-forward method. I want to build a seeker bar for playing back audio through the MediaPlayer. I haven't been able to find something like an onSeekChanged listener in the MediaPlayer object so I've built an AsyncTask that just keeps refreshing through a while(playing) loop and updates the duration and bar. This doesn't seem to be the best way, however, since this while loop causes the app to run very slowly (the audio doesn't lag, but buttons like pause are delayed). So I want to know what the best implementation is for building a seeker that is efficient. This isn't a difficult question since so many apps use it, I just want to know what the proper way of doing this should be. Thanks!
A: First of all you need put sleep at least 1 millisecond in your cycle whit:
Thread.sleep(1);
Second you can calculate needed time for next recheck:
Thread.sleep(1000 - currentPos % 1000);
This algorithm is used in standard MediaController.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to create a bar that stays on top when scrolling? I'm trying to create a div that stays fixed on top when a user scrolls down and when he scrolls back up, goes back to the original position.
I need this exact same behaviour that 9gag offers -> http://9gag.com/gag/293756
Thanks!
A: Do the following:
*
*Create a scroll event handler on the $(window).
*In this event handler, check if the user has scrolled lower than the top of the element you always want in view. You can use offest and scrollTop methods to do this.
*If yes, set the element to position: fixed with top: 0. You may also need to adjust the left attribute, depending on your layout.
*If no, set the element to position: static.
A: Use the Jquery Waypoints plugin: http://imakewebthings.github.com/jquery-waypoints/
Extremely easy to implement.
A: The code that creates exactly the same behavior as 9gag.com:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- tags html, header, body, divs, anything -->
<div id="post-control-bar" class="spread-bar-wrap">
<div class="spread-bar" style="width:600px">
Facebook button, Twitter button, anything...
</div>
</div>
<script type="text/javascript">
window.onscroll = function()
{
if( window.XMLHttpRequest ) {
if (document.documentElement.scrollTop > 173 || self.pageYOffset > 173) {
$('post-control-bar').style.position = 'fixed';
$('post-control-bar').style.top = '0';
} else if (document.documentElement.scrollTop < 173 || self.pageYOffset < 173) {
$('post-control-bar').style.position = 'absolute';
$('post-control-bar').style.top = '';
}
}
}
</script>
<!-- content, footer, anything -->
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Silverlight: ScrollIntoView, find the column number where a control is I need to scroll into a specific cell in a datagrid in silverlight, i'm trying to use the ScrollIntoView method, but I need the column and I don't have it.
How can I scroll into a specific cell in a datagrid control?
Thanks in advance.
A: I think using of Dispatcher will solve your problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CoffeeScript Refactoring shared variable I'm new to CoffeeScript and trying to understand how to refactor this example. Since both functions share canvas and context is there a way to pull them out side the functions and share them instead of repeating myself? I'm sure it is something obvious I'm missing, but I have not been able to get it to work.
CoffeeScript File
@draw_rectangle = ->
canvas = document.getElementById("main_canvas")
context = canvas.getContext("2d")
context.fillRect(50, 25, 150, 100)
@draw_square = ->
canvas = document.getElementById("main_canvas")
context = canvas.getContext("2d")
context.fillRect(100, 50, 100, 50)
HTML Body:
<body>
<canvas id="main_canvas"></canvas>
<p><a onclick="draw_square()" href="#">Draw Square</a></p>
<p><a onclick="draw_rectangle()" href="#">Draw Rectangle</a></p>
</body>
A: Probably the most elegant way would be to use a class, or at least an object, that would hold both methods and the canvas and context variables. The object would also keep track of whether it's been initialized already. Here's a first attempt:
painter =
draw_rectangle: ->
@init() unless @initialized
@context.fillRect 50, 25, 150, 100
draw_square: ->
@init() unless @initialized
@context.fillRect 100, 50, 100, 50
init: ->
canvas = document.getElementById "main_canvas"
@context = canvas.getContext "2d"
@initialized = true
Now, if you later decided that you wanted to have multiple canvases, it'd be very easy to change painter = to class Painter and reuse the code.
A: You can use a custom helper method to draw a rectangle.
canvasRectangle = (id, x, y, w, h) ->
canvas = document.getElementById(id)
context = canvas.getContext("2d")
context.fillRect(x, y, w, h)
@draw_rectangle = ->
canvasRectangle("main_canvas", 50, 25, 150, 100)
@draw_square = ->
canvasRectangle("main_canvas", 100, 50, 100, 50)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is the probability of collision with a 6 digit random alphanumeric code? I'm using the following perl code to generate random alphanumeric strings (uppercase letters and numbers, only) to use as unique identifiers for records in my MySQL database. The database is likely to stay under 1,000,000 rows, but the absolute realistic maximum would be around 3,000,000. Do I have a dangerous chance of 2 records having the same random code, or is it likely to happen an insignificantly small number of times? I know very little about probability (if that isn't already abundantly clear from the nature of this question) and would love someone's input.
perl -le 'print map { ("A".."Z", 0..9)[rand 36] } 1..6'
A: Based on the equations given at http://en.wikipedia.org/wiki/Birthday_paradox#Approximation_of_number_of_people, there is a 50% chance of encountering at least one collision after inserting only 55,000 records or so into a universe of this size:
http://wolfr.am/niaHIF
Trying to insert two to six times as many records will almost certainly lead to a collision. You'll need to assign codes nonrandomly, or use a larger code.
A: As mentioned previously, the birthday paradox makes this event quite likely. In particular, a accurate approximation can be determined when the problem is cast as a collision problem. Let p(n; d) be the probability that at least two numbers are the same, d be the number of combinations and n the number of trails. Then, we can show that p(n; d) is approximately equal to:
1 - ((d-1)/d)^(n*(n-1)/2)
We can easily plot this in R:
> d = 2176782336
> n = 1:100000
> plot(n,1 - ((d-1)/d)^(n*(n-1)/2), type='l')
which gives
As you can see the collision probability increases very quickly with the number of trials/rows
A: Because of the Birthday Paradox it's more likely than you might think.
There are 2,176,782,336 possible codes, but even inserting just 50,000 rows there is already a quite high chance of a collision. For 1,000,000 rows it is almost inevitable that there will be many collisions (I think about 250 on average).
I ran a few tests and this is the number of codes I could generate before the first collision occurred:
*
*73366
*59307
*79297
*36909
Collisions will become more frequent as the number of codes increases.
Here was my test code (written in Python):
>>> import random
>>> codes = set()
>>> while 1:
code=''.join(random.choice('1234567890qwertyuiopasdfghjklzxcvbnm')for x in range(6))
if code in codes: break
codes.add(code)
>>> len(codes)
36909
A: Well, you have 36**6 possible codes, which is about 2 billion. Call this d. Using a formula found here, we find that the probability of a collision, for n codes, is approximately
1 - ((d-1)/d)**(n*(n-1)/2)
For any n over 50,000 or so, that's pretty high.
Looks like a 10-character code has a collision probability of only about 1/800. So go with 10 or more.
A: While I don't know the specifics of exactly how you want to use these pseudo-random IDs, you may want to consider generating an array of 3000000 integers (from 1 to 3000000) and randomly shuffling it. That would guarantee that the numbers are unique.
See Fisher-Yates shuffle on Wikipedia.
A: A caution: Beware of relying on the built-in rand where the quality of the pseudo random number generator matters. I recently found out about Math::Random::MT::Auto:
The Mersenne Twister is a fast pseudorandom number generator (PRNG) that is capable of providing large volumes (> 10^6004) of "high quality" pseudorandom data to applications that may exhaust available "truly" random data sources or system-provided PRNGs such as rand.
The module provides a drop in replacement for rand which is handy.
You can generate the sequence of keys with the following code:
#!/usr/bin/env perl
use warnings; use strict;
use Math::Random::MT::Auto qw( rand );
my $SEQUENCE_LENGTH = 1_000_000;
my %dict;
my $picks;
for my $i (1 .. $SEQUENCE_LENGTH) {
my $pick = pick_one();
$picks += 1;
redo if exists $dict{ $pick };
$dict{ $pick } = undef;
}
printf "Generated %d keys with %d picks\n", scalar keys %dict, $picks;
sub pick_one {
join '', map { ("A".."Z", 0..9)[rand 36] } 1..6;
}
Some time ago, I wrote about the limited range of built-in rand on Windows. You may not be on Windows, but there might be other limitations or pitfalls on your system.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Programmatically call a firefox extension from javascript I have seen this excellent firefox extension, Screengrab!. It takes a "picture" of the web page and copies it to the clipboard or saves it to a png file. I need to do so, but with a new web page, from an url I have in javascript. I can open the web page in a new window, but then I have to call the extension -not to press the control- and saves the page once the page is fully loaded.
Is it possible?
A: I am pretty certain that it is not possible to access any Firefox add-on through web page content. This could create privacy and/or security issues within the Firefox browser (as the user has never given you permission to access such content on their machine). For this reason, I believe Firefox add-ons run in an entirely different JavaScript context, thereby making this entirely impossible.
However, as Dmitriy's answer states, there are server-side workarounds that can be performed.
A: Does not look like ScreenGrab has any javascript API.
There is a PHP solution for Saving Web Page as Image.
If you need to do it from JavaScript (from client side) - you can:
Step 1: Create a PHP server app that does the trick (see the link), and that accepts JSONP call.
Step 2: Create a client side page (JavaScript) that will send a JSONP request to that PHP script. See my answer here, that will help you to create such request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Move a file using bat from folder I'm trying to move a file from the folder the batch file is in to a folder on the C:\ drive, and I just can't figure out how.
I tried using dir to get the parent folder, but it registered an error.
What would I use?
move dir\test.bat C:\Some folder
A: I think you are missing the "":
move "A:\test.bat" "C:\Some folder"
A: This may be a permissions issue for the path you're trying. Try opening the command line as an administrator (right click -> run as administrator)
This works fine for me when the batch file is run from the directory that the test file is in:
move "test.txt" "C:\Test"
A: You must use backslashes \ as path separators. According to your comment you used forward slash / in source path.
A: To reference a file or a folder relative to the location of the batch script you need to use the %0 parameter and the ~dp combined modifier. The following moves the file somefile.txt to Some folder on C::
MOVE "%~dp0somefile.txt" "C:\Some folder"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Question about rendering .tiff image in HTML In my html page, I created an tag to render some of my .tif format images.
Since .tif images can not be rendered directly in "src" attribute of the tag, so I created the following code to render it:
<object width="200" height="200" type="image/tiff" data="Test.tif">
<param name="src" value="Test.tif"/>
<param name="negative" value="yes"/>
</object>
Everything worked perfectly :) in both Chrome and Firefox, but the image is not rendering in IE. Wonder if any expert could offer some help?
Thanks a lot!
A: tif is not a standard format for the web (though the spec doesn't define a standard list) and it won't be displayed in all browsers.
It looks like it only has support for IE and Safari.
Browser Image Support
A: You can convert it to a different file format, e.g. by screen capturing it using the PrtScrn button, then cropping it on Paint and saving it as a jpg/png/etc. file that every browser can display. If not, then somehow you will have to tell people to modify their registry because there is a registry that prevents .tif files by being rendered. Try looking at this:
http://www.pctools.com/guides/registry/detail/1182/
A: You can also use PHP and ImageMagick to convert the tiff images to png or jpeg on the fly. That way they will render nicely and work in all browsers.
http://www.imagemagick.org/script/index.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I pass a variable from inside a movieclip into another movieclip in Flash? The title kinda says it all..
I am creating a quiz and I set one quiz block with questions into a movieclip. When the person answers the correct answer I want it to add to a counter and pass that value onto the next movieclip. So movieclip one is added to the stage it does something then adds a counter. Then moves to the next frame and movieclip2 is added to the stage. It does something and add to the same counter variable from movieclip1. And so on and so on until no more movieclips.
A: Try a quick and easy class like this:
package
{
public class Scoreboard
{
// Constants
public static const TOTAL_QUESTIONS:int = 3;
// Score value
public static var correct:int = 0;
/**
* Returns success rate as a percentage in decimal form
*/
public static function get successRate():Number
{
return correct / TOTAL_QUESTIONS;
}
}
}
Where you can change the TOTAL_QUESTIONS as you like, and do the following:
Scoreboard.correct += 1; // Adds a correct answer
Scoreboard.correct = 0; // Reset the quiz
trace(Scoreboard.successRate); // Output the success rate based on correct answers at the end.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Disable chunking per request I have a web service backed by a Java Servlet. The service is used by an older version of Flash. We discovered through some pain that in this version of Flash, URLLoader won't work with chunked responses. Any chunked response is never received from the server.
I am using Glassfish to host the Servlet. I know how to disable chunking for the entire server, but that seems like a bad idea (is it?).
Is there a standard way to disable chunking per request? I tried calling ServletResponse.setBufferSize(SOME_LARGE_VALUE) but surprising this did not affect the server's decision to use chunking.
A: From the javadoc of HttpServlet#doGet():
...
Where possible, set the Content-Length header (with the ServletResponse.setContentLength(int) method), to allow the servlet container to use a persistent connection to return its response to the client, improving performance. The content length is automatically set if the entire response fits inside the response buffer.
When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.
...
So, if you set the response content length beforehand, then it won't be sent in chunked encoding.
response.setContentLength(contentLength);
// ...
Update: You also need to make sure that the servlet isn't in turn been called by <jsp:include> or RequestDispatcher#include(). See also its javadoc:
...
The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Are Process::detach and Process::wait mutually exclusive (Ruby)? I'm refactoring a bit of concurrent processing in my Ruby on Rails server (running on Linux) to use Spawn. Spawn::fork_it documentation claims that forked processes can still be waited on after being detached: https://github.com/tra/spawn/blob/master/lib/spawn.rb (line 186):
# detach from child process (parent may still wait for detached process if they wish)
Process.detach(child)
However, the Ruby Process::detach documentation says you should not do this: http://www.ruby-doc.org/core/classes/Process.html
Some operating systems retain the status of terminated child processes until the parent collects that status (normally using some variant of wait(). If the parent never collects this status, the child stays around as a zombie process. Process::detach prevents this by setting up a separate Ruby thread whose sole job is to reap the status of the process pid when it terminates. Use detach only when you do not intent to explicitly wait for the child to terminate.
Yet Spawn::wait effectively allows you to do just that by wrapping Process::wait. On a side note, I specifically want to use the Process::waitpid2 method to wait on the child processes, instead of using the Spawn::wait method.
Will detach-and-wait not work correctly on Linux? I'm concerned that this may cause a race condition between the detached reaper thread and the waiting parent process, as to who collects the child status first.
A: The answer to this question is there in the documentation. Are you writing code for your own use in a controlled environment? Or to be used widely by third parties? Ruby is written to be widely used by third parties, so their recommendation is to not do something that could fail on "some operating systems". Perhaps the Spawn library is designed primarily for use on Linux machines and tested only on a small subset thereof where this tactic works.
If you're distributing the code you're writing to be used by anyone and everyone, I would take Ruby's approach.
If you control the environment where this code will be run, I would write two tests:
*
*A test that spawns a process, detaches it and then waits for it.
*A test that spawns a process and then just waits for it.
Count the failure rate for both and if they are equal (within a margin that you feel is acceptable), go for it!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: time() to DateTime I have an application that uses time() to record the time a topic was posted. I have done this for a long time and the only glitch i ever had with the method was that the time was always off by an hour (mainly a DST issue i never looked into).
I'm want to switch to the DateTime method, since I'm also switching to Twig, which uses that date format when setting a timezone.
But from what I can see, you can't use timestamps to parse the date. my question is, how do you input a date and parse it and what format are they looking for if it isn't time()?
A: By the sounds of it your server's default timezone is UTC. I suggest you try changing the default_timezone setting in php.ini to something that applies DST. This will mean that when you use date(), the resulting output will be correctly adjusted for DST.
A:
you can't use timestamps to parse the date
There is a way, if your php version is >=5.3 :
$time = time();//or other time
$date = DateTime::createFromFormat('U',$time);
but as a matter of fact it is somewhat weird to use timestamp as DateTime does not rely on it. You can parse a date string directly with the datetime constructor if your date is english or "french" (i.e d/m/y). You can also create your custom format.
how do you input a date and parse it and what format are they looking for if it isn't time()
if it is a a standard format date :
$date = new DateTime($yourString);//would throw an exception if the format is wrong
if it is a custom format, like DD/MM/YYYY 14h32mins
$date = DateTime::createFromFormat('d/m/Y h\hi\m\i\n\s',$yourString);
if($date === false){//if format does not fit
exit('Your wrong !');
}
I have an application that uses time() to record the time a topic was posted.
Very bad practice. In MySQL you have DateTime format (and each relational data base system has his own equivalent) to store date times and there are fully compatible with the DateTime constructor in PHP so migrate to it (use FROM_TIMESTAMP to change into DateTime).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cakephp Acl Component and Inheritance cakephp acl component make roles like this:
*
*admin
*
*add_post
*delete_post
*edit_post
*view_post
*add_link
*delete_link
*edit_link
*view_link
*add_page
*delete_page
*edit_page
*view_page
*
manager_1:
*
*add_post
*view_post
*
manager_2:
*
*add_link
*view_link
*
manager_3:
*
*add_page
*view_page
*
users:
*view_post
*
now i will add a user to manager_1 and manager_2.
how i can do this with cakephp acl component???
maybe in this example i can create 4 or 5 different group. but when this options are many, i have to make group's role inheritance.
can i do this in cakephp acl component?
A: You will need to tell the ACL component to which ARO Group your User belongs. You can do that by implementing the parentNode() method in your User model. You can find an example of it here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: performing tests over variables in SAS I was wondering if it was possible to perform a ttest (proc ttest) over all variables in a dataset in SAS. Possibly through looping over the data?
Here's what I have currently but it's not running correctly:
data test;
set work.wisc;
array Avar(30) V1-V30;
do variable = 1 to 30;
proc ttest data = work.wisc;
class Diagnosis;
var Avar(variable);
end;
run;
Any help is much appreciated. Thanks!
A: Something like this may work. Calling the &&name&i. in the loop will reference each variable name. You may need to make some adjustments within the proc ttest as I'm not familiar with that function.
/* -- Get the names of the variables --*/
proc contents data = work.wisc out = names noprint; run;
/*--- Make macro vars needed ---*/
proc sql noprint;
select
count(distinct name) into :name_count from names;
select
distinct name into :name1 - :name9999 from names;
quit;
/*--- Strip spaces from name_count ---*/
%let name_count = &name_count.;
%put There are &name_count. variables in the data set;
/*--- Run the test for all variables ---*/
%macro testAll();
%do i = 1 %to &name_count.;
proc ttest data = work.wisc;
class Diagnosis;
var Avar(&&name&i.);
run;
%end;
%mend;
%testAll();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: GlPaint not accepting my image for brush Ok I'm not sure how much details I can really give, but I'm having a crazy weird problem. I'm using the GLPaint code in my app from Apple, and the PaintingView.m code is the same exact code from Apple-nothing else. Yesterday, everything was working fine and the brush image for the paint was a circular particle that came with the GLPaint, and it was working fine.
Now, out of nowhere, the particle is just a square, and a square particle means that the GLPaint app can't find my particle-meaning if I just put any file name into here: brushImage = [UIImage imageNamed:@"Particle.png"].CGImage; I'll get a square particle.
So this is something wrong. However, I just have no idea why. I tried replacing the Particle.png image over again and placing it in different places in my Xcode project but that didn't work. I know it's a long shot, but does anyone have ANY possible ideas as to why this could happen?
A: If you have replaced Particle.png with an image that is not square, and the sides are not a power of two, then it will not work. For instance, the particle image can be 32x32, or 64x64, but not 110x110.
As for debugging, I would suggest putting a breakpoint at the line after brushImage = [UIImage imageNamed...], and check the value of brushImage. If you are not comfortable using the debugger, just throw NSLog(@"%p", brushImage) right under that line. If the image is nil, or 0x0, then you know that the image file cannot be found or decoded. If it is not, then the problem is in the code, not the setup.
A: Well I figured out the problem and I'll post the solution just in case anyone ever has an issue like this. Turns out I had a duplicate painting view in IB that for some reason maybe confused the painting view class. All I had to do was delete one of the views, then everything worked fine again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Batch To get Count Of 0 Byte Files I'm trying to run a batch to get the number of 0 byte files in a directory. If the count is one or more then I want to delete the files otherwise quit. Here is what I have so far.
@echo off
if "%~z1" == "" (
echo File does not exist.
) else if "%~z1" == "0" (
echo File is empty.
) else (
echo File is non-empty.
)
A: (Edited, see comments. Original answer below.)
The following script counts empty files in a directory, then, if the count turns out greater than 0, deletes the empty files. The directory is specified as a parameter to the batch script. For example, if you need to process the directory of C:\Users\DS\Downloads, call the script like this (assuming script.bat is the script file's name):
script.bat C:\Users\DS\Downloads
This is the script:
@ECHO OFF
IF "%~1" == "" (ECHO Usage: %~nx0 path\to\files& GOTO :EOF)
SET "workdir=%~1"
SET count=0
SET "command=SET /A count+=1"
CALL :processempty
ECHO Number of empty files: %count%
IF %count% GTR 0 (
ECHO Deleting files...
SET "command=DEL ^"%%~F^""
CALL :processempty
)
GOTO :EOF
:processempty
FOR %%F IN ("%workdir%\*") DO (
IF "%%~zF" == "0" %command%
)
Original answer follows:
@ECHO OFF
SETLOCAL
SET firstfile=
SET delfirstfile=
FOR %%F IN (*) DO (
IF "%%~zF" == "0" (
IF DEFINED firstfile (
ECHO DEL "%%F"
SET delfirstfile=1
) ELSE (
SET "firstfile=%%F"
)
)
)
IF DEFINED delfirstfile ECHO DEL "%firstfile%"
ENDLOCAL
The above script works like this:
*
*It iterates through all the files in the current directory and checks their sizes.
*When the first empty file is found, its name is stored into a variable.
*Every subsequent empty file is deleted and another variable is set to indicate that the first empty file should be deleted too.
*After the loop the indicator variable is checked. If it is set, the first empty file is deleted.
PS. I would suggest you first to run this script as is to make sure it works correctly. Afterwards you'll need to remove ECHO in front of each of the two DEL commands to let the script actually remove files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Exporting Layout Positions for a Graph Using NetworkX After generating x/y layout coordinates for a graph in NetworkX, how do I export the graph, along with node positions, as part of the node definition using something like GraphML?
The layout algorithms don't seem to annotate the graph directly? Or do they?!
A: The layout algorithms don't set node attributes (but they should). Here is how to set the attributes:
In [1]: import networkx as nx
In [2]: G=nx.path_graph(4)
In [3]: pos=nx.spring_layout(G)
In [4]: nx.set_node_attributes(G,'pos',pos)
In [5]: G.node
Out[5]:
{0: {'pos': array([ 0., 0.])},
1: {'pos': array([ 0.32267963, 0.03340727])},
2: {'pos': array([ 0.67729057, 0.07011044])},
3: {'pos': array([ 1. , 0.10350174])}}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: itunes music developer app referral How do App developers get a referral bonus for sending users to the itunes store to purchase a song? If i'm not mistaken theres a 30% referral bonus, so to speak, just trying to determine how to tap into that.
A: It's documented here. I'm pretty sure the referral fee is 5%. Not 30%. It may depend on the type of media you're getting the commission on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: PHP file download problem: Server freezes for several minutes when user cancels a download then retries I'm using the following the PHP script to download a 20mb file:
(filepath & filename are set earlier in the script)
$fullPath = $filepath.$filename;
if ($fd = fopen($fullPath, "r")) {
// http headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($fullPath));
while(!feof($fd)) {
echo(fread($fd, 1024*8));
flush();
if (connection_status()!=0) {
fclose($fd);
die();
}
}
}
fclose($fd);
exit();
It works fine if the download finishes, but if the download is canceled by the user, and they click on the link to re-download, the server is completely unresponsive for several minutes, and then the download will begin. It seems like it is waiting for the script to time out...but isn't the "if (connection_status()!=0)..." part supposed to kil the script?
Any help is much appreciated! Thank you in advance!
A: I think you're over-engineering your solution somewhat. Try using readfile() instead of your fopen/fread loop.
Better yet, unless there's a compelling reason why you need PHP to mediate the file transfer, don't use a PHP script at all and simply provide a direct link to the file in question.
The best code is always the code you don't have to write.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WP7 dragging a pushpin on a map Does anyone have any insight into how to implement a draggable pushpin on a map on a WP7 client running Mango? I have a pushpin bound to a geo-location on a map and I want the user to be able to drag it on a map and record its new location. I've seen some resources, but they're for non-WP7 Bing Maps control. Any help would be appreciated.
Thanks!
A: e.GetPosition(element) gives the position relative to the element passed on the parameter. Also, the point to convert using ViewportPointToLocation has to be relative to the position of the map. So, you have to do the following:
Pushpin myPin = sender as Pushpin;
Point p = e.GetPosition(**Map**);
g = Map.ViewportPointToLocation(p);
A: I know this is a late response but I was working on a similar project and using a similar approach, so I thought I'd share. The approach that I used was:
Create two global double variables to hold X,Y coord's:
double mapLocX;
double mapLocY;
Set these global doubles to the location of the point of your pushpin in your DragStarted event:
Point point = myMap.LocationToViewportPoint(myPin.Location);
mapLocX = point.X;
mapLocY = point.Y;
In your dragDelta event, change these variables as your would your pushpin:
mapLocX += e.HorizontalChange;
mapLocY += e.VerticalChange;
Now on DragCompleted create a new point that takes in our rendered global variables, and map them to a geocoordinate, and here's the kicker; Remove our old pin from the ObservableCollection (Mine is Locations) and add in a new pushpin at our new coordinate:
Point point = new Point(mapLocX, mapLocY);
GeoCoordinate geoCoord = new GeoCoordinate();
geoCoord = myMap.ViewportPointToLocation(point);
Locations.Remove(myPin.Location);
Locations.Add(geoCoord);
Hope this helps
A: If anyone is curious, this is the solution I came up with:
XAML:
<map:Map x:Name="Map" Height="400" HorizontalAlignment="Left" Margin="6,10,0,0" VerticalAlignment="Top" Width="444" ZoomLevel="19" >
<map:Map.Mode><map:AerialMode /></map:Map.Mode>
<map:Pushpin x:Name="Pin" Background="Green" IsHitTestVisible="True" IsEnabled="True">
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener DragDelta="Pushpin_OnDragDelta" DragStarted="Pushpin_OnDragStarted" DragCompleted="Pushpin_OnDragCompleted">
</toolkit:GestureListener>
</toolkit:GestureService.GestureListener>
<map:Pushpin.RenderTransform>
<TranslateTransform></TranslateTransform>
</map:Pushpin.RenderTransform>
</map:Pushpin>
</map:Map>
.cs:
private void Pushpin_OnDragDelta(object sender, DragDeltaGestureEventArgs e)
{
Pushpin myPin = sender as Pushpin;
TranslateTransform transform = myPin.RenderTransform as TranslateTransform;
transform.X += e.HorizontalChange;
transform.Y += e.VerticalChange;
}
private void Pushpin_OnDragStarted(object sender, DragStartedGestureEventArgs e)
{
Map.IsEnabled = false; // prevents the map from dragging w/ pushpin
}
private void Pushpin_OnDragCompleted(object sender, DragCompletedGestureEventArgs e)
{
Map.IsEnabled = true;
}
Does anyone have any ideas on how to extract the geocoordinates of the pushpin's new location?? I tried the code below in the event handler and it doesn't give correct coordinates:
Pushpin myPin = sender as Pushpin;
Point p = e.GetPosition(myPin);
g = Map.ViewportPointToLocation(p);
myPin.location gives the old coordinates
A: You want to have the origin of your UI element not your finger right? Try this:
Point pM = e.GetPosition(**Map**);
Point pE = e.GetPosition(**UIElement**);
Point origin = new Point(pM.X - pE.X, pM.Y - pE.Y);
GeoCoordinate g = Map.ViewportPointToLocation(origin);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is it hard to beat AOT compiler with a JIT compiler (in terms of app. performance)? I was thinking that JIT compilers will eventually beat AOT compilers in terms of the performance of the compiled code, due to the inherent advantage of JIT (can use information available only at runtime). One argument is that AOT compilers can spend more time compiling code, but a server VM could spend a lot of time, too.
I do understand that JIT does seem to beat AOT compilers in some cases, but they still seem to lag behind in most cases.
So my question is, what are the specific, tough problems that is preventing JIT compilers to beat AOT compilers?
EDIT:
Some common arguments:
*
*AOT compilers can spend more time doing advanced optimizations -> If you are running a server VM for days, you can spend the same amount of time, if not longer.
*Byte code interpretation has cost -> Most JIT compilers cache native machine instructions anyways these days.
Yet another edit:
For a specific example, see this article: Improving Swing Performance: JIT vs AOT Compilation. From what I can gather from this article, the authors are basically saying that when there are no hotspots, the advantage of having runtime information decreases and thus AOT without the overhead of JIT, wins. But by 40%?? That doesn't seem to make a lot of sense. Is it simply that the JIT compiler that was compared wasn't tuned for this situation? Or is it something more fundamental?
A: There's a definite trade-off between JIT and AOT (ahead-of-time) compilation.
As you stated, JIT has access to run-time information that can aid in optimization. This includes data about the machine it's executing on, enabling platform-specific native optimization. However, JIT also has the overhead of translating byte-code to native instructions.
This overhead often becomes apparent in applications where a fast start-up or near real-time responses are necessary. JIT is also not as effective if the machine does not have sufficient resources for advanced optimization, or if the nature of the code is such that it cannot be "aggressively optimized."
For example, taken from the article you linked:
... what should we
improve in the absence of clear performance bottlenecks? As you may
have guessed, the same problem exists for profile-guided JIT
compilers. Instead of a few hot spots to be aggressively optimized,
there are plenty of "warm spots" that are left intact.
AOT compilers can also spend as much time optimizing as they like, whereas JIT compilation is bound by time requirements (to maintain responsiveness) and the resources of the client machine. For this reason AOT compilers can perform complex optimization that would be too costly during JIT.
Also see this SO question: JIT compiler vs offline compilers
A: Compilation and optimization are a function of code, context, and time.
Original Tradeoff
AOT can use as much time as needed, with deep code analysis, knowledge of execution platform, and additional hints for optimization. The disadvantages are slower builds, less portable code, bad optimizations based on wrong assumptions, and lacking support for advanced features like reflection during runtime.
JIT is much more portable and can support advanced code changes at runtime, but takes longer to start and has limited time and resources which means limited optimizations.
Modern Developments
The latest JIT compilers are much faster and start much quicker while still producing good code, closing most of the gap with AOT for startup latency.
Multiple compilation passes allow JIT to continually optimize the program as it runs, leading to similar performance as AOT after the warm-up period. The JIT can look at what code is actually used, how often it's used, and other factors like the running hardware that aren't available during AOT compilation.
The most advanced JIT compilers can meet or exceed AOT performance and maintain it under more scenarios. AOT is still the best option for fast startup and consistent/predictable operation, but no longer the default option for best overall performance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
}
|
Q: Workaround for TextField bug in FP 10.3.183.5 and 10.3.183.7 I have a client who is having a big problem with an AS2 application we developed a few years ago.
As far as I can tell, it is being caused by an acknowledged bug in recent versions of Flash Player (see http://forums.adobe.com/message/3859034 and https://bugbase.adobe.com/index.cfm?event=bug&id=2941694).
Two versions of FP are affected (10.3.183.5 and 10.3.183.7), and the bug was fixed in 10.3.183.10.
Obviously, upgrading Flash Player will fix the problem, but we all know users don't always do this and she has been getting emails about the problem.
I am contemplating having her update the SWFObject code to explicitly detect for 10.3.183.10 and have ExpressInstall "encourage" users to upgrade, but I don't know if this will fly.
I have tried several of the workaround that searches have uncovered, but none are working in my case.
I was wondering if anyone has found a reliable way to fix this?
A: First thing I would try would be to use the textField.htmlText instead of textField.text and see if that doesn't solve it (although I would be surprised if it did).
Second potential way I can see fixing this (and this is really not pretty) is to manually wordwrap. The following is in AS3 because that's what I use. I'll leave it to you to convert it to AS2 but I assume this should be possible in AS2 as well.
var text : String = "some text here";
var textField : TextField = new TextField();
textField.wordwrap = false;
textField.multiline = false;
textField.autosize = false;
textField.width = MAX_TEXT_WIDTH;
//other formatting stuff
var words : Array = text.split(" ");
var line : String = words[0];
textField.text = words[0];
var lines : Array = new Array();//will contain all lines
for(var i : int = 1; i < words.length; ++i)//start at second word
{
textField.text += " " + words[i];//try adding another word to the line
if(textField.textWidth > MAX_TEXT_WIDTH)//overflowed line
{
lines.push(line);
line = words[i];
textField.text = line;
}
else//doesn't overflow, line is still valid
{
lines += textField.text;
}
}
lines.push(line);
var text : String = lines[0];
for(i = 1; i < lines.length; ++i)
{
text += "\n" + lines[i];
}
textField.multiline = true;
textField.height = lines.length * HEIGHT_PER_LINE;//HEIGHT_PER_LINE can be found using getLineMetrics and
//adding gutter pixels to the height - might have to
//play a little with this
textField.text = text;
Not sure this compiles (it's probly not AS2 compatible anyways) but this should give the general idea. Do the wordwrapping yourself and see if that works. Also make sure that the formatting is applying to the text while you are checking for textWidth. I think you need to call setTextFormat(myTextFormat) everytime you change the textField.text value.
I also saw that apparently multiline might not work in that version. If that is the case, you might have to make a new TextField object for each line and offset their y values to make it look like it's the same TextField (hopefully you aren't using borders or backgrounds on your textFields if this is the case)
A: Now that the issue is fixed, it's unlikely anybody will bother coming up with a workaround. Probably the SWFObject method you suggested is the way to go. Just check if the version is within 10.3.183.5 and 10.3.183.7 and, if so, display the ExpressInstall.
A: The final AS version I think works best is
the_textfield.autoSize = false;
the_textfield.multiline = false;
the_textfield.wordWrap = false;
var words : Array = the_textfield.text.split(" ");
var line : String = words[0];
the_textfield.text = words[0];
var lines : Array = new Array();
for (var i : Number = 1; i < words.length; ++i) {
the_textfield.text += " " + words[i];
if (the_textfield.textWidth > SOME_WIDTH) {
lines.push(line);
line = words[i];
the_textfield.text = line;
} else {
line += " " + words[i];
}
}
lines.push(line);
var t : String = lines[0];
for (i = 1; i < lines.length; ++i) {
t += "\n" + lines[i];
}
the_textfield.text = t;
the_textfield.autoSize = true;
the_textfield.multiline = true;
the_textfield.wordWrap = false;
In my case, I had to futz with SOME_WIDTH, but the textfield was authored and there are some weird scaling things going on, so I just figured out the number empirically.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I modify the output of the PRINT function using Tie with a Moose implementation? I can't exactly wrap my head around TIE just yet but the examples ( example-1 example-2 example-3 ) I've seen so far use a non-Moosy implementation, is there anyway to do this:
package MY_STDOUT;
use strict;
my $c = 0;
my $malformed_header = 0;
open(TRUE_STDOUT, '>', '/dev/stdout');
tie *STDOUT, __PACKAGE__, (*STDOUT);
sub TIEHANDLE {
my $class = shift;
my $handles = [@_];
bless $handles, $class;
return $handles;
}
sub PRINT {
my $class = shift;
if (!$c++ && @_[0] !~ /^content-type/) {
my (undef, $file, $line) = caller;
print STDERR "Missing content-type in $file at line $line!!\n";
$malformed_header = 1;
}
return 0 if ($malformed_header);
return print TRUE_STDOUT @_;
}
1;
use MY_STDOUT;
print "content-type: text/html\n\n"; #try commenting out this line
print "<html>\n";
print "</html>\n";
In a more Perl-Moosy way?
For example should I do
open(TRUE_STDOUT, '>', '/dev/stdout');
tie *STDOUT, __PACKAGE__, (*STDOUT);
in a BUILD{} function?
Would it make more sense to implement this as a Moosy class or as Moose::Role?
And finally, would I have to do something like
my $MY_STDOUT = MY_STDOUT->new();
to use it?
A: I've figured out how to do it with IO::Scalar
https://gist.github.com/1250048
Now I just need to figure out how to do it for STDOUT!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Utf8 Linux filenames and C I am working at a OS independent file manager, using SDL_ttf to draw my text.
On Windows, everything works well, but on Linux I have to use the UTF8 functions of SDL_ttf, because the filenames can be UTF8 encoded.
This works well, but if I have my own C string (not a file name) such as "Ää", it will be displayed wrong. Is there any way to tell gcc to encode my strings as UTF8?
A: You don't need anything special from your C compiler for UTF-8 string literals. Proper support for it in the APIs you use is another matter, but that seems to be covered.
What you do need to do is to make sure your source files are actually saved in UTF-8, so that non-ASCII characters don't get converted to some other encoding when you edit or save the file.
The compiler doesn't need specific UTF-8 support, as long as it assumes 8-bit characters and the usual ASCII values for any syntactically significant characters; in other words, it's almost certainly not the problem.
A: gcc should interpret your source code and string literals as UTF-8 by default. Try -fexec-charset
See also: http://gcc.gnu.org/onlinedocs/gcc-4.0.1/cpp/Implementation_002ddefined-behavior.html#Implementation_002ddefined-behavior
A: C should have some sort of Unicode string literal syntax. Googling for "Unicode programming C" should get you started, two tutorials that seemed good are the one on developerworks and the one on cprogramming.com.
The general approach for your specific case would be using a wide string literal L"Ää", then converting that into UTF-8 with wcstrtombs().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Service not saving SharedPreference for Main Activity? I am using a service to download and retrieve a list of URL's and put them in a sharedpreference.
With this..
SharedPreference images_article = this.getSharedPreferences("images_articles", MODE_WORLD_READABLE);
editor.putString("article2", urlImage2);
editor.putString("article3", urlImage2);
editor.commit();
Then in my Main.Activity i pull the url's from preference.
SharedPreference images_article = this.getSharedPreferences("images_articles", MODE_WORLD_READABLE);
urlImage2 = images_article.getString("article2", "NO ARTICLE AVAILABLE");
urlImage3 = images_article.getString("article3", "NO ARTICLE URL AVAILABLE");
The only problem is for some reason it isnt going inside of the shared preference, because the Main activity is loading the OLD URL's that has now changed. But in the Service i log the url's being retrieved and they are updated but for some reason in the main activity it still loads the old one. and im retrieving them from the same preference.
Is there anything i am missing or a better way to do this? Any help would be great!!
A: I was running in to a similar issue with my SharedPreferences between my Activity and Service. I ended up not using the default and used my own set file name
in the activity and service I set
private static final String PREFERENCE_NAME = "MyPreferenceFileName";
Then to get the values:
SharedPreferences pref = getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
pref_checked = pref.getBoolean("checked", true);
and to set the values:
SharedPreferences pref = getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("checked", value);
editor.commit();
This allowed me to use the same get and put logic in both my Service and Activity without any issues. I hope this helped.
A: This might be happening due to the different contexts you are accessing from. I am not very sure though, but you can try this :
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
Use this code, whenever you try to access SharedPreferences, that is, from both the Service and the Activity. That might solve your problem.
A: Using this in both the Activity and Service classes seems to work for me, as it should now be using the same Context to access the application SharedPreferences:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Initializing array on the fly in constructor (Java) public class A{
public A(int[] a){}
}
public class B extends A{
public B(double[] b){
super({b.length}); //ERROR
}
}
I want to be able to compile the code above. To clarify, I have class A and B that extends it. Class A does not have an empty parameter constructor. If I don't put a call to super in Class B's constructor on the first line, it will try to call super(), which doesn't exist. But, I want to call super(int[] a) instead. I want to do this by taking the length of a given double array and sending it as an array with length 1. It does not let me do this because apparently you can't declare an array like that, and if I were to declare it on a separate line it would call super() first and that won't work.
Is there any way to declare an int[] on the fly like that? Or are the only solution here to either make a constructor for A with no parameters or make my own function that returns an int[]?
(Don't ask why I want to send it as an array like that.)
A: Yeap, try:
super(new int[]{b.length}); //ERROR NO MORE
A: you can also
public class A{
public A(int... a){}
}
public class B extends A{
public B(double[] b){
super( b.length );
}
}
A: If you insist on not asking why...
You could make the array, assign the first and only element and send it.
public class B extends A{
public B(double[] b){
int[] arr = new int[1];
arr[0] = b.length;
super(arr); // broken, super must be first.
}
}
This means you must have a one line solution. Luckily, Java provides an in-line way to make a series of elements into an array at compile time.
public class B extends A{
public B(double[] b){
super(new int[]{b.length}); // FIXED
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to Parse a Glossary Section of a Website with BeautifulSoup & strip HTML tags I'm trying to Parse this page
http://www.lib.uts.edu.au/about-uts-library/corporate-information/library-glossary
and get just the
Title,
Description
for each section and that's it, no tags.
I parse the page and try to search for all <title> and <p> tags but it doesn't produce the right results.
I am using Python 2.7 and BeautifulSoup 3-2-0
Here is a sample of my code:
import urllib2, sys
address = sys.argv[1]
html = urlib2.urlopen(http://www.lib.uts.edu.au/about-uts-library/corporate-information/library-glossary).read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
def printText(tags):
for tag in tags:
if tag._class_==NavigableString:
print tag,
else:
printText(tag)
print ""
printText(soup.findALL("p"))
print "".join(soup.findALL("p", text=re.compile(".")))
A: I'm not entirely sure what you're looking for, but I suspect you are looking to get the term and definition out from this page. Looking for the <title> and <p> tags is not really what you need. You should look for attributes that make a tag unique. In this case, looking at the <span> tag shows that there is a class attribute that uniquely labels the terms. This can be used to isolate the sections that you need. I suggest looking more closely at the documentation for find/findAll. Below is some code that will get you most of the way there.
from BeautifulSoup import BeautifulSoup
import urllib
url = 'http://www.lib.uts.edu.au/about-uts-library/corporate-information/library-glossary'
soup = BeautifulSoup(urllib.urlopen(url))
paragraphs = [x.parent for x in soup.findAll(name='span',attrs={'class':'definition'}) if x.parent.name == 'p']
for p in paragraphs:
name = p.find(name='span',attrs={'class':'definition'}).text
text = p.text.replace(name,'')
print '-'*80
print name
print text
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting/setting a global variable in InstallShield I have InstallScript code that executes a particular task. The task will either work or will not work. If the task works, I want to set a global variable to 1. If it does not work, I want to set a global variable to 0.
Somewhere down the line, I have another InstallScript code that executes. What I want is to check the global variable to see if it's 1. If it is, fire off that code.
I know that I can modify the Install Exec Condition, but what I do not know how to do is to check for a global variable. How I can accomplish this?
A: In an InstallScript project, merely create and set a global variable, and code against it as you please.
If instead you are asking in the context of an MSI with custom actions that run InstallScript, you have to use MSI Properties as your global variables. Call MsiSetProperty to set it, and write your custom action's condition against that property. Or call MsiGetProperty to retrieve it in your code and do the conditional execution there. Note that if the first action is in the UI sequence and the second is in the Execute sequence, you should add any properties you use to the SecureCustomProperties property.
To make this more concrete, your code might look like:
// Note: hInstall is the first parameter to your custom action
MsiSetProperty(hInstall, "RUN_SECOND_ACTION", "1");
and your condition in the custom action might be simply:
RUN_SECOND_ACTION
A: You can just declare a variable outside the function in .rul file, and the variable would be a global variable.
If you want to use the global variable in another .rul file, you have to include the rul file which declares the global variable.
ex.
/* featureevents.rul */
STRING globalVar; // declare a global variable
export prototype xxx_installed();
function xxx_installed()
STRING localVar; // declare a local variable
begin
end;
--
/* Setup.rul */
#include "featureevents.rul"
function OnFirstUIBefore()
begin
// use a global variable
globalVar="This is a global variable.";
MessageBox(globalVar, INFORMATION);
end;
I suggest you that add one or more resource header files, and put all the constants, global variables and function declaration in them.
/* featureevents.rul */
#include "CusRes.h"
...
--
/* Setup.rul */
#include "CusRes.h"
...
--
/* CusRes.h */
#ifndef _CUSRES_H_
#define _CUSRES_H_
// move the code to resource header file
STRING globalVar;
export prototype xxx_installed();
#endif //_CUSRES_H_
However, as Urman said, using property is a better way.
I miss the step of SecureCustomProperties, so I cannot get the value by MsiGetProperty() and use global variable instead.
But now I have got the information, and I'll also rewrite my code to use property instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Iterative piping implementation for linux in c I know this question gets asked a lot but I am still really confused as to how to go about fixing my problem. I have attempted to write code that handles command line input for the possibility of several pipes. However, I am unsuccessful and my code, although executing does not work correctly. The bug is once I've forked the children, I cannot get to the next command that the pipe goes to after the very first command executes. How do I move to the next command in the pipe without grabbing the wrong file descriptors? Here is a chunk of code;
a = 0;
while (a < cmdnum)
{
pid[a] = fork();
if( pid[a] == 0)
{
if( a == 0)
{
close(1);
dup(p1_to_pn[a][1]);
for( k = 0; k < nump; k++)
{
close(p1_to_pn[k][0]);
close(p1_to_pn[k][1]);
}
args = tokenize(cmd[a]);
execv(args[0], args);
}
else if ( a == (cmdnum-1))
{
close(0);
dup(p1_to_pn[a][0]);
for( k = 0; k < nump; k++)
{
close(p1_to_pn[k][0]);
close(p1_to_pn[k][1]);
}
args = tokenize(cmd[a]);
i = execv(args[0], args);
}
else
{
close(0);
dup(p1_to_pn[a][0]);
close(1);
dup(p1_to_pn[a][1]);
for( k = 0; k < nump; k ++)
{
close(p1_to_pn[k][0]);
close(p1_to_pn[k][1]);
}
args = tokenize(cmd[a]);
execv(args[0], args);
}
}
a++;
}
A: Your mistake is thinking you need to move to the "next" command. Start them all.
Here's the basic idea, for a pipeline like A | B | C
The parent process reads the command line. For each new command, it is going to fork a new process, and eventually exec it. The parent process already has fd 0,1,2 open (STDIN, STDOUT, and STDERR.) When you hit the pipe, use the pipe(2) and dup(2) system calls to make a new fd; fork the next process.
All the fd manipulation happens in the parent process.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: using if with scope on model I am trying to make a named scope called :current_season where the it will correctly identify the records associated with the year we are in. Mostly easy enough except I want everything June and later to use the current year and everything prior to June to use the previous year.
in rails 3.1 I can easily use:
scope :current_season, lambda { where('season = ?',Time.now.year) } if Time.now.month >= 6
to get the scope to only work if we are at the end of the year and :
scope :current_season, lambda { where('season = ?',Time.now.year - 1) } if Time.now.month < 6
But it seems to wasteful to have to name it all twice and not use an if/else type of thing or be able to call in something I define below to show the exact year such as:
scope :current_season, lambda { where('season = ?',:current_season_year) }
def current_season_year
if Time.now.month >= 6
Time.now.year
else
Time.now.year - 1
end
end
But that just laughs at me when I try it. Is there a cleaner way? I will also have a scope :last_season and scope :previous_season most likely and they will follow similar logic.
thanks in advance for any advice!
A: Named scopes are just a DSL for writing a class methods that all have a similar functionality. Whenever you find them to be limiting you, just switch to a class method instead:
def self.current_season
year = Time.now.month >= 6 ? Time.now.year : Time.now.year - 1
where('season = ?', year)
end
Of course, you could also include that in a scope like this:
scope :current_season, do
# same code as above...
end
It's just going to define it as a class method on the model though. The tradeoff is clarity in the intention of a scope (it's expected to return a chainable ActiveRecord::Relation) versus clarity in documentation (if you run something like RDoc it isn't going to notice a method available at Model.current_season because it hasn't been defined in the code yet).
Update:
There is one additional benefit from using a scope instead of a class method:
User.admin.create name: 'Corey' #=> <User: @name="Corey" @admin=true>
You can use a scope to create an object with certain parameters, as well. In this case, this isn't very useful, but it's worth considering when deciding which to use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: JSON read 4700 records from database My android application use this code for to read and import 4700 records from mysql database on the web with JSONArray :
@Override
protected String doInBackground(Void... params) {
try{
httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.example.com/preleva_prodotti.php");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
//Log.e("log_tag", "Error in http connection "+ e.toString());
httpclient.getConnectionManager().shutdown();
return result = "no_server";
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
String k = reader.readLine();
while ((line = k) != null) {
sb.append(line + "\n");
}
is.close();
result=sb;
}catch(Exception e){
return result = "no_server";
}
//parse json data
try{
JSONObject json= new JSONObject(result);
JSONArray jArray = json.getJSONArray("array");
return is_full="ok_insert";
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
return is_full = "no_dati";
}
}
but at the line :
while ((line = k) != null) {
sb.append(line + "\n");
}
there is the error : Out of Memory.
How can resolve this problem?
A: I'm not too familiar with Java, so bear with me, but this seems to be language-agnostic.
That said, the problem appears to be that k is never updated. Once k is assigned (k = reader.readLine()) you're (indefinitely) re-assigning line that same value (thus infinite loop, thus out of memory).
I think you're looking for:
String k = reader.readLine();
while ((line = k) != null) {
sb.append(line + "\n");
k = reader.readLine(); // or some facsimile
}
Note that I now re-assign k (though I'm not sure the redundancy of having k = line; seems like a waste of a variable, imho)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to display point cloud in vtk in different colors? I have a point cloud which I want to visualize in vtk. I want to see them in different colors depending on some conditions. I am using python.
Any suggestions on how to do that?
Thanks a lot
A: Here is an example that sets the point color based on z-axis value.
import vtk
from numpy import random
class VtkPointCloud:
def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6):
self.maxNumPoints = maxNumPoints
self.vtkPolyData = vtk.vtkPolyData()
self.clearPoints()
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(self.vtkPolyData)
mapper.SetColorModeToDefault()
mapper.SetScalarRange(zMin, zMax)
mapper.SetScalarVisibility(1)
self.vtkActor = vtk.vtkActor()
self.vtkActor.SetMapper(mapper)
def addPoint(self, point):
if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:
pointId = self.vtkPoints.InsertNextPoint(point[:])
self.vtkDepth.InsertNextValue(point[2])
self.vtkCells.InsertNextCell(1)
self.vtkCells.InsertCellPoint(pointId)
else:
r = random.randint(0, self.maxNumPoints)
self.vtkPoints.SetPoint(r, point[:])
self.vtkCells.Modified()
self.vtkPoints.Modified()
self.vtkDepth.Modified()
def clearPoints(self):
self.vtkPoints = vtk.vtkPoints()
self.vtkCells = vtk.vtkCellArray()
self.vtkDepth = vtk.vtkDoubleArray()
self.vtkDepth.SetName('DepthArray')
self.vtkPolyData.SetPoints(self.vtkPoints)
self.vtkPolyData.SetVerts(self.vtkCells)
self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth)
self.vtkPolyData.GetPointData().SetActiveScalars('DepthArray')
pointCloud = VtkPointCloud()
for k in xrange(1000):
point = 20*(random.rand(3)-0.5)
pointCloud.addPoint(point)
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
# Renderer
renderer = vtk.vtkRenderer()
renderer.AddActor(pointCloud.vtkActor)
renderer.SetBackground(.2, .3, .4)
renderer.ResetCamera()
# Render Window
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
# Interactor
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
# Begin Interaction
renderWindow.Render()
renderWindowInteractor.Start()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: can't have a file larger than 10*10 characters what makes it only be able to input 10*10 text files
package game;
import java.io.*;
import java.util.*;
public class Level {
static public void main(String[] args) throws IOException {
File f = new File("Data1.txt");
int[][] m = Map(f);
for (int x = 0; x < m.length; x++) {
for (int y = 0; y < m[x].length; y++) {
System.out.print(m[x][y]);
}
System.out.println();
}
}
public static int[][] Map(File f) throws IOException {
ArrayList line = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(f));
String s = null;
while ((s = br.readLine()) != null) {
line.add(s);
}
int[][] map = new int[line.size()][];
for (int i = 0; i < map.length; i++) {
s = (String) line.get(i);
StringTokenizer st = new StringTokenizer(s, " ");
int[] arr = new int[st.countTokens()];
for (int j = 0; j < arr.length; j++) {
arr[j] = Integer.parseInt(st.nextToken());
}
map[i] = arr;
}
return map;
}
}
if i put in a text file that is
10*10 or less characters it works
otherwise it comes out with a numberformatexception
fixed
package game;
import java.io.*;
import java.util.*;
public class Level {
static public void main(String[] args) throws IOException {
File f = new File("Data1.txt");
int[][] m = Map(f);
for (int x = 0; x < m.length; x++) {
for (int y = 0; y < m[x].length; y++) {
System.out.print(m[x][y]);
}
System.out.println();
}
}
public static int[][] Map(File f) throws IOException {
ArrayList line = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(f));
String s = null;
while ((s = br.readLine()) != null) {
line.add(s);
}
int[][] map = new int[line.size()][];
for (int i = 0; i < map.length; i++) {
s = (String) line.get(i);
char[] m = s.toCharArray();
String[] n = new String[m.length];
for (int t = 0; t<m.length;t++)
{
n[t] = ""+m[t];
}
int[] arr = new int[m.length];
for (int j = 0; j < arr.length; j++) {
arr[j] = Integer.parseInt(n[j]);
}
map[i] = arr;
}
return map;
}
}
A: Contrary to notes in the comments, your program seems to work with large files, and with long lines, as long as there are enough spaces.
I think your issue is actually that whenever the text file has a token with more than 10 characters it throws a NumberFormatException.
That would be because Integer.MAX_INT is 2147483647, which has 10 characters when written as a String, and Integer.parseInt just can't handle more digits than that.
You're splitting on space and expecting everything to parse as an integer, and some of your numbers are too big for Java's integer data type.
A: Int's max value is: 2,147,483,647 or 2147483647 without the commas. That's 10 characters. attempting to parse an 11 character string to an int would result in a number that is beyond the Int's max value, hence, the NumberFormatException.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamic linq: passing entire query as string Looking at Dynamic Linq, it's possible to use strings to define the key parts of the query. My question is, is it possible to pass the entire query in as a string?
ie: var foo = "from..."
A: That's not possible in dynamic LINQ -- dynamic LINQ only replaces specific pieces of the query. You can use ExecuteQuery on the data context in LINQ to SQL or SqlQuery on a DbSet<T>, though, to execute specific SQL commands.
A: LINQ stands for "Language INtegrated Queries" - it's compiled with the rest of the code, not parsed on the run. You can use Microsoft.CSharp.CSharpCodeProvider to compile your query on the run - but you will have to know in advance what local objects you want to send to the query.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Installing Remote Zoom-In on non-dev PC When developing for Windows Mobile I use "Remote Zoom-In" to take screen shots of the mobile device. This is part of Visual Studio 2008. I want to install this on a document-writer's PC but I don't want to install Visual Studio. How can I do this?
A: You can't install Remote Zoom without installing Studio (you might be able to copy it, but the connectivity pieces will be a challenge), but you can install SOTI Pocket Controller, which is free to try.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android-Java- converting a WeakReference to a normal Bitmap Ive been working on an app for a while that uses lots of Bitmaps and Ive gotten it to the point where its working really well on most devices that Ive tested it on except for a newer droid bionic that runs 2.3.4
I get an out of memory error and I can see the heap growing in the logcat too. So far Ive tried re-sizing the bitmaps with different techniques which works great for every other device except the new droid bionic which is weird being that you would think a newer phone would handle vm better.
Ive looked at some other threads on here that talk about using various methods but the one Im interested in using involves using WeakReferenced to store images as. This is great but how can I convert the weakreference back to a normal bitmap to use on a canvas.
EDIT: heres a recent stack trace dumparoo :p
09-30 12:33:09.231 2867 2922 E AndroidRuntime: FATAL EXCEPTION: go
09-30 12:33:09.231 2867 2922 E AndroidRuntime: java.lang.OutOfMemoryError
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.io.AbstractSessionInputBuffer.init(AbstractSessionInputBuffer.java:79)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.io.SocketInputBuffer.<init>(SocketInputBuffer.java:93)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.SocketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:83)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:170)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:106)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:129)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:363)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at graffit.data.ImageGrabber.imagegetter(ImageGrabber.java:164)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at graffit.data.ImageGrabber.traverseIDS(ImageGrabber.java:118)
09-30 12:33:09.231 2867 2922 E AndroidRuntime: at graffit.data.ImageGrabber$getMarkImageThread.run(ImageGrabber.java:238)
09-30 12:33:09.239 480 750 W ActivityManager: Force finishing activity graffit.main/.GraffView
09-30 12:33:09.669 480 873 I ActivityManager: Process graffit.main (pid 2867) has died.
09-30 12:33:09.677 480 590 I WindowManager: WINDOW DIED Window{407c4100 graffit.main/graffit.main.GraffView paused=true}
09-30 12:33:09.677 480 590 I WindowManager: WINDOW DIED Window{408044e0 Toast paused=false}
09-30 12:33:09.684 480 759 I WindowManager: Setting rotation to 0, animFlags=1
A: Are you making http calls in your code using the Apache DefaultHttpClient?
I've recently discovered a problem specific to the Droid Bionic which causes it to use a lot more VM memory than other Android devices while downloading files using the HttpClient. This may be the true cause of your memory leaks if your are not experiencing an OutOfMemoryError on other devices.
Do you have any stack traces that indicate an OutOfMemoryError during a http call?
I believe the work-around code starting at line 64 in the following source maybe missing on the Droid Bionic build:
http://codesearch.google.com/codesearch#CskViEIa27Y/src/org/apache/http/impl/io/SocketInputBuffer.java&q=package:android.git.kernel.org%20file:org/apache/http/impl/io/SocketInputBuffer.java&l=1
You can fix this by using HttpConnectionParams.setSocketBufferSize(params, 8192) when you create your http client.
A: WeakReference.get()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How To make scope of variable Global(Without making it actually Global) How can I make scope of a String variable(In Java) global.So that it is accessed from another function
Eg
//String b="null"; I don't want to do this... because if i do this, fun2 will print Null
public int func1(String s)
{
String b=s;
}
public int func2(String q)
{
System.out.println(b);//b should be accessed here and should print value of s
}
Any Help... Thanks
A: One of the fundamental concepts in OOP is the concept of scope: in almost all cases it is wise to reduce the scope of a variable (i.e. where it is visible from) to its minimum viable range.
I'm going to assume you absolutely require the use of that variable in both functions. Therefore, the minimum viable scope in this case would cover both functions.
public class YourClass
{
private String yourStringVar;
public int pleaseGiveYourFunctionProperNames(String s){
this.yourStringVar = s;
}
public void thisFunctionPrintsValueOfMyStringVar(){
System.out.println(yourStringVar);
}
}
Depending on the situation, you must assess the required scope of a variable, and you must understand the implications of increasing the scope (more access = potentially more dependencies = harder to keep track).
As an example, let's say you absolutely needed it to be a GLOBAL variable (as you call it in your question). A variable with Global scope can be accessed by anything within the application. This is exceptionally dangerous, which I will demonstrate.
To make a variable with global scope (there are no such things as global variables, exactly, in Java), you create a class with a static variable.
public class GlobalVariablesExample
{
public static string GlobalVariable;
}
If I were to alter the original code, it would now look like this.
public class YourClass
{
public int pleaseGiveYourFunctionProperNames(String s){
GlobalVariablesExample.GlobalVariable = s;
}
public void thisFunctionPrintsValueOfMyStringVar(){
System.out.println(GlobalVariablesExample.GlobalVariable);
}
}
This can be exceptionally powerful, and exceptionally dangerous as it can lead to weird behaviour that you do not expect, and you lose many of the abilities that object oriented programming gives you, so use it carefully.
public class YourApplication{
public static void main(String args[]){
YourClass instance1 = new YourClass();
YourClass instance2 = new YourClass();
instance1.pleaseGiveYourFunctionProperNames("Hello");
instance1.thisFunctionPrintsValueOfMyStringVar(); // This prints "Hello"
instance2.pleaseGiveYourFunctionProperNames("World");
instance2.thisFunctionPrintsValueOfMyStringVar(); // This prints "World"
instance1.thisFunctionPrintsValueOfMyStringVar(); // This prints "World, NOT Hello, as you'd expect"
}
}
Always assess the minimum viable scope for your variables. Do not make it more accessible than it needs to be.
Also, please don't name your variables a,b,c. And don't name your variables func1,func2. It doesn't make your application any slower, and it won't kill you to type in a few extra letters.
A: Hmm. You clearly need some lessons in object-oriented programming. In OO there is no "global" variable. But any variable defined as a member in a class (outside a method) is global within that class.
public class MyClass {
private String myVar; // this can be accessed everywhere in MyClass
public void func1(String s) {
myVar = s;
}
public void func2(String q) { // why is q needed here? It's not used
System.out.println(myVar);
}
}
So func2 will output the value of s ONLY IF you call func1 first.
final Myclass myClass = new MyClass();
myClass.func1("value");
myClass.func2("whatever"); // will output "value"
Also, why are the methods returning int in your example? They should be void.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: counting source code lines in python project How do I calculate the number of lines written in a project containing multiple sub dirs in a python project. for example a dir structure is like
A
\ <*some files here*>\
B
\ <*some files here*>\ ... and so on...
A: You could use the find utility in linux.
On the command prompt:
$ find <project_directory_path> -name '*.py' | xargs wc -l
This will give you the count of all files ending with .py in the project_directory and finally the total. (I am assuming you just want the count of .py files)
If you just want the total and nothing else, you could use:
$ find <project_directory_path> -name '*.py' | xargs wc -l | tail -1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Import troubles Here is part of my module: gm.py
def avg_list(list):
sum = 0
for num in list:
sum += num
avg = float(sum)/len(list)
print avg
def median(list):
i = len(list)
if not i%2: # if i divided my 2 has no remainder
return (list[(i/2)-1]+list[i/2])/2.0 # return the value of this block
else:
median = sorted(list)[len(list)/2] # otherwise, when the list is sorted, the index of len(s) / 2 is the middle number.
return median
When I save this as 'gm.py' and open a new script page to input the following function:
import gm
def stats(list):
stats = {} # empty dict named stats
stats['average'] = avg_list(list) # Stats(key)[average] = mean of the list of numbers [values]
stats['median'] = median(list) # same for median
return stats
When I run this program and type stats([2,3,4,5,6])... I get an error saying global variable avg_list not defined. I'm not sure if I'm doing the import correctly?
Do I need to do something like... from gm import avg_list() ?
A: Either reference the functions on the module object:
import gm
def stats(list):
stats = {} # empty dict named stats
stats['average'] = gm.avg_list(list) # Stats(key)[average] = mean of the list of numbers [values]
stats['median'] = gm.median(list) # same for median
return stats
or import the functions directly into the global namespace:
from gm import avg_list, median
def stats(list):
stats = {} # empty dict named stats
stats['average'] = avg_list(list) # Stats(key)[average] = mean of the list of numbers [values]
stats['median'] = median(list) # same for median
return stats
Note that you should not name a variable list. This masks the built-in list() function / type and can cause confusing errors later if you need to use it.
You can write
stats = {} # empty dict named stats
stats['average'] = avg_list(list) # Stats(key)[average] = mean of the list of numbers [values]
stats['median'] = median(list) # same for median
return stats
as
stats = {'average': avg_list(list), 'median': median(list)}
return stats # or just return the dict literal, no real need to give it a name.
I think you should look at the first branch of your median function. Does the list need to be sorted there too, like in the second branch?
Your avg_list function is also masking a built-in function, sum(), which you could use here instead of manually adding:
def avg_list(list):
avg = float(sum(list))/len(list)
print avg
Finally, look at the last line of that function -- it's printing the avg, but stats is expecting it to return the avg. The two aren't the same.
A: You need to put the module name first (gm.avg_list() and gm.median()) like so:
import gm
def stats(list):
stats = {} # empty dict named stats
stats['average'] = gm.avg_list(list) # Stats(key)[average] = mean of the list of numbers [values]
stats['median'] = gm.median(list) # same for median
return stats
Some Reference links and more info:
PEP 8 - Style Guide for Python Code
A guide to Python Namespaces on the differences between from blah import foo and import blah
*
*import SomeModule
This is the simplest way to do imports and generally recommended. You
get access to the module’s namespace provided you use the module’s
name as a prefix. This means that you can have names in your program
which are the same as those in the module, but you’ll be able to use
both of them. It’s also helpful when you’re importing a large number
of modules as you see which module a particular name belongs to.
*
*from SomeModule import SomeName
This imports a name (or a few, separated by commas) from a module’s
namespace directly into the program’s. To use the name you imported,
you no longer have to use a prefix, just the name directly. This can
be useful if you know for certain you’ll only need to use a few names.
The downside is that you can’t use the name you imported for something
else in your own program. For example, you could use add() instead of
Integer.add(), but if your program has an add() function, you’ll lose
access to the Integer’s add() function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WPF height and scroll at listbox - imposible To keep things simple all i am trying to do is to place a listbox and a button below it. Although it seems simple it isn't. It is not, because it is in a GRID...
The row size is star size and listbox having verticalAlign top works great all the time. The problem is that I cannot add a button below it. Having a grid with 2 rows one star height and the other auto would place the button at the bottom of the form even if listbox contents are little. Trying to set both rows auto doesn't work when resizing as no scrollbar is visible at the listbox.... Any workaround for this??
Update some code
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DockPanel >
<ListBox DockPanel.Dock="Top" Name="lbStaff" ItemsSource="{Binding}"
Grid.Row="0" VerticalAlignment="Top" BorderThickness="0"
Background="WhiteSmoke" Margin="15,10,20,30" Style="{DynamicResource
ListBoxUsers}" ScrollViewer.VerticalScrollBarVisibility="Visible">
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource
ListBoxTest1}"></Style>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Margin="5,4,5,4">
<TextBlock HorizontalAlignment="Stretch" FontSize="16"><Run
Text="{Binding Name}"/> - <Run Text="{Binding Mode=OneWay,
Path=PositionString}"/></TextBlock>
<TextBlock >Τηλέφωνο <Run Text="{Binding Phone}"/>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button DockPanel.Dock="Top" Grid.Row="0" HorizontalAlignment="Right"
VerticalAlignment="Top" Margin="0,10,7,0" Style="{DynamicResource
ButtonStyleNew1}">
<Button.Content>
<StackPanel Orientation="Horizontal">
<Image Source="/WpfApplication1;component/Images/filenew1.png"
Stretch="None" VerticalAlignment="Center"></Image>
<TextBlock Margin="5,0,0,0" FontSize="16">Προσθήκη Χρήστη</TextBlock>
</StackPanel>
</Button.Content>
</Button>
</DockPanel>
</Grid>
</Grid>
A: What i usually do is not using rows of grid but using DockPanel you can adjust the alignments by nesting each elements. But again it totally depends on the designer how they design that using grid row or any other way. What i got from the question the following code should help you out.
but if you post some code then we can figure out where the actual problem is.
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<DockPanel>
<DockPanel DockPanel.Dock="Top">
<ListBox Height="50"/>
</DockPanel>
<DockPanel DockPanel.Dock="Bottom">
<Button Height="20" DockPanel.Dock="Top"/>
<Label/>
</DockPanel>
</DockPanel>
</Grid>
A: So your problem here is that you have the in the ListBox you have ScrollViewer.VerticalScrollbars=Visible that make it collapsed if you dont want scrollbars and i would suggest not to use margins more in the designing. if you still have scroll bars remove the height of the ListBox and make the window larger. It all depends upon the size of the window if you don't have the size and proper alignment. Refining your code
<Window xmlns:my="clr-
namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
x:Class="MyLightWpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
xmlns:local="clr-namespace:MyLightWpfApplication.ViewModel"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Skins/MainSkin.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<DockPanel >
<DockPanel DockPanel.Dock="Top" Width="400" Height="200">
<ScrollViewer DockPanel.Dock="Top" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
<ListBox Name="lbStaff" ItemsSource="{Binding AutoCompleteData}"
BorderThickness="0"
Background="WhiteSmoke" >
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel >
<TextBlock HorizontalAlignment="Stretch" FontSize="16"><Run
Text="{Binding FirstName}"/> - <Run Text="{Binding Mode=OneWay,
Path=PositionString}"/></TextBlock>
<TextBlock >Τηλέφωνο <Run Text="{Binding LastName}"/>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
</DockPanel>
<DockPanel DockPanel.Dock="Bottom">
<Button DockPanel.Dock="Top" Height="30" Grid.Row="0">
<Button.Content>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="16">Προσθήκη Χρήστη</TextBlock>
</StackPanel>
</Button.Content>
</Button>
<Label/>
</DockPanel>
</DockPanel>
</Grid>
</Window>
Its all dependent on how much data you have in the ListBox. I have tried this code populating listbox with 20 rows its not showing scrollbars at all
A: You might try auto for both and put a MaxHeight on the ListBox but you still take a chance of pushing the button off the screen. Or put both in a ScrollViewer. Or can you live with the button on top?
A: I solved this problem using a dockpanel. I docked buttons at bottom and then i let listbox to fill the remaining area..(lastchildfill=true) ...
It works fine...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: LINQ to XML issue due to xml namespace I am trying to use Linq to select from XML. Here is an example of the XML:
<?xml version="1.0" encoding="UTF-8"?>
<listingexport xmlns="http://websitexmlfeed.com/webservice/2/listings"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://websitexmlfeed.com/webservice/2/listings ../listings.xsd">
<listing>
<id>00001</id>
<name>Modelname</name>
<type>Typename</type>
</listing>
</listingexport>
The code I am using is as follows:
XDocument le = XDocument.Load(@uri);
var listings = (from listing in le.Descendants("listing")
select new listingType
{
Id = listing.Element("id").Value,
Name= listing.Element("name").Value,
Type= listing.Element("type").Value
}).ToList();
Problem I have is that the le.Descendants("listing") call doesnt return any results from the XML file due to the namespace information (i guess an issue related to this post: ASP.NET 2.0 XmlDataSource's XPath doesn't support namespaces). However, If I modify the XML file so there is no namespace information as so:
<?xml version="1.0" encoding="UTF-8"?>
<listingexport>
<listing>
<id>00001</id>
<name>Modelname</name>
<type>Typename</type>
</listing>
</listingexport>
it works. Unfortunately I do not have access to modify the xml file so need a solution that will work. Any help appreciated.
thank you,
Joe
A: Include
XNamespace ns = "http://websitexmlfeed.com/webservice/2/listings";
and try
var listings = (from listing in le.Descendants(ns + "listing")
select new
{
Id = listing.Element(ns + "id").Value,
Name= listing.Element(ns + "name").Value,
Type= listing.Element(ns + "type").Value
}).ToList();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How does one install the FFTW package under Fedora and get Octave to recognize it as loaded? All the references to FFTW in Octave make it sound like it is a package only for Octave (not quite true, but close), and give instructions for installing a tar.gz file by typing on the Octave command line, "pkg install ". But the FFTW website itself says to either use RPM, or better yet, your own distributions package. Well, Fedora does have a package for it, named (surprise) 'fftw'. But after installing this with yum, I still have no idea what name to use on the Octave command line with the pkg install command: the obvious 'fftw' doesn't work. And there is no /etc/fftw directory created, either (I forget which directions said this should have happened, but it didn't).
So what is my next step after installing the Fedora package? I'm not going to need to build FFTW from source, am I?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to send inbox messages with facebook sdk php I would like to send a private message to inbox, like:
$facebook->api('/me/feed','POST',array(
'message'=>'mensagem aqui',
'name'=>'nome aqui',
'caption'=>'caption aqui',
));
but send it to inbox.
it's possible do to?
I mean it:
A: Not possible. See Facebook Permissions and Graph API (scroll down to Publishing section).
If the user has a facebook email (like user@facebook.com) you can just send an email there. Another alternative is to do a 'private' post. See Graph API Post
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What does "./" (dot slash) refer to in terms of an HTML file path location? I know ../ means go up a path, but what does ./ mean exactly?
I was recently going through a tutorial and it seems to be referring to just a file in the same location, so is it necessary at all? Can I just not use it if that's all it's doing?
A: . = This location
.. = Up a directory
So, ./foo.html is just foo.html. And it is optional, but may have relevance if a script generated the path (relevance to the script that is, not how the reference works).
A: Yes, ./ means the current working directory. You can just reference the file directly by name, without it.
A: / means the root of the current drive;
./ means the current directory;
../ means the parent of the current directory.
A: For example css files are in folder named CSS and html files are in folder HTML, and both these are in folder named XYZ means we refer css files in html as
<link rel="stylesheet" type="text/css" href="./../CSS/style.css" />
Here .. moves up to HTML
and . refers to the current directory XYZ
---by this logic you would just reference as:
<link rel="stylesheet" type="text/css" href="CSS/style.css" />
A: A fast and small recap about paths
Absolute paths
http://website.com/assets/image.jpg
IF the image is not on your domain - go look there for image
//website.com/assets/image.jpg
image loaded using http or https protocols
Relative paths
(For internal use if the image is on the same server)
image.jpg
image in the same place as the document calling the image!
./image.jpg
Same as above, image in the same place as the document calling the image!
/assets/image.jpg
Similar to Absolute Paths, just omitting the protocol and domain name
Go search my image starting from my root folder /, than into assets/
assets/image.jpg
this time assets is in the same place as the document, so go into assets for the image
../assets/image.jpg
From where the document is, go one folder back ../ and go into assets
../../image.jpg
go two folders back, there's my image!
../../assets/image.jpg
go two folders back ../../ and than go into assets
A: Yeah ./ means the directory you're currently in.
A: Do NOT use ./ as a web path! I explain why and what it is below...
TRUE WEB PATHS YOU SHOULD ALWAYS USE
../siblingfolder/file.html is a web path that starts from the folder you are in, goes up one parent folder (../), goes down into a new folder called "siblingfolder" and to "file.html" inside it. This is a type of relative path in the web world.
childfolder/file.html is another kind of web path that starts from the folder you are in and goes down to "childfolder" and "file.html" inside it. This is also as a relative path.
/subrootfolder/file.html is a web path that starts from the web root of your website and goes down from the web root into "subrootfolder" as an absolute path. Note: This path has the added advantage in that it works from any file and folder location on the server.
http://somewebsite.com/subrootfolder/file.html is another web path which works exactly the same as the ones above, but requires your web domain in the path. It still works but is very limiting because the web domain is hard-coded into the path. Some call this a fully qualified web path, which has some uses. The web browser also resolves most file paths to this address or an IP version of it.
AWKWARD AND RARELY USED PATHS
. is a shorthand for the current location or file context and is used in Linux and Unix to execute a compiled program in the current directory. That is why you don't see this used in Web Development much except by open source, non-Windows frameworks like Google Angular which was written by people stuck on open source platforms.
./ also resolves to the current directory and is atypical in Web but supported as a path in some open source frameworks. Because it resolves the same as no path to the current file directory its not used. Example: ./image.jpg = image.jpg. Even though it is used by software to identify a current folder location, because it is identical to the current software path or file location, it is the same as no path so redundant. Again, this is a relic of Unix operating systems that need path resolutions like this to run executables and resolve paths for security reasons. Its not a typical web path. That is why this syntax is redundant in HTML and web technologies.
//somewebsite.com/folder/folder/file.html this is a form of a fully qualified web URL resolution format. "//" tells the web browser to determine the fully qualified web URL/URI at runtime and concatenate the right http protocol onto the front of your path as so: https://mywebsite.com/folder/folder/file.html. It allows the browser to query one of many web domains and determine the most secure location or protocol to use: Either "http" or "https" as the most favorable and secure prefix. This is rarely used in most internal web paths but likely found in link href attribute paths in newer HTML5 elements and used when adding links to resources that may resolve to unknown dynamic secure socket layer connections at runtime that change.
PATH EQUIVALENTS
folder = /folder a relative path is the same as an absolute path in this case if the file accessing this child "folder" is located under the web root directory. Both paths would work the same for them.
../folder = /folder a relative path going up to a parent folder then down to "folder" is the same as the absolute path if the file accessing this path again is in the web root directory.
./folder = folder both relative paths start with the files current folder and point to the child "folder" under them no matter where these folders are located, so are the same. "./" is therefore redundant.
./file.html = file.html both relative paths point to the current folder and then to a "file.html" inside that folder. This means use of "./" is redundant.
./ = {no path} an empty path is the same as ./ in the web world so redundant again.
./ = / only true again if the file is under the web root folder. Again this means "./" is redundant.
MY WEB PATH RECOMMENDATIONS
ALWAYS use Absolute Paths ("/myfolder/myfile") whenever possible as they will always work from any file location in the web project, add no confusion to developers, moving files with absolute paths will not change paths, and they are easy to maintain and manage. The only drawback to absolute paths is if you move the files or folders being pathed to new locations (example: You move an image or CSS folder of files to a new location later in the project). That is why I recommend you manage paths via server-side virtual paths, application paths, or server-generated variables so you can change absolute paths dynamically as you move things around.
ALWAYS use Relative Web Paths ("../myfile") as a secondary option. These are a must for CSS file paths, CSS imported files, or font paths within CSS files. They should only be used if your web application is designed with many parallel applications running side-by-side under one domain, and have nested and heavily dependent resource files running inside them that must be separated. In that one case, you will often move these applications as one module deeper into the application making relative pathing more valuable. You will determine paths relative to the source files in that case and not relative to the web domain via absolute paths. As above, I would still manage paths via server-side or virtual application generated paths. This makes paths extremely simple, robust, and easy to dynamically update on the fly via server variables rather than inside scripts and dependencies which constantly evolve.
NEVER use the other paths listed unless forced to by atypical, 3rd party, proprietary software conventions that use substandard pathing solutions that add confusion and added maintenance. :(
A: You can use the following list as quick reference:
/ = Root directory
. = This location
.. = Up a directory
./ = Current directory
../ = Parent of current directory
../../ = Two directories backwards
Useful article:
https://css-tricks.com/quick-reminder-about-file-paths/
A: ./ is the the folder that the working file is in:
So in /index.htm ./ is the root directory
but in /css/style.css ./ is the css folder.
This is important to remember because if you move CSS from /index.htm to /css/style.css the path will change.
A: You are correct that you can omit it. It's useful only for clarity. There is no functional difference between it being there and not being there.
A:
./ = Current directory
This is correct but as i figured out from some templates that i worked on before, the purpose of this identification is to remind the developer that the file to be accessed is not actually in the same directory as the HTML file being worked. Yes, I know it sounds weird.
Developers who use such definitions usually put a <base href=""> tag at the beginning of the HEAD block of the HTML page. Double quotes also indicate the directory they want to reach, so they don't have to define phrases like "../images" to access all of the image files that are not in the same directory as the HTML.
For example,
/main
/ /assets
/ / /css
/ / /images
/ / / /logo.png
/ /html
/ / /demo
/ / / /index.html
/ /plugins
every time you want to access the files in the images folder from the index.html file on a website with a directory structure like above, you need to use the src="../../assets/images" path. If you specify <base href="../../assets"> instead, you can now just use "images/" or "./images". Of course, remember, in this case, you will need to specify the file locations accordingly, as other page links will also be based on that <base> tag. So it's up to you whether you need to use it or not.
I did not wrote this to find the correct answer. This is my experience about the "./" usage so i wanted to share it. I hope it could help anybody.
A: In reference to the quick reference list, specifically you can use the following :
\.\ Root Directory + Current directory (Drive Letter)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "302"
}
|
Q: If NoSQL is schemless how can it be good for massive updates? I was thinking in a schema for a problem where "people" got a country, in RDBMS i can make two tables, one for people and other for country and make a key to connect the two... if i want to change the name of a country then i just change it in "country" table and and people got this new value... but i was thinking that if i make this in a key/document like MongoDB i will just need one document for "people" that inside it will have the value of country, like:
{name:"Tiago",
Country: "Brazil"}
Now, if i want to change all "Brazil" to "BraSil", i will have to search for ALL people where country equals "Brazil" and then update? so, it will not be more slow than RDBMS???
A: There's no one answer; the technique will depend on the engine; As you said, "NoSQL" databases are not all created equal.
In CouchDB; you (usually) access all of your data through views, and you could easily change something like this in a view; The up-side is that since views are plain-old JavaScript, you can express just about any kind of transformation quite easily. The down side is that all views in CouchDB are basically the same idea as materialized views in SQL databases; and the first time you try to access such a value, the response will take as long as is neccessary to rebuild the whole view; if that's a lot of data to be rewritten, that'll take a while.
In AppScale or GoogleAppEngine, you'd have to change the entities directly; The only really effective way to systematically touch a possibly large set of data is to use a task queue, and you'd systematically query for entities that match "Brazil" until it didn't return any rows. There'd be a time when real queries return a mixture of both values.
In all cases; The strength of distributed document databases comes with a kind assumption that some kinds of operation are computationally intensive; but the engine itself is designed to still be available even while these kinds of operations are under way. This is largely a consequence of the trade offs that databases make to satisfy cap theorem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Editing xml using SQL I'm new the xml data type in SQL Server. I have a field with some xml that I want to edit. In essence I want to delete certain nodes if they have a certain datatype or value. There are many subtype nodes and each subtype can have many SubtypeFieldInfo.
In cases where a SubtypeFieldInfo node contains a node :
<DefaultValue xsi:type="xs:dateTime">2222-02-22T00:00:00</DefaultValue>
I would like to delete that node
Here is the full xml. Any help much appreciated
<DEFeatureClassInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:typens="http://www.esri.com/schemas/ArcGIS/10.0" xsi:type="typens:DEFeatureClassInfo">
<Subtypes xsi:type="typens:ArrayOfSubtype">
<Subtype xsi:type="typens:Subtype">
<SubtypeName>1</SubtypeName>
<SubtypeCode>1</SubtypeCode>
<FieldInfos xsi:type="typens:ArrayOfSubtypeFieldInfo">
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>Status</FieldName>
<DomainName>pwStatus</DomainName>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>OwnedBy</FieldName>
<DomainName>shdMaintainedBy</DomainName>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>MaintainedBy</FieldName>
<DomainName>shdMaintainedBy</DomainName>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>InputCode</FieldName>
<DomainName />
<DefaultValue xsi:type="xs:int">12</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>UnitType</FieldName>
<DomainName>trafStripingType</DomainName>
<DefaultValue xsi:type="xs:string">SY</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>CalTDescription</FieldName>
<DomainName>trafStripingDescr</DomainName>
<DefaultValue xsi:type="xs:string">CL</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>DetailNumber</FieldName>
<DomainName />
<DefaultValue xsi:type="xs:string">1</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>StripingDetail</FieldName>
<DomainName>trafStripingDetail</DomainName>
<DefaultValue xsi:type="xs:string">2WYCENTERLINE</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>Color</FieldName>
<DomainName>trafStripingColor</DomainName>
<DefaultValue xsi:type="xs:string">Yellow</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>LinePattern</FieldName>
<DomainName>trafStripeLineType</DomainName>
<DefaultValue xsi:type="xs:string">Skip</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>Material</FieldName>
<DomainName>trafStripingMaterial</DomainName>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>TravelDirection</FieldName>
<DomainName>trafTravelDirection</DomainName>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>IsSchoolZone</FieldName>
<DomainName>shdBooleanYesNo</DomainName>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>EstInstallDate</FieldName>
<DomainName />
<DefaultValue xsi:type="xs:dateTime">2222-02-22T00:00:00</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>RefreshDate</FieldName>
<DomainName />
<DefaultValue xsi:type="xs:dateTime">2222-02-22T00:00:00</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>WOUpdateDate</FieldName>
<DomainName />
<DefaultValue xsi:type="xs:dateTime">2222-02-22T00:00:00</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>Quadrant</FieldName>
<DomainName>shdQuadrantZone</DomainName>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>DwgAsbuiltDate</FieldName>
<DomainName />
<DefaultValue xsi:type="xs:dateTime">2222-02-22T00:00:00</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>DwgSignDate</FieldName>
<DomainName />
<DefaultValue xsi:type="xs:dateTime">2222-02-22T00:00:00</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>AcceptanceDate</FieldName>
<DomainName />
<DefaultValue xsi:type="xs:dateTime">2222-02-22T00:00:00</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>IsSyncHansen</FieldName>
<DomainName>shdBooleanYesNo</DomainName>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>ImageDate</FieldName>
<DomainName />
<DefaultValue xsi:type="xs:dateTime">2222-02-22T00:00:00</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>ModifiedDate</FieldName>
<DomainName />
<DefaultValue xsi:type="xs:dateTime">2222-02-22T00:00:00</DefaultValue>
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>CreateDate</FieldName>
<DomainName />
<DefaultValue xsi:nil="true" />
</SubtypeFieldInfo>
<SubtypeFieldInfo xsi:type="typens:SubtypeFieldInfo">
<FieldName>DwgSheet</FieldName>
<DomainName />
<DefaultValue xsi:nil="true" />
</SubtypeFieldInfo>
</FieldInfos>
</Subtype>
A: Not sure what node you want to delete so here are two options.
Delete the DefaultValue node:
update YourTable
set XMLCol.modify('delete (//SubtypeFieldInfo/DefaultValue)
[@xsi:type="xs:dateTime" and
text() = "2222-02-22T00:00:00"]')
Delete the SubtypeFieldInfo node:
update YourTable
set XMLCol.modify('delete (//SubtypeFieldInfo)
[DefaultValue/@xsi:type="xs:dateTime" and
DefaultValue/text() = "2222-02-22T00:00:00"]')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Fast n-gram calculation I'm using NLTK to search for n-grams in a corpus but it's taking a very long time in some cases. I've noticed calculating n-grams isn't an uncommon feature in other packages (apparently Haystack has some functionality for it). Does this mean there's a potentially faster way of finding n-grams in my corpus if I abandon NLTK? If so, what can I use to speed things up?
A: You might find a pythonic, elegant and fast ngram generation function using zip and splat (*) operator here :
def find_ngrams(input_list, n):
return zip(*[input_list[i:] for i in range(n)])
A: Since you didn't indicate whether you want word or character-level n-grams, I'm just going to assume the former, without loss of generality.
I also assume you start with a list of tokens, represented by strings. What you can easily do is write n-gram extraction yourself.
def ngrams(tokens, MIN_N, MAX_N):
n_tokens = len(tokens)
for i in xrange(n_tokens):
for j in xrange(i+MIN_N, min(n_tokens, i+MAX_N)+1):
yield tokens[i:j]
Then replace the yield with the actual action you want to take on each n-gram (add it to a dict, store it in a database, whatever) to get rid of the generator overhead.
Finally, if it's really not fast enough, convert the above to Cython and compile it. Example using a defaultdict instead of yield:
def ngrams(tokens, int MIN_N, int MAX_N):
cdef Py_ssize_t i, j, n_tokens
count = defaultdict(int)
join_spaces = " ".join
n_tokens = len(tokens)
for i in xrange(n_tokens):
for j in xrange(i+MIN_N, min(n_tokens, i+MAX_N)+1):
count[join_spaces(tokens[i:j])] += 1
return count
A: For character-level n-grams you could use the following function
def ngrams(text, n):
n-=1
return [text[i-n:i+1] for i,char in enumerate(text)][n:]
A: def generate_ngrams(words, ngram=2):
return [words[i:i+ngram] for i in range(len(words)-ngram+1)]
sentence = "I really like python, it's pretty awesome."
words = sentence.split()
words
['I', 'really', 'like', 'python,', "it's", 'pretty', 'awesome.']
res = generate_ngrams(words, ngram=2)
res
[['I', 'really'],
['really', 'like'],
['like', 'python,'],
['python,', "it's"],
["it's", 'pretty'],
['pretty', 'awesome.']]
res = generate_ngrams(words, ngram=3)
res
[['I', 'really', 'like'],
['really', 'like', 'python,'],
['like', 'python,', "it's"],
['python,', "it's", 'pretty'],
["it's", 'pretty', 'awesome.']]
res = generate_ngrams(words, ngram=4)
res
[['I', 'really', 'like', 'python,'],
['really', 'like', 'python,', "it's"],
['like', 'python,', "it's", 'pretty'],
['python,', "it's", 'pretty', 'awesome.']]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: iframe alternative Before I ask my question I have gone through this: Better alternative to an iframe?, and haven't found a solution to my problem, or maybe I did not understand correctly!
I have a HTML-page which contains a Dojo-tree on the left hand side. When I click on an element on the left-hand tree (Say element1), I load an iframe on the right with a url:
www.something.com?selected=element1
Now the source of the frame is a jsp which does this:
<%
/* Get the user selection*/
String selectedElement = request.getParameter("selected");
/* Code to Fetch some content from the database using the above string */
%>
Since the left hand side tree has many elements, clicking on each element loads the iframe on the right hand side as above. The arrangement works perfectly fine. But I am wondering if this is the best way to do it? Can I some how not use iframes and still obtain the same result? I read somewhere that loading iframes is several times slower than not loading iframes.
Any help will be appreciated!
A: If the links are in the same domain, you could use jQuery load to populate a DIV instead of an iframe. This would be much better from an organizational perspective and make your page much easier to navigate for people with accessibility issues. If the content is from another domain, you're stuck with the iframe unless you process the requests on your server.
<div id="menu">
<a class="menu-item" href="/?selected=foo">Foo</a>
<a class="menu-item" href="/?selected=bar">Bar</a>
...
</div>
<div id="content">
...default content...
</div>
<script type="text/javascript">
$(function() {
$('.menu-item').click( function() {
$('#content').load( $(this).attr('href') );
return false;
});
});
</script>
Dojo example
<script type="text/javascript">
dojo.ready( function() {
dojo.query('.menu-item').onclick( function() {
dojo.xhrGet({
url: dojo.attr(this,'href');
load: function(content) {
dojo.byId('content').innerHtml = content;
}
});
return false;
});
});
</script>
A: Using iframes to include page fragments which comes from the same server as the parent page is very poor for SEO and user experience. Bots don't index the iframe's content as part of the parent page. Ctrl+Clicking or copying links which should end up in iframe may cause "wtf?" experiences of the enduser when seeing the result.
Just use server side includes like <jsp:include>.
<jsp:include page="${param.selected}.jsp" />
Provide element1.jsp and so on.
Ajax-loading is also an option, but please do it unobtrusively (i.e. it must work the same way with JS disabled, see how tvanfosson demonstrated it). This way you reach a wider audience and better SEO.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Drupal Installation PDOException http://localhost got problem:
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal_test.semaphore' doesn't exist: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] => variable_init ) in lock_may_be_available() (line 165 of /var/www/drupal/includes/lock.inc).
This is my database configuration:
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'drupal_test',
'username' => 'root',
'password' => 'XXX',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
What to do?
A: This just happened to me. I manually added database information to settings.php and tried to run the install script by accessing http://localhost/mysubdirectory, instead of adding db info through the install script. Drupal saw the db information and thought it was installed, so it looked for its Drupal tables, couldn't find them, and threw the error.
The solution for me was simply to run the script manually (navigating to http://localhost/mysubdirectory/install.php). Hope this helps!
A: a lot of times simply uninstalling and trying again can fix bugs like this. It's possible that there was something wrong with the installation of maybe you gave it some incorrect information.
A: semaphore is core table for holding semaphores, locks, flags, etc. that cannot be stored as Drupal variables since they must not be cached. In some version updating (6.xx-6.yy) it was lost, so just create it:
CREATE TABLE IF NOT EXISTS `semaphore` (
`name` varchar(255) NOT NULL DEFAULT '',
`value` varchar(255) NOT NULL DEFAULT '',
`expire` double NOT NULL,
PRIMARY KEY (`name`),
KEY `expire` (`expire`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
A: It try to read a table was not found.
If you install a new module, try to reinstall this module, or remove it . But if you don't install anything, you need to reinstall all drupal :(
A: This problem is related to your mysql database type. If you are moving your site another server, probably your database type is mismatch and using InnoDB. Because of that, you have to change your database table's type with this command.
ALTER TABLE **table_name** ENGINE = MyISAM;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Using Code Project (CPOL) licenced code on Google Code I have a piece of software that I would like to open source via Google Code Project Hosting. The problem is that I have used some code from Code Project which is licenced with the Code Project Open Licence (CPOL).
Are any of the available licences I can choose from Google Code compatible with CPOL? Or do I have to find some way of removing the CPOL code before I can open source my software? I'm having a hard time figuring out if I can include the CPOL code. Thanks.
A: I read it the way that the original code (and in part if your create a derivate) requires that it's licensed under The Code Project Open License (CPOL) 1.02.
Google Project hosting requires an OSI-approved license.
As far as I can see, CPOL is not OSI-approved.
You can contact the original author/copyright holder of the code and ask to gain rights on the codebase under a different license that full-fills the requirements of your google code hosting.
Or you choose another platform that allows more licenses. I think github requires only that the code is "open source" (you can read the source code).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a difference between calling a member function from a leaf class in or out of the destructor body? I have a specific case which is hard to isolate in a code snippet here but I can explain it...
I have a class A : public B and A has a member pointer of some type foo * f. In the virtual destructor for A, I have something like:
A::~A() { shutdown(); }
where, shutdown is nonvirtual and looks something like:
void A::shutdown() {delete f;}
it turns out at runtime this gives me a "pure virtual method called terminate called without an active exception Aborted (core dumped)" but if I remove shutdown() from the body of the destructor and call it directly, and then let the destructor run...I no longer get this...
What could possibly be causing behavior of this sort? I've tried stepping with gdb but it's huge and I'm not even sure what to look for. Any ideas would be very much appreciated!
A: Either shutdown is a pure virtual function somewhere up the inheritance tree, or it calls another member function which is pure virtual somewhere up the inheritance tree. Either directly or indirectly, but that's what happens.
Check the execution path to see where the call is made and get rid of it.
A: If A has both the shutdown method AND the pointer f, don't call shutdown() at all. Just delete f in the destructor directly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Looking for windows equivalent of the unix script command The unix command "script" allows a user to run programs/commands, and when ctrl-d is pressed, the output is written to a file. A timestamp of the session is also written in this file. Is there is a equivalent command in Windows/Visual Studio?
A: is Cygwin an option? The script command can be found in the util-linux package.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Renaming MS-DOS internal commands Is it possible by any means to rename the internal commands of DOS? Firstly, I am doing this to learn a bit about the internals and possibilities of DOS. So far I have changed the internal command CLS to XLX (on Windows XP). But the command name XLX isn't executing. I am attaching 2 screenshots for the reference. Above everything else, this whole activity is just my curiosity.
A: That shell you're running isn't DOS and it isn't command.com; as the window title indicates, it's cmd.exe which is a different program entirely. Your changes might actually work if you were running the DOS command interpreter — which might or might not be as easy as just running command from the cmd shell.
A: It looks like you have only changed the string containing documentation about the CLS command. I would suspect that there is another "CLS" string somewhere.
It is difficult to know for sure because command.com is closed source software. One thing you could do is use debug or another debugger (ollydebug is a free GUI debugger) to trace out what happens when you run CLS and find the conditional jump where command.exe decides to perform the cls command.
A: COMMAND will try to run CMD's internal commands, at least on Vista.
To see the difference try starting COMMAND, and then the command VER. COMMAND /C VER will give a different result, so if you did it right you should try "COMMAND /C XLX". I have no idea if that will work or not.
A: changing the internal command mgiht cause danger to yoiur registry content.. so i suggest you to oerform your experiment after having a backup of your data or on a virtual machine is most preferable as per my experience..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how do you pass a parameter to a function when it is called by reference? I've created a global variable to pass informatin to a method that is called via a method reference
d_g.onerror=i_bm_err_fix;
I tried passing it the variable like this(below) but it did not work.
d_g.onerror=i_bm_err_fix(d_g);
All I'm trying to do is have a generic image load if the site favicon does not.
function i_bm_err_fix(d_g)
{
d_g.src='http://www.archemarks.com/favicon1.ico';
}
Currently I'm using a global variable to pass this info. but this does not seem like good practice.
A: If I understand what you're trying to do correctly, this should do the trick:
d_g.onerror = function() {
i_bm_err_fix(d_g);
}
A: Wouldn't this work?
var myFunc = function(myargument){
alert(myargument);
};
myFunc('Hello, World');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OnCheckedChanged event not firing when Checkboxes within Repeater are checked I am a relatively new developer, and have only been doing this for about 6 months full time, so thank you in advance for reading and/or responding to my question
I have a databound repeater. Inside this repeater, I have a gridview, SQLDS, and 2 checkboxes. Both checkboxes have a OnCheckedChanged event and AutoPostback is set to true. The repeater has an OnItemDataBound event as well.
Here is a sample of how my code is laid out:
<asp:Repeater ID="Repeater1" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:Panel>
<asp:UpdatePanel>
<ContentTemplate>
<asp:Checkbox ID="Checkbox1" Autopostback="True" OnCheckedChanged="CheckBox1_CheckedChanged">
<asp:Checkbox ID="Checkbox2"Autopostback="True" OnCheckedChanged="CheckBox2_CheckedChanged">
<asp:Gridview ID="Gridview1" DataSourceID="SqlDataSource1">
<asp:SQLDataSource ID="SQLDataSource1" SelectCommand="SP1" SelectCommandType="StoredProcedure">
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
And the C#
protected void Checkbox1_CheckedChanged(object sender, EventArgs e)
{
if (Checkbox1.Checked == true)
{
if (Checkbox2.Checked == true)
SqlDataSource1.SelectCommand = "SP1";
else
SqlDataSource1.SelectCommand = "SP2";
}
else
SqlDataSource1.SelectCommand = "SP3";
}
protected void Checkbox2_CheckedChanged(object sender, EventArgs e)
{
if (Checkbox2.Checked == true)
{
if (Checkbox1.Checked == true)
SqlDataSource1.SelectCommand = "SP3";
else
SqlDataSource1.SelectCommand = "SP2";
}
else
SqlDataSource1.SelectCommand = "SP1";
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//Uses FindControl to Databind the GV and hides it if GV.Rows.Count==0
}
I'm doing all of this within an AJAX TabPanel. I have another page where this code works perfectly, but it's not inside a repeater on that other page.
Essentially, I have a page load with a gridview, and the two checkboxes change what SP fills the gridview. The problem I'm having is that when you uncheck the checkbox (they start checked), it 1. Just rechecks itself and 2. Doesn't hit the CheckedChanged event.
Any help would be GREATLY appreciated.
A: You need to set AutoPostBack=True attribute for the checkboxes and also register/assign event handlers of all controls which are added into the UpdatePanel through Triggers property of UpdatePanel control.
A: The Autopostback on the checkboxes is causing the SQLDatasource to just revert to the original Stored Procedure, as it hits page load and just ignores the oncheckchanged events.
What I did is I took all of my databinding events in pageload and put them inside of a if (!IsPostBack) clause, so that when the Autopostback hits, it doesn't rebind the SQLDS to the original value.
This way, when the autopostback occurs, there's nothing for it to do, and it hits the OnCheckedChanged events as it's supposed to.
Thank you everyone for reading and responding.
A: ASP.NET Repeater has an event that causes a round trip from client to occur. The event is called ItemCommand. Check out this link :- http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemcommand.aspx
Hope this helps
A: i found a similar issue and solved
http://www.codeproject.com/Questions/88960/OnCheckedChanged-Event-for-the-checkbox-inside-the/?cmt=3621
Regards
A: First, you need to bring the UpdatePanel outside of the repeater, and add runat="server". You should also bring the datasource control outside of the repeater too, and reuse it for all of the GridViews inside of the repeater.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<!-- checkboxes -->
<!-- gridview -->
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ...>
A: Actually your databinding method probably called outside the if(!ISPOSTBACK) { }
condition, so call this method inside the ispostback block, i hope your problem will be solved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is the correct type required for the delete operator in C++? void * intptr = new int;
delete (int *) intptr;
Is the (int *) type cast required?
A: Yes. Since C++ is not an everything-is-and-object language, the delete command must know the type of what you want to delete in order to know how to delete it.
A: Yes.
The type must match that which was new'd. The only time it doesn't have to match is deletion of a derived type through a base pointer, where the base type has a virtual destructor.
A:
3 destructors for int will be called.
There's no such thing as a "destructor for int". delete/delete[] will only call a destructor for things that aren't POD or POD-class types.
A: It is required because delete will call a destructor for each allocated element, even for int.
Consider this:
char * chars = new char[3];
delete [] (int*)chars;
What will happen? 3 destructors for int will be called. First one for memory address of &chars[0], second one for &chars[4] and third one for &chars[8]. Consider that &chars[4] and &chars[8] exceed the size of allocated memory. Even though int destructor in most if not all compilers is dummy it is wrong behaviour. And imagine if you write
delete [] (Foo*)chars;
where Foo has destructor and sizeof(Foo) > sizeof(char). Behaviour of your program will be undefined.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Setting multiple truststore on the same JVM I have an Java application running on a weblogic server. The application has two distinct modules which use SSL to connect to external web services - let's say module A and module B.
Module A - Built on Axis - Uses truststore A
Moudle B - Built on Spring-ws - Uses truststore B.
Module A is existing. Module B is being introduced.
I need to be able to set the truststore dynamically in the JVM based on which module is being invoked.
Due to some constraints I do not have the option
- to create a custom key manager.
- use one truststore
I tried to use System.setProperty im Module B codebase to set truststore. However it works only if Module B got invoked first. For example - Say
I have a fresh restart of the JVM
then I invoke module A - it set's it's own truststore in the JVM
then I invoke module B - It fails - it's does not set it's own truststore in the JVM even though I have used System.setProperty method.
Am I missing something or it's just that System.setProperty doesn't override existing set values. If so what are my options here.
A: You can load trusted key stores dynamically at runtime.
// load your key store as a stream and initialize a KeyStore
InputStream trustStream = ...
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// if your store is password protected then declare it (it can be null however)
char[] trustPassword = ...
// load the stream to your store
trustStore.load(trustStream, trustPassword);
// initialize a trust manager factory with the trusted store
TrustManagerFactory trustFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustFactory.init(trustStore);
// get the trust managers from the factory
TrustManager[] trustManagers = trustFactory.getTrustManagers();
// initialize an ssl context to use these managers and set as default
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagers, null);
SSLContext.setDefault(sslContext);
Watch out, because SSLContext.getDefault() would give you back the default context which you cannot modify, so you have to create a new one, initialize it then set this new context as the default.
The bottom line is that you can use any number of trust stores if you want to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: TeamCity Visual Studio Plugin We use TeamCity at work. It would be nice to be able to keep an eye on checkin, build, and test run status without having to have a browser window open.
I have seen references to a TeamCity Visual Studio plugin here and here. The second page is their Professional vs. Enterprise Edition feature comparison page. Both version list "Plugins for MS Visual Studio, Eclipse, and JetBrains IDEs family."
Does anyone know how to download and install this add-in? It does not appear to be in the general TeamCity installation.
A: On your TeamCity web UI, goto My Settings and Tools
On the TeamCity tools right sidebar, you will see a link to download the Visual Studio Addin.
Direct link: http://your.teamcity.server/update/vsAddinInstallerv4.msi
A: This is what worked for me:
wget https://download.jetbrains.com/resharper/JetBrains.ReSharperUltimate.LightInstaller.exe
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Find string in another string using python Lets say that you have an email address xxx@yyy.com and you want to create something like this in python:
email = 'mystuff@yyy.com'
try:
if "@yyy.com":
#do something
if "@zzz.com":
#do something else
except:
#do something
How would I do this?
A: email_addr = "foo@yyy.com"
if email_addr.endswith("@yyy.com"):
# do something
elif email_addr.endswith("@zzz.com"):
# do something else
# or...
if "@yyy.com" in email_addr:
# do something
elif "@zzz.com" in email_addr:
# do something else
A: email = "xxx@yyy.com"
if "@yyy.com" in email:
#do something
if "@zzz.com" in email:
#do something else
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create a self resizing grid of buttons in tkinter? I am trying to create a grid of buttons(in order to achieve the clickable cell effect) with Tkinter.
My main problem is that I cannot make the grid and the buttons autoresize and fit the parent window.
For example, when I have a high number of buttons on the grid, instead of shrinking the buttons so that the grid fits inside the window, I get a stretched frame that goes off screen.
The effect that I am looking for is the grid filling all available space, then resizing its cells to fit within that space. I have read at the documentation, but I still cannot figure out how to make it work.
This is the basic code which is my starting point:
def __init__(self):
root = Tk()
frame = Frame(root)
frame.grid()
#some widgets get added in the first 6 rows of the frame's grid
#initialize grid
grid = Frame(frame)
grid.grid(sticky=N+S+E+W, column=0, row=7, columnspan=2)
#example values
for x in range(60):
for y in range(30):
btn = Button(grid)
btn.grid(column=x, row=y)
root.mainloop()
A: You need to configure the rows and columns to have a non-zero weight so that they will take up the extra space:
grid.columnconfigure(tuple(range(60)), weight=1)
grid.rowconfigure(tuple(range(30)), weight=1)
You also need to configure your buttons so that they will expand to fill the cell:
btn.grid(column=x, row=y, sticky="news")
This has to be done all the way up, so here is a full example:
from tkinter import *
root = Tk()
frame = Frame(root)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
frame.grid(row=0, column=0, sticky="news")
grid = Frame(frame)
grid.grid(sticky="news", column=0, row=7, columnspan=2)
frame.rowconfigure(7, weight=1)
frame.columnconfigure(0, weight=1)
#example values
for x in range(10):
for y in range(5):
btn = Button(frame)
btn.grid(column=x, row=y, sticky="news")
frame.columnconfigure(tuple(range(10)), weight=1)
frame.rowconfigure(tuple(range(5)), weight=1)
root.mainloop()
A: @Vaughn Cato gave an excellent answer here. However, he has accidentally included a bunch of extraneous code in his example. Here is a cleaned up and more organized full example doing exactly what his example does.
from tkinter import *
#Create & Configure root
root = Tk()
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
#Create & Configure frame
frame=Frame(root)
frame.grid(row=0, column=0, sticky=N+S+E+W)
#Create a 5x10 (rows x columns) grid of buttons inside the frame
for row_index in range(5):
Grid.rowconfigure(frame, row_index, weight=1)
for col_index in range(10):
Grid.columnconfigure(frame, col_index, weight=1)
btn = Button(frame) #create a button inside frame
btn.grid(row=row_index, column=col_index, sticky=N+S+E+W)
root.mainloop()
Screenshots:
When it first opens (small):
After you maximize the window:
A: To make the buttons expand when the window is maximized, try to modify the button.grid entry as follows:
btn.grid(column=x, row=y, sticky=N+S+E+W)
A: The grid weight method might not work when you use scrollbar (at least in Mac) , so while using it pack the widget and scrollbar inside a frame and then grid the frame instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "61"
}
|
Q: Create an xtable of a data.frame containing logical values I want to use xtable to display a simple data frame containing two vectors with logical values:
ia = c(TRUE, TRUE, FALSE)
ib = c(FALSE, TRUE, TRUE)
i.df = data.frame(ia, ib)
xtable(i.df)
This produces:
\begin{table}[ht]
\begin{center}
\begin{tabular}{rll}
\hline
& ia & ib \\
\hline
1 & c(TRUE, TRUE, FALSE) & c(FALSE, TRUE, TRUE) \\
2 & c(FALSE, TRUE, TRUE) & c(TRUE, TRUE, FALSE) \\
3 & c(TRUE, TRUE, FALSE) & c(FALSE, TRUE, TRUE) \\
\hline
\end{tabular}
\end{center}
\end{table}
However, I would have expected:
\begin{table}[ht]
\begin{center}
\begin{tabular}{rll}
\hline
& ia & ib \\
\hline
1 & TRUE & FALSE \\
2 & TRUE & TRUE \\
3 & FALSE & FALSE \\
\hline
\end{tabular}
\end{center}
\end{table}
For some reason xtable prints the full logical vectors in each line, instead of printing only one element per line. Does this make sense to anybody or am I overlooking something blatantly obvious?
A: This feels like a bug to me. The relevant lines in xtable.data.frame are:
logicals <- unlist(lapply(x, is.logical))
x[, logicals] <- as.character(x[, logicals])
That isn't how I'd do that coercion to character. I'd probably do something more like:
x[,logicals] <- lapply(x[,logicals],as.character)
I would consider contacting the package author. In the mean time, you can try converting the logical columns to characters beforehand, yourself, as this will likely fix the problem in the meantime.
EDIT
Roman's comment below alerted me to the fact that my suggested fix won't work if there is only one logical column, since the dimensions are dropped by default. It should have been:
x[,logicals] <- lapply(x[,logicals,drop = FALSE],as.character)
I have contacted the package maintainer about this (2012-04-22).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Facebook Canvas url using routes.rb I'd like my FB canvas app
apps.facebook.com/coolapp
to behave the same as my web app
coolapp.com
I've set up the canvas url in facebook developer page
http://coolapp.com/canvas/
Using Rails 3.1, I'd like to know how I can easily route the /canvas into my app so that going to the first url above does not route outside of the facebook canvas page (and all the resources work as expected).
A: Copying the answer from the comments in order to remove this question from the "Unanswered" filter:
stackoverflow.com/a/18028579/156561 i link to how to do all this (2 yrs later) in this question.
~ answer per pjammer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I refresh a databound dropdown list without refreshing the whole page? I've created a insert and update form for a PRODUCTS table using PHP and MySQL.
Each form contains a, databound, SELECT field that queries a COMPANIES table to populate.
The record ID, of each company, is used in the PRODUCTS table to group products by company.
I need to find a way to allow users to add new companies while adding products.
I want the user to be able to select 'Add New' from the dropdown and trigger a lightbox containing the 'Add company' form. They would add the their company name submit that form and the lightbox would close. That would trigger a refresh of the COMPANIES dropdown and select the passed value.
That's how I see it. Not sure if it's the best UX but I need some help. I kneed to know:
1. how to trigger the lightbox from an OPTION in the SELECT field.
2. how to place the Add Companies form in the lightbox.
3. how to refresh the COMPANIES SELECT field, on the original form, with the new value. While retaining any previously entered values in other fields.
Any suggestions are greatly appreciated.
Cheers
Doug
A: Pseuo-code:
*
*Load up your companies list (as you do)
*Bind to the "change" event on the company drop down (same as you do with updating products based on the selected company). When the select's value equals your "Add new company" value, trigger the light box.
*Light box form would use an AJAX call to a script (in the background) that would add the new company (I would also implement some error checking/validation).
*When a successful response comes back from AJAX, add the new company to the select list, select it, and then the value change should re-trigger your product drop-down to switch.
All-in-all, it should be pretty simple.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Skip before filter with Active Admin I am using devise and recently added active admin, which created a separate table of admin_users to keep admins.
All works fine with Active Admin when I try to log in and browse around. However, my application controller has this for general users:
before_filter :authenticate_user!, :except => [:show, :index]
Because of this, when inside the active admin interface, whenever I try to edit or delete anything, it asks me to log in. I learned that a skip_before_filter can be used inside the controller in which the before_filter needs to be excluded, however Active Admin doesn't have a controller file in the controllers folder or anywhere in my project I could look.
can anyone suggest how to make active admin ignore the application beofre_filter which I want to apply on all of the client/user facing?
A: In config/initializers/active_admin.rb you can add the following:
config.skip_before_action :authenticate_user!
You can also use the DSL provided to modify the ActiveAdmin controller: http://activeadmin.info/docs/8-custom-actions.html#modify_the_controller
Note: For Rails versions before 5.0 you will want to use skip_before_filter.
A: I couldn't get @coreyward's solution to work, but editing config/application.rb as per this Devise post and adding:
ActiveAdmin.register_page "Dashboard" do
controller do
skip_before_action :name_of_filter_to_skip
end
# Other code
end
to admin/dashboard.rb did the trick. It didn't work by just editing config/application.rb alone. Make sure to restart your server!
A: both of the corey and Sooie are right... but only partially, to stop your blanket authorize_user! filter from affecting active_admin you need to implement both of their answers...
config/initializers/active_admin.rb
config.skip_before_filter :authorize_user!
app/admin/dashboard.rb
controller do
skip_before_filter :authorize_user!
end
A: I couldn't make the solutions of @fringd and @coreyward to work on Rails4 (using ActiveAdmin master branch).
So, I've moved the filter methods (I have two filters: authorize_user! and check_user_status) to a new Concern, and included this created module into the Controllers which had those filters (except for the ApplicationController, which should remain clean).
Then restarted the server, and problem solved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Hidden Markov Models inplementation in R or python Do you know any good literature and/or tutorials about how to implement HMM in python, R (Bioconductor)? (especially for sequence analysis)
A: There is the HMM package on CRAN, which might be a good place to start.
http://cran.at.r-project.org/web/packages/HMM/index.html
This is easily found from R itself:
RSiteSearch("HMM")
A: GHMM for python has a tutorial, but it's short and they admit that "Currently, the GHMM is utterly lacking in documentation."
I like the Rabiner paper.
I have a technical report on the use of HMM for genetic mapping.
I recommend reading a bit of Rabiner and then implementing something. The forward/backward equations are just a few lines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Garbage Collection in Flash Player I build a simple Flex view state based video application on Flash Builder 4.5. There are 4 states. Everytime I go from State1->State2->State3 or State1->State2->State4, the memory in internet explorer increases, but is not released. What am I not deallocating?
Do i have to manually deallocate every single element and its event listeners for each state?
I have version Flash Player 10,2,153,1 installed.
Source Code download is here if you want to build the app and run.
here's the core code:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width.State1="1024" height.State1="768"
width.State2="1024" height.State2="768"
width.State3="1024" height.State3="768"
width.State4="1024" height.State4="768">
<fx:Script>
<![CDATA[
protected function button1_clickHandler(event:MouseEvent):void
{
// TODO Auto-generated method stub
currentState='State2';
}
protected function button2_clickHandler(event:MouseEvent):void
{
// TODO Auto-generated method stub
currentState='State3';
}
protected function button3_clickHandler(event:MouseEvent):void
{
// TODO Auto-generated method stub
currentState='State1';
}
protected function button4_clickHandler(event:MouseEvent):void
{
// TODO Auto-generated method stub
currentState='State2';
}
protected function button5_clickHandler(event:MouseEvent):void
{
// TODO Auto-generated method stub
currentState='State4';
}
]]>
</fx:Script>
<s:states>
<s:State name="State1" />
<s:State name="State2"/>
<s:State name="State3"/>
<s:State name="State4"/>
</s:states>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Button includeIn="State1" x="405" y="175" width="227" height="73" label="Music List"
click="button1_clickHandler(event)" fontSize="30" itemDestructionPolicy="auto" />
<s:Label includeIn="State1" x="440" y="61" fontSize="30" text="Main State" itemDestructionPolicy="auto"/>
<s:Label includeIn="State2" x="409" y="34" fontSize="30" text="Classical Video" itemDestructionPolicy="auto"/>
<s:Button includeIn="State2" x="328" y="151" width="369" height="91"
label="Beethoven - "Für Elise"" click="button2_clickHandler(event)"
fontSize="30"
itemDestructionPolicy="auto"
/>
<s:VideoPlayer includeIn="State3,State4" x="0" y="67" width="1024" height="530" autoPlay="false"
loop="true" scaleMode="stretch" source="assets/Beethoven__Für_Elise.mp4"
source.State4="assets/FOUR_SEASONS_VIVALDI_LANDSCAPES_AND_MUSIC.mp4"
itemDestructionPolicy="auto"
/>
<s:Button includeIn="State3,State4" x="2" y="14" width="240" height="45" label="Return to Main"
click="button3_clickHandler(event)" fontSize="30"
itemDestructionPolicy="auto"
/>
<s:Button includeIn="State3,State4" x="338" y="629" width="348" height="63" label="Return to classical"
click="button4_clickHandler(event)" fontSize="30"
itemDestructionPolicy="auto"
/>
<s:Button includeIn="State2" x="326" y="287" width="371" height="81"
label="Vivaldi – “Four Seasons”" click="button5_clickHandler(event)" fontSize="30"
itemDestructionPolicy="auto"
/>
</s:Application>
View from the detecting loitering objects(http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5510654d812e4d126514-8000.html#WS6f97d7caa66ef6eb1e63e3d11b6c4d0d21-7ee8) is here
View from the object references(http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5510654d812e4d126514-8000.html#WS6f97d7caa66ef6eb1e63e3d11b6c4d0d21-7eef) from the topmost Object in the 'loitering objects view' is here
I checked the documentation for "Controlling caching of objects created in a view state" and set the itemDestructionPolicy="auto". It still is caching the objects and memory is not being released as seen in the Task Manager.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there any complete guide to the building and installation of ITK 4.0? I want to use the python bindings with the ITK 4.0. Is there any complete guide that how to build and install and correctly set the options for the wrappers? I am using Linux 11.04.
Thanks a lot.
A: http://www.itk.org/Wiki/ITK_Release_4/Wrapping/WrapITK_Installation
A: Sept, 30, 2011 : WARNING ITKv4 is still in beta and is under VERY active development. Please do not take the current state of documentation as reflective of the process that will be available in the final version.
A: Did you have a look in this one? --> http://www.itk.org/Doxygen/html/index.html
A: I've just written a concise tutorial on this:
https://pythonhosted.org/MedPy/installation/itkwrapper4.7.html
A: Perhaps this link answers the question?
https://itk.org/Wiki/ITK/Release_4/Wrapping/BuildProcess
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to properly use the each() in jQuery? I have the following:
<div class="io-section-header">
<ul>
<li class="advanced">Eat</li>
<li class="advanced">Sleep</li>
<li class="advanced">Be merry</li>
</ul>
</div>
I have the jQuery (which is tied to a click() handler:
$('io-section-header').each(function() {
$("li").siblings(".advanced").toggle('fast',function(){});
});
Why aren't the list items toggling?
A: You just need to add a dot before your class selector.
$('.io-section-header').each(function() {
$("li").siblings(".advanced").toggle('fast',function(){});
});
jsFiddle
A: I dont think you actually need the each() statement for what you are trying to do. This should work fine.
$('.io-section-header li').siblings(".advanced").toggle('fast');
here is a fiddle http://jsfiddle.net/8kpcn/1/
In fact this will do the same thing as well
$('.io-section-header li.advanced').toggle('fast');
http://jsfiddle.net/8kpcn/2/
A: The callback function needs some parameters.
$('.io-section-header').each(function(index, Element) {
//Do whatever you need to do with each of them here.
//The current element in this iteration is in `Element`
});
A: Try this:
$('.io-section-header li').each(function() {
$(this).siblings(".advanced").toggle('fast');
});
jsFiddle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Fast Image Downscaling in C/C++ I'm looking for fast C/C++ libraries to perform fast downscaling using mainly linear and cubic interpolation. Are FreeImage and/or FFMPEG libswscale good alternatives. Any more suggestions?
A: Have you looked at imagemagick? http://www.imagemagick.org/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to check for Duplicates when Importing Excel Sheet into MySQL table using vb.net I have a upload excel file on my web application. When the file is uploaded it is supposed to be openned and then import the data into a mysql table. It works fine in that it adds the information just fine. However there is a problem the code I cannot get the duplicate checking to work correctly.. Part of this is because the excel sheet that will be used does not have any column that I can use as a unique identifier. Several times in the excel sheet the information is completely identical across the entire row with only differences in one or two columns... I was thinking I could do something like:
Select * FROM table_name WHERE table_col_1 = variable and table_col_2 = variable 2 and etc...
I am thinking by doing this I could compare the values of every column in the row to the import value and if its the same it would skip it... However I cant quite get my head around it... Maybe I am thinking into it to deep and there is a simple way to do this. Below is the function that i am using:
Private Function PerFormUpdate(ByVal customer As String, ByVal bill_to As String, ByVal Contact As String, ByVal Company As String, ByVal firstName As String, ByVal mi As String, ByVal lastname As String, ByVal phone As String, ByVal altPhone As String, ByVal fax As String)
Dim _db As New schoolEntities
Dim command As MySqlCommand = _dbconn.CreateCommand()
command.Parameters.AddWithValue("@Customer", customer)
command.Parameters.AddWithValue("@Bill_to", bill_to)
command.Parameters.AddWithValue("@Contact", Contact)
command.Parameters.AddWithValue("@Company", Company)
command.Parameters.AddWithValue("@First_Name", firstName)
command.Parameters.AddWithValue("@M_I", mi)
command.Parameters.AddWithValue("@Last_Name", lastname)
command.Parameters.AddWithValue("@Phone", phone)
command.Parameters.AddWithValue("@Alt_Phone", altPhone)
command.Parameters.AddWithValue("@Fax", fax)
command.CommandText = "SELECT * FROM quickbooks_imports WHERE Customer=@Customer, Bill_to=@Bill_to, Contact=@Contact, Company =@Company, First_Name=@First_Name, M_I=@M_I, Last_Name=@Last_Name, Phone =@Phone, Alt_Phone=@Alt_Phone, Fax=@Fax"
_dbconn.Open()
Dim _mysqlReader As MySqlDataReader = command.ExecuteReader()
_dbconn.Close()
If Not _mysqlReader.HasRows Then
Dim _UpdateItem As New quickbooks_imports
Dim updateCommand As MySqlCommand = _dbconn.CreateCommand()
_UpdateItem.Customer = customer
_UpdateItem.Bill_to = bill_to
_UpdateItem.Contact = Contact
_UpdateItem.Company = Company
_UpdateItem.First_Name = firstName
_UpdateItem.M_I = mi
_UpdateItem.Last_Name = lastname
_UpdateItem.Phone = phone
_UpdateItem.Alt_Phone = altPhone
_UpdateItem.Fax = fax
updateCommand.CommandText = "INSERT INTO quickbooks_imports (Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES (@Customer, @Bill_to, @Contact, @Company, @First_Name, @M_I, @Last_Name, @Phone, @Alt_Phone, @Fax)"
updateCommand.Parameters.AddWithValue("@Customer", _UpdateItem.Customer)
updateCommand.Parameters.AddWithValue("@Bill_to", _UpdateItem.Bill_to)
updateCommand.Parameters.AddWithValue("@Contact", _UpdateItem.Contact)
updateCommand.Parameters.AddWithValue("@Company", _UpdateItem.Company)
updateCommand.Parameters.AddWithValue("@First_Name", _UpdateItem.First_Name)
updateCommand.Parameters.AddWithValue("@M_I", _UpdateItem.M_I)
updateCommand.Parameters.AddWithValue("@Last_Name", _UpdateItem.Last_Name)
updateCommand.Parameters.AddWithValue("@Phone", _UpdateItem.Phone)
updateCommand.Parameters.AddWithValue("@Alt_Phone", _UpdateItem.Alt_Phone)
updateCommand.Parameters.AddWithValue("@Fax", _UpdateItem.Fax)
'updateCommand.CommandText = "INSERT INTO EXCEL (id,Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES ('" & _UpdateItem.id & "','" & _UpdateItem.Customer & "','" & _UpdateItem.Bill_to & "','" & _UpdateItem.Contact & "','" & _UpdateItem.Company & "','" & _UpdateItem.First_Name & "','" & _UpdateItem.M_I & "','" & _UpdateItem.Last_Name & "','" & _UpdateItem.Phone & "','" & _UpdateItem.Alt_Phone & "','" & _UpdateItem.Fax & "') ON DUPLICATE KEY UPDATE Customer= '" & _UpdateItem.Customer & "' Bill_to= '" & _UpdateItem.Bill_to & "' Contact= '" & _UpdateItem.Contact & "' Company= '" & _UpdateItem.Company & "' First_Name= '" & _UpdateItem.First_Name & "' M_I= '" & _UpdateItem.M_I & "' Last_Name= '" & _UpdateItem.Last_Name & "' Phone= '" & _UpdateItem.Phone & "' Alt_Phone= '" & _UpdateItem.Alt_Phone & "' Fax= '" & _UpdateItem.Fax & "'"
'updateCommand.CommandText = "INSERT INTO quickbooks_imports (Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES ('" & _UpdateItem.Customer & "','" & _UpdateItem.Bill_to & "','" & _UpdateItem.Contact & "','" & _UpdateItem.Company & "','" & _UpdateItem.First_Name & "','" & _UpdateItem.M_I & "','" & _UpdateItem.Last_Name & "','" & _UpdateItem.Phone & "','" & _UpdateItem.Alt_Phone & "','" & _UpdateItem.Fax & "') "
_dbconn.Open()
Try
updateCommand.ExecuteNonQuery()
Catch ex As Exception
Dim _error As String = Nothing
MsgBox(ex.Message)
End Try
_db.SaveChanges()
Else
Dim _NewItem As New quickbooks_imports
_NewItem.Customer = customer
_NewItem.Bill_to = bill_to
_NewItem.Contact = Contact
_NewItem.Company = Company
_NewItem.First_Name = firstName
_NewItem.M_I = mi
_NewItem.Last_Name = lastname
_NewItem.Phone = phone
_NewItem.Alt_Phone = altPhone
_NewItem.Fax = fax
_db.quickbooks_imports.AddObject(_NewItem)
_db.SaveChanges()
End If
_dbconn.Close()
Return View()
End Function
Any help would be greatly appreciated...
A: declare @tempExist varchar(50);
set @tempExist=null;
select @tempExist=[ColumnName1] from [TableName]
where [ColumnName1]=@ColumnName1 or [ColumnName2]= @ColumnName2 and so on..
if(@tempExist!=NULL)
Begin
Insert into [TableName] (...)
End
The above code is for mssql.. and some syntax might be wrong.. but that's what I think of..
But this might give u a hint.. good luck!!
A: Try to insert data from the excel into another (maybe temporary table), then copy data you need from additional table to the target table, e.g. -
INSERT INTO table1 SELECT DISTINCT * FROM temp_table;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fading the start of a sound with Python I'm a student in a programming class and I just can't get this fading in to work... Right now it's just muting the first few samples of length fade_length... can anyone tell me why it does so so I can find out a way to fix it?
<code erased>
Help without direct answers would be great. Thank you
A: If you're using Python 2.x, try
factor = 1.0 * index / fade_length
An int divided by a larger int is 0. You have to coerce the operation to floating point division.
Edit:
You can also use from __future__ import division to make the division operator use true division like Python 3. Use '//' for floor division.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails 3.0 to 3.1 Javascript error I am trying to learn to use Javascript in Rails and am following a Tutorial at http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/
Even though the tutorial is written for 3.0, since Rails 3.1 is out I am using it and running into an error. Following the lesson to the "AJAX form submission" part where it builds a js.erb file with the following content;
$('body').html("<h1><%= escape_javaScript(@post.title) %></h1>").append("<%= escape_javaScript(@post.content) %>");
I am getting the following error in the server log;
ActionView::Template::Error (undefined method `escape_javaScript' for #<#<Class:0x00000100917048>:0x0000010084b0d8>):
1: $('body').html("<h1><%= escape_javaScript(@post.title) %></h1>").append("<%=escape_javaScript(@post.content) %>");
Is this a 3.0 to 3.1 conversion problem? Can someone point me in the right direction?
Thanks!
A: The method you're looking for is escape_javascript (lower case "s"):
$('body').html("<h1><%= escape_javascript(@post.title) %></h1>").append("<%= escape_javascript(@post.content) %>");
Ruby is case sensitive and generally uses lower case words separated by underscores for method names.
The comments for the tutorial might be worth a read:
http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/comment-page-1/#comment-322477
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Creating 3 Perfectly Equal Columns that take up 100% on the Browser Window Width I have 3 square images of the same size that are floating next to each other. I want the three images, in total, to take up the full 100% of the browser window width, with no gaps. Giving each image a width of 33.33333333% works in Firefox, but does not work in most other browsers at certain widths, which can sometimes leave a small gap to the right of the 3rd image.
This may be a problem with many solutions, but nothing I've tried so far works reliably.
A: For those that come here now (oct 2015) you can use calc:
width:calc(100% / 3);
This will give you exactly 100% when added up. There are some browserbugs but you can use it without many issues: http://caniuse.com/#feat=calc
A: Try this:
HTML
<div class="container">
<div class="column">
<img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" />
</div>
<div class="column">
<img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" />
</div>
<div class="column">
<img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" />
</div>
</div>
CSS
html, body {
margin:0;
padding:0;
width:100%;
height:100%;
}
.container {
width:100%;
}
.column {
width:33.33333333%;
float:left;
}
.column img {
width:100%;
height:auto;
}
Demo
http://jsfiddle.net/andresilich/2p8uk/
Single page demo
http://fiddle.jshell.net/andresilich/2p8uk/show/
CSS3 demo
html, body {
margin:0;
padding:0;
width:100%;
height:100%;
}
.container {
display:-moz-box;
display:-webkit-box;
display:box;
-moz-box-orient:horizontal;
-webkit-box-orient:horizontal;
box-orient:horizontal;
width:100%;
}
.column {
-moz-box-flex:1;
-webkit-box-flex:1;
box-flex:1;
background-color:#ddd;
}
.column img {
width:100%;
height:auto;
}
Demo
http://jsfiddle.net/andresilich/2p8uk/2/
Single page demo
http://fiddle.jshell.net/andresilich/2p8uk/2/show/
Update: (safari, sorta, fix)
Safari does not equate 33.33% to 100% like other browsers, you can either use my CSS3 demo, which does the sizing automatically through CSS, or you can encase everything inside a container with a 101% width and just hide that extra 1% with overflow:hidden; off of the third image. Try this:
<div class="container">
<div class="inner">
<div class="column">
<img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" />
</div>
<div class="column">
<img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" />
</div>
<div class="column">
<img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" />
</div>
</div>
</div>
html, body {
margin:0;
padding:0;
width:100%;
height:100%;
}
.container {
width:100%;
}
.inner {
width:101%;
overflow:hidden;
}
.column {
width:33.33333333%;
float:left;
}
.column img {
width:100%;
height:auto;
}
Demo: http://fiddle.jshell.net/andresilich/2p8uk/4/
A: Have you tried something like this...
html, body{
margin:0;
padding:0;
}
div{
float:left;
height:100px;
width:33.33%;
background:red;
margin:0;
padding:0;
}
Example: http://jsfiddle.net/jasongennaro/jQA2Z/
EDIT
To get rid of that very small space at the right, wrap the divs and use a background-color or background-image to compensate.
div#wrapper{
height:100px;
background:red;
}
Example 2: http://jsfiddle.net/jasongennaro/jQA2Z/1/
A: Without Javascript 33.33% is going to always give you <100% total when added up.
What about 3.5%. Can you afford to lose a pixel or two from the right?
Or put a solid background behind (guessing your answer to this one will be no - but possible)
A: My work around for this problem has always been as follows:
*
*Wrap the 3 columns in a row
*Have the first 2 columns occupy 33.333333% of the width
*Finally, select your last column using the last-child filter and apportion a width of 33.333334% (Note that you can apportion the 33.333334% to any of the columns - the first one using first-child filter or second one using the nth-child filter)
Here's the HTML/CSS code
.row {
width: 100%;
}
.row .cols {
width: 33.333333%;
height: 150px;
float: left;
}
.row .cols:last-child {
width: 33.333334%;
}
<div class="row">
<div class="cols">lorem</div>
<div class="cols">lorem</div>
<div class="cols">lorem</div>
</div>
<div class="row">
<div class="cols">lorem</div>
<div class="cols">lorem</div>
<div class="cols">lorem</div>
</div>
A: I'm not sure any of the above answers are correct, even two years later. This is what I always use to achieve three columns. It requires a couple unique classes, but there is no extra pixels or percentages needed.
HTML:
<div id="column-wrapper">
<div class="column left">
</div>
<div class="column mid">
</div>
<div class="column right">
</div>
<div style="clear:both;"></div>
</div>
CSS:
#column-wrapper {
width: 1000px;
}
.column {
width: 320px;
float: left;
}
.column.mid {
margin: 0px 20px;
}
This is specifically for a 1000px wide layout, but you can change the math to any layout needed. They key is to make the width of each column a number that when subtracted from the entire width of the div, the resulting number is equally divisible by 2.
For instance, if you wanted to do a 800px wide layout, your columns could be, say, 250px. That means that all three columns added together equal 750px, leaving you with 50px of total space left. So divide 50px by 2 and you get 25px, which is then what you put for your left and right margins on the center column.
Hopefully that makes sense, IMO it is the best and more simple way to achieve three equal columns with pure CSS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: New to Objective-C. Trying to pass arguments through a void function, guessing I can't do that? I am new to Objective C. I am trying to write a void function in my implementation file with arguments however xcode doesn't like that. I did some research and it appears I can't do that.
This is what I am trying to do basically:
-(void)findMilesLeft(float x, float y)
{
float gallons = x;
float miles = y;
}
I would be calling this findMilesLeft within another void function- I believe I would call it as:
-(void)changeSUV
{
[self findMilesLeft(20, 100)];
}
Obviously I have tried this syntax and it didn’t work for me… is there some way I can execute this correctly?
The calculations arent in here obviously but I think the idea is clear.
Thanks,
John
A: The correct syntax is:
-(void)findMilesLeftWithX:(float)x andY:(float)y
{
float gallons = x;
float miles = y;
}
And then you call it like that:
-(void)changeSUV
{
[self findMilesLeftWithX:20 andY:100];
}
If you didn't do it yet, you should probably read this document :):
Introduction to Objective-C
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I get my "radio" buttons to show up on my email? I have a form that I have been working on and I've been having problems only with the radio buttons not showing up on the emails I receive. I have tried everything to get the right code but I am not sure what to do...PLEASE HELP!
here is my code for the visual .php:
<p style="color: #e40001;">* Denotes required field.</p>
<p><strong>General Information:</strong></p>
<form method="post" name="commentForm" action="sendmail.php">
<p>Your Name: <font size="2" color="#e40001">*</font>
<input type="text" name="name" value="" size="20" class="required" />
</p>
<br />
<p>Your Title:
<input type="text" name="title" value="" size="20" />
</p>
<p>Company: <font size="2" color="#e40001">*</font>
<input type="text" name="company" value="" size="20" class="required" />
</p>
<p>Email: <font size="2" color="#e40001">*</font>
<input type="text" name="email" value="" size="20" class="required" />
</p>
<p>Website:
<input type="text" name="website" value="" size="20" />
</p>
<p>Address:
<input type="text" name="address" value="" size="20" />
</p>
<p>City:
<input type="text" name="city" value="" size="20" />
</p>
<p>State/Provice: <font size="2" color="#e40001">*</font>
<input type="text" name="State" value="" size="20" class="required" />
</p>
<p>Zip Code: <font size="2" color="#e40001">*</font>
<input type="text" name="zip" value="" size="20" class="required" />
</p>
<p>Phone: <font size="2" color="#e40001">*</font>
<input type="text" name="phone" value="" size="20" class="required" />
</p>
<p>Fax:
<input type="text" name="fax" value="" size="20" />
</p><br /><br />
<p><strong>Professional Information:</strong></p>
<p>Type of business?
<SELECT name="operation"><option>--Select Operation--
<option>---------------------
<OPTION value=cafe/bar>Café/coffee bar
<OPTION value=restaurant>Restaurant/Bar
<OPTION value=kiosk>Kiosk
<OPTION value=hotel>Hotel/Motel
<OPTION value=university>University
<OPTION value=hospital>Hospital
<OPTION value=grocer/market>Grocer/Market
<OPTION value=other>Other
</select></p>
<p>If other, please desribe:
<input type="text" name="other" value="" size="20" />
</p><br /><br />
<p>Is this a new business?
<input type="radio" name="newsletter-yes" id="radio" value="No" title="Check No if you would not like our newsletter" />New
<input type="radio" name="newsletter-no" id="radio2" value="Yes" title="Check Yes if you would like our newsletter" />Existing</p>
<p>I am interested in learning more about the following equipment:<br />
<input type="radio" name="equipment" id="radio" value="BUNN Commercial Brewing & Gridning Equipment">BUNN Commercial Brewing & Gridning Equipment <br />
<input type="radio" name="equipment" id="radio" value="La Marzocco Traditional Espresso Machines">La Marzocco Traditional Espresso Machines<br />
<input type="radio" name="equipment" id="radio" value="Rancilio Traditional Espresso Machines">Rancilio Traditional Espresso Machines <br />
<input type="radio" name="equipment" id="radio" value="Egro Superautomatic Espresso Machines">Egro Superautomatic Espresso Machines <br />
<input type="radio" name="equipment" id="radio" value="Mazzer/Swift Espresso Grinders/Dosers">Mazzer/Swift Espresso Grinders/Dosers<br />
<input type="radio" name="equipment" id="radio" value="Blendtec Blenders">Blendtec Blenders <br />
</p>
<p>I am interested in learning more about the following products:<br />
<input type="radio" name="products" id="radio1" value="" title="" />Espressions Coffees/Teas<br />
<input type="radio" name="products" id="radio1" value="" title="" />Monin All-Natural Syrups, Sauces & Frappes <br />
<input type="radio" name="products" id="radio1" value="" title="" />Big Train Frozen Drink Bases<br />
<input type="radio" name="products" id="radio1" value="" title="" />Pacific Natural Foods Soy/Vanilla Soy, Smoothie Bases, Almond Milk<br />
<input type="radio" name="products" id="radio1" value="" title="" />Two Leaves and a Bud Tea Sachets<br />
<input type="radio" name="products" id="radio1" value="" title="" />Umpqua Oats<br />
</p>
<p>I am interested in learning more about your barista training program:
<input type="radio" name="barista training no" id="radio" value="No" title="Check No if you are not interested" />No
<input type="radio" name="barista training yes" id="radio2" value="Yes" title="Check Yes if you are interested" />Yes</p>
<p>Questions/ Comments:
<input type="text" name="other2" value="" size="40" />
</p>
<p><input type="submit" value="Send" />
<input type="reset" value="Reset" /></p>
</form><br /><br />
Here is my code for sendmail.php:
// values from POST data
$name = $_POST['name'];
$title = $_POST['title'];
$company = $_POST['company'];
$email = $_POST['email'];
$website = $_POST['website'];
$address = $_POST['address'];
$city = $_POST['city'];
$State = $_POST['State'];
$zip = $_POST['zip'];
$equipment = $_POST['equipment'];
$products = $_POST['products'];
$phone = $_POST['phone'];
$fax = $_POST['fax'];
$operation = $_POST['operation'];
$other = $_POST['other'];
$newsletter = $_POST['newsletter'];
$click1 = $_POST['click1'];
$click2 = $_POST['click2'];
$click3 = $_POST['click3'];
$click4 = $_POST['click4'];
$click5 = $_POST['click5'];
$click6 = $_POST['click6'];
$push1 = $_POST['push1'];
$push2 = $_POST['push2'];
$push3 = $_POST['push3'];
$push4 = $_POST['push4'];
$push5 = $_POST['push5'];
$push6 = $_POST['push6'];
// subject
$subject = 'Espressions Coffee Roastery Contact Form';
// message
$message = '
<html>
<head>
<title>Espressions Coffee Roastery Contact Form</title>
</head>
<body>
<p>Name: '.$name.'</p>
<p>Title: '.$title.'</p>
<p>Company: '.$company.'</p>
<p>Email: '.$email.'</p>
<p>Website: '.$website.'</p>
<p>Address: '.$address.'</p>
<p>city: '.$city.'</p>
<p>State: '.$State.'</p>
<p>Zip Code: '.$zip.'</p>
<p>Phone: '.$phone.'</p>
<p>Fax: '.$fax.'</p>
<p>Operation: '.$operation.'</p>
<p>Other: '.$other.'</p>
<p>Newsletter: '.$newsletter.'</p>
<p>questions: '.$other2.'</p>
<p>BUNN Commercial: '.$click1.'</p>
<p>La Marzocco: '.$click1.'</p>
<p>Ranchilio Traditional: '.$click1.'</p>
<p>Egro Superautomatic: '.$click1.'</p>
<p>Mazzer/ Swift Espresso: '.$click1.'</p>
<p>Blendtec Blenders: '.$click1.'</p>
<p>Espressions: '.$push1.'</p>
<p>Monin All-Natural: '.$push1.'</p>
<p>Big Train Frozen Drink: '.$push1.'</p>
<p>Pacific Natural Foods: '.$push1.'</p>
<p>Two Leaves and a Bud: '.$push1.'</p>
<p>interested in products: '.$radio.'</p>
<p>interested in services: '.$radio1.'</p>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Espressions Coffee Roastery <max@estudioray.com>' . "\r\n";
$headers .= 'From: Espressions Coffee Roastery Contact Form <max@estudioray.com>' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
A: Think the problem is here:
<p>interested in products: '.$radio.'</p>
<p>interested in services: '.$radio1.'</p>
It should be:
<p>interested in products: '.$products.'</p>
<p>interested in services: '.$equipment.'</p>
You've used the id attribute of the radio element and not the name attribute in your email code when you should just use what you have set it to at the top of your sendmail.php script which is $products and $equipment.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: work around stack overflow error when going through recursive function 300+ times in groovy? I have the following code, trying to find the first number of the Fibonacci sequence with over 1000 digits:
z = 0g
def fib
fib = {a,b->
if(a <= 10g**1000){
z++
fib(b.toBigInteger(), (a+b).toBigInteger())
}else{
return z
}
}
fib(1,2)
This function works when I change "1000" to ~300 or less, and it computes in well under a half a second.
However, when I raise the variable above that, I get a stack overflow. I saw another question about this and the answer was to use a function called "doall," but I don't see that in Groovy.
I figure the solution is pretty simple at this point, but I don't know where to look for it...
Can anyone help me out?
Thanks so much!
A: If you are using Groovy 1.8, this is what the trampoline() method was designed to handle on Closures.
http://mrhaki.blogspot.com/2011/04/groovy-goodness-recursion-with-closure.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: serverfbml returns 404 on one page and not a clone This case seems unbelievable.
I have two versions of a fbml page to display a list of users to invite. The two pages return identical html. The only difference is that one has a url like http://mydomain/user/myFriends and the other has a url http://mydomain/facebook/myFriends.
One version works great and the other gets stuck returning a 404 when the browser tries to get serverfbml from facebook. This is try in both IE and Firefox.
What's even weirder is that if I use the firefox firebug debugger and click on the url for the get for serverfbml and ask it to load it in a separate tab, I still get the same exact behavior. But I can look at the source loaded by firefox for both pages and see that it is INDENTICAL.
Here's the page's html.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link type="text/css" rel="stylesheet" href="/css/common.css"/>
</head>
<body id="page-facebook" class="facebook page-facebook-showInviteFriends logged-in ">
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/js/common.js"></script>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<fb:serverFbml width="760" height="346" style="width: 760px; height: 346px;">
<script type="text/fbml">
<fb:fbml style="width: 324px; height: 346px;">
<fb:request-form
action=""
method="POST"
invite="true"
type="Sample Name"
content="<fb:req-choice url='' label='Join Now!'></fb:req-choice>
">
<fb:multi-friend-selector
condensed="true"
showborder="true"
actiontext="Invite your friends"
email_invite=false
import_external_friends=false
exclude_ids=""
unselected_rows="10"
selected_rows="3"
/>
<fb:request-form-submit import_external_friends="false" label="null" />
</fb:request-form>
</fb:fbml>
</script>
</fb:serverFbml>
</html>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '130456257111111',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelUrl : 'http://sample.foobar.com/static/html/channel.html'
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<script type="text/javascript" src="/js/facebook.js"></script>
</body>
</html>
A: I figured out the problem. The app is registered with a canvas page of mydomain/facebook. Because the other page has a url that is not under /facebook the call fails. This is really poor error messages from Facebook. Nowhere obvious in the doc does it make it clear that it is a requirement that all content fetched must be under the canvas url pattern.
So I fixed it by changing my official canvas url to be a root path and changing how the default url gets mapped to my app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sql Optimizer for Large Db Table i have table that has millions of rows that i need to join to do selects. the response time is not so good, how can i improve its response? i have tried adding index to the columns i do select by, is there a tool i can use to optimize the sql or how can i diagnose on the bottlenecks of the sql and improve it? any suggestion would be very appreciated.
i am using oracle server 10g and using asp.net as my client.
is there any other kind of indexing helpful on tables with millions of rows?
A: You should probably start with EXPLAIN PLAN.
Use the EXPLAIN PLAN statement to determine the execution plan Oracle
Database follows to execute a specified SQL statement. This statement
inserts a row describing each step of the execution plan into a
specified table. You can also issue the EXPLAIN PLAN statement as part
of the SQL trace facility.
This statement also determines the cost of executing the statement. If
any domain indexes are defined on the table, then user-defined CPU and
I/O costs will also be inserted.
Then edit your question, and post the SQL statement and the output of EXPLAIN PLAN.
Later . . .
I'm not going to be much help to you on that query. 269 lines, at least 29 SELECTs, parallel queries, remote databases, outer joins (old style), and so on.
The best advice I can give you is
*
*get more information from EXPLAIN PLAN, and
*simplify the problem.
The plan table has more columns than are commonly posted. The columns COST, CARDINALITY, BYTES, and TIME might be useful in prioritizing your tuning effort.
You've got 10 full table scans in that query. ("TABLE ACCESS FULL" in the query plan.) That's usually a bad sign; full table scans often take a relatively long time to run. It's not always a bad sign. A full scan of a tiny table might be faster than an index scan.
Start by getting EXPLAIN PLAN output for each of the 29 SELECT statements in your query. If any of them show a full table scan, you can probably improve their performance with suitable indexes. (Oracle supports many different kinds of indexes. Don't overlook opportunities for multi-column indexes.) In any case, EXPLAIN PLAN output will help you identify the slowest of the 29 SELECTs.
A: There are potentially thousands of problems that may exist with this query and plan, only a local expert can truly help you.
But for what it's worth, the first thing I noticed is that only 1/5th of your plan uses parallelism. Normally you want to have all of the steps run in parallel or none of them run in parallel.
If your query only returns a small amount of data the overhead of parallelism probably isn't worth it. It may take a few extra seconds for Oracle to set up the parallel processes, coordinate them, and perform additional steps to optimize the plan (e.g. increase dynamic sampling). A seriel index read would probably work much better than a parallel full table scan. You may need to change the DEGREE of a table, or use a NOPARALLEL hint.
If your query returns a large amount of data you'll probably want to use as many parallel hash joins as possible to efficiently join everything. For really large queries, the worst performance usually occurs when Oracle underestimates the cardinality and uses nested loops and indexes. Look at your cardinality, and find the first part in the plan where the estimate is drastically lower than the actual, that will get you closer to the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to create a master/detail relationship with Telerik and OData? I have an OData WCF ADO.NET service created with Entity Framework using protocol version 2. The entity model looks like this:
I now wish to consume this using a Telerik RadGrid. Here's the markup so far:
<telerik:RadGrid ID="radGrid" runat="server" AutoGenerateColumns="false" Width="100%" Skin="Sitefinity">
<ClientSettings>
<DataBinding Location="http://aadev:8081/measuredata.svc">
<DataService TableName="MeasureTopics"></DataService>
</DataBinding>
</ClientSettings>
<MasterTableView DataKeyNames="MeasureTopicGuid" GroupLoadMode="Client" Name="MeasureTopics">
<Columns>
<telerik:GridBoundColumn DataField="TopicName" />
</Columns>
<DetailTables>
<telerik:GridTableView DataKeyNames="MeasureGuid" runat="server">
<ParentTableRelation>
<telerik:GridRelationFields DetailKeyField="TopicID" MasterKeyField="MeasureTopicGuid" />
</ParentTableRelation>
<Columns>
<telerik:GridBoundColumn DataField="MeasureKeyCode" />
<telerik:GridBoundColumn DataField="MeasureName" />
</Columns>
</telerik:GridTableView>
</DetailTables>
</MasterTableView>
</telerik:RadGrid>
This shows measure topics and a right-arrow to expand into measure definitions, but clicking the arrow does nothing. At least part of the problem is that ParentTableRelation can't work as "TopicID" doesn't exist on the entity. (It's not there because having "MeasureTopic" as a navigation property prevents EF from allowing it to also exist on the entity as a scalar.)
What I'd like to know is, as the relationship is coming through the OData feed as a link...
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/MeasureTopic" type="application/atom+xml;type=entry" title="MeasureTopic" href="MeasureDefinitions(guid'96df6072-a8e4-e011-890d-000c29ba97e5')/MeasureTopic" />
<category term="HealthMeasuresModel.MeasureDefinition" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
<content type="application/xml">
<m:properties>
<d:MeasureGuid m:type="Edm.Guid">96df6072-a8e4-e011-890d-000c29ba97e5</d:MeasureGuid>
<d:MeasureKeyCode>ABC-001</d:MeasureKeyCode>
<d:MeasureName>ABC Register</d:MeasureName>
<d:MeasureDescription>Test</d:MeasureDescription>
</m:properties>
</content>
...how do I configure RadGrid to understand it?
A: Your markup is mostly correct, only GroupLoadMode should be HierarchyLoadMode instead. The former specifies loading of groups, the latter - of hierarchical detail tables.
You also need some javascript, more specifically two RadGrid client events - OnHierarchyExpanding and OnCommand. The approach is demonstrated in this Telerik Blog post.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do you reduce a long query running up mysql resources that requires you to run multiple searches? I want to allow users to subscribe to other users, similar to twitter. So lets say john is subscribed to updates by tom, chris, david and 10 others.
When john checks his news feed, how can I display news from everyone he's subscribed too without running a long query like this:
select * from news where user='tom' and user='chris' and user='david' so on...
Doing it this way can end up resulting in 1 long query and will run up a lot of mysql resources. Looking for the correct method, or any alternatives that are more efficient.
A: You need a separate matching table that has a subscriber_id and a subscribed_id.. index the table on the subscriber_id.
Then you can
Select news.*
From news n
Join subscriptions s
On s.subscribed_id = n.user_id
Where subscriber_id = <user id of john>
A: your logic is wrong,
there won't be any matches for user = multiple user
logically should be
user in('tom', 'chris', 'david', ....);
however, using integer column with index is efficient
like what @Nick B suggest
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to map existing tables into a inheritance hierarchy in NHibernate? The problem is trying to map inheritance given an existing table structure. The table is also used by legacy apps using raw sql, ie, the table can't delete any existing schema details, but can add more to it.
The existing table is already mapped, and essentially has a bunch of fields with the following problem....
so existing class
class A
{
// Id etc
public virtual Client Client { get; set; }
}
with a table structure like
table A (
Id INT IDENTITY NOT NULL,
Client_id INT null,
primary key (Id)
)
Now I want to introduce a base class
class Base
{
// Id etc
public virtual Client Client { get; set; }
}
which will end up with a table like...
table Base (
Id INT IDENTITY NOT NULL,
Client_id INT null,
primary key (Id)
)
and change A to
class A : Base
{
// clients moved to the base...
}
which will do something like this to the table :-
table A(
Base_id INT IDENTITY NOT NULL,
Id INT not null, // I will need to keep the existing Id field...
Client_id INT null, // this Client now conflicts with the Base client
primary key (Base_id)
)
I'm using table per class inheritance.
the problem is....
'Client' will be on the table of "Base" and also it's on the existing table of "A". I want to be able to keep using the 'Client' on "A", as a kind of override.
How do I do this? can I do this?
or is it possible that on table "Base" it doesn't have 'Client' at all and then on all the subclass tables they define "Client"? (which would make querying interesting)
A: if its only for querying NH should support Querying by interface
class A : IHasClient
{
// Id etc
public virtual Client Client { get; set; }
}
class SomeOther : IHasClient
{
// Id etc
public virtual Client Client { get; set; }
}
var classesWithClients = session.QueryOver<IHasClient>().List();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery How to stop functions so they happen one at a time I have a form where a user can enter a page title into an input field and it will generate a URL. On the submit button click the value is displayed in a different input field(URL). If they are not happy with their URL they can manually edit it inside that field and then save their changes via a button click.
The button's value also changes depending on the state of the URL field.
My code is working but I have a problem with the last 2 functions happening at once, I have tried adding StopEventPropagation (or similar) and that has not worked for me. Please help if you can.
The JSfiddle is here
A: It's impossible in JavaScript or jquery to guarantee a priority for event order. I would recommend trying to change the 2nd event function to a normal function and calling it at the end of the 1st
function clickhandler(event)
{
//do stuff
//...
clickhandler2(event);
}
function clickhandler2(event)
{
//do stuff
//...
}
A: Last 2 functions fire together because you assigned them as a click handler to the same element.
consider the following JS:
I've combined bodies of both functions to 1. They will execute one after another now.
// Display entered text in URL field on submit
$("input#page_url_button").click(function () {
var text = $("input#page_title").val();
$("input#page_url").val(text);
});
// If URL has info in it, then change value of button and add class to button
$("input#page_url_button").click(function () {
if( $("input#page_url").val().length > 0 ) {
$(this).val("Edit URL");
$(this).addClass("edit_url_button");
}
if( $(this).hasClass('edit_url_button') ) {
$(this).val("Save");
$("input#page_url").removeAttr("disabled");
$(this).removeClass("edit_url_button");
$(this).addClass("save_url_button");
}
}); // This part is getting skipped, I need to find a way to include this in the process
A: Is this what you're looking for:
$("input#page_url_button").click(function() {
// Display entered text in URL field on submit
var text = $("input#page_title").val();
$("input#page_url").val(text);
if ($(this).hasClass('edit_url_button')) {
$(this).removeClass("edit_url_button");
$(this).addClass("save_url_button");
alert('Saved!');
$(this).val("Submit");
$("input#page_url").val('').attr('disabled', 'dsabled');
}
else if ($("input#page_url").val().length > 0) {
$('input#page_title').val("Edit URL");
$(this).addClass("edit_url_button");
$(this).val("Save");
$("input#page_url").removeAttr("disabled");
}
});
A: Rather than combining both handlers I used jQuerys live event handler for the second click.
$("input#page_url_button.edit_url_button").live('click', function () {
alert("2");
$(this).val("Save");
$("input#page_url").removeAttr("disabled");
$(this).removeClass("edit_url_button");
$(this).addClass("save_url_button");
});
See example at http://jsfiddle.net/dJPvJ/
Edit:
I was half-way there with my original answer, this amended code should do what you need:
// If URL has info in it, then change value of button and add class to button
$("input#page_url_button.save_url_button").live('click', function () {
if( $("input#page_url").val().length > 0 ) {
$(this).val("Edit URL");
$(this).addClass("edit_url_button");
}
}); // This part is getting skipped, I need to find a way to include this in the process
// If this button has class (edit_button_url) change value, add new class and remove the Dsiabled attr from URL field
$("input#page_url_button.edit_url_button").live('click', function () {
$(this).val("Save");
$("input#page_url").removeAttr("disabled");
$(this).removeClass("edit_url_button");
$(this).addClass("save_url_button");
});
To get this to work you also need to add "save_url_button" to the original markup:
<input id="page_url_button" type="button" value="Submit" class="save_url_button fright" style="width:60px">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Expressionengine interpreting jQuery curly braces as EE tags I'm using EE2.2 along with jQuery and jQuery templating plugin. In my template i have allot of curly braces that is part of how jQuery Templating works. The problem is EE is not differentiating between JavaScript curly braces and EE tags which also comes in curly braces. EE is interpreting the curly braces as EE tags and for that reason the template not working. Since these curly braces are inside a script tag, i would assume EE would count them as javascript and non EE tag related. How can i tell EE that these are not EE tags. Is there a work around this.
<script id="template-download" type="text/x-jquery-tmpl">
<tr class="template-download{{if error}} ui-state-error{{/if}}">
{{if error}}
<td></td>
<td class="name">${name}</td>
<td class="size">${sizef}</td>
<td class="error" colspan="2">Error:
{{if error === 1}}File exceeds upload_max_filesize (php.ini directive)
{{else error === 2}}File exceeds MAX_FILE_SIZE (HTML form directive)
{{else}}${error}
{{/if}}
</td>
{{else}}
<td class="preview">
.....
</script>
A: What does ExpressionEngine's hidden $config['protect_javascript'] actually do? It's probably best explained by an example — allow me to illustrate.
Given the following code sample, with $config['protect_javascript'] = 'y'; advanced conditionals will completely be ignored:
<script>
{if username == "admin"}
Welcome, {username}!
{if:elseif member_id == "2"}
Welcome, {screen_name}!
{if:else}
Welcome, Guest!
{/if}
</script>
Which will produce the following output:
<script>
Welcome, admin!
Welcome, Administrator!
Welcome, Guest!
</script>
Whereas, when $config['protect_javascript'] = 'n'; the same code snippet from above will allow advanced conditionals to be evaluated and will produce:
<script>
Welcome, admin!
</script>
As you can see, the difference is whether or not advanced conditionals are evaluated in JavaScript code blocks.
Simple conditionals and template tags are always evaluated in <script> tags, regardless of the $config['protect_javascript'] setting — just be sure to place your curly braces {} on separate lines!
<script>
// Simple Conditionals Are Unaffected and Always Work
{if segment_2 != ""}
{redirect="404"}
{/if}
</script>
A: This is a common question that has been answered before. Simply put:
*
*Place your JavaScript's curly braces {} on separate lines, or
*Enact the $config['protect_javascript'] Hidden Configuration Variable
With your usage, the second option is probably the best solution.
A: You can also set your template type to "static" for an easy fix. If your JS is in a template with other EE code, you can move it to a "static" template and embed it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to eval / constantize a string to a method, then pass arguments to it Given:
s = "foo_bar_path"
How can I eval or constantize s, and pass arguments to it, such as my final result would be the equivalent of:
foo_bar_path(@myvar, @foobar)
I was trying eval(s).send but that doesn't seem to work. And constantize seems to only work on Classes?
A: Another way to go about this sort of this sort of thing (better for OpenStruct):
#for more in this domain, see the Ruby core API for the Object class
class Demo
def initialize(n)
@iv = n
end
def hello()
"Hello, @iv = #{@iv}"
end
end
k = Demo.new(99)
m = k.method(:hello)
m.call #=> "Hello, @iv = 99"
A: You would just use the send method (or public_send depending on your needs) on the appropriate object:
some_object.send(s, @myvar, @foobar)
or if you want to call a method on yourself:
self.send(s, @myvar, @foobar)
The documentation says "symbol" but send is just as happy to get the method name in a string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What causes this ArrayIndexOutOfBoundsException? I am new to scala.
here is simple code
object SimpleIfStatementDemo {
def main(args: Array[String]) {
var numA: Int = args(0).toInt
var numB: Int = args(1).toInt
if(numA>numB) {
print(numA)
} else {
print(numB)
}
}
}
it's can be compile,but can not be run it. here is error i got it
java.lang.ArrayIndexOutOfBoundsException: 0 at
Main$.main(SimpleIfSatementDemo.scala:5) at
Main.main(SimpleIfSatementDemo.scala) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
scala.tools.nsc.util.ScalaClassLoader$$anonfun$run$1.apply(ScalaClassLoader.scala:78)
at
scala.tools.nsc.util.ScalaClassLoader$class.asContext(ScalaClassLoader.scala:24)
at
scala.tools.nsc.util.ScalaClassLoader$URLClassLoader.asContext(ScalaClassLoader.scala:88)
at
scala.tools.nsc.util.ScalaClassLoader$class.run(ScalaClassLoader.scala:78)
at
scala.tools.nsc.util.ScalaClassLoader$URLClassLoader.run(ScalaClassLoader.scala:101)
at scala.tools.nsc.ObjectRunner$.run(ObjectRunner.scala:33) at
scala.tools.nsc.ObjectRunner$.runAndCatch(ObjectRunner.scala:40) at
scala.tools.nsc.ScriptRunner.scala$tools$nsc$ScriptRunner$$runCompiled(ScriptRunner.scala:171)
at
scala.tools.nsc.ScriptRunner$$anonfun$runScript$1.apply(ScriptRunner.scala:188)
at
scala.tools.nsc.ScriptRunner$$anonfun$runScript$1.apply(ScriptRunner.scala:188)
at
scala.tools.nsc.ScriptRunner$$anonfun$withCompiledScript$1.apply$mcZ$sp(ScriptRunner.scala:157)
at
scala.tools.nsc.ScriptRunner$$anonfun$withCompiledScript$1.apply(ScriptRunner.scala:131)
at
scala.tools.nsc.ScriptRunner$$anonfun$withCompiledScript$1.apply(ScriptRunner.scala:131)
at scala.tools.nsc.util.package$.waitingForThreads(package.scala:26)
at
scala.tools.nsc.ScriptRunner.withCompiledScript(ScriptRunner.scala:130)
at scala.tools.nsc.ScriptRunner.runScript(ScriptRunner.scala:188) at
scala.tools.nsc.ScriptRunner.runScriptAndCatch(ScriptRunner.scala:201)
at
scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:58)
at
scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:80)
at
scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:89)
at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
Thanks
A: The program is not being passed enough arguments (it requires at least two; see the java command manual for how these can be specified). Consider putting this code as the first line of the main method:
println("I have " + args.length + " argument(s)")
And then try this on the Scala REPL to see a similar explosion:
val a = Array("Hello world!") // array of one element
a(0) // access first element, okay
a(1) // access second element -- KABOOM!
How can this new knowledge be used to make the program more robust (and not throw the exception)?
Happy coding.
The article First Steps to Scala has examples of passing and using arguments.
A: Assuming you run at the command line with 2.9.0 or later and that your source code is contained in a file called SimpleIfStatementDemo.scala:
$ scala SimpleIfStatementDemo.scala 1 2
will provide the arguments 1 and 2 to your program.
On 2.9.x and 2.8.x, you can also compile the source into class files compiled into an intermediate byte code for the JVM. A good practice is to have them under a subdirectory (classes in this example):
$ scalac -d classes SimpleIfStatementDemo.scala
$ scala -cp classes SimpleIfStatementDemo 1 2
If you run within an IDE, you have to figure out how to edit the run configuration to add arguments to the run command.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create a doctype with TagBuilder The ! in the doctype tag I cannot create. Is there a way to put the ! in a doctype tag using tagbuilder.
A: Since the Doctype is not an HTML tag, you can't use TagBuilder.
Although, you can return a normal MvcHtmlString.
public static class CustomHelpers
{
public static MvcHtmlString DocType(this HtmlHelper helper)
{
var docType = @"<!DOCTYPE ...>";
return MvcHtmlString.Create(docType);
}
}
And then use it like that:
@Html.DocType()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Checking XML using Google Maps API I have been playing around with Google Maps API for the past couple of days. I got up to the point where I'm stuck because of my lack of PHP skills. After running the PHP code below, the XML returned is:
<?xml version="1.0"?>
<markers/>
The link I'm using is: http://www.icliqz.com/Dev/phpsqlsearch_genxml_php.php?latitude=41.782321&longitude=-72.612031&radius=50
The code I'm playing around with is from: http://code.google.com/apis/maps/articles/phpsqlsearch.html
I'm using Dreamweaver to work on this project. If there's a good way to debug through PHP code, I'd really appreciate it. I tried googling it up, but I'm not sure what is best for a PHP newbie.
I checked that the radius of the records I have in my database. They are all within 50 miles of the coordinates I'm testing with.
The PHP code is:
<?php
require("phpsqlsearch_dbinfo.php");
// Start XML file, create parent node
$doc = new DOMDocument("1.0");
$node = $doc->createElement("markers");
$parnode = $doc->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT user, latitude, longitude, ( 3959 * acos( cos( radians('%s') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( latitude ) ) ) ) AS distance FROM tbl_UserLatLng HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $doc->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->set_attribute("user", $row['user']);
$newnode->set_attribute("latitude", $row['latitude']);
$newnode->set_attribute("longitude", $row['longitude']);
$newnode->set_Attribute("distance", $row['distance']);
}
echo $doc->saveXML();
?>
Thanks in advance!
A: Try running your query manually from the mysql shell to see what values are showing up for distance. It seems like you're not getting any results from the db.
SELECT user, latitude, longitude,
( 3959 * acos( cos( radians('%s') ) * cos( radians( latitude ) ) * cos( radians( longitude ) -
radians('%s') ) +
sin( radians('%s') ) * sin( radians( latitude ) ) ) ) AS distance
FROM tbl_UserLatLng
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Automatically update web application when data is updated on server Is it possible to send update (or automatic response) from a SERVER to a WEB APPLICATION?
I have a SERVER that updates data every 5 min (sometimes random). I want to update the new data on a running WEB APPLICATION without making a request from brower to server.
Right now I execute an ajax request every 5min so that I can update the latest data. But sometimes no data is updated. Also, sometimes the data gets updated at eg. 9:01 am and the update executes at eg. 9:05am. What i would like to do is: immediately update web application when the data gets updated on the server.
Any ideas on how this could be implemented? I can use any technology/language or anything that is required to do this.
Regards
A: You’re describing HTTP server push technology. There are many ways to implement it, but knowing what it’s called should help you get started.
A: I believe you want to use this model: http://en.wikipedia.org/wiki/Comet_(programming)
A: You can try SQL server notification, but you have to do a lot of business logic around it.
A: The client-server relationship cannot be reversed. The browser has to be the one to initiate any communication.
However, you can quite easily poll the server at short interval to ask "has anything changed?". Then, according to the result, you could refresh all or part of the data with a second AJAX call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Changing the Color of a Path Using Animation - iPhone Dev I am working on a "connect the dots" app and would like the line that is drawn from one dot to another to flash briefly to indicate to the user that they have successfully completed the correct line. I initially thought the best way to do this would be to alternate the stroke color between black and white. I have no animation experience and everything I've read regarding the Core Animation Types indicate that only properties of a view can be animated. I've considered creating a custom view that is as long and thin as the line it would represent, and then changing the background color. However, this seems extremely inefficient considering the number of lines needed to complete an object in a standard "connect the dots" image.
I have overridden the touchesBegan/touchesMoved/touchesEnd methods while incorporating CGContext methods to create and stroke paths to specific locations on the screen.
Is there a major concept I'm missing that would allow me to animate the color of the path? Or is my approach using UITouch/CGContext a problem when considering animation? Thank you for your time in advance.
A: There are a lot more options available for animation if you use CALayer's animation abilities. However that comes with complexity.
I'm not sure you need to animate anything at all. Animation implies intermediate values. You can simply delay 0.25s or whatever, then redraw the path in the alternate color.
If you really want animation, draw the path in two views, and animate the alpha of one back and forth between 0.0 and 1.0. That would give a smooth fade-y effect to the flashing. You can also use that technique to flash without animation if redrawing the path each time is not efficient (but unless you are redrawing 1000 paths, I think you will have enough cycles to redraw the path every 0.25s).
A: Having little experience in drawing and animation, it seemed logical to look up animation methods as a way of making lines flash. The answer to my question above (thank you morningstar) helped set me in the right direction.
I created two drawing methods. One that would draw a black line and another that would draw a lighter line. I then used the performSelector method and called each drawing method alternating every .05 seconds for 1 second total. This redraws the line in black then white quickly and repeatedly, giving it the flashing effect I was looking for. Having limited experience in this language, discovering the performSelector method is extremely valuable and something I will most likely be using quite a bit in the future!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting bulleted, bold, embedded text to display in Flash CS5 I am dubious that anyone will be able to help, but thought I'd post just in case...
I'm trying to get Flash to display a bulleted list using bold embedded fonts.
What I'm finding is that I can get bold fonts with bullets, but not embedded. Or embedded fonts with bullets that aren't bold, or bold embedded fonts without bullets.
This is incredibly frustrating (as well as annoying).
I'm embedding the fonts in the library and exporting them via actionscript. Here's my code...
var tf:TextField = new TextField();
tf.multiline = true;
tf.width = 100;
tf.x = 200;
tf.y = 100;
tf.antiAliasType = AntiAliasType.ADVANCED;
tf.wordWrap = true;
tf.autoSize = TextFieldAutoSize.LEFT;
tf.embedFonts = true;
var bulletTF:TextFormat = new TextFormat();
var myFontBold:VerdBold = new VerdBold();
var myFont:Verd = new Verd();
bulletTF.font = myFont.fontName;
bulletTF.size = 12;
bulletTF.bullet = true;
tf.htmlText ="This is the first bullet, but this text should wrap correctly.<br>and another<br>And another still" ;
tf.setTextFormat(bulletTF);
addChild(tf);
The above code produces the regular font embedded bulleted list.
If I change the bulletTF.font line to bulletTF.font = myFontBold.fontName The font goes bold and the bullets go away.
Has anyone dealt with this? And if so... what was your solution (or workaround).
Much obliged in advance.
A: You need to embed both the bold font and the normal font. Also rather than using TextFormat to set the format, you might get more predictable results by setting HTML tags directly:
var myFontBold:VerdBold = new VerdBold();
var myFont:Verd = new Verd();
tf.htmlText = '<p><font face="' + myFont.fontName + '">Some regular text</font></p><ul><li><font face="' + myFontBold.fontName + '">Some bold text</font></li></ul>';
It's ugly but normally it should work. Using <b> might also work, but I think it's more reliable to explicitly set the font names.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.